Skip to content

[pipelining] Add loss_kwarg_mbs for per-microbatch loss keyword arguments - #200238

Closed
wwwjn wants to merge 2 commits into
pytorch:mainfrom
wwwjn:pp-pytree-target-tuple-loss
Closed

wwwjn wants to merge 2 commits into
pytorch:mainfrom
wwwjn:pp-pytree-target-tuple-loss

Conversation

@wwwjn

@wwwjn wwwjn commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

step() forwards the same loss_kwargs to the loss of every microbatch, so a loss cannot take inputs that differ per microbatch beyond the target. TorchTitan's RL trainer needs this under PP: its loss takes per-token advantages, generator logprobs, a loss mask, and temperature for each microbatch. Today it works around this by packing those tensors into the target (pytorch/torchtitan#3980).

This PR adds loss_kwarg_mbs to step(): one dict of loss keyword arguments per microbatch, mirroring kwarg_mbs for model inputs.

schedule.step(
    arg_mbs=arg_mbs,
    target_mbs=target_mbs,
    loss_kwargs={"global_token_count": n},  # same for every microbatch
    loss_kwarg_mbs=[                        # one dict per microbatch
        {"advantages": advantages_mbs[i], "loss_mask": loss_mask_mbs[i]}
        for i in range(n_microbatches)
    ],
    losses=losses,
)
# Microbatch i computes:
#   loss_fn(output, target_mbs[i], **loss_kwargs, **loss_kwarg_mbs[i])
  • loss_kwargs is passed unchanged to every microbatch; unlike kwargs, it is not split.
  • loss_kwarg_mbs is a pre-split input, validated like the others: it must be a list of n_microbatches dicts, and it cannot be combined with whole-batch inputs or target, so per-token loss tensors and targets are always split by the caller in the same way.
  • A key in both loss_kwargs and loss_kwarg_mbs[i] raises Python's usual "multiple values for keyword argument" TypeError.
  • loss_fn still returns only the loss. Backward metadata inference uses the first microbatch's entry, as it already does for the target. The docs note that this extra loss_fn call means the loss must not accumulate into objects passed in loss_kwarg_mbs, such as a metrics dict.

The pipelining docs (docs/source/distributed.pipelining.md) now describe loss_kwargs and loss_kwarg_mbs next to the existing pre-split example.

Test plan:

  • test_schedule_with_loss_kwarg_mbs covers Schedule1F1B, ScheduleGPipe, ScheduleInterleaved1F1B, ScheduleInterleavedZeroBubble, and ScheduleLoopedBFS. Each uses a shared loss_kwargs value plus a per-microbatch weight and metrics dict, and checks losses, metrics, and gradients against a reference.
  • test_schedule_pre_split_validation adds the type, length, and whole-batch target error cases; test_schedule_with_loss_kwarg_mbs also checks the duplicate-key TypeError.
  • Without this change, all 6 tests fail; with it, pytest test/distributed/pipelining/ gives 210 passed and 112 skipped (GPU-only) on a CPU build.

@pytorch-bot

pytorch-bot Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/200238

Note: Links to docs will display an error until the docs builds have been completed.

✅ You can merge normally! (2 Unrelated Failures)

As of commit f15ed0c with merge base f6c4d43 (image):

NEW FAILURES SUPPRESSED BY AI (non-blocking) - The following job failed, but the AI CI Advisor judged the failure not to be evidence against this change:

BROKEN TRUNK - The following job failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@pytorch-bot pytorch-bot Bot added the ciflow/torchtitan Run TorchTitan integration tests label Oct 8, 2026
@wwwjn
wwwjn force-pushed the pp-pytree-target-tuple-loss branch from 6105e55 to 1f53c29 Compare October 8, 2026 04:23
@wwwjn wwwjn changed the title [pipelining] Allow pytree targets and loss functions with extra outputs [pipelining] Add loss_kwarg_mbs for per-microbatch loss keyword arguments Oct 8, 2026
@wwwjn
wwwjn force-pushed the pp-pytree-target-tuple-loss branch from 1f53c29 to ac707e2 Compare October 8, 2026 04:28
@wwwjn
wwwjn requested a review from sanketpurandare October 8, 2026 04:31
@wwwjn
wwwjn marked this pull request as ready for review October 8, 2026 04:31
wwwjn added a commit to pytorch/torchtitan that referenced this pull request Oct 8, 2026
Depends on pytorch/pytorch#200238, which adds per-microbatch loss keyword
arguments (`loss_kwarg_mbs`) to pipeline schedules.

- Engine: under PP, pass each microbatch's loss arguments to the schedule
  through `loss_kwarg_mbs` instead of rejecting them, and collect one loss
  metrics dict per microbatch. The schedule's scalar loss wrapper fills a
  per-microbatch `loss_metrics` dict and replaces it on each call, since the
  schedule also calls the loss on the first microbatch while inferring stage
  metadata. `ForwardBackwardResult.loss_metrics` is now one dict per
  microbatch on every path.
- GraphTrainer: its traced loss only takes the shared loss arguments, so its
  existing rejection of per-microbatch loss arguments also covers its PP path.
- RL trainer: lift the PP restriction (context parallelism still raises),
  run each `num_pp_microbatches` consecutive microbatches as one pipeline
  step (the batcher packs a multiple of it), share loss metrics from the rank
  holding the last stage (V-style schedules put it on the first PP rank), and
  publish every stage's partial state dict into the single "model_state_dict"
  TorchStore key so generators do not depend on the trainer PP layout.
- Add CPU unit tests and an 8-GPU PP=2 x FSDP=2 integration test.

@sanketpurandare sanketpurandare left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, approve to unblock

@sanketpurandare sanketpurandare added the module: pipelining Pipeline Parallelism label Oct 8, 2026
@sanketpurandare

Copy link
Copy Markdown
Contributor

@wwwjn please also modify the docs since this is a public API change.

target=None,
losses: list | None = None,
return_outputs: bool = True,
loss_kwargs: dict[str, Any] | None = None,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

loss_kwargs={"global_token_count": n},  # same for every microbatch
    loss_kwarg_mbs=[                        # one dict per microbatch
        {"advantages": advantages_mbs[i], "loss_mask": loss_mask_mbs[i]}
        for i in range(n_microbatches)
    ],

I don't think we need this from titan anymore, but I guess removal will be BC breaking :(

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you mean we don't need loss_kwargs={"global_token_count": n}, # same for every microbatch this parameter from torchtitan anymore?

But we would need loss_kwarg_mbs for RL, right?

wwwjn added 2 commits October 12, 2026 17:45
…ents

`step()` forwards the same `loss_kwargs` to the loss of every microbatch,
so a loss cannot take inputs that differ per microbatch beyond the
target, such as per-token advantages and loss masks in RL.

Add `loss_kwarg_mbs`: pre-split loss keyword arguments, one dict per
microbatch, mirroring `kwarg_mbs` for model inputs. Microbatch `i`
computes `loss_fn(output, target_mbs[i], **loss_kwargs,
**loss_kwarg_mbs[i])`, so a key in both raises the usual duplicate
keyword argument `TypeError`. `loss_kwarg_mbs` is validated like the
other pre-split inputs: it must be a list of `n_microbatches` dicts and
cannot be combined with whole-batch inputs or `target`. Backward
metadata inference uses the first microbatch's entry, as it does for
the target; the docs note that this extra `loss_fn` call means the loss
must not accumulate into objects passed this way.

Test plan:
python test/distributed/pipelining/test_schedule.py -k "test_schedule_with_loss_kwarg_mbs or test_schedule_pre_split_validation"
@wwwjn
wwwjn force-pushed the pp-pytree-target-tuple-loss branch from ac707e2 to f15ed0c Compare October 13, 2026 00:48
@wwwjn

wwwjn commented Oct 14, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Oct 14, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 1 checks: torchtitan-test / torchtitan-x-pytorch-test / test (torchtitan_features_integration, 1, 1, mt-l-x86aavx2-189-704-a10g-8)

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 jobs have failed, first few of them are: trunk / linux-noble-rocm-py3.11-mi350 / test (default, 3, 8, amd-dpx-linux.rocm.gpu.gfx950.1)

Details for Dev Infra team Raised by workflow job

@wwwjn

wwwjn commented Oct 15, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 2 checks: torchtitan-test / torchtitan-x-pytorch-test / test (torchtitan_features_integration, 1, 1, mt-l-x86aavx2-189-704-a10g-8), trunk / linux-noble-rocm-py3.11-mi350 / test (default, 3, 8, amd-dpx-linux.rocm.gpu.gfx950.1)

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

wwwjn added a commit to pytorch/torchtitan that referenced this pull request Oct 17, 2026
Depends on pytorch/pytorch#200238, which adds per-microbatch loss keyword
arguments (`loss_kwarg_mbs`) to pipeline schedules.

- Engine: under PP, copy `global_loss_token_counts` into each microbatch's
  loss arguments and pass one per-microbatch `loss_kwargs` list to
  `_pp_forward_backward_microbatch_group`, which returns the group loss and
  one loss metrics dict per microbatch. The schedule's scalar loss wrapper
  fills a per-microbatch `loss_metrics` dict and replaces it on each call,
  since the schedule also calls the loss on the first microbatch while
  inferring stage metadata. A `_pp_schedule_loss_kwargs` hook maps the
  per-microbatch arguments to the schedule's `step` arguments; GraphTrainer
  overrides it to keep passing the shared `loss_kwargs` its traced loss takes,
  and its rejection of per-microbatch loss arguments now covers its PP path.
- `ForwardBackwardResult.loss_metrics` is nested like `microbatch_groups`:
  one list per group, one dict per microbatch.
- Batcher: return `TrainerStepBatch.microbatch_groups`
  ([num_groups][num_pp_microbatches][dp_degree]); RDMA microbatches keep the
  group structure and number rows in training order.
- Controller: slice trainer ranks per DP rank as (pp, dp, cp, tp), send each
  DP rank its grouped column, and take the metrics from the first rank that
  returns them; reject RDMA microbatch transfer with PP for now.
- RL trainer: lift the PP restriction (context parallelism still raises),
  return no metrics on ranks without the last stage, and stage the merged
  state dicts of all local model parts so every stage publishes into the
  single "model_state_dict" TorchStore key.
- Add CPU unit tests and an 8-GPU PP=2 (Interleaved1F1B) x FSDP=2
  integration test.
wwwjn added a commit to pytorch/torchtitan that referenced this pull request Oct 19, 2026
Depends on pytorch/pytorch#200238, which adds per-microbatch loss keyword
arguments (`loss_kwarg_mbs`) to pipeline schedules.

