{
 "cells": [
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "---\n",
    "execute:\n",
    "  enabled: false\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=multi-gpu-practice-md-1 fw=all -->\n",
    "\n",
    "# Multi-GPU in Practice\n",
    "\n",
    "The hand-rolled loop of that section taught the mechanism and\n",
    "then lost the race: on a tiny model over a host-staged wire, the second\n",
    "GPU made things slower. Two things were wrong, and only one was the\n",
    "hardware. This section fixes the other — the *software* — by replacing our\n",
    "loop with the production machinery, and in doing so meets the chapter's\n",
    "sharpest framework contrast: PyTorch makes you launch processes and the\n",
    "collectives are explicit; JAX runs in one process and you merely *annotate\n",
    "the layout*, letting the compiler write the collectives for you. We\n",
    "measure real scaling on 2–4 GPUs, sketch how the same ideas shard a model\n",
    "too big to replicate (FSDP), and stop at the edge of the single node.\n",
    "\n",
    "*Prerequisites: the from-scratch data-parallel loop, the ring-allreduce\n",
    "identity, and the cost model of* that section*; the memory\n",
    "anatomy of* that section*. The multi-process idiom below\n",
    "was verified to run under this book's notebook build; why this box's\n",
    "fabric is slow is the topology story of* that section*,\n",
    "and what a collective costs on it is* that section*'s\n",
    "measurement.*"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "multi-gpu-practice-multi-gpu-in-practice"
   },
   "source": [
    "%matplotlib inline\n",
    "from d2l import torch as d2l\n",
    "import contextlib\n",
    "import io\n",
    "import json\n",
    "import os\n",
    "import pathlib\n",
    "import subprocess\n",
    "import sys\n",
    "import torch\n",
    "from torch import nn\n",
    "from torchvision import datasets\n",
    "\n",
    "torch.set_float32_matmul_precision('high')"
   ],
   "execution_count": 1,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=multi-gpu-practice-md-2 fw=all -->\n",
    "\n",
    "## What Our Hand-Rolled Loop Lacked\n",
    "\n",
    "Our that section implementation had three deficits, and modern\n",
    "data parallelism repairs each.\n",
    "\n",
    "* **No overlap.** Our loop finished the *entire* backward pass, then called\n",
    "  `allreduce`. But gradients become available layer by layer, back to\n",
    "  front, so the last layers' gradients could be communicated while the\n",
    "  earlier layers are still computing. Serializing compute-then-communicate\n",
    "  wastes exactly the time the fabric is idle during backward.\n",
    "* **One Python process.** A single interpreter drove all $k$ GPUs, so one\n",
    "  GIL-bound thread dispatched every kernel — the overhead regime of\n",
    "  that section, multiplied by $k$.\n",
    "* **A star topology.** Our `allreduce` funneled everything through device\n",
    "  0; that section showed the ring moves a constant per device\n",
    "  instead.\n",
    "\n",
    "PyTorch's `DistributedDataParallel` (DDP) fixes all three\n",
    "[@Li.Zhao.Varma.ea.2020]: one **process per GPU** (no shared GIL),\n",
    "NCCL's **ring/tree collectives** (no hub), and — the headline —\n",
    "gradient **bucketing that overlaps communication with the backward pass**\n",
    "(the figure). As each bucket of gradients fills, DDP kicks\n",
    "off its allreduce immediately, so by the time the backward pass reaches the\n",
    "first layer, the last layers' gradients are already summed. This is\n",
    "compute–communication overlap — independent work scheduled onto the fabric\n",
    "while the GPUs keep computing — finally shown where it pays.\n",
    "\n",
    "![What DDP buys over the hand-rolled loop: gradient bucketing lets each\n",
    "bucket's allreduce overlap the rest of the backward pass, instead of\n",
    "waiting for all of it.](../img/mdl-perf-ddp-overlap.svg)\n",
    "\n",
    "## DDP, Really Run\n",
    "\n",
    "DDP needs multiple processes, and a notebook is one process — so we launch\n",
    "the extra ones. The idiom, verified to work under this book's build: write\n",
    "the training script to a sidecar file, then launch it with `torchrun`,\n",
    "which spawns one process per GPU, sets up the rendezvous, and runs the\n",
    "script under `init_process_group`. Each rank writes its result to a scratch\n",
    "directory the notebook reads back (cleared before every launch, so a\n",
    "crashed run can never serve stale numbers). We keep the script minimal; the\n",
    "*loop body* is unchanged from single-GPU training, and the scaffolding\n",
    "around it is what the launcher's multi-process world requires:"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "multi-gpu-practice-ddp-really-run-1"
   },
   "source": [
    "\n",
    "def resnet18(num_classes, in_channels=1):\n",
    "    \"\"\"A slightly modified ResNet-18 model.\"\"\"\n",
    "    def resnet_block(in_channels, out_channels, num_residuals,\n",
    "                     first_block=False):\n",
    "        blk = []\n",
    "        for i in range(num_residuals):\n",
    "            if i == 0 and not first_block:\n",
    "                blk.append(d2l.Residual(out_channels, use_1x1conv=True, \n",
    "                                        strides=2))\n",
    "            else:\n",
    "                blk.append(d2l.Residual(out_channels))\n",
    "        return nn.Sequential(*blk)\n",
    "\n",
    "    # This model uses a smaller convolution kernel, stride, and padding and\n",
    "    # removes the max-pooling layer\n",
    "    net = nn.Sequential(\n",
    "        nn.Conv2d(in_channels, 64, kernel_size=3, stride=1, padding=1),\n",
    "        nn.BatchNorm2d(64),\n",
    "        nn.ReLU())\n",
    "    net.add_module(\"resnet_block1\", resnet_block(64, 64, 2, first_block=True))\n",
    "    net.add_module(\"resnet_block2\", resnet_block(64, 128, 2))\n",
    "    net.add_module(\"resnet_block3\", resnet_block(128, 256, 2))\n",
    "    net.add_module(\"resnet_block4\", resnet_block(256, 512, 2))\n",
    "    net.add_module(\"global_avg_pool\", nn.AdaptiveAvgPool2d((1,1)))\n",
    "    net.add_module(\"fc\", nn.Sequential(nn.Flatten(),\n",
    "                                       nn.Linear(512, num_classes)))\n",
    "    return net"
   ],
   "execution_count": 2,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=multi-gpu-practice-md-3 fw=all -->\n",
    "\n",
    "The DDP training script, written to disk from a cell. The two lines that\n",
    "make training data-parallel are `init_process_group(\"nccl\")` once per\n",
    "process and the `DDP(model)` wrap — after those, *the loop body is\n",
    "unchanged from single-GPU*. The rest is the launcher's housekeeping, shown\n",
    "in full so none of it is magic: a rank-local device, a\n",
    "`DistributedSampler` that hands each rank a disjoint shard of the data\n",
    "(re-shuffled per epoch by `set_epoch`), and process-group teardown. One\n",
    "practicality earns its own line: the parent notebook downloads\n",
    "Fashion-MNIST once, quietly, *before* any rank exists, so the ranks never\n",
    "race on the download:"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "multi-gpu-practice-ddp-really-run-2"
   },
   "source": [
    "with contextlib.redirect_stdout(io.StringIO()), \\\n",
    "     contextlib.redirect_stderr(io.StringIO()):     # download once, quietly\n",
    "    datasets.FashionMNIST('./data', train=True, download=True)\n",
    "\n",
    "DDP_SCRIPT = r'''\n",
    "import json, os, sys, time, torch\n",
    "from torch import nn\n",
    "import torch.distributed as dist\n",
    "from torch.nn.parallel import DistributedDataParallel as DDP\n",
    "from torchvision import datasets, transforms\n",
    "from d2l import torch as d2l\n",
    "\n",
    "rank = int(os.environ[\"LOCAL_RANK\"]); world = int(os.environ[\"WORLD_SIZE\"])\n",
    "torch.cuda.set_device(rank); dist.init_process_group(\"nccl\")\n",
    "torch.set_float32_matmul_precision(\"high\"); torch.backends.cudnn.benchmark = True\n",
    "\n",
    "model = d2l.resnet18(10, 1).to(rank)\n",
    "model(torch.zeros(1, 1, 64, 64, device=rank))     # materialize Lazy params\n",
    "model = DDP(model, device_ids=[rank])\n",
    "opt = torch.optim.SGD(model.parameters(), lr=0.1)\n",
    "loss = nn.CrossEntropyLoss()\n",
    "\n",
    "B = int(sys.argv[1]) if len(sys.argv) > 1 else 256   # per-rank batch size\n",
    "tf = transforms.Compose([transforms.Resize(64), transforms.ToTensor()])\n",
    "ds = datasets.FashionMNIST(\"./data\", train=True, transform=tf)\n",
    "sampler = torch.utils.data.distributed.DistributedSampler(ds, world, rank)\n",
    "loader = torch.utils.data.DataLoader(ds, B, sampler=sampler, num_workers=2)\n",
    "\n",
    "for epoch in range(2):                             # epoch 0 warms up\n",
    "    sampler.set_epoch(epoch); n = 0; torch.cuda.synchronize(); t0 = time.time()\n",
    "    for X, y in loader:\n",
    "        X, y = X.to(rank), y.to(rank)\n",
    "        opt.zero_grad(set_to_none=True)\n",
    "        loss(model(X), y).backward(); opt.step(); n += X.shape[0]\n",
    "    torch.cuda.synchronize(); dt = time.time() - t0\n",
    "here = os.path.dirname(os.path.abspath(__file__))\n",
    "with open(os.path.join(here, f\"rank{rank}.json\"), \"w\") as f:\n",
    "    json.dump({\"rank\": rank, \"samples_per_s\": n / dt}, f)\n",
    "dist.destroy_process_group()\n",
    "'''\n",
    "DDP_DIR = pathlib.Path('ddp_scratch')\n",
    "DDP_DIR.mkdir(exist_ok=True)\n",
    "_ = (DDP_DIR / 'train_ddp.py').write_text(DDP_SCRIPT)"
   ],
   "execution_count": 3,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=multi-gpu-practice-md-4 fw=all -->\n",
    "\n",
    "One word before the numbers, because every published speedup quietly picks\n",
    "a convention (that section). This sweep holds the\n",
    "*per-rank* batch fixed at 256, so the global batch grows to $256k$ —\n",
    "**weak scaling**: the efficiencies it prints are throughput per GPU\n",
    "relative to one GPU. Remember that a grown global batch also changes the\n",
    "optimization trajectory itself (that section); the\n",
    "strong-scaling question — same global batch, finishing sooner — comes\n",
    "right after."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "multi-gpu-practice-ddp-really-run-3"
   },
   "source": [
    "def ddp_throughput(k, batch_size=256):\n",
    "    \"\"\"Launch k-process DDP via torchrun; return aggregate samples/s.\"\"\"\n",
    "    for stale in DDP_DIR.glob('rank*.json'):   # a crashed run must not\n",
    "        stale.unlink()                         # serve old results\n",
    "    torchrun = str(pathlib.Path(sys.executable).parent / 'torchrun')\n",
    "    subprocess.run([torchrun, '--standalone', f'--nproc-per-node={k}',\n",
    "                    str(DDP_DIR / 'train_ddp.py'), str(batch_size)],\n",
    "                   check=True)\n",
    "    per_rank = []\n",
    "    for r in range(k):\n",
    "        with open(DDP_DIR / f'rank{r}.json') as f:\n",
    "            per_rank.append(json.load(f)['samples_per_s'])\n",
    "    return sum(per_rank)\n",
    "\n",
    "ks = [k for k in (1, 2, 4) if k <= d2l.num_gpus()]\n",
    "tput = [ddp_throughput(k) for k in ks]\n",
    "for k, t in zip(ks, tput):\n",
    "    print(f'{k} GPU(s): {t:.0f} samples/s, {t / tput[0]:.2f}x, '\n",
    "          f'{100 * t / tput[0] / k:.0f}% weak-scaling efficiency')\n",
    "d2l.plot(ks, [tput], 'GPUs', 'samples/s')"
   ],
   "execution_count": 4,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "1 GPU(s): 2107 samples/s, 1.00x, 100% weak-scaling efficiency\n2 GPU(s): 3714 samples/s, 1.76x, 88% weak-scaling efficiency\n4 GPU(s): 6924 samples/s, 3.29x, 82% weak-scaling efficiency\n"
     ]
    },
    {
     "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=\"255.828125pt\" height=\"183.35625pt\" viewBox=\"0 0 255.828125 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-21T00:37:51.249844</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 255.828125 183.35625 \nL 255.828125 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 53.328125 145.8 \nL 248.628125 145.8 \nL 248.628125 7.2 \nL 53.328125 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      <path d=\"M 62.205398 145.8 \nL 62.205398 7.2 \n\" clip-path=\"url(#pfc650e1d56)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_2\">\n      <defs>\n       <path id=\"m2f71ac3cb1\" d=\"M 0 0 \nL 0 3.5 \n\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </defs>\n      <g>\n       <use xlink:href=\"#m2f71ac3cb1\" x=\"62.205398\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_1\">\n      <!-- 1 -->\n      <g transform=\"translate(59.024148 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      </g>\n     </g>\n    </g>\n    <g id=\"xtick_2\">\n     <g id=\"line2d_3\">\n      <path d=\"M 121.387216 145.8 \nL 121.387216 7.2 \n\" clip-path=\"url(#pfc650e1d56)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_4\">\n      <g>\n       <use xlink:href=\"#m2f71ac3cb1\" x=\"121.387216\" 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(118.205966 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_5\">\n      <path d=\"M 180.569034 145.8 \nL 180.569034 7.2 \n\" clip-path=\"url(#pfc650e1d56)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_6\">\n      <g>\n       <use xlink:href=\"#m2f71ac3cb1\" x=\"180.569034\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_3\">\n      <!-- 3 -->\n      <g transform=\"translate(177.387784 160.398438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-33\" d=\"M 2597 2516 \nQ 3050 2419 3304 2112 \nQ 3559 1806 3559 1356 \nQ 3559 666 3084 287 \nQ 2609 -91 1734 -91 \nQ 1441 -91 1130 -33 \nQ 819 25 488 141 \nL 488 750 \nQ 750 597 1062 519 \nQ 1375 441 1716 441 \nQ 2309 441 2620 675 \nQ 2931 909 2931 1356 \nQ 2931 1769 2642 2001 \nQ 2353 2234 1838 2234 \nL 1294 2234 \nL 1294 2753 \nL 1863 2753 \nQ 2328 2753 2575 2939 \nQ 2822 3125 2822 3475 \nQ 2822 3834 2567 4026 \nQ 2313 4219 1838 4219 \nQ 1578 4219 1281 4162 \nQ 984 4106 628 3988 \nL 628 4550 \nQ 988 4650 1302 4700 \nQ 1616 4750 1894 4750 \nQ 2613 4750 3031 4423 \nQ 3450 4097 3450 3541 \nQ 3450 3153 3228 2886 \nQ 3006 2619 2597 2516 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-33\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_4\">\n     <g id=\"line2d_7\">\n      <path d=\"M 239.750852 145.8 \nL 239.750852 7.2 \n\" clip-path=\"url(#pfc650e1d56)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_8\">\n      <g>\n       <use xlink:href=\"#m2f71ac3cb1\" x=\"239.750852\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_4\">\n      <!-- 4 -->\n      <g transform=\"translate(236.569602 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=\"text_5\">\n     <!-- GPUs -->\n     <g transform=\"translate(137.825 174.076563) scale(0.1 -0.1)\">\n      <defs>\n       <path id=\"DejaVuSans-47\" d=\"M 3809 666 \nL 3809 1919 \nL 2778 1919 \nL 2778 2438 \nL 4434 2438 \nL 4434 434 \nQ 4069 175 3628 42 \nQ 3188 -91 2688 -91 \nQ 1594 -91 976 548 \nQ 359 1188 359 2328 \nQ 359 3472 976 4111 \nQ 1594 4750 2688 4750 \nQ 3144 4750 3555 4637 \nQ 3966 4525 4313 4306 \nL 4313 3634 \nQ 3963 3931 3569 4081 \nQ 3175 4231 2741 4231 \nQ 1884 4231 1454 3753 \nQ 1025 3275 1025 2328 \nQ 1025 1384 1454 906 \nQ 1884 428 2741 428 \nQ 3075 428 3337 486 \nQ 3600 544 3809 666 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-50\" d=\"M 1259 4147 \nL 1259 2394 \nL 2053 2394 \nQ 2494 2394 2734 2622 \nQ 2975 2850 2975 3272 \nQ 2975 3691 2734 3919 \nQ 2494 4147 2053 4147 \nL 1259 4147 \nz\nM 628 4666 \nL 2053 4666 \nQ 2838 4666 3239 4311 \nQ 3641 3956 3641 3272 \nQ 3641 2581 3239 2228 \nQ 2838 1875 2053 1875 \nL 1259 1875 \nL 1259 0 \nL 628 0 \nL 628 4666 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-55\" d=\"M 556 4666 \nL 1191 4666 \nL 1191 1831 \nQ 1191 1081 1462 751 \nQ 1734 422 2344 422 \nQ 2950 422 3222 751 \nQ 3494 1081 3494 1831 \nL 3494 4666 \nL 4128 4666 \nL 4128 1753 \nQ 4128 841 3676 375 \nQ 3225 -91 2344 -91 \nQ 1459 -91 1007 375 \nQ 556 841 556 1753 \nL 556 4666 \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-47\"/>\n      <use xlink:href=\"#DejaVuSans-50\" transform=\"translate(77.490234 0)\"/>\n      <use xlink:href=\"#DejaVuSans-55\" transform=\"translate(137.792969 0)\"/>\n      <use xlink:href=\"#DejaVuSans-73\" transform=\"translate(210.986328 0)\"/>\n     </g>\n    </g>\n   </g>\n   <g id=\"matplotlib.axis_2\">\n    <g id=\"ytick_1\">\n     <g id=\"line2d_9\">\n      <path d=\"M 53.328125 142.298083 \nL 248.628125 142.298083 \n\" clip-path=\"url(#pfc650e1d56)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_10\">\n      <defs>\n       <path id=\"m921cbe0d86\" d=\"M 0 0 \nL -3.5 0 \n\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </defs>\n      <g>\n       <use xlink:href=\"#m921cbe0d86\" x=\"53.328125\" y=\"142.298083\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_6\">\n      <!-- 2000 -->\n      <g transform=\"translate(20.878125 146.097302) 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-32\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(127.246094 0)\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(190.869141 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_2\">\n     <g id=\"line2d_11\">\n      <path d=\"M 53.328125 116.138548 \nL 248.628125 116.138548 \n\" clip-path=\"url(#pfc650e1d56)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_12\">\n      <g>\n       <use xlink:href=\"#m921cbe0d86\" x=\"53.328125\" y=\"116.138548\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_7\">\n      <!-- 3000 -->\n      <g transform=\"translate(20.878125 119.937766) scale(0.1 -0.1)\">\n       <use xlink:href=\"#DejaVuSans-33\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(127.246094 0)\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(190.869141 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_3\">\n     <g id=\"line2d_13\">\n      <path d=\"M 53.328125 89.979012 \nL 248.628125 89.979012 \n\" clip-path=\"url(#pfc650e1d56)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_14\">\n      <g>\n       <use xlink:href=\"#m921cbe0d86\" x=\"53.328125\" y=\"89.979012\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_8\">\n      <!-- 4000 -->\n      <g transform=\"translate(20.878125 93.778231) scale(0.1 -0.1)\">\n       <use xlink:href=\"#DejaVuSans-34\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(127.246094 0)\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(190.869141 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_4\">\n     <g id=\"line2d_15\">\n      <path d=\"M 53.328125 63.819477 \nL 248.628125 63.819477 \n\" clip-path=\"url(#pfc650e1d56)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_16\">\n      <g>\n       <use xlink:href=\"#m921cbe0d86\" x=\"53.328125\" y=\"63.819477\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_9\">\n      <!-- 5000 -->\n      <g transform=\"translate(20.878125 67.618696) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-35\" d=\"M 691 4666 \nL 3169 4666 \nL 3169 4134 \nL 1269 4134 \nL 1269 2991 \nQ 1406 3038 1543 3061 \nQ 1681 3084 1819 3084 \nQ 2600 3084 3056 2656 \nQ 3513 2228 3513 1497 \nQ 3513 744 3044 326 \nQ 2575 -91 1722 -91 \nQ 1428 -91 1123 -41 \nQ 819 9 494 109 \nL 494 744 \nQ 775 591 1075 516 \nQ 1375 441 1709 441 \nQ 2250 441 2565 725 \nQ 2881 1009 2881 1497 \nQ 2881 1984 2565 2268 \nQ 2250 2553 1709 2553 \nQ 1456 2553 1204 2497 \nQ 953 2441 691 2322 \nL 691 4666 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-35\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(127.246094 0)\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(190.869141 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_5\">\n     <g id=\"line2d_17\">\n      <path d=\"M 53.328125 37.659942 \nL 248.628125 37.659942 \n\" clip-path=\"url(#pfc650e1d56)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_18\">\n      <g>\n       <use xlink:href=\"#m921cbe0d86\" x=\"53.328125\" y=\"37.659942\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_10\">\n      <!-- 6000 -->\n      <g transform=\"translate(20.878125 41.45916) 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       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(127.246094 0)\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(190.869141 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_6\">\n     <g id=\"line2d_19\">\n      <path d=\"M 53.328125 11.500406 \nL 248.628125 11.500406 \n\" clip-path=\"url(#pfc650e1d56)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_20\">\n      <g>\n       <use xlink:href=\"#m921cbe0d86\" x=\"53.328125\" y=\"11.500406\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_11\">\n      <!-- 7000 -->\n      <g transform=\"translate(20.878125 15.299625) 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-37\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(127.246094 0)\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(190.869141 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"text_12\">\n     <!-- samples/s -->\n     <g transform=\"translate(14.798437 101.572656) rotate(-90) scale(0.1 -0.1)\">\n      <defs>\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-6d\" d=\"M 3328 2828 \nQ 3544 3216 3844 3400 \nQ 4144 3584 4550 3584 \nQ 5097 3584 5394 3201 \nQ 5691 2819 5691 2113 \nL 5691 0 \nL 5113 0 \nL 5113 2094 \nQ 5113 2597 4934 2840 \nQ 4756 3084 4391 3084 \nQ 3944 3084 3684 2787 \nQ 3425 2491 3425 1978 \nL 3425 0 \nL 2847 0 \nL 2847 2094 \nQ 2847 2600 2669 2842 \nQ 2491 3084 2119 3084 \nQ 1678 3084 1418 2786 \nQ 1159 2488 1159 1978 \nL 1159 0 \nL 581 0 \nL 581 3500 \nL 1159 3500 \nL 1159 2956 \nQ 1356 3278 1631 3431 \nQ 1906 3584 2284 3584 \nQ 2666 3584 2933 3390 \nQ 3200 3197 3328 2828 \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-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-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-2f\" d=\"M 1625 4666 \nL 2156 4666 \nL 531 -594 \nL 0 -594 \nL 1625 4666 \nz\n\" transform=\"scale(0.015625)\"/>\n      </defs>\n      <use xlink:href=\"#DejaVuSans-73\"/>\n      <use xlink:href=\"#DejaVuSans-61\" transform=\"translate(52.099609 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6d\" transform=\"translate(113.378906 0)\"/>\n      <use xlink:href=\"#DejaVuSans-70\" transform=\"translate(210.791016 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6c\" transform=\"translate(274.267578 0)\"/>\n      <use xlink:href=\"#DejaVuSans-65\" transform=\"translate(302.050781 0)\"/>\n      <use xlink:href=\"#DejaVuSans-73\" transform=\"translate(363.574219 0)\"/>\n      <use xlink:href=\"#DejaVuSans-2f\" transform=\"translate(415.673828 0)\"/>\n      <use xlink:href=\"#DejaVuSans-73\" transform=\"translate(449.365234 0)\"/>\n     </g>\n    </g>\n   </g>\n   <g id=\"line2d_21\">\n    <path d=\"M 62.205398 139.5 \nL 121.387216 97.464969 \nL 239.750852 13.5 \n\" clip-path=\"url(#pfc650e1d56)\" style=\"fill: none; stroke: #1f77b4; stroke-width: 1.5; stroke-linecap: square\"/>\n   </g>\n   <g id=\"patch_3\">\n    <path d=\"M 53.328125 145.8 \nL 53.328125 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 248.628125 145.8 \nL 248.628125 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 53.328125 145.8 \nL 248.628125 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 53.328125 7.2 \nL 248.628125 7.2 \n\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n   </g>\n  </g>\n </g>\n <defs>\n  <clipPath id=\"pfc650e1d56\">\n   <rect x=\"53.328125\" 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=multi-gpu-practice-md-5 fw=all -->\n",
    "\n",
    "On our four-GPU box, ResNet-18 on Fashion-MNIST-64 (11.2M parameters)\n",
    "scales the way the accounting of that section says a\n",
    "*compute-dense* model should: about 1.8× at two GPUs and about 3.3× at\n",
    "four — the cell prints 88% and 82% weak-scaling efficiency. The efficiency\n",
    "sags gently — no cliff — because each step's compute is large enough to\n",
    "hide most of the communication, unlike LeNet. Strong scaling asks a harder\n",
    "question of the same hardware: hold the global batch at 512 and split it\n",
    "ever thinner, so the per-rank batch shrinks as $512/k$ while the allreduce\n",
    "stays the same size:"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "multi-gpu-practice-ddp-really-run-4"
   },
   "source": [
    "tput_strong = [ddp_throughput(k, batch_size=512 // k) for k in ks]\n",
    "for k, t in zip(ks, tput_strong):\n",
    "    print(f'{k} GPU(s): {t:.0f} samples/s, {t / tput_strong[0]:.2f}x, '\n",
    "          f'{100 * t / tput_strong[0] / k:.0f}% strong-scaling efficiency')\n",
    "d2l.plot(ks, [tput, tput_strong], 'GPUs', 'samples/s',\n",
    "         legend=['weak (per-rank 256)', 'strong (global 512)'])"
   ],
   "execution_count": 5,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "1 GPU(s): 2092 samples/s, 1.00x, 100% strong-scaling efficiency\n2 GPU(s): 3717 samples/s, 1.78x, 89% strong-scaling efficiency\n4 GPU(s): 5885 samples/s, 2.81x, 70% strong-scaling efficiency\n"
     ]
    },
    {
     "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=\"255.828125pt\" height=\"183.35625pt\" viewBox=\"0 0 255.828125 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-21T00:41:17.889018</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 255.828125 183.35625 \nL 255.828125 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 53.328125 145.8 \nL 248.628125 145.8 \nL 248.628125 7.2 \nL 53.328125 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      <path d=\"M 62.205398 145.8 \nL 62.205398 7.2 \n\" clip-path=\"url(#p5e03b071d3)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_2\">\n      <defs>\n       <path id=\"ma3dac3f509\" d=\"M 0 0 \nL 0 3.5 \n\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </defs>\n      <g>\n       <use xlink:href=\"#ma3dac3f509\" x=\"62.205398\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_1\">\n      <!-- 1 -->\n      <g transform=\"translate(59.024148 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      </g>\n     </g>\n    </g>\n    <g id=\"xtick_2\">\n     <g id=\"line2d_3\">\n      <path d=\"M 121.387216 145.8 \nL 121.387216 7.2 \n\" clip-path=\"url(#p5e03b071d3)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_4\">\n      <g>\n       <use xlink:href=\"#ma3dac3f509\" x=\"121.387216\" 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(118.205966 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_5\">\n      <path d=\"M 180.569034 145.8 \nL 180.569034 7.2 \n\" clip-path=\"url(#p5e03b071d3)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_6\">\n      <g>\n       <use xlink:href=\"#ma3dac3f509\" x=\"180.569034\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_3\">\n      <!-- 3 -->\n      <g transform=\"translate(177.387784 160.398438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-33\" d=\"M 2597 2516 \nQ 3050 2419 3304 2112 \nQ 3559 1806 3559 1356 \nQ 3559 666 3084 287 \nQ 2609 -91 1734 -91 \nQ 1441 -91 1130 -33 \nQ 819 25 488 141 \nL 488 750 \nQ 750 597 1062 519 \nQ 1375 441 1716 441 \nQ 2309 441 2620 675 \nQ 2931 909 2931 1356 \nQ 2931 1769 2642 2001 \nQ 2353 2234 1838 2234 \nL 1294 2234 \nL 1294 2753 \nL 1863 2753 \nQ 2328 2753 2575 2939 \nQ 2822 3125 2822 3475 \nQ 2822 3834 2567 4026 \nQ 2313 4219 1838 4219 \nQ 1578 4219 1281 4162 \nQ 984 4106 628 3988 \nL 628 4550 \nQ 988 4650 1302 4700 \nQ 1616 4750 1894 4750 \nQ 2613 4750 3031 4423 \nQ 3450 4097 3450 3541 \nQ 3450 3153 3228 2886 \nQ 3006 2619 2597 2516 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-33\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_4\">\n     <g id=\"line2d_7\">\n      <path d=\"M 239.750852 145.8 \nL 239.750852 7.2 \n\" clip-path=\"url(#p5e03b071d3)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_8\">\n      <g>\n       <use xlink:href=\"#ma3dac3f509\" x=\"239.750852\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_4\">\n      <!-- 4 -->\n      <g transform=\"translate(236.569602 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=\"text_5\">\n     <!-- GPUs -->\n     <g transform=\"translate(137.825 174.076563) scale(0.1 -0.1)\">\n      <defs>\n       <path id=\"DejaVuSans-47\" d=\"M 3809 666 \nL 3809 1919 \nL 2778 1919 \nL 2778 2438 \nL 4434 2438 \nL 4434 434 \nQ 4069 175 3628 42 \nQ 3188 -91 2688 -91 \nQ 1594 -91 976 548 \nQ 359 1188 359 2328 \nQ 359 3472 976 4111 \nQ 1594 4750 2688 4750 \nQ 3144 4750 3555 4637 \nQ 3966 4525 4313 4306 \nL 4313 3634 \nQ 3963 3931 3569 4081 \nQ 3175 4231 2741 4231 \nQ 1884 4231 1454 3753 \nQ 1025 3275 1025 2328 \nQ 1025 1384 1454 906 \nQ 1884 428 2741 428 \nQ 3075 428 3337 486 \nQ 3600 544 3809 666 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-50\" d=\"M 1259 4147 \nL 1259 2394 \nL 2053 2394 \nQ 2494 2394 2734 2622 \nQ 2975 2850 2975 3272 \nQ 2975 3691 2734 3919 \nQ 2494 4147 2053 4147 \nL 1259 4147 \nz\nM 628 4666 \nL 2053 4666 \nQ 2838 4666 3239 4311 \nQ 3641 3956 3641 3272 \nQ 3641 2581 3239 2228 \nQ 2838 1875 2053 1875 \nL 1259 1875 \nL 1259 0 \nL 628 0 \nL 628 4666 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-55\" d=\"M 556 4666 \nL 1191 4666 \nL 1191 1831 \nQ 1191 1081 1462 751 \nQ 1734 422 2344 422 \nQ 2950 422 3222 751 \nQ 3494 1081 3494 1831 \nL 3494 4666 \nL 4128 4666 \nL 4128 1753 \nQ 4128 841 3676 375 \nQ 3225 -91 2344 -91 \nQ 1459 -91 1007 375 \nQ 556 841 556 1753 \nL 556 4666 \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-47\"/>\n      <use xlink:href=\"#DejaVuSans-50\" transform=\"translate(77.490234 0)\"/>\n      <use xlink:href=\"#DejaVuSans-55\" transform=\"translate(137.792969 0)\"/>\n      <use xlink:href=\"#DejaVuSans-73\" transform=\"translate(210.986328 0)\"/>\n     </g>\n    </g>\n   </g>\n   <g id=\"matplotlib.axis_2\">\n    <g id=\"ytick_1\">\n     <g id=\"line2d_9\">\n      <path d=\"M 53.328125 141.900765 \nL 248.628125 141.900765 \n\" clip-path=\"url(#p5e03b071d3)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_10\">\n      <defs>\n       <path id=\"m441511331d\" d=\"M 0 0 \nL -3.5 0 \n\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </defs>\n      <g>\n       <use xlink:href=\"#m441511331d\" x=\"53.328125\" y=\"141.900765\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_6\">\n      <!-- 2000 -->\n      <g transform=\"translate(20.878125 145.699983) 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-32\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(127.246094 0)\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(190.869141 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_2\">\n     <g id=\"line2d_11\">\n      <path d=\"M 53.328125 115.821927 \nL 248.628125 115.821927 \n\" clip-path=\"url(#p5e03b071d3)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_12\">\n      <g>\n       <use xlink:href=\"#m441511331d\" x=\"53.328125\" y=\"115.821927\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_7\">\n      <!-- 3000 -->\n      <g transform=\"translate(20.878125 119.621145) scale(0.1 -0.1)\">\n       <use xlink:href=\"#DejaVuSans-33\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(127.246094 0)\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(190.869141 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_3\">\n     <g id=\"line2d_13\">\n      <path d=\"M 53.328125 89.743089 \nL 248.628125 89.743089 \n\" clip-path=\"url(#p5e03b071d3)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_14\">\n      <g>\n       <use xlink:href=\"#m441511331d\" x=\"53.328125\" y=\"89.743089\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_8\">\n      <!-- 4000 -->\n      <g transform=\"translate(20.878125 93.542307) scale(0.1 -0.1)\">\n       <use xlink:href=\"#DejaVuSans-34\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(127.246094 0)\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(190.869141 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_4\">\n     <g id=\"line2d_15\">\n      <path d=\"M 53.328125 63.664251 \nL 248.628125 63.664251 \n\" clip-path=\"url(#p5e03b071d3)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_16\">\n      <g>\n       <use xlink:href=\"#m441511331d\" x=\"53.328125\" y=\"63.664251\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_9\">\n      <!-- 5000 -->\n      <g transform=\"translate(20.878125 67.463469) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-35\" d=\"M 691 4666 \nL 3169 4666 \nL 3169 4134 \nL 1269 4134 \nL 1269 2991 \nQ 1406 3038 1543 3061 \nQ 1681 3084 1819 3084 \nQ 2600 3084 3056 2656 \nQ 3513 2228 3513 1497 \nQ 3513 744 3044 326 \nQ 2575 -91 1722 -91 \nQ 1428 -91 1123 -41 \nQ 819 9 494 109 \nL 494 744 \nQ 775 591 1075 516 \nQ 1375 441 1709 441 \nQ 2250 441 2565 725 \nQ 2881 1009 2881 1497 \nQ 2881 1984 2565 2268 \nQ 2250 2553 1709 2553 \nQ 1456 2553 1204 2497 \nQ 953 2441 691 2322 \nL 691 4666 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-35\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(127.246094 0)\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(190.869141 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_5\">\n     <g id=\"line2d_17\">\n      <path d=\"M 53.328125 37.585413 \nL 248.628125 37.585413 \n\" clip-path=\"url(#p5e03b071d3)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_18\">\n      <g>\n       <use xlink:href=\"#m441511331d\" x=\"53.328125\" y=\"37.585413\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_10\">\n      <!-- 6000 -->\n      <g transform=\"translate(20.878125 41.384631) 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       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(127.246094 0)\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(190.869141 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_6\">\n     <g id=\"line2d_19\">\n      <path d=\"M 53.328125 11.506575 \nL 248.628125 11.506575 \n\" clip-path=\"url(#p5e03b071d3)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_20\">\n      <g>\n       <use xlink:href=\"#m441511331d\" x=\"53.328125\" y=\"11.506575\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_11\">\n      <!-- 7000 -->\n      <g transform=\"translate(20.878125 15.305793) 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-37\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(127.246094 0)\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(190.869141 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"text_12\">\n     <!-- samples/s -->\n     <g transform=\"translate(14.798437 101.572656) rotate(-90) scale(0.1 -0.1)\">\n      <defs>\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-6d\" d=\"M 3328 2828 \nQ 3544 3216 3844 3400 \nQ 4144 3584 4550 3584 \nQ 5097 3584 5394 3201 \nQ 5691 2819 5691 2113 \nL 5691 0 \nL 5113 0 \nL 5113 2094 \nQ 5113 2597 4934 2840 \nQ 4756 3084 4391 3084 \nQ 3944 3084 3684 2787 \nQ 3425 2491 3425 1978 \nL 3425 0 \nL 2847 0 \nL 2847 2094 \nQ 2847 2600 2669 2842 \nQ 2491 3084 2119 3084 \nQ 1678 3084 1418 2786 \nQ 1159 2488 1159 1978 \nL 1159 0 \nL 581 0 \nL 581 3500 \nL 1159 3500 \nL 1159 2956 \nQ 1356 3278 1631 3431 \nQ 1906 3584 2284 3584 \nQ 2666 3584 2933 3390 \nQ 3200 3197 3328 2828 \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-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-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-2f\" d=\"M 1625 4666 \nL 2156 4666 \nL 531 -594 \nL 0 -594 \nL 1625 4666 \nz\n\" transform=\"scale(0.015625)\"/>\n      </defs>\n      <use xlink:href=\"#DejaVuSans-73\"/>\n      <use xlink:href=\"#DejaVuSans-61\" transform=\"translate(52.099609 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6d\" transform=\"translate(113.378906 0)\"/>\n      <use xlink:href=\"#DejaVuSans-70\" transform=\"translate(210.791016 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6c\" transform=\"translate(274.267578 0)\"/>\n      <use xlink:href=\"#DejaVuSans-65\" transform=\"translate(302.050781 0)\"/>\n      <use xlink:href=\"#DejaVuSans-73\" transform=\"translate(363.574219 0)\"/>\n      <use xlink:href=\"#DejaVuSans-2f\" transform=\"translate(415.673828 0)\"/>\n      <use xlink:href=\"#DejaVuSans-73\" transform=\"translate(449.365234 0)\"/>\n     </g>\n    </g>\n   </g>\n   <g id=\"line2d_21\">\n    <path d=\"M 62.205398 139.111313 \nL 121.387216 97.205953 \nL 239.750852 13.5 \n\" clip-path=\"url(#p5e03b071d3)\" style=\"fill: none; stroke: #1f77b4; stroke-width: 1.5; stroke-linecap: square\"/>\n   </g>\n   <g id=\"line2d_22\">\n    <path d=\"M 62.205398 139.5 \nL 121.387216 97.130138 \nL 239.750852 40.589751 \n\" clip-path=\"url(#p5e03b071d3)\" style=\"fill: none; stroke-dasharray: 5.55,2.4; stroke-dashoffset: 0; stroke: #bf00bf; stroke-width: 1.5\"/>\n   </g>\n   <g id=\"patch_3\">\n    <path d=\"M 53.328125 145.8 \nL 53.328125 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 248.628125 145.8 \nL 248.628125 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 53.328125 145.8 \nL 248.628125 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 53.328125 7.2 \nL 248.628125 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 60.328125 44.55625 \nL 193.775 44.55625 \nQ 195.775 44.55625 195.775 42.55625 \nL 195.775 14.2 \nQ 195.775 12.2 193.775 12.2 \nL 60.328125 12.2 \nQ 58.328125 12.2 58.328125 14.2 \nL 58.328125 42.55625 \nQ 58.328125 44.55625 60.328125 44.55625 \nz\n\" style=\"fill: #ffffff; opacity: 0.8; stroke: #cccccc; stroke-linejoin: miter\"/>\n    </g>\n    <g id=\"line2d_23\">\n     <path d=\"M 62.328125 20.298438 \nL 72.328125 20.298438 \nL 82.328125 20.298438 \n\" style=\"fill: none; stroke: #1f77b4; stroke-width: 1.5; stroke-linecap: square\"/>\n    </g>\n    <g id=\"text_13\">\n     <!-- weak (per-rank 256) -->\n     <g transform=\"translate(90.328125 23.798438) scale(0.1 -0.1)\">\n      <defs>\n       <path id=\"DejaVuSans-77\" d=\"M 269 3500 \nL 844 3500 \nL 1563 769 \nL 2278 3500 \nL 2956 3500 \nL 3675 769 \nL 4391 3500 \nL 4966 3500 \nL 4050 0 \nL 3372 0 \nL 2619 2869 \nL 1863 0 \nL 1184 0 \nL 269 3500 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-6b\" d=\"M 581 4863 \nL 1159 4863 \nL 1159 1991 \nL 2875 3500 \nL 3609 3500 \nL 1753 1863 \nL 3688 0 \nL 2938 0 \nL 1159 1709 \nL 1159 0 \nL 581 0 \nL 581 4863 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-20\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-28\" d=\"M 1984 4856 \nQ 1566 4138 1362 3434 \nQ 1159 2731 1159 2009 \nQ 1159 1288 1364 580 \nQ 1569 -128 1984 -844 \nL 1484 -844 \nQ 1016 -109 783 600 \nQ 550 1309 550 2009 \nQ 550 2706 781 3412 \nQ 1013 4119 1484 4856 \nL 1984 4856 \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-2d\" d=\"M 313 2009 \nL 1997 2009 \nL 1997 1497 \nL 313 1497 \nL 313 2009 \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-29\" d=\"M 513 4856 \nL 1013 4856 \nQ 1481 4119 1714 3412 \nQ 1947 2706 1947 2009 \nQ 1947 1309 1714 600 \nQ 1481 -109 1013 -844 \nL 513 -844 \nQ 928 -128 1133 580 \nQ 1338 1288 1338 2009 \nQ 1338 2731 1133 3434 \nQ 928 4138 513 4856 \nz\n\" transform=\"scale(0.015625)\"/>\n      </defs>\n      <use xlink:href=\"#DejaVuSans-77\"/>\n      <use xlink:href=\"#DejaVuSans-65\" transform=\"translate(81.787109 0)\"/>\n      <use xlink:href=\"#DejaVuSans-61\" transform=\"translate(143.310547 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6b\" transform=\"translate(204.589844 0)\"/>\n      <use xlink:href=\"#DejaVuSans-20\" transform=\"translate(262.5 0)\"/>\n      <use xlink:href=\"#DejaVuSans-28\" transform=\"translate(294.287109 0)\"/>\n      <use xlink:href=\"#DejaVuSans-70\" transform=\"translate(333.300781 0)\"/>\n      <use xlink:href=\"#DejaVuSans-65\" transform=\"translate(396.777344 0)\"/>\n      <use xlink:href=\"#DejaVuSans-72\" transform=\"translate(458.300781 0)\"/>\n      <use xlink:href=\"#DejaVuSans-2d\" transform=\"translate(493.039062 0)\"/>\n      <use xlink:href=\"#DejaVuSans-72\" transform=\"translate(529.123047 0)\"/>\n      <use xlink:href=\"#DejaVuSans-61\" transform=\"translate(570.236328 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6e\" transform=\"translate(631.515625 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6b\" transform=\"translate(694.894531 0)\"/>\n      <use xlink:href=\"#DejaVuSans-20\" transform=\"translate(752.804688 0)\"/>\n      <use xlink:href=\"#DejaVuSans-32\" transform=\"translate(784.591797 0)\"/>\n      <use xlink:href=\"#DejaVuSans-35\" transform=\"translate(848.214844 0)\"/>\n      <use xlink:href=\"#DejaVuSans-36\" transform=\"translate(911.837891 0)\"/>\n      <use xlink:href=\"#DejaVuSans-29\" transform=\"translate(975.460938 0)\"/>\n     </g>\n    </g>\n    <g id=\"line2d_24\">\n     <path d=\"M 62.328125 34.976562 \nL 72.328125 34.976562 \nL 82.328125 34.976562 \n\" style=\"fill: none; stroke-dasharray: 5.55,2.4; stroke-dashoffset: 0; stroke: #bf00bf; stroke-width: 1.5\"/>\n    </g>\n    <g id=\"text_14\">\n     <!-- strong (global 512) -->\n     <g transform=\"translate(90.328125 38.476562) 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-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-67\" d=\"M 2906 1791 \nQ 2906 2416 2648 2759 \nQ 2391 3103 1925 3103 \nQ 1463 3103 1205 2759 \nQ 947 2416 947 1791 \nQ 947 1169 1205 825 \nQ 1463 481 1925 481 \nQ 2391 481 2648 825 \nQ 2906 1169 2906 1791 \nz\nM 3481 434 \nQ 3481 -459 3084 -895 \nQ 2688 -1331 1869 -1331 \nQ 1566 -1331 1297 -1286 \nQ 1028 -1241 775 -1147 \nL 775 -588 \nQ 1028 -725 1275 -790 \nQ 1522 -856 1778 -856 \nQ 2344 -856 2625 -561 \nQ 2906 -266 2906 331 \nL 2906 616 \nQ 2728 306 2450 153 \nQ 2172 0 1784 0 \nQ 1141 0 747 490 \nQ 353 981 353 1791 \nQ 353 2603 747 3093 \nQ 1141 3584 1784 3584 \nQ 2172 3584 2450 3431 \nQ 2728 3278 2906 2969 \nL 2906 3500 \nL 3481 3500 \nL 3481 434 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-62\" d=\"M 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\nM 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 \nL 1159 0 \nL 581 0 \nL 581 4863 \nL 1159 4863 \nL 1159 2969 \nz\n\" transform=\"scale(0.015625)\"/>\n      </defs>\n      <use xlink:href=\"#DejaVuSans-73\"/>\n      <use xlink:href=\"#DejaVuSans-74\" transform=\"translate(52.099609 0)\"/>\n      <use xlink:href=\"#DejaVuSans-72\" transform=\"translate(91.308594 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6f\" transform=\"translate(130.171875 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6e\" transform=\"translate(191.353516 0)\"/>\n      <use xlink:href=\"#DejaVuSans-67\" transform=\"translate(254.732422 0)\"/>\n      <use xlink:href=\"#DejaVuSans-20\" transform=\"translate(318.208984 0)\"/>\n      <use xlink:href=\"#DejaVuSans-28\" transform=\"translate(349.996094 0)\"/>\n      <use xlink:href=\"#DejaVuSans-67\" transform=\"translate(389.009766 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6c\" transform=\"translate(452.486328 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6f\" transform=\"translate(480.269531 0)\"/>\n      <use xlink:href=\"#DejaVuSans-62\" transform=\"translate(541.451172 0)\"/>\n      <use xlink:href=\"#DejaVuSans-61\" transform=\"translate(604.927734 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6c\" transform=\"translate(666.207031 0)\"/>\n      <use xlink:href=\"#DejaVuSans-20\" transform=\"translate(693.990234 0)\"/>\n      <use xlink:href=\"#DejaVuSans-35\" transform=\"translate(725.777344 0)\"/>\n      <use xlink:href=\"#DejaVuSans-31\" transform=\"translate(789.400391 0)\"/>\n      <use xlink:href=\"#DejaVuSans-32\" transform=\"translate(853.023438 0)\"/>\n      <use xlink:href=\"#DejaVuSans-29\" transform=\"translate(916.646484 0)\"/>\n     </g>\n    </g>\n   </g>\n  </g>\n </g>\n <defs>\n  <clipPath id=\"p5e03b071d3\">\n   <rect x=\"53.328125\" 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=multi-gpu-practice-md-6 fw=all -->\n",
    "\n",
    "At two GPUs the two conventions nearly coincide on this model — a 4090 is\n",
    "about equally saturated by a per-rank batch of 256 or 512, so the $k=1$\n",
    "baselines barely differ — but they part company as $k$ grows: by $k=4$ the\n",
    "strong-scaling run gives each GPU only 128 examples per step, and any gap\n",
    "that opens between the strong and weak efficiencies is pure\n",
    "underutilization, the mechanism that sank LeNet, now in miniature. That is\n",
    "the equation read twice: weak scaling holds $t_{\\text{compute}}$\n",
    "per device constant and asks the fabric to keep up; strong scaling shrinks\n",
    "$t_{\\text{compute}}(B/k)$ toward the fixed $t_{\\text{comm}}$ floor.\n",
    "\n",
    "Now confront the sweep with the cost model by measurement rather than by\n",
    "assertion. the equation prices a step's communication at\n",
    "$2N/\\beta$, and DDP itself provides the instrument to check it:\n",
    "`no_sync()` runs backward with gradient synchronization turned off, so the\n",
    "difference between synced and unsynced step times estimates what\n",
    "communication really costs — an estimate, not a truth, since turning sync\n",
    "off also changes what overlaps what:"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "multi-gpu-practice-ddp-really-run-5"
   },
   "source": [
    "COMM_SCRIPT = r'''\n",
    "import contextlib, json, os, time, torch\n",
    "from torch import nn\n",
    "import torch.distributed as dist\n",
    "from torch.nn.parallel import DistributedDataParallel as DDP\n",
    "from d2l import torch as d2l\n",
    "\n",
    "rank = int(os.environ[\"LOCAL_RANK\"])\n",
    "torch.cuda.set_device(rank)\n",
    "dist.init_process_group(\"nccl\", device_id=torch.device(\"cuda\", rank))\n",
    "torch.set_float32_matmul_precision(\"high\"); torch.backends.cudnn.benchmark = True\n",
    "\n",
    "model = d2l.resnet18(10, 1).to(rank)\n",
    "model(torch.zeros(1, 1, 64, 64, device=rank))\n",
    "model = DDP(model, device_ids=[rank])\n",
    "loss = nn.CrossEntropyLoss()\n",
    "X = torch.randn(256, 1, 64, 64, device=rank)\n",
    "y = torch.randint(0, 10, (256,), device=rank)\n",
    "\n",
    "def fwd_bwd():\n",
    "    model.zero_grad(set_to_none=True)\n",
    "    loss(model(X), y).backward()\n",
    "\n",
    "def step_time(sync_grads, steps=30):\n",
    "    ctx = contextlib.nullcontext if sync_grads else model.no_sync\n",
    "    for _ in range(10):                            # warmup\n",
    "        with ctx(): fwd_bwd()\n",
    "    torch.cuda.synchronize(); dist.barrier(); t0 = time.time()\n",
    "    for _ in range(steps):\n",
    "        with ctx(): fwd_bwd()\n",
    "    torch.cuda.synchronize()\n",
    "    return (time.time() - t0) / steps\n",
    "\n",
    "synced, silent = step_time(True), step_time(False)\n",
    "if rank == 0:\n",
    "    here = os.path.dirname(os.path.abspath(__file__))\n",
    "    with open(os.path.join(here, \"comm.json\"), \"w\") as f:\n",
    "        json.dump({\"synced_ms\": 1e3 * synced, \"no_sync_ms\": 1e3 * silent}, f)\n",
    "dist.destroy_process_group()\n",
    "'''\n",
    "_ = (DDP_DIR / 'comm_probe.py').write_text(COMM_SCRIPT)\n",
    "\n",
    "net = resnet18(10, 1)                     # the gradient bytes, N\n",
    "net(torch.zeros(1, 1, 64, 64))            # materialize Lazy params\n",
    "n_bytes = 4 * sum(p.numel() for p in net.parameters())\n",
    "beta = 4.5e9   # NCCL allreduce, effective bytes/device/s on this box (13.5)\n",
    "if d2l.num_gpus() >= 2:\n",
    "    torchrun = str(pathlib.Path(sys.executable).parent / 'torchrun')\n",
    "    subprocess.run([torchrun, '--standalone', '--nproc-per-node=2',\n",
    "                    str(DDP_DIR / 'comm_probe.py')], check=True)\n",
    "    with open(DDP_DIR / 'comm.json') as f:\n",
    "        comm = json.load(f)\n",
    "    print(f\"k=2: predicted comm 2N/beta = {2 * n_bytes / beta * 1e3:.0f} \"\n",
    "          f\"ms/step; measured {comm['synced_ms'] - comm['no_sync_ms']:.0f} ms \"\n",
    "          f\"(synced {comm['synced_ms']:.0f}, no_sync {comm['no_sync_ms']:.0f})\")"
   ],
   "execution_count": 6,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "k=2: predicted comm 2N/beta = 20 ms/step; measured 15 ms (synced 132, no_sync 117)\n"
     ]
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=multi-gpu-practice-md-7 fw=all -->\n",
    "\n",
    "Prediction and measurement land within tens of percent of each other, and\n",
    "**that agreement is the result**: a scaling curve you can price before you\n",
    "buy, not a marketing \"N× faster\" claim — and it holds at two GPUs as\n",
    "clearly as at four. One line on what a datacenter box changes: an NVLink\n",
    "fabric shrinks $t_{\\text{comm}}$ by roughly two orders of magnitude\n",
    "(the table), so the same accounting predicts near-linear\n",
    "scaling — same model, different constant. (The legacy `nn.DataParallel` is\n",
    "single-process and GIL-bound; use DDP even on one node, as PyTorch's own\n",
    "docs advise.)\n",
    "\n",
    "One loose end from that section deserves to be closed by\n",
    "measurement rather than left as an assertion. The diagnosis there was\n",
    "that NCCL's P2P-less fallback moves bytes with a latency-bound GPU-kernel\n",
    "copy — in effect a performance bug in how the library's default transport\n",
    "interacts with this particular platform — and that one documented switch,\n",
    "`NCCL_SHM_USE_CUDA_MEMCPY=1`, re-routes the same transfer over the DMA\n",
    "copy engines. Measure the bare collective both ways:"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "multi-gpu-practice-ddp-really-run-6"
   },
   "source": [
    "BENCH_SCRIPT = r'''\n",
    "import json, os, time, torch\n",
    "import torch.distributed as dist\n",
    "\n",
    "rank = int(os.environ[\"LOCAL_RANK\"])\n",
    "torch.cuda.set_device(rank)\n",
    "dist.init_process_group(\"nccl\", device_id=torch.device(\"cuda\", rank))\n",
    "x = torch.randn(16 * 1024 * 1024, device=rank)     # 64 MB of fp32\n",
    "for _ in range(5):                                 # warmup\n",
    "    dist.all_reduce(x)\n",
    "torch.cuda.synchronize(); t0 = time.time()\n",
    "for _ in range(15):\n",
    "    dist.all_reduce(x)\n",
    "torch.cuda.synchronize(); dt = (time.time() - t0) / 15\n",
    "if rank == 0:\n",
    "    here = os.path.dirname(os.path.abspath(__file__))\n",
    "    with open(os.path.join(here, \"bench.json\"), \"w\") as f:\n",
    "        json.dump({\"gbs\": 2 * x.numel() * 4 / dt / 1e9}, f)\n",
    "dist.destroy_process_group()\n",
    "'''\n",
    "_ = (DDP_DIR / 'allreduce_bench.py').write_text(BENCH_SCRIPT)\n",
    "\n",
    "def bare_allreduce_gbs(**env):\n",
    "    (DDP_DIR / 'bench.json').unlink(missing_ok=True)\n",
    "    torchrun = str(pathlib.Path(sys.executable).parent / 'torchrun')\n",
    "    subprocess.run([torchrun, '--standalone', '--nproc-per-node=2',\n",
    "                    str(DDP_DIR / 'allreduce_bench.py')],\n",
    "                   check=True, env={**os.environ, **env})\n",
    "    with open(DDP_DIR / 'bench.json') as f:\n",
    "        return json.load(f)['gbs']\n",
    "\n",
    "if d2l.num_gpus() >= 2:\n",
    "    slow = bare_allreduce_gbs()\n",
    "    # Works around an NCCL transport bottleneck on this P2P-less box\n",
    "    # (13.5's diagnosis) -- a platform-specific fix; validate on yours.\n",
    "    fast = bare_allreduce_gbs(NCCL_SHM_USE_CUDA_MEMCPY='1')\n",
    "    print(f'bare allreduce, effective bytes/device/s: '\n",
    "          f'{slow:.1f} GB/s at the default, {fast:.1f} GB/s configured '\n",
    "          f'({fast / slow:.1f}x)')"
   ],
   "execution_count": 7,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "bare allreduce, effective bytes/device/s: 4.4 GB/s at the default, 22.3 GB/s configured (5.1x)\n"
     ]
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=multi-gpu-practice-md-8 fw=all -->\n",
    "\n",
    "Roughly five-fold, from configuration alone. First the general lesson: a\n",
    "collective library's configuration — which transport it picks, what\n",
    "topology it assumes — can move communication performance by *factors*,\n",
    "not percent, so measure yours against what the wire demonstrably carries\n",
    "(that section's raw copy) before trusting it. Then the\n",
    "specific one, which is why every training run above still uses the\n",
    "library's defaults: this workaround wins the microbenchmark and loses\n",
    "the workload. On our box, with this NCCL build, the copy-engine mode\n",
    "deadlocks DDP's overlapped training path within seconds — the very\n",
    "collectives that just ran flawlessly in isolation wedge inside the\n",
    "training loop — so adopting it here would trade a five-fold bandwidth\n",
    "win for a hung notebook. An escape hatch is platform-specific twice over:\n",
    "whether you need it, and whether it survives your workload, are both\n",
    "measurements (the exercises have you reproduce both halves). The cost\n",
    "model is indifferent either way — the equation simply takes\n",
    "whatever $\\beta$ your fabric, as configured, sustains.\n",
    "\n",
    "## Sharding the Redundant: the FSDP Idea\n",
    "\n",
    "DDP replicates *everything* on every rank: $k$ identical copies of the\n",
    "parameters, the gradients, and the optimizer states. For the $16P$-byte\n",
    "training footprint of that section, that is $k-1$ copies\n",
    "of everything, wasted — and it caps the model size at what one GPU holds,\n",
    "the limitation that section flagged. **Fully Sharded Data\n",
    "Parallel** (FSDP) removes the redundancy by *sharding* those tensors across\n",
    "ranks, each rank owning $1/k$ of each, and materializing a full layer only\n",
    "for the moment it is needed [@Zhao.Gu.Varma.ea.2023]. The idea is the\n",
    "ZeRO ladder [@Rajbhandari.Rasley.Ruwase.ea.2020]: shard the\n",
    "optimizer states first (they are the biggest, $8P$), then the gradients,\n",
    "then the parameters — each rung cutting memory toward $1/k$ at the cost of\n",
    "more communication.\n",
    "\n",
    "The mechanism is the that section identity, cashed in. Recall\n",
    "that allreduce = reduce-scatter + all-gather. FSDP simply *keeps the two\n",
    "halves separate*: an **all-gather** reconstructs a layer's full parameters\n",
    "just before it computes, and frees them just after; a **reduce-scatter**\n",
    "sums each layer's gradients but leaves each rank holding only its own\n",
    "shard (the figure). No tensor's full replica ever lives\n",
    "longer than the layer that needs it.\n",
    "\n",
    "![The FSDP lifecycle of one block, under one simplified\n",
    "reshard-after-forward policy: parameters live sharded ($P/k$ per rank); an\n",
    "all-gather materializes the full block only while it computes, then frees\n",
    "it; a reduce-scatter leaves each rank with its gradient\n",
    "shard.](../img/mdl-perf-fsdp-lifecycle.svg)\n",
    "\n",
    "That completes the small family of collectives this chapter needs — worth\n",
    "one table, since the rest of the book will name them without ceremony:\n",
    "\n",
    "| collective | what every rank ends with | where it appears |\n",
    "|---|---|---|\n",
    "| allreduce | the full sum | DDP's gradient buckets; that section |\n",
    "| reduce-scatter | one shard of the sum | FSDP gradients |\n",
    "| all-gather | every shard, concatenated | FSDP parameters, just-in-time |\n",
    "| all-to-all | a different shard from each peer | expert parallelism (that section) |\n",
    "\n",
    "FSDP's payoff — fitting a model that does not fit — is invisible on our\n",
    "11.2M-parameter demo, which occupies a few hundred MB of a 24 GB card, so\n",
    "we show the *shape* of the code rather than run it. The modern API is\n",
    "`fully_shard` over a `DeviceMesh`; the original `FullyShardedDataParallel`\n",
    "wrapper class still imports at our pin, but it is the deprecated legacy\n",
    "path:"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "multi-gpu-practice-sharding-the-redundant-the-fsdp-idea"
   },
   "source": [
    "# Code sketch (not executed): shard each block, then the whole model.\n",
    "# from torch.distributed.fsdp import fully_shard\n",
    "# from torch.distributed.device_mesh import init_device_mesh\n",
    "# mesh = init_device_mesh(\"cuda\", (world_size,))\n",
    "# model = build_large_model()\n",
    "# for block in model.transformer_blocks:   # shard per repeated block\n",
    "#     fully_shard(block, mesh=mesh)\n",
    "# fully_shard(model, mesh=mesh)            # shard the remainder\n",
    "print('FSDP sketch: reach for it past a few billion parameters, '\n",
    "      'not on an 11M-param demo')"
   ],
   "execution_count": 8,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "FSDP sketch: reach for it past a few billion parameters, not on an 11M-param demo\n"
     ]
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=multi-gpu-practice-md-9 fw=all -->\n",
    "\n",
    "You reach for FSDP when the training state at your precision — the\n",
    "parameters, gradients, and optimizer states of\n",
    "that section's anatomy, plus activations — no longer\n",
    "fits on one GPU, or when that redundancy is worth trading away for\n",
    "communication; for this card class the threshold arrives at a few billion\n",
    "parameters. The production distributed-training map, and how to combine\n",
    "FSDP with the other parallelism axes, lives in\n",
    "that section.\n",
    "\n",
    "## JAX: Annotate the Layout, the Compiler Writes the Collectives\n",
    "\n",
    "Everything above was PyTorch's world: multiple processes, explicit\n",
    "collectives, a launcher. JAX offers a different deal, and it is the\n",
    "chapter's cleanest framework contrast. One process sees all the GPUs\n",
    "(that section); you describe *how the data is laid out*\n",
    "across them with a `Mesh` and a `NamedSharding`, `device_put` the arrays\n",
    "onto that layout — parameters replicated (`P()`), the batch sharded along\n",
    "its leading axis (`P('data')`) — and `jit` the **unchanged** single-device\n",
    "training step. XLA's automatic-parallelization pass (GSPMD\n",
    "[@Xu.Lee.Chen.ea.2021]) partitions the computation to match the data\n",
    "layout and *inserts the very allreduce* that that section wrote\n",
    "by hand — you never write a collective:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=multi-gpu-practice-md-10 fw=all -->\n",
    "\n",
    "Now run it — a real `ResNet18`, a real optimizer, a real Fashion-MNIST\n",
    "batch (resized once to 64×64 and kept as host arrays). The reveal is\n",
    "`visualize_array_sharding`, which draws where a tensor actually lives: the\n",
    "batch split across the mesh before the step, and a weight *after* the step\n",
    "still replicated everywhere — the compiler's allreduce is what kept every\n",
    "copy identical:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=multi-gpu-practice-md-11 fw=all -->\n",
    "\n",
    "Take the receipt. that section wrote its `pmean` by hand; here\n",
    "nobody wrote a collective — so where is it? In the compiled program. Lower\n",
    "and compile the step, and search the XLA text for what GSPMD inserted:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=multi-gpu-practice-md-12 fw=all -->\n",
    "\n",
    "Dozens of allreduces, not one — and reading them teaches. The two largest\n",
    "together carry the ~11M gradient floats (XLA bucketed them into two fused\n",
    "sums, much as DDP buckets); the many small ones are batch-norm statistics,\n",
    "because under `jit` even normalization is computed over the *global*\n",
    "batch — the compiler preserves single-device semantics exactly, where DDP\n",
    "leaves each replica its own batch-norm statistics unless you ask for\n",
    "`SyncBatchNorm`. (The exact count is a compiler artifact; the two big ones\n",
    "are the point.)\n",
    "\n",
    "Measured, under the same weak-scaling convention as the DDP sweep\n",
    "(per-device batch 256) — one process, no launcher, no sidecar files:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=multi-gpu-practice-md-13 fw=all -->\n",
    "\n",
    "The shape matches the DDP sweep — real gains, efficiency sagging as $k$\n",
    "grows, no cliff — with one instructive difference: the compiled XLA step\n",
    "is faster per device, so the same allreduce is a *larger fraction* of each\n",
    "step and the efficiency reads a few points lower (82% already at two GPUs\n",
    "in our runs). That is the equation again: speed up the compute and\n",
    "the fabric gets *relatively* slower. And note what these numbers are not:\n",
    "this loop feeds pre-staged host arrays while the DDP script pays a real\n",
    "`DataLoader`, so the absolute samples/s are not a framework shoot-out —\n",
    "the scaling curve is the comparison.\n",
    "\n",
    "One more check, because we are trusting a collective nobody wrote.\n",
    "that section ended its hand-built loop with a one-step equality\n",
    "test, and the declarative version deserves the same scrutiny — same\n",
    "initialization, same 256-example batch, one step on one device versus one\n",
    "step sharded across two:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=multi-gpu-practice-md-14 fw=all -->\n",
    "\n",
    "The two runs agree to about $10^{-4}$ against update magnitudes near\n",
    "$10^{-2}$ — not the $10^{-9}$ of that section's LeNet check,\n",
    "and the gap is itself informative: these are two *different compiled\n",
    "programs*, whose tf32 convolutions and batch-norm reductions associate\n",
    "their arithmetic differently, so the residue is rounding. What the check\n",
    "exists to catch — a summed-instead-of-averaged gradient, an accidental\n",
    "$k\\times$ learning rate — would announce itself at the scale of the update\n",
    "itself.\n",
    "\n",
    "And here is the punchline. To move between *data* parallelism, *tensor*\n",
    "parallelism, and *FSDP*-style sharding in JAX, you change the\n",
    "`PartitionSpec` — not the model code. Sharding the batch axis gives data\n",
    "parallelism (above); sharding a weight's feature axis gives tensor\n",
    "parallelism; sharding the parameters and letting XLA all-gather them\n",
    "just-in-time gives the FSDP pattern. **One sharding vocabulary — annotate\n",
    "the layout, the compiler writes the collectives — spans what PyTorch\n",
    "exposes as three different APIs** (DDP, tensor-parallel wrappers, FSDP) —\n",
    "though an effective sharding plan is still model-aware: someone has to\n",
    "choose the layouts and the constraint points. The manual end of the same\n",
    "spectrum is the `jax.shard_map` + `lax.psum` of that section,\n",
    "where you write the collective yourself; `jit` + sharding is the\n",
    "automatic end.\n",
    "\n",
    "| | PyTorch | JAX |\n",
    "|---|---|---|\n",
    "| processes | one per GPU (`torchrun`) | one, sees all GPUs |\n",
    "| collectives | explicit (NCCL, or DDP's buckets) | inserted by XLA/GSPMD |\n",
    "| data parallel | `DistributedDataParallel` | shard the batch axis |\n",
    "| tensor parallel | separate wrappers / DTensor | change the `PartitionSpec` |\n",
    "| sharded (FSDP) | `fully_shard` | change the `PartitionSpec` |\n",
    "| control | imperative, visible | declarative, compiler-driven |\n",
    "\n",
    "Neither deal is strictly better: PyTorch's explicitness makes the\n",
    "communication legible and debuggable; JAX's declarativeness makes the same\n",
    "code span parallelism strategies by editing an annotation. Knowing both is\n",
    "knowing the design space.\n",
    "\n",
    "## When One Node Is Not Enough\n",
    "\n",
    "This chapter stops at the boundary of a single machine, and it is worth\n",
    "naming what lies past it. When a model is too large for even sharded data\n",
    "parallelism on one node — when the parameters, or the batch, or the\n",
    "sequence length outgrow what $k$ local GPUs can hold — the answer is to\n",
    "shard across *machines*, combining data parallelism with tensor, pipeline,\n",
    "and expert parallelism into the \"3D parallelism\" of frontier training. The\n",
    "collectives then run over a network fabric measured in tens of GB/s\n",
    "between nodes rather than an NVLink domain within one, and the cost model\n",
    "of that section acquires a second, slower bandwidth term. That\n",
    "is the province of the Language Models part, which has models and datasets\n",
    "large enough to warrant it; the production library map — Megatron, the\n",
    "FSDP/DTensor stack, DeepSpeed, and how to launch and checkpoint them across\n",
    "a cluster — is that section. From here the communication\n",
    "*algebra* stays the same; what multi-node adds is engineering on top of\n",
    "it — a hierarchy of fabrics (NVLink inside a node, a network between\n",
    "nodes), rendezvous and elastic restart when machines fail, and stragglers\n",
    "that turn a synchronous step into a queueing problem.\n",
    "\n",
    "## Summary\n",
    "\n",
    "* Production data parallelism (DDP) fixes the three deficits of a\n",
    "  hand-rolled loop: one process per GPU (no shared GIL), ring/tree\n",
    "  collectives (no hub), and gradient bucketing that **overlaps\n",
    "  communication with the backward pass**.\n",
    "* Launched from a notebook via `torchrun` on a sidecar script, DDP scales\n",
    "  a compute-dense ResNet-18 by roughly 1.8× on two GPUs and 3.3× on four\n",
    "  on our host-staged box (88% and 82% *weak-scaling* efficiency; a\n",
    "  fixed-global-batch strong-scaling sweep asks the harder question), and a\n",
    "  `no_sync()` measurement confirms the equation's communication\n",
    "  price to within tens of percent. An NVLink box changes only the\n",
    "  constant.\n",
    "* The constant is also configuration-sensitive: one documented NCCL\n",
    "  switch quintuples the bare-collective bandwidth on this box — yet\n",
    "  deadlocks DDP's overlapped training path, so the notebooks keep the\n",
    "  library's defaults and teach the pair of measurements instead.\n",
    "  Collective-library configuration moves communication by factors, not\n",
    "  percent; a workaround is validated per platform *and* per workload.\n",
    "* FSDP shards the $16P$-byte training state across ranks — the ZeRO ladder\n",
    "  — by splitting allreduce back into its reduce-scatter and all-gather\n",
    "  halves and materializing each layer just-in-time. It is for models whose\n",
    "  training state outgrows one GPU — a few billion parameters on this card\n",
    "  class.\n",
    "* JAX inverts the model: one process, annotate the data layout with a\n",
    "  `Mesh` and `PartitionSpec`, `jit` the unchanged step, and XLA inserts\n",
    "  the collectives — visible in the compiled program's `all-reduce` ops,\n",
    "  measured in a k-sweep, and verified by a k=1-versus-k=2 equality check.\n",
    "  Changing the `PartitionSpec` — not the code — moves between data,\n",
    "  tensor, and FSDP-style sharding, spanning what PyTorch exposes as three\n",
    "  APIs.\n",
    "* Multi-node 3D parallelism and the production library map are the\n",
    "  Language Models part and that section.\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. Vary DDP's `bucket_cap_mb` (the gradient bucket size) and measure\n",
    "   throughput at $k = 2$. Why is there an optimum — what does a too-small\n",
    "   bucket cost, and a too-large one?\n",
    "1. Extend the `no_sync()` measurement to $k = 4$. How much does the\n",
    "   per-step communication time grow from $k=2$? Compare against\n",
    "   the equation's $2(k-1)/k$ growth and the flat $2N/\\beta$\n",
    "   of the equation — which fits better, and what does that tell\n",
    "   you about how NCCL schedules the transfer on this P2P-less box?\n",
    "1. Reproduce both halves of the fabric-configuration story. First extend\n",
    "   the bare-collective comparison across payloads from 1 MB to 256 MB:\n",
    "   where does each transport's effective bandwidth saturate, and does\n",
    "   the five-fold gap persist? Then set `NCCL_SHM_USE_CUDA_MEMCPY=1`\n",
    "   inside `train_ddp.py` itself and relaunch the $k=2$ sweep — on our\n",
    "   box the run wedges within seconds (be ready to kill the launcher).\n",
    "   What does the pair teach about trusting a library's defaults on a\n",
    "   topology it was not tuned for — and about trusting a workaround\n",
    "   anywhere you have not re-validated it, workload and all?\n",
    "1. Write the `PartitionSpec` that shards a weight matrix's *output*\n",
    "   features across the mesh (tensor parallelism) and\n",
    "   `visualize_array_sharding` the result. How does the communication\n",
    "   pattern differ from the batch-sharded (data-parallel) case?\n",
    "1. Size ZeRO stage 3 (parameters, gradients, and optimizer states all\n",
    "   sharded) for a 7-billion-parameter model on 8 GPUs with 80 GB each:\n",
    "   what is the per-GPU training footprint, and does it fit? Redo the\n",
    "   arithmetic for DDP (no sharding) and explain the difference.\n",
    "1. The weak-scaling efficiency in the DDP sweep fell from 88% at $k=2$ to\n",
    "   82% at $k=4$. Using the equation, predict the efficiency at\n",
    "   $k=8$ on the same fabric, and state the assumption your prediction\n",
    "   makes about how $t_{\\text{comm}}$ grows."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "name": "d2l-pytorch",
   "display_name": "d2l (PyTorch)",
   "language": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
