{ "nbformat": 4, "nbformat_minor": 5, "metadata": { "kernelspec": { "name": "python3", "display_name": "Python 3", "language": "python" }, "language_info": { "name": "python" } }, "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Lab 5.3 · Many GPUs\n", "\n", "**Goal:** run real distributed-training code on your laptop, with several CPU processes that talk to\n", "each other through PyTorch's `gloo` backend. You will do a ring all-reduce by hand, check that\n", "data-parallel gradients equal the gradients of one process on the whole batch, measure how step\n", "time and the all-reduce share change with 1, 2 and 4 processes, shard the optimizer state (ZeRO\n", "stage 1) and the whole model (FSDP), write a 2-way tensor-parallel MLP by hand, count the pipeline\n", "bubble, and break distributed training three ways.\n", "\n", "**Honesty label.** Every worker here is a **CPU process on one machine**, not a GPU. The\n", "communication is real (sockets on `localhost` moving real tensors) but it is *not* NVLink or\n", "InfiniBand, and the \"speed-ups\" you measure say how this laptop behaves, not how a GPU cluster\n", "behaves. Tensor parallelism is run as two processes for correctness only; pipeline parallelism is\n", "simulated as a schedule. Everything about real GPU interconnects is explained in the chapter and\n", "marked \"not run here\".\n", "\n", "**Runs on:** any laptop with 4 or more CPU cores (no GPU needed); macOS, Linux, Colab and Kaggle.\n", "Install locally with `uv run --with torch --with matplotlib`.\n", "\n", "**Versions tested:** printed by the last cell." ], "id": "lab-5-3-parallel-00" }, { "cell_type": "code", "metadata": {}, "source": [ "import csv\n", "import math\n", "import pathlib\n", "import platform\n", "import statistics\n", "import sys\n", "import tempfile\n", "import textwrap\n", "import time\n", "\n", "import torch\n", "\n", "print(\"PyTorch\", torch.__version__, \"| CPU cores visible:\", __import__(\"os\").cpu_count())\n", "print(\"gloo available:\", torch.distributed.is_available() and torch.distributed.is_gloo_available())\n", "\n", "\n", "def out_dir():\n", " for candidate in (pathlib.Path(\"data\"), pathlib.Path(\"../data\")):\n", " if candidate.is_dir():\n", " d = candidate / \"lab-5-3-parallel\"\n", " d.mkdir(parents=True, exist_ok=True)\n", " return d\n", " return pathlib.Path(\".\")\n", "\n", "\n", "def save_csv(name, header, rows):\n", " path = out_dir() / name\n", " with open(path, \"w\", newline=\"\") as f:\n", " w = csv.writer(f)\n", " w.writerow(header)\n", " w.writerows(rows)\n", " print(f\"saved {path} ({len(rows)} rows)\")\n", "\n", "\n", "MACHINE = f\"{platform.system()} {platform.machine()}, {__import__('os').cpu_count()} logical cores, CPU processes (gloo), not GPUs\"" ], "execution_count": null, "outputs": [], "id": "lab-5-3-parallel-01" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1 · Predict first\n", "\n", "Write down your answers before running the cells below.\n", "\n", "1. **Equivalence.** Two processes each compute the gradient of a 64-example batch's half, and an\n", " all-reduce averages the two gradients. How far from the gradient of one process on all 64\n", " examples will the result be (exactly equal, off by rounding noise around `1e-8`, or visibly\n", " different)?\n", "2. **Ring cost.** Four workers each hold a gradient of `S` numbers. In a ring all-reduce, how many\n", " numbers does *each worker* send in total? (Hint: the chapter's formula has `N` in it.)\n", "3. **Speed.** Train a 2.4-million-parameter MLP with a global batch of 256. With 1, 2 and 4 CPU\n", " processes, what speed-up do you expect for 4 processes (ideal is `4×`)? Which share of the step\n", " do you expect the all-reduce to take?\n", "4. **Memory.** A 7-billion-parameter model on 8 GPUs, trained with Adam in mixed precision at\n", " 16 bytes per parameter: how many GB per GPU does ZeRO stage 1, 2 and 3 need (weights, gradients\n", " and optimizer state only)?\n", "5. **Bubble.** A pipeline has 4 stages. With 4 micro-batches, what fraction of each stage's time is\n", " idle? With 16?" ], "id": "lab-5-3-parallel-02" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2 · How processes talk: a helper module\n", "\n", "A notebook cell cannot be handed to `torch.multiprocessing.spawn`: the child processes start a fresh\n", "Python and must be able to `import` the function. So the next cell writes the worker code to a small\n", "module file, and every later cell imports it and launches it. **Which launcher this notebook uses:**\n", "`torch.multiprocessing.start_processes(..., start_method=\"spawn\")` called from the notebook (not\n", "`torchrun`), because it works inside a headless notebook run. `torchrun` is the same idea started\n", "from a terminal; the worker functions would not change.\n", "\n", "Each worker runs with **one CPU thread** (`torch.set_num_threads(1)`), so that `N` processes use `N`\n", "cores and do not fight over them. Each worker joins a *process group* with `init_process_group`\n", "(backend `gloo`, rank `0 … N-1`, world size `N`); from then on `dist.all_reduce`, `dist.barrier` and\n", "friends are available. Read the module: every function is a few lines." ], "id": "lab-5-3-parallel-03" }, { "cell_type": "code", "metadata": {}, "source": [ "HELPERS = r'''\n", "import json, os, pathlib, socket, tempfile, time\n", "from datetime import timedelta\n", "\n", "import torch\n", "import torch.nn as nn\n", "import torch.nn.functional as F\n", "import torch.distributed as dist\n", "import torch.multiprocessing as mp\n", "\n", "D_IN, HIDDEN, N_CLASSES = 256, 1024, 10\n", "\n", "\n", "def make_model(seed=0, dtype=torch.float32, depth=4):\n", " \"\"\"MLP 256 -> 1024 -> 1024 -> 1024 -> 10 (about 2.4 M parameters), same init for the same seed.\"\"\"\n", " torch.manual_seed(seed)\n", " layers, d = [], D_IN\n", " for _ in range(depth - 1):\n", " layers += [nn.Linear(d, HIDDEN), nn.ReLU()]\n", " d = HIDDEN\n", " layers.append(nn.Linear(d, N_CLASSES))\n", " return nn.Sequential(*layers).to(dtype)\n", "\n", "\n", "def make_data(n, seed, dtype=torch.float32):\n", " \"\"\"Random inputs, labels from a fixed random linear 'teacher' (so there is something to learn).\"\"\"\n", " g = torch.Generator().manual_seed(seed)\n", " X = torch.randn(n, D_IN, generator=g)\n", " teacher = torch.randn(D_IN, N_CLASSES, generator=torch.Generator().manual_seed(123))\n", " return X.to(dtype), (X @ teacher).argmax(1)\n", "\n", "\n", "def flat_params(model):\n", " return torch.cat([p.detach().reshape(-1) for p in model.parameters()])\n", "\n", "\n", "def free_port():\n", " s = socket.socket()\n", " s.bind((\"127.0.0.1\", 0))\n", " port = s.getsockname()[1]\n", " s.close()\n", " return port\n", "\n", "\n", "def _entry(rank, fn_name, world_size, port, args, outdir, timeout_s):\n", " torch.set_num_threads(1)\n", " dist.init_process_group(\"gloo\", init_method=f\"tcp://127.0.0.1:{port}\", rank=rank,\n", " world_size=world_size, timeout=timedelta(seconds=timeout_s))\n", " out = pathlib.Path(outdir) / f\"rank{rank}.json\"\n", " try:\n", " res = globals()[fn_name](rank, world_size, *args)\n", " out.write_text(json.dumps({\"ok\": True, \"result\": res}))\n", " except BaseException as e: # a worker never crashes the notebook: it reports\n", " out.write_text(json.dumps({\"ok\": False, \"error\": (type(e).__name__ + \": \" + str(e))[:600]}))\n", " finally:\n", " try:\n", " dist.destroy_process_group()\n", " except Exception:\n", " pass\n", "\n", "\n", "def launch(fn_name, world_size, args=(), collective_timeout=120, hard_timeout=600, retries=2):\n", " \"\"\"Start `world_size` processes running fn_name(rank, world_size, *args); return [rank0, rank1, ...] results.\n", " If a process dies without reporting (a hard crash, seen once or twice on a loaded laptop), try again.\"\"\"\n", " for attempt in range(retries + 1):\n", " outdir = tempfile.mkdtemp(prefix=\"lab53_\")\n", " ctx = mp.start_processes(_entry, args=(fn_name, world_size, free_port(), args, outdir, collective_timeout),\n", " nprocs=world_size, join=False, start_method=\"spawn\")\n", " t0, killed = time.time(), False\n", " try:\n", " while not ctx.join(timeout=0.5):\n", " if time.time() - t0 > hard_timeout: # last resort: never hang the notebook\n", " killed = True\n", " for p in ctx.processes:\n", " p.kill()\n", " break\n", " except Exception:\n", " pass\n", " for p in ctx.processes:\n", " p.join(5)\n", " results = []\n", " for r in range(world_size):\n", " f = pathlib.Path(outdir) / f\"rank{r}.json\"\n", " results.append(json.loads(f.read_text()) if f.exists() else {\"ok\": False, \"error\": \"no result (killed or crashed)\"})\n", " crashed = any(r[\"error\"].startswith(\"no result\") for r in results if not r[\"ok\"])\n", " if not crashed or killed or attempt == retries:\n", " return results\n", " print(f\"[launch] a process of {fn_name} (world size {world_size}) crashed without a result; retrying (attempt {attempt + 2})\")\n", "\n", "\n", "def ok_results(results):\n", " bad = [r for r in results if not r[\"ok\"]]\n", " if bad:\n", " raise RuntimeError(bad[0][\"error\"])\n", " return [r[\"result\"] for r in results]\n", "\n", "\n", "# ---------------------------------------------------------------- data parallel\n", "def ddp_equiv(rank, ws, dtype_name, steps=20, batch=64):\n", " from torch.nn.parallel import DistributedDataParallel as DDP\n", " dtype = getattr(torch, dtype_name)\n", " X, y = make_data(batch, 0, dtype)\n", " # 1. one process, whole batch\n", " ref = make_model(0, dtype)\n", " F.cross_entropy(ref(X), y).backward()\n", " ref_grads = [p.grad.clone() for p in ref.parameters()]\n", " # 2. DDP: every rank takes its own slice of the batch\n", " lo, hi = rank * batch // ws, (rank + 1) * batch // ws\n", " model = DDP(make_model(0, dtype))\n", " F.cross_entropy(model(X[lo:hi]), y[lo:hi]).backward()\n", " grad_diff = max((p.grad - g).abs().max().item() for p, g in zip(model.parameters(), ref_grads))\n", " grad_scale = max(g.abs().max().item() for g in ref_grads)\n", " # 3. twenty SGD steps each way\n", " ref, opt_ref = make_model(0, dtype), None\n", " opt_ref = torch.optim.SGD(ref.parameters(), lr=0.1)\n", " for _ in range(steps):\n", " opt_ref.zero_grad()\n", " F.cross_entropy(ref(X), y).backward()\n", " opt_ref.step()\n", " model = DDP(make_model(0, dtype))\n", " opt = torch.optim.SGD(model.parameters(), lr=0.1)\n", " for _ in range(steps):\n", " opt.zero_grad()\n", " F.cross_entropy(model(X[lo:hi]), y[lo:hi]).backward()\n", " opt.step()\n", " param_diff = (flat_params(model) - flat_params(ref)).abs().max().item()\n", " # 4. are the replicas identical to each other?\n", " mine = flat_params(model)\n", " gathered = [torch.zeros_like(mine) for _ in range(ws)]\n", " dist.all_gather(gathered, mine)\n", " spread = max((g - gathered[0]).abs().max().item() for g in gathered)\n", " return {\"grad_max_abs_diff\": grad_diff, \"grad_max_abs\": grad_scale, \"param_diff_after_steps\": param_diff,\n", " \"replica_spread\": spread}\n", "\n", "\n", "def step_time(rank, ws, mode, per_rank_batch, steps=30, warmup=5):\n", " from torch.nn.parallel import DistributedDataParallel as DDP\n", " model = make_model(0)\n", " opt = torch.optim.AdamW(model.parameters(), lr=1e-3)\n", " if mode == \"ddp\":\n", " model = DDP(model)\n", " params = list(model.parameters())\n", " X, y = make_data(per_rank_batch, rank)\n", " keys = [\"compute\", \"wait\", \"allreduce\", \"opt\", \"step\"]\n", " rec = {k: [] for k in keys}\n", " for i in range(warmup + steps):\n", " t0 = time.perf_counter()\n", " opt.zero_grad(set_to_none=True)\n", " F.cross_entropy(model(X), y).backward()\n", " t1 = time.perf_counter()\n", " t2 = t3 = t1\n", " if mode == \"manual\" and ws > 1:\n", " dist.barrier() # wait for the slowest rank\n", " t2 = time.perf_counter()\n", " flat = torch.cat([p.grad.reshape(-1) for p in params])\n", " dist.all_reduce(flat) # sum over ranks\n", " flat /= ws # then average\n", " off = 0\n", " for p in params:\n", " n = p.numel()\n", " p.grad.copy_(flat[off:off + n].view_as(p))\n", " off += n\n", " t3 = time.perf_counter()\n", " opt.step()\n", " t4 = time.perf_counter()\n", " if i >= warmup:\n", " for k, v in zip(keys, [t1 - t0, t2 - t1, t3 - t2, t4 - t3, t4 - t0]):\n", " rec[k].append(v * 1000)\n", " srt = lambda a: sorted(a)[len(a) // 2]\n", " return {k: srt(v) for k, v in rec.items()}\n", "\n", "\n", "def allreduce_sizes(rank, ws, log2_sizes, iters=10):\n", " out = []\n", " for e in log2_sizes:\n", " t = torch.ones(2 ** e)\n", " for _ in range(2):\n", " dist.all_reduce(t)\n", " times = []\n", " for _ in range(iters):\n", " dist.barrier()\n", " t0 = time.perf_counter()\n", " dist.all_reduce(t)\n", " times.append((time.perf_counter() - t0) * 1000)\n", " out.append([t.numel() * 4, sorted(times)[len(times) // 2]])\n", " return out\n", "\n", "\n", "# ---------------------------------------------------------------- ZeRO stage 1 and FSDP\n", "def zero1(rank, ws, steps=5):\n", " from torch.nn.parallel import DistributedDataParallel as DDP\n", " from torch.distributed.optim import ZeroRedundancyOptimizer\n", " X, y = make_data(64, 0)\n", " lo, hi = rank * 64 // ws, (rank + 1) * 64 // ws\n", "\n", " def state_bytes(optim):\n", " return sum(v.numel() * v.element_size() for s in optim.state.values() for v in s.values()\n", " if torch.is_tensor(v) and v.ndim > 0)\n", "\n", " res = {}\n", " models = {}\n", " for name in (\"adam\", \"zero1\"):\n", " m = DDP(make_model(0))\n", " if name == \"adam\":\n", " opt = torch.optim.Adam(m.parameters(), lr=1e-3)\n", " inner = opt\n", " else:\n", " opt = ZeroRedundancyOptimizer(m.parameters(), optimizer_class=torch.optim.Adam, lr=1e-3)\n", " inner = opt.optim\n", " for _ in range(steps):\n", " opt.zero_grad()\n", " F.cross_entropy(m(X[lo:hi]), y[lo:hi]).backward()\n", " opt.step()\n", " res[name + \"_state_bytes\"] = state_bytes(inner)\n", " models[name] = flat_params(m)\n", " res[\"n_params\"] = models[\"adam\"].numel()\n", " res[\"param_diff_zero1_vs_adam\"] = (models[\"adam\"] - models[\"zero1\"]).abs().max().item()\n", " return res\n", "\n", "\n", "def fsdp(rank, ws):\n", " from torch.distributed.fsdp import fully_shard\n", " from torch.distributed.device_mesh import init_device_mesh\n", " import torch.nn as nn\n", " res = {\"default_error\": None}\n", " X, y = make_data(64, 0)\n", " lo, hi = rank * 64 // ws, (rank + 1) * 64 // ws\n", "\n", " def shard_model(mesh=None):\n", " m = make_model(0)\n", " kw = {} if mesh is None else {\"mesh\": mesh}\n", " for layer in m:\n", " if isinstance(layer, nn.Linear):\n", " fully_shard(layer, **kw)\n", " fully_shard(m, **kw)\n", " return m\n", "\n", " try: # first the call as the documentation shows it: no device given\n", " m = shard_model()\n", " m(X[lo:hi]).sum().backward()\n", " res[\"default\"] = \"worked\"\n", " except Exception as e:\n", " res[\"default_error\"] = (type(e).__name__ + \": \" + str(e))[:300]\n", " mesh = init_device_mesh(\"cpu\", (ws,)) # say explicitly that the shards live on the CPU\n", " m = shard_model(mesh)\n", " loss = F.cross_entropy(m(X[lo:hi]), y[lo:hi])\n", " loss.backward()\n", " ref = make_model(0)\n", " F.cross_entropy(ref(X), y).backward()\n", " diffs = [(p.grad.full_tensor() - q.grad).abs().max().item() for p, q in zip(m.parameters(), ref.parameters())]\n", " res[\"grad_max_abs_diff\"] = max(diffs)\n", " res[\"local_params\"] = sum(p.to_local().numel() for p in m.parameters())\n", " res[\"total_params\"] = sum(q.numel() for q in ref.parameters())\n", " res[\"local_shape_first_weight\"] = list(next(iter(m.parameters())).to_local().shape)\n", " return res\n", "\n", "\n", "# ---------------------------------------------------------------- tensor parallel\n", "COMM = {\"fwd_allreduce\": 0, \"bwd_allreduce\": 0, \"fwd_bytes\": 0, \"bwd_bytes\": 0}\n", "\n", "\n", "class CopyToTP(torch.autograd.Function):\n", " \"\"\"Megatron's f: identity in the forward pass, all-reduce in the backward pass.\"\"\"\n", " @staticmethod\n", " def forward(ctx, x):\n", " return x.clone()\n", "\n", " @staticmethod\n", " def backward(ctx, g):\n", " g = g.clone().contiguous()\n", " dist.all_reduce(g)\n", " COMM[\"bwd_allreduce\"] += 1\n", " COMM[\"bwd_bytes\"] += g.numel() * g.element_size()\n", " return g\n", "\n", "\n", "class ReduceFromTP(torch.autograd.Function):\n", " \"\"\"Megatron's g: all-reduce in the forward pass, identity in the backward pass.\"\"\"\n", " @staticmethod\n", " def forward(ctx, x):\n", " x = x.clone().contiguous()\n", " dist.all_reduce(x)\n", " COMM[\"fwd_allreduce\"] += 1\n", " COMM[\"fwd_bytes\"] += x.numel() * x.element_size()\n", " return x\n", "\n", " @staticmethod\n", " def backward(ctx, g):\n", " return g\n", "\n", "\n", "def tp_mlp(rank, ws, d=64, h=256, backward_allreduce=True):\n", " torch.manual_seed(0)\n", " A, bA = torch.randn(d, h) / d ** 0.5, torch.randn(h) * 0.1 # first matrix: [d, h]\n", " B, bB = torch.randn(h, d) / h ** 0.5, torch.randn(d) * 0.1 # second matrix: [h, d]\n", " X = torch.randn(4, 8, d) # [batch, seq, d]\n", " # unsplit reference\n", " Xr, Ar, bAr, Br, bBr = [t.clone().requires_grad_() for t in (X, A, bA, B, bB)]\n", " Yr = torch.nn.functional.gelu(Xr @ Ar + bAr) @ Br + bBr\n", " Yr.pow(2).mean().backward()\n", " # split: rank r owns columns [r*h/ws, (r+1)*h/ws) of A and bA, and the same rows of B\n", " c = h // ws\n", " sl = slice(rank * c, (rank + 1) * c)\n", " x = X.clone().requires_grad_()\n", " a, ba = A[:, sl].clone().requires_grad_(), bA[sl].clone().requires_grad_()\n", " b, bb = B[sl, :].clone().requires_grad_(), bB.clone().requires_grad_()\n", " for k in COMM:\n", " COMM[k] = 0\n", " x_in = CopyToTP.apply(x) if backward_allreduce else x\n", " hidden = torch.nn.functional.gelu(x_in @ a + ba) # [4, 8, h/ws]: no communication\n", " y_partial = hidden @ b # [4, 8, d]: a partial sum\n", " y = ReduceFromTP.apply(y_partial) + bb # all-reduce adds the partial sums\n", " y.pow(2).mean().backward()\n", " err = lambda u, v: (u - v).abs().max().item()\n", " return {\"forward_diff\": err(y, Yr), \"input_grad_diff\": err(x.grad, Xr.grad),\n", " \"A_shard_grad_diff\": err(a.grad, Ar.grad[:, sl]), \"B_shard_grad_diff\": err(b.grad, Br.grad[sl, :]),\n", " \"bA_shard_grad_diff\": err(ba.grad, bAr.grad[sl]), \"bB_grad_diff\": err(bb.grad, bBr.grad),\n", " \"params_per_rank\": a.numel() + ba.numel() + b.numel() + bb.numel(),\n", " \"params_unsplit\": A.numel() + bA.numel() + B.numel() + bB.numel(), **COMM}\n", "\n", "\n", "# ---------------------------------------------------------------- failure playgrounds\n", "def fail_seeds(rank, ws, mode):\n", " from torch.nn.parallel import DistributedDataParallel as DDP\n", " X, y = make_data(256, 0)\n", " Xe, ye = make_data(512, 99)\n", " seed = 100 + rank if mode.startswith(\"diff\") else 0\n", " model = make_model(seed)\n", " if mode == \"diff_seed_ddp\":\n", " model = DDP(model)\n", " opt = torch.optim.SGD(model.parameters(), lr=0.1)\n", " per = 256 // ws\n", " for step in range(50):\n", " opt.zero_grad()\n", " lo = rank * per\n", " F.cross_entropy(model(X[lo:lo + per]), y[lo:lo + per]).backward()\n", " if mode != \"diff_seed_ddp\": # by hand: average the gradients, nothing else\n", " for p in model.parameters():\n", " dist.all_reduce(p.grad)\n", " p.grad /= ws\n", " opt.step()\n", " mine = flat_params(model)\n", " gathered = [torch.zeros_like(mine) for _ in range(ws)]\n", " dist.all_gather(gathered, mine)\n", " spread = max((g - gathered[0]).abs().max().item() for g in gathered)\n", " with torch.no_grad():\n", " eval_loss = F.cross_entropy(model(Xe), ye).item()\n", " losses = [torch.zeros(1) for _ in range(ws)]\n", " dist.all_gather(losses, torch.tensor([eval_loss]))\n", " return {\"param_spread\": spread, \"eval_loss_per_rank\": [round(l.item(), 4) for l in losses]}\n", "\n", "\n", "def fail_shard(rank, ws, shard, steps=40, per_rank=32, n_train=2048):\n", " from torch.nn.parallel import DistributedDataParallel as DDP\n", " X, y = make_data(n_train, 0)\n", " Xe, ye = make_data(512, 99)\n", " perm = torch.randperm(n_train, generator=torch.Generator().manual_seed(7)) # same shuffle on every rank\n", " model = DDP(make_model(0))\n", " opt = torch.optim.Adam(model.parameters(), lr=1e-3)\n", " seen, per_step_unique = set(), []\n", " for s in range(steps):\n", " start = s * ws * per_rank + rank * per_rank if shard else s * per_rank # the whole bug is this line\n", " idx = perm[(start + torch.arange(per_rank)) % n_train] # wrap around at the end of the data\n", " opt.zero_grad()\n", " F.cross_entropy(model(X[idx]), y[idx]).backward()\n", " opt.step()\n", " mine = torch.zeros(n_train)\n", " mine[idx] = 1\n", " total = mine.clone()\n", " dist.all_reduce(total)\n", " per_step_unique.append(int((total > 0).sum().item()))\n", " seen |= set(torch.nonzero(total).flatten().tolist())\n", " with torch.no_grad():\n", " logits = model(Xe)\n", " loss, acc = F.cross_entropy(logits, ye).item(), (logits.argmax(1) == ye).float().mean().item()\n", " steps_per_epoch = n_train // (per_rank * ws) if shard else n_train // per_rank\n", " return {\"unique_samples_per_step\": per_step_unique[0], \"unique_samples_total\": len(seen), \"eval_loss\": loss,\n", " \"eval_acc\": acc, \"steps_per_epoch\": steps_per_epoch}\n", "\n", "\n", "def fail_deadlock(rank, ws, fixed):\n", " t0 = time.time()\n", " loss = torch.tensor([float(rank + 1)]) # pretend: this rank's training loss\n", " if fixed:\n", " dist.all_reduce(loss) # every rank calls the collective\n", " loss /= ws\n", " return {\"mean_loss\": loss.item(), \"seconds\": round(time.time() - t0, 1)}\n", " if rank == 0: # \"only rank 0 logs the average loss\"\n", " try:\n", " dist.all_reduce(loss)\n", " loss /= ws\n", " except Exception as e:\n", " return {\"error\": (type(e).__name__ + \": \" + str(e))[:250], \"seconds_stuck\": round(time.time() - t0, 1)}\n", " return {\"mean_loss\": loss.item()}\n", " time.sleep(8) # the other ranks carry on with their own work\n", " return {\"skipped_the_collective\": True}\n", "'''\n", "\n", "WORK = pathlib.Path(tempfile.gettempdir()) / \"lab53_helpers\"\n", "WORK.mkdir(exist_ok=True)\n", "(WORK / \"lab53_helpers.py\").write_text(HELPERS)\n", "sys.path.insert(0, str(WORK))\n", "import lab53_helpers as H\n", "\n", "print(\"helper module written to\", WORK / \"lab53_helpers.py\")\n", "model_probe = H.make_model(0)\n", "N_PARAMS = sum(p.numel() for p in model_probe.parameters())\n", "print(f\"the lab's MLP: {N_PARAMS:,} parameters = {N_PARAMS * 4 / 1e6:.2f} MB of float32 gradients per step\")" ], "execution_count": null, "outputs": [], "id": "lab-5-3-parallel-04" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3 · Ring all-reduce, by hand\n", "\n", "**All-reduce** means: every worker holds a vector, and when the call returns every worker holds the\n", "*sum* of all the vectors. The naive way sends everything to one worker, which adds and sends the\n", "answer back, so that one worker's link carries the whole load. The **ring** way arranges the `N`\n", "workers in a circle and cuts each vector into `N` chunks. Phase 1, *reduce-scatter*: for `N-1`\n", "steps every worker sends one chunk to its right neighbour, which adds it to its own copy of that\n", "chunk; afterwards each worker holds one chunk that is the complete sum. Phase 2, *all-gather*: for\n", "`N-1` more steps every worker forwards a finished chunk to its right neighbour, which overwrites\n", "its copy. The cell below does exactly that on plain Python lists, with one number per chunk, and\n", "counts what each worker sends." ], "id": "lab-5-3-parallel-05" }, { "cell_type": "code", "metadata": {}, "source": [ "def ring_allreduce(vectors, verbose=True):\n", " n = len(vectors)\n", " data = [list(v) for v in vectors] # data[worker][chunk]\n", " sent = [0] * n # chunks sent by each worker\n", " if verbose:\n", " print(\"start \", data)\n", " for phase in (\"reduce-scatter\", \"all-gather\"):\n", " for s in range(n - 1):\n", " if phase == \"reduce-scatter\": # worker i sends chunk (i - s) mod n to the right, who ADDS it\n", " msgs = [(i, (i - s) % n, data[i][(i - s) % n]) for i in range(n)]\n", " else: # worker i sends chunk (i + 1 - s) mod n to the right, who OVERWRITES\n", " msgs = [(i, (i + 1 - s) % n, data[i][(i + 1 - s) % n]) for i in range(n)]\n", " for i, c, val in msgs: # all messages of a step happen \"at the same time\"\n", " dst = (i + 1) % n\n", " data[dst][c] = data[dst][c] + val if phase == \"reduce-scatter\" else val\n", " sent[i] += 1\n", " if verbose:\n", " print(f\"{phase:14s} step {s + 1}\", data)\n", " return data, sent\n", "\n", "\n", "N = 4\n", "vectors = [[i * N + c + 1 for c in range(N)] for i in range(N)] # worker 0: [1,2,3,4] ... worker 3: [13,14,15,16]\n", "result, sent = ring_allreduce(vectors)\n", "expected = [sum(v[c] for v in vectors) for c in range(N)]\n", "print(\"\\nexpected sum per chunk:\", expected)\n", "print(\"every worker holds it: \", all(row == expected for row in result))\n", "print(f\"chunks sent per worker: {sent} = 2(N-1) = {2 * (N - 1)} chunks of size S/N\")\n", "print(f\"in units of S: {sent[0] / N:.2f} vs formula 2(N-1)/N = {2 * (N - 1) / N:.2f}\")\n", "print(f\"naive 'send everything to worker 0': worker 0 receives {(N - 1)} vectors and sends back {(N - 1)} -> \"\n", " f\"{2 * (N - 1)} S, versus {2 * (N - 1) / N:.2f} S per worker on the ring\")" ], "execution_count": null, "outputs": [], "id": "lab-5-3-parallel-06" }, { "cell_type": "code", "metadata": {}, "source": [ "rows = [(n, 2 * (n - 1) / n) for n in (2, 4, 8, 64, 1024)]\n", "print(\" N 2(N-1)/N (in units of S, per worker)\")\n", "for n, f in rows:\n", " print(f\"{n:5d} {f:.4f}\")\n", "save_csv(\"ring-cost.csv\", [\"workers_N\", \"per_worker_traffic_in_units_of_S\"], [(n, round(f, 6)) for n, f in rows])" ], "execution_count": null, "outputs": [], "id": "lab-5-3-parallel-07" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4 · What a real all-reduce costs on this machine\n", "\n", "Now the real thing: `dist.all_reduce` between processes over `gloo`. Time it for messages from 1 KB\n", "to 64 MB. Small messages are dominated by a fixed *latency* per call; large ones by *bandwidth*.\n", "**The bandwidth here is localhost sockets between CPU processes, not a GPU link.** We report the\n", "\"bus bandwidth\" `2(N-1)/N · bytes / time`, the number NCCL's benchmarks also use." ], "id": "lab-5-3-parallel-08" }, { "cell_type": "code", "metadata": {}, "source": [ "LOG2 = list(range(8, 25, 2)) # 256 floats (1 KB) ... 16 M floats (64 MB)\n", "rows = []\n", "for w in (2, 4):\n", " res = H.ok_results(H.launch(\"allreduce_sizes\", w, (LOG2,)))\n", " for nbytes, ms in res[0]:\n", " bus = 2 * (w - 1) / w * nbytes / (ms / 1000) / 1e9\n", " rows.append((w, nbytes, round(ms, 4), round(bus, 3)))\n", "print(f\"{'procs':>5} {'bytes':>12} {'ms':>10} {'bus GB/s':>9}\")\n", "for w, nb, ms, bus in rows:\n", " print(f\"{w:5d} {nb:12,d} {ms:10.3f} {bus:9.2f}\")\n", "save_csv(\"allreduce-size.csv\", [\"processes\", \"message_bytes\", \"median_ms\", \"bus_bandwidth_GBps\"], rows)" ], "execution_count": null, "outputs": [], "id": "lab-5-3-parallel-09" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5 · Data parallelism: do the gradients match one process?\n", "\n", "`DistributedDataParallel` (DDP) wraps a model so that `loss.backward()` also all-reduces the\n", "gradients (averaged). The claim to test: 2 or 4 processes, each on its own slice of a batch of 64,\n", "give the **same gradient** as one process on all 64 examples, because the mean of equal-sized means\n", "is the overall mean. Check it in float32 and float64, then check that 20 SGD steps end at the same\n", "weights and that all replicas stay identical to each other." ], "id": "lab-5-3-parallel-10" }, { "cell_type": "code", "metadata": {}, "source": [ "rows = []\n", "print(f\"{'dtype':8} {'procs':>5} {'max |grad diff|':>16} {'max |grad|':>11} {'weights after 20 steps':>24} {'replica spread':>15}\")\n", "for dtype_name in (\"float32\", \"float64\"):\n", " for w in (1, 2, 4):\n", " r = H.ok_results(H.launch(\"ddp_equiv\", w, (dtype_name,)))[0]\n", " rows.append((dtype_name, w, r[\"grad_max_abs_diff\"], r[\"grad_max_abs\"], r[\"param_diff_after_steps\"], r[\"replica_spread\"]))\n", " print(f\"{dtype_name:8} {w:5d} {r['grad_max_abs_diff']:16.3e} {r['grad_max_abs']:11.3e} \"\n", " f\"{r['param_diff_after_steps']:24.3e} {r['replica_spread']:15.3e}\")\n", "save_csv(\"ddp-equivalence.csv\",\n", " [\"dtype\", \"processes\", \"grad_max_abs_diff\", \"grad_max_abs\", \"weight_max_abs_diff_after_20_steps\", \"replica_spread\"],\n", " [(a, b, f\"{c:.4e}\", f\"{d:.4e}\", f\"{e:.4e}\", f\"{f:.4e}\") for a, b, c, d, e, f in rows])" ], "execution_count": null, "outputs": [], "id": "lab-5-3-parallel-11" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 6 · Step time and the all-reduce share, with 1, 2 and 4 processes\n", "\n", "**CPU processes on an Apple-silicon laptop, not GPUs.** Two experiments, each with 1, 2 and 4\n", "processes, 4 repeats (interleaved), median step of 30 after 5 warm-up steps, and the fastest repeat is reported\n", "(the one the rest of your machine disturbed least; the load average is saved with every run):\n", "\n", "- **strong scaling:** the *global* batch stays 256, so each process gets `256 / N` examples. A\n", " perfect system would be `N` times faster.\n", "- **weak scaling:** each process keeps 64 examples, so the global batch grows with `N`. A perfect\n", " system keeps the step time constant and processes `N` times more data per second.\n", "\n", "In the *manual* version each step is timed in four parts: forward + backward (**compute**), a\n", "`barrier` (**wait** for the slowest process), the all-reduce of all gradients in one flat tensor\n", "(**all-reduce**), and the optimizer (**opt**). A third run uses real DDP, which starts all-reduces\n", "while the backward pass is still running (overlap), and only its total step time is measured." ], "id": "lab-5-3-parallel-12" }, { "cell_type": "code", "metadata": {}, "source": [ "GLOBAL, PER_RANK, REPS, WORLDS = 256, 64, 4, (1, 2, 4)\n", "CONFIGS = [(sc, w) for sc in (\"strong\", \"weak\", \"strong-ddp\") for w in WORLDS]\n", "rows = [] # scenario, procs, global, per-rank, repeat, compute, wait, allreduce, opt, step, load average\n", "t_start = time.time()\n", "for rep in range(REPS): # repeats are interleaved, so slow drifts of the machine hit every config alike\n", " for scenario, w in CONFIGS:\n", " per = PER_RANK if scenario == \"weak\" else GLOBAL // w\n", " mode = \"ddp\" if scenario.endswith(\"ddp\") else \"manual\"\n", " load = __import__(\"os\").getloadavg()[0]\n", " res = H.ok_results(H.launch(\"step_time\", w, (mode, per)))\n", " m = {k: statistics.mean(r[k] for r in res) for k in res[0]}\n", " rows.append([scenario, w, per * w, per, rep, m[\"compute\"], m[\"wait\"], m[\"allreduce\"], m[\"opt\"], m[\"step\"], load])\n", "print(f\"measured {len(rows)} runs in {time.time() - t_start:.0f} s; \"\n", " f\"machine load average (1 min) before the runs: min {min(r[10] for r in rows):.1f}, max {max(r[10] for r in rows):.1f} \"\n", " f\"({__import__('os').cpu_count()} logical cores)\")" ], "execution_count": null, "outputs": [], "id": "lab-5-3-parallel-13" }, { "cell_type": "code", "metadata": {}, "source": [ "def best(scenario, w):\n", " \"\"\"The repeat with the smallest step time: the run the machine disturbed least.\"\"\"\n", " return min((r for r in rows if r[0] == scenario and r[1] == w), key=lambda r: r[9])\n", "\n", "\n", "def med(scenario, w, col):\n", " return statistics.median(r[col] for r in rows if r[0] == scenario and r[1] == w)\n", "\n", "\n", "COLS = {\"compute\": 5, \"wait\": 6, \"allreduce\": 7, \"opt\": 8, \"step\": 9}\n", "print(\"CPU processes on\", MACHINE)\n", "print(\"each line: the fastest of\", REPS, \"repeats (median of 30 steps inside each repeat); all repeats are in scaling.csv\\n\")\n", "print(f\"{'scenario':11} {'procs':>5} {'global':>6} {'per-rank':>8} {'compute':>8} {'wait':>6} {'allred':>7} {'opt':>6} {'step ms':>8} \"\n", " f\"{'allreduce share':>16} {'samples/s':>10} {'median step':>12}\")\n", "csv_rows, summary = [], {}\n", "for scenario, w in CONFIGS:\n", " r = best(scenario, w)\n", " gb, pr, c, wt, ar, op, st = r[2], r[3], r[5], r[6], r[7], r[8], r[9]\n", " share = ar / st if scenario != \"strong-ddp\" else float(\"nan\")\n", " thr = gb / (st / 1000)\n", " summary[(scenario, w)] = (st, thr)\n", " sh = f\"{100 * share:15.1f}%\" if share == share else f\"{'(overlapped)':>16}\"\n", " print(f\"{scenario:11} {w:5d} {gb:6d} {pr:8d} {c:8.1f} {wt:6.1f} {ar:7.1f} {op:6.1f} {st:8.1f} {sh} {thr:10.0f} {med(scenario, w, 9):12.1f}\")\n", "for r in rows:\n", " scenario, w, gb, pr, rep, c, wt, ar, op, st, load = r\n", " share = \"\" if scenario.endswith(\"ddp\") else f\"{ar / st:.4f}\"\n", " csv_rows.append([scenario, w, gb, pr, rep, f\"{c:.3f}\", f\"{wt:.3f}\", f\"{ar:.3f}\", f\"{op:.3f}\", f\"{st:.3f}\", share,\n", " f\"{gb / (st / 1000):.1f}\", f\"{load:.1f}\"])\n", "save_csv(\"scaling.csv\",\n", " [\"scenario\", \"processes\", \"global_batch\", \"per_rank_batch\", \"repeat\", \"compute_ms\", \"wait_ms\", \"allreduce_ms\",\n", " \"opt_ms\", \"step_ms\", \"allreduce_share_of_step\", \"samples_per_s\", \"machine_load_avg_1min\"], csv_rows)\n", "\n", "print(\"\\nstrong scaling speed-up (manual) vs 1 process:\",\n", " {w: round(summary[(\"strong\", 1)][0] / summary[(\"strong\", w)][0], 2) for w in WORLDS})\n", "print(\"strong scaling speed-up (DDP) vs 1 process:\",\n", " {w: round(summary[(\"strong-ddp\", 1)][0] / summary[(\"strong-ddp\", w)][0], 2) for w in WORLDS})\n", "print(\"weak scaling throughput vs 1 process (ideal = N):\",\n", " {w: round(summary[(\"weak\", w)][1] / summary[(\"weak\", 1)][1], 2) for w in WORLDS})\n", "print(\"spread of the step time over repeats (max/min):\",\n", " {f\"{sc} N={w}\": round(max(r[9] for r in rows if r[0] == sc and r[1] == w) / min(r[9] for r in rows if r[0] == sc and r[1] == w), 2)\n", " for sc, w in CONFIGS})" ], "execution_count": null, "outputs": [], "id": "lab-5-3-parallel-14" }, { "cell_type": "code", "metadata": {}, "source": [ "try:\n", " import matplotlib\n", " matplotlib.use(\"Agg\")\n", " import matplotlib.pyplot as plt\n", "\n", " fig, ax = plt.subplots(1, 2, figsize=(10, 3.6))\n", " bottoms = [0] * len(WORLDS)\n", " for k, lab in ((\"compute\", \"forward+backward\"), (\"wait\", \"wait\"), (\"allreduce\", \"all-reduce\"), (\"opt\", \"optimizer\")):\n", " vals = [best(\"strong\", w)[COLS[k]] for w in WORLDS]\n", " ax[0].bar([str(w) for w in WORLDS], vals, bottom=bottoms, label=lab)\n", " bottoms = [b + v for b, v in zip(bottoms, vals)]\n", " ax[0].set_title(\"strong scaling, global batch 256\\n(CPU processes)\")\n", " ax[0].set_xlabel(\"processes\")\n", " ax[0].set_ylabel(\"ms per step\")\n", " ax[0].legend()\n", " ax[1].plot(WORLDS, [summary[(\"weak\", w)][1] for w in WORLDS], \"o-\", label=\"weak (per-process batch 64)\")\n", " ax[1].plot(WORLDS, [summary[(\"strong\", w)][1] for w in WORLDS], \"s-\", label=\"strong (global batch 256)\")\n", " ax[1].set_xlabel(\"processes\")\n", " ax[1].set_ylabel(\"samples per second\")\n", " ax[1].set_xticks(list(WORLDS))\n", " ax[1].legend()\n", " plt.tight_layout()\n", " plt.show()\n", "except ImportError:\n", " print(\"matplotlib not installed: skipping the plot\")" ], "execution_count": null, "outputs": [], "id": "lab-5-3-parallel-15" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 7 · Sharding the optimizer: ZeRO, in arithmetic and for real\n", "\n", "**The arithmetic.** In mixed-precision training with Adam every parameter costs 16 bytes (Ch 5.1):\n", "2 for the fp16/bf16 weight, 2 for its gradient, and `K = 12` for the optimizer's fp32 master copy\n", "(4), momentum (4) and variance (4). ZeRO removes the redundancy of keeping all of that on every\n", "worker: stage 1 shards the `K` part across the `N` workers, stage 2 also the gradients, stage 3\n", "also the weights. Memory per worker, for `Ψ` parameters:\n", "\n", "| Stage | Formula (bytes per worker) |\n", "| --- | --- |\n", "| plain data parallel | `(2 + 2 + K) Ψ` |\n", "| ZeRO-1 | `(2 + 2 + K/N) Ψ` |\n", "| ZeRO-2 | `(2 + (2 + K)/N) Ψ` |\n", "| ZeRO-3 | `(2 + 2 + K) Ψ / N` |\n", "\n", "(Activations, temporary buffers and fragmentation are not included.)" ], "id": "lab-5-3-parallel-16" }, { "cell_type": "code", "metadata": {}, "source": [ "def zero_gb(psi, n, k=12):\n", " return {\"plain data parallel\": (2 + 2 + k) * psi / 1e9,\n", " \"ZeRO-1\": (2 + 2 + k / n) * psi / 1e9,\n", " \"ZeRO-2\": (2 + (2 + k) / n) * psi / 1e9,\n", " \"ZeRO-3\": (2 + 2 + k) * psi / n / 1e9}\n", "\n", "\n", "rows = []\n", "for label, psi, n in ((\"7 B on 8 GPUs\", 7e9, 8), (\"7.5 B on 64 GPUs (the ZeRO paper's example)\", 7.5e9, 64), (\"7 B on 1 GPU\", 7e9, 1)):\n", " print(f\"\\n{label} (GB = 10^9 bytes; weights + gradients + optimizer state only)\")\n", " for stage, gb in zero_gb(psi, n).items():\n", " bpp = gb * 1e9 / psi\n", " print(f\" {stage:20s} {bpp:6.3f} bytes/param -> {gb:7.2f} GB per GPU\")\n", " rows.append((label, psi, n, stage, round(bpp, 4), round(gb, 3)))\n", "save_csv(\"zero-memory.csv\", [\"case\", \"parameters\", \"gpus\", \"stage\", \"bytes_per_param\", \"GB_per_gpu\"], rows)\n", "\n", "print(\"\\nstep-by-step for 7 B on 8 GPUs:\")\n", "psi, n = 7e9, 8\n", "print(f\" plain : 16 B x 7e9 = {16 * psi / 1e9:.0f} GB\")\n", "print(f\" ZeRO-1: (2 + 2 + 12/8) = {2 + 2 + 12 / 8} B x 7e9 = {(4 + 12 / 8) * psi / 1e9:.1f} GB\")\n", "print(f\" ZeRO-2: (2 + 14/8) = {2 + 14 / 8} B x 7e9 = {(2 + 14 / 8) * psi / 1e9:.2f} GB\")\n", "print(f\" ZeRO-3: 16/8 = {16 / 8} B x 7e9 = {16 / 8 * psi / 1e9:.0f} GB\")" ], "execution_count": null, "outputs": [], "id": "lab-5-3-parallel-17" }, { "cell_type": "markdown", "metadata": {}, "source": [ "**The real thing.** PyTorch ships ZeRO stage 1 as `ZeroRedundancyOptimizer`: each rank keeps Adam's\n", "state only for its own slice of the parameters and broadcasts the updated slice afterwards. The\n", "cell trains the same model with plain Adam and with `ZeroRedundancyOptimizer(Adam)` on 1, 2 and 4\n", "processes, counts the optimizer-state bytes each rank really holds, and checks both end at the same\n", "weights." ], "id": "lab-5-3-parallel-18" }, { "cell_type": "code", "metadata": {}, "source": [ "rows = []\n", "print(f\"{'procs':>5} {'plain Adam state/rank':>22} {'ZeRO-1 state/rank (rank 0 .. last)':>40} {'weights diff':>13}\")\n", "for w in (1, 2, 4):\n", " res = H.ok_results(H.launch(\"zero1\", w))\n", " adam_b = res[0][\"adam_state_bytes\"]\n", " z_b = [r[\"zero1_state_bytes\"] for r in res]\n", " diff = max(r[\"param_diff_zero1_vs_adam\"] for r in res)\n", " print(f\"{w:5d} {adam_b / 1e6:19.2f} MB {', '.join(f'{b / 1e6:.2f}' for b in z_b):>34} MB {diff:13.2e}\")\n", " for r_i, b in enumerate(z_b):\n", " rows.append((w, r_i, adam_b, b, f\"{diff:.3e}\"))\n", "print(f\"\\nmodel: {res[0]['n_params']:,} parameters; Adam keeps 2 float32 numbers per parameter = {res[0]['n_params'] * 8 / 1e6:.2f} MB\")\n", "save_csv(\"zero1-measured.csv\", [\"processes\", \"rank\", \"plain_adam_state_bytes\", \"zero1_state_bytes_on_this_rank\", \"weight_max_abs_diff\"], rows)" ], "execution_count": null, "outputs": [], "id": "lab-5-3-parallel-19" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 8 · FSDP on the CPU\n", "\n", "FSDP (fully sharded data parallel) is ZeRO stage 3 in PyTorch: every parameter lives sharded over\n", "the processes; before a layer runs, an all-gather assembles its full weights, and after use they are\n", "freed again; gradients are reduce-scattered. The cell uses the current API, `fully_shard`, once as\n", "the documentation shows it (no device given) and, if that fails on your machine, again with an\n", "explicit CPU device mesh. It then compares the all-gathered gradients with the single-process\n", "gradients and reports how many parameters each rank really stores." ], "id": "lab-5-3-parallel-20" }, { "cell_type": "code", "metadata": {}, "source": [ "res = H.launch(\"fsdp\", 2)\n", "if all(r[\"ok\"] for r in res):\n", " r0 = res[0][\"result\"]\n", " print(\"first attempt, default device:\", r0.get(\"default\", \"FAILED\"))\n", " if r0[\"default_error\"]:\n", " print(\" error on this machine:\", r0[\"default_error\"])\n", " print(\"second attempt, explicit CPU mesh: worked\")\n", "else:\n", " print(\"FSDP failed on this PyTorch build:\", res[0][\"error\"])\n", "rows = []\n", "for w in (2, 4):\n", " res = H.launch(\"fsdp\", w)\n", " if all(r[\"ok\"] for r in res):\n", " rs = [r[\"result\"] for r in res]\n", " local = [r[\"local_params\"] for r in rs]\n", " print(f\"{w} processes: params stored per rank {local} of {rs[0]['total_params']:,}; \"\n", " f\"first weight shard shape {rs[0]['local_shape_first_weight']} of [1024, 256]; \"\n", " f\"max |gradient - single-process gradient| = {max(r['grad_max_abs_diff'] for r in rs):.2e}\")\n", " rows.append((w, rs[0][\"total_params\"], max(local), f\"{max(r['grad_max_abs_diff'] for r in rs):.3e}\"))\n", " else:\n", " print(f\"{w} processes: FSDP not supported here ->\", res[0][\"error\"])\n", "if rows:\n", " save_csv(\"fsdp-check.csv\", [\"processes\", \"total_params\", \"max_params_stored_on_one_rank\", \"grad_max_abs_diff\"], rows)" ], "execution_count": null, "outputs": [], "id": "lab-5-3-parallel-21" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 9 · Tensor parallelism by hand: one MLP split over two processes\n", "\n", "An MLP block computes `Y = GELU(X A) B`. Split `A` by **columns** and `B` by **rows**:\n", "process `r` owns `A_r` (`[d, h/N]`) and `B_r` (`[h/N, d]`). Each computes `H_r = GELU(X A_r)`\n", "(every column of `A` makes one column of `H`, so no communication is needed) and `Y_r = H_r B_r`,\n", "a *partial sum* of `Y`. One all-reduce adds the partial sums. In the backward pass the gradient\n", "with respect to `X` is also a sum over processes, so there is one more all-reduce. Those two are\n", "Megatron-LM's `g` and `f` operators; `CopyToTP` and `ReduceFromTP` in the helper module write them\n", "as `autograd.Function`s. Check everything against the unsplit layer, then break the backward\n", "all-reduce on purpose." ], "id": "lab-5-3-parallel-22" }, { "cell_type": "code", "metadata": {}, "source": [ "rows = []\n", "for w in (2, 4):\n", " res = H.ok_results(H.launch(\"tp_mlp\", w))\n", " r = res[0]\n", " worst = {k: max(x[k] for x in res) for k in r if k.endswith(\"_diff\")}\n", " print(f\"{w}-way split: parameters per rank {r['params_per_rank']:,} of {r['params_unsplit']:,}; \"\n", " f\"all-reduces: forward {r['fwd_allreduce']} ({r['fwd_bytes']:,} bytes), backward {r['bwd_allreduce']} ({r['bwd_bytes']:,} bytes)\")\n", " for k, v in worst.items():\n", " print(f\" max |split - unsplit| {k:22s} {v:.2e}\")\n", " rows.append((w, r[\"params_per_rank\"], r[\"params_unsplit\"], r[\"fwd_allreduce\"], r[\"bwd_allreduce\"], r[\"fwd_bytes\"],\n", " f\"{max(worst.values()):.3e}\"))\n", "res = H.ok_results(H.launch(\"tp_mlp\", 2, (64, 256, False)))\n", "print(\"\\nbackward all-reduce removed (2-way):\", {k: f\"{max(x[k] for x in res):.2e}\" for k in (\"forward_diff\", \"input_grad_diff\", \"A_shard_grad_diff\")})\n", "save_csv(\"tensor-parallel-check.csv\",\n", " [\"ways\", \"params_per_rank\", \"params_unsplit\", \"forward_allreduces\", \"backward_allreduces\", \"bytes_per_forward_allreduce\",\n", " \"worst_max_abs_diff\"], rows)" ], "execution_count": null, "outputs": [], "id": "lab-5-3-parallel-23" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 10 · Pipeline parallelism: the bubble\n", "\n", "Pipeline parallelism cuts the model into `p` consecutive *stages* on `p` workers, and cuts each batch\n", "into `m` *micro-batches* that flow through like items on a conveyor belt. At the start the last\n", "stages have nothing to do, and at the end the first stages are finished: that idle time is the\n", "**bubble**. The cell draws the forward schedule of a GPipe-style pipeline on a grid (rows = stages,\n", "columns = time slots, digits = which micro-batch is being processed, `.` = idle) and counts the idle\n", "slots, then compares with the formula `(p-1) / (m+p-1)`. (This is a schedule simulation: no processes\n", "are involved, and nothing about its timing is measured.)" ], "id": "lab-5-3-parallel-24" }, { "cell_type": "code", "metadata": {}, "source": [ "def gpipe_grid(p, m):\n", " T = m + p - 1\n", " grid = [[\".\"] * T for _ in range(p)]\n", " for s in range(p):\n", " for j in range(m):\n", " grid[s][s + j] = str(j % 10)\n", " idle = sum(row.count(\".\") for row in grid)\n", " return grid, idle / (p * T)\n", "\n", "\n", "grid, frac = gpipe_grid(4, 4)\n", "print(\"4 stages, 4 micro-batches (forward pass only):\")\n", "for s, row in enumerate(grid):\n", " print(f\" stage {s}: {' '.join(row)}\")\n", "print(f\" idle fraction counted: {frac:.4f}; formula (p-1)/(m+p-1) = {3 / 7:.4f}\\n\")\n", "rows = []\n", "print(f\"{'stages p':>8} {'micro-batches m':>16} {'bubble (counted)':>17} {'(p-1)/(m+p-1)':>14}\")\n", "for p in (2, 4, 8):\n", " for m in (1, 4, 8, 16, 32, 64):\n", " _, f = gpipe_grid(p, m)\n", " formula = (p - 1) / (m + p - 1)\n", " assert abs(f - formula) < 1e-12\n", " rows.append((p, m, round(f, 6), round(formula, 6)))\n", " print(f\"{p:8d} {m:16d} {f:17.4f} {formula:14.4f}\")\n", "save_csv(\"pipeline-bubble.csv\", [\"stages_p\", \"micro_batches_m\", \"idle_fraction_counted\", \"formula_p_minus_1_over_m_plus_p_minus_1\"], rows)" ], "execution_count": null, "outputs": [], "id": "lab-5-3-parallel-25" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 11 · Checkpoint\n", "\n", "Compare with your own run (the numbers that depend on your machine are the times; the differences\n", "and the memory counts should agree to the order of magnitude shown in Lab 5.3's page)." ], "id": "lab-5-3-parallel-26" }, { "cell_type": "code", "metadata": {}, "source": [ "ddp = [r for r in csv.DictReader(open(out_dir() / \"ddp-equivalence.csv\"))]\n", "print(\"DDP vs one process on the full batch (max abs gradient difference):\")\n", "for r in ddp:\n", " print(f\" {r['dtype']:8s} {r['processes']} process(es): {r['grad_max_abs_diff']}\")\n", "print(\"ring all-reduce: every worker sent\", sent[0], \"chunks = 2(N-1) for N =\", N)\n", "print(\"ZeRO-1/2/3 for 7 B on 8 GPUs (GB per GPU):\", [round(v, 2) for k, v in zero_gb(7e9, 8).items() if k != \"plain data parallel\"])\n", "print(\"pipeline bubble, p = 4: m = 4 ->\", round(3 / 7, 4), \"; m = 16 ->\", round(3 / 19, 4))" ], "execution_count": null, "outputs": [], "id": "lab-5-3-parallel-27" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 12 · Explore\n", "\n", "Change one knob at a time and write one sentence on what changed and why.\n", "\n", "| Knob | Try | Question |\n", "| --- | --- | --- |\n", "| message size | in section 4 add `2**26` floats (256 MB) | Does the bus bandwidth keep rising, flatten, or fall once the message no longer fits in the CPU cache? |\n", "| model size | in `helpers.make_model` set `HIDDEN = 256`, then `2048`, and rerun section 6 | When does the all-reduce share grow, and when does it vanish? What does that say about small models on many GPUs? |\n", "| batch size | strong scaling with a global batch of `64` and of `1024` | Why does a small per-process batch hurt scaling? |\n", "| processes | rerun section 6 with 8 processes | The M1 has 4 fast and 4 slow cores: what happens to compute time per process once the slow cores are used? |\n", "| ZeRO | add `torch.optim.SGD` (no state) to section 7 | How many bytes of optimizer state remain, and what does that tell you about why Adam's `K = 12` matters? |\n", "| tensor parallelism | try a 4-way split with `h = 250` | What error do you get, and which rule of the split does it break? |\n", "| pipeline | add the backward pass to the grid (assume it takes twice as long as the forward) | Does the bubble fraction change? What does the *memory* of the micro-batches waiting for their backward pass cost? |" ], "id": "lab-5-3-parallel-28" }, { "cell_type": "code", "metadata": {}, "source": [ "# your experiments here" ], "execution_count": null, "outputs": [], "id": "lab-5-3-parallel-29" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 13 · Failure playground\n", "\n", "Three distributed-training bugs. For each: run it, read the symptom, find the cause, fix it. Hints\n", "are in Review 5.3; answers are not. Every launch has a hard timeout, so the notebook cannot hang." ], "id": "lab-5-3-parallel-30" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 13a · The replicas that never agree\n", "\n", "A colleague writes the all-reduce by hand (average the gradients, step) and builds the model on\n", "each rank with `seed = 100 + rank`, \"so the ranks are independent\"." ], "id": "lab-5-3-parallel-31" }, { "cell_type": "code", "metadata": {}, "source": [ "rows = []\n", "for mode in (\"diff_seed_manual\", \"same_seed_manual\", \"diff_seed_ddp\"):\n", " res = H.ok_results(H.launch(\"fail_seeds\", 2, (mode,)))\n", " r = res[0]\n", " print(f\"13a {mode:18s} spread of weights between rank 0 and 1 after 50 steps = {r['param_spread']:.3e}; \"\n", " f\"held-out loss per rank = {r['eval_loss_per_rank']}\")\n", " rows.append((mode, f\"{r['param_spread']:.4e}\", r[\"eval_loss_per_rank\"][0], r[\"eval_loss_per_rank\"][1]))\n", "save_csv(\"failure-seeds.csv\", [\"mode\", \"weight_spread_between_ranks\", \"eval_loss_rank0\", \"eval_loss_rank1\"], rows)" ], "execution_count": null, "outputs": [], "id": "lab-5-3-parallel-32" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: the ranks hold different weights at the end and report different held-out losses, although\n", "every step averaged the gradients correctly. Why does averaging gradients not bring the replicas\n", "together? Why does the third line (real DDP, same different seeds) come out different from the first?\n", "(Hint: look at what DDP does when you wrap the model.)" ], "id": "lab-5-3-parallel-33" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 13b · Every rank sees the same batch\n", "\n", "A colleague gives every rank the same shuffle and forgets to offset by the rank (`start = step * per_rank`\n", "instead of `step * world * per_rank + rank * per_rank`)." ], "id": "lab-5-3-parallel-34" }, { "cell_type": "code", "metadata": {}, "source": [ "rows = []\n", "for shard in (False, True):\n", " res = H.ok_results(H.launch(\"fail_shard\", 4, (shard,)))\n", " r = res[0]\n", " label = \"sharded\" if shard else \"NOT sharded\"\n", " print(f\"13b {label:12s} unique examples per step = {r['unique_samples_per_step']:3d}; unique examples in 40 steps = \"\n", " f\"{r['unique_samples_total']:4d}; steps per epoch = {r['steps_per_epoch']:3d}; held-out loss {r['eval_loss']:.4f}, accuracy {100 * r['eval_acc']:.1f}%\")\n", " rows.append((label, r[\"unique_samples_per_step\"], r[\"unique_samples_total\"], r[\"steps_per_epoch\"], round(r[\"eval_loss\"], 4), round(r[\"eval_acc\"], 4)))\n", "save_csv(\"failure-shard.csv\", [\"data\", \"unique_examples_per_step\", \"unique_examples_in_40_steps\", \"steps_per_epoch\", \"eval_loss\", \"eval_acc\"], rows)" ], "execution_count": null, "outputs": [], "id": "lab-5-3-parallel-35" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: 4 processes, no error, same step time as the sharded run, but the model learned less. How many\n", "distinct examples did 4 processes see per step, versus what you paid for? What does an \"epoch\" mean\n", "in the unsharded case, and how much work is repeated?" ], "id": "lab-5-3-parallel-36" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 13c · A collective that only some ranks call\n", "\n", "A colleague logs the average loss with `if rank == 0: dist.all_reduce(loss)`. The process group has a\n", "5-second timeout here (in real jobs the default is much longer, and a stuck job can burn GPU-hours)." ], "id": "lab-5-3-parallel-37" }, { "cell_type": "code", "metadata": {}, "source": [ "t0 = time.time()\n", "res = H.launch(\"fail_deadlock\", 2, (False,), collective_timeout=5, hard_timeout=60)\n", "print(f\"13c wall time {time.time() - t0:.1f} s\")\n", "for r_i, r in enumerate(res):\n", " print(f\" rank {r_i}:\", r[\"result\"] if r[\"ok\"] else r[\"error\"])" ], "execution_count": null, "outputs": [], "id": "lab-5-3-parallel-38" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: nothing happens for a while, then an error mentions a timeout. Which rank was waiting, and for\n", "whom? Why did no other rank report anything? Fix it, then run the cell below." ], "id": "lab-5-3-parallel-39" }, { "cell_type": "code", "metadata": {}, "source": [ "res = H.launch(\"fail_deadlock\", 2, (True,), collective_timeout=5, hard_timeout=60)\n", "for r_i, r in enumerate(res):\n", " print(f\"13c fixed, rank {r_i}:\", r[\"result\"] if r[\"ok\"] else r[\"error\"])" ], "execution_count": null, "outputs": [], "id": "lab-5-3-parallel-40" }, { "cell_type": "code", "metadata": {}, "source": [ "print(\n", " \"Versions tested:\",\n", " f\"Python {platform.python_version()},\",\n", " f\"PyTorch {torch.__version__},\",\n", " end=\" \",\n", ")\n", "try:\n", " import matplotlib\n", " print(f\"matplotlib {matplotlib.__version__},\", end=\" \")\n", "except ImportError:\n", " pass\n", "print(f\"{platform.system()} {platform.machine()} (gloo, {__import__('os').cpu_count()} logical cores, CPU processes, launcher: torch.multiprocessing.start_processes with spawn)\")" ], "execution_count": null, "outputs": [], "id": "lab-5-3-parallel-41" } ] }