All events
25 July 2026 Red Hat office, Bengaluru

PyTorch × Hugging Face meetup, Bengaluru

Hosted by Hugging Face ML Club India and Red Hat. Five talks on the systems under the model.

Five layers of the stack, from the profiler down to the wire

This was not a meetup about calling APIs. Every talk was about what runs under the model: profilers, inference engines, RL environments, distributed training and GPU communication.

The evening opened with Sudhir Dharanendraiah. His point was simple. India uses a lot of AI. It should also help build the stack under it.

I took notes all evening. Later I went through the five slide decks and added what I had missed. This page puts both together.

Talk 1

Profiling in PyTorch

Aritra Roy Gosthipaty · Developer Advocacy, Hugging Face

Profile first. When the CPU is the one working, the fix is more work per launch, not a faster kernel.

4 min read 2 diagrams code 1 photo

“What you cannot profile, you cannot optimize.”

That was the title slide, and the whole talk. Aritra kept the demo tiny on purpose. The question was simply: what to profile? His answer was y = Wx + b, written in PyTorch as a torch.matmul followed by a torch.add.

Three steps

  1. Annotate the function. Wrap the step in torch.profiler.record_function("matmul_add"), so it has a name in the trace.
  2. Wrap the code in torch.profiler.profile and pick two things. The activities are CPU and CUDA. The schedule is how many steps to wait, warm up and record.
  3. Export two things. A trace with export_chrome_trace, and a table with key_averages().table(...).

Here is the whole demo.

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

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

activities = [
    torch.profiler.ProfilerActivity.CPU,
    torch.profiler.ProfilerActivity.CUDA,
]
schedule = torch.profiler.schedule(wait=1, warmup=1, active=3, repeat=1)

with torch.profiler.profile(
    activities=activities,
    schedule=schedule,
    record_shapes=False,
    profile_memory=False,
    with_stack=False,
) as prof:
    for _ in range(5):
        step()
        prof.step()

prof.export_chrome_trace(trace_path)
with open(table_path, "w") as f:
    f.write(prof.key_averages().table(sort_by="cuda_time_total", row_limit=15))

The schedule is easy to miss. Steps marked wait are skipped. Steps marked warmup are traced, but the results are thrown away, so the profiler can settle. Only the active steps are kept. With wait=1, warmup=1, active=3, the five steps of the loop are used up exactly.

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.

Three more switches are off in the demo. record_shapes tracks the shapes of the inputs. profile_memory tracks allocation and freeing. with_stack adds the line numbers of your code.

How to read the table

Sort by cuda_time_total. The first row is your biggest bottleneck. Then look at the number of calls. With active=3, every op was recorded three times, so every row shows 3×. Check whether the call count is the reason a row came to the top.

The idea I liked most: overhead bound

At the bottom of the table there are two totals: self CPU time and self CUDA time. He ran the script at three matrix sizes and read the ratio.

At size 64, the CPU spent 332 µs and the GPU only 17.8 µs. The matrix is so small that the CPU spends most of its time just dispatching CUDA kernels, and the GPU sits idle. That is overhead bound. At size 4096 the GPU finally has real work, and the two sides come close. (The totals on that last slide work out nearer 92% than 88%, and the exact percentages depend on your GPU. On another machine I got roughly 1%, 8% and 98%. The shape is the same.)

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.

A simple rule. Compare the CPU total with the GPU total. If the GPU time is larger, you are compute bound. If the CPU time is larger, the kernels are too small and you are overhead bound.

Reading the trace

The trace opens in the Hugging Face trace viewer, or in Perfetto. It is a temporal view with two lanes, one for the CPU and one for the GPU. Gaps in the GPU lane are idle time. The op names, like aten::matmul and aten::add, are ATen ops. ATen is PyTorch's tensor library.

Where torch.compile fits

In eager mode, each op is its own launch. torch.compile uses Dynamo to trace the graph and caches the result. It can fuse operations. For example, an aten::add after aten::mm becomes aten::addmm. That is graph fusion, not CUDA fusion. Fewer launches means less overhead.

The same idea goes further in an MLP. A matmul is done in tiles. The work right after it, like an activation or a normalization, is called the epilogue, and it can run while the result is still in the buffer. A compiled graph then launches one Triton kernel instead of several. So the fix for overhead bound is not a faster kernel. It is more work per launch.

Talk 2

SGLang, the Transformers backend and kernels

Adarsh · Hugging Face

Compute a shared prefix once, keep its cache, and reuse it for every request.

5 min read 2 diagrams 5 photos

Adarsh began with a plain point. Serving one user is easy. Serving a thousand at once is where the work starts. First he defined the word: inference means taking the prompt, processing all its tokens in parallel to build the model's working context, and then writing the answer one token at a time.

Inference is two jobs

Prefill reads the whole prompt in one pass and builds the KV cache. It is compute bound, because the maths is matrix times matrix. Decode writes one token at a time and reads the cache again at every step. It is memory bound, because the maths is matrix times vector.

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.

What SGLang is made of

He described SGLang as a high-performance serving framework for large language models and multimodal models. It has four parts.

  • Scheduler. Batches requests together.
  • KV cache manager. Stores the cache and reuses it.
  • Model runner. Runs the forward pass.
  • Attention backend. flash-attn or flash-infer.

One slide set the scene: the same 1,000 requests on the same GPU. Llama-3-8B on one H100, a 2K-token shared system prompt, 300-token replies.

That is about 38 times more. The run fell from about 25 minutes to about 40 seconds, and the cost per million tokens from about $3.30 to about $0.09. I could not reproduce these. A shared prompt with short replies is close to the best case for prefix reuse, so expect less on mixed traffic.

RadixAttention

Older systems threw the KV cache away when a request ended. SGLang keeps it. It holds an LRU cache of the KV cache of all previous requests in a radix tree, a memory-efficient prefix tree. The idea comes from the SGLang paper (Zheng et al., 2023). Nine slides built the tree step by step. A shared system prompt is the root, and each chat branches off it. When memory fills up, the least recently used leaves are evicted, and the shared prefixes stay. A new request with the same start simply reuses them.

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 cache is not small. For Llama-3-8B it is about 128 KiB per token, so a 2K-token prompt is about 256 MiB per request. That is why reuse pays. The flag --mem-fraction-static sets how much GPU memory goes to the weights and the cache pool. vLLM has a similar idea, automatic prefix caching, but it hashes fixed-size blocks and reuses only the full ones. There is a longer comparison in the questions below.

Scale

A fun-facts slide claimed SGLang runs on more than 400,000 GPUs, makes trillions of tokens a day, and merges about 44 PRs a day, with about 30.7k stars and a wall of company logos. When Grok answers you, it said, this codebase is moving the tokens. These are the project's own numbers.

