Back to the meetup notes
Learner kit

Systems under the model

A study guide built from the PyTorch × Hugging Face meetup in Bengaluru (25 July 2026), the five talk decks and other material from around the web.

How to use it: go in order. Each module explains the idea first, with a picture, worked numbers, code you can run and a small calculator. Then come the core ideas, things to try, and questions with answers. The links at the end of each module are for going deeper, so you can read the module without leaving this page. I checked that every link opens, on 10 November 2026.

Honest note: I wrote this from the talks and from the sources linked here. Where a number comes from a slide or a company blog, I say so. Treat those as claims to check, not facts.

0 of 7 modules done

The 8-week plan

About 6 to 8 hours a week.

WhenWhatGoal
Week 1Module 0 and 1Foundations and profiling. Finish the size 64/1024/4096 experiment.
Week 2Module 2torch.compile, Triton tutorials 1 to 3, load one HF kernel.
Weeks 3 and 4Module 3Inference. Read the NVIDIA overview, PagedAttention, the SGLang and vLLM prefix pages. Run the vLLM vs SGLang test.
Week 5Module 4RL environments. Build and red-team one small environment.
Weeks 6 and 7Module 5Distributed training. Do the four stages. Reshard a checkpoint.
Week 8Module 6 and a capstoneCommunication, then pick one capstone below.

Modules

0GPU performance basicsabout 5 hours

Every talk that night came back to one question: where does the time go? Compute, memory, or just launching work? Learn this first and the rest is easier.

The intuition

A GPU can do far more arithmetic per second than it can fetch numbers from memory. So every operation is held up by one of three things.

  • Compute. The maths units are the limit. This is what you want for big matmuls.
  • Memory. The units wait for data from HBM. Element-wise ops and decoding live here.
  • Overhead. The GPU is idle because the CPU has not yet handed it the next kernel. Tiny ops live here.

For the first two, count two things for an operation: the FLOPs it does, and the bytes it moves. Their ratio is the arithmetic intensity. The GPU has its own ratio, peak FLOP/s divided by peak bytes/s, called the ridge point. Below the ridge you wait on memory. Above it you wait on maths. That picture is the roofline.

0.11101001000100000.11101001000memory-boundcompute-boundfp32 adddecode, batch 1decode, batch 64matmul 4096arithmetic intensity (FLOPs per byte)TFLOP/s you can reach
A roofline for an H100 (bf16, about 989 TFLOP/s and 3.35 TB/s). The slope is memory, the flat part is compute, and they meet near 295 FLOPs per byte. Dots show where common jobs land.

Worked numbers

H100 ridge point989 TFLOP/s ÷ 3.35 TB/s≈ 295 FLOPs/byte
fp32 add, one element1 FLOP ÷ (4 + 4 + 4 bytes)0.083, far below the ridge: memory-bound
bf16 matmul, N × N2N³ FLOPs ÷ (3 × N² × 2 bytes)N / 3
N = 6464 / 321: memory-bound on paper, launch-bound in practice
N = 40964096 / 31,365: compute-bound
decode, batch 1, 8B model2 FLOPs per weight ÷ 2 bytes per weight≈ 1: memory-bound
best-case decode speed16 GB of weights ÷ 3.35 TB/s = 4.8 ms≈ 209 tokens/s for one stream
decode, batch Beach weight is read once for B tokensintensity ≈ B, so you need B near 295 to reach the ridge

That last line is why serving engines batch requests: the weights are read once per step, however many requests ride along.

Try it: a square matmul in bf16 on an H100N = 4096
arithmetic intensity
maths time (at peak)
memory time (at peak)
launch cost (assumed)
maths
memory
launch

Bars use a log scale. The launch cost is an assumed 8 µs per kernel. Real kernels reach only part of the peak numbers, so treat the verdict as the shape, not a measurement.

Code: find your own knee

Run this on any CUDA GPU. Time stays almost flat at small sizes (launch cost), then grows. TFLOP/s climbs and then levels off below the peak. Where it levels off is your GPU’s compute-bound region.

import torch

def bench(n, iters=50):
    a = torch.randn(n, n, device="cuda", dtype=torch.bfloat16)
    b = torch.randn(n, n, device="cuda", dtype=torch.bfloat16)
    for _ in range(10): a @ b                         # warm-up
    s, e = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
    s.record()
    for _ in range(iters): a @ b
    e.record(); torch.cuda.synchronize()              # wait for the GPU, then read the clock
    ms = s.elapsed_time(e) / iters
    return ms, 2 * n**3 / (ms * 1e-3) / 1e12          # time, TFLOP/s

for n in (64, 256, 1024, 4096, 8192):
    ms, tf = bench(n)
    print(f"N={n:5d}  {ms*1e3:9.1f} us  {tf:7.1f} TFLOP/s")

The core ideas, in short

  • Arithmetic intensity is FLOPs per byte moved. Low means memory-bound. High means compute-bound. This is the roofline idea.
  • Launch overhead. The CPU queues every kernel. Tiny kernels leave the GPU idle.
  • The memory ladder: registers, shared memory, L2, then HBM. Moving data costs more than the maths. Fusing ops avoids trips to HBM.
  • Orders of magnitude: On an H100, HBM moves about 3.35 TB/s. NVLink moves about 900 GB/s in total. A 400 Gb/s NIC moves about 50 GB/s. Each step out is slower.

Try it

  1. Work out the best-case decode speed for an 8B model on an H100: weights in bf16 are about 16 GB, bandwidth is about 3.35 TB/s.
  2. Time torch.matmul on square matrices of size 64, 256, 1024, 4096 with CUDA events. Plot time against size. Find where the line stops being flat. That is the launch-bound region.
  3. Compute the arithmetic intensity of an element-wise add in fp32 (read 2 numbers, write 1, do 1 FLOP). Then of a big matmul. Compare.

Check yourself tap a question for the answer

  • Why is decode memory-bound and prefill compute-bound?

    Decode multiplies one token’s vector by every weight matrix, so each weight is read once for about 2 FLOPs. That is roughly 1 FLOP per byte, far under the ridge. In prefill a prompt of T tokens reuses each weight T times, so the intensity grows with T and the work is matrix times matrix.

  • What does fusing two ops save, and where does the saving come from?

    It saves the round trips of the in-between results. Unfused, every op writes its result to HBM and the next op reads it back. Fused keeps the values in registers. The FLOPs stay the same. The bytes drop.

  • The add above has 1 FLOP per 12 bytes. Is it compute-bound or memory-bound on a modern GPU? Why? (Hint: an H100 needs about 295 FLOPs per byte in bf16 to be compute-bound.)

    Memory-bound. It is 1 FLOP per 12 bytes, about 0.083, which is thousands of times under the 295 ridge. The time is set by moving 12 bytes per element at 3.35 TB/s, not by the add.

Questions that come up tap one to open it

Why is prefill compute-bound and decode memory-bound?

Because of how much work each byte of weights does. In prefill, one read of the weights serves thousands of tokens. In decode, it serves one.

Think of FLOPs per byte moved. This is called arithmetic intensity.

  • Prefill: the whole prompt goes through together. The maths is matrix times matrix. Each weight is loaded once and used for many tokens. The tensor cores stay busy, so you are compute-bound.
  • Decode: one new token per request per step. The maths is matrix times vector. You load all the weights (and the whole KV cache) to make a single token. The GPU waits on memory.

A back-of-envelope check. Llama-3-8B in bf16 is about 16 GB of weights. An H100 SXM moves about 3.35 TB/s. One decode step must read 16 GB, so it takes at least about 4.8 ms. That is roughly 200 tokens per second for one request. This is an upper limit, and real runs reach less. Adarsh's slide showed about 209 tok/s for plain generate(). Check which GPU and precision it used before comparing.

Batching is the fix. If 64 requests share each weight read, you get close to 64 times more tokens for the same read. This goes on until the KV cache reads start to dominate. Another way to see it: an H100 can do roughly 300 bf16 FLOPs for every byte it reads from memory. Decode at batch 1 does about 1. So you need a very large batch before decode turns compute-bound. That is why continuous batching and cache memory matter so much.

Sources: NVIDIA: mastering LLM inference optimization · Transformer inference arithmetic · Making deep learning go brrr