- Engine: under PP, copy `global_loss_token_counts` into each microbatch's
  loss arguments and pass one per-microbatch `loss_kwargs` list to
  `_pp_forward_backward_microbatch_group`, which returns the group loss and
  one loss metrics dict per microbatch. The schedule's scalar loss wrapper
  fills a per-microbatch `loss_metrics` dict and replaces it on each call,
  since the schedule also calls the loss on the first microbatch while
  inferring stage metadata. A `_pp_schedule_loss_kwargs` hook maps the
  per-microbatch arguments to the schedule's `step` arguments; GraphTrainer
  overrides it to keep passing the shared `loss_kwargs` its traced loss takes,
  and its rejection of per-microbatch loss arguments now covers its PP path.
- `ForwardBackwardResult.loss_metrics` is nested like `microbatch_groups`:
  one list per group, one dict per microbatch.
- Batcher: return `TrainerStepBatch.microbatch_groups`
  ([num_groups][num_pp_microbatches][dp_degree]); RDMA microbatches keep the
  group structure and number rows in training order.
- Controller: slice trainer ranks per DP rank as (pp, dp, cp, tp), send each
  DP rank its grouped column, and take the metrics from the first rank that
  returns them; reject RDMA microbatch transfer with PP for now.
- RL trainer: lift the PP restriction (context parallelism still raises),
  return no metrics on ranks without the last stage, and stage the merged
  state dicts of all local model parts so every stage publishes into the
  single "model_state_dict" TorchStore key.
- Add CPU unit tests and an 8-GPU PP=2 (Interleaved1F1B) x FSDP=2
  integration test.
wwwjn added a commit to pytorch/torchtitan that referenced this pull request Oct 19, 2026
**Depends on pytorch/pytorch#200238**, which adds
`step(loss_kwarg_mbs=...)` to pipeline schedules. Every PP run in
TorchTitan now passes it, so CI will fail until that change reaches the
torch nightly.

## Why

The RL trainer rejected pipeline parallelism for two reasons:

1. TorchStore could not publish a complete model from stage-local state
dicts. The routing client from #5061 fixes this: every stage publishes
into the same key.
2. The RL loss takes per-token arguments (advantages, generator
logprobs, loss mask, temperature) that differ per microbatch, and
pipeline schedules passed the same `loss_kwargs` to every microbatch.
pytorch/pytorch#200238 adds `loss_kwarg_mbs` for this, so TorchTitan no
longer needs an RL-side workaround.

## What changes

- **Engine (shared):** under PP, the engine copies
`global_loss_token_counts` into each microbatch's loss arguments and
passes them to the schedule as `loss_kwarg_mbs`, instead of raising "not
supported with pipeline parallelism yet". It also collects one loss
metrics dict per microbatch: the schedule's scalar loss wrapper fills a
per-microbatch `loss_metrics` dict, replacing it on each call because
the schedule also calls the loss on microbatch 0 while inferring stage
metadata. `ForwardBackwardResult.loss_metrics` is now nested like
`microbatch_groups` (one list per group, one dict per microbatch). The
pretraining trainers do not read these metrics.
- **GraphTrainer:** its traced loss takes one shared set of loss
arguments. It overrides `_pp_forward_backward_microbatch_group` to keep
passing the shared `loss_kwargs` to its runtime, and its existing
rejection of per-microbatch loss arguments now also covers its PP path.
- **RL trainer:**
- Lifts the PP restriction. Context parallelism still raises, because
per-token loss arguments are not sharded along the sequence yet.
- The batcher returns `TrainerStepBatch.microbatch_groups`
(`[num_groups][num_pp_microbatches][dp_degree]`), so each group runs as
one pipeline step. The controller sends each DP rank its grouped column;
the Monarch actor system now slices the trainer ranks as `(pp, dp, cp,
tp)` so a DP rank's slice spans every pipeline stage.
- Ranks without the last stage return no metrics, and the controller
takes the result from a rank that has it. V-style schedules (ZBV,
DualPipeV) put the last stage on the first PP rank, so this does not
assume a fixed rank.
- RDMA microbatch transfer (`async_loop.batcher.rdma_min_tensor_bytes`,
off by default) keeps the group structure, but is rejected together with
PP for now: its prefetcher reads one microbatch per group.
- Every stage publishes its partial state dict into the single
`model_state_dict` key, so generators do not depend on the trainer PP
layout.
- **CI:** new 8-GPU integration test
`rl_grpo_pp2_interleaved1f1b_fsdp2_gen_tp2`: Qwen3-0.6B, trainer PP=2
with Interleaved1F1B (two stages per rank) x FSDP=2, two TP=2
generators, untied embeddings.

## Test plan

- `tests/unit_tests/cpu/test_trainer.py`,
`tests/unit_tests/cpu/test_pipeline_parallel.py`, and GraphTrainer's
`test_trace_module.py` and `test_graph_pp_runner.py` pass on the
2026-10-07 CPU nightly with pytorch/pytorch#200238 applied. One GraphPP
test fails because the optional `dist_moe` package is not installed,
which is unrelated.
- RL CPU unit tests pass locally with vLLM stubbed out (no real vLLM on
that host); the per-file failure set matches `main`. The tests that
spawn Monarch processes (`test_batcher_actor.py`, the multi-rank RDMA
test) time out on that host on `main` too, so CI covers them.
- Not yet run on this version: the 8-GPU integration test. It needs vLLM
plus the PyTorch change; CI covers it once #200238 is in the nightly.
- An earlier version of this PR, which used an RL-side workaround
instead of the PyTorch change, ran an 8-step deterministic
batch-invariant run where PP=2 x FSDP=2 matched no-PP FSDP=2 bit for bit
on loss, entropy, and reward, with `logprob_diff/max = 0`. grad_norm
differed by 1 ULP at one step. This needs re-running on this version.
acisseJZhong added a commit to pytorch/torchtitan that referenced this pull request Oct 22, 2026
TorchTitan `release/0.4` uses pipelining behavior missing from the
inspected PyTorch 2.15 RC: core PP rejects `loss_kwarg_mbs`, Dist-MoE PP
cannot register metadata cleanup, and ZeroBubble with release-pinned
remat fails when split backward detaches a view in place. This adds an
automatically applied compatibility shim for those three upstream fixes.

### PyTorch PRs backported

| Upstream PR | Author | Required behavior |
| --- | --- | --- |
| pytorch/pytorch#199884 | Sanket Purandare |
Register post-metadata-inference cleanup callbacks, used by Titan's
Dist-MoE PP integration and forwarded by GraphTrainer. |
| pytorch/pytorch#200238 | Jiani Wang | Support
per-microbatch `loss_kwarg_mbs`, already passed by core Titan PP
training. |
| pytorch/pytorch#200199 | Animesh Jain | Skip
in-place detach of view stage outputs during split input/weight
backward, needed by ZeroBubble with activation rematerialization. |

The corresponding upstream commits are
`f722f226bbcebd522c6fec3bc463b21df273cb7e`,
`9a2d9d7b6434e9aa4e048aa8d1b76939e5fe9962`, and
`b7442f6915a1d95412d7fab784e554053746b08d`.

### Behavior and compatibility boundary

- The packaged shim runs during `import torchtitan`, before training
constructs pipeline schedules. Users do not need to call a patch
function manually.
- It replaces the affected Python functions in the current process,
preserves schedule class identities, and updates the backward alias used
by `stage.py`. Installed PyTorch files are not modified.
- The tested wheel is `torch==2.15.0+cu130`, source commit
`dd1fefe31baf1bc8efbab6dc5291eebfb948b7bf`. The version gate accepts the
public version `2.15.0`; other public versions are left untouched.
- Missing-feature checks and exact before/after function-source
fingerprints bound the backports to the reviewed implementations. All
replacements are prepared before publication; an unsupported source
layout raises an explicit error without partially patching the modules.
Later RCs, the final wheel, and partial cherry-pick combinations need
revalidation.
- Set `TORCHTITAN_DISABLE_TORCH_COMPAT=1` before import in a fresh
process to disable the shim for diagnosis.

### Validation

- 66 CPU tests passed: 13 new compatibility regressions and 53 existing
PP tests. Coverage includes five schedules, microbatch loss values and
gradients, cleanup lifecycle, split-backward view outputs, invalid
inputs, and import gates/atomicity.
- Original RC core PP training reproduces the `loss_kwarg_mbs` failure.
With only the two API backports, ZeroBubble + Full remat reproduces
`Can't detach views in-place`.
- Two-H100 Llama3 training: 1F1B completed three steps; ZeroBubble +
Full remat completed four, including CUDA Graph replay. With seed 42 and
deterministic algorithms enabled, recorded loss and grad norm exactly
matched an independent application of the upstream source diffs for each
recipe.
- Selected GraphTrainer runner tests: 13 passed, plus 6 subtests. WGrad
fusion: 24 passed, plus 13 subtests. GraphTrainer Llama3 FSDP2 completed
four steps in both regional and full Inductor modes; these additional
runs are smoke tests, not numerical-equivalence checks.
- Built and installed the `0.4.0rc1` wheel with `--no-deps` into a
separate directory, then imported it outside the checkout. Automatic
activation, idempotence, class identity, backward alias binding, and
unchanged on-disk Torch hashes passed.
- `pre-commit run --all-files`: formatting/style checks passed; global
Pyrefly remains failing in files outside this diff (61 diagnostics with
the shared development environment; 38 when pointed at the RC overlay).
Unrelated automatic edits were restored. Static type checking does not
observe the runtime-added PyTorch API.

