{
 "cells": [
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "---\n",
    "execute:\n",
    "  enabled: false\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-1 fw=all -->\n",
    "\n",
    "# GPUs, Devices, and Memory\n",
    "\n",
    "So far every tensor in this book has lived in main memory and every computation\n",
    "has run on the CPU. Training at any interesting scale runs on an accelerator,\n",
    "almost always a CUDA GPU, and that changes two things at once. First, every\n",
    "tensor and every parameter now has a *home*, a device, and operations only\n",
    "combine tensors that live on the same one; placing data well is your job.\n",
    "Second, the GPU's memory is small compared with main memory, typically tens of\n",
    "gigabytes, and it is the resource you will exhaust first: the daily question of\n",
    "a single-GPU builder is not \"is my model correct?\" but \"does it fit?\". This\n",
    "section covers both skills: naming devices and placing tensors and models on\n",
    "them, then measuring what actually fills GPU memory during training, trading\n",
    "compute for memory when it does not fit, and keeping the device busy once it\n",
    "does. None of the code requires a GPU to run; the helpers we define fall back\n",
    "to the CPU, and the memory measurements simply report more interesting numbers\n",
    "when a GPU is present."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "gpus-devices-memory-gpus-devices-and-memory"
   },
   "source": [
    "import time\n",
    "import jax\n",
    "from jax import numpy as jnp\n",
    "from flax import nnx\n",
    "import optax\n",
    "from d2l import jax as d2l"
   ],
   "execution_count": 1,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-2 fw=all -->\n",
    "\n",
    "## Devices"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-3 fw=jax -->\n",
    "\n",
    "In JAX every array lives on a device, and `jax.devices(backend)` returns the\n",
    "device handles of a backend. `jax.devices('cpu')[0]` is the CPU, and it stands\n",
    "for *all* physical CPU cores and all of main memory; `jax.devices('gpu')[i]`\n",
    "is one specific CUDA card and its own memory. To see what your machine has,\n",
    "run `nvidia-smi` in a shell: it lists every card, its memory, and what is\n",
    "currently running on it. We wrap device lookup in two helpers that the rest\n",
    "of the book uses."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "gpus-devices-memory-devices-1"
   },
   "source": [
    "def cpu():\n",
    "    \"\"\"Get the CPU device.\"\"\"\n",
    "    return jax.devices('cpu')[0]\n",
    "\n",
    "def gpu(i=0):\n",
    "    \"\"\"Get a GPU device.\"\"\"\n",
    "    return jax.devices('gpu')[i]\n",
    "\n",
    "cpu()"
   ],
   "execution_count": 2,
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "CpuDevice(id=0)"
     },
     "metadata": {},
     "execution_count": 2
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-4 fw=jax -->\n",
    "\n",
    "Note that a JAX device object is a handle to hardware that actually exists:\n",
    "`jax.devices('gpu')` raises a `RuntimeError` when no GPU backend is present,\n",
    "rather than returning a placeholder (which is why the demo above calls only\n",
    "`cpu()`). Our next helper therefore counts GPUs through a `try`/`except`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-5 fw=all -->\n",
    "\n",
    "We can query how many GPUs are actually available."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "gpus-devices-memory-devices-2"
   },
   "source": [
    "def num_gpus():\n",
    "    \"\"\"Get the number of available GPUs.\"\"\"\n",
    "    try:\n",
    "        return jax.device_count('gpu')\n",
    "    except:\n",
    "        return 0  # No GPU backend found\n",
    "\n",
    "num_gpus()"
   ],
   "execution_count": 3,
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "2"
     },
     "metadata": {},
     "execution_count": 3
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-6 fw=all -->\n",
    "\n",
    "Now we define two convenient functions that allow us\n",
    "to run code even if the requested GPUs do not exist."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "gpus-devices-memory-devices-3"
   },
   "source": [
    "def try_gpu(i=0):\n",
    "    \"\"\"Return gpu(i) if exists, otherwise return cpu().\"\"\"\n",
    "    if num_gpus() >= i + 1:\n",
    "        return gpu(i)\n",
    "    return cpu()\n",
    "\n",
    "def try_all_gpus():\n",
    "    \"\"\"Return all available GPUs, or [cpu(),] if no GPU exists.\"\"\"\n",
    "    devices = [gpu(i) for i in range(num_gpus())]\n",
    "    return devices if devices else [cpu()]\n",
    "\n",
    "try_gpu(), try_gpu(10), try_all_gpus()"
   ],
   "execution_count": 4,
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "(CudaDevice(id=0), CpuDevice(id=0), [CudaDevice(id=0), CudaDevice(id=1)])"
     },
     "metadata": {},
     "execution_count": 4
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-7 fw=jax -->\n",
    "\n",
    "CUDA is not the only backend JAX understands: the same program runs on CPU,\n",
    "GPU, or TPU, and plain `jax.devices()` lists the devices of the *default*\n",
    "backend, which is the best accelerator present. We keep our own helpers\n",
    "anyway: they give all four of the book's implementations one vocabulary, and\n",
    "they degrade to the CPU instead of failing, which is exactly what lets this\n",
    "book's code run unchanged on a laptop. The book standardizes on CPU plus\n",
    "CUDA; everything below transfers to TPUs with no change beyond the backend\n",
    "name."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-8 fw=all -->\n",
    "\n",
    "## Tensors, Models, and Devices"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-9 fw=jax -->\n",
    "\n",
    "By default, arrays are created on the *default device*, the first accelerator\n",
    "when one exists and the CPU otherwise. We can query where an array lives."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "gpus-devices-memory-tensors-models-and-devices-1"
   },
   "source": [
    "x = jnp.array([1, 2, 3])\n",
    "x.device"
   ],
   "execution_count": 5,
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "CudaDevice(id=0)"
     },
     "metadata": {},
     "execution_count": 5
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-10 fw=jax -->\n",
    "\n",
    "To place an array somewhere specific, `jax.device_put(x, device)` copies it\n",
    "there, and the result is *committed* to that device: JAX will keep it and\n",
    "every computation on it exactly where you said. Arrays created without an\n",
    "explicit placement, like `x` above, are *uncommitted*; they sit on the default\n",
    "device but JAX may treat them as movable when they meet committed data."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "gpus-devices-memory-tensors-models-and-devices-2"
   },
   "source": [
    "X = jax.device_put(jnp.ones((2, 3)), try_gpu())\n",
    "X"
   ],
   "execution_count": 6,
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "Array([[1., 1., 1.],\n       [1., 1., 1.]], dtype=float32)"
     },
     "metadata": {},
     "execution_count": 6
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-11 fw=all -->\n",
    "\n",
    "On a machine with two GPUs we can put a second tensor on the second card\n",
    "(on your machine, `try_gpu(1)` substitutes whatever is available)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "gpus-devices-memory-tensors-models-and-devices-3"
   },
   "source": [
    "Y = jax.device_put(jax.random.uniform(jax.random.key(0), (2, 3)),\n",
    "                   try_gpu(1))\n",
    "Y"
   ],
   "execution_count": 7,
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "Array([[0.947667  , 0.9785799 , 0.33229148],\n       [0.46866846, 0.5698887 , 0.16550303]], dtype=float32)"
     },
     "metadata": {},
     "execution_count": 7
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-12 fw=all -->\n",
    "\n",
    "### Copying Between Devices"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-13 fw=jax -->\n",
    "\n",
    "Whenever we operate on multiple arrays, they need to be on the same device.\n",
    "Uncommitted arrays are flexible: JAX decides where the result lives. But `X`\n",
    "is committed to the first GPU and `Y` to the second, and adding them raises an\n",
    "error about arrays on different devices, probably the most common error\n",
    "message of a beginner's GPU life. JAX refuses to guess between two explicit\n",
    "placements: an implicit copy would hide a slow bus transfer inside an\n",
    "innocent-looking `+`, and you would never find it. Instead we copy\n",
    "explicitly, as in the figure, and then add."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-14 fw=all -->\n",
    "\n",
    "![X lives on GPU 0 and Y on GPU 1; X.to(gpu(1)) makes a copy Z on GPU 1 (dashed), and Y + Z then runs entirely on GPU 1.](../img/bg-copyto.svg)"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "gpus-devices-memory-copying-between-devices-1"
   },
   "source": [
    "Z = jax.device_put(X, try_gpu(1))\n",
    "print(X)\n",
    "print(Z)"
   ],
   "execution_count": 8,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "[[1. 1. 1.]\n [1. 1. 1.]]\n[[1. 1. 1.]\n [1. 1. 1.]]\n"
     ]
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-15 fw=all -->\n",
    "\n",
    "Now that `Z` and `Y` live on the same device, we can add them."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "gpus-devices-memory-copying-between-devices-2"
   },
   "source": [
    "Y + Z"
   ],
   "execution_count": 9,
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "Array([[1.947667 , 1.9785799, 1.3322915],\n       [1.4686685, 1.5698887, 1.165503 ]], dtype=float32)"
     },
     "metadata": {},
     "execution_count": 9
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-16 fw=jax -->\n",
    "\n",
    "What if `Z` already lives on the target device? Then `device_put` skips the\n",
    "transfer: the array it returns shares `Z`'s buffer, so calling it defensively\n",
    "costs nothing. Comparing the buffer addresses confirms that no copy was made."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "gpus-devices-memory-copying-between-devices-3"
   },
   "source": [
    "Z2 = jax.device_put(Z, try_gpu(1))\n",
    "Z2.unsafe_buffer_pointer() == Z.unsafe_buffer_pointer()"
   ],
   "execution_count": 10,
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "True"
     },
     "metadata": {},
     "execution_count": 10
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-17 fw=all -->\n",
    "\n",
    "The reason for keeping every copy explicit is the cost model. A\n",
    "modern GPU multiplies matrices hundreds of times faster than it can receive\n",
    "data over the PCIe bus, so a transfer in the wrong place can erase the\n",
    "speedup you bought the GPU for. The discipline that follows is simple: move data to the device\n",
    "once, at the boundary of the computation, and keep everything inside the\n",
    "training loop on one device. Many small transfers are worse than one big one,\n",
    "and a transfer hidden in an inner loop is worst of all.\n",
    "\n",
    "### Models on a Device"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-18 fw=jax -->\n",
    "\n",
    "An NNX model owns a state tree, and `jax.device_put` accepts that tree. Update\n",
    "the model with the placed state and every registered leaf moves together."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "gpus-devices-memory-models-on-a-device-1"
   },
   "source": [
    "net = nnx.Sequential(nnx.Linear(X.shape[-1], 1, rngs=nnx.Rngs(0)))\n",
    "nnx.update(net, jax.device_put(nnx.state(net), try_gpu()))\n",
    "net(X)"
   ],
   "execution_count": 11,
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "Array([[-0.4064557],\n       [-0.4064557]], dtype=float32)"
     },
     "metadata": {},
     "execution_count": 11
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-19 fw=all -->\n",
    "\n",
    "The input arrived on the device, the parameters live on the device, so the\n",
    "output is computed and stored there too. Let's confirm where the parameters\n",
    "ended up."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "gpus-devices-memory-models-on-a-device-2"
   },
   "source": [
    "jax.tree_util.tree_map(lambda p: p.device, nnx.state(net))"
   ],
   "execution_count": 12,
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "State({\n  'layers': {\n    0: {\n      'bias': Param(\n        value=CudaDevice(id=0)\n      ),\n      'kernel': Param(\n        value=CudaDevice(id=0)\n      )\n    }\n  }\n})"
     },
     "metadata": {},
     "execution_count": 12
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-20 fw=jax -->\n",
    "\n",
    "Device hygiene is short in JAX because all state is explicit. The optimizer's\n",
    "state is built from the model's parameter state, so it is\n",
    "born wherever the parameters live; and inside a compiled function you never\n",
    "place anything, since the computation runs where its inputs are. Keep the\n",
    "parameters and each batch on one device and everything downstream follows."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-21 fw=all -->\n",
    "\n",
    "## GPU Memory"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-22 fw=jax -->\n",
    "\n",
    "Here is a puzzle that every JAX user hits in their first week. You create one\n",
    "small array, yet `nvidia-smi` shows the card nearly full; is that a leak? It\n",
    "is not, and the explanation is the right mental model for everything else in\n",
    "this section. Requesting memory from the CUDA driver is slow, so on first use\n",
    "XLA *preallocates* about 75% of the GPU's memory as one block and hands out\n",
    "pieces of it from its own allocator (the fraction is controlled by the\n",
    "`XLA_PYTHON_CLIENT_PREALLOCATE` and `XLA_PYTHON_CLIENT_MEM_FRACTION`\n",
    "environment variables). `nvidia-smi` sees the process from the outside, so it\n",
    "reports the whole preallocated block no matter how little of it your arrays\n",
    "occupy. The real accounting lives inside: `device.memory_stats()` returns a\n",
    "dictionary whose `bytes_in_use` entry counts live buffers and whose\n",
    "`peak_bytes_in_use` entry is their high-water mark, the same nesting of views\n",
    "that the figure sketches. On the CPU backend there is no such\n",
    "allocator and the call returns `None`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-23 fw=all -->\n",
    "\n",
    "![The three memory views nest: nvidia-smi's driver allocation contains PyTorch's reserved cache, which contains the live tensors that memory_allocated() counts.](../img/bg-allocator.svg)"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "gpus-devices-memory-gpu-memory"
   },
   "source": [
    "if num_gpus() > 0:\n",
    "    def report(tag):\n",
    "        s = gpu().memory_stats()\n",
    "        print(f'{tag}: {s[\"bytes_in_use\"] / 2**20:7.1f} MiB in use, '\n",
    "              f'{s[\"peak_bytes_in_use\"] / 2**20:7.1f} MiB peak')\n",
    "    big = jnp.zeros((256, 1024, 1024))  # 1 GiB of float32\n",
    "    big.block_until_ready()\n",
    "    report('after creating big')\n",
    "    del big\n",
    "    report('after deleting it ')\n",
    "else:\n",
    "    print('No GPU: memory_stats() returns None on the CPU backend.')"
   ],
   "execution_count": 13,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "after creating big:  1024.0 MiB in use,  1024.0 MiB peak\nafter deleting it :     0.0 MiB in use,  1024.0 MiB peak\n"
     ]
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-24 fw=jax -->\n",
    "\n",
    "On a GPU, `bytes_in_use` falls by a gibibyte the moment the buffer's last\n",
    "reference dies, while `nvidia-smi` does not move at all: the block returns to\n",
    "XLA's preallocated pool, not to the driver. If another process must share the\n",
    "card, set `XLA_PYTHON_CLIENT_PREALLOCATE=false` in the environment before the\n",
    "first computation; allocations then go to the driver on demand, visibly to\n",
    "`nvidia-smi` but more slowly."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-25 fw=all -->\n",
    "\n",
    "### What Fills Memory During Training\n",
    "\n",
    "In that section we did the bookkeeping on paper: a model with\n",
    "$N$ parameters costs $4N$ bytes for float32 weights, another $4N$ for their\n",
    "gradients, and $8N$ for Adam's two moment estimates, roughly $16N$ before any\n",
    "data arrives. The remaining term, the *activations*, is different in kind:\n",
    "backpropagation must remember the intermediate results of the forward pass in\n",
    "order to compute gradients, and their size scales with the batch size and with\n",
    "the width of every layer, while the $16N$ does not."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-26 fw=jax -->\n",
    "\n",
    "We can watch the terms arrive by reading `bytes_in_use` around the pieces of\n",
    "a training step. The activations are the exception: they exist only while the\n",
    "gradient computation runs, so they leave their trace in `peak_bytes_in_use`\n",
    "rather than in a reading you can take afterwards."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "gpus-devices-memory-what-fills-memory-during-training"
   },
   "source": [
    "if num_gpus() > 0:\n",
    "    def in_use():\n",
    "        s = gpu().memory_stats()\n",
    "        return f'{s[\"bytes_in_use\"] / 2**20:7.1f} MiB'\n",
    "    rngs = nnx.Rngs(0)\n",
    "    net = nnx.Sequential(nnx.Linear(1024, 4096, rngs=rngs), nnx.relu,\n",
    "                         nnx.Linear(4096, 4096, rngs=rngs), nnx.relu,\n",
    "                         nnx.Linear(4096, 4096, rngs=rngs), nnx.relu,\n",
    "                         nnx.Linear(4096, 10, rngs=rngs))\n",
    "    key1, key2 = jax.random.split(d2l.get_key())\n",
    "    X = jax.random.normal(key1, (4096, 1024))\n",
    "    y = jax.random.randint(key2, (4096,), 0, 10)\n",
    "    def loss(model):\n",
    "        logits = model(X)\n",
    "        return optax.softmax_cross_entropy_with_integer_labels(\n",
    "            logits, y).mean()\n",
    "    jax.block_until_ready(nnx.state(net))\n",
    "    print('weights              ', in_use())\n",
    "    grads = jax.block_until_ready(nnx.grad(loss)(net))\n",
    "    print('+ gradients          ', in_use())\n",
    "    optimizer = nnx.Optimizer(net, optax.adam(1e-3), wrt=nnx.Param)\n",
    "    jax.block_until_ready(optimizer.opt_state)\n",
    "    print('+ optimizer state    ', in_use())\n",
    "    peak = gpu().memory_stats()['peak_bytes_in_use'] / 2**20\n",
    "    print(f'peak with activations {peak:7.1f} MiB')\n",
    "else:\n",
    "    print('No GPU: run this cell on a GPU to see the terms arrive.')"
   ],
   "execution_count": 14,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "weights                 160.2 MiB\n"
     ]
    },
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "+ gradients             304.4 MiB\n+ optimizer state       592.9 MiB\npeak with activations  1236.7 MiB\n"
     ]
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-27 fw=jax -->\n",
    "\n",
    "The readings map onto the accounting. The first is the weights alone (about\n",
    "$4N$ bytes, plus the input batch). The second adds gradients exactly the size\n",
    "of the weights: in JAX a gradient is not a field attached to a parameter but\n",
    "a second pytree of the same shape, returned by `jax.grad`. The third adds\n",
    "$8N$ when `optax.adam`'s `init` builds its two moment pytrees from the\n",
    "parameters, placed wherever they live. The activations never appear as a\n",
    "plateau: they exist only inside the `jax.grad` call, so the peak reading,\n",
    "several times the weights here because the batch is large, is the only\n",
    "evidence they leave. The practical consequence is the same everywhere: when\n",
    "you are out of memory, the knob that works immediately is the batch size,\n",
    "because it scales the one term the model architecture does not fix. If a\n",
    "*growing* staircase appears across steps, look for device arrays accumulating\n",
    "on the Python side, such as appending the loss array itself, rather than\n",
    "`loss.item()`, to a running log."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-28 fw=all -->\n",
    "\n",
    "### Trading Compute for Memory: Activation Checkpointing\n",
    "\n",
    "The activation term has a second knob. Backpropagation stores every\n",
    "intermediate result only to read each one exactly once, on the way back.\n",
    "*Activation checkpointing* [@Chen.Xu.Zhang.ea.2016] refuses to store\n",
    "them: it keeps only the inputs to selected segments of the network, and during\n",
    "the backward pass reruns each segment's forward computation to regenerate the\n",
    "activations it needs. For a stack of $N$ equally sized layers, dividing the\n",
    "stack into segments of about $\\sqrt{N}$ layers reduces stored activations from\n",
    "$O(N)$ to $O(\\sqrt{N})$. The price is roughly one extra forward pass, often\n",
    "30--40% more compute per step. the figure sketches\n",
    "this schedule.\n",
    "The trade pays off exactly where deep learning spends most of its time: deep\n",
    "stacks of identical blocks, such as the residual stack we assembled in\n",
    "that section and every Transformer you will meet later.\n",
    "We rebuild a compact version of that block here.\n",
    "\n",
    "![Standard backpropagation stores every activation (top); checkpointing keeps only segment-boundary activations and recomputes the rest during the backward pass (bottom), trading roughly 1.3x compute for O(sqrt(N)) instead of O(N) activation memory.](../img/bg-activation-checkpoint.svg)"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "gpus-devices-memory-trading-compute-for-memory-activation-checkpointing-1"
   },
   "source": [
    "class ResidualBlock(nnx.Module):  # As in :numref:`sec_model_construction`\n",
    "    def __init__(self, num_hiddens, rngs):\n",
    "        self.body = nnx.Sequential(\n",
    "            nnx.Linear(num_hiddens, num_hiddens, rngs=rngs), nnx.relu,\n",
    "            nnx.Linear(num_hiddens, num_hiddens, rngs=rngs), nnx.relu)\n",
    "\n",
    "    def __call__(self, X):\n",
    "        return X + self.body(X)\n",
    "\n",
    "def run_stack(graphdef, states, X, use_checkpoint=False, segment_size=4):\n",
    "    def segment(segment_states, X):\n",
    "        for state in segment_states:\n",
    "            X = nnx.merge(graphdef, state)(X)\n",
    "        return X\n",
    "    f = jax.checkpoint(segment) if use_checkpoint else segment\n",
    "    for start in range(0, len(states), segment_size):\n",
    "        X = f(states[start:start + segment_size], X)\n",
    "    return X"
   ],
   "execution_count": 15,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-29 fw=jax -->\n",
    "\n",
    "`jax.checkpoint` (also exported as `jax.remat`) is a function transformation\n",
    "like `grad` and `jit`: `jax.checkpoint(f)` behaves exactly like `f` when\n",
    "called, but when differentiated it saves only `f`'s inputs and recomputes the\n",
    "internals during the backward pass. Randomness needs no special handling:\n",
    "JAX functions receive their PRNG keys as explicit arguments, so recomputation\n",
    "with the same key reproduces a segment containing dropout bit for bit by\n",
    "construction."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-30 fw=all -->\n",
    "\n",
    "Before measuring memory, we should verify the claim that nothing about the\n",
    "result changes: the gradients through a checkpointed stack must equal the\n",
    "ordinary ones."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "gpus-devices-memory-trading-compute-for-memory-activation-checkpointing-2"
   },
   "source": [
    "X = jax.random.normal(jax.random.key(1), (32, 64))\n",
    "blocks = [ResidualBlock(64, nnx.Rngs(k))\n",
    "          for k in jax.random.split(jax.random.key(0), 4)]\n",
    "split_blocks = [nnx.split(block) for block in blocks]\n",
    "graphdef = split_blocks[0][0]\n",
    "states = [state for _, state in split_blocks]\n",
    "\n",
    "def stack_grads(use_checkpoint):\n",
    "    loss = lambda states: run_stack(graphdef, states, X,\n",
    "                                    use_checkpoint).sum()\n",
    "    return jax.tree_util.tree_leaves(jax.grad(loss)(states))\n",
    "\n",
    "for g, g_ckpt in zip(stack_grads(False), stack_grads(True)):\n",
    "    assert jnp.allclose(g, g_ckpt)\n",
    "print('checkpointed gradients match the ordinary ones')"
   ],
   "execution_count": 16,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "checkpointed gradients match the ordinary ones\n"
     ]
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-31 fw=all -->\n",
    "\n",
    "That check runs anywhere, CPU included. The memory effect needs a GPU and a\n",
    "stack deep enough for the difference to be unambiguous: sixteen blocks of\n",
    "width 1024 at batch size 8192."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "gpus-devices-memory-trading-compute-for-memory-activation-checkpointing-3"
   },
   "source": [
    "if num_gpus() > 0:\n",
    "    X = jax.random.normal(jax.random.key(1), (8192, 1024))\n",
    "    blocks = [ResidualBlock(1024, nnx.Rngs(k))\n",
    "              for k in jax.random.split(jax.random.key(0), 16)]\n",
    "    split_blocks = [nnx.split(block) for block in blocks]\n",
    "    graphdef = split_blocks[0][0]\n",
    "    states = [state for _, state in split_blocks]\n",
    "    for use_checkpoint in (True, False):  # low first: the peak only grows\n",
    "        grad_fn = jax.jit(jax.grad(\n",
    "            lambda states: run_stack(\n",
    "                graphdef, states, X, use_checkpoint).sum()))\n",
    "        jax.block_until_ready(grad_fn(states))  # compile outside timing\n",
    "        t = time.time()\n",
    "        jax.block_until_ready(grad_fn(states))\n",
    "        peak = gpu().memory_stats()['peak_bytes_in_use'] / 2**20\n",
    "        print(f'checkpointing={use_checkpoint!s:5}  peak {peak:6.0f} MiB, '\n",
    "              f'{time.time() - t:.2f} sec')\n",
    "else:\n",
    "    print('No GPU: peak-memory comparison needs a GPU.')"
   ],
   "execution_count": 17,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "checkpointing=True   peak   1377 MiB, 0.07 sec\n"
     ]
    },
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "checkpointing=False  peak   2401 MiB, 0.06 sec\n"
     ]
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-32 fw=all -->\n",
    "\n",
    "Without checkpointing, the peak carries the activations of all sixteen blocks\n",
    "at once; with four-block segments, it carries the four segment inputs plus the\n",
    "recomputed activations of one segment, at the cost of a slower step. When a\n",
    "model almost fits, this\n",
    "trade is the difference between training and not training, which is why large\n",
    "Transformer training runs use it as a matter of course.\n",
    "\n",
    "## Don't Break the Pipeline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-33 fw=jax -->\n",
    "\n",
    "The device runs ahead of Python; in JAX this *asynchronous dispatch* is the\n",
    "native execution model on every backend, the CPU included. When you write\n",
    "`B = A @ A`, JAX does not wait for the multiplication: it queues the\n",
    "computation, returns an array that is really a promise of the result, and\n",
    "Python races on to enqueue the next operation. This asynchrony is where much\n",
    "of the speed comes from, because Python can prepare work while the device\n",
    "crunches. It also means that timing or logging naively measures nothing, or\n",
    "worse, stalls everything. The explicit synchronization point is\n",
    "`block_until_ready()`; with it we can see the gap between *queueing* work and\n",
    "the work *finishing*, on this machine's CPU as well as on any GPU."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "gpus-devices-memory-don-t-break-the-pipeline-1"
   },
   "source": [
    "A = jax.random.normal(jax.random.key(0), (2000, 2000)) / 45\n",
    "(A @ A).block_until_ready()  # Warm up\n",
    "B, t = A, time.time()\n",
    "for _ in range(32):\n",
    "    B = B @ A  # Chained, so the last result implies all finished\n",
    "print(f'time to queue 32 matrix products: {time.time() - t:.4f} sec')\n",
    "B.block_until_ready()\n",
    "print(f'time until they all finished:     {time.time() - t:.4f} sec')"
   ],
   "execution_count": 18,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "time to queue 32 matrix products: 0.0028 sec\ntime until they all finished:     0.0159 sec\n"
     ]
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-34 fw=jax -->\n",
    "\n",
    "Python returned from the loop in a few milliseconds — far less time than\n",
    "the thousand products take; they were still running. Any operation that needs a concrete value on the host forces a\n",
    "*synchronization point*: `.item()`, `np.asarray`, `print`, an `if` on an\n",
    "array's value, and `block_until_ready()` itself, whose job is to make the\n",
    "synchronization explicit (our timings above depend on it). Each one makes\n",
    "Python block until the queued work drains, and the device then sits idle\n",
    "until Python catches up. A `print(loss.item())` in the inner loop can\n",
    "serialize the whole pipeline this way, once per step, as\n",
    "the figure lays out. The fix is not to give up monitoring\n",
    "but to move it off the hot path: keep running statistics on the device and\n",
    "transfer them once per epoch, or hand values to a background consumer, which\n",
    "is exactly what our `ProgressBoard` from that section does when the\n",
    "`Trainer` plots the loss."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-35 fw=all -->\n",
    "\n",
    "![Python queues kernels k1 through k4 and races ahead while the GPU works through them serially; loss.item() forces a synchronization point where the CPU blocks until the GPU drains its queue, then both resume.](../img/bg-async-queue.svg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-36 fw=jax -->\n",
    "\n",
    "The same overlap idea applies to getting data *onto* the device, and in JAX\n",
    "it needs no per-tensor flag: `device_put` dispatches the transfer and returns\n",
    "immediately, so Python prepares the next batch while the copy overlaps the\n",
    "device's current work, which is exactly the effect other stacks arrange with\n",
    "pinned host buffers. The full treatment of asynchrony, streams, and\n",
    "multi-device parallelism is in that section."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-37 fw=all -->\n",
    "\n",
    "## The Trainer, Now with Devices"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-38 fw=jax -->\n",
    "\n",
    "In that section the `Trainer` accepted a `num_gpus` argument and\n",
    "ignored it. We can now redeem that promise with everything this section\n",
    "taught: the parameters are created on the accelerator *once*, before training\n",
    "(JAX initializes arrays on the default device, which is the accelerator\n",
    "whenever one exists), and every batch streams over per step, at the boundary\n",
    "of the computation."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "gpus-devices-memory-the-trainer-now-with-devices-1"
   },
   "source": [
    "@d2l.add_to_class(d2l.Trainer)\n",
    "def __init__(self, max_epochs, num_gpus=0, gradient_clip_val=0):\n",
    "    self.save_hyperparameters()\n",
    "    self.gpus = [d2l.gpu(i) for i in range(min(num_gpus, d2l.num_gpus()))]\n",
    "\n",
    "@d2l.add_to_class(d2l.Trainer)\n",
    "def prepare_batch(self, batch):\n",
    "    if self.gpus:\n",
    "        batch = [d2l.to(a, self.gpus[0]) for a in batch]\n",
    "    return batch"
   ],
   "execution_count": 19,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-39 fw=jax -->\n",
    "\n",
    "The `min(num_gpus, d2l.num_gpus())` makes the request a ceiling rather than a\n",
    "demand: on a machine with no GPU, `self.gpus` is empty, `prepare_batch` is a\n",
    "no-op, and training proceeds on the CPU. There is no model hook to patch,\n",
    "because `fit` initializes the parameters itself and JAX creates them on the\n",
    "default device, the GPU whenever one is present. Every `Trainer(num_gpus=1)`\n",
    "you see from the next chapter onward relies on this fallback, which is how\n",
    "one codebase serves both the laptop you are reading on and a GPU server. As a\n",
    "capstone we train a classifier built from this chapter's residual blocks on\n",
    "Fashion-MNIST; the `Trainer` moves each batch, and the memory budget of the\n",
    "run is exactly the accounting from above."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "gpus-devices-memory-the-trainer-now-with-devices-2"
   },
   "source": [
    "class ResMLPClassifier(d2l.Classifier):\n",
    "    def __init__(self, num_hiddens=256, num_blocks=2, lr=0.1, rngs=None):\n",
    "        super().__init__()\n",
    "        self.save_hyperparameters(ignore=['rngs'])\n",
    "        rngs = nnx.Rngs(0) if rngs is None else rngs\n",
    "        self.net = nnx.Sequential(\n",
    "            lambda x: x.reshape((x.shape[0], -1)),\n",
    "            nnx.Linear(784, num_hiddens, rngs=rngs), nnx.relu,\n",
    "            *[ResidualBlock(num_hiddens, rngs) for _ in range(num_blocks)],\n",
    "            nnx.Linear(num_hiddens, 10, rngs=rngs))\n",
    "\n",
    "trainer = d2l.Trainer(max_epochs=1, num_gpus=1)\n",
    "trainer.fit(ResMLPClassifier(), d2l.FashionMNIST(batch_size=256))"
   ],
   "execution_count": 20,
   "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.554688pt\" height=\"183.35625pt\" viewBox=\"0 0 240.554688 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-19T14:44:14.399575</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.554688 183.35625 \nL 240.554688 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 30.103125 145.8 \nL 225.403125 145.8 \nL 225.403125 7.2 \nL 30.103125 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=\"m56ebd837db\" d=\"M 0 0 \nL 0 3.5 \n\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </defs>\n      <g>\n       <use xlink:href=\"#m56ebd837db\" x=\"30.103125\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_1\">\n      <!-- 0.0 -->\n      <g transform=\"translate(22.151563 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        <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-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=\"xtick_2\">\n     <g id=\"line2d_2\">\n      <g>\n       <use xlink:href=\"#m56ebd837db\" x=\"69.163125\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_2\">\n      <!-- 0.2 -->\n      <g transform=\"translate(61.211563 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-30\"/>\n       <use xlink:href=\"#DejaVuSans-2e\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-32\" transform=\"translate(95.410156 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_3\">\n     <g id=\"line2d_3\">\n      <g>\n       <use xlink:href=\"#m56ebd837db\" x=\"108.223125\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_3\">\n      <!-- 0.4 -->\n      <g transform=\"translate(100.271563 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-30\"/>\n       <use xlink:href=\"#DejaVuSans-2e\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-34\" transform=\"translate(95.410156 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_4\">\n     <g id=\"line2d_4\">\n      <g>\n       <use xlink:href=\"#m56ebd837db\" x=\"147.283125\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_4\">\n      <!-- 0.6 -->\n      <g transform=\"translate(139.331563 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-30\"/>\n       <use xlink:href=\"#DejaVuSans-2e\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-36\" transform=\"translate(95.410156 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_5\">\n     <g id=\"line2d_5\">\n      <g>\n       <use xlink:href=\"#m56ebd837db\" x=\"186.343125\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_5\">\n      <!-- 0.8 -->\n      <g transform=\"translate(178.391563 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-30\"/>\n       <use xlink:href=\"#DejaVuSans-2e\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-38\" transform=\"translate(95.410156 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_6\">\n     <g id=\"line2d_6\">\n      <g>\n       <use xlink:href=\"#m56ebd837db\" x=\"225.403125\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_6\">\n      <!-- 1.0 -->\n      <g transform=\"translate(217.451563 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-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=\"text_7\">\n     <!-- epoch -->\n     <g transform=\"translate(112.525 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=\"m9205254e29\" d=\"M 0 0 \nL -3.5 0 \n\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </defs>\n      <g>\n       <use xlink:href=\"#m9205254e29\" x=\"30.103125\" y=\"125.452661\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_8\">\n      <!-- 0.6 -->\n      <g transform=\"translate(7.2 129.251879) 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-36\" transform=\"translate(95.410156 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_2\">\n     <g id=\"line2d_8\">\n      <g>\n       <use xlink:href=\"#m9205254e29\" x=\"30.103125\" y=\"81.973507\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_9\">\n      <!-- 0.7 -->\n      <g transform=\"translate(7.2 85.772726) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-37\" d=\"M 525 4666 \nL 3525 4666 \nL 3525 4397 \nL 1831 0 \nL 1172 0 \nL 2766 4134 \nL 525 4134 \nL 525 4666 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-30\"/>\n       <use xlink:href=\"#DejaVuSans-2e\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-37\" transform=\"translate(95.410156 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_3\">\n     <g id=\"line2d_9\">\n      <g>\n       <use xlink:href=\"#m9205254e29\" x=\"30.103125\" y=\"38.494353\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_10\">\n      <!-- 0.8 -->\n      <g transform=\"translate(7.2 42.293572) 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-38\" transform=\"translate(95.410156 0)\"/>\n      </g>\n     </g>\n    </g>\n   </g>\n   <g id=\"line2d_10\">\n    <path d=\"M 78.510817 13.5 \nL 176.160817 139.5 \n\" clip-path=\"url(#pcc058ca5a0)\" style=\"fill: none; stroke: #1f77b4; stroke-width: 1.5; stroke-linecap: square\"/>\n   </g>\n   <g id=\"line2d_11\">\n    <path d=\"M 225.403125 47.241136 \n\" clip-path=\"url(#pcc058ca5a0)\" style=\"fill: none; stroke-dasharray: 5.55,2.4; stroke-dashoffset: 0; stroke: #ff7f0e; stroke-width: 1.5\"/>\n   </g>\n   <g id=\"line2d_12\">\n    <path d=\"M 225.403125 118.989396 \n\" clip-path=\"url(#pcc058ca5a0)\" style=\"fill: none; stroke-dasharray: 9.6,2.4,1.5,2.4; stroke-dashoffset: 0; stroke: #2ca02c; stroke-width: 1.5\"/>\n   </g>\n   <g id=\"patch_3\">\n    <path d=\"M 30.103125 145.8 \nL 30.103125 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 225.403125 145.8 \nL 225.403125 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 30.103125 145.8 \nL 225.403125 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 30.103125 7.2 \nL 225.403125 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 138.8125 60.06875 \nL 218.403125 60.06875 \nQ 220.403125 60.06875 220.403125 58.06875 \nL 220.403125 14.2 \nQ 220.403125 12.2 218.403125 12.2 \nL 138.8125 12.2 \nQ 136.8125 12.2 136.8125 14.2 \nL 136.8125 58.06875 \nQ 136.8125 60.06875 138.8125 60.06875 \nz\n\" style=\"fill: #ffffff; opacity: 0.8; stroke: #cccccc; stroke-linejoin: miter\"/>\n    </g>\n    <g id=\"line2d_13\">\n     <path d=\"M 140.8125 20.298438 \nL 150.8125 20.298438 \nL 160.8125 20.298438 \n\" style=\"fill: none; stroke: #1f77b4; stroke-width: 1.5; stroke-linecap: square\"/>\n    </g>\n    <g id=\"text_11\">\n     <!-- train_loss -->\n     <g transform=\"translate(168.8125 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       <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      </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-6c\" transform=\"translate(282.763672 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6f\" transform=\"translate(310.546875 0)\"/>\n      <use xlink:href=\"#DejaVuSans-73\" transform=\"translate(371.728516 0)\"/>\n      <use xlink:href=\"#DejaVuSans-73\" transform=\"translate(423.828125 0)\"/>\n     </g>\n    </g>\n    <g id=\"line2d_14\">\n     <path d=\"M 140.8125 35.254688 \nL 150.8125 35.254688 \nL 160.8125 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_12\">\n     <!-- val_acc -->\n     <g transform=\"translate(168.8125 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-61\" transform=\"translate(198.242188 0)\"/>\n      <use xlink:href=\"#DejaVuSans-63\" transform=\"translate(259.521484 0)\"/>\n      <use xlink:href=\"#DejaVuSans-63\" transform=\"translate(314.501953 0)\"/>\n     </g>\n    </g>\n    <g id=\"line2d_15\">\n     <path d=\"M 140.8125 50.210938 \nL 150.8125 50.210938 \nL 160.8125 50.210938 \n\" style=\"fill: none; stroke-dasharray: 9.6,2.4,1.5,2.4; stroke-dashoffset: 0; stroke: #2ca02c; stroke-width: 1.5\"/>\n    </g>\n    <g id=\"text_13\">\n     <!-- val_loss -->\n     <g transform=\"translate(168.8125 53.710938) scale(0.1 -0.1)\">\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-6c\" transform=\"translate(198.242188 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6f\" transform=\"translate(226.025391 0)\"/>\n      <use xlink:href=\"#DejaVuSans-73\" transform=\"translate(287.207031 0)\"/>\n      <use xlink:href=\"#DejaVuSans-73\" transform=\"translate(339.306641 0)\"/>\n     </g>\n    </g>\n   </g>\n  </g>\n </g>\n <defs>\n  <clipPath id=\"pcc058ca5a0\">\n   <rect x=\"30.103125\" 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=gpus-devices-memory-md-40 fw=all -->\n",
    "\n",
    "## Summary"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-41 fw=jax -->\n",
    "\n",
    "Every array and every parameter lives on a device, and committed arrays\n",
    "combine only when co-located; copies between devices are explicit\n",
    "(`device_put`), slow relative to compute, and belong at the boundary of the\n",
    "training loop, not inside it. GPU memory during training holds four things:\n",
    "weights, gradients, optimizer state (fixed by the model and optimizer), and\n",
    "activations (scaling with batch size); `device.memory_stats()` tracks live\n",
    "buffers inside the block XLA preallocates, while `nvidia-smi` shows the whole\n",
    "block, so the two disagree by design. Activation checkpointing\n",
    "(`jax.checkpoint`) recomputes instead of stores, trading roughly a third more\n",
    "compute for activation memory. Dispatch is asynchronous on every backend:\n",
    "`.item()`, `np.asarray`, and `print` are synchronization points that stall\n",
    "the pipeline, and `block_until_ready()` is the explicit one that accurate\n",
    "timings need. The `Trainer` encodes the placement discipline: parameters\n",
    "created on the device once, batches moved per step, graceful CPU fallback\n",
    "when no GPU exists."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=gpus-devices-memory-md-42 fw=all -->\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. Using the accounting model of this section, predict the peak memory of the\n",
    "   four-plateau cell at batch sizes 64, 256, and 1024, then measure with\n",
    "   your framework's peak-memory counter. Where does the prediction break down,\n",
    "   and what did it omit?\n",
    "1. Increase the batch size in the checkpointing comparison until the\n",
    "   non-checkpointed run raises an out-of-memory error. How much further can\n",
    "   the checkpointed run go before it does too? Explain the ratio using the\n",
    "   sizes of what each variant stores.\n",
    "1. Time one epoch of the capstone training run with `print(loss.item())`\n",
    "   after every step, and again printing only once per epoch. Explain the\n",
    "   difference in terms of synchronization points.\n",
    "1. If you have two GPUs, time 1000 matrix products of two $4096 \\times 4096$\n",
    "   matrices executed on one GPU, then 500 on each of two GPUs issued from the\n",
    "   same loop. You should see almost linear scaling; explain why Python can\n",
    "   drive both cards at once. Guard the experiment with `num_gpus() >= 2`."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "name": "d2l-jax",
   "display_name": "d2l (JAX)",
   "language": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
