Training (DDP) 11 labs
Training 1 · The cluster: GPUs inside a node vs across nodes
Big picture first. A cluster = several nodes (servers). Each node here has 8 GPUs. Inside a node, GPUs talk over NVLink (a direct GPU-to-GPU cable; an NVSwitch connects all 8). Between nodes, data has to leave the GPU, go over PCIe to the node's network card (NIC), through a switch, and into the other node the same way. NCCL picks the path for you. Pick a case:
So what: GPUs in the same node share a fast road (NVLink, hundreds of GB/s). GPUs in different nodes use a much slower road (the network: 100–400 Gbit/s per NIC = tens of GB/s, plus more latency). So a multi-GPU job is fastest when it uses as few nodes as possible (2 × 8 rather than 4 × 4). That's why a job may ask for whole nodes, and why the scheduler's placement matters (Kubernetes 3–4).
Training 2 · One DDP training step: where does the data go, and who calls whom?
4 ranks (one process + one GPU each, torchrun --nproc_per_node=4), a 6-layer model (L1–L6), 3 gradient buckets. The big map is rank 0: CPU (processes + RAM) on top, GPU (memory + 2 streams) below, joined by PCIe. The cards at the bottom are ranks 1–3, doing the same steps at the same time, so you can see what's different (data, gradients) and what's the same (weights). The comm stream is where NCCL, the GPU-to-GPU communication library, runs all-reduce and broadcast. Each press runs one part of the loop: the ● shows data moving, calls shows which functions run, in order, and reads shows which settings they read.
So what: data is built on the CPU (sampler → workers → pinned RAM), crosses PCIe once per batch at .cuda(), and from then on the tensors stay in GPU memory (the CPU just drives the loop and launches kernels). backward() is run by the autograd engine; DDP joins only through its hooks, and its Reducer hands full buckets to NCCL, which sends them on a separate stream while compute continues. optimizer.step() doesn't involve DDP or any communication.
Training 3 · Who drives for xb, yb in loader?
Step through one rank (rank 0 of 2, batch_size = 3). Watch who asks whom.
So what: the Dataset only answers "give me sample i". Picking indices is the sampler's job; collecting and stacking is the DataLoader's job.
Training 4 · What changes when you remove the DistributedSampler?
Two ranks, a dataset of 8 samples. Toggle the sampler and run one epoch.
So what: without a sampler there's no error — every rank processes the whole dataset (with shuffle=False: identical batches → identical gradients, so averaging changes nothing). Same model as one GPU, no speedup.
Training 5 · What does set_epoch change — and why don't ranks overlap?
10 samples (1–10), 2 ranks. DistributedSampler does 3 things on every rank: ① start from the full list, ② shuffle it with a seed, ③ keep only its own positions (rank 0: 1st, 3rd, 5th… · rank 1: 2nd, 4th, 6th…). The split is by position, not by value.
So what: every rank shuffles the whole list by itself — nobody sends it the list. Because they all use the same seed, they all get the same order, and taking different positions of the same order can't overlap. set_epoch(e) changes that shared seed each epoch, so each rank gets different samples every epoch — still disjoint.
Training 6 · What do DataLoader workers do while the GPU trains?
One rank. Loading a batch takes 2 units of CPU time; training on it takes 1 unit of GPU time.
So what: workers are helper processes inside each rank. They run dataset[i] + collate ahead of time into a queue, so the GPU doesn't wait. Not ranks — rank count is set by torchrun.
Training 7 · Where did the 24 seconds go?
Proportions from my dataloader_benchmark.py run (2 epochs, 2 workers). Toggle the setting and play.
So what: True = workers persist, so the restart blocks disappear. Always check sum(step times) ≈ total before trusting a throughput number.
Training 8 · Why zero_grad() every step?
Three training steps. Each backward() produces a fresh gradient — watch what lands in .grad.
So what: backward() adds (+=) into .grad. Without clearing, step 3 updates with g1+g2+g3 instead of g3 — stale gradients from older weights mixed in, and a step that keeps growing. (Gradient accumulation uses this on purpose: skip zero_grad for N micro-batches, then step once.)
Training 9 · Buckets & hooks: when does all-reduce start?
First: who exchanges gradients? A rank = one training process. On GPUs it's one rank per GPU, but a rank can also run on the CPU. Each rank trains on different samples, so each gets a different gradient. All-reduce turns them into the same average. Pick a setup:
compute = backward kernels on the GPU (producer). comm = the GPU's comm stream, where NCCL exchanges a full bucket with the other GPUs (consumer). The data travels over NVLink between GPUs in the same machine, or over the network card (InfiniBand / Ethernet) between machines. They run at the same time on separate GPU streams. New to hooks/NCCL? Do Training 2 first.
NCCL (NVIDIA Collective Communications Library) is the library that actually moves the data between GPUs. It runs collective operations such as all-reduce and broadcast as GPU kernels and picks the fastest path (NVLink, PCIe or the network). DDP's Reducer only asks for "all-reduce bucket A"; NCCL does it. You select it with init_process_group(backend="nccl").
A 6-layer model. backward() runs from the last layer (L6) to the first (L1); each layer's gradient takes 1 time unit. Every all-reduce costs a fixed 1.1 units of overhead + 0.25 per layer it carries. One press = one layer's gradient is ready.
Bucket size never removes the all-reduce. Every bucket is still sent, every step. What bucket size changes is when each send happens: during backward (hidden, free) or after it (exposed, the GPU waits). The gradients and the final weights are the same for every setting.
So what: a hook is a function autograd calls the moment one parameter's gradient is ready. DDP's hook drops it into its bucket; when a bucket is full, it launches that bucket's all-reduce asynchronously while backward keeps computing earlier layers. Communication overlaps computation. Too few buckets = no overlap; too many = per-call overhead piles up (bucket_cap_mb, default 25 MB, sets the size). "Full" means every gradient assigned to that bucket has arrived — DDP assigns layers to buckets up front (closing a bucket once it reaches the cap, so one can be a bit bigger than the cap), and the last bucket is sent at the end of backward even if it is small. A layer is never split across buckets.
Training 10 · Gradient accumulation: all-reduce every micro-batch, or once?
Goal: one weight update from 128 samples per rank. 2 ranks; each backward sends gradients in 2 buckets (buckets: Training 9). Two separate knobs: accumulation (feed 32 at a time, step every 4) cuts memory; no_sync cuts communication.
- iteration
- one pass of the
forloop = one micro-batch (32 samples) = 1 forward + 1 backward. Press Next once = one iteration. - optimizer step
- one weight update (
optimizer.step()). With ACCUM = 4 it happens once every 4 iterations. - all-reduce calls
- happen inside backward, one per bucket. So: calls = (backwards that sync) × (buckets) — here buckets = 2.
So what: A is the ideal, but 128 may not fit in GPU memory. B fits (32 at a time) but DDP syncs after every backward → 4× the communication. C keeps B's memory and gets back to A's communication: .grad sums locally because backward adds (+=), so one all-reduce of the sum gives the same average. Keep the last micro-batch outside no_sync, or the ranks never sync.
Training 11 · Checkpoint & resume: who writes, who reads, what's inside
4 ranks train for 4 epochs; a checkpoint is saved at the end of each epoch. In epoch 2 every rank dies. Press Next to see the save, the barrier, the crash and the resume. The two bug buttons show the classic mistakes.
So what: save 4 things (weights from ddp.module, optimizer state, epoch, RNG state); rank 0 writes, then a barrier; on resume every rank reads the same file and continues at saved epoch + 1. You lose only the work since the last save.
Kubernetes 5 labs
Kubernetes 1 · From kubectl apply to traffic: who reads which field?
Namespace k1-demo already has a ResourceQuota, a LimitRange and a PriorityClass. You apply a Deployment (3 replicas) and a Service. The order list shows which layer acts first for every Pod. Each press = one component doing its job: the map shows who, the YAML below highlights the fields it reads, and the box says what you see if it fails.
So what: every K8s answer has three parts: who acts (API server admission / a controller / the scheduler / the kubelet / kube-proxy), which field it reads, and where the failure shows up. Admission refuses → Forbidden, nothing created (if a controller made the request, look at its Events). Scheduler can't place → Pending. kubelet trouble → ImagePullBackOff, CrashLoopBackOff, OOMKilled.
Kubernetes 2 · A Pod isn't running — who said no?
Namespace with a ResourceQuota of 1 CPU (0.6 already used by other Pods). The only node has 8 allocatable CPUs, 5 already requested by other Pods → 3 unrequested. Pick a request and submit.
So what: over the quota → the API server rejects it (Forbidden) and the Pod is never created. Fits the quota but no node has room → the Pod exists and stays Pending; kubectl describe pod shows FailedScheduling.
Kubernetes 3 · Where do Pods land? Spreading vs bin packing
Setup: 4 nodes × 8 GPUs = 32 GPUs, all free. Twelve 1-GPU Pods arrive one by one, then a 16-GPU training job (DDP). For every Pod the scheduler does two things: filter (which nodes have enough free GPUs?) and score (of those, which is best?). The scoring policy decides the picture. Pick a policy and a job shape, then press Next.
- spreading
- put each Pod on the emptiest node (Kubernetes default:
LeastAllocated). Spreads load, but leaves a little free space on every node. - bin packing
- put each Pod on the fullest node that still fits (
MostAllocated, set in the scheduler's NodeResourcesFit plugin). Keeps whole nodes empty. - fragmentation
- enough free GPUs in total, but scattered in pieces too small for the job. The free GPUs exist, yet the job can't use them.
So what: the same 12 small Pods leave very different free space. Spreading → 5 free GPUs on every node: 20 free, but no node has 8 → a 2 × 8 job stays Pending (fragmentation). Bin packing → 2 whole nodes free → it runs. Asking for 4 × 4 instead fits the scattered space, but then more of its all-reduce crosses the slower network (Training 1). Trade-off: start now vs run fast.
Kubernetes 4 · A job of many Pods: one at a time vs gang scheduling
Setup: 4 nodes × 8 GPUs. Small, long-running jobs already use 3 GPUs on every node → 5 free per node, 20 free. Two DDP jobs, A and B, arrive together. Each is 4 Pods × 4 GPUs = 16 GPUs, and a DDP job can't train until all of its Pods are running (every rank waits for the others at start-up). The default scheduler places one Pod at a time and doesn't know Pods belong together.
- partial allocation
- some of a job's Pods are placed, the rest wait. The placed ones hold their GPUs idle.
- deadlock
- two jobs each hold part of what they need and wait for each other's GPUs → neither ever starts.
- gang scheduling
- all-or-nothing: place every Pod of a job at once, or none of them (Kueue, Volcano, or the scheduler's coscheduling plugin with a PodGroup).
- reservation / preemption
- so a big job isn't skipped forever: reserve GPUs for it as they free up, or preempt (evict) lower-priority Pods (PriorityClass).
So what: one Pod at a time, A and B each get half their Pods: 16 GPUs are held but idle, and both wait for each other forever (deadlock). Gang scheduling asks "do all 4 Pods fit right now?" A does → it starts whole. B doesn't → it waits holding nothing, so the free GPUs stay usable by small jobs. When A finishes, B starts. Add reservation or priority so B can't be skipped forever.
Kubernetes 5 · Delete a Pod, crash a container, send a request
A Deployment (replicas: 3) behind a ClusterIP Service. Try each button.
So what: deleted Pod → the ReplicaSet controller (the Deployment owns a ReplicaSet) creates a new Pod (new name, same label) · crashed process → the kubelet restarts the container (same name, RESTARTS +1) · the Service routes by label, so the client never notices.
Linux 3 labs
Linux 1 · What each vmstat number is, in the hardware
One machine with 4 CPU cores, RAM and a disk. RAM is managed in pages (4 KB blocks). Pick a column: the map shows what physically happens (tasks on cores, pages moving between RAM and disk), and the vmstat line on top shows which number it makes go up.
So what: vmstat counts three kinds of things. Tasks: r = running or waiting for a core, b = stuck waiting for the disk. Time: us / sy / id / wa = how each CPU second was spent. Pages and blocks moving: bi / bo = file data between disk and RAM, si / so = process memory pushed out to swap and pulled back. Read them together, then practise in Linux 3.
Linux 2 · Where network traffic goes: socket → TCP → interface → NIC
A slow download (e.g. docker pull). Data comes from a remote server, through a switch, into your machine's network card, and up through the kernel to the program. Each tool looks at a different layer: pick one.
So what: slow transfer → ask two questions. Is the pipe full? (sar -n DEV on the interface, compared with the link speed.) Or is one conversation struggling? (ss -ti per connection: rtt, cwnd, retransmits; sar -n ETCP for retransmits machine-wide.)
Linux 3 · Read a vmstat 1 line — what's the bottleneck?
An 8-core machine. Pick a scenario, guess the bottleneck from the numbers, then reveal.
So what: vmstat says which resource; then top / pidstat -u -t say which process and thread, and strace says which syscall. Confirm, fix, measure again.