This remains a draft pending release-wheel revalidation and the full
release CI matrix, including B200/Dist-MoE. No additional compiler or
performance backports are included.
MaxiBoether added a commit to datologyai/torchtitan-zephon that referenced this pull request Nov 10, 2026
* [CI Fix] Refresh MI350X goldens for FP32 first-WGRAD accumulation (#5423)

ROCm model/SFT numerical checks still use MI350X goldens from before
#5399. That change produces the first accumulated WGRAD directly in the
parameter's FP32 gradient dtype instead of rounding through BF16, and
refreshed the A10G goldens only.

Refresh the nine MI350X Real-PG golden files used by ten integration
configurations. Values come from full-precision TensorBoard scalars in
[main ROCm
CI](https://github.com/pytorch/torchtitan/actions/runs/38753451439),
using `torch==2.16.0.dev20261015+rocm10.0`. Preserve the existing
ten-step coverage, parallelism/config metadata, and strict
loss/gradient-norm equality checks. The two Llama3 configurations
sharing one golden produce identical values.

Validation in progress:

- Extracted and checked both metrics for all ten steps in every affected
configuration.
- All nine model configurations match bitwise across two independent
main CI runs (`38753451439` and `38778179164`), covering both metrics at
every step.
- Changed-file pre-commit checks passed. Full-tree pre-commit passed
except for 54 existing local Pyrefly dependency/type errors; unrelated
automatic edits were reverted.
- A controlled ROCm run restores only the pre-#5399 Linear
implementation while pinning the failing nightly. This checks whether
the old goldens still pass with the old WGRAD math, separating the
computation change from the nightly update:
https://github.com/pytorch/torchtitan/actions/runs/38787345295
- Full ROCm verification of the updated goldens is queued:
https://github.com/pytorch/torchtitan/actions/runs/38787809162 . Keeping
this PR in draft until the control and verification checks finish.

* [dsv4] HcPost: mix the residual branches (sum over the residual's branch axis) (#5417)

Fixes #5416.

`HcPost` kept the `dim=2` of DeepSeek-V4's reference `hc_post`. The
reference is written for `[B, S, hc, hc, D]`, where `dim=2` is the
residual's branch axis. On torchtitan's `[T, hc, hc, D]` product,
`dim=2` is the other branch index, so each branch was only scaled by its
row sum of `comb` and never mixed with the others.

This PR sums over `dim=1`:

`y[j] = post[j] * x + sum_i comb[i, j] * residual[i]`

That is what the reference and transformers' `DeepseekV4DecoderLayer`
(`comb.transpose(-1, -2) @ hidden_states`) compute.

No parameter changes. Checkpoints trained before this fix still load,
but they were trained without the mixing.

**Test plan**

`tests/unit_tests/cpu/models/deepseek_v4/test_deepseek_v4_mhc.py` (new)
compares `HcPost`, on a non-symmetric `comb`, with:
- the reference `hc_post`, copied verbatim and run on the `[B, S, ...]`
layout;
- the closed form `comb^T @ residual`.

```
pytest tests/unit_tests/cpu/models/deepseek_v4/test_deepseek_v4_mhc.py
```

With this change, both tests pass. With the current `HcPost`, both fail,
with every element mismatched. `ufmt`, `flake8` and `codespell` pass on
the changed files.

* [CI Fix][GraphTrainer] Fix CUDA graph pass test fixture after feed-forward migration (#5425)

The GraphTrainer A10G workflow fails in
`TestDefaultTransformerBlockBuckets.test_compile_time_passes_follow_core_cuda_graph_config`
with `AttributeError: 'int' object has no attribute 'feed_forward'`
([main
job](https://github.com/pytorch/torchtitan/actions/runs/38732792440/job/116414518598)).

Introduced by #5345 (`d51e4b3c6b`): `compile_time_passes` now reads
`layer_cfg.feed_forward`, but this fixture still supplies `layers=[0,
1]`. Give its two dense-layer stubs a `feed_forward=None` field,
matching the other fixtures. Production pass behavior is unchanged.

Validation:
- Reproduced the exact exception using the original fixture against
current main's pass implementation.
- All 3 tests in `TestDefaultTransformerBlockBuckets` pass after the
change.
- CPU validation used isolated `torch==2.16.0.dev20261015+cpu` with the
shared environment's incompatible optional CUDA-only `torchcomms`
package hidden from import. The shared torch 2.14 environment cannot
collect current main's tests because it lacks
`analyze_pipeline_activation_liveness`.
- Ran `pre-commit run --all-files`: all hooks except Pyrefly pass;
Pyrefly reports 54 existing dependency/type errors outside this change.
Restored its unrelated automatic edits. Scoped lint passes with Pyrefly
skipped.

Keeping this a draft pending the complete A10G GPU workflow. This fixes
the reported fixture failure; it does not establish that every later
workflow stage passes.

* [CI Fix][GraphTrainer] Build DeepSeek integration recipes with expert parallelism (#5426)

GraphTrainer's DeepSeek integration recipes enable EP after building a
model with EP disabled. Routed-expert weights consequently retain the
dense placement instead of sharding the expert dimension on the sparse
mesh. Pass `expert_parallel_degree` into the base recipe at construction
time; retain the existing runtime mesh degrees and schedules.

This fixes the stale sharding configuration behind these five failures
in the [main H100
job](https://github.com/pytorch/torchtitan/actions/runs/38781348820/job/116582123654):

| Integration test | Observed failure |
| --- | --- |
| `aot_fx_trace_deepseek_v3_hsdp_edp_shard_ep` | `KeyError: mesh_ep` |
| `aot_fx_trace_deepseek_v3_graph_pp_dual_pipe_v_full_inductor` |
`KeyError: mesh_ep` |
| `aot_fx_trace_deepseek_v3_graph_pp_zbv_zero_bubble_full_inductor` |
`KeyError: mesh_ep` |
| `aot_fx_trace_deepseek_v3_graph_pp_interleaved_1f1b_full_inductor` |
`KeyError: mesh_ep` |
| `aot_fx_trace_deepseek_v3_fused_mla_swiglu_fsdp_tp_ep` |
`RuntimeError: matrix batch sizes have to match` |

Root cause: #5280 (`b81852f007`) moved sharding to model-config
construction and removed the runtime re-sharding step, but missed these
derived integration recipes. Its [direct parent's H100
run](https://github.com/pytorch/torchtitan/actions/runs/38163639527/job/114541631402)
passed the integration stage; the [run at
#5280](https://github.com/pytorch/torchtitan/actions/runs/38172622630/job/114568343559)
first failed all five integrations. Both used
`torch==2.16.0.dev20261011+cu132`. The fused test initially reported an
ambient-mesh error and now reaches the grouped-matmul shape error. The
missing EP placement was reproduced with a local CPU configuration
check.

Pass EP at construction time in all seven affected callers of the
default DeepSeek GraphTrainer recipe in `integration_tests.py`, covering
15 derived recipes. Existing integration tests exercise the fix. Other
recipe families already build with the required EP-enabled layout or
only change mesh degrees.

Validation:
- Local CPU configuration check (kept outside the PR): expert-weight
placement is incorrect in all 15 derived recipes before the fix and
correct in all 15 after it.
- The CPU check used isolated `torch==2.16.0.dev20261015+cpu`, with the
shared environment's incompatible optional CUDA-only `torchcomms`
package hidden from import. No model/sharding code was mocked.
- Ran `pre-commit run --all-files`: all hooks except Pyrefly pass;
Pyrefly reports 54 existing dependency/type errors outside this change.
Restored unrelated automatic edits. Scoped lint passes with Pyrefly
skipped.
- Full H100 training/numerics still needs CI; keep this draft until
verified. Earlier H100 runs also had separate bitwise-determinism
failures after the integration stage, so fixing these configurations
alone does not establish that the entire workflow is green.

* [release] Refresh GPU validation coverage and add B200 (#5411)

The staged-RC GPU workflow omits B200 coverage and H100 DeepEP
activation-checkpoint gradient checks.

Add an 8x B200 job using the existing B200 CI runner/container and a
clean uv environment. Run the full B200 integration suite plus Dist-MoE
CPU/GPU and MXFP8 FSDP unit tests, including the shared GraphTrainer
SimpleFSDP cases. Install pytest/expecttest, FlashAttention 4, and
Dist-MoE before verifying the pinned package versions and the installed
TestPyPI RC. The B200 image recipes use the RC's image dependencies and
pinned torchvision.

Add the H100 DeepEP gradient checks after installing the matching
dependency, and copy the pytest configuration into the isolated
validation directory so strict marker checks recognize `multi_gpu`.
Preserve the existing A10G and H100 GraphTrainer release-validation
jobs, their numerical tests, and precompile support. Update the release
guide for all seven GPU jobs and remaining coverage gaps.

Validation:

- Bash syntax, ShellCheck (excluding SC1091 for the generated venv
activation file), and `git diff --check` passed.
- Static suite and mocked-command audits passed: the non-GraphTrainer
suites cover 92 integration tests / 104 configuration executions. Both
restored GraphTrainer runner functions and the H100 GraphTrainer job
match the pre-PR versions exactly. Verified installed-RC test paths,
precompile support, H100 dependency ordering, B200 SimpleFSDP inclusion,
and failure propagation.
- Pre-commit checks for the three changed files passed. `pre-commit run
--all-files` passed every hook except Pyrefly, which reported 52
existing type/dependency errors in unchanged Python files in the local
environment. Its unrelated automatic edits were reverted.
- Complete-script dry run: **22 mocked scenarios pass**, covering all
seven suites, install retries, version/hardware guards, failure
propagation, checkpoint cleanup, and Lighthouse shutdown.
- Built a synthetic RC wheel from this PR and imported the official
pinned staging wheels from isolated target directories. The original
version/import-location check passes on 8x H100, but **real core and
GraphTrainer CLI startup fail** because `torch==2.14.0` lacks
`torch.distributed.pipelining.analyze_pipeline_activation_liveness`,
imported by the existing Dist-MoE runtime. The current PR source must be
reconciled with the intended release's PyTorch version before it can
pass release validation.
- The branch still has `assets/version.txt=0.2.2`; the workflow
correctly rejects non-RC versions. A matching published RC and actual
A10G/H100/B200 runs are still required. Full dependency installation,
CUDA kernels, DeepEP compilation, and numerical goldens have not been
verified.

* [Muse Spark Open] Add integration tests (#5427)

Add integration tests for Muse Spark Open.

Move debug models from `torchtitan_recipes/models/muse_spark.py` to
`torchtitan_recipes/tests/models/muse_spark.py`.

TP gives NaN grad with fake PG, so tested with real PG.
fake PG leaves tokens on the missing TP vocabulary shard at zero,
causing RMSNorm backward overflow.

* [spmd_types] Overlap module-boundary collectives with compute (async_op) (#5398)

Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0)
(oldest at bottom):
* __->__ #5398

spmd_types collectives wait on the NCCL result right after issuing it,
so
module-boundary redistributes (e.g. the sequence-parallel all-gather
before
attention/MLP and the reduce-scatter after) never overlap with compute
in
eager mode. The DTensor backend avoided this by calling
`redistribute(..., async_op=True)` at exactly these boundaries.

spmd_types now has the same opt-in (meta-pytorch/spmd_types@fce1acb:
`async_op`, forward only by default; `backward_options={"async_op":
True}`
for backward). This bumps the spmd_types pin to that commit and passes
`async_op=True` through `spmd_redistribute_per_axis` from the two
module-boundary call sites in `Module`. Backward collectives still wait.

* [Muse Spark] Fix Muse spark typing (#5428)

Fix some typing issues and unnecessary pyrefly ignore for Muse Spark.

* [Muse Spark Open] Simplify Muse Spark checkpoint mapping (#5429)

Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.17.0)
(oldest at bottom):
* __->__ #5429

Build final HF names and tensor transforms directly. Remove the
intermediate checkpoint names and rename pass.

Add CPU coverage for checkpoint names, RoPE layout, packed weights,
round trips, and dtype checks.

Validation: 4 CPU tests pass. Mapping specs match across all four
flavors. Checkpoint tensors and 10 GPU steps of loss and grad norm are
bitwise identical. File lint passes; repository type checking reports
unrelated dependency errors.

* Consolidate norm input names (#5430)

## Summary

Consolidate norm inputs names on `input` and reuse shared norm sharding
configurations.

## Existing problem

Sharding configurations identify inputs by their `forward` argument
names. Shared norm configurations use `"input"`, but PyTorch's `RMSNorm`
and several custom norms used `"x"`.

This mismatch could silently skip input sharding checks or
redistribution when using something like the shared
`norm_sharding_config`. It also led to model-specific sharding helpers
and a suppressed parameter-name override error in Muse Spark.

## Changes

- Give the common RMSNorm wrapper and custom norms a consistent
`forward(input, ...)` signature.
- Update gated norm sharding keys to match.
- Replace Spark's duplicated head-norm sharding helper with the common
helper.
- Remove unused `input_name` and `has_weight` arguments from the audio
state sharding helper and reuse its wrapper configuration.

Computation order, parameter names, and checkpoint keys are unchanged.
The upstream RMSNorm naming difference is handled in one common wrapper.

* docs: add Muse-Spark-Open to supported models (#5431)

Update the main README by adding Muse-Spark-Open model there

* [Muse Spark Open] Fix tokenizer in FakePG scale recipes (#5438)

Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.17.0)
(oldest at bottom):
* __->__ #5438

Use the plain text tokenizer with test assets in both text-only FakePG
scale recipes. The production multimodal token settings require special
tokens absent from those assets.

Add CPU regression tests for both FakePG tokenizers and the production
token settings. All three tests pass locally; Dist-MoE and CUDA-graph
checks are mocked.

* [Muse Spark Open] Add CPU renderer and tokenizer tests (#5440)

Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.17.0)
(oldest at bottom):
* #5441
* __->__ #5440

Cover renderer prompts, loss masks, escaping, response parsing, tool
round trips, and media rejection with local tokenizer assets.

Check multimodal special tokens, generation templates, and debug recipe
construction. Record the open recipient-parsing bug as strict expected
failures.

Local CPU coverage: 25 tests and 14 subtests passed; 3 expected failures
cover review item 3.

* [Muse Spark Open] Add dummy-media and checkpoint unit tests (#5441)

Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.17.0)
(oldest at bottom):
* __->__ #5441
* #5440

----

- Check that dummy vision and audio encoders preserve text embeddings
and receive zero gradients.
- Save the HF model weights and AdamW state, restore them, and check the
next logits, loss, model state, and optimizer state exactly.
- Run on one GPU without a process group. The GPU unit CI job collects
both tests.

Verified locally: both GPU unit tests passed.

* [Muse] Consolidate Muse Spark and Muse Glimmer vision encoders (#5444)

Remove Muse Glimmer vision encoder implementation to use Muse Spark's.

One change in Muse Spark vision encoder to match the Hugging Face
implementation.
`self.rope_theta ** (-torch.arange(0, half_dim, 2, dtype=torch.float32,
device=device) / half_dim`
changed to
`1.0 / (self.rope_theta ** (torch.arange(0, half_dim, 2,
dtype=torch.float32, device=device) / half_dim)`
which are mathematically same.

## Equivalence testing
- Local numerical comparisons: nine CPU and nine CUDA cases against the
original towers using HF frequency arithmetic. CPU results matched
exactly. CUDA outputs, input gradients, and non-positional parameter
gradients matched exactly; positional gradients used tolerance.
- Ten deterministic CPU AdamW steps per tower: loss, gradient norm, and
updated parameters matched exactly with seed 42.
- GPU validation: six FSDP/HSDP placement, conditional-image, and
CPU-offload tests passed, plus two standalone FlexAttention
encoder/adapter backward cases. The standalone harness was removed from
the patch.
- Checkpoint loads correctly

* [Muse Spark Open] Bridge multi-turn prompts in the renderer (#5448)

## Summary

`MuseSparkRenderer.bridge_to_next_turn` returned `None`, so multi-turn
clients (the Verifiers train client) re-rendered every agent turn from
parsed messages. Parsing is lossy: it strips whitespace, merges
reasoning channels and re-serializes tool arguments. After a
non-canonical completion, the re-rendered prompt no longer starts with
the sampled tokens, and the trainer's sample builder starts a new sample
that repeats the whole history.

This PR implements the bridge. It keeps the previous prompt and
completion verbatim and renders only the new tool and user messages plus
the generation prompt, piece by piece as `render` does. For a canonical
completion the result equals the full re-render. It returns `None`, so
the caller re-renders, when:

- there is no previous turn, or the tail contains an assistant message;
- the completion did not close its turn with `<|eot|>` (a truncated
completion is re-rendered rather than closed with a synthesized
`<|eot|>`);
- the tool results do not match the completion's tool calls one to one.
Muse Spark tool calls carry no ids, so results are matched to calls in
order, and a result's own `name`, when given, must agree.

`render`-side behavior is unchanged.

## Evidence

On a 131k-context multi-turn SWE agent run (Verifiers + OpenCode, 3
steps), each rollout produced about 9 training samples that repeated the
history (~385k tokens per rollout). Two 3-step runs of the same config,
before and after the bridge:

| | step 1 | step 2 | step 3 |
|---|---|---|---|
| training samples, before | 312 | 291 | 264 |
| training samples, after | 64 | 100 | 76 |
| trainer fwd/bwd (s), before | 110 | 86 | 62 |
| trainer fwd/bwd (s), after | 58 | 33 | 16.9 |

The rollouts differ between the two runs, so the per-step numbers are
indicative; the sample count drop is the direct effect.

## Tests

- `tests/unit_tests/cpu/models/muse_spark/test_renderer.py`, 4 new
tests:
- a canonical completion bridged with a tool result equals the full
render;
  - two tool results plus a user message equal the full render;
- a completion with extra spaces in its reasoning is kept verbatim,
while the full re-render drops the spaces and no longer extends the
sampled turn;
- fallbacks to `None`: no previous turn, truncated completion, more tool
results than calls, tool name disagrees with the call, assistant in the
tail.
- The first three fail without the change. The file passes: 10 passed, 3
xfailed (the existing review-item xfails).
- The same 4 tests also pass with the `Muse-Spark-1.2-816B-A42B-open`
checkpoint tokenizer.
- `pre-commit` on the touched files; pyrefly reports 0 errors in
`renderer.py`.

* [Attn] Rename CP backends and relocate model attention modules (#5445)

Stack: this PR -> #4760.

Separate naming and file organization from the MLA CP optimization in
#4760: rename CP/vLLM backends consistently with `InnerAttention`, move
DeepSeek/Kimi MLA classes into model-specific `attention.py` files, and
update callers, including Muse Spark. Computation, parameter names, and
initialization order are unchanged.

Validation: 163 CPU tests passed. DeepSeek V3 and text-only Kimi K3
debug models match main bitwise over 10 BF16/Flex training steps (seed
42, deterministic): initial/final weights, outputs, losses, gradients,
and grad norms. Non-Pyrefly lint hooks passed; Pyrefly reports the same
53 diagnostics as main. GraphTrainer validation is blocked by the
installed PyTorch missing `_is_cacheable_effect`.

* [Muse Spark Open] Match the updated published chat template (#5464)

## Summary

`MuseSparkRenderer` reimplements the checkpoint's `chat_template.jinja`
token by token. The published template on
[meta-models/Muse-Spark-Open-816B-A42B](https://huggingface.co/meta-models/Muse-Spark-Open-816B-A42B)
changed on 2026-10-15 (revision `0fb02478`), and the renderer no longer
produced the same prompts. This PR aligns it with that revision:

- **Reasoning strength:** `low` is 8 and `medium` is 32 (were 16 and
64). `high` (256) and `xhigh` (512) are unchanged. `minimal` is gone
from the template, so
`MuseSparkRendererConfig(reasoning_effort="minimal")` now raises, as the
template does.
- **Function schemas:** a schema without `additionalProperties` gets
`"additionalProperties": false` appended, and missing or empty
`parameters` render as `{"type": "object", "properties": {},
"additionalProperties": false}`. Schemas that already set
`additionalProperties` are kept as is. The template describes these
lines as "as the training renderer prints it".

The template also adds namespace tools and deferred tool loading
(`defer_loading`, `deferred_render_mode`). The renderer does not
implement those yet.

## Verification

- Compared against the published template with transformers'
`apply_chat_template` and the checkpoint's tokenizer, over 5
conversations (user only, system + reasoning, tools with one and two
tool calls and results, special-character escaping) at `low`, `medium`
and `high`:
  - before: 12 of 15 differed (reasoning strength and tool schemas);
  - after: 0 differences, in text and in token ids.
- Against the previous template revision, the old renderer had 0
differences, so these two changes are the whole gap.
- New unit tests in
`tests/unit_tests/cpu/models/muse_spark/test_renderer.py` (the gated
template is not vendored, so they assert the behavior directly):
  - reasoning strength for each effort, and `minimal` rejected;
- `additionalProperties` appended when missing, kept when present, and
the empty-parameters schema.
- 5 tests fail without the renderer change and pass with it; the file
passes (16 passed, 3 existing xfails).

* [rl] Fix model-specific attention scaling in vLLM (#5347)

The vLLM attention replacement does not include model specific softmax
scales which makes GPT-OSS and DeepSeek lose their YaRN-adjusted
scaling.

I just exposed the scale as a property on the attention config and
threaded it through to vLLM. Not sure if this is how you’d want it done.

KL mismatch went from 0.055 before to 0.0006 with GPT-OSS-20b. I didn't
test deepseek.

* Share CUDA graph memory between training and validation (#5241)

Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0)
(oldest at bottom):
* __->__ #5241

----

 ## Summary

Add optional validation CUDA graphs with
`validator.enable_cuda_graphs=True`. Training, validation, and optimizer
graphs share the existing memory pool. Capturing eval first lets its
temporary buffers share storage with training gradients.

- Keep scheduled step 1 eval. After training and optimizer warmup, run
eager eval, then captured eval. This allows us to reuse the memory,
otherwise we will see memory jump during the warmup.
- Preserve memory reuse through `_CUDAGraphGradientState`.
- Prepare PP metadata outside capture and finish PP/FSDP eval cleanup.
- Wait for checkpoint staging before eval can update model buffers.
- Document tensor lifetimes in cuda_graph.md


## Memory usage
  Peak allocated memory per GPU for muse glimmer 30B:

  • Training only: 59.024 GiB.
  • Original main train/eval (w/o cudagraph): 61.531 GiB.
  • This PR's train/eval (w/ cudagraph): 61.530 GiB.

* Fix HFBackendTokenizer chat labels: no generation prompt, single BOS (#4993)

> _Drafted by Claude (AI) for @egeboy35. Opened as a draft until
pre-commit and the CPU tests have run._
>
> ChatProcessor renders the whole conversation with
apply_chat_template(messages) and encodes it with add_bos=True.
HFBackendTokenizer.apply_chat_template defaulted add_generation_prompt
to True, so every sample ended with an extra assistant header that
became part of the supervised labels ('<|start_header_id|>assistant
<|end_header_id|>' for Llama-3.2, '<|im_start|>assistant' for Qwen3).
For templates that render bos_token themselves (Llama 3, and the
tests/assets/tokenizer used by the transformers backend SFT recipe),
encode then added a second BOS.
>
> Drop the add_generation_prompt default (ChatProcessor already passes
it when it renders the prompt) and skip add_bos in encode when the text
already starts with bos_token. Stripping bos_token from the rendered
text would also work, but this keeps apply_chat_template's output
identical to the HF template. bos_token/eos_token are still passed to
the template, which Seed-Coder-style templates need.
>
> Behavior change: HFBackendTokenizer.apply_chat_template(messages) no
longer adds the generation prompt by default. A caller outside
ChatProcessor that relied on that default, for example an ad-hoc
inference script, now has to pass add_generation_prompt=True.
>
> Test Plan:
>
> Run locally without torch (torch cannot be imported on this machine):
a harness loaded the real tokenizer.py, the experiment tokenizer and
text_datasets.py with torch stubbed and ran ChatProcessor on one
question/answer sample. On tests/assets/tokenizer, main gives 2 leading
BOS and labels ['4', eos, 'assistant', eos]; with this change 1 BOS and
['4', eos]. Llama-3.2-1B-Instruct and Seed-Coder-8B-Instruct also get a
single BOS, Qwen3-4B-Instruct-2507 has no BOS, and all supervise only
the answer and EOS.
>
> CI loss for the transformers_modeling_backend SFT debug recipe
(transformers_backend_sft, 2 steps on 2 A10G, from the "Transformers
Modeling Backend 8 GPU Integration Tests" job logs). The recipe sets no
seed, so the init differs between runs:
>
> | run | step 1 | step 2 |
> |---|---|---|
> | main 7349a22,
[35801730461](https://github.com/pytorch/torchtitan/actions/runs/35801730461)
| 11.16481 | 7.31840 |
> | main f2b9625 (parent of this PR),
[36860400769](https://github.com/pytorch/torchtitan/actions/runs/36860400769)
| 11.25066 | 7.05117 |
> | main 33a2dc4,
[36945914121](https://github.com/pytorch/torchtitan/actions/runs/36945914121)
| 11.27421 | 7.13110 |
> | this PR merged into main 8812ee1,
[36976825010](https://github.com/pytorch/torchtitan/actions/runs/36976825010)
| 10.69224 | 7.14706 |
>
> The loss drops over the two steps as it does on main, and step 2 is
inside main's spread. Step 1 is 0.47 to 0.58 below the main runs, which
differ from each other by 0.11; two unseeded steps can't say how much of
that is the label change. The first logged sample on main ends with
`<|end_of_text|>assistant`, with this PR it ends with `<|end_of_text|>`.
The PR run also picked up main's move from the cu130 to the cu132
nightly, which landed after 33a2dc4.
>
> pre-commit on the two changed files passed in the CI Lint job. Not run
yet: the CPU Unit Test workflow was skipped for this commit, so this
still needs a run:
>
> ```
> pytest tests/unit_tests/cpu/test_chat_dataset.py
> ```

Co-authored-by: Claude Opus 5.5 <[email protected]>

* [checkpoint] Reseed EMA after a model-only or EMA-excluded load on any backend (#5141)

`CheckpointManager` (DCP) reseeds the EMA from the just-loaded weights
when the EMA itself was not restored: a model-only load (a seed `step-0`
checkpoint, or `initial_load_path` with the default
`initial_load_model_only=True`) or `exclude_from_loading=["ema"]`.
`docs/checkpoint.md` describes this, and
`test_model_only_load_reseeds_ema_from_loaded_weights` /
`test_exclude_ema_honored_even_when_data_is_present` pin it. The reseed
lives in `CheckpointManager._load_checkpoint`, so
`TorchCheckpointingManager` never does it: after those loads its EMA
keeps tracking the random initialization the model just discarded, and
the EMA's cold-start warning does not fire.

Loading a seed checkpoint, then resuming a step-5 checkpoint with
`exclude_from_loading=["ema"]` (CPU, both backends on the same model):

```
CheckpointManager          after loading step-0: EMA==loaded weights True,  EMA==discarded random init False
TorchCheckpointingManager  after loading step-0: EMA==loaded weights False, EMA==discarded random init True
TorchCheckpointingManager  resume step-5 excluding ema: EMA==loaded weights False, EMA==discarded random init True
```

### Change

Move the reseed from `CheckpointManager._load_checkpoint` into
`BaseCheckpointManager.load`, right after `_load_checkpoint`, so every
backend gets it. The old condition also required `MODEL in states`, to
keep TorchFT's per-replica dataloader-only load from reseeding; that
load calls `_load_checkpoint` directly rather than `load()`, and inside
`load()` the states always include `MODEL` (`model_only` returns it and
`Config.__post_init__` rejects it in `exclude_from_loading`), so that
check can no longer be false and was removed.

### Test plan

- New `test_model_only_load_reseeds_ema_from_loaded_weights` in
`tests/unit_tests/cpu/components/checkpointer/test_torch_checkpointing.py`
loads a step-0 checkpoint with an EMA attached and checks the EMA is
reseeded. It fails on main.
- New `test_ema_excluded_from_resume_is_reseeded` (step-5 resume with
`exclude_from_loading=["ema"]`; fails on main) and
`test_full_resume_keeps_restored_ema` (a full resume restores the EMA
and does not reseed it).
- `TestBaseCheckpointManagerTracing._manager` builds a
`Mock(spec=BaseCheckpointManager)` and sets the instance attributes
`load()` reads; it now also sets `states = {}`.
- `test_torch_checkpointing.py` and `test_checkpoint.py` on the rebased
branch: 115 passed (CPU, torch nightly, locally). The two
`test_hf_load_*` tests fail locally with and without this change because
macOS has no `os.O_DIRECT`.
- The comparison above, run on the first commit: both backends report
`EMA==loaded weights True` after both loads.
- flake8 (with the hook's plugins) and ufmt (black 22.12.0, usort 1.0.5)
pass on the changed files of the latest commit; the first commit also
passed pydoclint and codespell.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>

* [scripts] Download chat_template.jinja with the tokenizer assets (#5471)

`HuggingFaceTokenizer` loads a standalone `chat_template.jinja` from the
tokenizer directory first and falls back to the inline `chat_template`
in `tokenizer_config.json` (`torchtitan/components/tokenizer.py`,
"Models like GPT-OSS use this pattern"). `scripts/download_hf_assets.py
--assets tokenizer` doesn't download that file. For
`openai/gpt-oss-20b`, the repo has `chat_template.jinja`,
`tokenizer.json` and `tokenizer_config.json`, and its
`tokenizer_config.json` has no `chat_template` key. A tokenizer
downloaded with the script therefore has no chat template, and building
chat samples fails with `ValueError: No chat template set. Call
set_chat_template() first.`

This adds `chat_template.jinja` to the tokenizer file patterns and to
the docstring list. Repos without the file are unaffected; the script
only downloads patterns that exist in the repo. For a repo that has both
`chat_template.jinja` and an inline `chat_template` in
`tokenizer_config.json`, a fresh download now uses the `.jinja` file,
which is what the tokenizer already prefers and what `transformers`
does.

**Test**
- New `test_tokenizer_includes_standalone_chat_template` in
`tests/unit_tests/cpu/scripts/test_download_hf_assets.py`, using the
existing mocked `list_repo_files` / `hf_hub_download`. It fails on
`main` (2 files downloaded instead of 3) and passes with this change.
The file's 12 tests pass.
- ufmt (black 22.12.0, usort 1.0.5) and flake8 with the pre-commit
plugins are clean on both files.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <[email protected]>

* fix: preserve global metadata for offloaded ema checkpoints (#5357)

## summary

preserve the live parameter's global shape and stride when rebuilding
offloaded ema tensors for checkpoint save and load.

for a 5 by 4 parameter sharded over two ranks, the local shards have 3
and 2 rows. inferring the global shape from each local shard produces 6
and 4 rows, which makes the checkpoint planner reject the chunks. using
`shape=p.shape` and `stride=p.stride()` also handles empty tail shards
and transposed layouts.

the existing cpu rewrap fixture now covers 4, 5 and 1 rows. checkpoint
keys, host shadow storage and ema updates stay unchanged.

## validation

merged `main` at `dbfba1da`. on `0d0d72a1`:

- 44 existing cpu ema tests and 7 optimizer tests passed with torch
2.16.0.dev20261010.
- 8 two-rank gloo checkpoint scenarios passed, covering plain and
replicated tensors, even and uneven fsdp shards, empty tail shards,
transposed tensors and two-dimensional meshes.
- 4 four-rank scenarios passed with both mesh axes larger than one,
including native hsdp and two-axis sharding.
- the same lifecycle checks fail at save on current main for 5 of the
two-rank cases and all 4 four-rank cases. the extended rewrap fixture
also fails on current main.
- the earlier `4934fc73` revision passed old checkpoint loading, layout
changes, and save and reload into the old implementation for 4 layouts.
shadow object and storage identity stayed unchanged. the ema fix is
unchanged in this merge.
- 11 formatting and lint hooks passed. full-repository typechecking and
link checking were excluded. the full-repository typecheck needs
dependencies absent from the local cpu environment.

the gloo scenarios use cpu shadow storage to check checkpoint metadata.
pinned-memory transfers, cuda stream ordering, two-gpu checkpoint
continuation and the debug llama loss comparison remain untested.

Project CI: Please run the CUDA offload and numerical checks in the
project GPU environment: pinned-memory transfers, stream ordering,
two-GPU checkpoint continuation, and the debug Llama loss comparison.
The CPU and Gloo checkpoint results above are ready for review.

Signed-off-by: ZenAlexa <[email protected]>

* Support HF generation tags in HFBackendTokenizer chat templates (#4992)

> _Drafted by Claude (AI) for @egeboy35._
>
> Some HF chat templates wrap assistant turns in `{% generation %} ...
{% endgeneration %}` (SmolLM3-3B and LFM2.5-1.2B `chat_template.jinja`,
TRL's `*_training.jinja`). transformers registers that tag to build
assistant masks. torchtitan's Jinja environment does not, so
`HFBackendTokenizer` raises `TemplateSyntaxError` while auto-loading
such a tokenizer directory.
>
> Per review, the change is now confined to
`experiments/transformers_modeling_backend/tokenizer.py`.
`HFBackendTokenizer.set_chat_template` rewrites the tags into `{% with
%}` / `{% endwith %}`, keeping the `-`/`+` whitespace-control markers,
and then calls `super().set_chat_template()`.
`torchtitan/components/tokenizer.py` is untouched. A with-block also
scopes a `{% set %}` inside it to the block, as transformers does.
>
> Test Plan:
>
> Run locally without torch (torch cannot be imported on this machine).
The real `components/tokenizer.py` and this file were loaded with only
`tokenizers` and `torchtitan.config` stubbed. SmolLM3-3B, LFM2.5-1.2B
and the two TRL training templates render identically to transformers
with `add_generation_prompt` False and True, also with every tag
rewritten as `{%- generation -%}`, `{%+ generation %}`, `{%generation%}`
and similar forms. Templates without the tag (Llama-3.2, Qwen3, OLMo-3,
LFM2, Seed-Coder) are unchanged by the rewrite and render exactly as on
main. The new test fails on main with `TemplateSyntaxError` and passes
with this change. `pre-commit run --files` passes on both files (lychee
skipped). pyrefly, run separately, reports the same errors as on main.
>
> Not run yet (CI):
>
> ```
> pytest tests/unit_tests/cpu/test_tokenizer.py -k
test_hf_backend_renders_generation_tags -v
> ```
>
> 🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <[email protected]>

* [CP] Work around Ulysses graph registration on older NCCL (#5393)

Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.17.0)
(oldest at bottom):
* __->__ #5393

NCCL may reuse an incomplete CUDA-graph IPC mapping for another buffer
view. This can cause incorrect results or invalid memory access. Set
NCCL_GRAPH_REGISTER=0 before process-group initialization for normal
Ulysses on NCCL releases before 2.32.3.

The affected NCCL registration code is shared with other collective
paths, including all-gather and some out-of-place all-reduce paths. This
workaround is scoped to normal Ulysses because that is the confirmed
reproduction. We currently couldn't reproduce this issues with other
collectives, so we just enable the workaround for Ulysses.

Reproduced the error on a smaller scale, need a larger scale run of Kimi
K3 to verify.

Upstream fix: https://github.com/NVIDIA/nccl/pull/2362. The first fixed
public release is NCCL 2.32.3.

* [rl] Split the generator into service, engine loop, dispatcher and engine; add GenerationEngine (#5317)

Stacked on #5316.

## Why

`torchtitan/rl/generator/generator.py` (1860 lines) mixed three concerns
in one class, `VLLMGenerator`:

- calls into vLLM (`EngineArgs`, `render_cmpl` + `add_request`, `step`,
`SamplingParams`, `RequestOutput` parsing, prefix-cache reset,
teardown);
- request dispatch across data-parallel replicas and fan-in of results
to rank 0;
- the engine thread and its SPMD loop (queue, rank 0's decision,
broadcast, step bursts, load coalescing).

That makes each part hard to read in isolation and ties the generator to
vLLM. This PR splits the file along those lines and puts the inference
engine behind an interface, so a second engine (e.g. SGLang) can be
added as another `GenerationEngine` without touching the generator, the
engine loop or the dispatcher.

## What changed

**Generator split**

| File | Contents |
| --- | --- |
| `generator/generator.py` | `Generator` (was `VLLMGenerator`), the
service: config, setup and endpoints |
| `generator/engine_loop.py` | `EngineLoopThread` (the thread and event
loop the engine lives on) and `EngineLoop` (queue, decide -> broadcast
-> apply, load coalescing, policy version, per-group cache-salt pins) |
| `generator/dispatcher.py` | `RequestDispatcher` and the rank-0
completion metrics |
| `generator/types.py` | `SamplingConfig`, `EngineRequest`,
`FinishedRequest`, `RequestMetricsInputs` |
| `generator/engine.py` | `GenerationEngine`, the engine interface |
| `generator/vllm/engine.py` | `VLLMEngine`, holding every vLLM call |
| `generator/vllm/config.py` | `VLLMCudaGraphConfig` |

The dispatcher now receives engine-agnostic `FinishedRequest`s instead
of vLLM `RequestOutput`s, and rank 0 builds each `Completion`. Peer
replicas used to send a `Completion` with a placeholder
`min_policy_version` that rank 0 overwrote; they now send their
`FinishedRequest`s plus the policy version installed when those
finished.

**Engine interface**

- `VLLMGenerator` -> `Generator`, `VLLMGeneratorActor` ->
`GeneratorActor`.
- `GenerationEngine` (`generator/engine.py`) is the interface the engine
loop and the generator call: `add_requests`, `step`,
`has_unfinished_requests`, `load_prefetched_model_state_dict`,
`shutdown`, `prefetched_model_state_dict`, and the data-parallel layout.
Its docstring lists the build arguments every engine accepts.
- `VLLMEngine` implements it. vLLM setup, `EngineArgs` and the stat
logger are private `VLLMEngine` methods, and the engine is built from
its config on the engine loop thread.
- Only `generator/vllm/` imports vLLM; `generator.py` imports the
default engine config lazily.

**Monarch README**

`actors/monarch/README.md` lists the Monarch adapters and the Monarch
use that still lives outside them (provisioning in `train.py`, spawning
in the controller and rollouter, `InterGeneratorRouter` as an `Actor`,
and the RDMA microbatch), with the planned path to confine it to
`actors/monarch/`.

## User-facing changes

- `VLLMGenerator` -> `Generator`, `VLLMGeneratorActor` ->
`GeneratorActor`.
- vLLM-only settings move from `Generator.Config` to
`VLLMEngine.Config`, selected by the new `Generator.Config.engine`
(default `VLLMEngine.Config()`):

  | Before | After |
  | --- | --- |
  | `generator.cuda_graph` | `generator.engine.cuda_graph` |
| `generator.extra_vllm_engine_args` |
`generator.engine.extra_engine_args` |
  | `generator.vllm_stat_logger` | `generator.engine.stat_logger` |
| `generator.session_kv_holder` | `generator.engine.session_kv_holder` |

Engine-agnostic settings stay on `Generator.Config` and are passed to
the engine's build: `model_dtype`, `gpu_memory_limit`,
`max_num_batched_tokens`, `checkpointer`, `dist_moe_runtime`, `debug`.
Every recipe and test is updated. Only Python configs change: the CLI
has no per-field overrides, and `--override` targets override functions,
not config paths.
- `SamplingConfig` moves to `torchtitan.rl.generator.types`,
`VLLMCudaGraphConfig` to `torchtitan.rl.generator.vllm.config`, and
`add_extra_vllm_engine_args` to `torchtitan.rl.generator.vllm.engine`;
every caller is updated.

## Execution order

The per-iteration sequence is unchanged: decide, broadcast, stamp
versions, admit, step burst, fan-in, load. The differences:

- The engine's process-wide setup (`register_to_vllm`, the model runner
env var, the batch-invariant logprob patch) now runs on the engine loop
thread inside the engine build, after `set_batch_invariance` and the
determinism flags. vLLM reads neither at import time.
- `RequestOutput` -> `FinishedRequest` conversion happens in
`VLLMEngine.step` on every rank, not only TP rank 0 (a small list copy
on the other ranks; the n=1 check now fires on every rank instead of
only rank 0).
- A model state dict load sets the policy version after the optional
prefix-cache reset rather than before; both run synchronously on the
engine loop thread, and nothing reads the version in between.
- `generate`'s `stop_token_ids` assert runs before the
closed/not-started guard (error path only).
- Session KV release (#5220) runs through the engine loop as a
`SessionReleaseMessage`, applied on every rank in the next decision;
vLLM priority scheduling (#5257) passes `group_id` as the priority and
rank 0's `arrival_time` to every rank, as on main. Because
`session_kv_holder` is vLLM-only, its check against
`reset_kv_cache_on_model_state_dict_load` now fails when the engine is
built rather than when `Generator.Config` is constructed.

## Testing

- RL CPU unit tests: 492 passed, 8 skipped (rebased on `dc9ea005e`).
`test_engine_loop.py` drives `EngineLoop` directly with a fake engine;
`VLLMEngine`'s admission, salting, rejection, step, shutdown and
KV-reset tests use a fake `LLMEngine`; the engine kwargs test builds
`VLLMEngine` through `Config.build(...)` with vLLM mocked; the
`generate` endpoint and the DP fan-in's min/max versions have their own
tests.
- `pre-commit run --all-files`: clean for the changed files (see #5316
for the unrelated local `kda.py` pyrefly errors).
- Every RL recipe builds, except a hardware-gated MXFP8 recipe.
- GPU A/B against main (2x GB300, Qwen3 debug model with random init and
a deterministic varying reward):
- on-policy, batch-invariant: all 65 non-timing metrics are bitwise
identical to main, and identical run to run;
- async (`target_offpolicy_steps=3`): within main's own run-to-run
variation.
- After the rebase onto `dc9ea005e`, CI's multi-GPU RL suites pass
locally under torchrun: bitwise parity Varlen 3/3, Flex 3/3, Qwen3.5
4/4, and the 4-GPU uneven decode test 1/1.

* [rl] Select the actor framework by config: ActorSystem, implemented for Monarch (#5391)

Stacked on #5317.

## Why

The controller, the rollouter, the trainer, the batcher and `train.py`
used Monarch directly: `train.py` provisioned the GPU proc meshes; the
controller spawned the router and batcher processes, set up torch
elastic, spawned every actor, sliced the trainer by DP rank and stopped
the meshes; the rollouter spawned and stopped its worker pool; the
batcher and the trainer exchanged `MonarchRDMAMicrobatch`es. Running the
RL loop on another actor framework (e.g. Ray) would mean editing all of
them.

This PR puts actor placement behind an interface selected by config, the
way `Generator.Config.engine` selects the inference engine (#5317).

## What changed

- **`actors/system.py`: `ActorSystem`**, framework-agnostic. It
provisions processes, spawns each service, initializes TorchStore
(storage on the trainer's processes, plus every trainer and generator
actor's client), stops the processes, and shuts its client down. The
name follows Akka/Pekko's actor system (see its docstring). Its
docstring also defines the call convention its handles follow: `.call()`
with `.get(rank)` on the result, `.call_one()`, `.choose()`,
`.stream()`, `.broadcast()` (Monarch's endpoint calls; another framework
wraps its handles to provide them).
- `spawn_trainer(config, dp_degree=...)` returns a **`TrainerHandle`**:
all-ranks, rank-0 and per-DP-rank handles. The actor system slices the
trainer by DP rank and checks the `(dp, cp, tp)` layout with
`get_dp_rank`, so the controller no longer slices meshes.
- `spawn_generator_router(router_config, generator_config=...)` spawns
the generators and the router over them, and returns only the router:
the controller reaches the generators through the router.
  - `spawn_batcher`, `spawn_rollout_workers` / `stop_rollout_workers`.
- **`Controller.Config.actor_system`** selects the implementation; the
default `MonarchActorSystem.Config()` is imported lazily.
`Controller.setup_async(actor_system=...)` also accepts one the launcher
built, e.g. a `MonarchActorSystem` on hosts it allocated (`host_meshes`,
`generator_env` constructor arguments), so launchers that bring their
own hosts keep working. `train.py` only builds, runs and closes the
controller, then calls the actor system's `shutdown()`.
- **`actors/monarch/system.py`: `MonarchActorSystem`.**
`actors/monarch/provisioning.py` takes `train.py`'s proc mesh
provisioning (`PerHostProvisioner`, `HostMeshes`, `spawn_proc_mesh`, the
spawn bootstraps) plus `spawn_cpu_procs` and the client `shutdown`.
- **`actors/monarch/router.py`: `InterGeneratorRouterActor`**, the
endpoints and the singleton check. `InterGeneratorRouter` is now a plain
class with public async methods, like `Trainer` and `Generator`.
- **RDMA microbatches (separate commit).** `MonarchRDMAMicrobatch` moves
to `actors/monarch/rdma_microbatch.py`. The batcher and the trainer use
an `RDMAMicrobatch` protocol (`read`, `drop`, the batch/DP
rank/microbatch indices) in `trainer/rdma_microbatch.py`, next to
`RDMAMicrobatchPrefetcher`; `BatcherActor` injects
`MonarchRDMAMicrobatch.register` into `Batcher`.
- **Fix:** `VerifiersRollouter.setup_async` takes `actor_system`
(unused: rollouts run in the Verifiers EnvServer), plus a test that its
signature matches `Rollouter.setup_async`.

After this PR no module outside `actors/monarch/` imports Monarch,
except the controller's lazy default config. `actors/monarch/README.md`
describes the package and the call convention that remains outside it.

## Behavior

- Processes and actors are created in the same order as before: GPU
meshes, router and batcher processes, torch elastic, trainer,
generators, router, batcher, rollout workers, TorchStore. The trainer's
DP-rank layout check now runs right after the trainer spawns instead of
after TorchStore init. Teardown order is unchanged.
- `ts.initialize(mesh=trainer_mesh)` and the per-actor TorchStore client
setup move into `ActorSystem.initialize_torchstore()` (with a TODO to
move it to a model state dict transport).
- A batcher with `rdma_min_tensor_bytes` set but no registration raises
`ValueError`.

## Testing

- RL CPU unit tests: 497 passed, 8 skipped. The Verifiers tests (skipped
without `verifiers`) pass with `verifiers==0.3.1`: 37 passed, 1 skipped.
New tests cover provisioning order and launcher host meshes, trainer
DP-rank grouping and the layout check, teardown order with the batcher,
and the Batcher's missing-registration error.
- `pre-commit run` on the changed files: clean.
- GPU A/B against main (`dc9ea005e`), GB300, Qwen3 debug model with
random init and a deterministic varying reward, 6 steps:
- on-policy, batch-invariant, 1 trainer GPU + 1 generator GPU: all
non-timing metrics bitwise identical (only time-to-first-token differs);
- same, with a DP=2 trainer and `rdma_min_tensor_bytes=1024` (3 GPUs,
per-DP-rank columns over RDMA): bitwise identical;
- async (`target_offpolicy_steps=3`): finishes all steps on both. Both
then hit the same teardown error on main and here (the rollout worker
mesh stops while a router reply is in flight).

* [models] Let the attn_gym facade defer missing-backend import errors (#5467)

## Summary

#5231 made the models importable when `attn_gym` is **absent**. On a
machine where `attn_gym` is **installed but one of its kernel backends
is not** (cutlass and triton have no macOS wheels, the same happens on
any non CUDA box without them), `attn_gym` itself imports fine and its
submodules raise `ModuleNotFoundError(name="cutlass")` /
`(name="triton")` at import time. The facade's `_load_module` only
tolerates `error.name == "attn_gym"`, so the error escapes,
`torchtitan.models.common` fails to import, and none of
`tests/unit_tests/cpu` can collect.

This keeps the existing contract from #5231 and extends it to that case:

- `_load_module` records a `ModuleNotFoundError` raised from inside an
`attn_gym.*` import (keyed by module) and resolves the export to
`_MissingKernel`, so the identity checks in `kda.py` / `gdn.py` /
`linear_attention.py` / `cp_linear_attention.py` still skip SPMD
registration.
- `_raise_missing` re-raises the recorded backend error (same `name` and
message) when a placeholder kernel is called, and `require_attn_gym()`
raises it when a kernel is built. The existing
`test_linear_attention_reports_missing_dependency[cutlass-*]` cases
therefore still see `error.name == "cutlass"`.
- No change when `attn_gym` is missing, and no change when every backend
imports.
- `require_attn_gym()` is deliberately coarse, any recorded backend
failure makes it raise, which matches the previous behaviour where the
module import itself failed. Per kernel granularity can come later if a
backend mix (e.g. cuDNN present, cutlass absent) turns out to matter.

Related: #5181 (@githubsgi) handles the same symptom for the KDA import
in `attention/__init__.py`, this does it once at the facade for every
export, including the `linear_attention.py` import that still fails
without it.

## Test plan

New
`test_common_attention_imports_with_broken_attention_gym_backend[cutlass|triton]`
in `tests/unit_tests/cpu/models/common/test_optional_imports.py`: an
installed `attn_gym` whose submodules all fail on the backend import,
the common package and every model debug config still import/build,
`_MissingKernel` is not registered with SPMD, and calling a kernel,
`require_attn_gym()`, or building `KDAKernel` / `GDNKernel` raises the
backend's own `ModuleNotFoundError`.

On macOS 15 (Apple Silicon, torch 2.16.0.dev20261014+cpu, attn-gym
0.0.17 without cutlass/triton):
- before: `pytest tests/unit_tests/cpu/components/checkpointer` → 2
errors during collection (`No module named 'cutlass'`, then `'triton'`)
- after: `tests/unit_tests/cpu/models/common/test_optional_imports.py`
11 passed; `tests/unit_tests/cpu/components/checkpointer` 120 passed, 2
failed (unrelated: torch_checkpointing uses `os.O_DIRECT`, reported
separately); `torchtitan/experiments/torchft/tests` 26 passed
- `pre-commit run --files` on both files: all hooks pass (flake8, µfmt,
pydoclint, codespell, pyrefly)

* [tokenizer] Preserve non-special added tokens (#5470)

`_infer_special_tokens` reads `special=False` from
`added_tokens_decoder`, then passes every token to `add_special_tokens`.
That call marks the ordinary added tokens special too, so default
decoding drops them.

This affects Qwen3's reasoning and tool-call delimiters. I changed the
registration call to `add_tokens`, which keeps each `AddedToken.special`
flag. True special tokens such as EOS are still filtered. The change
does not alter token IDs, model parameters, or checkpoint keys.

Reproducer (downloads only two tokenizer files):

```python
import torchtitan
from huggingface_hub import model_info, snapshot_download
from tokenizers import Tokenizer
from torchtitan.components.tokenizer import HuggingFaceTokenizer

repo_id = "Qwen/Qwen3-0.6B"
revision = model_info(repo_id).sha
path = snapshot_download(
    repo_id,
    revision=revision,
    allow_patterns=["tokenizer.json", "tokenizer_config.json"],
)
reference = Tokenizer.from_file(f"{path}/tokenizer.json")
wrapped = HuggingFaceTokenizer(tokenizer_path=path)
print("torchtitan:", torchtitan.__file__)
print("revision:", revision)
for text in (
    "<think>reason</think>answer<|im_end|>",
    '<tool_call>{"name":"f"}</tool_call><|im_end|>',
):
    ids = reference.encode(text).ids
    print("reference:", reference.decode(ids))
    print("wrapped:", wrapped.decode(ids))
```

Observed on Qwen3 tokenizer revision
`c1899de289a04d12100db370d81485cdf75e47ca`:

| Decoded content | Before | After / reference |
|---|---|---|
| Reasoning + answer | `reasonanswer` | `<think>reason</think>answer` |
| Tool call | `{"name":"f"}` | `<tool_call>{"name":"f"}</tool_call>` |

The new offline CPU regression uses a small WordLevel tokenizer and
checks that encoding IDs stay the same, non-special added tokens survive
decoding, EOS is still filtered, and `skip_special_tokens=False` still
preserves both token kinds. It fails on main with `'hello world' !=
'hello <domain> world'` and passes with the fix.

Test plan:

```bash
pytest tests/unit_tests/cpu/components/test_tokenizer.py \
       tests/unit_tests/cpu/components/test_renderer.py \
       tests/unit_tests/cpu/components/data/test_chat_dataset.py \
       tests/unit_tests/cpu/models/muse_spark/test_tokenizer.py -q
```

52 passed, 1 skipped, 5 subtests passed on CPU with torch
`2.16.0.dev20261016+cpu`. The skip was the gated Llama tokenizer
download. No GPU training was run.

`pre-commit run --all-files` passes, with Pyrefly run separately (no
errors).

I used AI assistance (Claude and GPT-6 Astra) to find, fix and test this
bug.

---------

Signed-off-by: mottopanikeiku <[email protected]>
Co-authored-by: mottopanikeiku <[email protected]>

* [models] Report the missing backend per Attention Gym kernel (#5500)

## Summary

Follow up to #5467 (review point 2 there). The facade recorded backend
import errors per attn_gym module, but every placeholder raised the
first recorded error, so with, say, `attn_gym.sparse` failing on cutlass
and the GDN modules importing fine, `GDNKernel.Config().build()`
reported cutlass although GDN would have worked.

- Exports of a module whose backend is missing now resolve to a
`_MissingKernel` subclass carrying that module's error (one subclass per
module, cached, named `_MissingKernel[<attn_gym module>]`). Calling it,
`.apply`, or `.from_fragments` raises a fresh `ModuleNotFoundError` with
that backend's name and message.
- `is_missing_kernel()` (a `TypeGuard`) replaces the `is not
_MissingKernel` identity checks in `kda.py`, `gdn.py`,
`linear_attention.py` and `cp_linear_attention.py`, so the subclasses
are also kept out of SPMD registration.
- `require_attn_gym(kernel, *kernels)` checks the given exports and each
module calls it from `__init__` with every export it uses, so a build
error names the backend that module needs: `KDAKernel` (`chunk_kda`,
`bound_gate`, `l2norm`), `GDNKernel` (`chunk_gdn`, `recurrent_gdn`,
`l2norm`), `InnerKDA` / `InnerGDN` (`causal_conv1d`),
`ContextParallelInnerKDA` / `ContextParallelInnerGDN`
(`context_parallel_kda` / `context_parallel_gdn`,
`context_parallel_conv_history`, `ContextParallelRouting`, and `l2norm`
for GDN). The zero argument form from #5467, which raised on any error
recorded so far, is gone.
- No change when `attn_gym` is missing (the placeholders are the base
class and raise the install hint) or when every backend imports.

Not in this PR: attn_gym resolves `causal_conv1d` and the other
`attn_gym.linear.short_conv` exports lazily (`attn_gym.linear._lazy`)
and raises a plain `ImportError` at attribute access, which
`_load_module` never sees, so on a machine without cutlass `gdn.py` /
`kda.py` still fail to import and 18 CPU test modules do not collect. I
have that fixed on top of this branch and will open it next, the
`causal_conv1d` checks here are what make it fail at build rather than
at the first forward.

## Test plan

`tests/unit_tests/cpu/models/common/test_optional_imports.py`:
- new `test_attention_modules_report_their_own_backend_at_build`: a fake
attn_gym whose modules all import except the broken ones. With
`attn_gym.linear.short_conv` failing on cutlass, `KDAKernel` /
`GDNKernel` build and `InnerKDA`, `InnerGDN` and their CP variants fail
at build with cutlass, with the three context parallel modules failing
on triton, the inner modules build and the CP variants fail with triton.
Fails without the `__init__` checks.
- mixed case extended: `…l2norm_fwd` fails on triton and
`attn_gym.linear.kda.impl.fused` on cutlass in one process, `_L2Norm()`
raises triton, `_ChunkKDA()` / `.apply` raise cutlass,
`require_attn_gym(_ChunkKDA)` raises cutlass, `require_attn_gym(real,
_L2Norm)` raises triton, `require_attn_gym(real, real)` passes, the
placeholder is named after its module.
- broken backend case asserts the placeholders are subclasses and that
none reached the SPMD registry.
- existing `[cutlass-*]` build cases now go through
`require_attn_gym(kernels)` and still see `error.name == "cutlass"`.

On macOS without cutlass/triton, rebased on e61df55, 15 passed,
`tests/unit_tests/cpu/components/checkpointer` 123 passed (2 known,
meta-pytorch/torch_checkpointing#9), pre commit on all files passes
every hook except pyrefly, which reports the same pre existing
diagnostics as main in files this PR does not touch.

* [rl] Support pipeline parallelism in trainer (#3980)

**Depends on pytorch/pytorch#200238**, which adds
`step(loss_kwarg_mbs=...)` to pipeline schedules. Every PP run in
TorchTitan now passes it, so CI will fail until that change reaches the
torch nightly.

## Why

The RL trainer rejected pipeline parallelism for two reasons:

1. TorchStore could not publish a complete model from stage-local state
dicts. The routing client from #5061 fixes this: every stage publishes
into the same key.
2. The RL loss takes per-token arguments (advantages, generator
logprobs, loss mask, temperature) that differ per microbatch, and
pipeline schedules passed the same `loss_kwargs` to every microbatch.
pytorch/pytorch#200238 adds `loss_kwarg_mbs` for this, so TorchTitan no
longer needs an RL-side workaround.

## What changes

- **Engine (shared):** under PP, the engine copies
`global_loss_token_counts` into each microbatch's loss arguments and
passes them to the schedule as `loss_kwarg_mbs`, instead of raising "not
supported with pipeline parallelism yet". It also collects one loss
metrics dict per microbatch: the schedule's scalar loss wrapper fills a
per-microbatch `loss_metrics` dict, replacing it on each call because
the schedule also calls the loss on microbatch 0 while inferring stage
metadata. `ForwardBackwardResult.loss_metrics` is now nested like
`microbatch_groups` (one list per group, one dict per microbatch). The
pretraining trainers do not read these metrics.
- **GraphTrainer:** its traced loss takes one shared set of loss
arguments. It overrides `_pp_forward_backward_microbatch_group` to keep
passing the shared `loss_kwargs` to its runtime, and its existing
rejection of per-microbatch loss arguments now also covers its PP path.
- **RL trainer:**
- Lifts the PP restriction. Context parallelism still raises, because
per-token loss arguments are not sharded along the sequence yet.
- The batcher returns `TrainerStepBatch.microbatch_groups`
(`[num_groups][num_pp_microbatches][dp_degree]`), so each group runs as
one pipeline step. The controller sends each DP rank its grouped column;
the Monarch actor system now slices the trainer ranks as `(pp, dp, cp,
tp)` so a DP rank's slice spans every pipeline stage.
- Ranks without the last stage return no metrics, and the controller
takes the result from a rank that has it. V-style schedules (ZBV,
DualPipeV) put the last stage on the first PP rank, so this does not
assume a fixed rank.
- RDMA microbatch transfer (`async_loop.batcher.rdma_min_tensor_bytes`,
off by default) keeps the group structure, but is rejected together with
PP for now: its prefetcher reads one microbatch per group.
- Every stage publishes its partial state dict into the single
`model_state_dict` key, so generators do not depend on the trainer PP
layout.
- **CI:** new 8-GPU integration test
`rl_grpo_pp2_interleaved1f1b_fsdp2_gen_tp2`: Qwen3-0.6B, trainer PP=2
with Interleaved1F1B (two stages per rank) x FSDP=2, two TP=2
generators, untied embeddings.

## Test plan

- `tests/unit_tests/cpu/test_trainer.py`,
`tests/unit_tests/cpu/test_pipeline_parallel.py`, and GraphTrainer's
`test_trace_module.py` and `test_graph_pp_runner.py` pass on the
2026-10-07 CPU nightly with pytorch/pytorch#200238 applied. One GraphPP
test fails because the optional `dist_moe` package is not installed,
which is unrelated.
- RL CPU unit tests pass locally with vLLM stubbed out (no real vLLM on
that host); the per-file failure set matches `main`. The tests that
spawn Monarch processes (`test_batcher_actor.py`, the multi-rank RDMA
test) time out on that host on `main` too, so CI covers them.
- Not yet run on this version: the 8-GPU integration test. It needs vLLM
plus the PyTorch change; CI covers it once #200238 is in the nightly.
- An earlier version of this PR, which used an RL-side workaround
instead of the PyTorch change, ran an 8-step deterministic
batch-invariant run where PP=2 x FSDP=2 matched no-PP FSDP=2 bit for bit
on loss, entropy, and reward, with `logprob_diff/max = 0`. grad_norm
differed by 1 ULP at one step. This needs re-running on this version.

* perf: keep chunked loss gradient buffers in their native dtype (#5408)

## Summary

Keep the chunked-loss hidden-gradient buffers in the hidden-state dtype
and pass those buffers directly to decoder backward. On an H100, this
reduces peak allocated memory by **128 MiB** for the 16K-token cases and
**1,043.983 MiB** for the 128K-token case below.

`GradAccumulator.add()` copies each chunk gradient into a disjoint
slice. Each detached hidden-state leaf already receives a gradient in
its own dtype. The current FP32 assembly therefore widens every
BF16/FP16 chunk and narrows the complete buffer at the end without
performing any arithmetic in between. Using the original dtype removes
both conversions and their temporary allocations.

The change is confined to `ChunkedLossWrapper`; `GradAccumulator`
retains its explicit-dtype contract and zero initialization. LM-head
parameter-gradient accumulation, loss computation, and FSDP
synchronization remain unchanged. This continues the chunked-loss memory
work in #5082.

For BF16/FP16 hidden states with shape `[T, D]`, the assembly buffer
uses `2 * T * D` fewer bytes per output. Removing the final
FP32-to-hidden-dtype copy eliminates another full-buffer allocation at
the handoff. The overall peak depends on the LM-head and loss
intermediates.

## H100 measurements

Measured against `10f03e13d6f3ca8fcf08a16620abe3e2670b3101` on one
NVIDIA H100 80GB HBM3 with MIG disabled, driver 580.95.05, and PyTorch
`2.16.0.dev20261010+cu132`.

All inputs use BF16 and hidden size 4,096. The 16K cases use 16,384
tokens and 8 chunks; the 128K case uses 131,072 tokens and 64 chunks.
`Linear` uses vocabulary size 128,256; `HiMidLoLinear` uses 151,936.

| Workload | Baseline peak allocated (MiB) | Patched peak allocated
(MiB) | Baseline call (ms) | Patched call (ms) |
| --- | ---: | ---: | ---: | ---: |
| Linear, eager CE (16K) | 5394.127 | 5266.127 | 106.849 | 106.524 |
| Linear, compiled CE (16K) | 3392.144 | 3264.144 | 78.625 | 77.781 |
| HiMidLoLinear, compiled CE (16K) | 7510.127 | 7382.127 | 202.609 |
201.783 |
| Linear, compiled CE (128K) | 6101.002 | 5057.019 | 653.783 | 649.521 |

Each timing is the arithmetic mean of two per-process medians, with 15
measured calls after 5 warmup calls per process and
baseline/patched/patched/baseline ordering. Peak allocated memory was
identical between the two processes for each version and workload. The
measured region includes the complete native LM-head, chunked loss, and
backward call. Gradient copies to CPU occur after timing and peak-memory
collection.

This is a peak-memory optimization. The observed latency changes are
small (0.30–1.07%); the two compiled-Linear baseline medians differ by
1.25%. The timing results describe these calls on this device. The
debug-Llama scenario below checks training behavior; its instrumented
step timings are excluded from performance claims.

<details>
<summary>Per-process wall-time medians in execution order</summary>

| Workload | Baseline 1 (ms) | Patched 1 (ms) | Patched 2 (ms) |
Baseline 2 (ms) |
| --- | ---: | ---: | ---: | ---: |
| Linear, eager CE (16K) | 106.880 | 106.627 | 106.420 | 106.818 |
| Linear, compiled CE (16K) | 78.135 | 77.829 | 77.732 | 79.114 |
| HiMidLoLinear, compiled CE (16K) | 202.377 | 201.925 | 201.642 |
202.842 |
| Linear, compiled CE (128K) |…
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged module: pipelining Pipeline Parallelism release notes: distributed (pipeline) release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants