Skip to content

Multi-Turn Chat Dataset SFT - #2769

Merged
tianyu-l merged 5 commits into
pytorch:mainfrom
haydn-jones:sft-multiturn
Sep 15, 2026
Merged

tianyu-l merged 5 commits into
pytorch:mainfrom
haydn-jones:sft-multiturn

Conversation

@haydn-jones

@haydn-jones haydn-jones commented Mar 31, 2026 •

Copy link
Copy Markdown
Contributor

Multi-turn SFT with renderers

Added multi-turn SFT support using the renderers library (https://github.com/PrimeIntellect-ai/renderers) as 0.1.11 no longer requires transformers as a dependency. The RL experiment was already using renderers to some degree, so I moved the config / adapter out into components so it could be shared by SFT. I also needed to do a slight small serialization change to ensure that the renderers config would be properly saved. For now this is opt-in and the old template based path is still there.

If thinking gets dropped by the template for any given turn, then the model is not trained on that thinking (there is no conversation expansion). To enable that, the dataset needs to include N-turn conversations expanded to multiple data points.

Validation:

  • Relevant CPU tests: 183 passed, 2 skipped.
  • Checked with the real Qwen3 tokenizer including tool calls/results, unicode, newline boundaries / etc. Everything lines up.
  • The new multi turn integration test passes through the same fake PG setup used by PR CI. I only ran it on one physical GPU locally.
  • Single-turn loss and grad_norm match main over 10 steps.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Mar 31, 2026
@haydn-jones

haydn-jones commented Mar 31, 2026 •

Copy link
Copy Markdown
Contributor Author

Geeze, ok there's actually an issue with how I'm detecting conversation boundaries. Because BPE is not compositional I tried to get around this by progressively tokenizing the chat, but with models like Qwen which add and drop thinking tokens based on position in chat my span detection is wrong.

I'm not sure exactly what to do about this. I know transformers now uses special jinja directives ({% generation %}) to detect the assistant spans, but plenty of models do not use them (like GPT-OSS 🙄). Marking as WIP until I figure this out.

@haydn-jones
haydn-jones marked this pull request as draft March 31, 2026 18:23
@haydn-jones haydn-jones changed the title Sft multiturn [WIP] Sft multiturn Mar 31, 2026
@haydn-jones
haydn-jones marked this pull request as ready for review April 1, 2026 04:35
@haydn-jones haydn-jones changed the title [WIP] Sft multiturn Multi-Turn Chat Dataset SFT Apr 1, 2026
@joecummings

Copy link
Copy Markdown
Contributor

Thanks for the thorough work here @haydn-jones

Couple things that give me pause:

  1. Per-model maintenance: Every new model needs a hand-written regex, and the GPT-OSS pattern is already complex enough to be hard to audit. I'd rather have something that works with at least most templates automatically.
  2. Readability: The char_spans_to_token_spans offset-walking logic is difficult to follow. I had to trace through it multiple times to convince myself it was correct.

I've been looking at how https://github.com/axolotl-ai-cloud/axolotl/blob/main/src/axolotl/prompt_strategies/chat_template.py does it where they find where assistant turn i lives in the token stream, render the conversation with that turn's content replaced by an empty string, tokenize both, and diff.

Some claude pseudocode:

  def _get_assistant_spans(self, messages, full_tokens):
      spans = []
      for i, msg in enumerate(messages):
          if msg["role"] != "assistant":
              continue

          # Same conversation structure, just empty content for this turn.
          # Strips extra fields (e.g. reasoning_content) so template
          # conditionals like Qwen3's <think> insertion also differ.
          dummy_messages = [
              {"role": m["role"], "content": ""} if j == i else m
              for j, m in enumerate(messages)
          ]
          dummy_tokens = tokenize(apply_chat_template(dummy_messages))

          # Scan from front to find where they diverge
          start = first index where full_tokens[start] != dummy_tokens[start]

          # Scan from back to find where they reconverge
          end = last index (in full_tokens) where they still differ

          spans.append((start, end + 1))
      return spans

I think this handles the Qwen3 problem because both renderings have the same conversation structure - the template's conditional logic fires identically. The only difference is the content of one turn. It should also handle any future template quirks without needing new regexes.

The tradeoff is 2N extra tokenization calls per sample (N = assistant turns). Tokenization is fast relative to a training step, but I acknowledge it's not free. For train_on="last_assistant" we can reduce this to a single extra call.

Thoughts? Something I might be missing here?

@haydn-jones

haydn-jones commented Apr 1, 2026 •

Copy link
Copy Markdown
Contributor Author

I think your suggestion is the better approach, and I’ve implemented it. I've pushed so you can look at it.

With respect to the token diffing method: it correctly finds the assistant content span, but I don’t think the diff alone can reliably recover the end of turn token.

Concrete example:

full:   ...<|im_start|>assistant\nHello there!<|im_end|>\n<|im_start|>user...
blank:  ...<|im_start|>assistant\n            <|im_end|>\n<|im_start|>user...

When scanning from the back, the two sequences reconverge at <|im_end|>\n<|im_start|>user..., because that suffix is identical in both renderings. So the diff isolates Hello there!, but not Hello there!<|im_end|>.

As far as I can tell, Axolotl also needs more than just the diff for this. Their find_turn(...) path renders twice per turn (turns_with_empty and turns_with_content) to find the content boundary, and then they have separate logic to locate EOT / EOS near that boundary.

How do you feel about this? If we want to also supervise the end of turn token, I think that requires additional machinery beyond the diff itself, and I’d be happy to add that once we agree on the right approach.

Edit: Not sure how commit hygiene is enforced here, if we settle on an approach I'd be happy to open a separate PR with cleaner diffs.

@joecummings

Copy link
Copy Markdown
Contributor

Thanks for implementing - looks straightforward. Yeah we have to supervise eot. Could it be as simple as a post-hoc extension that checks whether full_tokens[end] is a special token and include it?

Don't worry about commit hygiene, we'll squash on merge and unless you have 50 reverting commits, it should be fine

@haydn-jones

Copy link
Copy Markdown
Contributor Author

I checked gpt-oss, llama3, llama4, qwen3, and deepseek, and yes the heuristic is correct for all of them. The last things on my mind are:

  1. Push the EOT heuristic
  2. Probably should implement train_on=last_assistant (so we have all, assistant, last_assistant). Or whatever names we want to use.
  3. Reasoning field. gpt-oss expects the reasoning content in a thinking field, qwen3 expects it in a reasoning_content field. Not sure if it should be the responsibility of the dataset to try and handle that mapping at all (e.g., expose reasoning_field_name for the field in the dataset and reasoning_template_name for the chat template expected name). Would allow you to use the same dataset on Qwen / gpt-oss without having to like re-upload to HF. I don't mind either way.

If you have any comments on the above or anything else, let me know and I'll take care of them so we can hopefully close this out.

@joecummings

Copy link
Copy Markdown
Contributor

1 and 2 are fine - maybe use an Enum for 2.

WRT 3, my current thinking is to make this the responsibility of the user constructing the dataset (see how I set up the Qwen3 experiment config).

@haydn-jones

Copy link
Copy Markdown
Contributor Author

Looks like I've done everything I intended to. Merged main in and hit some issues in the validation pipeline. I'm not certain this is correct for context parallel, so this might need some scrutiny.

0582ecc#diff-a05647646c2ceafcb0c9312bebbefe6a7952fbb16e6ffa1c0bf7367680cba184R201

Comment thread torchtitan/hf_datasets/text_datasets.py Outdated
Comment on lines +66 to +68
ALL = "all"
ASSISTANT = "assistant"
LAST_ASSISTANT = "last_assistant"

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.

As someone who doesn't know sft well in general, can I ask when would we want the three modes, respectively? E.g. my naive thinking would be ASSISTANT mode should always be used.

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.

Generally, you do only want to train on assistant completions only as far as I know, though I don't have any insight on real CPT after standard pretraining. I definitely always default to assistant only loss.

I have the other two to match TRL from huggingface and Axolotl. TRL defaults to ALL and axolotl technically supports LAST_ASSISTANT but it's not really advertised (you have to set roles_to_train: []).

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.

Thanks. I would lean on the side of "keeping it simple unless we know it's going to be useful". But maybe @joecummings knows more.

@joecummings joecummings Apr 6, 2026 •

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.

It's not uncommon to be able to specify weighting per-turn (OpenAI also allows this). The best reasoning would be some datasets wherein there's a lot of "setup" and we're really only interested in having the model predict the last turn.

It is definitely not as common as just training on all assistant turns.

In the spirit of "as minimal as possible", we can omit from this PR but please leave a TODO to revisit at some point. Sorry, I got overeager here :)

Comment thread torchtitan/hf_datasets/text_datasets.py Resolved
Comment thread torchtitan/hf_datasets/text_datasets.py Resolved
Comment thread torchtitan/hf_datasets/text_datasets.py Outdated
sample_processor: Annotated[Callable, tyro.conf.Suppress]
"""Callable(sample_dict) -> list[message_dict]. Set in config functions."""