Go deeper read in this order

  1. Making Deep Learning Go Brrrr From First Principles Start here. Compute, memory and overhead, with fusion. It is long, but worth it.
  2. Transformer Inference Arithmetic Count FLOPs and bytes for a Transformer by hand. It uses A100 numbers.
  3. How to Scale Your Model A free book on rooflines, sharding and communication. Mostly TPUs, so treat it as optional and come back later. Chapter 12 covers GPUs.
  4. NVIDIA: GPU performance background Plain explanations of tensor cores, memory, arithmetic intensity, and math-bound versus memory-bound work.
  5. Modal GPU glossary Short linked definitions of SMs, the memory hierarchy, roofline and arithmetic intensity. Its arithmetic-intensity page says an H100 needs about 295 FLOPs per byte in bf16 to be compute-bound.
  6. GPU MODE lectures Talks on profiling, CUDA, Triton and more. Pick what you need.
1Profiling PyTorchabout 4 hours

Aritra's rule: what you cannot profile, you cannot optimize. Profiling turns guesses into evidence.

The intuition

Think of the CPU as a cook writing orders and the GPU as a kitchen working through them. When Python calls torch.matmul on a CUDA tensor, it only queues a kernel on a stream and returns at once. The GPU runs it later. Two things follow.

  • A plain time.time() around a CUDA op measures the queueing, not the work. You must synchronize, or use CUDA events.
  • If each kernel is tiny, the cook cannot write orders as fast as the kitchen finishes them, and the GPU sits idle. That is overhead bound.
Overhead bound (tiny matrices)CPUGPUThe CPU is busy launching. The GPU runs a sliver, then waits.Compute bound (big matrices)CPUGPUOne launch, then the GPU is busy while the CPU runs ahead.
Blue is CPU work (launching kernels). Green is GPU work. The gaps in the GPU lane are idle time.

The profiler records both lanes. You can run it in a loop, so it needs a schedule: skip some steps, warm up, then record a few.

step 0waitskipped
step 1warmuptraced, then dropped
step 2activerecorded
step 3activerecorded
step 4activerecorded
wait=1, warmup=1, active=3: the five steps of the loop, used up exactly. Only the green steps reach your trace.

Reading the table

  • Self CPU / Self CUDA is time spent in that op alone. CPU total includes the ops it called, so a parent row can look huge. Sort by self CUDA time to find the real hogs.
  • # of Calls is how many times the op ran. With active=3 every row shows 3.
  • The two footer lines, Self CPU time total and Self CUDA time total, give the ratio that tells you the regime.

The ratio of GPU time to CPU time

size 64 (from the talk)17.8 µs GPU ÷ 332 µs CPU5%: overhead bound
size 1024ratio from the talk slide26%: mixed
size 4096ratio from the talk slide88%: GPU is the busy one

The rule. GPU total bigger than CPU total: compute bound. CPU total bigger: overhead bound. The exact percentages depend on your GPU, so look for the shape, not the digits.

Code: timing it right

The profiler is for finding what to fix. For a quick before-and-after number, use events and a warm-up.

import time, torch

def slow_wrong(fn):
    t = time.perf_counter(); fn()
    return time.perf_counter() - t            # measures only the time to QUEUE the kernel

def right(fn, iters=100):
    for _ in range(10): fn()                  # warm-up
    torch.cuda.synchronize()
    s, e = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
    s.record()
    for _ in range(iters): fn()
    e.record(); torch.cuda.synchronize()
    return s.elapsed_time(e) / iters          # milliseconds per call

Code: the starter script

Change n to 64, 1024 and 4096, and compare the footers. Open trace.json in Perfetto to see the two lanes.

import torch
from torch.profiler import profile, record_function, schedule, ProfilerActivity

n = 4096  # try 64, 1024, 4096
x = torch.randn(n, n, device="cuda")
w = torch.randn(n, n, device="cuda")
b = torch.randn(n, device="cuda")

def fn(x, w, b):
    return torch.add(torch.matmul(x, w), b)

def step():
    with record_function("matmul_add"):
        return fn(x, w, b)

sched = schedule(wait=1, warmup=1, active=3, repeat=1)
with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA],
             schedule=sched, record_shapes=True, profile_memory=True) as prof:
    for _ in range(5):
        step()
        prof.step()

prof.export_chrome_trace("trace.json")
print(prof.key_averages().table(sort_by="self_cuda_time_total", row_limit=15))

The core ideas, in short

  • Annotate with record_function so your code has a name in the trace.
  • Schedule: wait, warm up, then record a few active steps. Warm-up steps run the profiler but throw the data away.
  • Two outputs: a trace (a timeline) and a table (totals). Sort the table by self CUDA time first. A row you wrapped in record_function can show a bogus total, so read the self times.
  • Overhead bound shows as gaps in the GPU lane and a low CUDA-to-CPU time ratio.
  • Turn on record_shapes (op input sizes), profile_memory (allocations) and with_stack (source line) only when you need them. They add overhead.

Try it

  1. Change n in the script below to 64, 1024 and 4096. Each time, divide the “Self CUDA time total” by the “Self CPU time total” from the table footer. Do not add up the rows, because the record_function row double-counts. Do you get a rising curve? Aritra's slide showed 5% → 26% → 88%. On one H100-class machine we measured about 1%, 8% and 98%. Your numbers will differ. The shape is what matters.
  2. Open the trace in Perfetto. Find the gaps in the GPU lane at size 64.
  3. Wrap the function in torch.compile and compare the tables. In the Hugging Face post, compile turned the matmul and add into one aten::addmm call. But it still launched two GPU kernels and cost about 2× more CPU time per step at this tiny size. Compile does not always help small work.
  4. Turn on with_stack and find the exact line of your biggest op.

Check yourself tap a question for the answer

  • Why skip the warm-up steps?

    Warm-up steps pay one-time costs: CUDA context setup, kernel selection, cache allocation, lazy initialisation and the profiler’s own start-up. Counting them makes the first step look slow and skews the averages.

  • If one row is on top of the table, what else should you check before blaming it?

    Check the call count (a row with more calls adds up), self against total time (a parent includes its children), whether the row is a wrapper you added with record_function, the input shapes, and whether the GPU lane is actually idle.

  • Name three ways to fix an overhead-bound step.

    Give each launch more work (bigger batch or shapes). Fuse ops with torch.compile or a fused kernel. Use CUDA graphs to launch many kernels in one go. Remove needless syncs, such as .item() in the hot loop, so the CPU can run ahead. Move Python work out of the loop.

Questions that come up tap one to open it

My GPU shows 5% busy in the profile. Is bigger the only fix?

No. Bigger work per launch is one fix. You can also fuse ops, replay launches with CUDA graphs, or cut Python in the hot path.

Every op has a fixed CPU cost: Python, the dispatcher, the driver. A tiny kernel can finish faster than the CPU can launch the next one. The GPU then sits idle. That is overhead bound.

  1. Do more per launch. Bigger batch, bigger matrices, or merge small ops. This is what the 64 → 1024 → 4096 demo showed.
  2. Fuse. torch.compile can merge a matmul with its epilogue (the add, activation or norm after it) into fewer kernels.
  3. Replay. CUDA graphs record a sequence of launches once and replay them in one go. vLLM V1 uses piecewise CUDA graphs for this reason.
  4. Trim the CPU path. Less Python per step, fewer small tensors, avoid syncs like .item() in the loop.

How to check: open the trace. Gaps in the GPU lane mean the GPU was waiting for work.

Sources: torch.profiler docs · Profiler recipe · torch.compile tutorial · vLLM V1 release post

Go deeper read in this order

  1. Hugging Face blog: torch profiler (Part 1) A beginner series by Aritra and others. It uses this same matmul plus add example.
  2. Hugging Face blog: profiling Part 2 From nn.Linear to a fused MLP. Compares aten::addmm, eager, torch.compile and a Liger kernel.
  3. Profiler recipe A runnable walk-through on ResNet18. The later parts need a GPU.
  4. Perfetto UI Open a Chrome-format trace and zoom into the lanes.
  5. Hugging Face trace viewer (Space) A Hugging Face Space for looking at traces in the browser.
  6. PyTorch profiler docs The full API. Use it as a reference.
  7. PyTorch performance tuning guide A checklist of easy wins, including avoiding syncs and fusing pointwise ops.
  8. CUDA semantics Streams, async launches and syncs. Explains why the CPU runs ahead.
  9. NVIDIA Nsight Systems When you need a system-wide view beyond PyTorch.
2torch.compile, Triton and kernelsabout 6 hours

Once you know where the time goes, the next step is to remove work. Fusing ops and shipping good kernels are the two big levers. Hugging Face Kernels makes the second one easier.

The intuition

Small ops like add, multiply and relu do almost no maths per byte, so the time is spent moving data to and from HBM. In eager mode every op is its own kernel, and every kernel writes its result back to HBM for the next one to read. A fused kernel does all the steps while the values sit in registers.

Eager: three kernels, six trips to memory

HBMreadx * 2writeHBMread+ 1writeHBMreadreluwriteHBM

Fused: one kernel, two trips

HBMread oncex * 2, + 1, relu
in registers
write onceHBM
The same three element-wise ops. The maths is trivial, so the time is the trips to HBM. Fusing keeps the in-between values in registers.

Worked example

100M fp32 elements400 MB per tensor
eager3 kernels × (400 MB read + 400 MB write) = 2.4 GB≈ 0.72 ms at 3.35 TB/s
fused1 read + 1 write = 0.8 GB≈ 0.24 ms, 3× faster

What torch.compile does

It does not guess. It runs your Python once, records the tensor ops into a graph, rewrites the graph, and generates code.

your PythontraceDynamo
captures a graph
forward + backwardAOTAutogradfuse, scheduleInductoremitTriton kernels
(C++ on CPU)
The compile pipeline. The first call is slow because it compiles. Later calls reuse the result.

When Dynamo meets something it cannot trace, such as a branch on a tensor’s value, it ends the graph there, runs that bit in plain Python, and starts a new graph after it. That is a graph break. Each break means fewer fused ops and a bit more overhead.

import torch

def f(x):
    y = x * 2 + 1
    if y.sum() > 0:          # branch on a tensor VALUE: Dynamo must stop and run this in Python
        y = y - 1
    return torch.relu(y)

g = torch.compile(f)                      # works, but with a graph break
# TORCH_LOGS=graph_breaks python this_file.py       -> prints where and why
# torch.compile(f, fullgraph=True)(x)               -> turns the break into an error

Code: a Triton kernel

This is the whole idea of Triton. Each program owns a block of elements, loads them, computes and stores. Triton handles the thread-level details. This is the same shape of kernel that Inductor writes for you.

import torch, triton, triton.language as tl

@triton.jit
def add_kernel(x_ptr, y_ptr, out_ptr, n, BLOCK: tl.constexpr):
    pid = tl.program_id(0)                          # which block am I?
    offs = pid * BLOCK + tl.arange(0, BLOCK)        # the elements I own
    mask = offs < n                                 # stay in bounds
    x = tl.load(x_ptr + offs, mask=mask)
    y = tl.load(y_ptr + offs, mask=mask)
    tl.store(out_ptr + offs, x + y, mask=mask)

def add(x, y):
    out = torch.empty_like(x)
    n = x.numel()
    add_kernel[(triton.cdiv(n, 1024),)](x, y, out, n, BLOCK=1024)
    return out

x = torch.randn(1 << 20, device="cuda"); y = torch.randn(1 << 20, device="cuda")
assert torch.allclose(add(x, y), x + y)

Shipping kernels

Writing a fast kernel is half the job. A compiled kernel is tied to the GPU architecture, the CUDA version and the PyTorch build, so sharing one usually means a pile of CMake files. HF Kernels gives every kernel the same folder layout, builds it reproducibly with Nix for many PyTorch and CUDA combinations, and hosts it on the Hub, so using one is a download.

from kernels import get_kernel

activation = get_kernel("kernels-community/activation", version=1)   # downloads a prebuilt kernel
y = torch.empty_like(x)
activation.gelu_fast(y, x)                                           # call it like a function

The core ideas, in short

  • Graph capture: torch.compile traces your model into a graph and hands it to a compiler (Inductor).
  • Fusion: the compiler merges ops, such as a matmul and the add or activation after it (the epilogue). That means fewer launches and fewer memory trips.
  • Triton lets you write GPU kernels in Python-like code. On GPUs, Inductor generates Triton kernels for you. On CPUs, it generates C++.
  • Kernel distribution is painful: many build tools, many CUDA and PyTorch versions. HF Kernels gives a fixed structure, repeatable Nix builds and a Hub to share them. Builds cover many PyTorch and CUDA versions. Backends are CUDA, ROCm, XPU, Metal and CPU. CUDA and CPU are the best supported.

Try it

  1. Compile a small MLP with torch.compile. Run it as TORCH_LOGS=graph_breaks python your_script.py. It prints each graph break and why. You can also call torch._logging.set_logs(graph_breaks=True).
  2. Do Triton tutorials 1 to 3. Compare your softmax to PyTorch's.
  3. Install the library with pip install kernels (it needs torch 2.5 or newer, and a CUDA GPU for this example). Then run from kernels import get_kernel, activation = get_kernel("kernels-community/activation", version=1), y = torch.empty_like(x), activation.gelu_fast(y, x). Next try kernelize(model, mode=Mode.INFERENCE) to swap Hub layers into a small model. Use Mode.INFERENCE | Mode.TORCH_COMPILE if you compile too.

Check yourself tap a question for the answer

  • What is an epilogue, and why is fusing it useful?

    An epilogue is the work that follows a matmul on its output, such as adding a bias or applying an activation. Fusing it into the matmul kernel runs it on the result while the result is still on chip. That saves a trip to HBM and a kernel launch.

  • What is a graph break, and how do you find one?

    A graph break is a point where Dynamo cannot keep tracing, for example a branch on a tensor value or an unsupported call. It splits the graph and runs that part in eager Python. Find them with TORCH_LOGS=graph_breaks, or make them errors with fullgraph=True.

  • Why do kernel builds break across CUDA and PyTorch versions?

    A compiled kernel depends on the GPU architecture, the CUDA toolkit, the PyTorch version and the C++ ABI. Change any of them and the binary may not load or may be wrong. Reproducible per-variant builds, as in HF Kernels, avoid that.

Go deeper read in this order

  1. torch.compile tutorial Start with the basics and graph breaks.
  2. PyTorch 2 paper How TorchDynamo and TorchInductor work.
  3. TorchInductor design post The compiler's design in the team's words. It is an early 2022 prototype post, so read it for ideas, not details.
  4. Triton tutorials Vector add, softmax, matmul, fused attention. Do them in order.
  5. How to optimize a CUDA matmul Step-by-step from naive to fast. Teaches the memory ladder.
  6. FlashAttention paper The classic fusion story: tile the attention so it avoids reading and writing the big matrix in HBM.
  7. Hugging Face kernels (GitHub) The repo. It has the kernels package, the kernel-builder and the install steps.
  8. Kernels docs Overview. Open Quickstart to load a kernel and Builder to publish one.
  9. Kernels quickstart Load a kernel with get_kernel.
  10. Hello, Hugging Face Kernels June 2025 intro to the Kernel Hub. It covers get_kernel, not the builder or Nix.
  11. Why graph breaks happen .item(), tensor-dependent if, and printing.
3LLM inference: engines, caches and MoEabout 10 hours

Adarsh's line: one user is easy, a thousand is not. This module follows one request through prefill, decode, batching, the KV cache and the big MoE tricks.

The intuition: one request, start to finish

A request first goes through prefill: the model reads the whole prompt in parallel and stores each token’s keys and values, the KV cache. Then decode writes the answer one token at a time. Each new token only needs to compute its own keys and values, because the old ones are in the cache. Without the cache, every step would re-read the whole conversation.

Prefillthe whole prompt, one pass
matrix × matrixcompute bound
Decodeone new token per step
123?
matrix × vectormemory bound
Prefill builds the KV cache for every prompt token at once. Decode adds one token at a time, and every step reads all the weights and the whole cache (grey chips) again.

The cache is what limits how many users you can serve at once, so it is worth doing the sum.

Worked numbers: the KV cache

formula2 (K and V) × layers × KV heads × head size × bytesbytes per token
Llama-3-8B2 × 32 × 8 × 128 × 2 bytes131,072 B = 128 KiB per token
one 2K-token request2,048 × 128 KiB256 MiB
room on an 80 GB GPU72 GB usable − 16 GB weights≈ 56 GB for cache
requests that fit56 GB ÷ 256 MiBabout 200
Llama-2-7B, no grouped-query attention32 KV heads instead of 84× more: 512 KiB per token
Try it: how many requests fit?
cache per token
cache per request
room for cache
requests that fit

Assumes 90% of GPU memory is usable and ignores activations, so the real number is a little lower.

Batching and paging

Decode is memory-bound, so a step costs about the same for 1 request or 50. The trick is to keep the batch full. Continuous batching checks after every step and fills a slot the moment a request ends, instead of waiting for the slowest request of a group.

Static batching: 18 steps

slot 0slot 1slot 2

Continuous batching: 10 steps

slot 0slot 1slot 2
Six requests of different lengths (A to F) on three slots. Static batching waits for the longest request in each group (grey is idle). Continuous batching fills a slot the moment it frees up.