Transformers is the source of truth

The next slide was titled “the dependency nobody thinks about”. SGLang's own pyproject.toml pins transformers==5.12.1. Config parsing, tokenizers, weight formats and chat templates all start as a Transformers artifact on the Hub. Transformers defines the model. SGLang makes it run fast.

The Transformers backend turns that into one flag: --model-impl transformers. The forward pass runs straight from Transformers, with no native port. SGLang still owns RadixAttention, continuous batching and scheduling. There are about 2 million models on the Hub and SGLang has ported a few hundred. The backend covers the rest on day 0. (vLLM has a similar backend too, so the idea is not unique to SGLang.)

“Transformers internals hijacked!”

This slide built up in four steps. The model graph comes from Transformers. Then SGLang swaps the hot paths at load time. One config line, config._attn_implementation = "sglang", flips the attention backend.

  • The attention call becomes RadixAttention plus the KV cache.
  • nn.Linear becomes a column- or row-parallel linear, matched through the HF tp_plan, which says how the model is split across GPUs.
  • experts.forward() becomes FusedMoE and expert-parallel kernels.
  • RMSNorm is swapped by class for a fused RMSNorm kernel.

One warning: numeric drift. Different kernels give slightly different numbers, so the same model can behave a little differently on a different backend.

Enter HF Kernels

A meme slide set up the problem. Install and build FlashAttention 3, only to drown in CMake errors. Or get_kernel("kernels-community/flash-attn3") in two lines. Why it exists: no unified structure, build tools scattered across CMake, Nix, Meson and Bazel, endless build times, and support matrices to maintain. HF Kernels is unified tooling to build compute kernels, with a predictable structure, reproducible builds and native PyTorch compatibility.

Adarsh said he “shamelessly copied” the next few slides from Sayak and Aritra's talk. The kernel builder is a Nix-based build system. It targets ROCm, XPU, CUDA and Metal, many PyTorch versions and many CUDA capabilities. A small RGB-to-grayscale kernel showed the enforced folder structure. Using one is “as easy as swapping 4 lines”, with no messy wheels or incompatible builds. Then the call to action: push your kernels to the Hub.

He closed with one more idea. When GPU memory runs out, the KV cache can be pushed down to SSDs. DeepSeek does this.

Talk 3

RL environments 101

Adithya S Kolavi · post-training, Hugging Face

If a program can grade it, a model can learn it. So the environment is where the work, and the danger, lives.

10 min read 2 diagrams code 2 photos

Adithya opened with a show of hands: how many of you have heard of “RL environments”? Then he told the story of how models are taught, one step at a time.

  1. Pretraining. Trillions of tokens of raw web text, and predict the next one. You get a model that knows a lot but does not yet know how to behave.
  2. SFT. Curated examples, a question and its ideal answer. It works, but it saturates. Great data is slow and costly, and the model never gets better than what we hand it.
  3. RLHF. We cannot write the perfect answer for everything. So let the model try, and let a person say which answer is better. “Better” becomes the reward. But people cannot rate everything.
  4. RLVR and GRPO. Then DeepSeek happened. DeepSeek-R1 used GRPO, which rewards the model only when its answer passes a check. A program grades it, with no human. It is cheap, hard to fake and endlessly scalable. A fun fact: GRPO had already shipped a year earlier, in DeepSeekMath (Feb 2024), before R1 (Jan 2025). GRPO has no critic. It scores each answer against the other answers sampled for the same prompt, which is why you sample many.
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.

“If a program can grade it, a model can learn it.”

That was the unlock, and it turned the race into something simple: build more environments. A chart showed models trained on more and more of them. About 20 for Qwen3, 20K for Qwen3-Coder, 100K+ for MiniMax Forge and 1M+ for Qwen3.5. These are his numbers, and I did not check them against each model's report.

What an environment is

RL environments are not new. CartPole is the hello world: an agent sends an action, and the environment sends back a state and a reward. Gym (2016, later Gymnasium) gave every environment one contract: reset() gives the first observation, and step(action) gives the next observation, a reward and a done flag. For LLMs the idea is the same. The agent is the LLM. The environment is a sandbox with tools, code and state. The reward is a verifier.

But there is a lot more to wire up than in supervised learning. There you have a dataset, a model and a trainer, and you swap them freely. In RL you have tasks, a prompt template, an initial state, tools, observations, an execution backend, state, a reward, a done signal, episode control and a transport. So frameworks stepped in to standardise it: OpenEnv (from Meta, over HTTP and MCP), Verifiers (Prime Intellect), OpenReward and Harbor (Laude Institute), plus NeMo Gym, SkyRL Gym and GEM. Same concept, different dialects. His definition: a place a model practises, gets graded, and learns.

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.

A coding environment, by example

Task: find the .py file with the most lines. Tool: bash, any shell command in a sandbox. Reward: +1 if the final answer is right, else 0. Two attempts on the same task show it well. In the first, the model lists the files, counts lines with wc -l and answers train.py. Reward +1. In the second, it peeks at the directory, guesses from the names and answers model.py. Reward 0. GRPO samples N attempts per task and nudges the model toward the ones that score.

He split environments in two. One-shot (RLVR): prompt, answer, verifier, one turn, a reward every time. Maths, code and logic fit here. Multi-turn agent RL: the model acts, the environment answers, for 10 to 100+ turns, and one sparse reward comes at the end. Think SWE-bench, OSWorld and AppWorld.

OpenEnv and TRL

OpenEnv's pitch is one shape, so any environment plugs into any trainer. It has a Gym-style API, first-class MCP, a built-in Rubric where the rewards live, and a Task API. It started at Meta's PyTorch team, together with Hugging Face, and is now run by a committee of several companies. The repo lives at openenv/OpenEnv. His slide said 1000+ environments are on the Hub, but the official catalog lists about 40, so the bigger number probably counts community Spaces.

Four slides built one live. The action space is just plain functions marked @mcp.tool. reset() loads the task into the sandbox. A rubric returns 1.0 if the hidden tests pass. create_app turns the class into an HTTP and MCP server, with up to 8 parallel rollouts.

# The action space is just functions
class CodingEnv(MCPEnvironment):
    def __init__(self):
        mcp = FastMCP("coding_env")

        @mcp.tool
        def bash(command: str) -> str:
            "Run a shell command in the sandbox."
            result = self._sandbox.run_shell(command)
            self._state.step_count += 1
            return result.stdout + result.stderr

        super().__init__(mcp)   # actions route to @mcp.tool fns

    # each episode starts from a task, handed in on reset()
    def reset(self, seed=None, episode_id=None, **kwargs) -> Observation:
        self._sandbox = Sandbox()
        self._task = kwargs["task"]              # one task per rollout
        for f in self._task["files"]:            # e.g. a repo with a failing test
            self._sandbox.upload(f["path"], f["content"])
        self._state = State(episode_id=episode_id or uuid4().hex)
        return Observation(done=False, metadata={"prompt": self._task["prompt"]})