train_on: Annotated[SupervisionMode, tyro.conf.EnumChoicesFromValues] = (

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.

In terms of naming, can we do
supervision_mode: Literal["assistant", ...]

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.

oops, name seems not addressed -- but we can wait until the decision is made on whether or not to have this field.

@haydn-jones

Copy link
Copy Markdown
Contributor Author

Need to do a training run on my silly dataset to make sure everything is looking good.

@haydn-jones

haydn-jones commented Apr 5, 2026 •

Copy link
Copy Markdown
Contributor Author

A couple of things:

  1. The VLM CI is broken because the VLM dataset doesn't emit positions, and because of some changes that happened while I was working on this my fix no longer works around that. The correct fix would be to add position info in to the VLM dataset, and maybe a simple fast fix is emit dummy position information from the VLM collator.
  2. My E2E experiment isn't working properly with the token-span diffing method of finding assistant spans. For Qwen3, we cant supervise the opening <think> token in the assistant message because it shows up in both the blanked render and the real render. When serving, vLLM will use something like add_generation_prompt=True to start off the assistant message, but this does not include a <think> token, so my trained model seems to be getting confused and not thinking / responding as it should. I can get it to do what it should by prefilling the assistant response with a thinking token but not great. Thoughts @joecummings?
  3. Will fix the SupervisionMode thing once we decide if we want to keep configurable supervision modes.

@haydn-jones
haydn-jones marked this pull request as draft April 7, 2026 01:54
@haydn-jones

Copy link
Copy Markdown
Contributor Author

A couple of things:

  1. The VLM CI is broken because the VLM dataset doesn't emit positions, and because of some changes that happened while I was working on this my fix no longer works around that. The correct fix would be to add position info in to the VLM dataset, and maybe a simple fast fix is emit dummy position information from the VLM collator.
  2. My E2E experiment isn't working properly with the token-span diffing method of finding assistant spans. For Qwen3, we cant supervise the opening <think> token in the assistant message because it shows up in both the blanked render and the real render. When serving, vLLM will use something like add_generation_prompt=True to start off the assistant message, but this does not include a <think> token, so my trained model seems to be getting confused and not thinking / responding as it should. I can get it to do what it should by prefilling the assistant response with a thinking token but not great. Thoughts @joecummings?
  3. Will fix the SupervisionMode thing once we decide if we want to keep configurable supervision modes.

Marked this as draft so CI won't run. Points (1) and (2) still need to be addressed. Will wait a few days for comments before checking back in.

@haydn-jones

Copy link
Copy Markdown
Contributor Author

@joecummings I'm a bit swamped with NeurIPS deadline stuff, but I do think I have a solution to the small tokenization issue here. Will implement when I have time. Maybe this weekend?

@pytorch-bot

pytorch-bot Bot commented Apr 18, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@tianyu-l
tianyu-l requested review from jinsooihm and removed request for joecummings and yiming0416 September 13, 2026 17:50

@jinsooihm jinsooihm 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.

Thank you. I think it looks good.

Codex has one concrete complaint

TorchTitan:          Python >=3.11
renderers 0.1.11:   Python >=3.10,<3.14
Effective range:     Python >=3.11,<3.14

On Python 3.14, pip install torchtitan sees that the exact required renderer version does not support the interpreter and fails during dependency resolution:

ERROR: Ignored renderers 0.1.11 because it requires Python <3.14
ERROR: No matching distribution found for renderers==0.1.11

Comment thread torchtitan/hf_datasets/text_datasets.py Resolved
Comment thread torchtitan/hf_datasets/text_datasets.py Resolved
@haydn-jones

Copy link
Copy Markdown
Contributor Author

Thank you. I think it looks good.

Codex has one concrete complaint

TorchTitan:          Python >=3.11
renderers 0.1.11:   Python >=3.10,<3.14
Effective range:     Python >=3.11,<3.14

On Python 3.14, pip install torchtitan sees that the exact required renderer version does not support the interpreter and fails during dependency resolution:

ERROR: Ignored renderers 0.1.11 because it requires Python <3.14
ERROR: No matching distribution found for renderers==0.1.11

Addressed your two comments. For the 3.14 thing, I checked with renderers and 3.14 works fine, I've opened a PR there (PrimeIntellect-ai/renderers#155).

@tianyu-l
tianyu-l requested a review from jinsooihm September 15, 2026 00:10
Comment thread .ci/docker/requirements.txt Resolved
Comment thread torchtitan/components/renderer.py Outdated
import tyro
from renderers import create_renderer, Renderer
from renderers.configs import BaseRendererConfig
from renderers.configs import RendererConfig as LibraryRendererConfig

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.

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.

It started failing type checking once I moved it into core (experiments is excluded from pyrefly). BaseRendererConfig doesn't define name and create_renderer() expects the union of concrete configs. I could rename to like ExternalRendererConfig or something if you want.

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.

OK, let's do PrimeRendererConfig. Thanks!

return val.to_dict()
elif dataclasses.is_dataclass(val):
return _convert(dataclasses.asdict(val))
return {f.name: _convert(getattr(val, f.name)) for f in fields(val)}

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.

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.

That works when called directly but the SFT config nests it inside plain dataset/packing dataclasses. dataclasses.asdict() recursively flattens those before we get to the renderers to_dict() so that method never gets called and the Pydantic config ends up as a string.

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude give renaming / aliasing suggestions, as

  • we already have RendererConfig as core abstraction in repo, RenderersLibraryConfig as a concrete impl of the abstraction to work with prime-rl renderers library configs
  • Now this PR requires importing RendererConfig from prime-rl repo.

@claude

claude Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 42s —— View job


Renaming / aliasing suggestions

I read torchtitan/components/renderer.py and traced all callsites. There are three distinct concepts in play, two of which literally share the name RendererConfig:

# Concept Current name Used where
1 Our base buildable config (Configurable.Config, build() -> renderers.Renderer) RendererConfig components/renderer.py; imported all over RL (controller, rollouter, actors, text_datasets, tests)
2 Our concrete impl that wraps a library config RenderersLibraryConfig components/renderer.py; configs, README, RL examples, tests
3 prime-rl library's base config imported as LibraryRendererConfig only in components/renderer.py (one field annotation)

Two problems:

  • (2) vs (3) are near-anagrams — RenderersLibraryConfig and LibraryRendererConfig sit ~40 lines apart in the same file. This is the bigger readability hazard.
  • (1) vs (3) share the literal name RendererConfig, disambiguated only by the import alias.

Recommendation (minimal churn)

Concept (3) appears in exactly one place (the renderers_config field annotation on line 53), so an alias fully resolves it. Pick an alias that signals upstream origin rather than one that near-duplicates (2):

# torchtitan/components/renderer.py:14
from renderers.configs import RendererConfig as PrimeRendererConfig
# line 53
renderers_config: Annotated[PrimeRendererConfig, tyro.conf.Suppress]
  • Keep (1) RendererConfig — it's the established core abstraction; renaming ripples through every RL file that imports it for no real gain.
  • Keep (2) RenderersLibraryConfig — it's the public name used in configs/README/examples/tests.
  • PrimeRendererConfig (from Prime Intellect) makes it unmistakable that the type is upstream, and kills the anagram collision with RenderersLibraryConfig.

Alternative aliases for (3) if Prime feels too org-specific: LibRendererConfig, UpstreamRendererConfig. I'd avoid LibraryRendererConfig precisely because of the (2) collision.

Alternative (only if you want ownership explicit on our base)

Rename (1) so the literal name RendererConfig can belong to the upstream import:

  • RendererConfig -> RendererBuildConfig (or TitanRendererConfig)
  • then from renderers.configs import RendererConfig

Downside: churn across ~8 RL files/tests, and it doesn't fix the (2)/(3) anagram unless you also touch the alias. I don't think it's worth it — the one-line re-alias above solves the actual confusion.

Want me to apply the recommended one-line change (re-alias to PrimeRendererConfig + update the field annotation and the docstring reference on line 24)?

  • branch sft-multiturn

@haydn-jones

Copy link
Copy Markdown
Contributor Author

@claude give renaming / aliasing suggestions, as

  • we already have RendererConfig as core abstraction in repo, RenderersLibraryConfig as a concrete impl of the abstraction to work with prime-rl renderers library configs
  • Now this PR requires importing RendererConfig from prime-rl repo.

Renamed to PrimeRendererConfig


processor = ChatProcessor.Config(
messages_fn=lambda row: row["messages"],
renderer=RenderersLibraryConfig(renderers_config=Qwen3RendererConfig()),

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.

Is there a reason why we expose RenderersLibraryConfig as a config ? I checked its occurence in the repo: RenderersLibraryConfig takes only one attr renderers_config and its value is always a renderer config.
RenderersLibraryConfig can still exist but not as an exposed config to the user. something like

processor = ChatProcessor.Config(
    messages_fn=lambda row: row["messages"],
    renderer=renderers_config=Qwen3RendererConfig(), # no more RenderersLibraryConfig
)

and RenderersLibraryConfig is instantiated inside ChatProcessor.Config or somewhere else.
I feel RenderersLibraryConfig is in the config as a legacy code from the RL examples and now can be cleaned out from the config.
Maybe not part of this PR but as a follow up as it touches several files unrelated to multiturn SFT.
I can create the PR once this one is merged.
cc @felipemello1 @tianyu-l

@tianyu-l tianyu-l Sep 15, 2026 •

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.

I think it sounds "accidental" that renderers lib also uses config.build() style. But that doesn't mean it'd always be seamlessly usable, e.g.

So from maintenance perspective, every config should be torchtitan native, hence the seemingly unnecessary wrapper. WDYT?

@slimfrkha slimfrkha Sep 15, 2026 •

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.

oh yeah that's right !
However, RenderersLibraryConfig is technically a TorchTitan config, but conceptually it is an adapter (renderer to torchtian config conversion). Exposing it makes users wonder what TorchTitan-specific behavior they are supposed to configure. There is none: the only meaningful choice is already expressed by Qwen3RendererConfig. So I’d rename RenderersLibraryConfig to RenderersConfigAdapter and make these changes:

  def from_renderers(config: PrimeRendererConfig) -> RendererConfig:
      """Adapt a renderers-library config to TorchTitan's renderer config interface."""
      return RenderersConfigAdapter(renderers_config=config)

Then:

  processor = ChatProcessor.Config(
      messages_fn=lambda row: row["messages"],
      renderer=from_renderers(Qwen3RendererConfig(enable_thinking=False)),
  )

Keep RenderersConfigAdapter public for compatibility and internal cases such as Verifiers, but make from_renderers(...) the documented API.

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.

@slimfrkha
I think that's great idea. Please submit a PR.

acisseJZhong added a commit that referenced this pull request Sep 15, 2026
## Summary

- pass an explicit Sigmoid score function to the padding-mask router
tests
- align the tests added by #4594 with the required score_func API
introduced by #4609
- fix the two CPU test failures observed in the PR #2769 CI job

## Test plan

- pytest -q tests/unit_tests/cpu/test_moe.py
- pre-commit hooks for ufmt, flake8, pydoclint, and codespell on
tests/unit_tests/cpu/test_moe.py
@tianyu-l

Copy link
Copy Markdown
Contributor

merging as errors are irrelevant, being fixed by @acisseJZhong

@tianyu-l
tianyu-l merged commit 4a0d8da into pytorch:main Sep 15, 2026
21 of 23 checks passed
@github-project-automation github-project-automation Bot moved this from Todo to Done in TorchTitan Development Sep 15, 2026
tianyu-l pushed a commit that referenced this pull request Sep 15, 2026
Follow-up to #2769 

- Rename RenderersLibraryConfig to RenderersConfigAdapter.
- Add from_renderers(...) as the user-facing API.
- Update recipes, examples, documentation, and tests.

This preserves TorchTitan’s native config boundary while making renderer
configuration clearer.
jinsooihm added a commit that referenced this pull request Oct 6, 2026
Add tool support for multiturn SFT chat data as mentioned by
#2769 (comment)


## Summary

- Add an optional `tools_fn` to `ChatProcessor.Config`.
- Pass per-sample tool definitions to `renderer`-based chat processing.

## Test Plan

python -m unittest tests.unit_tests.cpu.test_chat_dataset
18 tests passed.
jwills added a commit to datologyai/torchtitan-zephon that referenced this pull request Oct 12, 2026
* [data] Keep Hugging Face streaming state opaque to DCP (#5017)

Fixes #4991

## Summary

`GrainDataLoader.state_dict()` stores the nested object from
`iterator.get_state()` under the data-parallel rank key. Distributed
checkpoint flattens that tree and requires the flattened keys to match
at save and load.

With `HuggingFaceStreamingSource`, `examples_iterable.previous_state` is
`None` on a freshly built loader and a dict after iteration. A
checkpoint saved after iteration therefore has no leaf
`dataloader.dp_rank_0...hf.examples_iterable.previous_state`, while
`dcp.load` builds its plan from a new loader that still has that key.
Load planning raises `CheckpointException` (`Missing key in checkpoint
state_dict: ...previous_state`) before `GrainDataLoader.load_state_dict`
runs. Direct `state_dict()` / `load_state_dict()` round trips never hit
this.

That key change is inside the Hugging Face dataset state.
`_HuggingFaceCursorIterator.get_state` stores
`pickle.dumps(self._dataset.state_dict())` under `hf`, and `set_state`
unpickles that bytes leaf before `load_state_dict`. `epoch` stays a
plain field. The rest of the Grain tree stays nested, so other data
sources can still be resharded. `GrainDataLoader` stays on checkpoint
version 1 and still rejects a different data-parallel degree.

## Test plan

- [ ] `pytest tests/unit_tests/cpu/test_dataset_checkpointing.py`
- [ ] `pytest tests/unit_tests/cpu/components/data/test_grain_data.py`

* [ROCm][CI] Regenerate mi350x loss baselines after torch nightly bump (#5062)

## Summary

ROCm model tests loss assertion have been red from today after the CI's
unpinned torch install moved from `dev20261004` to `dev20261005`. I
believe CUDA is also failing on the same test. This regenerates all
affected mi350x loss files.

* [dist_moe] Defer optional backend imports (#5066)

The Dist-MoE integration imported the standalone backend while defining
its module and config types. This made otherwise generic TorchTitan
imports fail once another feature referenced the integration classes.
Especially problematic for defining relations for transforms #4995,
#5007.

Route backend symbol access through a cached lazy module. Postponed
annotations and deferred MXFP8 defaults keep the integration importable,
while selecting Dist-MoE still reports the focused installation error
and preserves failures from dependencies inside an installed backend.

Test Plan: taskset -c 0-7 pytest
tests/unit_tests/cpu/test_optional_imports.py
tests/unit_tests/cpu/test_transforms.py
tests/unit_tests/cpu/test_dist_moe.py -q -k 'not
runtime_passes_per_slot_capacity_to_annex and not
dist_moe_671b_recipe_topology'

Test Plan: env SKIP=pyrefly-check pre-commit run --files
tests/unit_tests/cpu/test_optional_imports.py
torchtitan/models/common/dist_moe/_optional.py
torchtitan/models/common/dist_moe/mxfp8.py
torchtitan/models/common/dist_moe/routed_experts.py
torchtitan/models/common/dist_moe/runtime.py
torchtitan/config/transform/dist_moe.py

* [FSDP] enable apply_fsdp_to_decoder to configure MixedPrecisionPolicy param_dtype_override_fn (#5068)

Allow passing into `apply_fsdp_to_decoder` the `param_dtype_override_fn`
option for `MixedPrecisionPolicy`.

* LoRA for BF16 DistMoE (#4995)

Adds support for LoRA BF16 DistMoE.

`DistMoeRoutedExperts._weight_operands` returns the weights matrices
`w13_EFD, w2_EDF` used to make the DistMoE kernel call.
LoRA overrides `_weight_operands` to add the LoRA matrices to `w13_EFD,
w2_EDF` before returning.

This does not support MXFP8 DistMoE. It would be quite tricky to
implement.

## Some caveats
- `DistMoeTransform -> LoRATransform (for GroupedLinear w13, w2)` would
not error but result in no op. Would it be worth to error out by
checking the parent? It wouldn't be too clean.
- In `transform/lora.py`, `LoRATransform.run_after` registers
`DistMoeRoutedExpert` which requires importing `dist_moe` which is an
optional package dependency. Similar for `common/lora.py`
- Should we just set `LoRATransform.run_after` inside
`transform/dist_moe.py` and move the DistMoE LoRA to DistMoE files?
    - This also raises a question on how to do #5007 nicely.

## Test Plan
One node, 4 GB300 GPU DP shard 4, EP 2, LoRA rank 8, alpha 16
Deepseek v3 debug model on DistMoE LoRA compared to LoRA on
`GroupedLinear` on `w13, w2` with all to all backend.

| Metric | Step 1 | Step 100 | Mean absolute difference | RMSE | Maximum
absolute difference |
|---|---:|---:|---:|---:|---:|
| Loss, all-to-all | 8.217248 | 4.354145 | — | — | — |
| Loss, DistMoE | 8.217256 | 4.347911 | 0.002922 | 0.005632 | 0.030035 |
| Grad norm, all-to-all | 0.00892750 | 0.12869738 | — | — | — |
| Grad norm, DistMoE | 0.00892772 | 0.12781706 | 0.005116 | 0.013849 |
0.098999 |

<img width="1120" height="409" alt="Screenshot 2026-10-03 at 3 46 52 PM"
src="https://github.com/user-attachments/assets/3aa077ce-f666-424e-ba3e-6ef818aa8459"
/>

* Bump attn-gym to 0.0.16 (#5069)

attn-gym 0.0.16 removes `T` from the GDN local-dV kernel's autotune key
(meta-pytorch/attention-gym#625). That kernel takes no `T` argument, and
Triton 3.9 validates autotune keys when the decorator runs, so fused GDN
backward raised on Triton 3.9 with 0.0.15. The release changes no
dependency pins.

Before publishing, the attn-gym release workflow tested the built wheel
on Modal B200 (296 passed, 0 failed, 5 skipped).

* [graph_trainer] Split graph_builder.py by execution path (#5000)

Regenerated on current `main` (the earlier version predated #4999,
#5001, #5003, #5035, #5038 and the Dist-MoE adapter #4541, which all
touched `graph_builder.py`).

## Why
`graph_builder.py` had grown to ~2650 lines mixing the stage-graph
provider, shared helpers, SPMD graph construction (with and without
gradient accumulation), and PP stage graph construction. Splitting it
along the execution paths (SPMD / PP) makes each path readable on its
own.

## What
| File | Contents |
|---|---|
| `graph_builder.py` (~290 lines) | `GraphExecutionPlan`, placement
types, `GraphTrainerStageGraphProvider`, the provider's Dist-MoE slot
lookup |
| `graph_builder_utils.py` (~310) | `GraphTrainerConfigView`, FSDP
bucketing helpers, graph execute/pack/compile helpers shared by both
paths |
| `spmd_graph_builder.py` (~360) | joint-graph tracing shared by both
SPMD paths; SPMD without gradient accumulation executor and builder |
| `spmd_gradient_accumulation_graph_builder.py` (~810) | SPMD with
gradient accumulation: first / middle / last graphs, their executor,
accumulation, edge-graph bucketing |
| `graph_pp/pp_graph_builder.py` (~1020) | PP stage graphs,
partitioning, overlap graphs, the Dist-MoE activation-slot rewrite used
by PP stages |

**Pure code move.** All 45 top-level definitions are AST-identical to
`main` (checked by script), except:
- `spmd_graph_builder.py` imports `GraphExecutionPlan` under
`TYPE_CHECKING` and quotes its annotations, to avoid an import cycle
with `graph_builder.py`.
- Each file has only the imports it uses, its own `logger`, and keeps
`graph_builder.py`'s `from __future__ import annotations` (needed for
the `TYPE_CHECKING`-only Dist-MoE annotations).

Callers (`pipeline.py`, `precompile_main.py`, tests) and `mock.patch`
targets are updated to the new modules.

**Second commit** moves the SPMD gradient-accumulation code out of
`spmd_graph_builder.py` (it was ~70% of that file), so the simple SPMD
path reads on its own. The only non-move change is the dispatch:
`_build_fwd_bwd_graphs` used to trace and then branch on
`plan.has_gradient_accumulation`; its tracing becomes
`_trace_spmd_stage_graph` (shared), `_build_fwd_bwd_graphs` builds only
SPMD without gradient accumulation, the new
`_build_gradient_accumulation_fwd_bwd_graphs` builds the GA path, and
`GraphTrainerStageGraphProvider` picks between them as it already does
for PP. The new module imports from `spmd_graph_builder.py`, not the
reverse.

## Tests
- `test_graph_pp_runner.py`, `test_graph_pp_passes.py`,
`test_trace_module.py`: 169 passed, 4 skipped, 2 failed. Both failures
reproduce on unmodified `main`:
- `test_dist_moe_slot_is_an_explicit_stage_graph_input`: `dist_moe`
package not installed locally.
- `test_initializes_one_stage_pipeline_runtime`: its `SimpleNamespace`
config lacks the new `dist_moe` field read at `trainer.py:108`.
- Bitwise-identical loss and grad_norm vs. `main`, 10 steps, `seed=42`,
`deterministic=True` (`scripts/loss_compare.py --assert-equal`): SPMD GA
first/last (FSDP=4), SPMD GA without FSDP (1 GPU), SPMD without GA
(FSDP=4).
- `precompile_main` / `trainer` import check passes.
- pre-commit clean.

* [config] Centralize built-in transform relations (#5007)

## Summary
Consolidate `run_after` and `conflicts_with` relation into one file,
rather than scattered for each transform.

This makes the import logic simpler and also less brain power to reason
about composability.

`run_after` is modeled by a direct graph `PRECEDES` with an edge `(a,
b)` meaning `a` must be applied before `b`.

`conflicts_with` is modeled by an undirected graph `CONFLICTS` with an
edge `{a, b}` meaning `a` and `b` cannot be applied together.

`PRECEDES` does not necessarily have to be a DAG (although I would
believe a set of reasonable transforms would keep it a DAG), but only
the induced subgraph on the user chosen valid set of transforms without
conflict should be a DAG.

## Not sure about this part but Codex insists
External users who implement their own transform outside of torchtitan
library should still be able to specify these relations,
so the class owned `run_after` and `conflicts_with` should be preserved?

* Always run Flux after the integration suite (#4850)

Flux always runs after run_tests on the fake-PG job and the real-PG
models job, including when run_tests failed. The job still fails if
either suite failed. Flux flavors also finish the rest of the suite
after a failure, same as run_tests. The features job still does not run
Flux.

---------

Co-authored-by: Cursor <[email protected]>

* [qwen3.5] Compile the shared expert's sigmoid gate (#5079)

Qwen3.5's MoE shared expert ends with an eager `sigmoid(gate) * out`
over `[T, 2048]`. This PR compiles it as the `shared_expert_gate` region
and turns it on in the Qwen3.5 defaults.

Kernel time, gate `[T, 1]` x out `[T, 2048]` bf16, eager -> region:
```text
                 H100              GB300
fwd+bwd T=16k    314 -> 153 us     202 -> 51 us
fwd+bwd T=64k    1214 -> 621 us    757 -> 193 us
fwd     T=2k     11.7 -> 4.5 us    10.6 -> 5.7 us
fwd     T=1      3.3 -> 1.1 us     3.6 -> 1.1 us
```

2 MoE layers of Qwen3.5-35B-A3B (GDN + attention), 16k tokens, fwd+bwd,
default regions on:
```text
H100     no AC 66.09 -> 65.81 ms    SelectiveAC 83.10 -> 82.89 ms    peak memory unchanged
GB300    no AC 28.11 -> 27.79 ms    SelectiveAC 37.89 -> 37.34 ms
```

- Accuracy vs fp64 (16k, output and grads): rel L2 4.1e-3 eager, 1.7e-3
region. The region keeps the sigmoid in fp32; eager rounds it to bf16.
- `batch_invariant=True`, like `swiglu`: forward and grads are bitwise
equal when the batch is split (halves, uneven splits, single tokens).
- Recompiles: 3 graphs for train T = 16k, 8k, 2k plus no_grad 16k, 2k,
and 3 for the generator's CUDA graph sizes 2048 ... 1.

**Test plan**
- `tests/unit_tests/gpu/test_sigmoid_gate.py`: matches an fp32
reference; batch invariant.
- H100 with torch 2.15.0.dev20261004+cu132. The GB300 numbers are from
an earlier main (torch 2.15.0.dev20260926).

Co-authored-by: Felipe Mello <[email protected]>

* [CP][Attn] Delegate attention metadata ownership to attention backends (#4897)

## Summary

- Store model-level attention metadata by attention backend class, so
mixed
  models can carry independent metadata for each backend.
- Let each inner-attention backend build its own metadata, and select
that
  metadata before invoking each transformer layer.
- Rename `VarlenMetadata` to `VarlenAttentionMetadata` and preserve
  backend-owned CP metadata preparation.

## Known limitation

Attention metadata is keyed by backend class. If the same backend class
is
configured differently across layers, metadata is currently built once
using
the first encountered configuration. Existing model configurations are
not
affected.

## Testing

- `SKIP=pyrefly-check pre-commit run --all-files`
- Targeted Pyrefly check of the common attention, CP, transform, and
validation
  modules (0 errors)
- `pytest -q
torchtitan/experiments/graph_trainer/tests/test_simple_fsdp.py
tests/unit_tests/cpu/test_context_parallel_validation.py
tests/unit_tests/cpu/test_cp_attention.py
torchtitan/experiments/transformers_modeling_backend/tests/test_hf_build_forward_inputs.py
-k 'not test_every_cp_recipe_passes_the_gate'` (58 passed, 1 deselected,
2 subtests passed)

Rebased without conflicts onto `a3ffc9482` (PR head `e9136ed2c`), then
repeated the pre-commit and targeted CPU tests above successfully.

Retested PR commit `9acf7ac45` against parent commit `0b7536202`.
Deterministic parent-vs-PR comparisons used `seed=42` and 10 training
steps.
All used a shared seed checkpoint except the Transformers backend row,
which
used identical deterministic initialization. Values were read at full
precision from TensorBoard.

| Configuration | GPUs | Loss diff | Grad norm diff |
| --- | ---: | ---: | ---: |
| Llama 3 all-gather CP | 4 | 0 at every step | 0 at every step |
| Llama 3 Ulysses CP | 2 | 0 at every step | 0 at every step |
| Flux HSDP 2x2 + CP=2 with validation | 8 | 0 at every step | 0 at
every step |
| DeepSeek V3 MoE FSDP2 + TP2 + CP2 + EP8 | 8 | 0 at every step | 0 at
every step |
| Qwen3 MoE param groups FSDP2 + TP2 + CP2 + EP8 | 8 | 0 at every step |
0 at every step |
| Transformers backend MoE FSDP + TP + EP + CP (PTRR) | 8 | 0 at every
step | 0 at every step |

The GraphTrainer numerics CI currently reports a small Llama 3 mismatch
at
step 2. A control run from the rebased parent `0b7536202`, without this
PR,
reproduces the exact same values (`7.747598648071289` vs.
`7.747601509094238`), so this failure is not introduced by this PR.

* [optim] Hold the final LR when training runs past lr_scheduler.total_steps (#5057)

`lr_scheduler.total_steps` decouples the LR schedule from
`training.steps`. When it is smaller than `training.steps`, the steps
after the schedule ends keep extrapolating the decay, because `progress`
in `linear_warmup_stable_decay` is never capped at 1:

- linear and sqrt decay go below `min_lr_factor` and then negative
- cosine decay climbs back up toward the peak LR
- with `decay_ratio=0.0` (no decay phase), the first step past the
schedule fails `assert decay_steps != 0`

LR used at steps 1..10 with `training.steps=10`,
`lr_scheduler.total_steps=6`, `warmup_steps=2`, `min_lr_factor=0.1`,
base LR 1.0 (main at d09c6f5):

```
linear  [0.5, 1.0, 1.0, 0.775, 0.55, 0.325, 0.1, -0.125, -0.35, -0.575]
sqrt    [0.5, 1.0, 1.0, 0.55, 0.3636, 0.2206, 0.1, -0.0062, -0.1023, -0.1906]
cosine  [0.5, 1.0, 1.0, 0.8682, 0.55, 0.2318, 0.1, 0.2318, 0.55, 0.8682]
linear, decay_ratio=0.0: 1.0 for steps 2..7, then AssertionError: decay_steps must not be zero to reach this branch
```

### Change

- Clamp the step at the top of the schedule function to the schedule's
last step, so steps past `total_steps` hold its final LR (`min_lr_factor
* lr` here). This covers warmup, stable and decay alike, including
`decay_ratio=0.0`.
- Warn in `build()` when `total_steps < training.steps`, and say on the
`total_steps` field that the LR is held at its final value for the
remaining steps.

With this change all four cases above hold at 0.1 (or 1.0 for
`decay_ratio=0.0`) from step 7 on. Runs where `total_steps` is unset or
at least `training.steps` are unchanged, since the clamp never applies
there.

### Test plan

New `test_steps_beyond_total_steps_hold_final_lr` in
`tests/unit_tests/cpu/test_lr_scheduler.py` covers the four cases above:
from the schedule's last step on the LR equals the final value, and the
steps inside the schedule match a schedule built without `total_steps`.
Its four subtests fail on main and pass with this change.

Run locally (macOS, CPU):

```
pytest tests/unit_tests/cpu/test_lr_scheduler.py tests/unit_tests/cpu/test_optim.py \
       tests/unit_tests/cpu/test_checkpoint.py tests/unit_tests/cpu/test_trainer.py
124 passed, 21 subtests passed
```

`pre-commit run --files` on both files passes; `pyrefly check` (0.45.1)
reports the same result on this branch and on main.

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

---------

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

* ChunkedLossWrapper: free each chunk's logits before its backward (#5082)

**TLDR:** `ChunkedLossWrapper` now frees each chunk's logits before that
chunk's backward. Peak memory drops by 0.58-1.16 GiB for Qwen3-8B;
results are bitwise identical and speed is unchanged.

**Problem**
1. `ChunkedLossWrapper` runs lm_head + loss on one chunk, then
`chunk_loss.backward()`.
2. The `logits` variable keeps that chunk's `[T, V]` logits alive
through the backward, which doesn't need them.
3. So each backward holds one extra buffer: 1.16 GiB per 2048-token
Qwen3-8B chunk with fp32 logits, 0.58 GiB with bf16.

**Solution:** `del logits` right after the loss call.

**Results**

Qwen3-8B head, 16384 tokens in 8 chunks, H100, peak memory during the
call:
```text
CastLinear head (fp32 logits)   8.46 -> 7.30 GiB   eager and compiled CE
bf16 Linear head                5.47 -> 4.89 GiB   eager CE
                                3.78 -> 3.20 GiB   compiled CE
```
Loss, dX and dW are bitwise identical. Speed is unchanged: paired over 8
rounds, within ±0.8 ms of a ~250 ms call.

**Test plan**
- Re-checked on current main (H100, torch 2.15.0.dev20261004): same
savings, bitwise identical loss, dX and dW.
- CPU `test_loss`, `test_lora`, `test_override` and graph_trainer
`test_chunked_loss`: 89 passed.

NOTE: measured on H100; needs retesting on Blackwell.

Co-authored-by: Felipe Mello <[email protected]>

* [docs] Correct stale README launch commands (#5078)

## Summary

Four README commands named modules, configs, or an entrypoint that do
not resolve. tianyu-l asked to land these doc fixes in one PR and to
drop the README guard tests, so #5075, #5076, and #5077 are folded in
here. No unit test is added.

- DeepSeek-V3 16B. `torchtitan_recipes.models.deepseek_v3` defines
`deepseek_v3_671b` and the two 671B Dist-MoE recipes. `deepseek_v3_16b`
lives in `torchtitan_recipes.tests.models.deepseek_v3`, next to
`deepseek_v3_debugmodel`, and does not require Dist-MoE. The 16B command
now uses that tests module. The 671B command stays
`MODULE=torchtitan_recipes.models.deepseek_v3 CONFIG=deepseek_v3_671b`.
- GraphTrainer DeepSeek. `graph_trainer_deepseek_v3_16b` is not defined.
The production module `torchtitan_recipes.graph_trainer.deepseek_v3`
provides `graph_trainer_deepseek_v3_671b_dist_moe_bf16` and the MXFP8
variant. The quick start now runs the BF16 671B Dist-MoE recipe, next to
the production Llama3 and Qwen3 commands. The heading says 671B
Dist-MoE. The 16B name exists only as
`graph_trainer_deepseek_v3_16b_dist_moe_bf16` under
`torchtitan_recipes.tests.graph_trainer`, and that recipe requires
Dist-MoE.
- NVFP4 Llama 3 8B. `Trainer.Config` has no `optimizer` field. The
learning rate is `config.optim.optimizer.optimizers[0].lr`
(`Optim.Config.optimizer` is an `OptimizersContainer.Config`, and that
config's `optimizers` list holds the AdamW config).
`config.optimizer.optimizers[0].lr` raises AttributeError.
- Search-R1. `python torchtitan/rl/train.py` inserts the script
directory `torchtitan/rl` at `sys.path[0]` and does not put the repo
root on `sys.path`, so `import torchtitan` fails unless the package is
installed. `python -m torchtitan.rl.train` puts the current directory on
`sys.path`. `--module` and `--config` are unchanged. The Results
permalinks `e28796e0` and `4b183e3a` stay as historical links.

## Test plan

- [ ] Docs only. The four commands name callables and an entrypoint that
exist on this branch. No unit test is added.

* [CP] Support Kimi K3 KDA CP (#4639)

## Summary

This PR replaces #4500 so the branch can participate in GitHub's native
PR
stacks.

Enable context parallelism for Kimi K3's hybrid KDA/MLA decoder and
multimodal input path.

- KDA layers use Attention Gym's native context-parallel implementation.
Each
rank keeps its local sequence fragments while exchanging the
short-convolution
  history and composing the recurrent state from preceding fragments.
- MLA layers can use all-gather K/V CP with contiguous or headtail
partitions,
  or Ulysses CP with contiguous partitions.
- Multimodal preprocessing shards token-aligned vision-bank indices with
the
token IDs, allowing each rank to map replicated vision-encoder outputs
to its
  local placeholders.

KDA and MLA reuse the same TorchTitan CP mesh. The all-gather
configuration
supports contiguous and headtail partitions across the hybrid model; the
Ulysses configuration requires contiguous partitioning.

## Implementation

The integration follows Attention Gym's [delta-rule context-parallel
example](https://github.com/meta-pytorch/attention-gym/blob/main/examples/linear/delta_rule_context_parallel.py).

The KDA path separates its local stages so the CP adapter can replace
only the
distributed operations while sharing projection, normalization, gating,
and
output logic with the non-CP path. Attention Gym provides:

- `context_parallel_conv_history` for convolution halo exchange; and
- `context_parallel_kda` for recurrent-state summary composition and the
local
  KDA computation.

TorchTitan builds an Attention Gym routing plan that matches its
contiguous or
headtail token assignment and passes the per-batch routing through every
KDA
layer.

## Limitations

- KDA CP currently supports contiguous and headtail partitions; PTRR is
not
  supported.
- Ulysses MLA requires contiguous partitioning; it does not support
headtail.
- Current TorchTitan partitioning requires equal-sized fragments, where
`T` is
  the token count and `C` is the CP degree:
  - contiguous: `T % C == 0`
  - headtail: `T % (2 * C) == 0`

This is a limitation of the current PyTorch/TorchTitan equal-sized
sharder,
not Attention Gym; Attention Gym routing accepts arbitrary fragment
ranges.
- Kimi K3 sample packing is not yet supported. Routing currently models
the
  batch as one global sequence.

## Tests

**CP=1 regression check**

| Step | Before PR loss (CP=1) | This PR loss (CP=1) | Diff | Before PR
grad norm (CP=1) | This PR grad norm (CP=1) | Diff |
| ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| 1 | `8.084497` | `8.084497` | `0.000%` | `2.531250` | `2.531250` |
`0.000%` |
| 10 | `3.574754` | `3.574754` | `0.000%` | `2.562500` | `2.562500` |
`0.000%` |
| 100 | `3.089925` | `3.089925` | `0.000%` | `5.156250` | `5.156250` |
`0.000%` |

**CP=2 loss vs. the before-PR CP=1 baseline**

| Step | Before PR (CP=1) | This PR all-gather (CP=2) | Diff | This PR
Ulysses (CP=2) | Diff |
| ---: | ---: | ---: | ---: | ---: | ---: |
| 1 | `8.084497` | `8.084440` | `0.001%` | `8.084446` | `0.001%` |
| 10 | `3.574754` | `3.576608` | `0.052%` | `3.571825` | `0.082%` |
| 100 | `3.089925` | `3.060069` | `0.966%` | `3.051986` | `1.228%` |

**CP=2 grad norm vs. the before-PR CP=1 baseline**

| Step | Before PR (CP=1) | This PR all-gather (CP=2) | Diff | This PR
Ulysses (CP=2) | Diff |
| ---: | ---: | ---: | ---: | ---: | ---: |
| 1 | `2.531250` | `2.531250` | `0.000%` | `2.531250` | `0.000%` |
| 10 | `2.562500` | `2.562500` | `0.000%` | `2.546875` | `0.610%` |
| 100 | `5.156250` | `5.062500` | `1.818%` | `5.031250` | `2.424%` |

* [1/3] [graph_trainer] Extract FSDP split-pad-cat together with reduce_grad chains (#5058)

FSDP reduce grad chains can contain split-pad-cat before reduce_grad.
We should extract them into REDUCE_GRAD to not execute it in the
middle-repeated microbatch no unshard , no reduce logic.
This PRs includes split-pad-cat into those chains.

Before:

    # Every microbatch
    cast_grad = grad.to(reduce_dtype)
    chunks = torch.split(cast_grad, ...)
    padded = torch.nn.functional.pad(chunks[-1], ...)
    packed_grad = torch.cat((*chunks[:-1], padded))
    grad_accumulator.add_(packed_grad)

    # Final reduce_grad
    reduced_grad = reduce_scatter_tensor(grad_accumulator, ...)


We follow SimpleFSDP annotations to include them.
cast_grad is left in grad computation, to keep it before grad
accumulation.
To have:
grad_accum = cast_bf16(g0) ... cast_bf16(gN).

This matches eager grad accumulation.

After:

    # Every microbatch
    cast_grad = grad.to(reduce_dtype)
    grad_accumulator.add_(cast_grad)

    # Final reduce_grad
    chunks = torch.split(grad_accumulator, ...)
    padded = torch.nn.functional.pad(chunks[-1], ...)
    packed_grad = torch.cat((*chunks[:-1], padded))
    reduced_grad = reduce_scatter_tensor(packed_grad, ...)

* [2/3] [graph_trainer] Fuse WGrad accumulation through views (#5059)

Depends on #5058.

Matmul often followed by view operations.
We need to handle this to do WGrad accumulation.
We fuse grad accumulation before this view op.

Before:

    grad_2d = mm(lhs, rhs)
    grad_3d = grad_2d.reshape(1, 3, 2)
    result = accumulator_3d.add_(grad_3d)

When the path contains only single-user storage aliases, view the
accumulator in the producer shape and let the GEMM accumulate directly
into its storage.

After:

    accumulator_2d = accumulator_3d.view(3, 2)
    grad_2d = addmm_(accumulator_2d, lhs, rhs)
    result = grad_2d.reshape(1, 3, 2)

* [3/3] [graph_trainer] Bucket routed experts by parent scope (#5067)

## Stack

1. #5058
2. #5059
3. This PR

## Summary

Bucket the routed-expert `w13` and `w2` FSDP collectives using their
captured parent scope, `layers.N.moe.routed_experts`.

The traced collective nodes are annotated with the parent scope, while
the bucket plan previously named the `w13` and `w2` child scopes. Those
entries therefore did not match the captured nodes, leaving two
routed-expert buckets per MoE layer. Using the parent scope combines
them into one bucket.

## 256-GPU result

DeepSeek V3 671B DistMoE on 256 GB300 GPUs:

- Cat-fix-only GraphTrainer: 5,670.50 tokens/s/GPU
- GraphTrainer with parent-scope bucketing: 5,830.50 tokens/s/GPU
- Improvement: +2.82%
- Same-cluster eager baseline: 5,822.00 tokens/s/GPU
- GraphTrainer versus eager: +0.15%
- Peak memory: 249.38 GiB versus 265.08 GiB eager

The profile shows all-gathers and reduce-scatters decreasing from 179 to
121 each, removing exactly one of each from all 58 MoE layers. The
experimental dense-overlap scheduler was disabled, so it did not
contribute to this result.

* [rl] Fix RL CPU unit tests resolving a month-old torch nightly (#5083)

## Why

RL CPU Unit Tests is red on `main` and on every PR that runs it. Four
test modules fail at collection:

```
ERROR tests/rl/unit_tests/cpu/test_alphabet_sort.py
ERROR tests/rl/unit_tests/cpu/test_verifiers_example.py
ERROR tests/rl/unit_tests/cpu/test_vllm_registry.py
ERROR tests/rl/unit_tests/cpu/test_vllm_wrapper.py
E   ImportError: cannot import name 'analyze_pipeline_activation_liveness' from 'torch.distributed.pipelining'
```

The cause is the torch the job ends up with. The CPU job resolves `torch
2.15.0.dev20260830` + `vllm 1.0.0.dev20260830`, while the RL GPU jobs in
the same run get `20261005` for both. The CPU job installs the Verifiers
example requirements first and then passes them as a `--constraint` to
the nightly install:

- `verifiers==0.3.1` requires `mcp>=1.24.0,<2`.
- vLLM nightlies since about 2026-10-01 require `mcp>=2.0.0,<3.0.0`.

uv therefore falls back to the newest vLLM that accepts mcp 1.x
(`1.0.0.dev20260830`), which pins a torch from the same day. That torch
predates `analyze_pipeline_activation_liveness`, which `dist_moe`
started importing in #4541.

To reproduce, force a current vLLM next to the Verifiers requirements:

```
$ uv pip compile in.txt --prerelease allow ... # vllm>=1.0.0.dev20261001, verifiers==0.3.1
  × No solution found when resolving dependencies:
  ╰─▶ Because vllm>=1.0.0.dev20261001+cu132 depends on mcp>=2.0.0,<3.0.0 [...]
      And because you require mcp>=1.24.0,<2, we can conclude that your
      requirements are unsatisfiable.
```

## What

- Install torch/torchvision/vLLM nightlies the same way the RL GPU jobs
do (no Verifiers constraint), then run the CPU suite. The plain DAPO
example requirements
(`torchtitan/rl/examples/dapo_math/requirements.txt`, i.e.
`math-verify==0.9.0` for `test_dapo_math.py`) are still installed first
and passed as a constraint. They resolve fine with the current
nightlies.
- After that, install the Verifiers requirements with the installed
torch/torchvision/vLLM versions as constraints, and run
`test_verifiers.py` and `test_verifiers_example.py`. Verifiers only
changes its own dependencies: uv swaps `mcp` 2.x -> 1.30.0 and
`websockets` 17.1 -> 16.1.1 and leaves the nightlies alone.
- Add `pytest.importorskip("verifiers")` to `test_verifiers.py`, the
same guard `test_verifiers_example.py` already has, so the first run
skips it instead of failing at collection.
- Drop the `mcp>=1.24.0,<2` line from `dapo_math/requirements.txt`. It
only existed to constrain the nightly install, and `verifiers==0.3.1`
already requires the same bound.

## Tests

Run locally with torch `2.15.0.dev20260926` and vLLM `1.0.0.dev20260926`
(mcp 2.2.0):

- First run, without Verifiers: `pytest tests/rl/unit_tests/cpu` gives
474 passed, 6 skipped. That includes the three non-Verifiers modules
above; both Verifiers files skip with "could not import 'verifiers'".
- Second run, with `verifiers==0.3.1` installed on top:
`test_verifiers.py` and `test_verifiers_example.py` give 11 passed, and
vLLM still imports with mcp 1.30.0.
- Dry run of the new `uv pip install -r .../requirements.txt
--constraint <nightly pins>` against that env: it installs 19 packages,
changes only `mcp` and `websockets`, and leaves torch/torchvision/vLLM
untouched.
- `uv pip compile` of the nightlies plus `math-verify==0.9.0` resolves
to torch/vLLM `20261005`.
- CI on the first commit picked up torch/vLLM `20261005`, but
`test_dapo_math.py` failed to collect because `math_verify` was missing.
That's fixed by the DAPO requirements step above.

## Follow-up

Outside CI, the Verifiers example still can't share an environment with
current vLLM nightlies, since `verifiers==0.3.1` needs `mcp<2`. The
`verifiers` 0.3.2 dev releases move to `mcp==2.0.0`, but they also
require `renderers>=0.1.12.dev2`, while torchtitan pins
`renderers==0.1.11`. Bumping `verifiers` makes sense once a 0.3.2
release is out.

* [rl] Keep only the NCCL env vars batch invariance needs (#5081)

## Why

`set_batch_invariance` copied all ten NCCL env vars from vLLM's
`override_envs_for_invariance()`, without saying why each one is there.
Most of them are either no-ops or redundant. One isn't an NCCL variable
at all, and one has an invalid value. One of the redundant ones
(`NCCL_NVLS_ENABLE=0`) also turns off NVLS for FSDP
all-gather/reduce-scatter in every batch-invariant training run.

Batch invariance only needs the cross-rank reduction to sum each element
in the same order regardless of message size (that is, token count). The
TP all-reduce is the only collective in a batch-invariant forward that
reduces across ranks: the RL controller rejects sequence parallel, and
FSDP reduce-scatter only runs in backward.

## What

Keep two vars:

- `NCCL_ALGO=allreduce:tree`: tree sums each element along one fixed
tree for every message size. Ring's order depends on how the message is
chunked. Pinning the all-reduce to tree also rules out NVLS and CollNet
for it.
- `NCCL_MAX_NCHANNELS=1`: NCCL builds two inter-node trees and
alternates channels between them (`connectTrees` in
`src/graph/connect.cc`). With several channels, which tree reduces a
given element depends on the message size. With one channel there is
only one tree.

Drop eight vars:

| Var | Why it can go (NCCL 2.30 source) |
|---|---|
| `NCCL_P2P_NET_DISABLE=1` | Not an NCCL variable. |
| `NCCL_NTHREADS=1` | Not a multiple of 32, so `getNthreads`
(`src/graph/tuning.cc`) rejects it as invalid and uses the max thread
count. |
| `NCCL_LAUNCH_MODE=GROUP` | Only toggles a launch barrier for grouped
launches (`src/group.cc`); arithmetic is unchanged. |
| `NCCL_SOCKET_NTHREADS=1` | Helper threads for the socket transport;
only moves bytes. |
| `NCCL_PROTO=Simple` | Simple, LL, and LL128 all sum in the order
`((own + child0) + child1) + child2`, so the protocol doesn't change the
result. |
| `NCCL_MIN_NCHANNELS=1` | No effect once the max is 1. |
| `NCCL_NVLS_ENABLE=0`, `NCCL_COLLNET_ENABLE=0` | Already ruled out for
the all-reduce by `NCCL_ALGO=allreduce:tree`. |

`torchtitan/rl/docs/bitwise_parity.md` is updated to match.

## Tests

Setup: torch 2.15 nightly (cu130), NCCL 2.30.7, vLLM 1.0.0.dev20260926,
a single node with 7x H100.

**1. NCCL all-reduce probe.** Each rank all-reduces bf16 `[num_tokens,
4096]` for `num_tokens` in {1, 2, 7, 33, 128, 511, 2048, 8191, 32768}.
Row `r` holds the same input for every `num_tokens`, and the check is
whether row `r` of the output is bitwise identical across all sizes.

| Env | TP=2 | TP=4 | TP=7 |
|---|---|---|---|
| none (NCCL default) | invariant | **variant** | **variant** |
| all 10 vars (before) | invariant | invariant | invariant |
| `ALGO` + `MAX_NCHANNELS` (after) | invariant | invariant | invariant |
| `ALGO` only | invariant | invariant | invariant |
| `MAX_NCHANNELS` + `PROTO`, no `ALGO` | invariant | **variant** |
invariant |

TP=2 is always invariant, because summing two operands gives the same
result in either order. The existing TP=2 parity recipes therefore can't
catch a cross-rank reduction-order bug.

**2. End-to-end bitwise parity at TP=4.** `TestBitwiseParityVarlen`
(Qwen3-0.6B) with trainer and generator TP set to 4:

- With this PR: 3/3 pass (`test_batch_invariance`,
`test_trainer_vs_vllm_prefill`, `test_vllm_decode_vs_prefill`).
- Negative control, same run with `NCCL_ALGO` removed: all 3 fail
(max_delta 2.4e-2, 7.4e-2, and 7.0e-3). The test does detect the
all-reduce algorithm.

**Not tested:** multi-node. Keeping `NCCL_MAX_NCHANNELS=1` and dropping
`NCCL_PROTO` are both based on reading the NCCL source, not on a
multi-node run.

<details>
<summary>NCCL probe script</summary>

```python
import os
import torch
import torch.distributed as dist

HIDDEN = 4096
NUM_TOKENS = [1, 2, 7, 33, 128, 511, 2048, 8191, 32768]

dist.init_process_group("nccl")
rank = dist.get_rank()
torch.cuda.set_device(int(os.environ["LOCAL_RANK"]))
gen = torch.Generator(device="cuda").manual_seed(1234 + rank)
base = torch.randn(max(NUM_TOKENS), HIDDEN, generator=gen, device="cuda").to(torch.bfloat16)

results = {}
for n in NUM_TOKENS:
    x = base[:n].clone()
    dist.all_reduce(x)
    results[n] = x
ref = results[max(NUM_TOKENS)]
mismatched = [n for n in NUM_TOKENS if not torch.equal(results[n], ref[:n])]
if rank == 0:
    print("invariant" if not mismatched else f"variant at {mismatched}")
dist.destroy_process_group()
```

Run with `torchrun --standalone --nproc_per_node=<TP> probe.py` under
each env setting.

</details>

* Add precomputed routing for weight sync (#5061)

<!-- forkstack:stack:start -->
---
Stack (top to bottom):
- -> #5061 Add precomputed routing for weight sync
---
<!-- forkstack:stack:end -->

Integrate Titan to optionally use the new locally cached routing plan.
Currently, we look up and creating the routing plan every time weights
need to be pulled on the generator. This change speeds up weight
transfer by dispatching the requests faster. This also unblocks features
in Titan e.g. pipeline parallel that need merged state_dict's from
multiple trainers and dtype conversion inside torchstore.

# API Changes

- Pass an enum to `ts.initialize()` that initializes torchstore in the
new mode - a lightweight API that spawns ts actors
- Have Titan explicitly initialize ts client with `ts.client(role=...)`
- this tells ts who stores the data and who needs to get the data

# How it works

There is some metadata exchange that happens lazily on the first
`get_state_dict` and `put_state_dict`

### First `put_state_dict`

The trainer ts clients send state dict metadata to a coordinator

### First `get_state_dict`

The generator ts clients 

- Wait for all trainers to register their metadata with the coordinator
- Build and cache a routing plan after they get all the metadata from
trainers

Co-authored-by: Tushar Jain <[email protected]>

* Make AllToAll dispatch and combine single remat regions (#4958)

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

Human note
----------

* With EP > 1, the all-to-all dispatcher declares two remat regions,
`dispatch` and `combine`. The previous regions covered only the
all-to-all collectives; these also cover the processing around them.
* With EP = 1 there is no communication, so dispatch and combine are not
regions; they are always recomputed.
* The combine now multiplies the bf16 expert outputs by the fp32 router
scores instead of casting them to fp32 first. The product is still
computed in fp32, but the multiply now saves the bf16 input for backward
instead of an fp32 copy. This is unrelated to remat but lands in the
same commit.

Agent note
----------

Before, the split sync ran as a bare op, so it replayed in every
backward
(one host sync per MoE layer) even with `ep_communication` saved. The
operator-level SelectiveAC avoided this by always saving CUDA -> CPU
copies;
a saved `dispatch` region gives a torch_remat policy the same behavior.
The
pins on the all-to-all outputs and on the w2 output are gone, since
those
tensors are now region inputs or outputs: when w2 and the combine are
both
saved, the w2 output is no longer kept.

Regions return only tensors, so the splits come back as CPU tensors and
the
pre-permute shape is derived from them; TorchAO's padded `_unpermute`
allocates and strips its sentinel row itself. Without EP there is no
communication, so the local dispatch and combine stay bare. Bare readers
of
the routed-expert outputs (the dtype cast and postprocess after w2, the
local
scatter-add, the TP zero-fill, the shared-expert add, and the
DeepEP/HybridEP
kernels) call `recompute_needs_tensor` before they read.

The combine also multiplies the bf16 expert outputs by the float32
router
scores directly instead of casting them to float32 first. Type promotion
still
computes the product in float32, but the multiply now saves the bf16
output for
backward rather than a float32 copy twice its size. The local,
all-to-all, and
TorchAO EP=1 combines share `_score_and_scatter_add`. Losses are bitwise
identical; on qwen3 MoE (30B-A3B width, 4 layers, TP2 EP2) activation
memory
without AC drops from 6.5 GiB to 5.5 GiB (256 MiB per layer).

* Fix per-depth MTP loss normalization (#5055)

## Summary
- compute distinct per-depth loss-token and routing-token counts in the
data pipeline, with MTP depth synchronized into dataloader/batcher
config
- carry local counts on microbatches; standard trainers only
accumulate/reduce them, while the RL batcher supplies global counts
- normalize every MTP objective and MoE auxiliary loss with its matching
denominator across packed-sequence and padding boundaries
- forward the optional auxiliary-loss denominator uniformly through
dense and MoE transformer blocks

## Testing
- 252 focused model, loss, MoE, trainer, and config CPU tests
- 179 focused data, trainer, validation, and Flux CPU tests
- 4x H100 real FSDP run, 10 steps: identical loss/grad norm across
ranks, loss 10.50247 -> 5.14992
- 4x H100 real TP+CP MTP integration run, 10 steps
- `pre-commit run --all-files` (all gates except local Pyrefly, whose
installed PyTorch lacks current nightly APIs)

* Fix MXFP8 DCP checkpoint serialization (#5094)

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

MXFP8Linear installs _LinearShardedTensorWithMXFP8Compute as its
nn.Parameter. DCP plans it as an ordinary tensor entry, but when writing
it
asks the tensor for its data through __get_tensor_shard__, and
_ShardedFSDPTensor does not implement that hook. DCP therefore writes
the
wrapper itself, and torch.save pickles the wrapper class along with the
plain high-precision shard it holds in _tensor. The read then fails,
since
torch.load runs under weights_only=True:

    _pickle.UnpicklingError: Weights only load failed.
    WeightsUnpickler error: Unsupported global: GLOBAL

torchtitan.quantization.mxfp8.tensor._LinearShardedTensorWithMXFP8Compute
      was not an allowed global by default

Saving succeeds, so this surfaces only on resume. Any MXFP8 run that
resumes from a DCP checkpoint is affected. #4203 added both the class
and
the parameter wrap.

_ShardedFSDPTensor already documents itself as "the nn.Parameter the
optimizer updates and the checkpoint stores", and quantized operands are
rebuilt per unshard by _build_operands, never checkpointed. So _tensor
is
the shard DCP should persist: high-precision data, byte-identical to
what
an unconverted model writes, and loadable by a model built without the
converter. Under FSDP the parameter is a DTensor, whose
__get_tensor_shard__ forwards to its local tensor's hook.

The test clears torch.serialization's safe globals around the save and
load, so the load fails if the wrapper class is pickled into the
checkpoint even when another import has allowlisted it.

Verified on 2 nodes: save at step 2, resume at step 6. Also verified at
671B on 16 nodes, where the MXFP8 attention arm resumed with no
UnpicklingError.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Save trailing adds so replay skips them (#5070)

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

`torch.utils.checkpoint` stops replay once every tensor saved under the
checkpoint has been recomputed, so it never reruns the trailing ops of a
block
that save nothing. `remat.checkpoint` replays the whole block, so the
bare
end-of-block residual add and the shared-expert add replayed, and their
`recompute_needs_tensor` markers kept their inputs (e.g. the MoE combine
output
and the shared-expert output) alive from the forward until replay.

Make these adds fixed `recompute=False` regions (`ffn_residual`,
`moe.shared_add`) and drop the markers. A saved add keeps nothing
resident
because it saves nothing for backward, its inputs need no persisting,
and
replay skips it, matching checkpoint early stop. Trailing ops that save
what
they produce, such as Muse Glimmer's `post_ffn_norm`, stay bare.

With every region saved (RegionAC `*`), activation memory drops from
8.18 to
7.93 GiB on qwen3 MoE (30B-A3B width, 4 layers, FSDP4 + EP4) and from
9.11 to
8.67 GiB on DeepSeek V3 16B (same setup), one tensor per layer plus one
more
per layer with shared experts, at the same step time; losses are bitwise
identical.

* [1/2] [graph_trainer] Support MTP in single-stage schedules (#5091)

MTP preprocessing returns `(main, mtp)` tuples for both model inputs and
labels. The single-stage GraphTrainer path still asserted that each
value was one tensor, so it rejected a valid MTP batch before tracing.

This removes that single-tensor restriction and lets the existing
runtime carry the tuple structure unchanged:

```text
preprocess -> ((tokens, mtp_tokens), (labels, mtp_labels), kwargs)
```

* Support multiple EMA copies (#5074)

This is a follow-up of https://github.com/pytorch/torchtitan/pull/3985.

It allows EMA to keep track of multiple copies by having a mixture of
`decays` and `half_life_fractions` as the input list. As a results, we
can now support both decay mode and half_life_fractions mode.

It still maintains one `ema` checkpoint key. Each tensor's state now
holds one copy per entry, flattened by DCP to
`ema.state.<fqn>.ema_params.<ema_key>`. The decays and half-life
fractions are flattened into one list of copies, and each copy is
updated independently on the same firing. The CPU-offload path is
unchanged; it runs once per copy on the same side stream.

* [debug] Save the device-mesh layout with `debug.save_parallelism_file` (#5045)

## Parallelism Layout Debug File

Add a new debug option, `config.debug.save_parallelism_file`, which is
**disabled by default**.

When enabled, rank 0 writes a JSON file to `<dump_folder>/<file>`
describing how `ParallelismContext.build_mesh` laid out the world:

```json
{
  "world_size": 8,
  "degrees": {
    "pp": 1,
    "dp_replicate": 1,
    "dp_shard": 8,
    "cp": 1,
    "tp": 1,
    "ep": 4
  },
  "ranks": [
    {"host": "node-a", "local_rank": 0, "global_rank": 0},
    ...
    {"host": "node-a", "local_rank": 3, "global_rank": 7}
  ],
  "meshes": {
    "dense": {
      "axis_names": ["pp", "dp_replicate", "dp_shard", "cp", "tp"],
      "mesh": [...]
    },
    "sparse": {
      "axis_names": ["pp", "dp_replicate", "edp_shard", "ep"],
      "mesh": [[[[0, 1, 2, 3], [4, 5, 6, 7]]]]
    }
  }
}
```

The option is wired into **Trainer**, the **TorchFT trainer**, and the
**RL trainer**

### Why

`debug.save_config_file` records the **requested** parallelism degrees,
but it does not capture the **resulting rank and mesh layout** produced
by `ParallelismContext.build_mesh`.

This debug file makes the actual layout inspectable. In particular, it
provides an easy way to verify that **expert parallelism (EP) is placed
intra-node**, which is important in setups where communication across
nodes is significantly slower than communication within a node.

* [rl] Fix loss_token_counts asserts in test_async_controller (#5100)

**TLDR:** RL CPU Unit Tests have been red on main since ed35bdaed. This
fixes the two broken asserts in `test_async_controller.py`.

**Problem**
1. ed35bdaed changed two asserts to
`torch.testing.assert_close(microbatch.loss_token_counts,
torch.tensor(N))`.
2. The file never imports `torch`, so both tests fail with `NameError:
name 'torch' is not defined`.
3. With the import added, they still fail: `torch.Size([1]) !=
torch.Size([])`.
4. `get_mtp_token_counts` returns one count per depth, so with no MTP
layers `loss_token_counts` has shape `(1,)`.

**Solution**
1. Add `import torch`.
2. Compare against `torch.tensor([8])` and `torch.tensor([3])`.

**Test plan**
```
pytest -q tests/rl/unit_tests/cpu/test_async_controller.py
before: test_batcher_uses_flat_rank_capacity_and_reports_padding, test_flat_rank_packing_preserves_padding_mask -> NameError
after:  32 passed
```
NOTE: I deselected `test_controller_config_maybe_log` locally because my
env has an older torchstore (no `RankRole`). It passes in CI.

Co-authored-by: Felipe Mello <[email protected]>

* [Data] Add tool call capability for ChatProcessor (#5098)

Add tool support for multiturn SFT chat data as mentioned by
https://github.com/pytorch/torchtitan/pull/2769#issuecomment-5654985510


## Summary

- Add an optional `tools_fn` to `ChatProcessor.Config`.
- Pass per-sample tool definitions to `renderer`-based chat processing.

## Test Plan

python -m unittest tests.unit_tests.cpu.test_chat_dataset
18 tests passed.

* Add HiMidLoLinear for the LM head and router gate; delete CastLinear and RouterGateLinear (#4923)

**Update after review 5** (rebased on main):
- Renamed `FP32OutputLinear` to `HiMidLoLinear`
(`torchtitan/models/common/hi_mid_lo_linear.py`), after the hi, mid and
lo pieces of its backward. `LMHeadFP32OutputConverter` keeps its name:
it exists for the fp32 logits.
- The split's custom op is gone. graph_trainer runs with local_compile
regions off, so it never traces the compiled split. The op also hid the
split from Inductor when it compiles the whole backward (graph_trainer's
full mode, an outer `torch.compile`), where dropping the
`.to(bf16).float()` round trip zeroes every piece after the first. The
split now upcasts its pieces with an integer shift, which leaves no
round trip to drop, so `emulate_precision_casts` is gone too. Run
uncompiled (graph_trainer's regional mode), the layer's backward is 5-7%
slower; graph_trainer's full mode gets faster (LM-head forward +
backward 20.5 -> 16.5 ms, H100).
- The region is `fp32_to_bf16_split`, and the split's argument is
`tensor`.
- `backward_mode: Literal["hi_mid", "hi_mid_lo"]`, default "hi_mid",
named after the pieces (the 2-piece split is hi + mid); the router gates
set "hi_mid_lo".
- RL loss reference, steps 3-10: the LM head's grad_weight is now fp32,
where `CastLinear` rounded it to bf16, and FSDP2 in recent torch
nightlies keeps it, so the rollouts diverge from step 3.
- Docstrings: why chunking the grad_input sum helps when the GEMM
already accumulates in fp32, and when our pieces equal cuBLAS BF16x9's
a0, a1, a2 bit for bit.

**Update after review 4**:
- `FP32OutputLinear` moved to
`torchtitan/models/common/fp32_output_linear.py`.
- `higher_precision_bwd` -> `backward_mode: Literal["bf16x2",
"bf16x3"]`, default "bf16x2"; the router gates set "bf16x3".
- The split rounds each piece with `.to(torch.bfloat16)`, ties to even:
cuBLAS BF16x9's a0, a1, a2 without their scales. It is compiled with
`emulate_precision_casts`, so it matches eager bit for bit, with the
same errors as before and faster than the integer bit ops it replaces.
- The split is the `fp32_output_split` local_compile region. The LM-head
converter and the models with FP32OutputLinear routers turn it on. It
uses `dynamic=True`, so at most 4 graphs.
- NOTE: the split timings in the docstrings and the tables below are
being regenerated on GB300.

**Update after review 3** (rebased on main):
- Every piece is rounded to nearest instead of truncated: LM-head
grad_weight error 1.6e-5 -> 8.4e-6, router grad_input 4.9e-6 -> 2.4e-6
(2 pieces, GB300).
- `exact_grad_output_split` -> `higher_precision_bwd`, default False;
the router gates set it to True.
- The backward has one function per layout, and the split runs as one
compiled kernel behind a custom op
(`torchtitan::split_into_bf16_pieces`).
- NOTE: CI compares golden losses exactly, so the MoE goldens need
regenerating from this PR's CI run.

TLDR: 

(Check the tables below)

- We want some layers to be computed in Fp32, e.g. lm_head and router
gate
- For the head, we use CastLinear, which sets weight.to(fp32) every
forward
- The weight is a huge matrix (248k vocab for Qwen3.5), so each forward
copies it to fp32 and runs a slow fp32 GEMM
- BF16x9 (the trainer's fp32 matmul emulation) is faster, but still slow
- TF32 is faster, but imprecise
- This PR instead does `torch.mm(out_dtype=float32)`, which does the
GEMM in bf16, but accumulates in fp32 (check the table).
- This is already what `RouterGateLinear` does
- However, in this PR we improved the backward by running only 2 out of
the 9 GEMMs: fwd/bwd go from 55.7 ms (`RouterGateLinear`'s BF16x9
backward) to 18.9 ms, or 18.0 ms compiled
- We deleted `CastLinear` and `RouterGateLinear`, and unified the code
under `HiMidLoLinear`
- The router splits grad_output into 3 bf16 pieces (exact), the LM head
into 2; see "2 vs 3 pieces" below

### Controlled results
1x GB300, the real Qwen3.5-27B lm_head weight (vocab 248320, hidden
5120) and hidden states from 2048 tokens of text. Tokens are sampled
from the model's fp64 distribution, like the generator samples them.
Logprob error is the mean |error| of the sampled token's logprob vs
fp64.

Inference, LM head alone, per call
```
                                          1 seq (us)  16 seq (us)   logprob |err|
upcast + IEEE GEMM (generator before)           1850         2720         8.9e-06
upcast + BF16x9 GEMM                            1850         2720         2.2e-06
upcast + TF32 GEMM                              1868         1815         1.9e-05
bf16 GEMM, fp32 out (this PR)                    362          368         1.0e-05
bf16 GEMM, bf16 out (bf16 head)                  360          364         1.7e-02
```

Training, one 2048-token chunk of `ChunkedLossWrapper` (forward + CE +
backward). Gradient errors are vs exact fp64 gradients; rounding those
to bf16 alone gives 1.66e-03 (`dh`) and 1.65e-03 (`dW`).
```
                                                       ms   logprob |err|     dh err     dW err
upcast + IEEE GEMM                                  229.5         8.9e-06   1.66e-03   1.65e-03
upcast + BF16x9 GEMM (trainer before)                77.5         2.2e-06   1.66e-03   1.65e-03
upcast + TF32 GEMM                                   20.3         1.9e-05   1.71e-03   1.66e-03
bf16 GEMM, fp32 out, BF16x9 bwd (router)             55.7         1.0e-05   1.66e-03   1.65e-03
bf16 GEMM, fp32 out, bf16 bwd (megatron)             12.0         1.0e-05   2.23e-03   2.13e-03
bf16 GEMM, fp32 out, hi+mid bwd (this PR)             18.9         1.0e-05   1.69e-03   1.65e-03
bf16 GEMM, fp32 out, hi+mid bwd, fp32 .grad           18.5         1.0e-05   1.69e-03   2.78e-05
bf16 GEMM, bf16 out (bf16 head)                      12.3         1.7e-02   1.14e-02   1.24e-02
(compile) bf16 GEMM, fp32 out, BF16x9 bwd (router)   53.4         1.0e-05   1.66e-03   1.65e-03
(compile) bf16 GEMM, fp32 out, bf16 bwd (megatron)   10.0         1.0e-05   2.23e-03   2.13e-03
(compile) bf16 GEMM, fp32 out, hi+mid bwd (this PR)   18.0         1.0e-05   1.69e-03   1.65e-03
```

### Validation
Qwen3-30B-A3B, 2 nodes x 4 GB300 (PP2 x DP4, EP4, HybridEP + CUDA
graphs, no AC), random init, c4, 1M tokens/step, 100 and 300 steps,
seeds 42 / 777 (each cell is `seed 42 / seed 777`). tps is the median
over steps 21-300.

**fp32 lm_head, old vs new**

| run | lm_head | gate bwd | MFU | tps/GPU | vs old | lm_head-stage mem
| loss@300 |
|---|---|---|---:|---:|---:|---:|---:|
| `main_head-fp32cast_gate-old` | fp32 (`CastLinear`) | old (BF16x9) |
15.3 / 15.2% | 13,686 / 13,606 | | 149.4 GiB | 6.145 / 6.228 |
| `pr_head-fp32_gate-new` | fp32 (`HiMidLoLinear`) | new (hi+mid) | 18.8
/ 18.6% | 16,822 / 16,684 | +22.9 / +22.6% | 148.7 GiB | 6.164 / 5.997 |

Seed 777
<img width="1413" height="306" alt="image"
src="https://github.com/user-attachments/assets/17f39a77-8e97-4d5e-8d17-e46c4112e5b4"
/>

Seed 42
<img width="1178" height="305" alt="image"
src="https://github.com/user-attachments/assets/d7890cba-d6ed-465d-9048-b9534d700d25"
/>

**Router gate backward, old vs new (bf16 lm_head)**

| run | lm_head | gate bwd | MFU | tps/GPU | vs old | lm_head-stage mem
| loss@300 |
|---|---|---|---:|---:|---:|---:|---:|
| `main_head-bf16_gate-old` | bf16 | old (BF16x9) | 19.4 / 19.4% |
17,410 / 17,409 | | 148.0 GiB | 6.128 / 6.119 |
| `pr_head-bf16_gate-new` | bf16 | new (hi+mid) | 19.6 / 19.5% | 17,516
/ 17,492 | +0.6 / +0.5% | 148.0 GiB | 6.180 / 6.019 |

Seed 777
<img width="1421" height="312" alt="image"
src="https://github.com/user-attachments/assets/4fe1e18d-8444-4d1a-b3af-f0d72107c516"
/>

Seed 42
<img width="1179" height="310" alt="image"
src="https://github.com/user-attachments/assets/f77a3b94-6fa6-4595-bce5-7d4b4f96674b"
/>

- tps moves at most 0.8% between seeds for the same run.
- Loss is worse on the 100 step run, maybe due to an unlucky peak? 300
step looks fine and better.

## How the backward trick works

More details in the docstring

### 2 vs 3 pieces of grad_output

`backward_mode` ("hi_mid_lo" for routers, "hi_mid" for the LM head)
splits the fp32 grad_output into 3 bf16 pieces (exact) instead of 2 (~16
bits):
- **Router** (grad_input sums over its experts): the split sets the
error, so a 3rd piece cuts it ~7x for a small op.
- **LM head** (sums over the vocab): tensor-core accumulation sets the
error, so a 3rd piece doesn't help and costs ~1.5x backward.
`LMHeadFP32OutputConverter` defaults it to "hi_mid" (configurable).

Relative error vs fp64, and backward time as a multiple of a bf16
Linear's (GB300; Qwen3-8B LM head on 2048 tokens; a 2048 -> 128 router,
errors on 16k tokens, times on 64k). Same table as the docstring:
```
                            relative error             backward time
                            grad_input  grad_weight    eager   compiled
LM head (bf16 backward: 2.8 ms)
  bf16 grad_output          1.5e-3      1.3e-3          1.0x    1.0x
  2 pieces (default)        2.1e-4      8.4e-6          2.4x    2.5x
  3 pieces                  2.1e-4      8.6e-6          3.6x    3.8x
  fp32 matmul (IEEE)        7.9e-5      2.3e-6         26.2x   27.4x
router (bf16 backward: 0.24 ms)
  bf16 grad_output          1.7e-3      1.2e-3          1.0x    1.0x
  2 pieces                  2.4e-6      2.9e-6          2.2x    1.6x
  3 pieces (routers)        3.5e-7      2.1e-6          2.8x    1.7x
  fp32 matmul (IEEE)        5.1e-8      2.9e-7          5.1x    4.5x
```
NOTE: the validation runs above predate review 3: 2 truncated pieces for
the head and the router, an eager split, and a bf16 `grad_weight`. In
the Controlled results, grad_weight is bf16 except in the fp32 `.grad`
row; the table above keeps it in fp32.

## Q&A

- **Why not keep the router's BF16x9 backward?** Same gradients (`dh`
1.66e-03 vs 1.69e-03, `dW` equal), but 2.9x slower eager (55.7 vs 18.9
ms per chunk) and 3.0x compiled (53.4 vs 18.0 ms).
- **Does the router get the same gradient error with this?** Yes.
Qwen3.5-35B-A3B router shape (2048 -> 256 experts, 40 layers, 64k
tokens, GB300), with 3 pieces: grad_input error 1.66e-03 for both,
100.0% of grad_input elements bitwise equal, GPU time 44.6 -> 15.8 ms.
grad_weight now stays fp32: 1.66e-03 -> 8.1e-06. So `RouterGateLinear`
is replaced, not just the LM head.

## Code changes

- `HiMidLoLinear(Linear)`, in `hi_mid_lo_linear.py`, replaces
`CastLinear` and `RouterGateLinear`. bf16 operands on CUDA take the
bf16-GEMM path (see the docstring). CPU and fp32 or mixed dtypes upcast
to fp32, as `RouterGateLinear` did; batch-invariant mode also upcasts
(see the last bullet).
- The backward has one function per layout (wide, e.g. an LM head;
narrow, e.g. a router). The grad_output split is the
`fp32_to_bf16_split` local_compile region; it upcasts its pieces with an
integer shift, so no compiler can drop its `.to(bf16).float()` round
trip. The router gates set `backward_mode="hi_mid_lo"` explicitly.
- `LMHeadFP32OutputConverter` (replacing `LMHeadCastConverter`) swaps
the `lm_head` config to `HiMidLoLinear.Config`. Quantization rejects the
class through its allowlist, as it did `CastLinear` and
`RouterGateLinear`.
- Every RL config with a plain `Linear` head now uses
`LMHeadFP32OutputConverter`; the GPT-OSS, Qwen3 MoE, Qwen3-30B-A3B and
search_r1 configs didn't before. Muse Glimmer's head is a
`SoftCappedLinear` and is unchanged.
- Removed `enable_fp32_matmul_emulation_with_bf16x9` (the global
`fp32_precision = "bfx9"`, added for `RouterGateLinear`). After this PR
it only affected fp32-weight training and DeepSeek V4's mHC fp32
`F.linear`, on Blackwell.
- `grad_weight` now comes back in fp32; `grad_input` is still rounded
once to bf16. FSDP2 keeps it in torch nightlies since 2026-10-02, so the
LM head (eager in `ChunkedLossWrapper`) gets an fp32 `dW`: 2.5e-06 error
vs fp64, against the 1.66e-03 bf16 floor (H100, 2 GPUs, toy shape).
Compiled code still rounds it to bf16 (an open PyTorch fix). On older
torch, autograd casts it back to bf16: same bits as before, +0.6 ms per
Qwen3-8B head chunk on GB300.
- Behavior changes for MoE: router gradients change slightly (3 bf16
pieces instead of BF16x9: closer to fp32, not bitwise), and in
batch-invariant mode the router now computes with fp32 inputs through
`batch_invariant_ops` (Triton runs them in TF32) instead of cuBLAS's
`out_dtype` GEMM, which is not batch-invariant.

---------

Co-authored-by: Felipe Mello <[email protected]>

* [RL] Run the vLLM engine on its own thread, fed by a thread-safe inbox (#5029)

**For reviewers**: *I carefully made the change incrementally through
the list of commits. So if you find the whole PR is too confusing to
review, I strongly suggest to go through the changes commit by commit.*

Right now everything in VLLMGenerator runs on one event loop, including
`_engine_loop()`, which does most of the work. We notice
`LLMEngine.step()` used in the loop could be a long blocking call (e.g.
~30ms). As a result, the Monarch actor can't take in requests while the
engine steps.

This PR moves the engine loop to its dedicate thread. The endpoints stay
on the actor's event loop, and reach the engine loop only through a
thread-safe inbox and the `concurrent.futures.Future` replies it
resolves. After the move, the actor can keeps taking calls while the
engine loop executes long blocking calls such as `LLMEngine.step()`.

The data flow looks the the following. For states crossing the thread
boundaries, it uses 2 mechanisms:

* endpoint -> engine loop: `EngineLoopInbox`
* engine loop -> endpoint: `concurrent.futures.Future`
 
  ```
actor thread (actor's event loop) | vllm-engine thread (its own event
loop)
                                            |
    generate / pull_model_state_dict        |
      reply = concurrent.futures.Future()   |
inbox.put(message) ----------------------> asyncio.Queue (owned by this
loop)
        with lock: raise if closed          |      |
        call_soon_threadsafe(put_nowait)    |      v
        returns at once, even mid-step      |   _decide_next_action
await wrap_future(reply) | idle: await get(); then drain
        ^                                   |     CloseRequest -> CLOSE
| | reply.set_running_or_notify_cancel()
| | False (cancelled on inbox): skip
| | True: register reply with dispatcher
        |                                   |      |
        |                                   |      v
| | LoopDecision ---- gloo ----> other ranks
        |                                   |      |
        |                                   |      v
| | engine.step() burst (blocks only this thread)
        |                                   |      |
+------ call_soon_threadsafe ------------ reply.set_result(completion)
                                            |
    close                                   |
inbox.close(CloseRequest()) -------------> queued behind earlier puts;
later puts raise
await wrap_future(engine_loop_future) <--- _engine_loop exits; its
finally releases
| the dispatcher, renderer and engine
  ```

  ## Performance

Stress test of the final commit on Monarch 0.6.0 and 8x H100: 2
generators x TP4, 512 requests per wave (256 per generator), one cold
wave then 5 warm waves per `max_tokens`, 2 runs per arm interleaved with
control. Mean time for a warm wave to finish:

  | max_tokens | control | this PR |
  | ---: | ---: | ---: |
  | 48 | 2.76 s | 1.46 s (-47%) |
  | 256 | 6.04 s | 5.27 s (-13%) |
  | 1024 | 21.98 s | 21.15 s (-4%) |

In a warm wave, each generator's rank 0 now starts all 256 of its
`generate` calls within 83-117 ms, against 2.26-2.55 s on control. That
saves 0.8-1.3 s per wave, so the gain is largest for short generations.

* [checkpoint] Parallelize Hugging Face checkpoint loading (#5087)

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

The reader otherwise loads each shard serially. Two workers overlap
reads while limiting storage and CPU pressure.

- Use two workers for unquantized readers by default.
- Allow callers to override the thread count.
- Preserve existing quantized reader defaults.
- Reuse the shared reader in model adapters and conversion tooling.
- Cover default and overridden thread counts.

Test Plan:

- pytest -q tests/unit_tests/cpu/test_state_dict_adapter.py -x
- pytest -q
test/distributed/checkpoint/test_hf_safetensor_e2e.py::TestSingleRankSaveLoad::test_load_with_multiple_threads
- Full formatting, lint, spelling, link, and Pyrefly checks pass.

* [LoRA] Target modules by FQN (#5095)

Addresses
https://github.com/pytorch/torchtitan/pull/4995#discussion_r4175611437

Also addresses
https://github.com/pytorch/torchtitan/pull/4995#discussion_r4181602839
since `handler` interface is gone.

## Summary

HuggingFace
[link](https://huggingface.co/docs/diffusers/en/training/lora) and
Megatron
[link](https://docs.nvidia.com/nemo/automodel/latest/recipes-e2e-examples/sft-peft)
target LoRA modules by FQN.

This PR lets the user only specify the FQN, and the transform handles
applying the correct LoRA for different kinds of modules, including
`Linear`, `GroupedLinear`, `DistMoeRoutedExperts`.

Only complication is the `DistMoeRoutedExperts` because the previous
implementation assumed both `w13` and `w2` are targeted, but this one
allows one to target only one of them.
- traverse the modules from bottom up (child -> parent)
- apply `GroupedLinear` or `Linear` LoRA for targeted modules
- when we reach `DistMoeRoutedExperts` and it has child `w13` or `w2`
that is already LoRA transformed, edit `_weight_operands` to return the
LoRA weight summed matrix.

* Add TITAN_LOG_LEVEL var for the logger. (#5089)

Currently, all logs at the `DEBUG` level are silently dropped, with no
way to access them.

This PR introduces the `TITAN_LOG_LEVEL` environment variable to control
the logging level. It defaults to `INFO`; setting it to `DEBUG` enables
access to debug logs.

* [compile] Gated activations: unbind gate/up inside the compiled region (#5086)

**TLDR:** SwiGLU, SiTUGLU and GPT-OSS SwiGLU now take `w13`'s fused
`gate_up` tensor and unbind it inside their compiled region, and the
`FusedSwiGLU` kernel takes it too. This removes an eager copy from their
backward: Qwen3.5-4B FFN fwd+bwd 10.99 -> 10…
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/rl ciflow/8gpu CLA Signed This label is managed by the Meta Open Source bot.

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

8 participants