PagedAttention does for the cache what virtual memory does for RAM. A request’s cache is a list of small blocks that can live anywhere, so there is no big contiguous reservation sized for the longest possible reply, and little memory is wasted.

Prefix caching: stop recomputing the same start

If a thousand requests begin with the same system prompt, prefill for that prompt should run once. vLLM hashes each full block together with the tokens before it and reuses matching blocks. SGLang keeps a radix tree of token sequences, so any shared start is found, even where chats branch apart.

system prompt (computed once)chat Achat Bchat Creply A1reply B1reply B2
A radix tree of cached prefixes. Every chat shares the system prompt, so it is stored once. When memory is tight, the least recently used leaf (dashed) goes first.

The prompt-order rule. Cache hits need an identical start. Put the stable parts (system prompt, tools, documents) first, and the parts that change (timestamp, user ID, the question) last. One timestamp at the top throws away every hit.

The other speed tricks

TrickThe ideaWhat it helps
Continuous batchingRefill a slot the moment a request finishes.Throughput
Paged KV cacheStore the cache in small fixed blocks (16 tokens by default in vLLM) instead of one big reserved stretch per request.More requests fit
Prefix cachingReuse the cache of a prompt start that was seen before.Time to first token, cost
Chunked prefillCut a long prompt into pieces so decode steps keep running between them.Tail latency
Speculative decodingA small model drafts a few tokens. The big model checks them all in one pass and keeps the good ones.Decode speed, same output distribution
QuantizationFewer bytes per weight. Decode is memory-bound, so fewer bytes means faster steps.Decode speed, memory
Prefill/decode splitRun the two jobs on separate GPU pools so each can be tuned alone.Both latencies
quantization, worked8B weights at 8 bits = 8 GB, and 8 GB ÷ 3.35 TB/s = 2.4 ms≈ 419 tokens/s bound, double the bf16 bound

Mixture of experts in one paragraph

An MoE layer has many small expert MLPs and a router that sends each token to its top few. Only those experts run, so the compute per token is small, but all the experts’ weights must live somewhere. They are spread across GPUs (expert parallelism). That means each token travels to the GPU that holds its expert and comes back: every GPU sends a different piece to every other GPU, which is an all-to-all. If a few experts are hot, the others wait, so serving stacks add an expert load balancer and overlap this traffic with compute.

Code: see the cache work

Start a server, then measure the time to first token for ten requests that share one long system prompt.

# terminal 1: start a server (SGLang shown; `vllm serve <model>` is the vLLM equivalent)
python -m sglang.launch_server --model-path meta-llama/Llama-3.1-8B-Instruct --port 30000
import time
from openai import OpenAI

client = OpenAI(base_url="http://localhost:30000/v1", api_key="none")
SYSTEM = open("policy.txt").read()        # long, and identical for every request

def ttft(question):
    t0 = time.perf_counter()
    stream = client.chat.completions.create(
        model="default", stream=True, max_tokens=64,
        messages=[{"role": "system", "content": SYSTEM},     # stable part FIRST
                  {"role": "user", "content": question}])    # changing part LAST
    for chunk in stream:
        if chunk.choices and chunk.choices[0].delta.content:
            return time.perf_counter() - t0                  # time to first token

for i in range(10):
    print(i, f"{ttft(f'Question {i}: what is the refund window?') * 1e3:.0f} ms")
# request 0 is cold. Later ones should be faster, because the system prompt's cache is reused.

The core ideas, in short

  • Prefill and decode are two different jobs. One is compute-bound, the other memory-bound.
  • KV cache size: for Llama-3-8B (32 layers, 8 KV heads, head size 128, 16-bit), that is 2 × 32 × 8 × 128 × 2 bytes = 128 KiB per token. A 2K-token prompt is about 256 MiB per request. Llama-3-8B shares KV heads (8 instead of 32), so it needs about 4× less per token than a model without grouped-query attention, like Llama 2 7B.
  • Paged KV cache (PagedAttention) stores the cache in small blocks to avoid waste.
  • Continuous batching adds and removes requests at every step instead of waiting for a whole batch.
  • Prefix caching: vLLM hashes each full block together with the tokens before it. Only full blocks are cached. SGLang's RadixAttention keeps a radix tree keyed by tokens. It matches token by token, or page by page if you set a page size above 1. Both engines now also handle hybrid models and can push cache out of GPU memory (SGLang with HiCache, vLLM with an offloading connector or LMCache).
  • Speed tricks: speculative decoding, chunked prefill, quantization, prefill/decode disaggregation.
  • MoE serving: expert parallelism, data-parallel attention, an expert load balancer, and overlapping communication with compute.

Try it

  1. Compute the KV cache size for a model you like. How many 2K-token requests fit next to the weights on a 80 GB GPU?
  2. Serve a small model with vLLM and with SGLang. Send a 10-turn chat to each and log the time to first token per turn. Then turn prefix caching off and compare. In SGLang, add --disable-radix-cache. In vLLM caching is on by default, so run vllm serve --help to find the off switch for your version, then restart the server.
  3. Make a prompt that starts with a timestamp. Watch the hit rate drop. Move the timestamp to the end. Watch it recover. Read the hit rate from the server logs. The first request is always cold, so compare turns 2 to 10.
  4. Reproduce the slide's shape at small scale: 200 requests with a shared 2K-token prefix against plain generate() and against a server.
  5. Read the “limits” section of the DeepSeek post. Write down three things the authors say they could not test.

Check yourself tap a question for the answer

  • Why does decode get faster per token when you batch more requests?

    Decode is memory-bound: each step reads all the weights once, whatever the batch size. More requests add FLOPs but barely add bytes, so a step takes nearly the same time while it produces more tokens. This holds until the batch is large enough to reach the ridge, or until reading the KV cache starts to dominate.

  • What is the difference between vLLM's block hashing and SGLang's radix tree? When does it matter?

    vLLM hashes each full block with the tokens before it, so it matches in whole blocks. SGLang’s radix tree is keyed by tokens, so it matches token by token (or page by page) and handles chats that branch from a shared start. It matters most for short shared prefixes, prompts that differ mid-block, and branching programs. For one long identical system prompt, both do well.

  • What is the job of each part in SGLang: scheduler, KV cache manager, model runner, attention backend?

    Scheduler: chooses which requests run each step and batches them. KV cache manager: allocates, reuses and evicts cache. Model runner: runs the forward pass and sampling. Attention backend: the kernel (flash-attn or flash-infer) that attends over the cached keys and values.

  • Why does an MoE model need all-to-all?

    The experts live on different GPUs. Each token must reach its top-k experts wherever they are, and the results must come back. Every GPU therefore sends different data to every other GPU, which is an all-to-all.

  • What is numeric drift and when would you care?

    Different kernels (fused or not, different reduction order, different precision) give slightly different floating-point results, and small gaps can grow over many layers and sampling steps. Care about it when comparing backends, when checking that a port is correct, and in RL, where the training engine and the inference engine can disagree on token probabilities.

Questions that come up tap one to open it

Is prefix caching free? Does it change my outputs?

It is cheap, not free. The cache is the same maths reused, so outputs should match, up to tiny numeric drift.

  • Cost when nothing hits: SGLang says it saw no noticeable overhead. vLLM V1 reports under 1% throughput loss at a 0% hit rate.
  • Memory: cached KV lives in the same GPU memory as running requests. Old entries are dropped by least recently used. A busy server may drop your prefix before the next turn arrives.
  • Things that kill hits: a timestamp or user ID at the start of the prompt; requests spread across replicas with no routing; different LoRA adapters or images (they are part of the hash in vLLM).
  • Outputs: reusing a cached prefix is exact reuse. But batch shapes and kernels can change, and different kernels give slightly different numbers. Adarsh called this numeric drift. Test if you need bit-exact results.

Habit to build: put stable text first (system prompt, tools, documents). Put changing text last.

Sources: vLLM prefix caching design · RadixAttention post · vLLM V1 release post