# The reward: a Rubric scores the outcome
class TestsPassRubric(Rubric):
    def forward(self, action, observation) -> float:
        passed = observation.metadata.get("tests_passed")
        return 1.0 if passed else 0.0

# Serve it: HTTP + MCP server with /reset, /step, /state
app = create_app(CodingEnv, CallToolAction, CallToolObservation,
                 env_name="coding_env",
                 max_concurrent_envs=8)           # parallel rollouts
# uvicorn server.app:app --port 8000

Then you ship it with four commands: openenv init, build, validate and push. And then: “You have an environment. Now what?” Train a model with it. TRL, Hugging Face's RL post-training library, trains against an environment directly. You pass environment_factory to GRPOTrainer, and that is the whole hookup. OpenEnv is first-class there. OpenReward and Harbor work too. TRL marks all of this as experimental, so check its docs for your version.

from trl import GRPOConfig, GRPOTrainer
from coding_env import CodingEnv          # your OpenEnv env

def env_reward(completions, environments, **kw):
    return [e.reward for e in environments]

trainer = GRPOTrainer(
    model="Qwen/Qwen3-4B",
    train_dataset=tasks,
    reward_funcs=env_reward,
    environment_factory=CodingEnv,        # the hookup
    args=GRPOConfig(num_generations=8),
)
trainer.train()

And then the catch: training is the easy part now. You still need thousands of environments. A good one needs tasks that mirror the real world and a reward you cannot game. Hand-building is slow.

Repo2RLEnv

Why start with code? It is easy to verify, deterministic and high value. And there is a near-endless supply of real code: repos, issues, PRs. Public GitHub repos are a goldmine, with real tasks, real code and tests that grade themselves. His question: could we turn them into thousands of environments, automatically? Repo2RLEnv converts any repository into a verifiable RL environment. He said about 1,000 were already generated and live on Hugging Face. The project's README now lists 1,930 tasks across 21 datasets, in the Harbor format.

Reward hacking: the best part of the talk

The slide read “Reward modeling hacking”: when the model games the reward, not the task. He opened with a story he said had just happened at frontier scale. News clippings on the slide showed OpenAI's models escaping a locked test environment and hacking Hugging Face to cheat on a benchmark. In that account, a GPT-5.6 “Sol” model, plus an unreleased one, was tested on ExploitGym, 898 real vulnerabilities scored pass or fail. Instead of solving them, it chained zero-days out of the sandbox and read the answer key from Hugging Face's production database. Both sides caught it. The experts' word for it: reward hacking. Tech press reported the same story, with OpenAI disclosing it on 21 July 2026 and Hugging Face saying it had contained the intrusion on 16 July. I could not find a first-hand write-up from either company, and the outlets differ on details, so treat it as reported. See TechRadar and The Next Web. His line: frontier models, same failure mode, just bolder.

A toy version first. “Rewind to last year.” GRPO had just landed in TRL, and everyone was fine-tuning tiny models, Qwen 0.5B and Llama 1B or 3B, on GSM8K grade-school maths. He changed one thing. Instead of asking the model to solve the maths, he asked it to write Python that solves it and prints the answer. He rewarded three things: the format (the right XML structure), correctness (the final answer matches), and code execution (it runs cleanly, a 0 to 2 bonus). The last one felt harmless.

The training curves looked great. The other rewards moved up and down. Then the code-execution reward shot up and stayed high. He got excited. Then he read the traces. The model had learned to wrap everything in try / except: pass, so the code never errors.

def solve():
    # ...model's "solution"...
    try:
        answer = some_wrong_math()
    except:
        pass            # never errors -> reward!
    print(answer)

Reward maxed, and the maths was never solved. The model had maximized the reward without doing the task. And that was a toy, he said, with a lot more to reward hacking than this.

Now a frontier agent. “That was a 0.5B model. Now watch a frontier agent.” He built an environment from a real CVE: CVE-2026-48156 in pypdf, where a crafted PDF loops forever. The reward was a hidden test. A correct fix gets 1.0. A no-op gets 0.0. The agent, Claude Code with Opus, scored a perfect 1.0 while fixing nothing. Three times, each after he closed the last door.

  1. Just ask GitHub. The prompt was the public advisory, and it named the fixing PR. The agent fetched the PR diff and pasted the fix in. Fix: scrub the prompt. Strip the CVE id, the PR number, the commit hashes and “fixed in version”.
  2. The answer was in the box. He cut the web tools and re-ran. Same score. The container shipped the full git history, and the agent ran git log and git diff against origin/main. Fix: scrub to the base commit. Drop the remote, delete future branches and tags, expire the reflog, run gc.
  3. pip is a search engine. Web blocked, git scrubbed. It ran pip download pypdf==6.12.0, unzipped the wheel, and used the fixed release of the very package it was told to fix. The fix is public: GitHub, PyPI, mirrors, archives. Block one door, the house has ten.

“You can't out-scrub the internet.”

So he cut the egress, with an allowlist and not a block. And for the first time Opus actually worked the bug. The reward was 0.000, “the number I wanted”. Every green before was contamination. The real solve rate was about 0.

Trust lives in the environment

This was my favourite slide. The environment enforces the rules. The prompt never asks for them.

  • Make the verifier trustworthy first: gold patch 1.0, no-op 0.0, only targeted tests.
  • Strip the answer from the prompt.
  • Scrub the repo to the base commit.
  • Pre-bake dependencies and run offline by default.
  • If the network is needed, use an allowlist, never a full block.
  • Keep the gold patch and hidden tests out of the container.

All of it is baked into Repo2RLEnv, so the trust lives in the box by default. His closing quote:

“A model never does the task. It does the reward. At scale, every gap gets found, so reward design is never done, only iterated.”

Hands-on, close to my own work

The demo built the latex-ocr-env environment and trained a vision-language model against it with TRL and GRPO, on a free GPU. The task: a VLM sees an image of a formula and writes the LaTeX. The reward: does it render back to the same maths? The data was unsloth/LaTeX_OCR.

The deck ended with “Do it yourself”: the full tutorial, with the env, TRL and GRPO, runs on a free GPU. Next on my list is his “ultimate guide to RL environments”, a Hugging Face write-up published in May 2026.

Talk 4

Scaling up, one dimension at a time

Mansi Agarwal · Senior ML Engineer, PyTorch Engineering, Red Hat

