{
 "cells": [
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "---\n",
    "execute:\n",
    "  enabled: false\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=rnn-implementation-md-1 fw=all -->\n",
    "\n",
    "# Implementing RNN Language Models\n",
    "\n",
    "We are now ready to build the RNN language model of that section end to\n",
    "end: first from raw tensor operations, so that every moving part is visible,\n",
    "and then again with the recurrent layer that every deep learning framework\n",
    "ships. We train both on *The Time Machine*, tokenized into the 1,024-token\n",
    "byte-pair-encoding (BPE) vocabulary of that section and served\n",
    "as minibatches of shifted input and target windows by the pipeline of\n",
    "that section. Along the way we meet gradient clipping, the\n",
    "standard defense against exploding gradients, and we generate our first text."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "rnn-implementation-implementing-rnn-language-models"
   },
   "source": [
    "%matplotlib inline\n",
    "from d2l import jax as d2l\n",
    "from flax import nnx\n",
    "import jax\n",
    "from jax import numpy as jnp\n",
    "import math\n",
    "import random\n",
    "import time"
   ],
   "execution_count": 1,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=rnn-implementation-md-2 fw=all -->\n",
    "\n",
    "## An RNN Language Model from Scratch\n",
    "\n",
    "The model has three parts, and we implement each as its own class or method:\n",
    "a *recurrent cell* that updates the hidden state one time step at a time, an\n",
    "*embedding* that turns token ids into the vectors the cell consumes, and an\n",
    "*output layer* that maps each hidden state to a vector of logits over the\n",
    "vocabulary.\n",
    "\n",
    "### The Recurrent Cell\n",
    "\n",
    "The `RNNScratch` class holds the three parameters of the recurrence\n",
    "the equation: the input-to-hidden weights\n",
    "$\\mathbf{W}_{\\textrm{xh}}$, the hidden-to-hidden weights\n",
    "$\\mathbf{W}_{\\textrm{hh}}$, and the bias $\\mathbf{b}_\\textrm{h}$. The number\n",
    "of hidden units `num_hiddens` is a tunable hyperparameter, and `num_inputs`\n",
    "is the width of the vectors arriving at each step, which will shortly be the\n",
    "embedding dimension."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "rnn-implementation-the-recurrent-cell-1"
   },
   "source": [
    "class RNNScratch(nnx.Module):\n",
    "    \"\"\"The RNN model implemented from scratch.\"\"\"\n",
    "    def __init__(self, num_inputs, num_hiddens, sigma=0.01, rngs=None):\n",
    "        rngs = nnx.Rngs(0) if rngs is None else rngs\n",
    "        self.num_inputs, self.num_hiddens = num_inputs, num_hiddens\n",
    "        self.sigma = sigma\n",
    "        self.W_xh = nnx.Param(\n",
    "            rngs.params.normal((num_inputs, num_hiddens)) * sigma)\n",
    "        self.W_hh = nnx.Param(\n",
    "            rngs.params.normal((num_hiddens, num_hiddens)) * sigma)\n",
    "        self.b_h = nnx.Param(jnp.zeros(num_hiddens))"
   ],
   "execution_count": 2,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=rnn-implementation-md-3 fw=all -->\n",
    "\n",
    "The forward computation loops over the outermost axis of `inputs`, whose\n",
    "shape is (`num_steps`, `batch_size`, `num_inputs`), applying the recurrence\n",
    "the equation once per time step and collecting the hidden state\n",
    "at every step. When no initial state is supplied we start from zeros. The\n",
    "explicit Python loop, kept in every tab including JAX, is the deliberately\n",
    "readable teaching form; the gated cells of that section swap the\n",
    "JAX loop for `jax.lax.scan`, trading that clarity for acceptable JIT\n",
    "compilation time."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "rnn-implementation-the-recurrent-cell-2"
   },
   "source": [
    "@d2l.add_to_class(RNNScratch)\n",
    "def __call__(self, inputs, state=None):\n",
    "    if state is None:\n",
    "        # Initial state with shape: (batch_size, num_hiddens)\n",
    "        state = jnp.zeros((inputs.shape[1], self.num_hiddens))\n",
    "    outputs = []\n",
    "    for X in inputs:  # Shape of inputs: (num_steps, batch_size, num_inputs)\n",
    "        state = d2l.tanh(d2l.matmul(X, self.W_xh) +\n",
    "                         d2l.matmul(state, self.W_hh) + self.b_h)\n",
    "        outputs.append(state)\n",
    "    return outputs, state"
   ],
   "execution_count": 3,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=rnn-implementation-md-4 fw=all -->\n",
    "\n",
    "We can feed a minibatch of input sequences into the cell as follows."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "rnn-implementation-the-recurrent-cell-3"
   },
   "source": [
    "batch_size, num_inputs, num_hiddens, num_steps = 2, 16, 32, 100\n",
    "rnn = RNNScratch(num_inputs, num_hiddens)\n",
    "X = d2l.ones((num_steps, batch_size, num_inputs))\n",
    "outputs, state = rnn(X)"
   ],
   "execution_count": 4,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=rnn-implementation-md-5 fw=all -->\n",
    "\n",
    "Let's check that the cell produces results of the correct shapes, so that\n",
    "the dimensionality of the hidden state indeed remains unchanged from step\n",
    "to step."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "rnn-implementation-the-recurrent-cell-4"
   },
   "source": [
    "def check_len(a, n):\n",
    "    \"\"\"Check the length of a list.\"\"\"\n",
    "    assert len(a) == n, f'list\\'s length {len(a)} != expected length {n}'\n",
    "\n",
    "def check_shape(a, shape):\n",
    "    \"\"\"Check the shape of a tensor.\"\"\"\n",
    "    assert a.shape == shape, \\\n",
    "            f'tensor\\'s shape {a.shape} != expected shape {shape}'\n",
    "\n",
    "check_len(outputs, num_steps)\n",
    "check_shape(outputs[0], (batch_size, num_hiddens))\n",
    "check_shape(state, (batch_size, num_hiddens))"
   ],
   "execution_count": 5,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=rnn-implementation-md-6 fw=all -->\n",
    "\n",
    "### From Token IDs to Embeddings\n",
    "\n",
    "The cell consumes vectors, but our data pipeline delivers integer token ids.\n",
    "Older treatments bridged the gap with a *one-hot encoding*: token $i$ becomes\n",
    "the length-$|\\mathcal{V}|$ vector with a single 1 in position $i$, and the\n",
    "input weights multiply that vector. With a vocabulary of 27 characters this\n",
    "is harmless. With our BPE vocabulary of over a thousand tokens it is\n",
    "wasteful: each step would multiply a 1,024-wide vector that is zero\n",
    "everywhere but one entry, and the \"input\" would carry no learnable\n",
    "information about the token itself.\n",
    "\n",
    "As introduced in that section, we instead use an *embedding lookup*.\n",
    "We store a trainable matrix $\\mathbf{W}_\\textrm{e} \\in\n",
    "\\mathbb{R}^{|\\mathcal{V}| \\times d}$ and represent token $i$ by its $i$-th\n",
    "row, a dense $d$-dimensional vector that gradient descent shapes along with\n",
    "every other parameter. Note that multiplying a one-hot vector by\n",
    "$\\mathbf{W}_\\textrm{e}$ *selects a row* of $\\mathbf{W}_\\textrm{e}$, so an\n",
    "embedding lookup computes exactly a one-hot matrix product, just without\n",
    "materializing the zeros. One-hot encoding is thus the special case of an\n",
    "embedding whose table is frozen at the identity; the embedding generalizes\n",
    "it by letting the model choose what each token looks like.\n",
    "\n",
    "The `RNNLMScratch` class assembles the full language model around a cell\n",
    "`rnn`: the embedding table `W_e` on the input side and an output projection\n",
    "(`W_hq`, `b_q`) on the output side. The embedding dimension is read off the\n",
    "cell's `num_inputs`, since the cell consumes what the embedding produces. We\n",
    "initialize the embedding rows at unit scale, taking over the role the one-hot\n",
    "1s used to play, while the output projection starts near zero, so the initial\n",
    "next-token distribution is close to uniform, with perplexity near\n",
    "$|\\mathcal{V}|$ before the first update. Since we evaluate with perplexity\n",
    "(that section), the training and validation steps plot it in\n",
    "place of raw loss."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=rnn-implementation-md-7 fw=jax -->\n",
    "\n",
    "The training and validation steps run inside `@nnx.jit` and only return the\n",
    "mean loss: plotting from inside them would hand the board a JAX tracer.\n",
    "`Trainer.fit_epoch` plots the materialized loss eagerly outside jit, and we\n",
    "override `plot` to relabel that value as perplexity for parity with the\n",
    "other tabs."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "rnn-implementation-from-token-ids-to-embeddings-1"
   },
   "source": [
    "class RNNLMScratch(d2l.Classifier):\n",
    "    \"\"\"The RNN-based language model implemented from scratch.\"\"\"\n",
    "    def __init__(self, rnn, vocab_size, lr=0.01, rngs=None):\n",
    "        super().__init__()\n",
    "        self.save_hyperparameters(ignore=['rnn', 'rngs'])\n",
    "        self.rnn = rnn\n",
    "        rngs = nnx.Rngs(1) if rngs is None else rngs\n",
    "        self.W_e = nnx.Param(\n",
    "            rngs.params.normal((vocab_size, rnn.num_inputs)))\n",
    "        self.W_hq = nnx.Param(rngs.params.normal(\n",
    "            (rnn.num_hiddens, vocab_size)) * rnn.sigma)\n",
    "        self.b_q = nnx.Param(jnp.zeros(vocab_size))\n",
    "\n",
    "    def training_step(self, batch):\n",
    "        return self.loss(self(*batch[:-1]), batch[-1])\n",
    "\n",
    "    def validation_step(self, batch):\n",
    "        return self.loss(self(*batch[:-1]), batch[-1])\n",
    "\n",
    "    def plot(self, key, value, train):\n",
    "        # The train/val steps run inside `@nnx.jit` and only return the mean\n",
    "        # loss: plotting a tracer from there would crash the board's drawing\n",
    "        # thread. `Trainer.fit_epoch` instead calls this with the materialized\n",
    "        # loss (outside jit), which we relabel as perplexity for parity with\n",
    "        # the other tabs.\n",
    "        if key == 'loss':\n",
    "            key, value = 'ppl', d2l.exp(value)\n",
    "        super().plot(key, value, train)"
   ],
   "execution_count": 6,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=rnn-implementation-md-8 fw=all -->\n",
    "\n",
    "The minibatches sampled by our data pipeline have shape (`batch_size`,\n",
    "`num_steps`). The `embedding` method looks up each id and transposes the\n",
    "result to (`num_steps`, `batch_size`, `num_inputs`), the layout whose\n",
    "outermost axis the cell's forward loop walks over."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "rnn-implementation-from-token-ids-to-embeddings-2"
   },
   "source": [
    "@d2l.add_to_class(RNNLMScratch)\n",
    "def embedding(self, X):\n",
    "    # Output shape: (num_steps, batch_size, num_inputs)\n",
    "    return self.W_e[X.T]"
   ],
   "execution_count": 7,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=rnn-implementation-md-9 fw=all -->\n",
    "\n",
    "To confirm the equivalence claimed above, we check on a toy five-token\n",
    "vocabulary that multiplying one-hot vectors into a table picks out the same\n",
    "rows that indexing does."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "rnn-implementation-from-token-ids-to-embeddings-3"
   },
   "source": [
    "W, ids = jax.random.normal(d2l.get_key(), (5, 3)), d2l.tensor([0, 2])\n",
    "jnp.allclose(jax.nn.one_hot(ids, 5) @ W, W[ids])"
   ],
   "execution_count": 8,
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "Array(True, dtype=bool)"
     },
     "metadata": {},
     "execution_count": 8
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=rnn-implementation-md-10 fw=all -->\n",
    "\n",
    "### The Output Layer\n",
    "\n",
    "The language model applies a fully connected output layer to the hidden\n",
    "state at every time step, producing one vector of $|\\mathcal{V}|$ logits per\n",
    "step, and stacks them into a (`batch_size`, `num_steps`, `vocab_size`)\n",
    "tensor that lines up with the target array. The `forward` method chains the\n",
    "three parts together."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "rnn-implementation-the-output-layer-1"
   },
   "source": [
    "@d2l.add_to_class(RNNLMScratch)\n",
    "def output_layer(self, rnn_outputs):\n",
    "    outputs = [d2l.matmul(H, self.W_hq) + self.b_q for H in rnn_outputs]\n",
    "    return d2l.stack(outputs, 1)\n",
    "\n",
    "@d2l.add_to_class(RNNLMScratch)\n",
    "def forward(self, X, state=None):\n",
    "    embs = self.embedding(X)\n",
    "    rnn_outputs, _ = self.rnn(embs, state)\n",
    "    return self.output_layer(rnn_outputs)"
   ],
   "execution_count": 9,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=rnn-implementation-md-11 fw=all -->\n",
    "\n",
    "Let's check that the forward computation produces outputs with the correct\n",
    "shape, using a vocabulary of 1,024 tokens like the one we are about to train\n",
    "on."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "rnn-implementation-the-output-layer-2"
   },
   "source": [
    "model = RNNLMScratch(rnn, vocab_size=1024)\n",
    "outputs = model(d2l.ones((batch_size, num_steps), dtype=d2l.int32))\n",
    "check_shape(outputs, (batch_size, num_steps, 1024))"
   ],
   "execution_count": 10,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=rnn-implementation-md-12 fw=all -->\n",
    "\n",
    "## Gradient Clipping\n",
    "\n",
    "While you are already used to thinking of neural networks as \"deep\" in the\n",
    "sense that many layers separate input from output within a single time step,\n",
    "the length of the sequence introduces a new notion of depth. Backpropagating\n",
    "through $T$ time steps produces a chain of matrix products of length\n",
    "$\\mathcal{O}(T)$, and as that section warned, such\n",
    "products can make gradients explode or vanish depending on the weight\n",
    "matrices. We analyze this phenomenon carefully in that section;\n",
    "vanishing gradients motivate the architectures of that section.\n",
    "Exploding gradients, however, have a blunt and ubiquitous remedy that we\n",
    "need right now, because even this small model will diverge without it.\n",
    "\n",
    "To see what a large gradient threatens, suppose the objective $f$ is\n",
    "$L$-Lipschitz, so that $|f(\\mathbf{x}) - f(\\mathbf{y})| \\leq\n",
    "L \\|\\mathbf{x} - \\mathbf{y}\\|$ for any $\\mathbf{x}$ and $\\mathbf{y}$. A\n",
    "gradient step with learning rate $\\eta$ then changes the objective by at most\n",
    "\n",
    "$$|f(\\mathbf{x}) - f(\\mathbf{x} - \\eta\\mathbf{g})| \\leq L \\eta\\|\\mathbf{g}\\|.$$\n",
    "\n",
    "If $\\|\\mathbf{g}\\|$ spikes, a single update can be violent enough to undo\n",
    "thousands of steps of progress, and training diverges or proceeds through\n",
    "massive loss spikes. Shrinking $\\eta$ until even the rare spike is safe would\n",
    "slow every step to protect against a few. *Gradient clipping* instead caps\n",
    "the norm on the occasions it is too large, projecting $\\mathbf{g}$ onto a\n",
    "ball of radius $\\theta$:\n",
    "\n",
    "$$\\mathbf{g} \\leftarrow \\min\\left(1, \\frac{\\theta}{\\|\\mathbf{g}\\|}\\right) \\mathbf{g}.$$\n",
    "\n",
    "The clipped gradient never exceeds norm $\\theta$ and keeps its original\n",
    "direction. It also limits the influence any single minibatch can exert on the\n",
    "parameters, a crude form of robustness. To be clear, clipping means we do not\n",
    "always follow the true gradient, and reasoning analytically about its side\n",
    "effects is hard. It is a hack, but a nearly universal one: virtually every\n",
    "recurrent (and, at scale, transformer) training loop runs with some form of\n",
    "gradient clipping. Below we compute the norm over all model parameters\n",
    "concatenated into one giant vector."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=rnn-implementation-md-13 fw=jax -->\n",
    "\n",
    "In the JAX trainer, clipping is not a separate method call: `fit` chains\n",
    "`optax.clip_by_global_norm(gradient_clip_val)` in front of the optimizer, so\n",
    "every update is clipped inside the jitted training step. The method below\n",
    "implements the same projection explicitly. The trainer never calls it; we\n",
    "show it so you can see, in the same style as the other tabs, exactly what\n",
    "the `optax` transformation computes."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "rnn-implementation-gradient-clipping"
   },
   "source": [
    "@d2l.add_to_class(d2l.Trainer)\n",
    "def clip_gradients(self, grad_clip_val, grads):\n",
    "    grad_leaves, _ = jax.tree_util.tree_flatten(grads)\n",
    "    norm = jnp.sqrt(sum(jnp.vdot(x, x) for x in grad_leaves))\n",
    "    clip = lambda grad: jnp.where(norm < grad_clip_val,\n",
    "                                  grad, grad * (grad_clip_val / norm))\n",
    "    return jax.tree_util.tree_map(clip, grads)"
   ],
   "execution_count": 11,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=rnn-implementation-md-14 fw=all -->\n",
    "\n",
    "## Training\n",
    "\n",
    "The `d2l.TimeMachine` pipeline of that section downloads the\n",
    "corpus, trains the BPE tokenizer on it, and serves minibatches of token-id\n",
    "windows together with their shift-by-one targets. The corpus is about 66,000\n",
    "BPE tokens long; its default split reserves only the first 10,000 windows\n",
    "for training, which suits quick demonstrations but starves a real model\n",
    "(an exercise asks you to watch what goes wrong). We therefore train on\n",
    "50,000 windows, most of the novella, and validate on the following 5,000."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "rnn-implementation-training-1"
   },
   "source": [
    "data = d2l.TimeMachine(batch_size=1024, num_steps=32,\n",
    "                       num_train=50000, num_val=5000)"
   ],
   "execution_count": 12,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=rnn-implementation-md-15 fw=all -->\n",
    "\n",
    "One subtlety of this pipeline deserves a name before we train on it. Every\n",
    "window is `num_steps` tokens long and every forward pass starts from a fresh\n",
    "zero state, so gradients flow backward through at most 32 steps: the\n",
    "dependency chain is *truncated* at the window boundary. The model can still\n",
    "learn longer-range structure only insofar as it helps within a window. This\n",
    "is the standard practical compromise, called truncated backpropagation\n",
    "through time, and that section analyzes what the truncation costs. A\n",
    "common variant for very long sequences carries the final state across\n",
    "consecutive minibatch chunks instead of resetting it; in that case the\n",
    "carried state must be *detached* from the autograd graph (for instance with\n",
    "`state.detach()` in PyTorch or `jax.lax.stop_gradient` in JAX), since\n",
    "otherwise the graph, and the cost of the backward pass, would grow with\n",
    "every chunk processed.\n",
    "\n",
    "Now we train the model, a cell with 128 hidden units under an embedding of\n",
    "dimension 64, for ten epochs, clipping gradients to norm 1. Recall from\n",
    "that section that training is teacher-forced: every step conditions on\n",
    "the true prefix from the corpus. We time the run for a comparison to come."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "rnn-implementation-training-2"
   },
   "source": [
    "rnn = RNNScratch(num_inputs=64, num_hiddens=128)\n",
    "model = RNNLMScratch(rnn, vocab_size=len(data.vocab), lr=4)"
   ],
   "execution_count": 13,
   "outputs": []
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "rnn-implementation-training-3"
   },
   "source": [
    "trainer = d2l.Trainer(max_epochs=10, gradient_clip_val=1, num_gpus=1)\n",
    "model.board.yscale = 'log'  # perplexity spans orders of magnitude\n",
    "t0 = time.time()\n",
    "trainer.fit(model, data)\n",
    "t_scratch = time.time() - t0"
   ],
   "execution_count": 14,
   "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=\"240.6625pt\" height=\"183.35625pt\" viewBox=\"0 0 240.6625 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-19T15:11:10.359085</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 240.6625 183.35625 \nL 240.6625 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 31.8 145.8 \nL 227.1 145.8 \nL 227.1 7.2 \nL 31.8 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=\"m840e69fe04\" d=\"M 0 0 \nL 0 3.5 \n\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </defs>\n      <g>\n       <use xlink:href=\"#m840e69fe04\" x=\"31.8\" 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(28.61875 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=\"#m840e69fe04\" x=\"70.86\" 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(67.67875 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=\"#m840e69fe04\" x=\"109.92\" 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(106.73875 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=\"#m840e69fe04\" x=\"148.98\" 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(145.79875 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=\"#m840e69fe04\" x=\"188.04\" 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(184.85875 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=\"#m840e69fe04\" x=\"227.1\" 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(220.7375 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     <!-- epoch -->\n     <g transform=\"translate(114.221875 174.076563) scale(0.1 -0.1)\">\n      <defs>\n       <path id=\"DejaVuSans-65\" d=\"M 3597 1894 \nL 3597 1613 \nL 953 1613 \nQ 991 1019 1311 708 \nQ 1631 397 2203 397 \nQ 2534 397 2845 478 \nQ 3156 559 3463 722 \nL 3463 178 \nQ 3153 47 2828 -22 \nQ 2503 -91 2169 -91 \nQ 1331 -91 842 396 \nQ 353 884 353 1716 \nQ 353 2575 817 3079 \nQ 1281 3584 2069 3584 \nQ 2775 3584 3186 3129 \nQ 3597 2675 3597 1894 \nz\nM 3022 2063 \nQ 3016 2534 2758 2815 \nQ 2500 3097 2075 3097 \nQ 1594 3097 1305 2825 \nQ 1016 2553 972 2059 \nL 3022 2063 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-70\" d=\"M 1159 525 \nL 1159 -1331 \nL 581 -1331 \nL 581 3500 \nL 1159 3500 \nL 1159 2969 \nQ 1341 3281 1617 3432 \nQ 1894 3584 2278 3584 \nQ 2916 3584 3314 3078 \nQ 3713 2572 3713 1747 \nQ 3713 922 3314 415 \nQ 2916 -91 2278 -91 \nQ 1894 -91 1617 61 \nQ 1341 213 1159 525 \nz\nM 3116 1747 \nQ 3116 2381 2855 2742 \nQ 2594 3103 2138 3103 \nQ 1681 3103 1420 2742 \nQ 1159 2381 1159 1747 \nQ 1159 1113 1420 752 \nQ 1681 391 2138 391 \nQ 2594 391 2855 752 \nQ 3116 1113 3116 1747 \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       <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-68\" 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 4863 \nL 1159 4863 \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-65\"/>\n      <use xlink:href=\"#DejaVuSans-70\" transform=\"translate(61.523438 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6f\" transform=\"translate(125 0)\"/>\n      <use xlink:href=\"#DejaVuSans-63\" transform=\"translate(186.181641 0)\"/>\n      <use xlink:href=\"#DejaVuSans-68\" transform=\"translate(241.162109 0)\"/>\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=\"m03c6736304\" d=\"M 0 0 \nL -3.5 0 \n\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </defs>\n      <g>\n       <use xlink:href=\"#m03c6736304\" x=\"31.8\" y=\"92.756818\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_8\">\n      <!-- $\\mathdefault{10^{2}}$ -->\n      <g transform=\"translate(7.2 96.556037) scale(0.1 -0.1)\">\n       <use xlink:href=\"#DejaVuSans-31\" transform=\"translate(0 0.765625)\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(63.623047 0.765625)\"/>\n       <use xlink:href=\"#DejaVuSans-32\" transform=\"translate(128.203125 39.046875) scale(0.7)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_2\">\n     <g id=\"line2d_8\">\n      <defs>\n       <path id=\"m6256a735e8\" d=\"M 0 0 \nL -2 0 \n\" style=\"stroke: #000000; stroke-width: 0.6\"/>\n      </defs>\n      <g>\n       <use xlink:href=\"#m6256a735e8\" x=\"31.8\" y=\"143.220043\" style=\"stroke: #000000; stroke-width: 0.6\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_3\">\n     <g id=\"line2d_9\">\n      <g>\n       <use xlink:href=\"#m6256a735e8\" x=\"31.8\" y=\"131.162159\" style=\"stroke: #000000; stroke-width: 0.6\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_4\">\n     <g id=\"line2d_10\">\n      <g>\n       <use xlink:href=\"#m6256a735e8\" x=\"31.8\" y=\"121.809337\" style=\"stroke: #000000; stroke-width: 0.6\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_5\">\n     <g id=\"line2d_11\">\n      <g>\n       <use xlink:href=\"#m6256a735e8\" x=\"31.8\" y=\"114.167525\" style=\"stroke: #000000; stroke-width: 0.6\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_6\">\n     <g id=\"line2d_12\">\n      <g>\n       <use xlink:href=\"#m6256a735e8\" x=\"31.8\" y=\"107.706465\" style=\"stroke: #000000; stroke-width: 0.6\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_7\">\n     <g id=\"line2d_13\">\n      <g>\n       <use xlink:href=\"#m6256a735e8\" x=\"31.8\" y=\"102.10964\" style=\"stroke: #000000; stroke-width: 0.6\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_8\">\n     <g id=\"line2d_14\">\n      <g>\n       <use xlink:href=\"#m6256a735e8\" x=\"31.8\" y=\"97.172891\" style=\"stroke: #000000; stroke-width: 0.6\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_9\">\n     <g id=\"line2d_15\">\n      <g>\n       <use xlink:href=\"#m6256a735e8\" x=\"31.8\" y=\"63.7043\" style=\"stroke: #000000; stroke-width: 0.6\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_10\">\n     <g id=\"line2d_16\">\n      <g>\n       <use xlink:href=\"#m6256a735e8\" x=\"31.8\" y=\"46.709666\" style=\"stroke: #000000; stroke-width: 0.6\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_11\">\n     <g id=\"line2d_17\">\n      <g>\n       <use xlink:href=\"#m6256a735e8\" x=\"31.8\" y=\"34.651782\" style=\"stroke: #000000; stroke-width: 0.6\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_12\">\n     <g id=\"line2d_18\">\n      <g>\n       <use xlink:href=\"#m6256a735e8\" x=\"31.8\" y=\"25.29896\" style=\"stroke: #000000; stroke-width: 0.6\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_13\">\n     <g id=\"line2d_19\">\n      <g>\n       <use xlink:href=\"#m6256a735e8\" x=\"31.8\" y=\"17.657148\" style=\"stroke: #000000; stroke-width: 0.6\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_14\">\n     <g id=\"line2d_20\">\n      <g>\n       <use xlink:href=\"#m6256a735e8\" x=\"31.8\" y=\"11.196088\" style=\"stroke: #000000; stroke-width: 0.6\"/>\n      </g>\n     </g>\n    </g>\n   </g>\n   <g id=\"line2d_21\">\n    <path d=\"M 36.479062 13.5 \nL 46.244062 40.704648 \nL 56.009062 59.063398 \nL 65.774062 69.20577 \nL 75.539062 77.947916 \nL 85.304063 85.299347 \nL 95.069063 92.117168 \nL 104.834063 98.507346 \nL 114.599063 103.833335 \nL 124.364063 108.279823 \nL 134.129063 112.862343 \nL 143.894063 116.759335 \nL 153.659063 120.307584 \nL 163.424063 123.473685 \nL 173.189063 126.819587 \nL 182.954063 129.741391 \nL 192.719063 132.500735 \nL 202.484063 134.906508 \nL 212.249063 137.722342 \nL 222.014063 139.5 \n\" clip-path=\"url(#pee714eb89e)\" style=\"fill: none; stroke: #1f77b4; stroke-width: 1.5; stroke-linecap: square\"/>\n   </g>\n   <g id=\"line2d_22\">\n    <path d=\"M 51.33 52.869378 \nL 70.86 70.648186 \nL 90.39 80.618758 \nL 109.92 87.525983 \nL 129.45 90.514727 \nL 148.98 94.478173 \nL 168.51 96.257071 \nL 188.04 95.898801 \nL 207.57 98.15012 \nL 227.1 97.720942 \n\" clip-path=\"url(#pee714eb89e)\" 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 31.8 145.8 \nL 31.8 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 227.1 145.8 \nL 227.1 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 31.8 145.8 \nL 227.1 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 31.8 7.2 \nL 227.1 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 144.35 45.1125 \nL 220.1 45.1125 \nQ 222.1 45.1125 222.1 43.1125 \nL 222.1 14.2 \nQ 222.1 12.2 220.1 12.2 \nL 144.35 12.2 \nQ 142.35 12.2 142.35 14.2 \nL 142.35 43.1125 \nQ 142.35 45.1125 144.35 45.1125 \nz\n\" style=\"fill: #ffffff; opacity: 0.8; stroke: #cccccc; stroke-linejoin: miter\"/>\n    </g>\n    <g id=\"line2d_23\">\n     <path d=\"M 146.35 20.298438 \nL 156.35 20.298438 \nL 166.35 20.298438 \n\" style=\"fill: none; stroke: #1f77b4; stroke-width: 1.5; stroke-linecap: square\"/>\n    </g>\n    <g id=\"text_9\">\n     <!-- train_ppl -->\n     <g transform=\"translate(174.35 23.798438) scale(0.1 -0.1)\">\n      <defs>\n       <path id=\"DejaVuSans-74\" d=\"M 1172 4494 \nL 1172 3500 \nL 2356 3500 \nL 2356 3053 \nL 1172 3053 \nL 1172 1153 \nQ 1172 725 1289 603 \nQ 1406 481 1766 481 \nL 2356 481 \nL 2356 0 \nL 1766 0 \nQ 1100 0 847 248 \nQ 594 497 594 1153 \nL 594 3053 \nL 172 3053 \nL 172 3500 \nL 594 3500 \nL 594 4494 \nL 1172 4494 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-72\" d=\"M 2631 2963 \nQ 2534 3019 2420 3045 \nQ 2306 3072 2169 3072 \nQ 1681 3072 1420 2755 \nQ 1159 2438 1159 1844 \nL 1159 0 \nL 581 0 \nL 581 3500 \nL 1159 3500 \nL 1159 2956 \nQ 1341 3275 1631 3429 \nQ 1922 3584 2338 3584 \nQ 2397 3584 2469 3576 \nQ 2541 3569 2628 3553 \nL 2631 2963 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-61\" d=\"M 2194 1759 \nQ 1497 1759 1228 1600 \nQ 959 1441 959 1056 \nQ 959 750 1161 570 \nQ 1363 391 1709 391 \nQ 2188 391 2477 730 \nQ 2766 1069 2766 1631 \nL 2766 1759 \nL 2194 1759 \nz\nM 3341 1997 \nL 3341 0 \nL 2766 0 \nL 2766 531 \nQ 2569 213 2275 61 \nQ 1981 -91 1556 -91 \nQ 1019 -91 701 211 \nQ 384 513 384 1019 \nQ 384 1609 779 1909 \nQ 1175 2209 1959 2209 \nL 2766 2209 \nL 2766 2266 \nQ 2766 2663 2505 2880 \nQ 2244 3097 1772 3097 \nQ 1472 3097 1187 3025 \nQ 903 2953 641 2809 \nL 641 3341 \nQ 956 3463 1253 3523 \nQ 1550 3584 1831 3584 \nQ 2591 3584 2966 3190 \nQ 3341 2797 3341 1997 \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       <path id=\"DejaVuSans-5f\" d=\"M 3263 -1063 \nL 3263 -1509 \nL -63 -1509 \nL -63 -1063 \nL 3263 -1063 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-6c\" d=\"M 603 4863 \nL 1178 4863 \nL 1178 0 \nL 603 0 \nL 603 4863 \nz\n\" transform=\"scale(0.015625)\"/>\n      </defs>\n      <use xlink:href=\"#DejaVuSans-74\"/>\n      <use xlink:href=\"#DejaVuSans-72\" transform=\"translate(39.208984 0)\"/>\n      <use xlink:href=\"#DejaVuSans-61\" transform=\"translate(80.322266 0)\"/>\n      <use xlink:href=\"#DejaVuSans-69\" transform=\"translate(141.601562 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6e\" transform=\"translate(169.384766 0)\"/>\n      <use xlink:href=\"#DejaVuSans-5f\" transform=\"translate(232.763672 0)\"/>\n      <use xlink:href=\"#DejaVuSans-70\" transform=\"translate(282.763672 0)\"/>\n      <use xlink:href=\"#DejaVuSans-70\" transform=\"translate(346.240234 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6c\" transform=\"translate(409.716797 0)\"/>\n     </g>\n    </g>\n    <g id=\"line2d_24\">\n     <path d=\"M 146.35 35.254688 \nL 156.35 35.254688 \nL 166.35 35.254688 \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_10\">\n     <!-- val_ppl -->\n     <g transform=\"translate(174.35 38.754688) scale(0.1 -0.1)\">\n      <defs>\n       <path id=\"DejaVuSans-76\" d=\"M 191 3500 \nL 800 3500 \nL 1894 563 \nL 2988 3500 \nL 3597 3500 \nL 2284 0 \nL 1503 0 \nL 191 3500 \nz\n\" transform=\"scale(0.015625)\"/>\n      </defs>\n      <use xlink:href=\"#DejaVuSans-76\"/>\n      <use xlink:href=\"#DejaVuSans-61\" transform=\"translate(59.179688 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6c\" transform=\"translate(120.458984 0)\"/>\n      <use xlink:href=\"#DejaVuSans-5f\" transform=\"translate(148.242188 0)\"/>\n      <use xlink:href=\"#DejaVuSans-70\" transform=\"translate(198.242188 0)\"/>\n      <use xlink:href=\"#DejaVuSans-70\" transform=\"translate(261.71875 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6c\" transform=\"translate(325.195312 0)\"/>\n     </g>\n    </g>\n   </g>\n  </g>\n </g>\n <defs>\n  <clipPath id=\"pee714eb89e\">\n   <rect x=\"31.8\" 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=rnn-implementation-md-16 fw=all -->\n",
    "\n",
    "Since perplexity ranges over orders of magnitude during training, we plot it\n",
    "on a logarithmic axis. The curve starts near the vocabulary size, exactly\n",
    "the near-uniform initial model we constructed, and falls fast; at this\n",
    "aggressive learning rate the first few updates can transiently overshoot\n",
    "(clipping keeps the overshoot from becoming divergence, as an exercise\n",
    "invites you to verify). Let's read off the final validation perplexity."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "rnn-implementation-training-4"
   },
   "source": [
    "total_loss = num_tokens = 0\n",
    "for X_val, y_val in data.val_dataloader():\n",
    "    losses = model.loss(model(X_val), y_val, averaged=False)\n",
    "    total_loss += float(losses.sum())\n",
    "    num_tokens += losses.size\n",
    "ppl_scratch = math.exp(total_loss / num_tokens)\n",
    "print(f'validation perplexity {ppl_scratch:.1f}')"
   ],
   "execution_count": 15,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "validation perplexity 88.3\n"
     ]
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=rnn-implementation-md-17 fw=all -->\n",
    "\n",
    "A perplexity in the tens-to-hundreds may look alarming next to the\n",
    "single-digit perplexities of the character-level models earlier in this\n",
    "chapter. Both numbers are correct, and the comparison is meaningless: our model\n",
    "chooses among 1,024 BPE tokens per step, a character model among 27\n",
    "characters, and per-token perplexity cannot compare models with different\n",
    "tokenizers. This is precisely why that section introduced\n",
    "bits per byte. Each of our tokens covers several bytes of text, so we\n",
    "convert: dividing the per-token surprisal $\\log_2(\\textrm{ppl})$ by the\n",
    "average number of bytes per token gives the price in bits of each byte of\n",
    "validation text."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "rnn-implementation-training-5"
   },
   "source": [
    "ids = d2l.numpy(data.X[data.num_train:data.num_train+data.num_val, 0]).tolist()\n",
    "bytes_per_token = len(data.tokenizer.decode(ids).encode('utf-8')) / len(ids)\n",
    "print(f'{bytes_per_token:.2f} bytes/token, '\n",
    "      f'{math.log2(ppl_scratch) / bytes_per_token:.2f} bits per byte')"
   ],
   "execution_count": 16,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "2.78 bytes/token, 2.33 bits per byte\n"
     ]
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=rnn-implementation-md-18 fw=all -->\n",
    "\n",
    "Back in that section, the character-tokenized trigram scored\n",
    "2.68 bits per byte on this same text. Our BPE-level model, despite a\n",
    "per-token perplexity more than ten times larger, comes in below that,\n",
    "compressing the same text *better*. The lesson carries beyond this\n",
    "comparison: whenever two language models tokenize differently, compare bits\n",
    "per byte, never perplexity.\n",
    "\n",
    "## Generating Text\n",
    "\n",
    "Once trained, the language model can do what that section promised:\n",
    "continue a prefix. The `predict` method below first *warms up* on the\n",
    "user-supplied prefix, feeding its tokens one at a time to build up a hidden\n",
    "state without emitting anything. It then generates `num_tokens` new tokens,\n",
    "each time turning the current logits into a choice of next token and feeding\n",
    "that choice back in as the next input.\n",
    "\n",
    "How should logits become a choice? The method offers the two simplest\n",
    "strategies. With `temperature=0` it is *greedy*: always take the\n",
    "highest-scoring token. Otherwise it *samples* from the model's next-token\n",
    "distribution after scaling the logits by $1/T$ for temperature $T$: values\n",
    "below 1 sharpen the distribution toward greedy behavior, values above 1\n",
    "flatten it toward uniform randomness."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "rnn-implementation-generating-text-1"
   },
   "source": [
    "@d2l.add_to_class(RNNLMScratch)\n",
    "def predict(self, prefix, num_tokens, tok, device=None, temperature=0.0,\n",
    "            rng=None):\n",
    "    model = nnx.view(self, deterministic=True, use_running_average=True,\n",
    "                     raise_if_not_found=False)\n",
    "    outputs, state = tok.encode(prefix), None\n",
    "    for i in range(len(outputs) - 1):  # Warm up on the prefix\n",
    "        X = d2l.tensor([[outputs[i]]])\n",
    "        _, state = model.rnn(model.embedding(X), state)\n",
    "    rng = random.Random() if rng is None else rng\n",
    "    for _ in range(num_tokens):  # Generate num_tokens continuation tokens\n",
    "        X = d2l.tensor([[outputs[-1]]])\n",
    "        rnn_outputs, state = model.rnn(model.embedding(X), state)\n",
    "        logits = d2l.numpy(model.output_layer(rnn_outputs))[0, 0]\n",
    "        if temperature == 0:\n",
    "            outputs.append(int(logits.argmax()))\n",
    "        else:\n",
    "            weights = [math.exp(l) for l in\n",
    "                       (logits - logits.max()) / temperature]\n",
    "            outputs.append(rng.choices(range(len(weights)), weights)[0])\n",
    "    return tok.decode(outputs)"
   ],
   "execution_count": 17,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=rnn-implementation-md-19 fw=all -->\n",
    "\n",
    "Greedy decoding first. Note that the prefix is real text, not token ids: the\n",
    "tokenizer trained by the pipeline (`data.tokenizer`) encodes it on the way\n",
    "in and decodes the generated ids on the way out."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "rnn-implementation-generating-text-2"
   },
   "source": [
    "model.predict('the time traveller', 50, data.tokenizer)"
   ],
   "execution_count": 18,
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "\"the time traveller.\\n\\n'In the Time Traveller, and\\nsossibly the Time Traveller.\\n\\n'In the Time Traveller, and\\nsossibly the Time Traveller.\\n\\n'In the Time Traveller,\""
     },
     "metadata": {},
     "execution_count": 18
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=rnn-implementation-md-20 fw=all -->\n",
    "\n",
    "The continuation is locally plausible Wells, but it does not stay\n",
    "interesting for long. Greedy decoding is deterministic, and it tends to fall\n",
    "into repetition: once the hidden state drifts into a high-probability\n",
    "neighborhood, the same phrases recur again and again. Sampling with\n",
    "temperature breaks such loops at the price of occasional strange choices,\n",
    "and lowering the temperature interpolates back toward the greedy behavior."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "rnn-implementation-generating-text-3"
   },
   "source": [
    "for T in (1.0, 0.5):\n",
    "    print(model.predict('the time traveller', 30, data.tokenizer,\n",
    "                        temperature=T, rng=random.Random(0)))"
   ],
   "execution_count": 19,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "the time traveller soly in a little recognive out of pastentre Neverildren of explain genepecies than\nthe time traveller.\n\n'Soverny, but the half-dimension of the probleiss, and I had come\n"
     ]
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=rnn-implementation-md-21 fw=all -->\n",
    "\n",
    "Neither knob fixes the underlying problem: repetition, incoherence, and the\n",
    "trade-off between them are properties of *how we choose tokens*, not just of\n",
    "the model. Choosing well is a rich topic with a modern toolkit of its own,\n",
    "and that section is devoted to it. For now we have what we need: a\n",
    "trained model and a way to watch it write.\n",
    "\n",
    "## Concise Implementation\n",
    "\n",
    "Implementing the RNN from scratch was instructive, but frameworks ship\n",
    "recurrent layers that bundle the cell and the time loop into one optimized\n",
    "call. The `RNN` class below wraps the framework layer while keeping exactly\n",
    "the interface of `RNNScratch`: it consumes a (`num_steps`, `batch_size`,\n",
    "`num_inputs`) tensor and an optional state, and returns per-step hidden\n",
    "states plus the final state."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=rnn-implementation-md-22 fw=jax -->\n",
    "\n",
    "Flax NNX provides `SimpleCell` for a vanilla recurrent cell. Unlike a layer\n",
    "that processes an entire sequence at once, the cell consumes one time step\n",
    "and an explicit hidden state; `nnx.RNN` scans it over the input sequence."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "rnn-implementation-concise-implementation-1"
   },
   "source": [
    "class RNN(nnx.Module):\n",
    "    \"\"\"The RNN model implemented with high-level APIs.\"\"\"\n",
    "    def __init__(self, num_inputs, num_hiddens, rngs=None):\n",
    "        rngs = nnx.Rngs(0) if rngs is None else rngs\n",
    "        self.num_inputs, self.num_hiddens = num_inputs, num_hiddens\n",
    "        self.rnn = nnx.RNN(\n",
    "            nnx.SimpleCell(num_inputs, num_hiddens, rngs=rngs),\n",
    "            time_major=True, return_carry=True, rngs=rngs)\n",
    "\n",
    "    def __call__(self, inputs, H=None):\n",
    "        H, outputs = self.rnn(inputs, initial_carry=H)\n",
    "        return outputs, H"
   ],
   "execution_count": 20,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=rnn-implementation-md-23 fw=all -->\n",
    "\n",
    "Because the interface is unchanged, the language model wrapper carries over\n",
    "by inheritance: `RNNLM` subclasses `RNNLMScratch` and merely swaps the\n",
    "hand-rolled embedding table and output projection for the framework's\n",
    "embedding and dense layers. Training, evaluation, and `predict` are all\n",
    "inherited. One detail deserves attention: several frameworks initialize\n",
    "embedding tables at the small scale appropriate for dense-layer weights,\n",
    "which starves the recurrence of input signal on this task, so where needed\n",
    "we request the unit-normal initialization that embeddings conventionally\n",
    "use (and that our scratch model, and PyTorch's `nn.Embedding`, already\n",
    "default to)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "rnn-implementation-concise-implementation-2"
   },
   "source": [
    "class RNNLM(d2l.RNNLMScratch):\n",
    "    \"\"\"The RNN-based language model implemented with high-level APIs.\"\"\"\n",
    "    def __init__(self, rnn, vocab_size, lr=0.01, rngs=None):\n",
    "        d2l.Classifier.__init__(self)\n",
    "        self.save_hyperparameters(ignore=['rnn', 'rngs'])\n",
    "        self.rnn = rnn\n",
    "        rngs = nnx.Rngs(2) if rngs is None else rngs\n",
    "        self.emb = nnx.Embed(vocab_size, rnn.num_inputs,\n",
    "                             embedding_init=nnx.initializers.normal(1.0),\n",
    "                             rngs=rngs)\n",
    "        self.linear = nnx.Linear(rnn.num_hiddens, vocab_size, rngs=rngs)\n",
    "\n",
    "    def embedding(self, X):\n",
    "        return self.emb(X.T)\n",
    "\n",
    "    def output_layer(self, hiddens):\n",
    "        return d2l.swapaxes(self.linear(hiddens), 0, 1)"
   ],
   "execution_count": 21,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=rnn-implementation-md-24 fw=all -->\n",
    "\n",
    "Before training, let's make a prediction with the randomly initialized\n",
    "model. Since the network has learned nothing, the continuation is byte soup;\n",
    "the replacement characters appear where generated ids decode to bytes that\n",
    "do not form valid UTF-8. It is still a useful check that the wiring, from\n",
    "tokenizer through model and back, is sound."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "rnn-implementation-concise-implementation-3"
   },
   "source": [
    "rnn = RNN(num_inputs=64, num_hiddens=128)\n",
    "model = RNNLM(rnn, vocab_size=len(data.vocab), lr=4)"
   ],
   "execution_count": 22,
   "outputs": []
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "rnn-implementation-concise-implementation-4"
   },
   "source": [
    "model.predict('it has', 20, data.tokenizer)"
   ],
   "execution_count": 23,
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "'it has m\\x1d e5asause sornessare ex( lab� Thenhing�imes now strange'"
     },
     "metadata": {},
     "execution_count": 23
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=rnn-implementation-md-25 fw=all -->\n",
    "\n",
    "Training is the same call as before, with the same hyperparameters."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "rnn-implementation-concise-implementation-5"
   },
   "source": [
    "trainer = d2l.Trainer(max_epochs=10, gradient_clip_val=1, num_gpus=1)\n",
    "model.board.yscale = 'log'\n",
    "t0 = time.time()\n",
    "trainer.fit(model, data)\n",
    "t_concise = time.time() - t0"
   ],
   "execution_count": 24,
   "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=\"240.6625pt\" height=\"183.35625pt\" viewBox=\"0 0 240.6625 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-19T15:11:42.555443</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 240.6625 183.35625 \nL 240.6625 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 31.8 145.8 \nL 227.1 145.8 \nL 227.1 7.2 \nL 31.8 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=\"mbe8c3a5054\" d=\"M 0 0 \nL 0 3.5 \n\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </defs>\n      <g>\n       <use xlink:href=\"#mbe8c3a5054\" x=\"31.8\" 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(28.61875 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=\"#mbe8c3a5054\" x=\"70.86\" 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(67.67875 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=\"#mbe8c3a5054\" x=\"109.92\" 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(106.73875 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=\"#mbe8c3a5054\" x=\"148.98\" 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(145.79875 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=\"#mbe8c3a5054\" x=\"188.04\" 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(184.85875 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=\"#mbe8c3a5054\" x=\"227.1\" 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(220.7375 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     <!-- epoch -->\n     <g transform=\"translate(114.221875 174.076563) scale(0.1 -0.1)\">\n      <defs>\n       <path id=\"DejaVuSans-65\" d=\"M 3597 1894 \nL 3597 1613 \nL 953 1613 \nQ 991 1019 1311 708 \nQ 1631 397 2203 397 \nQ 2534 397 2845 478 \nQ 3156 559 3463 722 \nL 3463 178 \nQ 3153 47 2828 -22 \nQ 2503 -91 2169 -91 \nQ 1331 -91 842 396 \nQ 353 884 353 1716 \nQ 353 2575 817 3079 \nQ 1281 3584 2069 3584 \nQ 2775 3584 3186 3129 \nQ 3597 2675 3597 1894 \nz\nM 3022 2063 \nQ 3016 2534 2758 2815 \nQ 2500 3097 2075 3097 \nQ 1594 3097 1305 2825 \nQ 1016 2553 972 2059 \nL 3022 2063 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-70\" d=\"M 1159 525 \nL 1159 -1331 \nL 581 -1331 \nL 581 3500 \nL 1159 3500 \nL 1159 2969 \nQ 1341 3281 1617 3432 \nQ 1894 3584 2278 3584 \nQ 2916 3584 3314 3078 \nQ 3713 2572 3713 1747 \nQ 3713 922 3314 415 \nQ 2916 -91 2278 -91 \nQ 1894 -91 1617 61 \nQ 1341 213 1159 525 \nz\nM 3116 1747 \nQ 3116 2381 2855 2742 \nQ 2594 3103 2138 3103 \nQ 1681 3103 1420 2742 \nQ 1159 2381 1159 1747 \nQ 1159 1113 1420 752 \nQ 1681 391 2138 391 \nQ 2594 391 2855 752 \nQ 3116 1113 3116 1747 \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       <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-68\" 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 4863 \nL 1159 4863 \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-65\"/>\n      <use xlink:href=\"#DejaVuSans-70\" transform=\"translate(61.523438 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6f\" transform=\"translate(125 0)\"/>\n      <use xlink:href=\"#DejaVuSans-63\" transform=\"translate(186.181641 0)\"/>\n      <use xlink:href=\"#DejaVuSans-68\" transform=\"translate(241.162109 0)\"/>\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=\"m50742cfcde\" d=\"M 0 0 \nL -3.5 0 \n\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </defs>\n      <g>\n       <use xlink:href=\"#m50742cfcde\" x=\"31.8\" y=\"84.084764\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_8\">\n      <!-- $\\mathdefault{10^{2}}$ -->\n      <g transform=\"translate(7.2 87.883982) scale(0.1 -0.1)\">\n       <use xlink:href=\"#DejaVuSans-31\" transform=\"translate(0 0.765625)\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(63.623047 0.765625)\"/>\n       <use xlink:href=\"#DejaVuSans-32\" transform=\"translate(128.203125 39.046875) scale(0.7)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_2\">\n     <g id=\"line2d_8\">\n      <defs>\n       <path id=\"m811e6dc55f\" d=\"M 0 0 \nL -2 0 \n\" style=\"stroke: #000000; stroke-width: 0.6\"/>\n      </defs>\n      <g>\n       <use xlink:href=\"#m811e6dc55f\" x=\"31.8\" y=\"133.881446\" style=\"stroke: #000000; stroke-width: 0.6\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_3\">\n     <g id=\"line2d_9\">\n      <g>\n       <use xlink:href=\"#m811e6dc55f\" x=\"31.8\" y=\"121.982828\" style=\"stroke: #000000; stroke-width: 0.6\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_4\">\n     <g id=\"line2d_10\">\n      <g>\n       <use xlink:href=\"#m811e6dc55f\" x=\"31.8\" y=\"112.753542\" style=\"stroke: #000000; stroke-width: 0.6\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_5\">\n     <g id=\"line2d_11\">\n      <g>\n       <use xlink:href=\"#m811e6dc55f\" x=\"31.8\" y=\"105.212667\" style=\"stroke: #000000; stroke-width: 0.6\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_6\">\n     <g id=\"line2d_12\">\n      <g>\n       <use xlink:href=\"#m811e6dc55f\" x=\"31.8\" y=\"98.836948\" style=\"stroke: #000000; stroke-width: 0.6\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_7\">\n     <g id=\"line2d_13\">\n      <g>\n       <use xlink:href=\"#m811e6dc55f\" x=\"31.8\" y=\"93.314049\" style=\"stroke: #000000; stroke-width: 0.6\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_8\">\n     <g id=\"line2d_14\">\n      <g>\n       <use xlink:href=\"#m811e6dc55f\" x=\"31.8\" y=\"88.442507\" style=\"stroke: #000000; stroke-width: 0.6\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_9\">\n     <g id=\"line2d_15\">\n      <g>\n       <use xlink:href=\"#m811e6dc55f\" x=\"31.8\" y=\"55.415985\" style=\"stroke: #000000; stroke-width: 0.6\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_10\">\n     <g id=\"line2d_16\">\n      <g>\n       <use xlink:href=\"#m811e6dc55f\" x=\"31.8\" y=\"38.645825\" style=\"stroke: #000000; stroke-width: 0.6\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_11\">\n     <g id=\"line2d_17\">\n      <g>\n       <use xlink:href=\"#m811e6dc55f\" x=\"31.8\" y=\"26.747206\" style=\"stroke: #000000; stroke-width: 0.6\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_12\">\n     <g id=\"line2d_18\">\n      <g>\n       <use xlink:href=\"#m811e6dc55f\" x=\"31.8\" y=\"17.517921\" style=\"stroke: #000000; stroke-width: 0.6\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_13\">\n     <g id=\"line2d_19\">\n      <g>\n       <use xlink:href=\"#m811e6dc55f\" x=\"31.8\" y=\"9.977046\" style=\"stroke: #000000; stroke-width: 0.6\"/>\n      </g>\n     </g>\n    </g>\n   </g>\n   <g id=\"line2d_20\">\n    <path d=\"M 36.479062 13.5 \nL 46.244062 55.933625 \nL 56.009062 69.998229 \nL 65.774062 79.549633 \nL 75.539062 87.830607 \nL 85.304063 93.963957 \nL 95.069063 99.937454 \nL 104.834063 104.563308 \nL 114.599063 109.08504 \nL 124.364063 113.006585 \nL 134.129063 116.773561 \nL 143.894063 119.644025 \nL 153.659063 123.165267 \nL 163.424063 125.694935 \nL 173.189063 128.235944 \nL 182.954063 130.709143 \nL 192.719063 133.374074 \nL 202.484063 135.276685 \nL 212.249063 137.22923 \nL 222.014063 139.5 \n\" clip-path=\"url(#paf9298aacf)\" style=\"fill: none; stroke: #1f77b4; stroke-width: 1.5; stroke-linecap: square\"/>\n   </g>\n   <g id=\"line2d_21\">\n    <path d=\"M 51.33 55.858214 \nL 70.86 68.877143 \nL 90.39 74.43638 \nL 109.92 77.491729 \nL 129.45 80.501009 \nL 148.98 82.422776 \nL 168.51 82.07288 \nL 188.04 81.652042 \nL 207.57 81.725328 \nL 227.1 80.846167 \n\" clip-path=\"url(#paf9298aacf)\" 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 31.8 145.8 \nL 31.8 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 227.1 145.8 \nL 227.1 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 31.8 145.8 \nL 227.1 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 31.8 7.2 \nL 227.1 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 144.35 45.1125 \nL 220.1 45.1125 \nQ 222.1 45.1125 222.1 43.1125 \nL 222.1 14.2 \nQ 222.1 12.2 220.1 12.2 \nL 144.35 12.2 \nQ 142.35 12.2 142.35 14.2 \nL 142.35 43.1125 \nQ 142.35 45.1125 144.35 45.1125 \nz\n\" style=\"fill: #ffffff; opacity: 0.8; stroke: #cccccc; stroke-linejoin: miter\"/>\n    </g>\n    <g id=\"line2d_22\">\n     <path d=\"M 146.35 20.298438 \nL 156.35 20.298438 \nL 166.35 20.298438 \n\" style=\"fill: none; stroke: #1f77b4; stroke-width: 1.5; stroke-linecap: square\"/>\n    </g>\n    <g id=\"text_9\">\n     <!-- train_ppl -->\n     <g transform=\"translate(174.35 23.798438) scale(0.1 -0.1)\">\n      <defs>\n       <path id=\"DejaVuSans-74\" d=\"M 1172 4494 \nL 1172 3500 \nL 2356 3500 \nL 2356 3053 \nL 1172 3053 \nL 1172 1153 \nQ 1172 725 1289 603 \nQ 1406 481 1766 481 \nL 2356 481 \nL 2356 0 \nL 1766 0 \nQ 1100 0 847 248 \nQ 594 497 594 1153 \nL 594 3053 \nL 172 3053 \nL 172 3500 \nL 594 3500 \nL 594 4494 \nL 1172 4494 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-72\" d=\"M 2631 2963 \nQ 2534 3019 2420 3045 \nQ 2306 3072 2169 3072 \nQ 1681 3072 1420 2755 \nQ 1159 2438 1159 1844 \nL 1159 0 \nL 581 0 \nL 581 3500 \nL 1159 3500 \nL 1159 2956 \nQ 1341 3275 1631 3429 \nQ 1922 3584 2338 3584 \nQ 2397 3584 2469 3576 \nQ 2541 3569 2628 3553 \nL 2631 2963 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-61\" d=\"M 2194 1759 \nQ 1497 1759 1228 1600 \nQ 959 1441 959 1056 \nQ 959 750 1161 570 \nQ 1363 391 1709 391 \nQ 2188 391 2477 730 \nQ 2766 1069 2766 1631 \nL 2766 1759 \nL 2194 1759 \nz\nM 3341 1997 \nL 3341 0 \nL 2766 0 \nL 2766 531 \nQ 2569 213 2275 61 \nQ 1981 -91 1556 -91 \nQ 1019 -91 701 211 \nQ 384 513 384 1019 \nQ 384 1609 779 1909 \nQ 1175 2209 1959 2209 \nL 2766 2209 \nL 2766 2266 \nQ 2766 2663 2505 2880 \nQ 2244 3097 1772 3097 \nQ 1472 3097 1187 3025 \nQ 903 2953 641 2809 \nL 641 3341 \nQ 956 3463 1253 3523 \nQ 1550 3584 1831 3584 \nQ 2591 3584 2966 3190 \nQ 3341 2797 3341 1997 \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       <path id=\"DejaVuSans-5f\" d=\"M 3263 -1063 \nL 3263 -1509 \nL -63 -1509 \nL -63 -1063 \nL 3263 -1063 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-6c\" d=\"M 603 4863 \nL 1178 4863 \nL 1178 0 \nL 603 0 \nL 603 4863 \nz\n\" transform=\"scale(0.015625)\"/>\n      </defs>\n      <use xlink:href=\"#DejaVuSans-74\"/>\n      <use xlink:href=\"#DejaVuSans-72\" transform=\"translate(39.208984 0)\"/>\n      <use xlink:href=\"#DejaVuSans-61\" transform=\"translate(80.322266 0)\"/>\n      <use xlink:href=\"#DejaVuSans-69\" transform=\"translate(141.601562 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6e\" transform=\"translate(169.384766 0)\"/>\n      <use xlink:href=\"#DejaVuSans-5f\" transform=\"translate(232.763672 0)\"/>\n      <use xlink:href=\"#DejaVuSans-70\" transform=\"translate(282.763672 0)\"/>\n      <use xlink:href=\"#DejaVuSans-70\" transform=\"translate(346.240234 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6c\" transform=\"translate(409.716797 0)\"/>\n     </g>\n    </g>\n    <g id=\"line2d_23\">\n     <path d=\"M 146.35 35.254688 \nL 156.35 35.254688 \nL 166.35 35.254688 \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_10\">\n     <!-- val_ppl -->\n     <g transform=\"translate(174.35 38.754688) scale(0.1 -0.1)\">\n      <defs>\n       <path id=\"DejaVuSans-76\" d=\"M 191 3500 \nL 800 3500 \nL 1894 563 \nL 2988 3500 \nL 3597 3500 \nL 2284 0 \nL 1503 0 \nL 191 3500 \nz\n\" transform=\"scale(0.015625)\"/>\n      </defs>\n      <use xlink:href=\"#DejaVuSans-76\"/>\n      <use xlink:href=\"#DejaVuSans-61\" transform=\"translate(59.179688 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6c\" transform=\"translate(120.458984 0)\"/>\n      <use xlink:href=\"#DejaVuSans-5f\" transform=\"translate(148.242188 0)\"/>\n      <use xlink:href=\"#DejaVuSans-70\" transform=\"translate(198.242188 0)\"/>\n      <use xlink:href=\"#DejaVuSans-70\" transform=\"translate(261.71875 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6c\" transform=\"translate(325.195312 0)\"/>\n     </g>\n    </g>\n   </g>\n  </g>\n </g>\n <defs>\n  <clipPath id=\"paf9298aacf\">\n   <rect x=\"31.8\" 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=rnn-implementation-md-26 fw=all -->\n",
    "\n",
    "The trained model reaches a validation perplexity comparable to the\n",
    "from-scratch implementation, and its samples read the same."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "rnn-implementation-concise-implementation-6"
   },
   "source": [
    "total_loss = num_tokens = 0\n",
    "for X_val, y_val in data.val_dataloader():\n",
    "    losses = model.loss(model(X_val), y_val, averaged=False)\n",
    "    total_loss += float(losses.sum())\n",
    "    num_tokens += losses.size\n",
    "ppl_concise = math.exp(total_loss / num_tokens)\n",
    "pred = model.predict('the time traveller', 30, data.tokenizer)\n",
    "print(f'perplexity {ppl_concise:.1f}, {pred!r}')"
   ],
   "execution_count": 25,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "perplexity 107.5, \"the time traveller, and\\nthemathem of\\nthem, and,\\nthe silent of of\\nthe Time Traveller. 'You\"\n"
     ]
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=rnn-implementation-md-27 fw=all -->\n",
    "\n",
    "### Scratch versus Concise, Measured\n",
    "\n",
    "Since we timed both training runs, we can put the comparison in a small\n",
    "table rather than assert it."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "rnn-implementation-scratch-versus-concise-measured"
   },
   "source": [
    "print(f'{\"model\":>8} {\"time (s)\":>9} {\"val ppl\":>8}')\n",
    "for name, t, p in [('scratch', t_scratch, ppl_scratch),\n",
    "                   ('concise', t_concise, ppl_concise)]:\n",
    "    print(f'{name:>8} {t:>9.1f} {p:>8.1f}')"
   ],
   "execution_count": 26,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "   model  time (s)  val ppl\n scratch      21.0     88.3\n concise      15.0    107.5\n"
     ]
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=rnn-implementation-md-28 fw=jax -->\n",
    "\n",
    "The gap is modest here because both versions are JIT-compiled end to end:\n",
    "our scratch loop is unrolled and fused by XLA just like the library cell,\n",
    "and the remaining difference is mostly compilation and dispatch overhead.\n",
    "The comparison is starker in eager frameworks, where the scratch loop pays a\n",
    "Python-level launch cost at every time step."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=rnn-implementation-md-29 fw=all -->\n",
    "\n",
    "At this model size the absolute difference is seconds. At the scale of\n",
    "that section's gated cells, with more parameters per step,\n",
    "deeper stacks, and longer sequences, the same per-step overhead multiplies,\n",
    "and the fused layer becomes the only sensible choice. We will keep the\n",
    "scratch idiom for exposition and the framework layer for every model we\n",
    "actually train at length.\n",
    "\n",
    "## Summary\n",
    "\n",
    "We implemented an RNN language model twice. The from-scratch version makes\n",
    "the anatomy explicit: an embedding lookup replaces the wasteful one-hot\n",
    "encoding (it is the same linear map, with trainable rows), a recurrent cell\n",
    "carries a fixed-size state across time steps, and a shared output layer\n",
    "produces next-token logits at every step. Training with gradient clipping\n",
    "bounds the damage any one exploding gradient can do, though it does nothing\n",
    "for vanishing gradients. Because each minibatch window starts from a fresh\n",
    "state, backpropagation is truncated at the window length, a compromise that\n",
    "that section examines. Perplexities measured over different vocabularies\n",
    "are incomparable, so we converted to bits per byte to see that our BPE-level\n",
    "model genuinely improves on a character-level one. Finally, the trained model\n",
    "generates text: greedy decoding is fluent but circles, temperature sampling\n",
    "trades repetition for noise, and doing better is the subject of\n",
    "that section. The concise implementation collapses all of this into\n",
    "framework layers with the same interface and, where fused kernels exist,\n",
    "meaningfully better speed.\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. Does the trained language model ever condition on tokens further back\n",
    "   than the start of its current window? Which hyperparameter bounds the\n",
    "   length of the history it can use?\n",
    "1. Adjust the hyperparameters (number of epochs, hidden units, embedding\n",
    "   dimension, window length `num_steps`, learning rate) to improve the\n",
    "   validation perplexity. How low can you go with this architecture? Does\n",
    "   bits per byte improve by the same factor?\n",
    "1. Run the training in this section without gradient clipping. What happens?\n",
    "1. Replace $\\tanh$ with ReLU as the activation of the recurrent cell and\n",
    "   repeat the experiment. Do you still need gradient clipping? Why?\n",
    "1. Restore the pipeline defaults (`num_train=10000`) and train for 100\n",
    "   epochs. Compare the training and validation perplexity curves and explain\n",
    "   what you see. Roughly how many parameters does the model have per\n",
    "   training token in this regime?\n",
    "1. Rebuild the dataset with a 2,048-token tokenizer\n",
    "   (`d2l.TimeMachine(..., vocab_size=2048)`) and retrain. Compare the result\n",
    "   against this section's model using bits per byte. Why would comparing\n",
    "   validation perplexities mislead you here?\n",
    "1. Set the embedding dimension equal to the number of hidden units and *tie\n",
    "   the weights*: use $\\mathbf{W}_\\textrm{e}^\\top$ as the output projection\n",
    "   instead of a separate $\\mathbf{W}_{\\textrm{hq}}$. How many parameters\n",
    "   does this save? How does it affect perplexity?\n",
    "1. Show that sampling at temperature $T$ draws token $x$ with probability\n",
    "   proportional to $P(x)^{1/T}$, where $P$ is the model's next-token\n",
    "   distribution. What do the limits $T \\to 0$ and $T \\to \\infty$ recover?\n",
    "1. Train on a different H. G. Wells novel (for example, *The War of the\n",
    "   Worlds*) and evaluate on *The Time Machine*. Report both perplexity and\n",
    "   bits per byte. What does the gap relative to in-book validation tell you?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=rnn-implementation-md-30 fw=jax -->\n",
    "\n",
    "[Discussions](https://d2l.discourse.group/t/18014)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "name": "d2l-jax",
   "display_name": "d2l (JAX)",
   "language": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