Go deeper read in this order

  1. NVIDIA: mastering LLM inference optimization The best overview. It is also on Adarsh's slide.
  2. A gentle KV caching explainer A simple first read.
  3. PagedAttention (vLLM paper) Why paging the KV cache raised throughput.
  4. Continuous batching (Anyscale) Why static batching wastes the GPU.
  5. Continuous batching (Hugging Face) The same idea, built up from first principles.
  6. SGLang paper RadixAttention and the programming model.
  7. SGLang / RadixAttention post A readable version of the paper.
  8. vLLM prefix caching design Block hashes, the hash chain and LRU eviction.
  9. vLLM V1 release post Why V1 was rebuilt and why prefix caching is now on by default.
  10. FlashAttention-2 Better work split on the GPU.
  11. FlashAttention-3 Tuned for Hopper GPUs.
  12. FlashInfer paper The attention kernel library used in serving engines.
  13. FlashInfer (GitHub) Code and docs.
  14. Speculative decoding A small model guesses several tokens. The big model checks them all in one pass. The output is the same as the big model alone.
  15. Sarathi-Serve (chunked prefill) Keep decode smooth while prefill runs.
  16. DistServe Why separating prefill and decode helps.
  17. Mooncake A KV-cache-centred serving system for Kimi. It splits prefill and decode, and uses spare CPU, DRAM and SSD in the GPU cluster as a shared KV cache. The closest paper to the SSD offload note from the talk.
  18. SGLang: DeepSeek on 96 H100s Data-parallel attention, DeepEP, load balancing, disaggregation. Read the limits section.
  19. DeepEP (GitHub) The all-to-all library for MoE.
  20. DeepSeek-V3 paper The model that drove this whole serving work.
  21. vLLM expert-parallel deployment How vLLM does it.
  22. NVIDIA: LLM benchmarking basics TTFT, inter-token latency, throughput. Learn the terms before you benchmark.
  23. SGLang HiCache Spill the radix tree to CPU and disk. Mooncake is one of its storage backends.
  24. vLLM hybrid KV cache manager How vLLM caches prefixes for models that mix attention with Mamba or sliding-window layers. The page says it is early-stage.
  25. Hybrid models in vLLM (PyTorch blog) Why hybrid models need a different KV cache allocator.
  26. LMCache paper A KV cache layer across GPU, CPU, storage and network. The speed-ups are the authors' own claim.
  27. vLLM docs Install and serve.
  28. SGLang docs Install and serve.
  29. vLLM (GitHub)
  30. SGLang (GitHub)
4RL environments and reward designabout 8 hours

If a program can grade it, a model can learn it. That makes environments the new datasets. Most of the work, and most of the danger, is in the environment.

The intuition

Models are taught in stages. The last stage is different: instead of copying answers, the model tries, gets a score, and learns to repeat what scored well.

1PretrainingPredict the next token on web text.learns what is true
2SFTImitate curated question and answer pairs.learns the format
3RLHFA person says which answer is better.reward from people
4RLVR + GRPOA program checks the answer.reward from a verifier
How a model is taught, one step at a time. The last step is where RL environments live.

The score has to come from somewhere. If a program can check the answer (the tests pass, the maths matches, the LaTeX renders to the same formula), no person is needed, and you can run millions of attempts. The place where the model tries and gets checked is the environment.

LLM(the agent)Environmentsandbox, tools, stateVerifiera programGRPO updatethe traineraction: a tool call or codeobservation: output, new staterunrewardlearn
The Gym loop, for an LLM. The agent acts, the environment answers, a verifier turns the outcome into a reward, and the trainer nudges the model toward what scored.

How GRPO uses the score

The aim is simple: make answers that scored above average more likely. The question is what “average” means. PPO trains a second network, a critic, to guess it. GRPO skips the critic. It samples a group of answers to the same prompt, scores them all, and uses the group’s own mean and spread. An answer is good if it beats its siblings.

Worked examples

4 samples, rewards 1, 0, 0, 1mean 0.5, std 0.5advantages +1, −1, −1, +1
4 samples, rewards 1, 0, 0, 0mean 0.25, std 0.43advantages +1.7, −0.6, −0.6, −0.6
4 samples, rewards 1, 1, 1, 1mean 1, std 0advantages 0: nothing to learn

The third row matters. When every sample gets the same score, there is no signal for that prompt. That is why the reward must be neither too easy nor too hard, and why you watch the fraction of groups with zero spread.

Try it: one prompt, eight samplesclick a sample to flip pass and fail
group mean
group std

Advantage = (reward − mean) ÷ std. Libraries differ slightly in how they estimate the std and add a small constant, so the digits move a little.

Code: the smallest environment

Every environment is the Gym contract. reset() gives the first observation. step() takes the model’s action and returns a reward and a done flag. For a one-shot coding task the action is the whole answer.

import subprocess, tempfile, textwrap, pathlib

HIDDEN_TESTS = textwrap.dedent("""
    from solution import add
    assert add(2, 3) == 5
    assert add(-1, 1) == 0
    assert add(10**9, 1) == 10**9 + 1
""")

class AddEnv:
    prompt = "Write a Python function add(a, b) that returns a + b."

    def reset(self):
        return {"prompt": self.prompt}                       # the first observation

    def step(self, completion: str):
        with tempfile.TemporaryDirectory() as d:
            d = pathlib.Path(d)
            (d / "solution.py").write_text(completion)       # the model's code
            (d / "check.py").write_text(HIDDEN_TESTS)        # <- sits NEXT TO the model's code
            try:
                r = subprocess.run(["python", "check.py"], cwd=d, capture_output=True, timeout=5)
                reward = 1.0 if r.returncode == 0 else 0.0
            except subprocess.TimeoutExpired:
                reward = 0.0
        return {"reward": reward, "done": True}

Look closely: the hidden tests are written into the same folder the model’s code runs from. A cheating solution can simply open check.py and read the expected answers. This is the kind of hole the talk was about.

Reward hacking: a short field guide

The cheatWhy it workedThe fix
try / except: passThe reward was “runs without an error”.Reward the outcome you care about, not a proxy for it.
Read the hidden testsThey sat in the same folder as the model’s code (see check.py above).Grade from outside the sandbox. Copy the tests in only after the model is done, or never.
Hard-code the answersOnly a few fixed test inputs.Many hidden or randomised tests.
Look up the fixThe fix is on GitHub, in the git history, and on PyPI.Scrub the prompt and the repo, and allow only the network you need.
Edit the graderThe grader was writable.Read-only mounts. The grader lives outside the box.

Rule of thumb. Trust lives in the environment. Do not write “please do not cheat” in the prompt. Build a box where cheating is not possible, and check that a gold answer scores 1.0 and an empty answer scores 0.0.

Code: train against it

With TRL you can pass a plain reward function. For plain-text prompts the completions arrive as strings.

from datasets import Dataset
from trl import GRPOConfig, GRPOTrainer

env = AddEnv()
ds = Dataset.from_dict({"prompt": [env.prompt] * 64})

def reward_fn(completions, **kwargs):                        # one score per completion
    return [AddEnv().step(c)["reward"] for c in completions]

trainer = GRPOTrainer(
    model="Qwen/Qwen2.5-0.5B-Instruct",
    reward_funcs=reward_fn,
    args=GRPOConfig(output_dir="out", num_generations=8, logging_steps=5, log_completions=True),
    train_dataset=ds,
)
trainer.train()      # read the logged completions, not just the reward curve

The core ideas, in short

  • The arc: pretraining, SFT, RLHF, then RLVR (verifiable rewards) with GRPO.
  • Gym contract: reset() starts an episode. step(action) returns the next observation, a reward and a done flag. OpenEnv adds state(). For LLMs: agent = model, environment = sandbox, reward = verifier.
  • One-shot vs multi-turn: one answer and one grade, or many tool calls and a grade at the end.
  • Parts of an environment: task, prompt, tools, state, observations, execution, reward, done signal.
  • Reward hacking: the model does the reward, not the task. Trust must live in the environment.
  • Frameworks: OpenEnv, Verifiers and OpenReward (ORS) give environments a common shape. Harbor is a task format and agent harness. OpenEnv and Repo2RLEnv build on it.

Try it

  1. Build a tiny environment: ask for a Python function, run the tests in a sandbox, return 1 or 0. Write the reset and step yourself first. Then port it to OpenEnv with openenv init, build (needs Docker), validate and push.
  2. Red-team it. Write three ways to score 1.0 without solving the task. Fix each one. Check that a gold answer gets 1.0 and an empty answer gets 0.0.
  3. Train a small model on it with TRL's GRPO trainer. TRL's environment_factory is experimental and needs transformers>=5.2.0. It wants named tool methods such as guess(word), not a generic step(action). Set log_completions=True and logging_steps=50. Read some rollouts. Watch frac_reward_zero_std: a high value means most groups give no signal.
  4. Run the LaTeX OCR environment from the talk and compare before and after scores.