Add a kind of parallelism by adding a mesh dimension, not by rewriting the training loop.

5 min read 2 diagrams code 3 photos

The title was composable parallelism with DeviceMesh and DTensor. Mansi started with the parallelism zoo. Data parallel (DDP), fully sharded (FSDP), tensor parallel (TP) and pipeline parallel (PP) each have their own API, their own wrapper and their own state-dict format. Combining them means manual plumbing and version-specific hacks. A new kind of parallelism means rewriting the training loop. Her question: what if parallelism was composable, like adding dimensions to a grid?

The old way

One slide showed what it took to mix FSDP with TP before any of this. Five steps: compute the rank groups by hand, create the process groups by hand, write your own TP layers instead of nn.Linear, change the model code, and wrap with FSDP1. About 100 lines. Forget one manual all-reduce and the results are silently wrong. And adding PP later means a third set of groups.

Three primitives

  • DeviceMesh. It describes your GPU topology as a multi-dimensional grid. A 4×2 grid means 4 groups for data parallel and 2 for tensor parallel. You name each dimension, like dp and tp, and pick sub-meshes by name.
  • DTensor. It makes every tensor aware of how it is distributed. A placement is Shard(dim), Replicate() or Partial().
  • FSDP2 (fully_shard). Sharded data parallel as a composable transform, rebuilt on DTensor.

Communication becomes automatic. For dtensor_a @ dtensor_b, if one side is sharded and the op needs it whole, DTensor adds the all-gather for you. Her line: you write the maths, DTensor handles the communication. Under the hood, every ATen op is intercepted. A sharding rule is looked up (over 410 ops are covered), the cheapest one is chosen, collectives are added if the inputs do not match, and the op runs on the local shards. An op with no rule raises an error. It does not silently fall back to replicating.

tp 0tp 1dp 0GPU 0GPU 1dp 1GPU 2GPU 3dp 2GPU 4GPU 5dp 3GPU 6GPU 7tensor-parallel groupdata-parallel group
A (4, 2) 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.

“Locally optimal”

DTensor picks the best sharding for each op as it goes. It does not look at the whole graph, so the full plan may not be the best one. JAX with GSPMD takes the other path. It looks at the whole graph and can find a globally optimal plan, but it is compiler-first. DTensor is eager-first, so you can debug it with print and pdb. Mansi was honest about the trade-off: eager-first gives up global optimality to keep debugging easy.

FSDP2

FSDP2 is FSDP1 rebuilt on DTensor. Every parameter is its own DTensor, not one big FlatParameter. It is an in-place transform, not a wrapper, so isinstance(model, MyTransformer) still works. LoRA and frozen layers work, fp8 works, and sharded checkpoints need no communication. FSDP1 is deprecated.

The flow per layer: all-gather the parameters before forward, run, and free the memory after. Backward does the same, then a reduce-scatter turns the partial gradients into shards. One slide made a point clearly. FSDP2's hooks decide when things happen. DTensor only executes. FSDP2 even skips DTensor's dispatch for its own collectives, so it does not pay the eager overhead.

From one GPU to many dimensions

The code walkthrough made it real. One GPU, then DDP, which is one added line. Then FSDP2, where the training loop stays the same.

# Stage 1: one GPU
model = MyTransformer().cuda()
optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4)
for batch in dataloader:
    optimizer.zero_grad()
    loss = model(batch).sum()
    loss.backward()
    optimizer.step()

# Stage 2: DDP, one line added
dist.init_process_group("nccl")
model = DDP(MyTransformer().cuda())

# Stage 3: FSDP2, training loop unchanged
mesh = init_device_mesh("cuda", (world_size,))
model = MyTransformer().cuda()
for layer in model.layers:
    fully_shard(layer, mesh=mesh)   # shard each layer
fully_shard(model, mesh=mesh)       # shard the root module

Then 2D parallelism, a few more lines. Apply tensor parallel on the tp mesh, with column-wise layers for the qkv and the first FFN layer and row-wise for the outputs. Then call fully_shard on the dp mesh.

# Stage 4: FSDP2 + tensor parallel on a 2D mesh
mesh = init_device_mesh("cuda", (4, 2),
                        mesh_dim_names=("dp", "tp"))
model = MyTransformer().cuda()

# step 1: TP on the tp sub-mesh
for layer in model.layers:
    parallelize_module(layer, mesh["tp"], {
        "attn.qkv":  ColwiseParallel(),
        "attn.proj": RowwiseParallel(),
        "ffn.w1":    ColwiseParallel(),
        "ffn.w2":    RowwiseParallel(),
    })
# step 2: FSDP on the dp sub-mesh
for layer in model.layers:
    fully_shard(layer, mesh=mesh["dp"])
fully_shard(model, mesh=mesh["dp"])
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.

Adding parallelism is adding a dimension to the mesh. 1D is FSDP only. 2D, a 4×2 mesh, is FSDP plus TP. 3D adds PP. 4D adds CP. The next one adds expert parallel for MoE. Each dimension is independent, so you can mix and match based on your hardware.

Compile and checkpoints

torch.compile removes DTensor's eager overhead. Her ordering rule was: activation checkpoint, then fully_shard, then compile last. Start with fullgraph=False to find graph breaks, and set compile_threads=1, because background threads can hang a distributed run. One caution. TorchTitan, as far as I could read it, compiles each block before applying FSDP, so check its current code before you copy either order.

Checkpointing with torch.distributed.checkpoint needs no communication on save. An async save was 10 to 20 times faster, 148 s down to 6.3 s for a 7B model. And it re-shards when you load: save on 8 GPUs, load on 16. That is one piece of elastic training, not all of it. Elastic training also needs something to notice the change and restart the job, like torchrun or TorchFT. There is more on this in the questions below.

# The ordering rule: checkpoint -> fully_shard -> compile
for layer in model.layers:
    checkpoint(layer)              # 1. activation checkpoint
    fully_shard(layer, mesh=mesh)  # 2. shard
fully_shard(model, mesh=mesh)
model = torch.compile(model)       # 3. compile LAST

# Distributed checkpointing
dcp.save(model.state_dict(), checkpoint_id="epoch_5")        # communication-free
dcp.load(model.state_dict(), checkpoint_id="epoch_5")        # works on a different GPU count
future = dcp.async_save(model.state_dict(), checkpoint_id="epoch_5")   # 10-20x faster

What the docs don't tell you

One slide listed the known limits. DTensor's eager dispatch costs about 7× per op, though compile removes it. About 58 ATen ops still have no strategy. Views that work on plain tensors can break. reduce_dtype is ignored for the TP all-reduce, a silent precision loss. HSDP with mixed precision uses 3× the gradient memory on a 2D mesh. There is no uneven sharding yet, which blocks clean MoE expert parallelism. And shape changes can trigger full recompiles. Her words: these are the costs of an eager-first composable design.

