Repository navigation
[MoE] Annotate routed-expert weights on the dense mesh when EP is off - #4973
Merged
Merged
Conversation
[ghstack-poisoned]
pianpwk
requested review from
fegin,
tianyu-l,
wconstab and
wwwjn
as code owners
September 30, 2026 17:44
tianyu-l
approved these changes
Sep 30, 2026
pianpwk
added a commit
that referenced
this pull request
Sep 30, 2026
Issue: any MoE model with EP=1 on more than one rank (FSDP/HSDP/CP-only,
since MoE requires EP >= TP) crashed in core FSDP:
ValueError: When dp_mesh_dims is provided, all parameters must be
DTensors on the full SPMD mesh ... Got plain tensor for parameter 'weight'.
Why: without EP, `_routed_experts_sharding_configs` set the routed `w13`/`w2`
sharding configs to `None`, so expert weights never got spmd_types
annotations and stayed plain tensors, which FSDP rejects once
`dp_mesh_dims` is set.
Fix: give them the dense param placement (Replicate on DP/CP/TP) when EP is
off, so FSDP shards them on the dense mesh like other dense params. EP
configs are unchanged, and on a single rank the annotations are filtered out,
so existing numerics/gold losses (all EP > 1) are unaffected. Callsites:
- gpt_oss: expert biases now always follow their weight's placement
(previously only annotated under EP, so they would also stay plain).
- Grouped LoRA: accept the dense placement too. The configs are always set
now, so keeping the EP-only check would reject every EP=1 LoRA run.
Test Plan (8x H100, EP=1, TP=1, 3 steps; all crashed or would crash before):
- FSDP=8: qwen3_moe_debug, gpt_oss_debugmodel, deepseek_v3_debugmodel,
deepseek_v4_debugmodel, kimi_k3_debugmodel
- FSDP=4, PP=2: qwen35_debugmodel_moe, qwen35_debugmodel_moe_float8_lora
- HSDP 2x4: qwen3_moe_debug
- FSDP=2, CP=2, PP=2: deepseek_v3_debugmodel_fsdp2_cp2_pp2_ep4 (EP=1)
- EP path sanity: qwen3_moe_debug FSDP=4, TP=2, EP=2
- CPU: test_moe.py, test_lora.py, test_qwen3_5.py (no new failures)
Follow-up (waits for #4949 to land): graph_trainer simple FSDP's non-EP
path shards the stacked W13 expert weight on dim 2 while core shards routed
experts on dim 0, so graph_trainer qwen3 MoE EP=1 diverges from eager at
step 1. That fix needs #4949's `param_shard_placements` argument.
ghstack-source-id: 63aa073
Pull-Request: #4973
[ghstack-poisoned]
pianpwk
added a commit
that referenced
this pull request
Sep 30, 2026
Issue: any MoE model with EP=1 on more than one rank (FSDP/HSDP/CP-only,
since MoE requires EP >= TP) crashed in core FSDP:
ValueError: When dp_mesh_dims is provided, all parameters must be
DTensors on the full SPMD mesh ... Got plain tensor for parameter 'weight'.
Why: without EP, `_routed_experts_sharding_configs` set the routed `w13`/`w2`
sharding configs to `None`, so expert weights never got spmd_types
annotations and stayed plain tensors, which FSDP rejects once
`dp_mesh_dims` is set.
Fix: give them the dense param placement (Replicate on DP/CP/TP) when EP is
off, so FSDP shards them on the dense mesh like other dense params. EP
configs are unchanged, and on a single rank the annotations are filtered out,
so existing numerics/gold losses (all EP > 1) are unaffected. Callsites:
- gpt_oss: expert biases now always follow their weight's placement
(previously only annotated under EP, so they would also stay plain).
- Grouped LoRA: accept the dense placement too. The configs are always set
now, so keeping the EP-only check would reject every EP=1 LoRA run.
Test Plan (8x H100, EP=1, TP=1, 3 steps; all crashed or would crash before):
- FSDP=8: qwen3_moe_debug, gpt_oss_debugmodel, deepseek_v3_debugmodel,
deepseek_v4_debugmodel, kimi_k3_debugmodel
- FSDP=4, PP=2: qwen35_debugmodel_moe, qwen35_debugmodel_moe_float8_lora
- HSDP 2x4: qwen3_moe_debug
- FSDP=2, CP=2, PP=2: deepseek_v3_debugmodel_fsdp2_cp2_pp2_ep4 (EP=1)
- EP path sanity: qwen3_moe_debug FSDP=4, TP=2, EP=2
- CPU: test_moe.py, test_lora.py, test_qwen3_5.py (no new failures)
Follow-up (waits for #4949 to land): graph_trainer simple FSDP's non-EP
path shards the stacked W13 expert weight on dim 2 while core shards routed
experts on dim 0, so graph_trainer qwen3 MoE EP=1 diverges from eager at
step 1. That fix needs #4949's `param_shard_placements` argument.
ghstack-source-id: 4028ec2
Pull-Request: #4973
pianpwk
added a commit
that referenced
this pull request
Oct 1, 2026
Issue: any MoE model with EP=1 on more than one rank (FSDP/HSDP/CP-only,
since MoE requires EP >= TP) crashed in core FSDP:
ValueError: When dp_mesh_dims is provided, all parameters must be
DTensors on the full SPMD mesh ... Got plain tensor for parameter 'weight'.
Why: without EP, `_routed_experts_sharding_configs` set the routed `w13`/`w2`
sharding configs to `None`, so expert weights never got spmd_types
annotations and stayed plain tensors, which FSDP rejects once
`dp_mesh_dims` is set.
Fix: give them the dense param placement (Replicate on DP/CP/TP) when EP is
off, so FSDP shards them on the dense mesh like other dense params. EP
configs are unchanged, and on a single rank the annotations are filtered out,
so existing numerics/gold losses (all EP > 1) are unaffected. Callsites:
- gpt_oss: expert biases now always follow their weight's placement
(previously only annotated under EP, so they would also stay plain).
- Grouped LoRA: accept the dense placement too. The configs are always set
now, so keeping the EP-only check would reject every EP=1 LoRA run.
Test Plan (8x H100, EP=1, TP=1, 3 steps; all crashed or would crash before):
- FSDP=8: qwen3_moe_debug, gpt_oss_debugmodel, deepseek_v3_debugmodel,
deepseek_v4_debugmodel, kimi_k3_debugmodel
- FSDP=4, PP=2: qwen35_debugmodel_moe, qwen35_debugmodel_moe_float8_lora
- HSDP 2x4: qwen3_moe_debug
- FSDP=2, CP=2, PP=2: deepseek_v3_debugmodel_fsdp2_cp2_pp2_ep4 (EP=1)
- EP path sanity: qwen3_moe_debug FSDP=4, TP=2, EP=2
- CPU: test_moe.py, test_lora.py, test_qwen3_5.py (no new failures)
Follow-up (waits for #4949 to land): graph_trainer simple FSDP's non-EP
path shards the stacked W13 expert weight on dim 2 while core shards routed
experts on dim 0, so graph_trainer qwen3 MoE EP=1 diverges from eager at
step 1. That fix needs #4949's `param_shard_placements` argument.
ghstack-source-id: bc9a03e
Pull-Request: #4973
Armandpl
added a commit
to commaai/torchtitan
that referenced
this pull request
Oct 21, 2026
* [DSV4] Place compressed KV at its group's first token when positions is None (#4932)
# Summary
Bug fix; since we compress tokens via ratio e..g HCA is 128 key
compressions. Token one shoudl get rope freq0 and then token 2 needs
rope freq 128. We dropped this offset when no positions are passed in.
Probs doesnt show up but good to fix regardless
### Agent note
Compressed entry j summarizes tokens [j * ratio, (j + 1) * ratio) and,
as in the DeepSeek-V4
reference, takes the RoPE position of its first token, j * ratio. With
explicit positions the
compressor used positions[::ratio], which is that. Without positions it
passed None to RoPE,
which then placed entry j at position j, so a model called without
positions (tests,
standalone calls) computed different compressed-KV RoPE than the
training path, which always
passes positions (the collators materialize them). On the debug model
the two disagreed by
5.6% relative in the logits.
The default now matches explicit positions: torch.arange(0, seqlen,
ratio). The training path
is unchanged.
The new CPU test compares the CSA (ratio 4) and HCA (ratio 128)
compressors with and without
positions; it fails before this change.
---
<sub>Stack created with <a
href="https://github.com/github/gh-stack">GitHub Stacks CLI</a> • <a
href="https://gh.io/stacks-feedback">Give Feedback 💬</a></sub>
* [graph_trainer] Link public Slack channel in README (#4953)
Adds a note near the top of the GraphTrainer README inviting users and
developers to join the public PyTorch Slack channel
(https://pytorch.slack.com/archives/C0C4ZRE5BL7), so there is a
discoverable place for questions, discussion, and updates.
Docs-only change; no code affected.
* [graph_trainer] Remove graph-based EP chunking (#4952)
## Why
EP overlap had two chunking strategies: `eager` (wrap module forwards
before tracing) and `graph` (`ep_chunk_pass.py`, which rewrites the
traced graph using unbacked SymInts, a concretize pass, and trace-input
preparers). The graph strategy duplicated what eager chunking already
provides while being a large maintenance surface (~2.5k lines of pass
code plus ~2k lines of tests). This PR keeps EP overlap and removes only
the graph chunking path.
## What
- Delete `ep_chunk_pass.py` and the graph-only helpers in
`ep_pass_utils.py` (region discovery via `collect_chunked_regions` is
kept).
- Drop `EpOverlapConfig.strategy` (eager is the only mode) and
`disable_early_grad_accumulation` (graph-only).
- `ep_overlap_schedule_pass` is unchanged; the pipeline is
`populate_eager_chunk_metadata_pass` -> `isolate_ep_process_group_pass`
-> DCE -> `ep_overlap_schedule_pass`.
- `--compile.enable_fsdp_dense_region_overlap` only composed with graph
chunking; with ep_overlap enabled it is now skipped with a warning
(standalone behavior unchanged).
- Remove the now-unused `TRACE_INPUT_PREPARERS` /
`TRACE_CALL_INPUT_PREPARERS` registries, `trace_input_preparer_keys`,
and the `prepare_inputs` / `prepare_call_inputs` args of
`minimal_fx_tracer`. `PASS_PIPELINE_REGISTRY`, `POST_INIT_HOOKS`,
`PRE_TRAIN_STEP_HOOKS` are kept.
- Tests: remove graph-chunking unit tests and the graph-vs-eager
loss-compare tests; `test_ep_chunk_matches_eager_chunking_bitwise` now
compares an eager-chunked `Trainer` against `GraphTrainer` with
ep_overlap enabled.
## Testing
- `pytest torchtitan/experiments/graph_trainer/tests/test_passes.py`:
182 passed, 1 skipped (includes the 11 eager-chunking tests).
- `pre-commit`: clean except Pyrefly missing-import errors in untouched
files (local env).
- `pytest
torchtitan/experiments/graph_trainer/tests/test_bitwise_deterministic.py
-k TestDSv3FlexAttnBitwiseDeterministic` (GB300): 3 passed, 2 skipped
(pre-existing skips), including
`test_ep_chunk_matches_eager_chunking_bitwise` (eager-chunked `Trainer`
vs `GraphTrainer` with ep_overlap, bitwise identical).
* [deepep] free dispatch handles replayed by FullAC early-stopped recompute (#4918)
Human note:
This PR changes ~1 lines of code. Theres a dict whose content is never
deleted in Full AC with early stop. I added a line that deletes it.
Last week i landed a PR removing the hardcoded `early_stop=False` from
FullAC. This slows down models in ~1-4% and was added because of MoE
memory leakage. At the time, i tested MoE and didn't see any leakage.
Today, testing DeepEP and HybridEP, i saw the leakage for DeepEP
**only**. This PR changes ~1 lines of code, but the agent added a lot of
(useful) context for the reviewer.
Note:
- One specific function is not compilable anymore
- The real fix would be to do it like HybridEP, but it would require a
big refactor
-----
TLDR:
- With the DeepEP dispatcher and full activation checkpointing (FullAC),
MoE training leaks GPU memory every step. On Qwen3-30B-A3B, peak active
memory goes 64 -> 77 GiB in 100 steps, with 14 allocator retries by step
100. With this PR it stays flat at ~64 GiB.
- Cause: every dispatch stores a handle in a global dict, and only
combine removes it. FullAC re-runs dispatch during backward but stops
before re-running combine, so that handle is never removed: one leak per
MoE layer per step.
- Fix: a `weakref.finalize` removes an entry when its `handle_id` tensor
is garbage-collected, so an entry whose combine never ran is freed too.
Combine still removes its entry first, so nothing changes on the normal
path.
## DeepEP 101
In an MoE layer, each token picks its top-k experts (Qwen3-30B-A3B: 8 of
128). With expert parallelism (EP), the experts are split across GPUs,
so every token has to travel to the GPUs that hold its experts, and the
expert outputs have to travel back:
```
GPU 0 (experts 0-63) GPU 1 (experts 64-127)
x -> router -> dispatch ==== NVLink / RDMA all-to-all ====> expert GEMMs -> combine ==== back to each token's GPU ====> sum -> + x
```
- **dispatch** sends each token to the GPUs holding its experts.
- **combine** sends the expert outputs back and sums them per token.
- **DeepEP** (DeepSeek's library) provides fast kernels for these two
steps.
Dispatch also returns a **handle**: the routing layout (which token went
where). Combine needs it to route outputs back, and so does backward,
since dispatch's backward is a combine and combine's backward is a
dispatch. The handle holds routing buffers on the GPU (~2.8 MB each at
this shape, estimated from the leak rate).
PyTorch custom ops can only pass tensors between each other, so
`deepep.py` keeps each handle in a Python dict keyed by an int, and
passes that int around as a tiny CPU tensor, `handle_id`:
```
dispatch(x) -> recv_x, ..., handle_id # _handle_cache[id] = handle
combine(y, handle_id) -> out # handle = _handle_cache.pop(id)
```
## How the leak happens
Full activation checkpointing (FullAC) saves memory by not keeping a
layer's activations. During backward it re-runs the layer's forward
("recompute") to rebuild them. Since #4836, that recompute stops early,
as soon as it has rebuilt the last tensor backward needs. In the MoE
layer that tensor comes right before combine; nothing after combine
needs saving.
One MoE layer, one training step, on main:
```
forward: dispatch -> cache[N] = handle experts combine -> cache.pop(N) cache = {}
backward:
recompute: dispatch -> cache[M] = handle experts X stops early, combine never re-runs
gradients: use handle N, which autograd kept cache = {M} <- leaked
```
Every step leaves one entry per MoE layer, and each entry keeps its
handle's GPU buffers alive: 48 layers x 100 steps ≈ 13 GiB.
Other setups aren't affected:
- **Selective AC:** it saves the dispatch/combine outputs instead of
re-running them, so dispatch never runs a second time.
- **HybridEP:** its op returns the handle itself as an opaque object,
with no dict, so a re-run handle is freed with the recompute's outputs.
- **All-to-all dispatcher:** it has no handle at all.
## The fix
```python
handle_id = _get_next_handle_id()
handle_key = handle_id.item()
_handle_cache[handle_key] = handle
# weakref.finalize(obj, fn) calls fn() once obj is garbage-collected.
# FullAC's recompute replays dispatch but stops before combine; this frees that handle.
weakref.finalize(handle_id, lambda: _handle_cache.pop(handle_key, None))
```
- Normal path: combine pops the entry as before, and the finalizer finds
nothing to remove.
- Re-run dispatch without a combine: when the stopped recompute drops
its outputs, `handle_id` is freed and the finalizer removes the entry.
- `@torch.compiler.disable` on the dispatch kernel: the op has no fake
implementation, so `torch.compile` graph-breaks and then traces the
kernel as a regular Python frame. Dynamo can't trace `weakref.finalize`:
it guards on `weakref.finalize._registry`'s size, which the call itself
changes.
### Result
8x H100, Qwen3-30B-A3B random init, dp_shard=4 tp=2 ep=2, DeepEP v2,
FullAC, 32k tokens/DP rank, c4, bf16, no compile, 100 steps. Rank 0 peak
memory (GiB):
```
step 2 20 40 60 80 100 alloc retries median tps
peak active main r1 64.3 67.3 69.3 72.6 73.5 77.2 14 5252
main r2 64.3 66.6 69.0 71.8 73.9 77.0 14 5294
this PR 64.0 64.7 64.4 63.9 64.2 63.8 0 5380
peak reserved main r1 70.5 73.0 75.4 78.4 81.3 82.5
this PR 70.2 71.0 71.1 71.1 71.1 71.1
```
Loss over steps 81-100: 7.726 / 7.580 for main r1 / r2, and 7.753 for
this PR. DeepEP runs aren't bitwise reproducible, so that spread is
run-to-run noise.
### Works with other features
CPU, the real DeepEP ops against a single-rank fake buffer; entries left
in `_handle_cache` after 2 fwd+bwd steps (`compat_checks.py`):
```
main this PR grads match no-AC
no AC 0 0 yes
FullAC, early stop (default) 2 0 yes
FullAC, early_stop=False 0 0 yes
selective AC (DeepEP ops saved) 0 0 yes
RegionAC, DeepEP regions replayed 0 0 yes
RegionAC, DeepEP regions saved 0 0 yes
torch.compile (aot_eager), no AC 0 0 yes
torch.compile (aot_eager) + FullAC 2 0 yes
no_grad / inference_mode forward 0 0 -
exception between dispatch/combine 1 0 -
```
- **Quantization:** Float8/MXFP8 change the expert GEMMs, not
dispatch/combine, so they don't touch the handle cache.
- **CUDA graphs, inference** (generator, expand layout): checked on 2
GPUs with the real `ElasticBuffer` (`cuda_graph_check.py`). Capture plus
5 replays on new inputs match eager bitwise, with 0 entries left, same
as main. Combine still pops at capture time, and replay runs no Python.
- **CUDA graphs, training:** config validation already rejects DeepEP
with trainer CUDA graphs (only non-blocking HybridEP is allowed), so
this path doesn't exist.
- **Graph trainer:** it traces with `make_fx` under `FakeTensorMode`,
which needs fake impls. HybridEP has them; DeepEP's ops don't, so DeepEP
isn't supported there on main either. This PR doesn't change that.
- **Pipeline parallel:** each micro-batch's dispatch has its own
`handle_id`.
- NOTE: not run on GPU: `torch.compile` (CPU: aot_eager and inductor,
including `fullgraph=True`, all leave 0 entries) and PP.
## Q&A
- **Why not just set `early_stop=False`?** It also fixes the leak, since
the recompute then always reaches combine. But every layer's backward
would re-run the combine communication and the rest of the block, for
every model.
- **Now that the finalizer exists, why keep combine's pop and the
`will_backward` flag?** I tried removing them. It's correct, but under
`torch.compile` dynamo keeps a reference to one `handle_id` per compiled
frame, so without combine's pop that handle lives until torchtitan's
next `gc.collect()` (torchtitan disables automatic GC). Keeping the pop
leaves lifetimes identical to main whenever combine runs.
- **Why not return the handle as an opaque object, like HybridEP?**
That's the right end state, and it deletes the dict entirely. It changes
both op schemas and needs its own compile/SAC validation, so there's a
`TODO` next to `_handle_cache`.
- **Why not save the DeepEP outputs under FullAC, as Selective AC
does?** It would remove the re-run dispatch (an all-to-all plus a host
sync per layer in backward). But it keeps each layer's dispatch and
combine outputs, roughly 9 GiB at this shape (estimate). That's a
separate perf trade-off.
## Code changes
- `torchtitan/distributed/deepep/deepep.py` (+12 / -1: one existing line
now reuses `handle_key`):
- `weakref.finalize` on each `handle_id`.
- `@torch.compiler.disable` on the dispatch kernel.
- Comments, plus a `TODO` for the opaque handle.
- `tests/unit_tests/cpu/test_deepep_handle_cache.py` (new):
- Runs the real DeepEP ops on CPU against a single-rank fake buffer.
- Covers FullAC with early stop on/off, `torch.compile`, and an
inference forward, checking that no entry is left.
- Skips when `deep_ep` isn't installed.
### Validation
- New test: 4 passed. On main,
`test_full_ac_recompute_frees_handles[True]` fails. Without
`@torch.compiler.disable`, `test_compile_frees_handles` fails with the
dynamo guard error.
- `tests/unit_tests/cpu/test_inference_moe.py` passes.
- pre-commit passes. Pyrefly reports 0 errors on `deepep.py`; I ran it
by hand because the hook can't run from a worktree path.
- GPU runs (wandb project `qwen30b_moe_pretrain_pr68_pr55`):
- this PR:
https://meta.wandb.io/felipemello/qwen30b_moe_pretrain_pr68_pr55/runs/fc0l7x3n
- main r1:
https://meta.wandb.io/felipemello/qwen30b_moe_pretrain_pr68_pr55/runs/zo867pzz
- main r2:
https://meta.wandb.io/felipemello/qwen30b_moe_pretrain_pr68_pr55/runs/0znra4x7
---------
Co-authored-by: Felipe Mello <[email protected]>
* local_spmd regions with spmd.local_map (#4960)
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.12.0)
(oldest at bottom):
* __->__ #4960
mistake here, from tests seems not much was incorrect
* [graph_trainer] Skip PP stage metadata inference for SPMD (#4944)
Fixes #4921
Adding is_spmd flag to GraphRuntime and Schedule to skip PP specific
initializations, that OOMed because of using real memory.
* [graph_trainer] Keep Shard(0) for routed experts when EP covers the experts (#4949)
#4867 made data_parallel look up linear_param_shard_placements(model)
for every parameter.
When `edp_shard * ep <= num_experts`, apply_simple_fsdp wraps routed
experts with shard_dim=0 to match core FSDP, which shards every
routed-expert parameter on the expert dimension.
The new lookup overrode that for the stacked W13 GroupedLinear weight,
sharding it on dim 2 instead. Sharded init then diverged from eager and
test_moe_qwen3_aot_fx_trace_vs_eager failed at step 1 (7.719911098480225
vs 7.716061592102051).
This PR lets callers pass param_shard_placements explicitly. The
expert-dim path passes {} so all routed-expert parameters use Shard(0)
again.
Note: agent pointed out " EP=1 may still have a placement mismatch
between eager and GraphTrainer." - no test currently covers this, and
this PR doesn't address it. We should discuss/review it.
Test Plan:
- pytest torchtitan/experiments/graph_trainer/tests/test_numerics.py -k
"moe_qwen3 or stacked_ or dsv3_ep_overlap_moe or dense_qwen3" (8x H100):
qwen3 MoE losses match eager bitwise over 20 steps (failed before);
EP-overlap seq/batch, dense qwen3 and both stacked-linear tests pass.
* Replace Tyro CLI with Python config loading (#4908)
## Human note
- removed Tyro capability: CLI now only supports few core launching
options, e.g. `--override`, `--output_dir`, `--comm_backend` (can be
found at torchtitan/config/README.md)
- removed `update_from_config` -- set sharding is done at model
constructor
- token dispatcher backend selection now is a `ModelConfigTransform`
- `moe_force_load_balance` is moved to `RoundRobinTokenChoiceTopKRouter`
as "model code"
## Summary
- replace Tyro-generated training flags with a small `ConfigLoader` CLI
for `--module`, `--config`, registered `--override`s, and operational
launch settings
- move model derivation into recipe construction, model config
transforms, and model constructors; keep context length aligned across
training, RoPE, and vLLM
- make MoE dispatcher selection a context-aware config transform and
model forced balancing a dedicated round-robin router
- migrate integration and numerics launchers to complete Python config
recipes and remove the Tyro dependency
## Testing
- `pre-commit run --all-files`
- focused CPU suites: 290+ passed (with expected skips)
- full CPU collection is blocked locally by the installed PyTorch
missing `torch.utils.checkpoint._is_cacheable_effect` required by
GraphTrainer
* [Fix] RoutedExperts output_postprocess parameter under FSDP (#4954)
`RoutedExperts.output_postprocess` can have a parameter. FSDP did not
handle it correctly, even when one specifies `SpmdType` for it.
https://github.com/pytorch/torchtitan/blob/156949fa579d021e6f7b500d1d24e40ec47cef55/torchtitan/distributed/fsdp.py#L351-L359
https://github.com/pytorch/torchtitan/blob/156949fa579d021e6f7b500d1d24e40ec47cef55/torchtitan/distributed/fsdp.py#L394-L411
Without a change in `fsdp.py`, one `SpmdType` for `output_postprocess`
does not work
- Sparse SpmdType
- expert_sharding_size > num_experts: omitted by the linear-only map,
incorrectly selects dense mesh.
- expert_sharding_size <= num_experts: correctly selects sparse mesh.
- Dense SpmdType
- expert_sharding_size > num_experts: omitted, correctly selects dense
mesh.
- expert_sharding_size <= num_experts: included with all routed
parameters, incorrectly selects sparse mesh.
Currently, `RoutedExperts` runs with `local_spmd=True` which has
`spmd.no_typecheck()`, so both dense or sparse `SpmdType` could
technically work. Semantically, sparse `SpmdType` would make more sense,
so I am going with sparse.
But using dense could save more memory because
`edp_shard = dp_shard * cp * tp / ep` so compared to dense fsdp, sparse
fsdp shards less, and would use `ep/tp >= 1` factor more memory.
## Test Plan
- `taskset -c 0-7 python -m pytest -q
tests/unit_tests/gpu/test_fsdp_moe_sharding.py::TestApplyFsdpMoESharding`
6 passed
- Verified the new eight-GPU regression across both expert-sharding
branches, including forward, backward, and state-dict round-trip.
* [DSV4] Support packed documents (#4943)
### Human note
Wires up the packed dsv4 training; ran a bunch of experiements the
interesting offset in loss has to do with `real` tokens e.g. non padded
up to the seqlen model when the sequences dont evenly divide
## Agent Note
DeepSeek-V4 rejected packed batches (#4879) because its compressors, CSA
indexer, and sparse attention cores
ignored document boundaries. Attention Gym 0.0.14's `gather_attn` and
`lightning_indexer` accept packed
`cu_seqlens`, so all three now take per-document offsets and the recipes
go back to packed batches.
**What changes**
- `get_attention_masks` returns `VarlenMetadata` from positions (reset
to 0 at each document start; padding kept as
its own segment) instead of raising. DSV4's `preprocess_inputs` (added
in #4858) also annotates the nested offsets
for SPMD, as kimi_k3 does.
- **Compressor:** groups restart at each document, a document's trailing
partial group forms no entry, and the
ratio-4 overlap never reaches into the previous document. Entries are
packed by document into a fixed pool of
`seqlen // ratio` slots (located with `searchsorted`, gathered by
index): no host syncs, CUDA-graph capturable.
- **Indexer + all three cores** receive `cu_seqlens` / `cu_seqlens_k`,
so top-k selection, the sliding window, and
HCA's index list stay inside each document. The CSA/HCA index width is
bounded by the longest document
(`VarlenMetadata.max_k`), not the whole packed batch: extra slots were
always -1, and at the debug recipe's
16K-token microbatch the wider HCA list made the first Triton compile
take over 20 minutes.
- **Recipes:** the debug microbatch returns to `8 * max_context_length`;
`max_num_documents=1` becomes a fixed
capacity of 64 (as in llama3), which keeps the offsets static and
sync-free.
The unpacked path is kept (not expressed as a one-document packed
batch): the gather-based path is ~30% slower
for the compressor, and a one-document packed batch already matches it
bitwise.
## Results
All loss runs: DSv4 debug model, C4, 500 steps, 16,384 tokens per step,
1x GB300, `--debug.seed 42
--debug.deterministic` unless noted. Branches: main `a475ccd89`, stack
top #4932 `5e90dfef9`, this PR.
**1. No behavior change for unpacked training.** The same one-document
batches through this PR's packed path and
through the stack top give identical loss and grad_norm at every one of
500 steps (bitwise).
**2. Packing trains on real tokens instead of padding.** One-document
microbatches are 41% padding (9,722 real
tokens per 16,384-token step, 8 documents); packed steps are all real
tokens (~14 documents).
| run (loss, lower is better) | mean loss, last 50 steps | real tokens
seen |
|---|---|---|
| stack top, one document per microbatch | 2.1195 | 4.86 M |
| this PR, packed documents | **2.0106** | 8.19 M |

**Per real token, packing costs nothing once updates are matched.** At
16,384 tokens per step the packed run
reaches the one-document run's 4.86 M real tokens in 297 updates instead
of 500, which costs loss at this model
size (a fully annealed 297-step packed run reaches 2.245, so the LR
schedule is not the cause). A packed control
at 9,728 tokens per step (the one-document run's ~9,722 real tokens per
step) takes the same 500 updates on the
same real tokens and lands on the one-document curve:
| mean train loss (lower is better) | last 25 steps | last 50 | last 100
|
|---|---|---|---|
| one document per microbatch, 16,384 tokens/step | 2.1357 | 2.1195 |
2.1295 |
| packed, 9,728 tokens/step (matched updates) | 2.1419 | 2.1225 | 2.1283
|
| difference | +0.006 | +0.003 | -0.001 |
All differences are inside the 0.0098 seed-to-seed spread.

**3. The stack below (Flex -> gather_attn, #4858) does not change
convergence.** main vs stack top over 8
seeds, mean train loss over the last 100 of 500 steps (lower is better):
| seed | main (Flex) | stack (gather_attn) | Flex - gather |
|---|---|---|---|
| 42 | 2.1246 | 2.1295 | -0.0049 |
| 1 | 2.1406 | 2.1410 | -0.0004 |
| 2 | 2.1480 | 2.1490 | -0.0010 |
| 3 | 2.1529 | 2.1457 | +0.0071 |
| 4 | 2.1229 | 2.1220 | +0.0009 |
| 5 | 2.1486 | 2.1400 | +0.0086 |
| 6 | 2.1350 | 2.1328 | +0.0022 |
| 7 | 2.1233 | 2.1166 | +0.0067 |
Mean gap +0.0024, 95% CI [-0.0015, +0.0063], paired t-test p = 0.19; 3
of 8 seeds favor Flex (sign test
p = 0.73). The gap is 0.11% of the loss and about a fifth of the stack's
own seed-to-seed spread (std 0.0114), and
it does not grow over training (+0.0022, +0.0039, +0.0029, +0.0027,
+0.0024 for steps 0-100 ... 400-500). The
first three seeds leaned toward Flex by chance.

Seed 42 alone, step by step (top), and the bitwise check from result 1
(bottom):

## Methodology
- **Loss runs:** DSv4 debug model (10.6 M params, 16 heads x head_dim
256), C4 streamed from HF, seed 42 (plus
seeds 1-7 for main vs stack), `--debug.deterministic`, 500 steps, 16,384
tokens per step, LR warmup 2 then
linear decay to 0, CUDA graphs on, one GB300 per run. "One document per
microbatch" is the #4879 recipe
(8 x 2,048-token microbatches, 41% padding); "packed" is this PR's
recipe (one 16,384-token microbatch,
`max_num_documents=64`). Only the commit and batching differ between
runs.
- **Loss** is the logged train loss: mean over non-padding tokens of
each step's own batch. Curves are EMA(0.05);
tables use means over the last N steps. Real tokens per step were
counted by building each config's dataloader
and walking the same 500 steps.
- **Bitwise checks** compare the full-precision TensorBoard loss and
grad_norm scalars of two runs step by step.
- **Throughput runs:** all back to back inside one `gpu-run` claim (same
GPU, full clocks), without
`--debug.deterministic` (`gather_attn` uses Triton under it), median
over steps 11+. The flash-shaped model
keeps DSv4-flash attention and indexer exactly (64 heads x 512, window
128, top-k 512) with 6 layers (SWA, SWA,
CSA, HCA, CSA, HCA) and 8 experts, 4,096 context, 8,192 tokens per step,
30 steps.
- Every chart repeats its method in a footnote.
## Performance
Without `--debug.deterministic` (so CSA/HCA run on the FA4 CuTe kernel
at head_dim 512), same GPU, run
back to back, median of steps 11+ (higher is better):
| model | run | tokens/s | real tokens/s | peak reserved |
|---|---|---|---|---|
| debug (head_dim 256, Triton) | stack top, one document per microbatch
| 101,341 | 60,135 | 0.98 GiB |
| debug (head_dim 256, Triton) | this PR, packed | 234,005 | **234,005
(3.9x)** | 5.88 GiB |
| 6-layer flash-shaped (64 x 512) | stack top, one document per 4K
microbatch | 17,717 | - | 90.5 GiB |
| 6-layer flash-shaped (64 x 512) | this PR, one document per 4K
microbatch | 17,637 | - | 90.5 GiB |
| 6-layer flash-shaped (64 x 512) | this PR, packed 8K microbatch |
19,614 | - | 106.6 GiB |
The packed path costs nothing when a batch holds one document (rows
3-4). The flash-shaped packed row uses an 8K
microbatch (vs 4K x 2 accumulation), which also explains its higher
memory. The debug model runs Triton everywhere:
attn-gym's CuTe backend needs head_dim 512, and `gather_attn` uses
Triton under `--debug.deterministic`, under
`torch.compile`, and for SWA's empty compressed pool.

## Test Plan
Unit tests replace #4879's rejection tests: document offsets with and
without padding; offsets reaching the model
through `preprocess_inputs`; and, on CPU fp64, a packed batch through
SWA, CSA, and HCA matching each document run
alone (partial groups and a 5-token document included). Removing the
document-start overlap mask fails the CSA
cases. CSA selects every causal candidate in this test because top-k
ties between exact-zero indexer scores are
broken by layout, and can differ packed vs unpacked.
GPU checks on GB300 (flash-shaped layers, bf16) with deterministic
algorithms: forward+backward runs under
`sync_debug_mode="error"`; a CUDA graph captured once and replayed on
new documents matches eager bitwise; a
one-document packed batch matches the unpacked path bitwise. Packed vs
per-document runs of the debug model and
the flash-shaped layers (CuTe) agree within bf16 tolerance.
```bash
pytest tests/unit_tests/cpu/test_deepseek_v4_dsa.py tests/unit_tests/cpu/test_deepseek_v4_compressor.py \
tests/unit_tests/cpu/test_deepseek_v4_mtp.py tests/unit_tests/cpu/test_deepseek_v4_flops.py \
tests/unit_tests/cpu/test_debug_config_defaults.py tests/unit_tests/gpu/test_deepseek_v4_attention.py
# E2E loss runs (per branch): C4, 16384 tokens/step, 500 steps
torchrun --nproc_per_node=1 -m torchtitan.train --module deepseek_v4 --config deepseek_v4_debugmodel \
--training.steps 500 --debug.seed 42 --debug.deterministic # C4 + TensorBoard overrides
```
Scripts, raw per-step data (CSV), and the chart generator were kept
outside the repo; available on request.
* Remove torchcomms dependency (#4941)
Torchcomms is not strictly required to run Torch Titan therefore
completely remove it as a dependency. Torchcomms is currently one of the
backend options in TorchFT and in Torchstore. Both the libraries allow
using different backends so if somebody does not want to use torchcomms,
the dependency on torchcomms is unecessary. This makes users responsible
to install the backend that they need.
<!-- forkstack:stack:start -->
---
Stack (top to bottom):
- #4945 [rl] Stage generator weights in CPU memory
- -> #4941 Remove torchcomms dependency
---
<!-- forkstack:stack:end -->
Co-authored-by: Tushar Jain <[email protected]>
* [rl] generator: one trace span per engine-step burst (#4975)
Logging on engine.step is too much. Lets do it on the burst only.
two reasons:
1) Today our logging is slow on NFS (0.5ms per call), which doesn't
matter in training, but matters for engine.step. Peng is working on
putting logging in a background thread, so this is not a problem
anymore. This PR is a quick fix
2) Our logger output is very large for the generator. This should reduce
it significantly.
A couple of notes:
- This was done with another PR that avoid unnecessary tokenization
https://github.com/pytorch/torchtitan/pull/4976
- I have no clue why bs64 would benefit from thism ore than bs1
I didn't remeasure it, but in any case, the change is good.
## Result
- GB300, Qwen3.5-4B, logs on NFS:
```
bs64 3937 -> 9950 tok/s (2.5x), TPOT 14.1 -> 5.72 ms
bs1 258 -> 288 tok/s (+12%)
```
Co-authored-by: Felipe Mello <[email protected]>
* [graph_trainer] Remove legacy AOT export helpers in graph_utils.py (#4979)
## Why
`graph_utils.py` holds the old AOT export path: `export_joint`,
`aot_export_joint_with_descriptors_alone`, `joint_graph_builder` and
`CompiledModule`. Compile mode is now only `aot_fx_trace`, so
GraphTrainer no longer uses any of it. The only importer left was
`TestReassignCollectivePgsPass` in `tests/test_passes.py`, and that test
was checking the pass on a graph from a tracer GraphTrainer no longer
uses.
This is the first step in simplifying GraphTrainer after the
GraphRuntime refactor.
## What
- Delete `graph_utils.py`.
- Port `TestReassignCollectivePgsPass` to trace the joint fwd+bwd graph
with `minimal_fx_tracer`, the tracer GraphTrainer uses. All three
overlap tests are kept.
- Remove the mentions of `graph_utils.py` from
`autoresearch/autoresearch.md`.
## Testing
```
pytest torchtitan/experiments/graph_trainer/tests/test_passes.py
182 passed, 1 skipped
```
The training code path is unchanged: this removes dead code and updates
a test, so no loss comparison is needed.
* Reorganize training recipes (#4913)
Human notes
- move model flavors definition from `__init__.py` to `flavors.py`, to
keep the former clean
- rename `model_registry` to `build_model_config` because we are not
registering anything in the function
- move `config_registry.py` recipes to torchtitan_recipes, with
unverified / inactive ones removed; the RL ones are all kept
- reorganize torchtitan_recipes and the tests subfolder, to be
consistent with the "models vs. rl vs. experiments" structure
- move `overrides/` modules into torchtitan_recipes, while keeping the
.md in core
- remove `_supported_experiments` and `_supported_models` shortcuts
- removed unused functions e.g. `dist_mean`,
`check_if_feature_in_pytorch`
## Summary
- move verified training recipes into the top-level `torchtitan_recipes`
package and keep CI-only configurations under `torchtitan_recipes.tests`
- organize recipes by model, subsystem, and test suite; consolidate
duplicate Flux and Transformers test recipe modules
- move bundled overrides out of the core library and remove unused or
unverified configurations and helpers
- move model flavor definitions to `flavors.py` and expose the uniform
`MODEL_FLAVORS` / `build_model_config` API
## Testing
- `pre-commit run --all-files`
- focused CPU configuration, model, recipe, and state-dict tests (193
passed)
* remove timeout and fix assertion (#4974)
* [Perf][Compile] Add local compilation for gated RMSNorm and loss functions (#4894)
## Summary
- Compile the shared gated RMSNorm with TorchInductor by default for
Kimi K3 and Qwen3.5.
- Preserve Kimi sigmoid gating and Qwen3.5 SiLU gating in one FP32
implementation.
- Add a function-scoped local compile API shared by gated RMSNorm and
opt-in loss compilation.
- Fall back to eager gated RMSNorm in batch-invariant mode.
Stacked on #4895. This follows up on
https://github.com/pytorch/torchtitan/pull/4832.
## Single-operator performance
### Kimi K3 gated RMSNorm
One H100 with BF16 inputs, 20 warmup iterations, 100 timed iterations
per trial, five trials, and synchronized CUDA events. Values are median
trial averages. All measurements are forward+backward and include input,
gate, and weight gradients.
Operation tested: `RMSNorm(x.float(), weight.float(), eps) *
sigmoid(gate.float())`, cast back to BF16.
Shapes use `[T, H, V]`, where `T` is the packed-token dimension, `H` is
the number of rank-local value heads, and `V` is the value-head
dimension (128 here). The handwritten Triton implementation is the
previous Kimi K3 kernel from #4832 and is used only for comparison; it
is not included in this PR.
| Shape `[T, H, V]` | Eager | Handwritten Triton | Compiled | Compiled
vs eager | Compiled vs Triton |
| --- | ---: | ---: | ---: | ---: | ---: |
| `[2048, 16, 128]` | 346.84 us | 233.26 us | 172.07 us | **2.02x** |
**1.36x** |
| `[2048, 32, 128]` | 728.17 us | 245.18 us | 214.75 us | **3.39x** |
**1.14x** |
| `[4096, 12, 128]` | 542.46 us | 247.37 us | 243.17 us | **2.23x** |
**1.02x** |
| `[4096, 96, 128]` | 3,089.36 us | 972.49 us | 406.30 us | **7.60x** |
**2.39x** |
| `[8192, 12, 128]` | 824.82 us | 249.14 us | 223.32 us | **3.69x** |
**1.12x** |
| `[8192, 24, 128]` | 1,592.17 us | 438.95 us | 219.84 us | **7.24x** |
**2.00x** |
| `[8192, 48, 128]` | 3,088.79 us | 973.62 us | 404.70 us | **7.63x** |
**2.41x** |
| `[8192, 96, 128]` | 6,094.38 us | Compilation failure | 788.54 us |
**7.73x** | N/A |
| `[16384, 12, 128]` | 1,592.23 us | 439.85 us | 224.74 us | **7.08x** |
**1.96x** |
| `[16384, 24, 128]` | 3,091.79 us | 976.80 us | 406.68 us | **7.60x** |
**2.40x** |
| `[16384, 48, 128]` | 6,095.45 us | Compilation failure | 786.84 us |
**7.75x** | N/A |
| `[16384, 96, 128]` | 12,100.33 us | Compilation failure | 1,552.79 us
| **7.79x** | N/A |
| `[32768, 12, 128]` | 3,090.03 us | 977.90 us | 406.19 us | **7.61x** |
**2.41x** |
| `[32768, 24, 128]` | 6,094.32 us | Compilation failure | 788.40 us |
**7.73x** | N/A |
| `[65536, 12, 128]` | 6,094.23 us | Compilation failure | 788.41 us |
**7.73x** | N/A |
The compiled implementation is 2.02x-7.79x faster than eager and
1.02x-2.41x faster than handwritten Triton for every shape where the
handwritten kernel compiles. The handwritten weight-gradient reduction
exceeds Triton's maximum tensor size for the five largest row counts.
### Loss functions
One H100 with BF16 inputs, 20 warmup iterations, 100 timed iterations
per trial, five trials, and synchronized CUDA events. Values are median
trial averages. Measurements include forward and input-gradient
backward.
Operations tested:
- Cross entropy: `cross_entropy(logits.float(), labels, reduction="sum",
ignore_index=-100)` on the single-GPU, non-vocab-parallel path.
- MSE: `mse_loss(pred.float(), target.float().detach(),
reduction="sum")`.
| Operation | Input shape | Eager | Compiled | Speedup | Numerical check
|
| --- | --- | ---: | ---: | ---: | --- |
| Cross entropy | logits `[2048, 8192]`, labels `[2048]` | 340.41 us |
169.29 us | **2.01x** | `assert_close`; output max diff 0.001953125,
grad max diff 0.00000190735 |
| MSE | prediction and target `[4096, 4096]` | 438.61 us | 154.33 us |
**2.84x** | Bitwise-equal output and input gradient |
### Determinism and batch invariance
| Compiled target | Fwd+bwd deterministic | Batch invariant |
| --- | --- | --- |
| Kimi sigmoid gated RMSNorm | Yes | No (backward `grad_weight` max
diff: 0.00000858307; forward output and backward `grad_x`/`grad_gate`
max diffs: 0) |
| Qwen3.5 SiLU gated RMSNorm | Yes | No (backward `grad_weight` max
diff: 0.00000953674; forward output and backward `grad_x`/`grad_gate`
max diffs: 0) |
| Cross entropy (`none`) | Yes | Yes (output and logits-gradient max
diffs: 0) |
| Cross entropy (`sum`) | Yes | No (forward loss max diff:
0.00048828125; backward logits-gradient max diff: 0) |
| MSE (`sum`) | Yes | No (forward loss max diff: 0.25; backward
prediction-gradient max diff: 0) |
These isolated operator results do not claim an end-to-end training
speedup.
## Testing
- CPU local compile, gated RMSNorm, loss, config, and RL trainer tests:
93 passed, 9 subtests passed
- GPU gated RMSNorm codegen, grouped linear compile, Kimi KDA, and
Qwen3.5 DeltaNet tests: 10 passed
- Compiled cross-entropy and MSE loss forward+backward correctness and
performance tests passed on H100
- Pre-commit passed with Pyrefly and link checking skipped
* [rl] Default the inter-generator router to sticky sessions (#4986)
The inter-generator router defaulted to least-loaded, so the turns of
one multi-turn rollout landed on different generators and missed each
other's prefix KV (Qwen3.5-27B agentic run, 12 generators: ~35%
prefix-cache hit rate at 12-17% KV usage). Default to
`StickySessionRoutingStrategy` (new sessions still go to the
least-loaded generator), like the intra-generator router already does,
and drop the per-recipe strategy overrides so every recipe uses sticky.
* [rl] generator: token-in/token-out sampling (#4976)
TLDR:
vllm detokenizes because users may do "stop_condition" based on some
string.
We dont expose this today, so its a waste in a generator
-----
## Problem
The generator's engine loop runs inline with vLLM's engine core
(`external_launcher` keeps it in-process), so vLLM's per-token output
processing sits on the same thread that launches the next step. vLLM
detokenizes every generated token and builds a `{token_id: Logprob}`
dict per token per request. The generator never reads text (stops are
token ids), and it keeps only the sampled token's logprob float.
## Solution
`SamplingParams(detokenize=False, flat_logprobs=True)`, and read the
logprob floats straight from `FlatLogprobs`. verl does the same
(`detokenize=False` unless stop strings are set). NeMo-RL instead turns
off tokenizer loading engine-wide (`skip_tokenizer_init`).
Outputs are unchanged. `detokenize` only switches off vLLM's output-side
text decoding (stops and EOS are checked in the engine core), and vLLM
stores the sampled token first at each position. Checked on GPU: same
prompts and seed, 64/64 requests with identical token ids and
bit-identical logprobs.
Alternatives considered:
- **`skip_tokenizer_init=True` engine-wide.** Same gain, but a larger
blast radius: `render_cmpl`, the multimodal processor, EOS defaults, and
any future text feature.
- **Engine core in its own process**, vLLM's own design. It needs weight
sync to stop reaching into the in-process model.
## Result
**Short version:** this PR removes ~75% of vLLM's CPU work per engine
step and almost all garbage-collection pauses. On H100 with current main
that is worth 0-2% tokens/s. The engine step is 4-13x longer than that
CPU work, and vLLM runs the CPU work while the GPU computes the next
step (async scheduling), so most of it was already hidden.
Tokens/s, generator only (real `VLLMGenerator`, H100, fixed-length
outputs, before/after interleaved in one process, median of 6 reps; 3
for 2048 out):
```
before after gain
4B bs64, 1024 in, 512 out 3.47k tok/s 3.45k tok/s none (noise ±1%)
4B bs256, 512 in, 256 out 5.83k tok/s 5.85k tok/s none (noise ±1%)
4B bs128, 512 in, 2048 out 4.67k tok/s 4.72k tok/s +1% (all 3 reps)
0.6B bs256, 512 in, 256 out 12.2k tok/s 12.4k tok/s +1.5% (noisy, sd 1.9%)
```
GB300, Qwen3.5-4B, all other generator PRs stacked (~5.6 ms engine
step), `detokenize=False` alone (no `flat_logprobs`), one measurement:
```
bs64, 1024 in, 512 out 9.88k tok/s -> 10.14k tok/s +2.6%
```
Where the time goes (H100):
```
engine step CPU output work / step GC pauses / batch
4B bs64, 1024 in, 512 out 17 ms 1.35 -> 0.33 ms 17 -> 1 ms
4B bs256, 512 in, 256 out 34 ms 4.41 -> 1.15 ms 108 -> 5 ms
4B bs128, 512 in, 2048 out 26 ms 3.29 -> 0.77 ms 799 -> 3 ms
0.6B bs256, 512 in, 256 out 16 ms 3.86 -> 1.06 ms 109 -> 5 ms
```
- `detokenize=False` is most of the CPU saving (4B bs256: 4.41 -> 1.35
ms per step).
- `flat_logprobs=True` is the GC saving. One Python dict per generated
token made the garbage collector run 7 full collections per batch at
2048-token outputs; flat lists make it 0. That is the +1% at 2048 out,
and it should grow with longer outputs.
NOTE: DAPO-Math 4B 8k end to end on H100 (50 steps, 6 generators) showed
no measurable change.
Tests: the generator unit tests pass with `FlatLogprobs` in the fake
request outputs, and assert the new sampling params.
* [Perf][Compile] Add local compilation for OffsetRMSNorm (#4928)
## Summary
- Add an `offset_rmsnorm` local-compile target for Qwen3.5-compatible
models and enable it by default.
- Compile the existing FP32 OffsetRMSNorm expression with TorchInductor
while preserving the eager implementation and state dict.
- Fall back to eager in batch-invariant mode; the existing Triton
override remains available.
The default compile configuration enables both normalization targets:
```python
CompileConfig(local_compile=["gated_rmsnorm", "offset_rmsnorm"])
```
Stacked on #4894. The handwritten Triton comparison uses the override
from #4417.
## Single-operator performance
One H100 with BF16 inputs, 20 warmup iterations, 100 timed iterations
per trial, five trials, and synchronized CUDA events. Values are median
trial averages. Each measurement runs OffsetRMSNorm forward+backward and
includes input and weight gradients.
`[T, H, K]` represents Q/K normalization and `[T, D]` represents
transformer-block/final normalization. `T` is the packed-token
dimension, `H` is the number of rank-local heads, `K` is the head
dimension, and `D` is the model dimension.
### Q/K normalization
| Shape `[T, H, K]` | Eager | Handwritten Triton | Local compile | Local
compile vs eager | Local compile vs Triton |
| --- | ---: | ---: | ---: | ---: | ---: |
| `[2048, 2, 256]` | 313.58 us | 219.49 us | 160.53 us | **1.95x** |
**1.37x** |
| `[2048, 12, 256]` | 453.85 us | 249.55 us | 195.39 us | **2.32x** |
**1.28x** |
| `[4096, 2, 256]` | 302.94 us | 230.75 us | 165.11 us | **1.83x** |
**1.40x** |
| `[4096, 12, 256]` | 1,007.96 us | 233.84 us | 204.22 us | **4.94x** |
**1.15x** |
| `[8192, 2, 256]` | 306.46 us | 237.97 us | 162.37 us | **1.89x** |
**1.47x** |
| `[8192, 12, 256]` | 1,927.70 us | 281.30 us | 204.86 us | **9.41x** |
**1.37x** |
| `[16384, 2, 256]` | 638.66 us | 238.48 us | 211.81 us | **3.02x** |
**1.13x** |
| `[16384, 12, 256]` | 3,653.61 us | 473.79 us | 251.77 us | **14.51x**
| **1.88x** |
### Transformer-block/final normalization
| Shape `[T, D]` | Eager | Handwritten Triton | Local compile | Local
compile vs eager | Local compile vs Triton |
| --- | ---: | ---: | ---: | ---: | ---: |
| `[2048, 1024]` | 301.50 us | 232.64 us | 165.14 us | **1.83x** |
**1.41x** |
| `[2048, 2048]` | 303.49 us | 235.76 us | 168.55 us | **1.80x** |
**1.40x** |
| `[2048, 2560]` | 374.40 us | 235.71 us | 162.36 us | **2.31x** |
**1.45x** |
| `[2048, 4096]` | 631.91 us | 242.07 us | 162.85 us | **3.88x** |
**1.49x** |
| `[2048, 5120]` | 822.58 us | 249.33 us | 161.20 us | **5.10x** |
**1.55x** |
| `[4096, 1024]` | 298.79 us | 271.44 us | 196.35 us | **1.52x** |
**1.38x** |
| `[4096, 2048]` | 622.85 us | 233.16 us | 196.25 us | **3.17x** |
**1.19x** |
| `[4096, 2560]` | 812.56 us | 240.31 us | 186.85 us | **4.35x** |
**1.29x** |
| `[4096, 4096]` | 1,282.33 us | 275.66 us | 211.94 us | **6.05x** |
**1.30x** |
| `[4096, 5120]` | 1,571.87 us | 287.10 us | 186.61 us | **8.42x** |
**1.54x** |
| `[8192, 1024]` | 622.00 us | 244.76 us | 196.14 us | **3.17x** |
**1.25x** |
| `[8192, 2048]` | 1,277.67 us | 240.85 us | 194.41 us | **6.57x** |
**1.24x** |
| `[8192, 2560]` | 1,568.81 us | 251.18 us | 203.89 us | **7.69x** |
**1.23x** |
| `[8192, 3584]` | 2,136.69 us | 226.28 us | 194.45 us | **10.99x** |
**1.16x** |
| `[8192, 4096]` | 2,429.91 us | 236.55 us | 203.66 us | **11.93x** |
**1.16x** |
| `[8192, 4864]` | 2,851.04 us | 281.80 us | 293.99 us | **9.70x** |
**0.96x** |
| `[8192, 5120]` | 2,994.64 us | 293.76 us | 308.83 us | **9.70x** |
**0.95x** |
| `[8192, 7168]` | 4,134.76 us | 397.10 us | 415.27 us | **9.96x** |
**0.96x** |
| `[8192, 8192]` | 4,693.66 us | 451.78 us | 492.81 us | **9.52x** |
**0.92x** |
Local compile is faster than eager for every tested shape and faster
than handwritten Triton for 23 of 27 shapes. Handwritten Triton is
faster at four large-width shapes, so performance is shape-dependent and
the handwritten Triton override remains useful. A `Local compile vs
Triton` value below `1.0x` indicates that Triton is faster.
These isolated operator results do not claim an end-to-end training
speedup.
## Testing
- Local-compile codegen emits Triton for OffsetRMSNorm forward and
backward.
- Compiled forward, input gradient, and weight gradient match the eager
FP32 reference.
- A two-GPU TP test verifies the compiled Q/K norm inside its local SPMD
boundary.
- Relevant CPU/GPU tests: 19 passed, 9 subtests passed.
- All enabled pre-commit hooks passed; Pyrefly was skipped because of
unrelated environment errors.
* [2/2] [graph_trainer] PP=1 GA schedule with FSDP overlap (#4927)
Before:
If we extract UNSHARD and REDUCE_GRAD in a separate schedule action and
bucket all collectives - we lose overlap, this collectives will be
exposed.
Addition:
1. Overlap of UNSHARD and REDUCE_GRAD
Add option to preserve overlap of UNSAHRD (fsdp allgathers) and
REDUCE_GRAD(fsdp reduce_scatters) in first and last microbatch.
We result in schedule
FWD_BWD_WITH_UNSHARD, ... FWD_BWD x (num_micro_batches - 2) ...
FWD_BWD_WITH_REDUCE_GRAD
The split of fsdp collectives is done BEFORE bucketing.
This significantly simplifies split_fsdp passes.
We prepare:
1.Get FULL_FWD_BWD(nobucket) by tracing, bucketing extracted from passes
and deferred to later(FULL in the name means that we have FSDP
collectives inside)
2. FULL_FWD_BWD(nobucket) extract only REDUCE_GRAD
-> get FWD_BWD_WITH_UNSHARD
-> apply bucketing for AG only
3. 2. FULL_FWD_BWD(nobucket) extract only UNSHARD
-> get FWD_BWD_WITH_REDUCE_GRAD
-> apply bucketing for RS only
applying bucketing for AG o RS separately is seamless, current algorithm
supports missing of some types of collectives.
4. FULL_FWD_BWD -> extract both get FWD_BWD middle graph that will be
reused multiple times.
Gradient Accumulation:
For FWD_BWD_WITH_UNSHARD we add unsharded gradients into outputs
(graph_pass in grad_accumulation). They are becoming our gradient
accumulators.
For FWD_BWD we add unsharded gradients as inputs and add add_ or wgrad
fused add_ (optional under config) for gradient accumulations into
gradient accumulators passed as inputs.
For FWD_BWD_WITH_REDUCE_GRAD we add add_/wgrad fused add_ before
reduce_grads (as a pass).
2. Gradent Accumulation Ingraph Inplace
Gradient accumulation for PP=1 becomes ingraph by default. First
FWD_BWD_WITH_UNSHARD produces gradient_accumulators and returns as
outputs. (unsharded param gradients)
gradient_accumulators are fed into "middle" batches, where unsharded
gradients are inplace (or fused in wgrad producer) accumulated inside
accumulators.
The last stage FWD_BWD_WITH_REDUCE_GRAD accumulates grads in
gradient_accumulators and then does overlapped reduce_grad and returns
sharded gradients.
4. GA currently is implemented via graph passes to avoid retracing and
compile time overhead.
All gradient accumulation parts are extracted into
torchtitan/experiments/graph_trainer/grad_accumulation.py
WGrad fusion functionality stays in wgrad_accumulation.
6. Testing: GB300 x 3 EP4 FSDP4
Interesting that separate UNSHARD and REDUCE_GRAD with all bucketed
collectives was faster than overlaped case:
29 -> 31 MFU for DSv3 16b GA
But expectation is that when FSDP will include non nvlink domain -
overlap should be beneficial.
This is the reason why I want to keep both paths.
* [graph_trainer] Resolve one GraphExecutionPlan for PP=1 and PP>1 (#4980)
Stacked on `graph-trainer-pp1-ga-fsdp-overlap`.
## Why
A single FSDP placement choice currently passes through several
representations: config strings -> `GraphRuntimeFSDPPolicy` ->
`PP1FwdBwdPlan` properties. The validation is spread across
`resolve_graph_runtime_fsdp_policy`,
`resolve_graph_runtime_gradient_accumulation_policy`,
`_resolve_pp1_fwd_bwd_plan`, `_make_spmd_graph_runtime` and both graph
builders. PP>1 gets no plan at all. Its provider receives two loose
`extract_*` booleans next to an optional PP=1 plan.
This PR resolves everything once, into one object shared by PP=1 and
PP>1.
## What
- `PP1FwdBwdPlan` becomes `GraphExecutionPlan` and gains a `pp_enabled`
field. PP>1 uses the same plan: both boundaries are `"schedule"`, or
`None` without FSDP.
- `resolve_graph_execution_plan()` replaces the three resolve functions
and the two policy dataclasses.
- Config modes map to placements through lookup tables. `auto` is
handled in one place.
- WGrad-fusion resolution returns a plain bool.
- Every placement-related check now runs during plan resolution:
- the PP>1 config checks (`_validate_graph_pp_config`);
- the SPMD extraction support checks, moved out of
`_make_spmd_graph_runtime` into
`_validate_spmd_graph_extraction_support`;
- the dense-region-overlap check. It was duplicated in
`_build_fwd_bwd_graphs` and `_build_stage_graphs`, and it only fired
after tracing.
- `GraphTrainerStageGraphProvider` takes `plan` only. The `pp1_plan`,
`extract_fsdp_param_unshard` and `extract_fsdp_grad_reduction` fields
are gone. The factory layers forward `plan` instead of `fsdp_policy` and
`gradient_accumulation_policy`.
- The `num_microbatches < 1` check is removed.
This is intended as a pure refactor. The resolved placements, schedules
and error messages are unchanged. The one exception: the two
dense-region messages are now a single message.
## Testing
- `test_graph_pp_runner.py`: all 53 tests pass. The tests are ported to
`resolve_graph_execution_plan`. The dense-region test now covers PP=1
and PP>1, and there is a new PP>1 placement test.
- `pre-commit`: passes, except pyrefly, which already fails on
missing-import errors unrelated to this PR.
- The rest of the graph_trainer suite fails the same 24 GPU tests with
and without this PR. The failures come from this machine: a
`/tmp/seed_training.log` permission error and an Inductor config key the
local PyTorch build doesn't support.
- Not run yet: a bitwise loss comparison with `scripts/loss_compare.py`.
* [graph_trainer] Always enable graph pass instrumentation (#4977)
## Summary
Removes the `compile.debug_graph_passes` flag from
`GraphTrainerCompileConfig`. The per-pass instrumentation that used to
sit behind it now always runs in `apply_graph_passes`:
- the graph is dumped to tlparse before and after each pass
- each pass's wall-clock time is logged
- each pass's op-count / node-count diff is logged
## Why
This information is what you want whenever you're looking at a
GraphTrainer compile, and having to re-run with a flag to get it is
friction. Keeping it always on costs very little:
- The tlparse dumps go through `trace_structured` with a lazy
`payload_fn`, so the graph is only printed when `TORCH_TRACE` is set.
- `snapshot_graph` is a single O(num_nodes) walk per pass, which is
negligible next to tracing and compilation.
The visible change is more log output: each compile prints one timing
line and one diff block per pass on the logging rank.
## Changes
- `configs.py`: drop `debug_graph_passes`.
- `passes.py`: remove the `debug` gating in `apply_graph_passes`.
- `debug_utils.py`: drop the `debug` parameter from
`tlparse_log_graph_pass` (`apply_graph_passes` was its only caller).
`seq_nr` is now always included in the printed node metadata.
- `graph_trainer/.claude/CLAUDE.md`: update the "Debugging Graph Passes"
section.
Recipes or CLI invocations that set `compile.debug_graph_passes` will
need to drop it.
## Testing
- `pytest torchtitan/experiments/graph_trainer/tests/test_passes.py`:
182 passed, 1 skipped.
- Numerics are unaffected: only logging and tlparse dumps changed, and
no pass behavior changed.
* [MoE] Annotate routed-expert weights on the dense mesh when EP is off (#4973)
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.12.0)
(oldest at bottom):
* __->__ #4973
Issue: any MoE model with EP=1 on more than one rank (FSDP/HSDP/CP-only,
since MoE requires EP >= TP) crashed in core FSDP:
ValueError: When dp_mesh_dims is provided, all parameters must be
DTensors on the full SPMD mesh ... Got plain tensor for parameter
'weight'.
Why: without EP, `_routed_experts_sharding_configs` set the routed
`w13`/`w2`
sharding configs to `None`, so expert weights never got spmd_types
annotations and stayed plain tensors, which FSDP rejects once
`dp_mesh_dims` is set.
Fix: give them the dense param placement (Replicate on DP/CP/TP) when EP
is
off, so FSDP shards them on the dense mesh like other dense params. EP
configs are unchanged, and on a single rank the annotations are filtered
out,
so existing numerics/gold losses (all EP > 1) are unaffected. Callsites:
- gpt_oss: expert biases now always follow their weight's placement
(previously only annotated under EP, so they would also stay plain).
- Grouped LoRA: accept the dense placement too. The configs are always
set
now, so keeping the EP-only check would reject every EP=1 LoRA run.
Test Plan (8x H100, EP=1, TP=1, 3 steps; all crashed or would crash
before):
- FSDP=8: qwen3_moe_debug, gpt_oss_debugmodel, deepseek_v3_debugmodel,
deepseek_v4_debugmodel, kimi_k3_debugmodel
- FSDP=4, PP=2: qwen35_debugmodel_moe, qwen35_debugmodel_moe_float8_lora
- HSDP 2x4: qwen3_moe_debug
- FSDP=2, CP=2, PP=2: deepseek_v3_debugmodel_fsdp2_cp2_pp2_ep4 (EP=1)
- EP path sanity: qwen3_moe_debug FSDP=4, TP=2, EP=2
- CPU: test_moe.py, test_lora.py, test_qwen3_5.py (no new failures)
Follow-up (waits for #4949 to land): graph_trainer simple FSDP's non-EP
path shards the stacked W13 expert weight on dim 2 while core shards
routed
experts on dim 0, so graph_trainer qwen3 MoE EP=1 diverges from eager at
step 1. That fix needs #4949's `param_shard_placements` argument.
* [graph_trainer] Pass one config through GraphRuntime construction (#4983)
Stacked on #4980.
## Why
GraphRuntime construction threaded `compile_config`, `model_config`,
`parallelism` and `trainer_config` side by side. On PP=1 the first three
are always `trainer_config.compile` / `.model` / `.parallelism`, so they
were pure duplication. PP>1 enters through core's generic
`model.pipeline(**kwargs)` API and only has the decomposed fields, which
is why both shapes existed.
## What
- `make_graph_runtime`, `_register_graph_runtime`,
`_make_pipeline_parallel_graph_runtime`,
`GraphTrainerStageGraphProvider`, `_build_stage_graphs` and
`_apply_graph_pp_pre_partition_or_extraction_passes` take a single
`config: GraphTrainer.Config | GraphTrainerConfigView`.
- `_GraphTrainerPassConfigView` is renamed to `GraphTrainerConfigView`
(`compile`, `parallelism`, `model`) and is built once in
`graph_pipeline_llm`. Core's pipelining API is unchanged.
- PP=1-only builders (`make_spmd_graph_runtime`,
`_make_spmd_graph_runtime`, `_build_fwd_bwd_graphs`,
`_build_scheduled_fwd_bwd_graphs`, `_extract_fwd_bwd_action_graphs`)
take only `trainer_config`; the `trainer.py` call drops three arguments.
- The provider selects the PP=1 vs PP>1 path from `plan.pp_enabled`
instead of `trainer_config is not None`.
- Removed the "model_config and parallelism required when passes are
enabled" ValueError; the view makes those fields required.
Helpers that only need compile settings (`apply_graph_passes`,
`_compile_graph_pp_module`, scheduling/compile helpers) still take
`compile_config`.
No behavior change intended; this is a pure plumbing refactor.
## Test plan
- `pytest
torchtitan/experiments/graph_trainer/tests/test_graph_pp_runner.py
torchtitan/experiments/graph_trainer/tests/test_trace_module.py`: 111
passed, 3 skipped
- `pre-commit` clean on changed files; pyrefly reports no errors in
changed files
* [Perf][Compile] Add local compilation for SwiGLU (#4931)
## Summary
- Enable the `swiglu` local-compile target by default for the shared
torch-native SwiGLU activation.
- Fuse SiLU and multiplication in TorchInductor-generated forward and
backward kernels.
- Keep the handwritten Triton override for sparse fixed-capacity expert
buffers.
`LocalCompileConfig()` enables SwiGLU local compile by default.
Stacked on #4928.
## Performance
One H100 with BF16 inputs, 20 warmup iterations, 100 timed
forward+backward iterations per trial, five trials, and synchronized
CUDA events. Values are median trial averages and include gate and up
gradients.
`T` is the token-row count, `R` is grouped-expert buffer capacity, `F`
is the SwiGLU hidden width, and `R_valid = offsets[-1]`. A speedup above
`1.0x` means local compile is faster.
### DeepSeek V3 training shapes
`T = 65,536` comes from four 16,384-token sequences per DP rank.
Balanced routed-expert rows are `R_valid = T * top_k / EP`: 49,152 for
16B EP8 and 262,144 for 671B EP2. Hidden widths come from the model
flavors.
| Workload | Shape `[T/R, F]` | `R_valid` | Eager | Triton | Local
compile | Speedup vs eager | Speedup vs Triton |
| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| 16B dense FFN | `[65536, 10944]` | N/A | 8.90 ms | 5.48 ms | 5.09 ms |
**1.75x** | **1.08x** |
| 236B dense FFN | `[65536, 12288]` | N/A | 9.99 ms | 6.01 ms | 5.72 ms
| **1.75x** | **1.05x** |
| 671B dense FFN | `[65536, 18432]` | N/A | 15.00 ms | 8.81 ms | 8.58 ms
| **1.75x** | **1.03x** |
| 16B shared experts | `[65536, 2816]` | N/A | 2.31 ms | 1.36 ms | 1.32
ms | **1.75x** | **1.03x** |
| 236B shared experts | `[65536, 3072]` | N/A | 2.52 ms | 1.46 ms | 1.44
ms | **1.75x** | **1.01x** |
| 671B shared expert | `[65536, 2048]` | N/A | 1.68 ms | 0.97 ms | 0.96
ms | **1.75x** | **1.01x** |
| 16B routed experts, EP8 compact | `[49152, 1408]` | 49,152 | 0.88 ms |
0.51 ms | 0.51 ms | **1.72x** | **0.99x** |
| 671B routed experts, EP2 compact | `[262144, 2048]` | 262,144 | 6.67
ms | 3.85 ms | 3.89 ms | **1.71x** | **0.99x** |
| 671B HybridEP CF=1, 25% utilized | `[1048576, 2048]` | 262,144 | 26.65
ms | 4.07 ms | 15.46 ms | **1.72x** | **0.26x** |
### Grouped-buffer utilization crossover
Local compile evaluates the full buffer, while handwritten Triton reads
`R_valid` on the GPU and skips padded tiles.
| Buffer `[R, F]` | `R_valid` | Utilization | Triton | Local compile |
Speedup vs Triton |
| --- | ---: | ---: | ---: | ---: | ---: |
| `[32768, 2048]` | 8,192 | 25% | 183.49 us | 485.85 us | **0.38x** |
| `[32768, 2048]` | 16,384 | 50% | 251.80 us | 486.28 us | **0.52x** |
| `[32768, 2048]` | 24,576 | 75% | 371.20 us | 485.72 us | **0.76x** |
| `[32768, 2048]` | 32,768 | 100% | 491.07 us | 486.16 us | **1.01x** |
For DeepSeek V3 shapes, local compile is 1.71-1.75x faster than eager.
It is 1.01-1.08x faster than Triton for dense/shared activations and
within about 1% for compact routed experts. Small shapes can regress
versus eager (for example, `[2048, 1792]` measured 0.51x), but the
representative DeepSeek V3 training shapes support enabling the target
by default.
The Triton override remains valuable for sparse fixed-capacity buffers:
it is 3.80x faster for the 25%-utilized 671B HybridEP case. A tensor
mask would still scan the full buffer, while reading `R_valid` on the
host would add synchronization. These are isolated operator
measurements, not end-to-end training results.
## Numerics
BF16 results on one H100:
| Case | Repeated fwd+bwd deterministic | Batch invariant | Maximum
output/gradient difference |
| --- | --- | --- | ---: |
| Dense `[8192, 3584]` | Yes | Yes, full batch vs two half-batches | 0 |
| Grouped `[32768, 2048]`, `R_valid = 8192` | Yes | Yes, fixed-capacity
vs compact valid rows | 0 |
The compiled output, `grad_gate`, and `grad_up` are bitwise identical in
all comparisons.
## Testing
- Inductor emits Triton code for SwiGLU forward and backward.
- Relevant CPU/GPU tests: 27 passed.
- All enabled pre-commit hooks passed; Pyrefly was skipped because of
unrelated environment errors.
* [RL] Preserve per-group KV cache across policy updates (#4761)
## Why
A policy update changes the model weights but does not automatically
invalidate vLLM's cached KV. Letting a newly started rollout hit KV
created by an older policy would give it stale prefix state. Clearing
the entire cache prevents that reuse, but it also preempts every active
request and makes long-running, multi-turn rollouts prefill their
accumulated context again. This change supports two explicit KV-cache
lifecycle modes.
### Mode 1: preserve version-salted KV (default)
With `generator.reset_kv_cache_on_weight_sync=false`:
1. When a generator first admits a rollout (a routing session), rank 0
pins the rollout to the generator's installed policy version. Every
later turn of that rollout on the same generator reuses the pin, and the
generator passes it to vLLM as `cache_salt`.
2. A weight pull runs between `engine.step()` bursts. No request is
admitted or advanced while the new weights are being installed, but
existing requests and their KV blocks remain in vLLM.
3. After the pull, in-flight rollouts resume from their existing KV
instead of being preempted and re-prefilled, and their later turns hit
their own history under the pinned salt.
4. Rollouts first admitted after the pull are pinned to the new version.
They cannot hit old-salt blocks, so their prefixes are computed with the
new weights.
5. Old-salt blocks remain reusable by their original rollouts until vLLM
evicts them normally.
Each completion reports the pinned version as `min_policy_version`,
since the completion may depend on KV cached under that version.
`policy_age` and the `max_offpolicy_steps` check therefore account for
the reused KV.
This mode avoids reset-and-reprefill work and preserves cache locality
across policy updates. Its tradeoff is that the salt is only a
prefix-hash namespace; it does not guarantee that every KV block used by
an in-flight rollout came from one weight version. A rollout can retain
prefix KV produced by its starting policy and append new KV after newer
weights have been installed. Because the salt is the version number,
rollouts pinned at the same version on a generator share one namespace:
they reuse common prefixes such as a system prompt with tool
definitions, and after a pull that namespace can also hold KV computed
under the newer weights.
### Mode 2: reset and re-prefill
With `generator.reset_kv_cache_on_weight_sync=true`:
1. The generator installs the new weights.
2. It clears the prefix cache and the pins, and preempts running
requests.
3. vLLM reschedules those requests and recomputes their accumulated
context with the new weights before decode continues.
**Config change.** `reset_kv_cache_on_weight_sync` replaces main's
`reset_prefix_cache_on_weight_sync` and
`reset_running_requests_on_weight_sync`, and the default flips from
reset to preserve. Configs that set either old field must switch to the
new one. Resetting the prefix cache while keeping running requests' KV
is no longer an option: the version salt already gives new requests
fresh KV without a reset, so a reset only matters as a strict recompute,
which must include running requests.
This mode provides strict recomputation under the latest installed
policy and remains useful for exact trainer/generator comparisons
(`batch_invariant` requires it). The additional prefill compute may also
help overlap FSDP parameter all-gathers. The cost is extra prefill work,
queueing, and latency, especially for long-running multi-turn rollouts.
The default mode follows Prime-RL's behavior: a rollout keeps its start
policy version as the cache salt, and the prefix cache is not cleared on
weight updates. TorchTitan obtains these semantics without calling
vLLM's asynchronous `pause_generation` API because weight pulls are
serialized between `engine.step()` bursts.
## Where the salt lives
The salt only matters inside one engine's KV pool, so each generator
owns its pins: rank 0 keeps `group id -> routing session id -> pinned
version` and fills it at admission. The router stays stateless.
Placement belongs to the routing strategy. Later turns only hit their
history if they return to the same generator, which
`StickySessionRoutingStrategy` guarantees (the alphabet_sort recipes use
it; the router default stays `LeastLoadedRoutingStrategy`, as on main).
Under any strategy the salt is still correct: a turn that lands
elsewhere pins that generator's version and misses the cache.
| Request | Salt | Why |
| --- | --- | --- |
| 1st turn of a rollout | The generator's installed version | Pins the
rollout; it cannot hit KV from older weights. |
| Late…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stack from ghstack (oldest at bottom):
Issue: any MoE model with EP=1 on more than one rank (FSDP/HSDP/CP-only,
since MoE requires EP >= TP) crashed in core FSDP:
Why: without EP,
_routed_experts_sharding_configsset the routedw13/w2sharding configs to
None, so expert weights never got spmd_typesannotations and stayed plain tensors, which FSDP rejects once
dp_mesh_dimsis set.Fix: give them the dense param placement (Replicate on DP/CP/TP) when EP is
off, so FSDP shards them on the dense mesh like other dense params. EP
configs are unchanged, and on a single rank the annotations are filtered out,
so existing numerics/gold losses (all EP > 1) are unaffected. Callsites:
(previously only annotated under EP, so they would also stay plain).
now, so keeping the EP-only check would reject every EP=1 LoRA run.
Test Plan (8x H100, EP=1, TP=1, 3 steps; all crashed or would crash before):
deepseek_v4_debugmodel, kimi_k3_debugmodel
Follow-up (waits for #4949 to land): graph_trainer simple FSDP's non-EP
path shards the stacked W13 expert weight on dim 2 while core shards routed
experts on dim 0, so graph_trainer qwen3 MoE EP=1 diverges from eager at
step 1. That fix needs #4949's
param_shard_placementsargument.