Check yourself tap a question for the answer

  • Why do rewards like “the code ran without errors” fail?

    It rewards a proxy (“no crash”) instead of the task. The cheapest way to maximise it is to wrap everything in try / except, which never crashes and never solves anything.

  • What goes wrong if every sample in a GRPO group gets the same score?

    Every advantage becomes zero, so that prompt gives no learning signal. If many groups look like that, the task is too easy or too hard, or the reward is too coarse. The log field to watch is frac_reward_zero_std.

  • In the CVE story, why was blocking the network not enough?

    The fix was available through more than the web: the container’s own git history, and pip download of the fixed release. Closing one door left the others open. You have to scrub the prompt and the repo, and allow only the network the task needs.

  • What is the difference between a one-shot and a multi-turn environment?

    One-shot: one prompt, one answer, one grade. Multi-turn: the model acts through many tool calls, the environment answers each time, and the reward often comes only at the end. The credit-assignment problem is harder, and the environment has to hold state.

Questions that come up tap one to open it

Why do models game rewards, and how do I stop it?

Because RL optimizes exactly what the verifier measures. Any gap between “the reward” and “the task” will be found.

This is Goodhart's law, with a very patient searcher. The model tries thousands of paths. If one of them scores without solving the task, the training signal pushes the model towards it.

Adithya's two stories show it. A try / except: pass wrapper kept code from crashing, so a “code runs cleanly” reward went up with no maths solved. In the CVE environment, the agent read the fix from the PR, then from git history, then from pip.

  • Test the verifier first. The gold solution must score 1.0. A no-op must score 0.0.
  • Remove the answer from the prompt, the repo, the history and the network.
  • Isolate the sandbox. Offline by default. Allowlist, never block-list.
  • Read rollouts, not just reward curves. A sudden jump in reward is a smell.
  • Use several signals, and keep a hidden test the model never trains on.

The honest summary is on his last slide: reward design is never done. It is only iterated.

Sources: Reward hacking (Lilian Weng) · Specification gaming (DeepMind) · The RL environments guide from the talk

Why GRPO instead of PPO for verifiable rewards?

GRPO needs no critic (value) model. It scores a group of answers to the same prompt and compares them with each other.

  • PPO trains a value model next to the policy. It is usually about the size of the policy. That costs memory and adds moving parts.
  • GRPO samples a group of answers for each prompt, scores them, and uses the group's average (and spread) as the baseline. An answer is good if it beats its siblings.
  • With a program-graded reward like pass or fail, that is simple and works well.
  • Catch: if every answer in a group gets the same score, all right or all wrong, every advantage is zero. The reward gives no policy-gradient signal for that prompt. (A KL term, if used, can still move the weights.) The task must be neither too easy nor too hard. TRL logs frac_reward_zero_std so you can see how often this happens.

Sources: DeepSeekMath (introduces GRPO) · PPO paper · TRL GRPO trainer

Go deeper read in this order

  1. Spinning Up in Deep RL Classic RL basics: policies, returns, policy gradients.
  2. Hugging Face Deep RL course Hands-on, with notebooks. It uses Stable Baselines3 and CleanRL, not LLMs. The Unit 7 challenge and leaderboard no longer work.
  3. Andrej Karpathy: Pong from pixels The simplest policy gradient story.
  4. Lilian Weng: policy gradient algorithms A tidy reference.
  5. PPO
  6. InstructGPT (RLHF)
  7. DeepSeekMath (GRPO)
  8. DeepSeek-R1 RL with verifiable rewards at scale.
  9. Tulu 3 (RLVR) Introduces the term RLVR (reinforcement learning with verifiable rewards). A fully open post-training recipe.
  10. The ultimate guide to RL environments (from the talk) Hugging Face article, May 2026. The authors build one environment in six frameworks (OpenEnv, ORS, NeMo Gym, Verifiers, SkyRL Gym, GEM) and compare them. It does not cover reward hacking in depth.
  11. Adithya's RL Envs 101 Open-source RL environments for LLM agents, in numbered projects. Project 01 trains Qwen3-VL-2B to turn math images into LaTeX with a verifiable reward. The repo has been renamed FineEnvs, and the old link redirects.
  12. OpenEnv docs
  13. OpenEnv (GitHub)
  14. Repo2RLEnv Turn a repo into a verifiable environment.
  15. Verifiers (Prime Intellect)
  16. Gymnasium The maintained fork of OpenAI Gym. Its reset and step API is the model for most RL environments.
  17. TRL docs
  18. TRL GRPOTrainer
  19. SWE-bench A real-repo benchmark. It is also a good source of environments.
  20. OpenEnv: your first environment Scaffold, implement, run, validate and push, step by step.
  21. TRL: OpenEnv integration How environment_factory works, with tips on rewards.
  22. Verifiers docs
  23. Reward hacking (Lilian Weng) Covers RLHF and LLM coding hacks, such as editing the unit tests.
  24. Natural emergent misalignment from reward hacking in production RL Anthropic. Models trained on real coding environments learned to reward hack, and it spread into broader misalignment.
  25. EvilGenie: a reward hacking benchmark Coding tasks where hardcoding tests or editing test files is easy.
  26. Specification gaming (DeepMind) A list of real cases.
5Distributed training with DeviceMesh, DTensor and FSDP2about 10 hours

Mansi's idea: parallelism should be composable. Adding a kind of parallelism should mean adding a dimension to the mesh, not rewriting the training loop.

The intuition: what fills the GPU

Training memory is not just the weights. For each parameter, mixed-precision Adam keeps a bf16 weight (2 bytes), a bf16 gradient (2), and in fp32 a master weight (4), a momentum (4) and a variance (4). That is 16 bytes per parameter.

8B model8 × 10&sup9; × 16 bytes128 GB, more than one 80 GB GPU
plain data parallelevery GPU holds all of it128 GB each: does not fit
FSDP across 8 GPUs128 GB ÷ 816 GB each, plus activations
Try it: model state per GPUbf16 compute, fp32 master weights, Adam
plain DDP
FSDP

The bars are measured against an 80 GB GPU. This is model state only (weights, gradients, optimizer). Activations are extra.

Three ways to split the work

  • Data parallel. Every GPU has the whole model and a slice of the batch. Gradients are averaged at the end.
  • Sharded data parallel (FSDP). Same data split, but the weights, gradients and optimizer state are cut into pieces, one per GPU. A layer is gathered just before it is used and freed right after.
  • Tensor parallel (TP). One matmul is cut across GPUs, so each holds part of every layer.
1/N of each
weight
all-gatherfull layercomputeactivationsfree the weights1/N againbackward: gather, computefull gradientreduce-scatter1/N of
the gradient
What FSDP does for each layer. The gather and the scatter overlap with compute, so slow links are tolerable.

Tensor parallel works because of one identity. Split the first matrix by columns and the second by rows. The activation sits between them and acts on each element on its own, so it needs no communication. The two halves add up at the end: Y = act(X·A1)·B1 + act(X·A2)·B2. That one sum is an all-reduce.

xGPU 0x · W1 (cols)act· W2 (rows)GPU 1x · W1 (cols)act· W2 (rows)all-reduce
Split the first matrix by columns and the second by rows. Each GPU works alone until the end, then one all-reduce adds the partial results.

DeviceMesh: name the grid, then pick a row or column

With both ideas on, a GPU belongs to a TP group and an FSDP group. A DeviceMesh lays the GPUs on a named grid so that you can say mesh["tp"] and mesh["dp"] instead of building process groups by hand. Ranks are laid out row by row, so the last dimension (tp) holds neighbouring ranks, which usually share a node and the fast NVLink. That is why TP goes last.

tp 0tp 1tp 2tp 3dp 0GPU 0GPU 1GPU 2GPU 3dp 1GPU 4GPU 5GPU 6GPU 7tensor-parallel groupdata-parallel group
A (2, 4) mesh with the dimensions dp and tp. Each GPU sits in one tensor-parallel group (a row) and one data-parallel group (a column). Pick a group by name and the collectives follow.

DTensor is the piece that makes this composable. Each tensor knows how it is spread over the mesh: Shard(dim), Replicate() or Partial() (a pending sum). When an op needs a different layout, DTensor inserts the collective.

Code: TP and FSDP2 on a 2D mesh

This is the entire change. The model, the loss and the optimizer step stay as they were.

import torch, torch.nn as nn
from torch.distributed.device_mesh import init_device_mesh
from torch.distributed.tensor.parallel import parallelize_module, ColwiseParallel, RowwiseParallel
from torch.distributed.fsdp import fully_shard          # FSDP2 (PyTorch 2.6 or newer)

mesh = init_device_mesh("cuda", (2, 4), mesh_dim_names=("dp", "tp"))   # 8 GPUs

class MLP(nn.Module):
    def __init__(self, d=1024):
        super().__init__()
        self.up, self.down = nn.Linear(d, 4 * d), nn.Linear(4 * d, d)
    def forward(self, x):
        return self.down(torch.relu(self.up(x)))