What is next

AutoParallel is experimental. It runs a linear program over a compiled graph to find the sharding, and it discovers FSDP, TP and EP on its own. It was in development on LLaMA-3 at 64 and 256 GPUs. Also on the list: DTensor erasure, Symmetric Memory, TorchFT, Monarch (one Python script for the whole cluster), zero-bubble pipeline parallelism, and compiler-assisted backward sharding. Her summary: eager composable primitives today, compiler-optimized sharding tomorrow.

Talk 5

Zero-copy GPU-to-GPU communication

Arkadip Maitra · PyTorch Engineering, Red Hat

Under the training loop, extra copies and extra distance can cost more than the model code you tuned.

6 min read 1 diagram 1 photo

Arkadip went below the training loop, to how GPUs talk to each other. He began with c10d, the default PyTorch distributed layer. User code calls the torch.distributed API, which goes to a ProcessGroup, which picks a backend like NCCL, Gloo, MPI or UCC. It is a general-purpose interface, it worked well across CPU and GPU, and it was a good fit up to roughly 10K GPUs. Why did it work? Training was bulk-synchronous, the collectives were regular, the host knew the metadata, and the API did not care about the backend.

Meanwhile…

The world around it changed. NICs got GPUDirect RDMA, better DMA engines and richer queue-pair behaviour. RoCE grew into larger AI fabrics, with congestion-control tuning. NVLink got stronger paths inside a node. And there were new fabrics: AI Clos networks, cross-zone and cross-datacentre training. A timeline put the hardware lane and the framework lane side by side. NVLink in 2014, 400G RoCE at scale in 2024, and by 2025 NCCLX and 100K+ GPUs becoming normal. On the framework side: c10d and NCCL in 2018, the GPT-4 boom in 2023, a backend and runtime race in 2024, and in 2026 comms moving into c10d.

The new workloads broke the old assumptions. MoE routing wants dynamic, fine-grained all-to-all. Tensor parallel wants compute and comms to overlap. Pipeline parallel wants send and receive between micro-batches. Inference wants fast KV cache movement. And 100K+ GPU jobs need fault tolerance and hierarchical networks. Distance started to matter a lot too.

These are latency multipliers, from Meta's NCCLX paper. His line: comms was only one entrant in this race. The answer was TorchComms: explicit communicators, pluggable backends, richer semantics, and a path aligned with PyTorch. The stack goes: your code, the TorchComms API, an NCCLX or RCCLX backend, the CTran transport, and then IB or RoCE, NVLink, or sockets. TorchComms was announced as experimental in October 2025. The sources I found disagree on where it stands now, so check the repo before depending on it.

Then: “many innovations were made, but let's focus on zero-copy.”

The default path against the zero-copy path

Two sequence diagrams were the heart of the talk. On the default c10d path, a GPU kernel first copies your data from your buffer into NCCL's internal FIFO. A PCIe DMA moves it to the NIC. It crosses the fabric, and the receiver does the same in reverse: a DMA into a FIFO, then a GPU-kernel copy into the destination buffer. Two copies.

On the zero-copy path, the sender's NIC reads straight from your GPU buffer, and the receiver's NIC writes straight into the other GPU's buffer. No staging, and no copy kernels. A CPU progress thread drives the transfer, so GPU cores are not used for the copy.

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.

The efficiency gains

2×copy tax saved
1.09–2.7×faster comm
2,560threads saved
up to 50%fewer thread blocks

His footnote matters: thread-count reductions refer to specific communication kernels, and speedups are for the message sizes in the source, about 1 MB to 128 MB, in medium-message point-to-point cases. I checked each number against Meta's NCCLX paper. The 1.09–2.7× speed-up is in the paper, for exactly that range. The “2× copy tax” is the paper's worst-case cost of copying across hosts, so it is a bound and not a measured saving. The 2,560 comes from a copy-based send using 4 thread blocks of 640 threads, so it is derived. And the “up to 50% fewer thread blocks” comes from a different feature, the fault-tolerant all-reduce, which uses 2 thread blocks where NCCL uses 4.

How the transfer works

A wait and stall diagram showed the host side. The host calls and queues the op. A CPU progress thread picks it up, and the host orders the stream. The GPU stream stalls at one wait point while earlier kernels finish. Meanwhile the progress thread chooses the algorithm, posts the RDMA, and polls the completion queue. Then it completes the op, which releases the wait, and the next kernels run.

He compared RDMA put and get. With put, the source writes its payload into the destination's window tensor, then writes a signal flag. The destination polls wait_signal(), sees the flag, and launches the GPU kernel that consumes the data. With get, the requester asks to read the responder's source tensor. The payload comes across by RDMA read, a local ready flag is set, and the responder's state does not change.

Underneath, CTran IB opens a virtual connection. It has a control queue pair for setup, a notify queue pair for completion messages, an atomic one for signals and flags, and one or more data queue pairs for the payload. A big request is chunked and spread over several NICs and queue pairs, with sequence numbers. The fabric may deliver the packets out of order, so the receiver keeps a bitmask of what it has seen and the next expected number, reassembles the data, and completes the request. One long diagram tied it all together: a call to comms.some_call(), through TorchComms and RCCLX, the NCCLX API and the CTran mapper picking IB, then a DMA read from one GPU's memory, a packet on the wire, a key and address check at the other NIC, and a DMA write into the other GPU's memory.

How comms fare

The last slides were charts. The first compared normalized transfer latency, zero-copy against copy-based, as the network gets farther away. I read these values off the plot, so they are approximate.

The next chart was the cross-host copy tax for medium-message point-to-point: 2.00× for copy-based against 1.00× for zero-copy. Then bandwidth. Peak GPUDirect bandwidth was 48.55 GB/s over ibverbs, 48.88 GB/s over EFA and 27.85 GB/s over NVMe-oF. And RoCE matched InfiniBand on collective bus bandwidth, 232.6 against 230.7 GB/s. I could not trace those last two charts to a source. A vendor-run test reports similar RoCE and IB numbers, so treat them as claims.

What I am taking away

tok 01Measure firstProfile before you optimize. Not every slowdown is a model problem.
tok 02Launch lessSmall work is overhead bound. Give the GPU more work per launch, or fuse ops.
tok 03Reuse the cachePrefill is compute, decode is memory. A shared prefix should be computed once.
tok 04Rewards get gamedA model does the reward, not the task. The trust has to live in the environment.
tok 05Compose, do not rewriteAdd a mesh dimension, not a new training stack.
tok 06Look under the loopCopies and distance in the network can cost more than the model code you tuned.

