{
 "cells": [
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "---\n",
    "execute:\n",
    "  enabled: false\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=oo-design-md-1 fw=all -->\n",
    "\n",
    "# Object-Oriented Design for Implementation\n",
    "\n",
    "Almost every model in this book follows the same loop: load data, run a forward\n",
    "pass, compute the loss, update the parameters, and repeat. If we wrote that loop\n",
    "from scratch for each new model, a small change to the training procedure (say,\n",
    "adding gradient clipping or a learning-rate schedule) would force us to touch\n",
    "every chapter. The fix, borrowed from libraries such as\n",
    "[Lightning](https://lightning.ai/), is to write the loop once inside a reusable\n",
    "`Trainer` class and let the model and the data vary as subclasses of `Module` and\n",
    "`DataModule`:\n",
    "\n",
    "* **`Module`** holds the model parameters, the `forward` pass, the loss, and the\n",
    "  optimizer. Every model in the book is a subclass.\n",
    "* **`DataModule`** holds a dataset and serves its training and validation data\n",
    "  loaders. Every dataset is a subclass.\n",
    "* **`Trainer`** owns the epoch loop: it feeds batches from the `DataModule` into\n",
    "  the `Module` and applies the optimizer.\n",
    "\n",
    "Most chapters subclass only `Module` and `DataModule`; we return to the `Trainer`\n",
    "itself when we reach GPUs, parallel training, and optimization.\n",
    "the figure shows how the three fit together.\n",
    "\n",
    "![The three base classes and how they fit together. `Trainer.fit` drives a `Module` (which holds the model, loss, and optimizer) over data served by a `DataModule`; new models and datasets are written as subclasses.](../img/mdl-linreg-oo-classes.svg)"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "oo-design-object-oriented-design-for-implementation"
   },
   "source": [
    "import time\n",
    "import numpy as np\n",
    "from d2l import torch as d2l\n",
    "import torch\n",
    "from torch import nn"
   ],
   "execution_count": 1,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=oo-design-md-2 fw=all -->\n",
    "\n",
    "## Utilities\n",
    "\n",
    "We need a few utilities to simplify object-oriented programming in Jupyter notebooks. One of the challenges is that class definitions tend to be fairly long blocks of code. Notebook readability demands short code fragments, interspersed with explanations, a requirement incompatible with the style of programming common for Python libraries. The first\n",
    "utility function allows us to register functions as methods in a class *after* the class has been created. In fact, we can do so *even after* we have created instances of the class! It allows us to split the implementation of a class into multiple code blocks."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "oo-design-utilities-1"
   },
   "source": [
    "def add_to_class(Class):\n",
    "    \"\"\"Register functions as methods in created class.\"\"\"\n",
    "    def wrapper(obj):\n",
    "        setattr(Class, obj.__name__, obj)\n",
    "        return obj\n",
    "    return wrapper"
   ],
   "execution_count": 2,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=oo-design-md-3 fw=all -->\n",
    "\n",
    "Let's have a quick look at how to use it. We plan to implement a class `A` with a method `do`. Instead of having code for both `A` and `do` in the same code block, we can first declare the class `A` and create an instance `a`."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "oo-design-utilities-2"
   },
   "source": [
    "class A:\n",
    "    def __init__(self):\n",
    "        self.b = 1\n",
    "\n",
    "a = A()"
   ],
   "execution_count": 3,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=oo-design-md-4 fw=all -->\n",
    "\n",
    "Next we define the method `do` as we normally would, but not in class `A`'s scope. Instead, we decorate this method by `add_to_class` with class `A` as its argument. In doing so, the method is able to access the member variables of `A` just as we would expect had it been included as part of `A`'s definition. Let's see what happens when we invoke it for the instance `a`."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "oo-design-utilities-3"
   },
   "source": [
    "@add_to_class(A)\n",
    "def do(self):\n",
    "    print('Class attribute \"b\" is', self.b)\n",
    "\n",
    "a.do()"
   ],
   "execution_count": 4,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Class attribute \"b\" is 1\n"
     ]
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=oo-design-md-5 fw=all -->\n",
    "\n",
    "The second one is a utility class that saves all arguments in a class's `__init__` method as class attributes. This allows us to extend constructor call signatures implicitly without additional code."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "oo-design-utilities-4"
   },
   "source": [
    "class HyperParameters:\n",
    "    \"\"\"The base class of hyperparameters.\"\"\"\n",
    "    def save_hyperparameters(self, ignore=None):\n",
    "        raise NotImplementedError"
   ],
   "execution_count": 5,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=oo-design-md-6 fw=all -->\n",
    "\n",
    "The stub above fixes the *interface*; that section fills in the implementation on this same class, which is why saving even a `NotImplementedError` body with `#@save` is worthwhile. To use it, we define our class that inherits from `HyperParameters` and calls `save_hyperparameters` in the `__init__` method."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "oo-design-utilities-5"
   },
   "source": [
    "# Call the fully implemented HyperParameters class saved in d2l\n",
    "class B(d2l.HyperParameters):\n",
    "    def __init__(self, a, b, c):\n",
    "        self.save_hyperparameters(ignore=['c'])\n",
    "        print('self.a =', self.a, 'self.b =', self.b)\n",
    "        print('There is no self.c =', not hasattr(self, 'c'))\n",
    "\n",
    "b = B(a=1, b=2, c=3)"
   ],
   "execution_count": 6,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "self.a = 1 self.b = 2\nThere is no self.c = True\n"
     ]
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=oo-design-md-7 fw=all -->\n",
    "\n",
    "The final utility allows us to plot experiment progress interactively while it is going on. In deference to the much more powerful (and complex) [TensorBoard](https://www.tensorflow.org/tensorboard) we name it `ProgressBoard`. The  implementation is deferred to that section. For now, let's simply see it in action.\n",
    "\n",
    "The `draw` method records a point `(x, y)` to be shown in the figure, with `label` specified in the legend. The optional `every_n` smooths the line: it shows one point per $n$ calls to `draw`, plotting the average of the last $n$ recorded values. As we explain just below, `draw` is *asynchronous*: it merely schedules the point and returns immediately, so that plotting never slows down training."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "oo-design-utilities-6"
   },
   "source": [
    "class ProgressBoard(d2l.HyperParameters):\n",
    "    \"\"\"The board that plots data points in animation.\"\"\"\n",
    "    def __init__(self, xlabel=None, ylabel=None, xlim=None,\n",
    "                 ylim=None, xscale='linear', yscale='linear',\n",
    "                 ls=['-', '--', '-.', ':'], colors=['C0', 'C1', 'C2', 'C3'],\n",
    "                 fig=None, axes=None, figsize=(3.5, 2.5), display=True):\n",
    "        self.save_hyperparameters()\n",
    "\n",
    "    def draw(self, x, y, label, every_n=1):\n",
    "        raise NotImplementedError"
   ],
   "execution_count": 7,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=oo-design-md-8 fw=all -->\n",
    "\n",
    "Why does `draw` go to the trouble of *scheduling* work instead of plotting\n",
    "right away? The answer previews a theme that runs through the entire book.\n",
    "Modern frameworks get their speed by *compiling* the training computation into a\n",
    "graph that runs on the accelerator with little Python in the loop. Compilation\n",
    "imposes two rules we must respect. First, a compiled step has to be *pure*: a\n",
    "`print` or a plotting call inside it cannot be captured by the compiler, forcing a\n",
    "fallback to slower eager execution. Second, the accelerator runs *asynchronously*,\n",
    "ahead of Python; the instant we ask for a concrete number (to print or plot it),\n",
    "Python must *block* until the device catches up, stalling the very pipeline we\n",
    "worked to speed up.\n",
    "\n",
    "Real-time monitoring therefore seems to be at odds with efficiency. `ProgressBoard`\n",
    "resolves the tension by *decoupling* the two: `draw` hands the value to a queue and\n",
    "returns at once, while a background thread performs the device-to-host transfer and\n",
    "the (comparatively slow) rendering at its own pace, dropping points if it falls\n",
    "behind, since a live loss curve needs no more than a few updates per second. The\n",
    "training loop stays compiled and the device stays busy, yet we still watch the loss\n",
    "go down as it happens. The pattern is general: keep the hot path pure and compiled,\n",
    "and push logging, plotting, and checkpointing off to the side.\n",
    "\n",
    "In the following example, we draw `sin` and `cos` with different smoothness. If you\n",
    "run this code block interactively, you will see the lines grow in animation. Because\n",
    "drawing is asynchronous, we finish with `board.flush()`, which waits for the queue\n",
    "to drain and renders the final figure; `Trainer.fit` (developed below) does this for\n",
    "you."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "oo-design-utilities-7"
   },
   "source": [
    "board = d2l.ProgressBoard('x')\n",
    "for x in np.arange(0, 10, 0.1):\n",
    "    board.draw(x, np.sin(x), 'sin', every_n=2)\n",
    "    board.draw(x, np.cos(x), 'cos', every_n=10)\n",
    "board.flush()  # wait for the queued points, then render the final figure"
   ],
   "execution_count": 8,
   "outputs": [
    {
     "output_type": "display_data",
     "data": {
      "image/svg+xml": "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>\n<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"\n  \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n<svg xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"241.185572pt\" height=\"183.35625pt\" viewBox=\"0 0 241.185572 183.35625\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">\n <metadata>\n  <rdf:RDF xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:cc=\"http://creativecommons.org/ns#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n   <cc:Work>\n    <dc:type rdf:resource=\"http://purl.org/dc/dcmitype/StillImage\"/>\n    <dc:date>2026-07-19T13:50:13.844938</dc:date>\n    <dc:format>image/svg+xml</dc:format>\n    <dc:creator>\n     <cc:Agent>\n      <dc:title>Matplotlib v3.10.8, https://matplotlib.org/</dc:title>\n     </cc:Agent>\n    </dc:creator>\n   </cc:Work>\n  </rdf:RDF>\n </metadata>\n <defs>\n  <style type=\"text/css\">*{stroke-linejoin: round; stroke-linecap: butt}</style>\n </defs>\n <g id=\"figure_1\">\n  <g id=\"patch_1\">\n   <path d=\"M -0 183.35625 \nL 241.185572 183.35625 \nL 241.185572 0 \nL -0 0 \nz\n\" style=\"fill: #ffffff\"/>\n  </g>\n  <g id=\"axes_1\">\n   <g id=\"patch_2\">\n    <path d=\"M 38.482813 145.8 \nL 233.782813 145.8 \nL 233.782813 7.2 \nL 38.482813 7.2 \nz\n\" style=\"fill: #ffffff\"/>\n   </g>\n   <g id=\"matplotlib.axis_1\">\n    <g id=\"xtick_1\">\n     <g id=\"line2d_1\">\n      <defs>\n       <path id=\"m46bdc40378\" d=\"M 0 0 \nL 0 3.5 \n\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </defs>\n      <g>\n       <use xlink:href=\"#m46bdc40378\" x=\"46.454241\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_1\">\n      <!-- 0 -->\n      <g transform=\"translate(43.272991 160.398438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-30\" d=\"M 2034 4250 \nQ 1547 4250 1301 3770 \nQ 1056 3291 1056 2328 \nQ 1056 1369 1301 889 \nQ 1547 409 2034 409 \nQ 2525 409 2770 889 \nQ 3016 1369 3016 2328 \nQ 3016 3291 2770 3770 \nQ 2525 4250 2034 4250 \nz\nM 2034 4750 \nQ 2819 4750 3233 4129 \nQ 3647 3509 3647 2328 \nQ 3647 1150 3233 529 \nQ 2819 -91 2034 -91 \nQ 1250 -91 836 529 \nQ 422 1150 422 2328 \nQ 422 3509 836 4129 \nQ 1250 4750 2034 4750 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-30\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_2\">\n     <g id=\"line2d_2\">\n      <g>\n       <use xlink:href=\"#m46bdc40378\" x=\"82.688007\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_2\">\n      <!-- 2 -->\n      <g transform=\"translate(79.506757 160.398438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-32\" d=\"M 1228 531 \nL 3431 531 \nL 3431 0 \nL 469 0 \nL 469 531 \nQ 828 903 1448 1529 \nQ 2069 2156 2228 2338 \nQ 2531 2678 2651 2914 \nQ 2772 3150 2772 3378 \nQ 2772 3750 2511 3984 \nQ 2250 4219 1831 4219 \nQ 1534 4219 1204 4116 \nQ 875 4013 500 3803 \nL 500 4441 \nQ 881 4594 1212 4672 \nQ 1544 4750 1819 4750 \nQ 2544 4750 2975 4387 \nQ 3406 4025 3406 3419 \nQ 3406 3131 3298 2873 \nQ 3191 2616 2906 2266 \nQ 2828 2175 2409 1742 \nQ 1991 1309 1228 531 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-32\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_3\">\n     <g id=\"line2d_3\">\n      <g>\n       <use xlink:href=\"#m46bdc40378\" x=\"118.921774\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_3\">\n      <!-- 4 -->\n      <g transform=\"translate(115.740524 160.398438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-34\" d=\"M 2419 4116 \nL 825 1625 \nL 2419 1625 \nL 2419 4116 \nz\nM 2253 4666 \nL 3047 4666 \nL 3047 1625 \nL 3713 1625 \nL 3713 1100 \nL 3047 1100 \nL 3047 0 \nL 2419 0 \nL 2419 1100 \nL 313 1100 \nL 313 1709 \nL 2253 4666 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-34\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_4\">\n     <g id=\"line2d_4\">\n      <g>\n       <use xlink:href=\"#m46bdc40378\" x=\"155.15554\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_4\">\n      <!-- 6 -->\n      <g transform=\"translate(151.97429 160.398438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-36\" d=\"M 2113 2584 \nQ 1688 2584 1439 2293 \nQ 1191 2003 1191 1497 \nQ 1191 994 1439 701 \nQ 1688 409 2113 409 \nQ 2538 409 2786 701 \nQ 3034 994 3034 1497 \nQ 3034 2003 2786 2293 \nQ 2538 2584 2113 2584 \nz\nM 3366 4563 \nL 3366 3988 \nQ 3128 4100 2886 4159 \nQ 2644 4219 2406 4219 \nQ 1781 4219 1451 3797 \nQ 1122 3375 1075 2522 \nQ 1259 2794 1537 2939 \nQ 1816 3084 2150 3084 \nQ 2853 3084 3261 2657 \nQ 3669 2231 3669 1497 \nQ 3669 778 3244 343 \nQ 2819 -91 2113 -91 \nQ 1303 -91 875 529 \nQ 447 1150 447 2328 \nQ 447 3434 972 4092 \nQ 1497 4750 2381 4750 \nQ 2619 4750 2861 4703 \nQ 3103 4656 3366 4563 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-36\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_5\">\n     <g id=\"line2d_5\">\n      <g>\n       <use xlink:href=\"#m46bdc40378\" x=\"191.389306\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_5\">\n      <!-- 8 -->\n      <g transform=\"translate(188.208056 160.398438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-38\" d=\"M 2034 2216 \nQ 1584 2216 1326 1975 \nQ 1069 1734 1069 1313 \nQ 1069 891 1326 650 \nQ 1584 409 2034 409 \nQ 2484 409 2743 651 \nQ 3003 894 3003 1313 \nQ 3003 1734 2745 1975 \nQ 2488 2216 2034 2216 \nz\nM 1403 2484 \nQ 997 2584 770 2862 \nQ 544 3141 544 3541 \nQ 544 4100 942 4425 \nQ 1341 4750 2034 4750 \nQ 2731 4750 3128 4425 \nQ 3525 4100 3525 3541 \nQ 3525 3141 3298 2862 \nQ 3072 2584 2669 2484 \nQ 3125 2378 3379 2068 \nQ 3634 1759 3634 1313 \nQ 3634 634 3220 271 \nQ 2806 -91 2034 -91 \nQ 1263 -91 848 271 \nQ 434 634 434 1313 \nQ 434 1759 690 2068 \nQ 947 2378 1403 2484 \nz\nM 1172 3481 \nQ 1172 3119 1398 2916 \nQ 1625 2713 2034 2713 \nQ 2441 2713 2670 2916 \nQ 2900 3119 2900 3481 \nQ 2900 3844 2670 4047 \nQ 2441 4250 2034 4250 \nQ 1625 4250 1398 4047 \nQ 1172 3844 1172 3481 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-38\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_6\">\n     <g id=\"line2d_6\">\n      <g>\n       <use xlink:href=\"#m46bdc40378\" x=\"227.623072\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_6\">\n      <!-- 10 -->\n      <g transform=\"translate(221.260572 160.398438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-31\" d=\"M 794 531 \nL 1825 531 \nL 1825 4091 \nL 703 3866 \nL 703 4441 \nL 1819 4666 \nL 2450 4666 \nL 2450 531 \nL 3481 531 \nL 3481 0 \nL 794 0 \nL 794 531 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-31\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(63.623047 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"text_7\">\n     <!-- x -->\n     <g transform=\"translate(133.173438 174.076563) scale(0.1 -0.1)\">\n      <defs>\n       <path id=\"DejaVuSans-78\" d=\"M 3513 3500 \nL 2247 1797 \nL 3578 0 \nL 2900 0 \nL 1881 1375 \nL 863 0 \nL 184 0 \nL 1544 1831 \nL 300 3500 \nL 978 3500 \nL 1906 2253 \nL 2834 3500 \nL 3513 3500 \nz\n\" transform=\"scale(0.015625)\"/>\n      </defs>\n      <use xlink:href=\"#DejaVuSans-78\"/>\n     </g>\n    </g>\n   </g>\n   <g id=\"matplotlib.axis_2\">\n    <g id=\"ytick_1\">\n     <g id=\"line2d_7\">\n      <defs>\n       <path id=\"meb00042e7d\" d=\"M 0 0 \nL -3.5 0 \n\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </defs>\n      <g>\n       <use xlink:href=\"#meb00042e7d\" x=\"38.482813\" y=\"139.701599\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_8\">\n      <!-- −1.0 -->\n      <g transform=\"translate(7.2 143.500818) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-2212\" d=\"M 678 2272 \nL 4684 2272 \nL 4684 1741 \nL 678 1741 \nL 678 2272 \nz\n\" transform=\"scale(0.015625)\"/>\n        <path id=\"DejaVuSans-2e\" d=\"M 684 794 \nL 1344 794 \nL 1344 0 \nL 684 0 \nL 684 794 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-2212\"/>\n       <use xlink:href=\"#DejaVuSans-31\" transform=\"translate(83.789062 0)\"/>\n       <use xlink:href=\"#DejaVuSans-2e\" transform=\"translate(147.412109 0)\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(179.199219 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_2\">\n     <g id=\"line2d_8\">\n      <g>\n       <use xlink:href=\"#meb00042e7d\" x=\"38.482813\" y=\"108.131347\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_9\">\n      <!-- −0.5 -->\n      <g transform=\"translate(7.2 111.930566) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-35\" d=\"M 691 4666 \nL 3169 4666 \nL 3169 4134 \nL 1269 4134 \nL 1269 2991 \nQ 1406 3038 1543 3061 \nQ 1681 3084 1819 3084 \nQ 2600 3084 3056 2656 \nQ 3513 2228 3513 1497 \nQ 3513 744 3044 326 \nQ 2575 -91 1722 -91 \nQ 1428 -91 1123 -41 \nQ 819 9 494 109 \nL 494 744 \nQ 775 591 1075 516 \nQ 1375 441 1709 441 \nQ 2250 441 2565 725 \nQ 2881 1009 2881 1497 \nQ 2881 1984 2565 2268 \nQ 2250 2553 1709 2553 \nQ 1456 2553 1204 2497 \nQ 953 2441 691 2322 \nL 691 4666 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-2212\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(83.789062 0)\"/>\n       <use xlink:href=\"#DejaVuSans-2e\" transform=\"translate(147.412109 0)\"/>\n       <use xlink:href=\"#DejaVuSans-35\" transform=\"translate(179.199219 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_3\">\n     <g id=\"line2d_9\">\n      <g>\n       <use xlink:href=\"#meb00042e7d\" x=\"38.482813\" y=\"76.561095\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_10\">\n      <!-- 0.0 -->\n      <g transform=\"translate(15.579688 80.360314) scale(0.1 -0.1)\">\n       <use xlink:href=\"#DejaVuSans-30\"/>\n       <use xlink:href=\"#DejaVuSans-2e\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(95.410156 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_4\">\n     <g id=\"line2d_10\">\n      <g>\n       <use xlink:href=\"#meb00042e7d\" x=\"38.482813\" y=\"44.990843\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_11\">\n      <!-- 0.5 -->\n      <g transform=\"translate(15.579688 48.790062) scale(0.1 -0.1)\">\n       <use xlink:href=\"#DejaVuSans-30\"/>\n       <use xlink:href=\"#DejaVuSans-2e\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-35\" transform=\"translate(95.410156 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_5\">\n     <g id=\"line2d_11\">\n      <g>\n       <use xlink:href=\"#meb00042e7d\" x=\"38.482813\" y=\"13.420591\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_12\">\n      <!-- 1.0 -->\n      <g transform=\"translate(15.579688 17.21981) scale(0.1 -0.1)\">\n       <use xlink:href=\"#DejaVuSans-31\"/>\n       <use xlink:href=\"#DejaVuSans-2e\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(95.410156 0)\"/>\n      </g>\n     </g>\n    </g>\n   </g>\n   <g id=\"line2d_12\">\n    <path d=\"M 47.360085 73.409329 \nL 50.983462 60.959407 \nL 54.606838 49.131475 \nL 58.230215 38.397075 \nL 61.853592 29.184154 \nL 65.476968 21.860003 \nL 69.100345 16.716611 \nL 72.723722 13.959031 \nL 76.347098 13.697196 \nL 79.970475 15.941548 \nL 83.593851 20.602609 \nL 87.217228 27.494558 \nL 90.840605 36.342636 \nL 94.463981 46.794096 \nL 98.087358 58.432273 \nL 101.710735 70.793189 \nL 105.334111 83.384053 \nL 108.957488 95.702907 \nL 112.580864 107.258638 \nL 116.204241 117.590554 \nL 119.827618 126.286755 \nL 123.450994 133.000552 \nL 127.074371 137.464285 \nL 130.697748 139.5 \nL 134.321124 139.02654 \nL 137.944501 136.062779 \nL 141.567877 130.726874 \nL 145.191254 123.231551 \nL 148.814631 113.875623 \nL 152.438007 103.032084 \nL 156.061384 91.133229 \nL 159.684761 78.653429 \nL 163.308137 66.090215 \nL 166.931514 53.944442 \nL 170.55489 42.700323 \nL 174.178267 32.806126 \nL 177.801644 24.656302 \nL 181.42502 18.575758 \nL 185.048397 14.806907 \nL 188.671774 13.5 \nL 192.29515 14.70714 \nL 195.918527 18.380202 \nL 199.541903 24.372753 \nL 203.16528 32.445888 \nL 206.788657 42.277757 \nL 210.412033 53.476395 \nL 214.03541 65.595347 \nL 217.658787 78.151469 \nL 221.282163 90.644187 \nL 224.90554 102.575457 \n\" clip-path=\"url(#pb5e4a998ec)\" style=\"fill: none; stroke: #1f77b4; stroke-width: 1.5; stroke-linecap: square\"/>\n   </g>\n   <g id=\"line2d_13\">\n    <path d=\"M 54.606838 22.023199 \nL 72.723722 69.262535 \nL 90.840605 123.212134 \nL 108.957488 134.270983 \nL 127.074371 92.271627 \nL 145.191254 35.828081 \nL 163.308137 16.83428 \nL 181.42502 52.753037 \nL 199.541903 110.560813 \nL 217.658787 137.109405 \n\" clip-path=\"url(#pb5e4a998ec)\" style=\"fill: none; stroke-dasharray: 5.55,2.4; stroke-dashoffset: 0; stroke: #ff7f0e; stroke-width: 1.5\"/>\n   </g>\n   <g id=\"patch_3\">\n    <path d=\"M 38.482813 145.8 \nL 38.482813 7.2 \n\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n   </g>\n   <g id=\"patch_4\">\n    <path d=\"M 233.782813 145.8 \nL 233.782813 7.2 \n\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n   </g>\n   <g id=\"patch_5\">\n    <path d=\"M 38.482813 145.8 \nL 233.782813 145.8 \n\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n   </g>\n   <g id=\"patch_6\">\n    <path d=\"M 38.482813 7.2 \nL 233.782813 7.2 \n\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n   </g>\n   <g id=\"legend_1\">\n    <g id=\"patch_7\">\n     <path d=\"M 45.482813 140.8 \nL 94.309375 140.8 \nQ 96.309375 140.8 96.309375 138.8 \nL 96.309375 110.44375 \nQ 96.309375 108.44375 94.309375 108.44375 \nL 45.482813 108.44375 \nQ 43.482813 108.44375 43.482813 110.44375 \nL 43.482813 138.8 \nQ 43.482813 140.8 45.482813 140.8 \nz\n\" style=\"fill: #ffffff; opacity: 0.8; stroke: #cccccc; stroke-linejoin: miter\"/>\n    </g>\n    <g id=\"line2d_14\">\n     <path d=\"M 47.482813 116.542188 \nL 57.482813 116.542188 \nL 67.482813 116.542188 \n\" style=\"fill: none; stroke: #1f77b4; stroke-width: 1.5; stroke-linecap: square\"/>\n    </g>\n    <g id=\"text_13\">\n     <!-- sin -->\n     <g transform=\"translate(75.482813 120.042188) scale(0.1 -0.1)\">\n      <defs>\n       <path id=\"DejaVuSans-73\" d=\"M 2834 3397 \nL 2834 2853 \nQ 2591 2978 2328 3040 \nQ 2066 3103 1784 3103 \nQ 1356 3103 1142 2972 \nQ 928 2841 928 2578 \nQ 928 2378 1081 2264 \nQ 1234 2150 1697 2047 \nL 1894 2003 \nQ 2506 1872 2764 1633 \nQ 3022 1394 3022 966 \nQ 3022 478 2636 193 \nQ 2250 -91 1575 -91 \nQ 1294 -91 989 -36 \nQ 684 19 347 128 \nL 347 722 \nQ 666 556 975 473 \nQ 1284 391 1588 391 \nQ 1994 391 2212 530 \nQ 2431 669 2431 922 \nQ 2431 1156 2273 1281 \nQ 2116 1406 1581 1522 \nL 1381 1569 \nQ 847 1681 609 1914 \nQ 372 2147 372 2553 \nQ 372 3047 722 3315 \nQ 1072 3584 1716 3584 \nQ 2034 3584 2315 3537 \nQ 2597 3491 2834 3397 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-69\" d=\"M 603 3500 \nL 1178 3500 \nL 1178 0 \nL 603 0 \nL 603 3500 \nz\nM 603 4863 \nL 1178 4863 \nL 1178 4134 \nL 603 4134 \nL 603 4863 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-6e\" d=\"M 3513 2113 \nL 3513 0 \nL 2938 0 \nL 2938 2094 \nQ 2938 2591 2744 2837 \nQ 2550 3084 2163 3084 \nQ 1697 3084 1428 2787 \nQ 1159 2491 1159 1978 \nL 1159 0 \nL 581 0 \nL 581 3500 \nL 1159 3500 \nL 1159 2956 \nQ 1366 3272 1645 3428 \nQ 1925 3584 2291 3584 \nQ 2894 3584 3203 3211 \nQ 3513 2838 3513 2113 \nz\n\" transform=\"scale(0.015625)\"/>\n      </defs>\n      <use xlink:href=\"#DejaVuSans-73\"/>\n      <use xlink:href=\"#DejaVuSans-69\" transform=\"translate(52.099609 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6e\" transform=\"translate(79.882812 0)\"/>\n     </g>\n    </g>\n    <g id=\"line2d_15\">\n     <path d=\"M 47.482813 131.220313 \nL 57.482813 131.220313 \nL 67.482813 131.220313 \n\" style=\"fill: none; stroke-dasharray: 5.55,2.4; stroke-dashoffset: 0; stroke: #ff7f0e; stroke-width: 1.5\"/>\n    </g>\n    <g id=\"text_14\">\n     <!-- cos -->\n     <g transform=\"translate(75.482813 134.720313) scale(0.1 -0.1)\">\n      <defs>\n       <path id=\"DejaVuSans-63\" d=\"M 3122 3366 \nL 3122 2828 \nQ 2878 2963 2633 3030 \nQ 2388 3097 2138 3097 \nQ 1578 3097 1268 2742 \nQ 959 2388 959 1747 \nQ 959 1106 1268 751 \nQ 1578 397 2138 397 \nQ 2388 397 2633 464 \nQ 2878 531 3122 666 \nL 3122 134 \nQ 2881 22 2623 -34 \nQ 2366 -91 2075 -91 \nQ 1284 -91 818 406 \nQ 353 903 353 1747 \nQ 353 2603 823 3093 \nQ 1294 3584 2113 3584 \nQ 2378 3584 2631 3529 \nQ 2884 3475 3122 3366 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-6f\" d=\"M 1959 3097 \nQ 1497 3097 1228 2736 \nQ 959 2375 959 1747 \nQ 959 1119 1226 758 \nQ 1494 397 1959 397 \nQ 2419 397 2687 759 \nQ 2956 1122 2956 1747 \nQ 2956 2369 2687 2733 \nQ 2419 3097 1959 3097 \nz\nM 1959 3584 \nQ 2709 3584 3137 3096 \nQ 3566 2609 3566 1747 \nQ 3566 888 3137 398 \nQ 2709 -91 1959 -91 \nQ 1206 -91 779 398 \nQ 353 888 353 1747 \nQ 353 2609 779 3096 \nQ 1206 3584 1959 3584 \nz\n\" transform=\"scale(0.015625)\"/>\n      </defs>\n      <use xlink:href=\"#DejaVuSans-63\"/>\n      <use xlink:href=\"#DejaVuSans-6f\" transform=\"translate(54.980469 0)\"/>\n      <use xlink:href=\"#DejaVuSans-73\" transform=\"translate(116.162109 0)\"/>\n     </g>\n    </g>\n   </g>\n  </g>\n </g>\n <defs>\n  <clipPath id=\"pb5e4a998ec\">\n   <rect x=\"38.482813\" y=\"7.2\" width=\"195.3\" height=\"138.6\"/>\n  </clipPath>\n </defs>\n</svg>\n"
     },
     "metadata": {}
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=oo-design-md-9 fw=all -->\n",
    "\n",
    "## Models\n",
    "\n",
    "The `Module` class is the base class of all models we will implement. At the very least we need three methods. The first, `__init__`, stores the learnable parameters, the `training_step` method accepts a data batch to return the loss value, and finally, `configure_optimizers` returns the optimization method, or a list of them, that is used to update the learnable parameters. Optionally we can define `validation_step` to report the evaluation measures.\n",
    "Sometimes we put the code for computing the output into a separate `forward` method to make it more reusable.\n",
    "The `plot` method converts the trainer's batch\n",
    "counter into a *fractional epoch* for the x-coordinate, so that the training\n",
    "loss (recorded several times per epoch) and the validation loss (recorded once\n",
    "per epoch) can share a single x-axis, with `every_n` chosen so each curve shows\n",
    "a fixed number of points per epoch."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "oo-design-models"
   },
   "source": [
    "class Module(d2l.nn_Module, d2l.HyperParameters):\n",
    "    \"\"\"The base class of models.\"\"\"\n",
    "    def __init__(self, plot_train_per_epoch=2, plot_valid_per_epoch=1):\n",
    "        super().__init__()\n",
    "        self.save_hyperparameters()\n",
    "        self.board = ProgressBoard()\n",
    "\n",
    "    def loss(self, y_hat, y):\n",
    "        raise NotImplementedError\n",
    "\n",
    "    def forward(self, X):\n",
    "        assert hasattr(self, 'net'), 'Neural network is not defined'\n",
    "        return self.net(X)\n",
    "\n",
    "    def plot(self, key, value, train):\n",
    "        \"\"\"Plot a point in animation.\"\"\"\n",
    "        assert hasattr(self, 'trainer'), 'Trainer is not inited'\n",
    "        self.board.xlabel = 'epoch'\n",
    "        if train:\n",
    "            x = self.trainer.train_batch_idx / \\\n",
    "                self.trainer.num_train_batches\n",
    "            n = self.trainer.num_train_batches / \\\n",
    "                self.plot_train_per_epoch\n",
    "        else:\n",
    "            x = self.trainer.epoch + 1\n",
    "            n = self.trainer.num_val_batches / \\\n",
    "                self.plot_valid_per_epoch\n",
    "        # Pass a thunk, not the value: the device-to-host transfer is deferred\n",
    "        # to the board's drawing thread so this loop never blocks on it.\n",
    "        self.board.draw(x, lambda v=value: d2l.numpy(d2l.to(v, d2l.cpu())),\n",
    "                        ('train_' if train else 'val_') + key,\n",
    "                        every_n=int(n))\n",
    "\n",
    "    def training_step(self, batch):\n",
    "        l = self.loss(self(*batch[:-1]), batch[-1])\n",
    "        self.plot('loss', l, train=True)\n",
    "        return l\n",
    "\n",
    "    def validation_step(self, batch):\n",
    "        l = self.loss(self(*batch[:-1]), batch[-1])\n",
    "        self.plot('loss', l, train=False)\n",
    "\n",
    "    def configure_optimizers(self):\n",
    "        raise NotImplementedError"
   ],
   "execution_count": 9,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=oo-design-md-10 fw=pytorch -->\n",
    "\n",
    "You may notice that `Module` is a subclass of `nn.Module`, the base class of neural networks in PyTorch.\n",
    "It provides convenient features for handling neural networks. For example, if we define a `forward` method, such as `forward(self, X)`, then for an instance `a` we can invoke this method by `a(X)`. This works since it calls the `forward` method in the built-in `__call__` method. You can find more details and examples about `nn.Module` in that section."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=oo-design-md-11 fw=all -->\n",
    "\n",
    "##  Data\n",
    "\n",
    "The `DataModule` class is the base class for data. Quite frequently the `__init__` method is used to prepare the data. This includes downloading and preprocessing if needed. The `train_dataloader` returns the data loader for the training dataset. A data loader is a (Python) generator that yields a data batch each time it is used. This batch is then fed into the `training_step` method of `Module` to compute the loss. There is an optional `val_dataloader` to return the validation dataset loader. It behaves in the same manner, except that it yields data batches for the `validation_step` method in `Module`."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "oo-design-data"
   },
   "source": [
    "class DataModule(d2l.HyperParameters):\n",
    "    \"\"\"The base class of data.\"\"\"\n",
    "    def __init__(self, root='../data', num_workers=4):\n",
    "        self.save_hyperparameters()\n",
    "\n",
    "    def get_dataloader(self, train):\n",
    "        raise NotImplementedError\n",
    "\n",
    "    def train_dataloader(self):\n",
    "        return self.get_dataloader(train=True)\n",
    "\n",
    "    def val_dataloader(self):\n",
    "        return self.get_dataloader(train=False)"
   ],
   "execution_count": 10,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=oo-design-md-12 fw=all -->\n",
    "\n",
    "## Training\n",
    "<!-- d2l:prose id=oo-design-md-13 fw=pytorch, mxnet, tensorflow -->\n",
    "\n",
    "The `Trainer` class trains the learnable parameters in the `Module` class with data specified in `DataModule`. The key method is `fit`, which accepts two arguments: `model`, an instance of `Module`, and `data`, an instance of `DataModule`. It iterates over the entire dataset `max_epochs` times to train the model. Note that `fit_epoch` is left abstract here; it is implemented just two sections later, in that section."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "oo-design-training"
   },
   "source": [
    "class Trainer(d2l.HyperParameters):\n",
    "    \"\"\"The base class for training models with data.\"\"\"\n",
    "    def __init__(self, max_epochs, num_gpus=0, gradient_clip_val=0):\n",
    "        self.save_hyperparameters()\n",
    "        assert num_gpus == 0, 'No GPU support yet'\n",
    "\n",
    "    def prepare_data(self, data):\n",
    "        self.train_dataloader = data.train_dataloader()\n",
    "        self.val_dataloader = data.val_dataloader()\n",
    "        self.num_train_batches = len(self.train_dataloader)\n",
    "        self.num_val_batches = (len(self.val_dataloader)\n",
    "                                if self.val_dataloader is not None else 0)\n",
    "\n",
    "    def prepare_model(self, model):\n",
    "        model.trainer = self\n",
    "        model.board.xlim = [0, self.max_epochs]\n",
    "        self.model = model\n",
    "\n",
    "    def fit(self, model, data):\n",
    "        self.prepare_data(data)\n",
    "        self.prepare_model(model)\n",
    "        self.optim = model.configure_optimizers()\n",
    "        self.epoch = 0\n",
    "        self.train_batch_idx = 0\n",
    "        self.val_batch_idx = 0\n",
    "        for self.epoch in range(self.max_epochs):\n",
    "            self.fit_epoch()\n",
    "        self.model.board.flush()  # drain queued points; render the final figure\n",
    "\n",
    "    def fit_epoch(self):\n",
    "        raise NotImplementedError"
   ],
   "execution_count": 11,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=oo-design-md-14 fw=all -->\n",
    "\n",
    "## Summary\n",
    "\n",
    "The classes above sketch the object-oriented design\n",
    "for our deep learning implementations: how their objects\n",
    "store data and interact with each other.\n",
    "We will keep enriching implementations of these classes,\n",
    "such as via `@add_to_class`,\n",
    "in the rest of the book.\n",
    "Moreover,\n",
    "these fully implemented classes\n",
    "are saved in the [D2L library](https://github.com/d2l-ai/d2l-en/tree/master/d2l),\n",
    "a *lightweight toolkit* that makes structured modeling for deep learning easy. \n",
    "In particular, it facilitates reusing many components between projects without changing much at all. This modularity keeps implementations concise: you can swap just the optimizer, the model, or the dataset, and it can do the same for your own projects. \n",
    "\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. The `add_to_class` decorator works by calling `setattr(Class, obj.__name__, obj)`. (a) Add a method `greet(self)` to the existing class `A` *after* the instance `a` has been created, using `@add_to_class(A)`, and verify that `a.greet()` works. (b) What happens if you define `greet` *without* the decorator and then call `a.greet()`? Why?\n",
    "1. The `Module` class keeps the optimizer in `configure_optimizers`, a *method of the model*, rather than passing it as an argument to `Trainer`. What are the advantages of this design choice? Can you think of a case where putting the optimizer on the model is awkward?\n",
    "1. Extend `DataModule` with a `test_dataloader` method and extend `Trainer.fit` to run a final evaluation pass on the test set after training. What invariant must the test loader satisfy that the validation loader need not?\n",
    "1. The `save_hyperparameters` implementation uses Python's `inspect` module to capture the caller's local variables. Can you implement a version that does *not* use `inspect`, for example by requiring the caller to pass the local namespace explicitly? What are the trade-offs?\n",
    "1. (Advanced) The `ProgressBoard.draw` method is *asynchronous*: it hands values to a background thread rather than plotting immediately. Sketch a synchronous alternative. Under what conditions would the synchronous version be slower? When would the two perform identically?\n",
    "1. Remove the `save_hyperparameters` statement in the `B` class. Can you still print `self.a` and `self.b`? Optional: if you have studied the full implementation of the `HyperParameters` class, can you explain why?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=oo-design-md-15 fw=pytorch -->\n",
    "\n",
    "[Discussions](https://d2l.discourse.group/t/6646)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "name": "d2l-pytorch",
   "display_name": "d2l (PyTorch)",
   "language": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