model = MLP().cuda()
model = parallelize_module(model, mesh["tp"], {"up": ColwiseParallel(), "down": RowwiseParallel()})
fully_shard(model, mesh=mesh["dp"])                     # shard what is left across the dp dimension

opt = torch.optim.AdamW(model.parameters(), lr=1e-3)
x = torch.randn(16, 1024, device="cuda")
model(x).sum().backward(); opt.step()                   # the training step is unchanged

# run:  torchrun --nproc_per_node=8 train.py     (on 4 GPUs use a (2, 2) mesh)

Checkpoints

With sharded state, each GPU can write its own piece, so saving needs no communication. torch.distributed.checkpoint (DCP) stores the layout as well, so you can load the same checkpoint on a different number of GPUs and it re-shards on the way in.

The core ideas, in short

  • DeviceMesh names the GPU grid: (4, 2) with dp and tp.
  • DTensor placements: Shard(dim), Replicate(), Partial(). Collectives appear when placements need to change.
  • FSDP2 is fully_shard(), a transform on the model. Each parameter is a DTensor sharded on dim 0, Shard(0). All-gather before forward, free after, reduce-scatter for grads.
  • Tensor parallel: column-wise, then row-wise, so a pair of linears needs one all-reduce. A full transformer layer needs two all-reduces in forward and two in backward. Keep it inside a node: the TP tutorial applies it within each host.
  • Order for compile: Mansi's slide says checkpoint, then fully_shard, then torch.compile last. TorchTitan, as I read a mirror of its Llama 3 code, compiles each transformer block before applying FSDP. Check the current file. The safe habit is to try both on your model.
  • DCP saves each shard without communication and can reshard on load, for example from 8 GPUs to 16.
  • Memory: mixed-precision Adam needs about 16 bytes per parameter. That is 2 for bf16 weights, 2 for bf16 gradients and 12 for fp32 master weights, momentum and variance. Activations are extra.

Try it

  1. Follow Mansi's four stages on a toy model: 1 GPU, DDP, FSDP2, FSDP2 + TP. Use the same seed and data order. The loss curves should match to within small numerical noise. The last stage needs at least 4 GPUs. With 2 GPUs you only get a 1×2 mesh.
  2. Print the DTensor placements of a few weights after parallelize_module. Call full_tensor() and compare with the original.
  3. Save a checkpoint with DCP on 2 processes. Load it on 4.
  4. Compute memory per GPU for a 7B model on 8 GPUs with FSDP. Use bf16 compute, fp32 master weights and Adam. Ignore activations. Check: 7B × 16 bytes = 112 GB, divided by 8 is 14 GB per GPU for the sharded state. Then add the short-lived full bf16 copy of one layer that FSDP gathers.

Check yourself tap a question for the answer

  • What changes in the training loop when you go from DDP to FSDP2? (Almost nothing. Why?)

    fully_shard(model) changes how the parameters are stored (as sharded DTensors) and hooks the all-gather and reduce-scatter into forward and backward. You still call the model, loss.backward() and optimizer.step() as before. The collectives are hidden inside the hooks.

  • Which dimension of the mesh should sit inside a node, and why?

    The tp dimension, as the innermost one. Tensor parallel does an all-reduce on the critical path of every layer, so it needs the fastest links, the NVLink inside a node. Data-parallel traffic can overlap with compute and can cross slower links.

  • What does DTensor do when an op has no sharding rule? Why is silently falling back to replicate a risky default?

    As presented, it raises an error. A silent fallback would gather the full tensor onto every GPU without telling you. That means memory spikes and extra traffic you did not plan for, possibly an out-of-memory error at scale, while the numbers still look right.

  • Mansi's slide calls DTensor’s sharding choice “locally optimal”. What does that mean?

    It picks the cheapest sharding for each op using only that op’s inputs. It does not look at the whole graph, so the combination of choices may not be the cheapest overall. A compiler-first system like JAX with GSPMD can search the whole graph, at the cost of being harder to debug.

Questions that come up tap one to open it

FSDP, tensor parallel, or both?

Start with FSDP. Add tensor parallel inside a node when FSDP alone is not enough. Put the chattiest dimension on the fastest links.

  • FSDP splits parameters, gradients and optimizer states across data-parallel ranks. It all-gathers one layer at a time. It saves memory and is easy to adopt: Mansi's walkthrough changed only a few lines.
  • Tensor parallel splits each matmul inside a layer. It needs an all-reduce in almost every layer, so it is very sensitive to latency. Keep it inside a node on NVLink.
  • Memory check: mixed-precision Adam costs about 16 bytes per parameter (2 weights, 2 grads, 12 optimizer state). A 7B model is about 112 GB before activations. That is why you must shard.
  • Combine when data parallel alone cannot grow (global batch limit), or a single layer is too heavy. Then add pipeline parallel across nodes, and context parallel for very long sequences.

With DeviceMesh this is a shape choice: (4, 2) with names dp and tp.

Sources: Ultra-Scale Playbook · ZeRO paper · Megatron-LM paper · FSDP2 docs

Go deeper read in this order

  1. DeviceMesh recipe Meshes and sub-meshes.
  2. DDP notes The baseline to understand first.
  3. FSDP2 API (fully_shard)
  4. FSDP tutorial
  5. Tensor parallel API parallelize_module, Colwise and Rowwise styles.
  6. FSDP2 design RFC Why FSDP2 shards each parameter.
  7. Tensor parallel tutorial Colwise and Rowwise in practice.
  8. Distributed checkpoint recipe
  9. Accelerate: FSDP1 vs FSDP2 Mansi's slide pointed here.
  10. Ultra-Scale Playbook The best single guide to all the parallelisms.
  11. TorchTitan paper
  12. TorchTitan (GitHub) A reference stack that composes these pieces.
  13. ZeRO The idea behind sharding optimizer state, grads and params.
  14. Megatron-LM (tensor parallel)
  15. Megatron-LM at scale How 3D parallelism is combined.
  16. GPipe (pipeline parallel)
  17. PyTorch FSDP paper
  18. Llama 3 paper See the parallelism and failure sections.
  19. TorchFT Fault tolerance across the replicated dimension (DDP or HSDP). Some parts are experimental.
  20. AutoParallel Experimental.
6GPU communication: NCCL, RoCE and zero-copyabout 6 hours

At scale, how GPUs talk matters as much as how fast they compute. Arkadip's talk went under the training loop to show where copies and distance cost time.

The intuition

Every step of distributed training ends in the same few patterns of “who sends what to whom”. They are called collectives, and NCCL implements them.

CollectiveBeforeAfter
broadcastOne GPU has the data.Every GPU has it.
reduce-scatterEvery GPU has a full vector.Each holds one slice of the sum.
all-gatherEach holds one slice.Every GPU has the whole vector.
all-reduceEvery GPU has a vector.Every GPU has the sum. It is a reduce-scatter followed by an all-gather.
all-to-allEach GPU has a different piece for every other GPU.Each GPU holds the pieces meant for it.

FSDP’s two steps from the last module are exactly the two halves of an all-reduce, used separately. Tensor parallel uses all-reduce. MoE uses all-to-all.

Worked numbers: the ring all-reduce

GPU 0GPU 1GPU 2GPU 3each step: send 1/Nof the data onward
A ring of N GPUs. The data is cut into N chunks. Reduce-scatter takes N−1 steps and all-gather takes N−1 more, so each GPU sends 2(N−1)/N times the data in total.
data each GPU sends2 × (N − 1) / N × sizeN = 8: 1.75 × size
1 GB, 8 GPUs, 400 GB/s1.75 GB ÷ 400 GB/s≈ 4.4 ms
1 GB, 8 GPUs, 50 GB/s1.75 GB ÷ 50 GB/s≈ 35 ms
16 GB of gradients, 50 GB/s1.75 × 16 GB ÷ 50 GB/s≈ 0.56 s

Two terms make up the time: time ≈ steps × latency + bytes ÷ bandwidth. Small messages are dominated by latency, big ones by bandwidth. That is why one big all-reduce beats many small ones.

Algorithm bandwidth (size over time) falls as you add GPUs. Bus bandwidth multiplies it by 2(N−1)/N, which makes it comparable to the speed of the link, whatever N is. That is the number nccl-tests reports.

Try it: how long does an all-reduce take?ring algorithm
each GPU sends
bandwidth time
latency time
total

The defaults are 16 GB of bf16 gradients (an 8B model) over a 400 Gb/s NIC (about 50 GB/s). Try 400 GB/s for NVLink inside a node.

Where the time goes under the loop

A collective is not just maths. The data crosses PCIe, a NIC, a switch, and the same trip back. Two things cost time that your model code never shows.