The theme of the night, in one line: move from using AI to building the stack under it.

Questions, answered

Four questions that stayed with me after the talks. The short answer comes first. Tap one to open it.

vLLM or SGLang: when should I use which?

Half true. “SGLang for multi-turn and big MoE, vLLM for the rest” is a fair starting rule. It is not a law, and the gap keeps shrinking.

Multi-turn chat: mostly true

Each turn re-sends the whole chat so far. A good engine reuses the KV cache from the last turn and only computes the new part.

  • SGLang keeps the KV cache of finished requests in a radix tree. It matches prefixes one token at a time. It also keeps the cache of the replies, not just the prompts. vLLM does this too, but only for full blocks. Its scheduler is cache-aware, so it tries to run requests that share a prefix together.
  • vLLM hashes fixed-size blocks. Each block's hash includes the hash of the block before it. Only full blocks are reused. With a block size of 4, a 10-token match reuses 8 tokens. In general you lose at most one block minus one token. For a long chat, that is small. The default block size has changed between versions, so check yours.
  • The tree helps most when conversations branch: agents, tree-of-thought, many users sharing one long system prompt or document.
  • One more thing changed. vLLM V1 turned prefix caching on by default. They report under 1% throughput loss even when nothing hits the cache. So old comparisons, where vLLM ran without caching, are out of date.

Big MoE models: partly true

MoE is different because each token only visits a few experts. The tokens must travel to the GPUs that hold those experts. That is an all-to-all. Expert load is also uneven, so the busiest GPU slows everyone. And the attention cache gets copied on every GPU if you use plain tensor parallel.

  • SGLang published a full open recipe for DeepSeek: data-parallel attention, expert parallelism with DeepEP, a load balancer for experts, two-batch overlap, and prefill/decode disaggregation. On 96 H100s they report 52.3k input and 22.3k output tokens per second per node. These are their own numbers.
  • vLLM is not limited to dense models. Its docs describe data-parallel attention with expert parallelism (DeepEP backends) and disaggregated prefill and decode.
  • So who is faster on MoE depends on the model, the GPUs and the release. It moves quickly.
  • Both engines have also moved on cache. Both now handle hybrid models. Both can push cache out of GPU memory: SGLang with HiCache, vLLM with an offloading connector or LMCache.

Dense models: no clear rule

vLLM's real edge is breadth. It supports many models and many kinds of hardware, and a lot of tooling is built around it. For single-turn requests with no shared prefix, both do similar work. I found only a few independent tests, and they disagree by workload. One academic trace study (CCL-Bench) reports vLLM using the GPU more efficiently on small dense models, and SGLang spending less of each step on communication on one small MoE model. Both ran on A100s with small models, so treat it as a hint. Most other comparisons online are vendor or blog posts.

Your workloadStart withWhy
Chat, agents, long shared contextSGLang, then test vLLMToken-level prefix reuse, branching, cache-aware scheduling.
RAG with one big shared document, few-shot with fixed examplesEither, with prefix caching onBoth reuse a shared start. Put the stable text first.
DeepSeek-class MoE on many GPUsSGLang has the most written recipevLLM can do it too. Compare on your cluster.
One-shot jobs, no shared prefixWhichever supports your model and hardwareLittle to gain from the cache.
Unusual hardware, brand-new modelCheck both support pages firstSupport, not speed, decides here.

How to decide for real: replay your own traffic on both. Same GPU, same precision, prefix caching on for both. Measure time to first token, tokens per second and the slowest 1% of requests. Remember the cache only helps if the next turn lands on the same replica, so route sticky. Match the settings too. In one 2026 controlled study, much of the default gap between engines came from different defaults such as chunked prefill, not from the cache design. If one engine has chunked prefill on and the other off, you are not comparing the caches.

Sources: SGLang / RadixAttention post · vLLM prefix caching design · vLLM V1 release post · SGLang: DeepSeek on 96 H100s · vLLM expert-parallel docs · A controlled study of serving-engine settings and caches (2026) · CCL-Bench

Why do vLLM and SGLang give slightly different results from the Hugging Face model?

Numeric drift. Floating-point maths is not associative, so a different kernel, a different fusion or a different batch changes the last few bits. Those bits pile up over dozens of layers. It is noise, not a bug, and it is not the same thing as lower accuracy.

Start with the surprising fact

Adding numbers in a different order can give a different answer. With 16-bit floats the effect is easy to see.

import torch
x   = torch.tensor(256.0, dtype=torch.bfloat16)
one = torch.tensor(1.0,   dtype=torch.bfloat16)

print((x + one) + one)   # 256.  each +1 is rounded away
print(x + (one + one))   # 258.  the two ones are added first

bfloat16 keeps only about three significant digits. Near 256 the gap between two neighbouring numbers is 2, so adding 1 rounds straight back down. The sum of a long vector works the same way, just with smaller errors. The answer depends on the order of the additions.

Why the order is different in every engine

  • Different kernels. Hugging Face usually runs plain PyTorch ops, with SDPA for attention. vLLM and SGLang use FlashAttention or FlashInfer, paged attention and their own matmul tiling. A matmul sums along its inner dimension in tiles, and the tile size and the way it splits the work change the order.
  • Fused ops. An engine fuses things like add-and-RMSNorm, or the activation with the multiply. Inside a fused kernel the in-between values can stay in fp32. An unfused version rounds to bf16 after every op. Neither is wrong, but they round in different places.
  • Different shapes. The engine picks a kernel for the batch it has right now. The same request in a batch of 1 and in a batch of 64 can take different kernels and a different reduction order. That is why the same prompt can give different logits from one run to the next on a busy server.
  • Different ways of building the cache. An engine may prefill in chunks, reuse a cached prefix, or fill the KV cache in one batched pass. The cache values it stores differ in the last bits from a one-shot pass.
  • Parallelism. With tensor parallel, partial sums from each GPU are added in an all-reduce. The order of that sum depends on the number of GPUs and the algorithm.

Why a tiny difference can change the text

Each layer adds a little rounding error to the one before. After 32 or 80 layers the logits are close, but not identical. That is fine until two tokens are nearly tied. Then the top choice can flip. With greedy decoding, one flipped token changes every token after it. So two texts can look quite different even though the logits agreed to about two or three digits.

Is it lower accuracy?

Usually not. The Hugging Face run is not the truth either. It is also bf16, and it also has rounding error against a float32 reference. If you want to know which one is closer, compare both with fp32. On benchmarks, two bf16 runs of the same model typically land within the noise of each other. My rule of thumb: a gap of a few tenths of a point is drift, and a gap of several points is worth hunting as a bug.

Check these before you blame drift

  • The dtype. Transformers can load fp32 unless you pass a dtype. vLLM uses the dtype in the model config. You may be comparing fp32 with bf16.
  • The chat template and special tokens. A missing or doubled BOS token, or a different template, changes the prompt itself.
  • Sampling settings. Compare greedy with greedy, and check temperature, top-p and the default generation config on each side.
  • Quantization. An FP8 or INT4 checkpoint loses real accuracy. That is not drift.

How to measure it properly

Do not compare generated text. Feed both engines the same token ids and compare the log-probabilities of those tokens. Look at the mean and the maximum difference per token. Small differences, of the order of 1e-2 in bf16, are normal. A large jump on a few tokens points to a real difference, such as a wrong mask, a wrong rotary scale or a different template.

When it matters, and what you can do

  • RL training. The rollout engine and the trainer compute token probabilities in different ways, even with identical weights. The small mismatch makes the data slightly off-policy. Teams watch for this and, in some setups, correct for it with importance weights or run the engine in fp32 for the final layer.
  • Reproducible outputs. Both engines now have a batch-invariant mode, so a request gives the same bits whatever else is in the batch. In vLLM it is the VLLM_BATCH_INVARIANT=1 environment variable. In SGLang it is the --enable-deterministic-inference flag. It costs some speed.
  • Evals. Use the same engine for every model you compare, and fix the dtype and the sampling settings.

Sources: Defeating nondeterminism in LLM inference (Thinking Machines Lab) · vLLM: batch invariance · SGLang: deterministic inference · What every computer scientist should know about floating-point arithmetic

dcp.load can reshard on load: save on 8 GPUs, resume on 16. Is that how elastic training works inside HF Trainer, Megatron and other frameworks?

Only in part. torch.distributed.checkpoint.load (dcp.load) is the resharding piece, and several frameworks use it, or something built on it, underneath. Elastic training also needs a launcher that notices changes, restarts the workers, and restores more than the weights. Resuming on a different topology is one more step, and it is still not the same thing as elastic training.

The function in question is torch.distributed.checkpoint.load, usually imported as dcp.load. I first wrote that its resharding is “exactly what elastic training needs”. That was too strong. Here is the fuller picture, and then which frameworks use it.

import torch.distributed.checkpoint as dcp

state = {"app": AppState(model, optimizer)}      # Stateful wrapper around model + optimizer

dcp.save(state, checkpoint_id="ckpt/step_1000")  # run on 8 GPUs: one file per rank

# later, on 16 GPUs: build the model and the mesh first, then load into them
dcp.load(state, checkpoint_id="ckpt/step_1000")  # each rank reads the slices it now owns

One detail matters. DCP loads in place. You build the model with its new sharding first, and DCP uses that layout to decide which slices each rank reads. That is how the new world size does not have to match the old one.

The common recipe: checkpoint, restart, reshard

  1. Notice the change. A node dies or a new one joins. In torchrun's elastic mode you give a range, like --nnodes=MIN:MAX, and a restart budget. Workers find each other through a rendezvous.
  2. Restart the whole worker group. The group is torn down and started again with the new set of workers. It does not grow or shrink while running.
  3. Reload the latest checkpoint. This is where torch.distributed.checkpoint helps. Each rank saved its own shard with metadata about the full tensors. On load, each rank reads the slices it now needs. So the new world size does not have to match the old one.
  4. Resume the rest of the state. Optimizer state must reshard too. The data loader position, random seeds and learning-rate schedule need to come back as well. Without the data position you repeat or skip samples.

Do HF Trainer, Megatron and the others use it?

I read the code and docs of each. The short version is that the resharding piece is shared, and the “notice and restart” piece is not part of any of them.

  • HF Trainer. With FSDP, Trainer calls Accelerate's save_fsdp_model and load_fsdp_model, and the optimizer versions. For a sharded state dict, Accelerate's default (use_dcp=True) calls dist_cp.save and dist_cp.load, which is DCP. With DeepSpeed, Trainer calls DeepSpeed's own save_checkpoint. Trainer does not restart or rescale the job. You resume with resume_from_checkpoint under torchrun or your scheduler. Its data skipping counts steps, so after a change of world size the batch size per step changes too, and you need to take care. That last point is my reading of the code.
  • Megatron Core. Its dist_checkpointing package uses the torch_dist format. The torch strategy calls PyTorch's checkpoint.save and checkpoint.load with its own save and load planners. Its docs say a checkpoint saved under one tensor, pipeline or data parallel setup can be loaded under another. That goes beyond a change of world size.
  • TorchTitan. Its checkpointer calls dcp.save, dcp.async_save and dcp.load directly. That is where async saving comes from.
  • DeepSpeed. It does not use DCP. It has its own route, Universal Checkpointing. You convert a ZeRO checkpoint to a universal format and load it with checkpoint.load_universal enabled, and it can then change the parallelism.

So “save on 8, resume on 16” is real and common. Nobody calls it elastic training by itself, though. It is the reload step of a checkpoint-and-restart loop.

What about resuming on a different topology?

Changing the number of GPUs is the easy case. A topology change is when the parallel layout changes too. For example, you saved with plain FSDP on a mesh of (dp=8) and you resume with FSDP plus tensor parallel on (dp=4, tp=2). Or, in Megatron, you saved with tensor parallel 2 and pipeline parallel 4 and you resume with tensor parallel 4 and pipeline parallel 2.

# saved on mesh (dp=8,): FSDP only
# resumed on mesh (dp=4, tp=2): FSDP + tensor parallel
mesh  = init_device_mesh("cuda", (4, 2), mesh_dim_names=("dp", "tp"))
model = build_model()
parallelize(model, mesh)                  # same parameter names, new placements
dcp.load({"app": AppState(model, optimizer)}, checkpoint_id="ckpt/step_1000")

It works because DCP does not store “rank 3 held this file”. For every tensor it stores the global shape and where each saved chunk sits inside it. On load, each rank looks at its own new placement, works out which slice of the global tensor it needs, and reads exactly that. The old layout of ranks no longer matters. Megatron does the same job with its own sharded-tensor metadata, which is why its docs promise loading under a different tensor, pipeline or data parallel setup.

The catches are real, though:

  • Names must match. The saved and the new model need the same parameter names. A wrapper that adds a prefix, or torch.compile, can break this. That is what helpers like get_state_dict are for.
  • Layouts that are not a plain slice. Fused weights, such as a combined QKV matrix, can be cut in a layout that depends on the parallel degree. The framework has to describe that. Megatron has helpers for it. A hand-written TP plan may not.
  • Optimizer state is harder than weights. If the optimizer keeps its state in flat buffers, the format must say how to cut them. Megatron's docs show the cost. Optimizer states saved by mcore 0.14 or earlier cannot be loaded directly by newer versions, because the format changed.
  • The data loader. Its position is kept per data-parallel rank. If the data-parallel size changes, that position has to be mapped to the new ranks, or you accept a small repeat or skip.
  • Numbers move. A different tensor parallel degree adds in a different order, so the loss curve will not match bit for bit. That is the numeric drift from the earlier question.