Copies. On the default path, a GPU kernel first copies your tensor into a communication buffer, and does so again on the receiving side. Those copies use GPU cores and memory bandwidth. With zero-copy, the NIC reads and writes your tensors directly through GPUDirect RDMA, with no staging copy and no copy kernels.

Default path: two copies

your tensor
on GPU
copy kernelNCCL
buffer
PCIe DMANICnetworkNICDMANCCL
buffer
copy kerneltheir tensor
on GPU

Zero-copy path: none

your tensor
on GPU
RDMA readNICnetworkNICRDMA writetheir tensor
on GPU
Red marks a copy. On the default path a GPU kernel copies your data into NCCL’s buffer, and does it again at the other end. With zero-copy the NIC reads and writes your tensors directly.

Distance. A message across the room is not the same as a message across a data centre.

This is why parallelism is arranged around the hardware: the chattiest dimension (TP) stays inside a node, and the traffic that tolerates delay (data parallel) goes across.

Code: measure bus bandwidth yourself

Run this with torchrun on 2 GPUs, then on 8, and compare the bus bandwidth with the link’s rated speed. The gap is your opportunity.

import os, time, torch, torch.distributed as dist

dist.init_process_group("nccl")
torch.cuda.set_device(int(os.environ["LOCAL_RANK"]))
x = torch.ones(256 * 1024 * 1024, device="cuda")             # 1 GiB of fp32

for _ in range(5): dist.all_reduce(x)                        # warm-up
torch.cuda.synchronize(); t0 = time.perf_counter()
for _ in range(20): dist.all_reduce(x)
torch.cuda.synchronize(); dt = (time.perf_counter() - t0) / 20

n, size = dist.get_world_size(), x.numel() * x.element_size()
algbw = size / dt / 1e9                                      # data size over time
busbw = algbw * 2 * (n - 1) / n                              # comparable to the link speed
if dist.get_rank() == 0:
    print(f"{dt*1e3:.2f} ms   algbw {algbw:.1f} GB/s   busbw {busbw:.1f} GB/s")

# run:  torchrun --nproc_per_node=8 bench.py

The core ideas, in short

  • Collectives: all-reduce, all-gather, reduce-scatter, all-to-all, broadcast, plus send and receive.
  • Ring all-reduce sends about 2(N−1)/N times the data size per GPU. Bus bandwidth scales the result so you can compare it with the hardware peak. Raw algorithm bandwidth falls as you add GPUs. Bus bandwidth does not.
  • GPUDirect RDMA gives a third-party device, such as a NIC, a direct data path to GPU memory over PCIe.
  • Zero-copy means the NIC reads your buffer directly. It skips the staging copies through internal buffers. In CTran it is also SM-free: a CPU thread drives the whole transfer, so no GPU cores are used for it.
  • TorchComms adds explicit communicators and pluggable backends. NCCLX is a backend. CTran is the host-driven transport inside NCCLX. It supports NVLink, IB/RoCE and sockets. TorchComms was announced in October 2025 as experimental. Its status has been changing, so check the repo and the speaker's article before relying on it.
  • Distance matters. The NCCLX paper reports latency of 7×, 15× and 30× the same-rack latency across racks, zones and data centres.

Try it

  1. Run all_reduce_perf from nccl-tests on 2 GPUs, then on 8. Plot bus bandwidth against message size.
  2. Work out the time for a ring all-reduce of 1 GB across 8 GPUs at 400 GB/s bus bandwidth. Then at 50 GB/s. Check: each GPU moves 2 × 7/8 = 1.75 GB, so 4.4 ms at 400 GB/s and 35 ms at 50 GB/s.
  3. Read the TorchComms post and draw the stack from your code down to the NIC. Mark where the copies are.

Check yourself tap a question for the answer

  • What does a zero-copy path skip?

    It skips the staging copies. A GPU kernel no longer copies your tensor into a communication buffer on send and out of it on receive, so no GPU cores are spent copying. The NIC reads and writes your tensors directly.

  • Why is tensor parallel kept inside a node?

    Tensor parallel does an all-reduce on the critical path of every layer, forward and backward, so it needs the highest bandwidth and lowest latency. That means the NVLink inside a node. Data-parallel traffic can overlap with compute and tolerate slower links between nodes.

  • Why did c10d fit the first ~10K GPU era, and what changed?

    c10d assumed regular, bulk-synchronous collectives, with the host knowing the metadata and an API that did not care about the backend. That fit training up to roughly 10K GPUs. Newer workloads (MoE all-to-all, compute and communication overlap, pipeline send and receive, KV cache movement, fault tolerance, 100K-plus GPU jobs and cross-data-centre training) need finer control, richer semantics and pluggable backends. That is the gap TorchComms aims at.

Questions that come up tap one to open it

Why does distance cost so much in a GPU cluster?

Farther means more switches, shared links and longer cables. Meta's NCCLX paper reports latency of 1× in one rack and 30× across data centres.

The numbers on Arkadip's slide: same rack 1×, cross-rack 7×, cross-zone 15×, cross-DC 30×. The NCCLX paper gives the same three figures, as latency compared with the same rack. I could not check how they were measured.

  • Each extra hop adds a switch, a queue and a chance of congestion.
  • Upper layers of a network are often shared, so traffic from many jobs meets there.
  • Longer cables add delay that no software can remove.

What to do about it: place by chattiness. Tensor parallel inside a node. FSDP or data parallel inside a rack or zone. Pipeline parallel, which sends less, across the far links. This is what “match the mesh to your topology” means.

Sources: Meta: RoCE networks for AI training · TorchComms blog · NCCLX paper

Go deeper read in this order

  1. NCCL user guide
  2. NCCL collectives Pictures of every collective.
  3. Ring all-reduce explained Gibiansky's classic walk-through.
  4. nccl-tests Measure real bandwidth on your cluster. Read doc/PERFORMANCE.md for how algbw and busbw are defined.
  5. GPUDirect RDMA
  6. Meta: RoCE networks for distributed AI training Why distance and topology matter.
  7. NCCL point-to-point Send, receive and grouped all-to-all.
  8. Demystifying NCCL The ring and tree algorithms and the Simple, LL and LL128 protocols.
  9. PyTorch Distributed is changing, and TorchComms is why (Red Hat, July 2026) Written by the speaker. It says c10d stays the user-facing API.
  10. RCCLX (Meta) CTran moving to AMD through torchcomms.
  11. TorchComms blog
  12. NCCLX / CTran paper Zero-copy and SM-free transfers. The core of the talk.
  13. Llama 3 paper Real cluster numbers and failures at scale.
  14. DeepEP A communication library for MoE all-to-all.
  15. NCCL docs: environment and tuning Look for the sections on environment variables and topology.

Capstone ideas

Pick one. A small, finished project beats a big one you never ship.

Glossary29 terms
Arithmetic intensityFLOPs per byte moved. Decides compute- or memory-bound.
ATenPyTorch's C++ tensor library. Names like aten::matmul come from here.
c10dPyTorch's default distributed communication layer.
Context parallel (CP)Splits a long sequence across GPUs.
Continuous batchingAdd and remove requests at every step, not per batch.
CTranThe transport layer under NCCLX. Supports IB/RoCE, NVLink and sockets.
CUDA graphRecord a set of launches once and replay them cheaply.
DCPDistributed checkpoint. Saves shards without communication, reshards on load.
DecodeGenerate one token at a time. Memory-bound.
DeviceMeshA named grid of GPUs, one dimension per kind of parallelism.
DTensorA tensor that knows how it is split across a mesh.
EpilogueWork right after a matmul: bias, activation, norm.
Expert parallel (EP)Different experts live on different GPUs.
FSDP / FSDP2Sharded data parallel. FSDP2 is built on DTensor.
GPUDirect RDMAA NIC reads and writes GPU memory directly.
GRPORL method that compares a group of answers to the same prompt.
KV cacheStored keys and values of earlier tokens, so they are not recomputed.
MoEMixture of experts. Each token uses only a few experts.
NCCLNVIDIA's GPU collective library.
Overhead boundThe CPU cannot launch work fast enough, so the GPU idles.
PD disaggregationRun prefill and decode on separate GPUs.
PrefillProcess the whole prompt at once. Compute-bound.
RadixAttentionSGLang's radix tree of cached prefixes.
Reward hackingScoring well without doing the task.
RLVRRL with verifiable rewards, graded by a program.
RoCERDMA over Ethernet.
Tensor parallel (TP)Splits each matmul across GPUs.
TTFTTime to first token.
Zero-copyThe NIC reads your buffer directly, with no staging copy.

From the event itself