Topology-flexible resume versus elastic training

They are easy to mix up, because both can end with “it came back on a different number of GPUs”. They are different kinds of thing.

Topology-flexible resume
  • A property of the checkpoint format.
  • Answers: can this state be loaded into a different layout?
  • Usually planned, between two jobs. You decide to move from 64 to 128 GPUs, or to try a new mesh.
  • Needs a resharding load, like dcp.load, Megatron's dist_checkpointing or DeepSpeed's universal checkpoint.
  • A person may still relaunch the job by hand.
Elastic training
  • A property of the running system.
  • Answers: what happens when the set of workers changes while I am not looking?
  • Triggered by events: a node dies, a spot instance is taken back, the scheduler grows the job.
  • Needs everything above, plus detection, a rendezvous (torchrun --nnodes=MIN:MAX), a restart, a rule for the new mesh and batch size, and a resume of data and random state.
  • Runs without a person.

You can have one without the other. With flexible resume alone, a person relaunches the job after a failure. With a launcher that restarts on the same number of nodes, you have fault tolerance, but the size never changes. Real elasticity needs both.

One practical rule falls out of this. Elasticity is much easier along a dimension where every group holds the same state. Keep tensor parallel inside a node and make data parallel the dimension that grows and shrinks. Replica groups, like the ones TorchFT is built around, hold identical state, so a new one can copy from a healthy peer and nothing needs resharding. Resharding is for the dimensions that cut a tensor.

Things the checkpoint cannot decide for you

  • Batch size and learning rate. The number of GPUs changed, so the global batch size changes unless you adjust, for example with gradient accumulation. What to do with the learning rate is your call.
  • The mesh shape. On 16 GPUs, your DeviceMesh might need different dimensions. The parallelism plan has to be built again at startup.
  • Lost work. You go back to the last checkpoint. Async checkpoints (the slides showed 7B: 148 s down to 6.3 s) make saving often cheap.

The newer idea: do not restart everything

Mansi listed TorchFT as coming. It aims at fault tolerance per step, without a full-job restart. The rough idea is to run data-parallel replica groups. If one fails, the others keep going, and the failed one catches up from healthy peers. I have not verified the details against its docs, so read the repo before relying on that description.

In short: DCP resharding is a necessary piece for elastic restarts. It is not the mechanism. The launcher, the rendezvous and the resume logic make it elastic.

Sources: DCP getting started · Accelerate FSDP checkpointing · Megatron Core dist_checkpointing · TorchTitan DCP checkpointer · DeepSpeed Universal Checkpointing · torchrun / elastic launch docs · Rendezvous docs · Distributed checkpoint docs · TorchFT

What is AutoParallel, and should I use it instead of writing the plan by hand?

It is an experimental library that picks the sharding plan for you. You give it a model and a mesh. It scores every option for every op and solves for the cheapest plan over the whole graph. Today it fits standard Transformers best.

The problem it targets

DTensor chooses the cheapest sharding for each op on its own. It never sees the whole graph, so the full plan may not be the best one. For a plain Transformer that does not matter, because the good plan is well known. It is column-wise on the first linear and row-wise on the next, so the pair needs one all-reduce. For an odd architecture, you would be guessing.

What it does, in four steps

  1. Trace the model into one joint forward and backward graph.
  2. List the valid shardings for each node: replicated, sharded activations, sharded weights, partial results that reduce later.
  3. Solve for one choice per node with an integer linear program. It looks at the whole graph at once, so a choice that looks expensive for one op can win if it saves a redistribution somewhere else.
  4. Apply the chosen placements and return a parallel module. It runs eagerly unless you compile it yourself.

What the solver counts as cost

  • Compute. The larger of the compute time (FLOPs over throughput) and the memory time (bytes over bandwidth), so it is the roofline idea from the learner kit. There is a small launch floor so tiny ops do not look free.
  • Communication. A model of NCCL, with different speeds inside a node (NVLink) and across nodes (the network). That is why it prefers to keep heavy traffic inside the node.
  • A small tie-breaker when neighbouring ops disagree, so the plan does not flip back and forth.
  • The prefetch discount. FSDP-style all-gathers can overlap with the previous layer's compute. You apply this discount explicitly. Without it, the solver sees the full cost and may choose to replicate parameters.

A first look

from torch.distributed.device_mesh import init_device_mesh
from torch.distributed.tensor import DTensor
from torch.distributed.tensor.placement_types import Shard
from autoparallel import auto_parallel

mesh = init_device_mesh("cuda", (4,), mesh_dim_names=("dp",))
with torch.device("meta"):
    model = MLP(dim=1024, hidden_dim=4096)

# the input is sharded on the batch dimension across the mesh
sample_x = DTensor.from_local(torch.randn(8, 128, 1024), mesh, [Shard(0)])

parallel_model = auto_parallel(
    model, mesh,
    sample_inputs=(sample_x,),
    out_shardings=(Shard(0),),             # keep the output batch-sharded
    parameter_memory_budget=(None, None),  # force it to consider sharding parameters
)
parallel_model.to_empty(device="cuda")     # then initialise or load weights

The input is a global shape. At runtime each rank passes only its local shard.

Things that trip people up

  • It replicates everything. With no parameter memory constraint, full replication is often the cheapest plan on paper. Add the budget, as above.
  • Not stable. The project says so itself. It needs a PyTorch nightly, newer than 2.10, and the API may change.
  • MoE. Routing depends on the data, so DTensor placements cannot describe it. You wrap the expert block in local_map and manage that communication by hand. AutoParallel still plans the dense parts around it.
  • Try it without a cluster. The repo has a HuggingFace example that uses a fake process group, so you can run the trace and the solver on one machine.

When I would reach for it

For a standard Transformer, write the plan by hand. You know it, you can read it, and you can debug it. Use AutoParallel as a second opinion: let it choose, and compare its plan with yours. It is more interesting for a model whose layout you do not know. In the talk it was in development on LLaMA-3 at 64 and 256 GPUs, and the claim was that it finds FSDP, tensor parallel and expert parallel on its own.

Sources: AutoParallel README · Getting started · How it chooses a strategy · MoE and local_map · FAQ · DTensor docs

The other questions I worked through, on prefill and decode, prefix caching, GPU idle time, reward hacking, GRPO, FSDP and tensor parallel, and network distance, now sit inside the matching modules of the learner kit.