Skip to content

feat(ezpz): sync current TorchTitan and validate Aurora XPU RL - #21

Merged
saforem2 merged 185 commits into
ezpzfrom
sync/upstream-0fd69d0b
Sep 25, 2026
Merged

saforem2 merged 185 commits into
ezpzfrom
sync/upstream-0fd69d0b

Conversation

@saforem2

Copy link
Copy Markdown
Owner

Summary

This integrates the ezpz branch with TorchTitan upstream through 0fd69d0b and ports the Aurora/XPU paths to the resulting current stack.

The branch also adds and validates:

  • the aurora_full_sonic MoE backend on current TorchTitan;
  • native-DDP, checkpoint, model/config, sharding, and RL API migrations required by the upstream integration;
  • both MLA and GQA sharding paths;
  • Torch 2.14 XPU + Triton-XPU + vLLM + Monarch GRPO integration;
  • AGPT checkpoint serialization/token metadata repair;
  • direct AGPT, Qwen, and broad MDS controls;
  • exact environment and reproduction artifacts;
  • an independent two-node rollout control for the broad AGPT-2B MDS stage3-mix/global_step154391 conversion.

Validation

  • Core integration: 98 passed, 2 legitimate platform/dependency skips, plus 9 subtests.
  • aurora_full_sonic: trains successfully on current TorchTitan with activation_checkpoint_mode="none".
  • Protected environment: Python 3.12.12, PyTorch 2.14.0+xpu, Triton-XPU 3.8.0, vLLM XPU, torchmonarch 0.6.0.
  • Qwen direct control: coherent generation.
  • Qwen TorchTitan/TorchStore/vLLM synchronized control: rollout, backward, optimizer, save, and shutdown succeeded.
  • AGPT checkpoint-900 direct control: malformed behavior reproduces before TorchTitan or TorchStore; this rules out synchronization as its root cause.
  • Broad MDS global_step154391 direct control: coherent pretrained continuations.
  • Broad MDS two-node control (12478450): both independent vLLM/XPU workers loaded the exact SHA-256-verified model and produced coherent outputs; factual token sequences matched across nodes.

AGPT conclusion

The old AGPT checkpoint lineage had real BOS/EOS/EOT and historical-template mismatches. Repair improves stopping but does not restore semantic quality. The malformed behavior is already present in direct HF inference, so it predates TorchTitan, Monarch, TorchStore, and distributed weight synchronization.

The broad MDS stage-3 base is coherent but is a pretrained completion model rather than an instruction-tuned policy. Controlled full-weight SFT and semantic gating remain follow-up work and are not claimed as completed by this PR.

Review guide

Start with the focused diagnosis and reproduction report:

https://github.com/saforem2/torchtitan/blob/sync/upstream-0fd69d0b/torchtitan/experiments/ezpz/docs/production/rl/grpo/torch214-reproduction.md

The report links the repair code, exact package/source revisions, checkpoint provenance and hashes, launch commands, raw generations, and complete two-node rollouts.

Known limitations

  • The MDS two-node test validates independent per-node rollout execution, not cross-node tensor parallelism.
  • No semantic quality claim is made from reward or throughput alone.
  • A new stage-3-derived SFT candidate has not yet passed the direct alphabet-sort gate.
  • Two SFT submissions failed before training due to launcher/bootstrap issues (missing mpi4py, then PMIx initialization); neither produced or validated a candidate checkpoint.

tianyu-l and others added 30 commits September 17, 2026 15:26
## Human's note:

This is pure refactor, and there is **NO NUMERICS CHANGE**. I personally
think it's enough for reviewer to read the note I wrote below, and check
the code changes that sounds interesting / problematic to you.

**Core changes**

1.
extracted `TrainingEngine` into `torchtitan/training_engine.py`, shared
by core eager trainer and RL trainer. See API below.
- supervised trainer specific: tokenizer, dataloader,
`create_seed_checkpoint`, metrics
- for metrics, they were done differently due to historical reasons. Now
they share a common function `compute_training_performance_metrics()`. I
think the two trainer may be unified regarding metrics, but I'll leave
it out to future work (cc @felipemello1)
  - RL trainer specific
- weight sync / torchstore `push_state_dict`, receiving whole batch of
data instead of building on the fly
- the following are shared with generator, thus owned by RL controller,
including `compile_config`, `dump_folder`, `model_spec`,
`hf_assets_path`
- FLUX trainer still inherits core Trainer, and is greatly simplified,
by moving image encoder processing into recently introduced
`model.preprocess_inputs`
- GraphTrainer now has its own `GraphTrainingEngine(TrainingEngine)`,
which has compatible interface to potentially be used as an RL trainer
backend, but it is not tested (cc @SherlockNoMad @aditvenk)
- `FaultTolerantTrainingEngine` inherits `TrainingEngine`, but
`FaultTolerantTrainer` does not inherit core `Trainer` because it anyway
has to rewrite most things.

2.
`torchtitan/experiments/rl/` is graduated to `torchtitan/rl/`
- added @felipemello1 @wwwjn @pzhan9 @tianyu-l as codeowners (can be
revisited later)
- reorganized files under the torchtitan/rl/ folder. Put a section in
torchtitan/rl/README.md to explain the new file layout.
- Regarding RL trainer and generator, I put non-monarch-actor "real"
definitions under `torchtitan/rl/`, and put thin monarch actor
inheritance under `torchtitan/rl/distributed/actors/`. The idea is that
**trainer and generator could be adopted by others independently without
monarch**. (cc @pzhan9)
- RL `RolloutWorkerActor` keeps composition with `RolloutWorker`,
instead of inheritance, because users might inherit `RolloutWorker` and
change its behavior.
- `InterGeneratorRouter` is still a monarch actor only class, because
it's not just an endpoint. It uses monarch APIs to call other actors.
- linter is still excluded because the unsettled dependency story --
would like to worry later


**`TrainingEngine` public APIs**
```
class TrainingEngine(
    Configurable,
    torch.distributed.checkpoint.stateful.Stateful,
):
    def __init__(
        config,
        *,
        model_config,
        max_num_documents,
        output_dir,
    ) -> None

    def initialize(
        model_spec,
        *,
        compile_config,
        sd_adapter,
        dataloader=None,
        create_seed_checkpoint=False,
    ) -> None

    def prepare_step(
        global_valid_tokens,
        *,
        num_accumulation_steps=1,
    ) -> torch.Tensor

    def forward_backward_microbatch(
        *,
        microbatch_group,
        global_valid_tokens,
        accumulation_index=0,
    ) -> torch.Tensor

    def optimizer_step() -> torch.Tensor

    def load_checkpoint() -> bool
    def save_checkpoint(*, last_step=False) -> bool

    def start_profiler() -> None
    def step_profiler() -> None
    def close_profiler() -> None

    def state_dict() -> dict[str, Any]
    def load_state_dict(state_dict) -> None

    def close() -> None
```

**Other changes**

**supervised training**
- renamed `batch` to `microbatch`, whenever appropriate.
- for each spmd gradient accumulation step, PP has multiple microbatches
-- it is now consistently named as a `microbatch_group` to be
non-ambiguous
- removed "batch" mesh, because it's a duplicate to "dp" mesh
- rename lowercase `cudagraph` to `cuda_graph`, whenever appropriate.
- `wrap_with_cuda_graph` no longer assumes each optimizer step has fixed
number of microbatches, because RL training doesn't satisfy this
condition
- changing from `Checkpointer.Config` having `enable` field to
`checkpointer: Checkpointer.Config | None` style

**RL**
- RL trainer is renamed from `PolicyTrainer` to `Trainer`, under
torchtitan/rl/trainer.py
- RL trainer now should share core capability like cudagraph,
sdc_replay, garbage collection, profiling, HSDP optimization, etc. And
hard to miss one in the future.
- RL trainer cudagraph not enabled / tested yet; PP is not enabled due
to torchstore issue (cc @wwwjn)
- Per RL example trivial rollouters are removed; as a replacement, a
`config_registry` file now hosts a simple shared rollouter config such
as `_alphabet_sort_rollouter_config()` and
`_dapo_math_rollouter_config()`, so all configs don't have to redefine
them.
- RL losses now require `global_valid_tokens` to be device tensor to be
cudagraphable
- RL now does not accept DP > 1 unless EP is used, in which it is
required EP == DP * TP. Otherwise, it is recommended to use
`num_generators > 1`



-------------------------------------------------------

### Summary by agent:

Core and RL trainers had independently accumulated the same distributed
model lifecycle and per-microbatch execution logic. That duplication
made features such as CUDA graphs, SDC replay, profiling, GC,
checkpointing, and HSDP accumulation easy to support in one workflow but
miss in the other.

This introduces a configurable `TrainingEngine` composed by
workflow-specific trainers, moves shared model initialization and
forward/backward behavior into it, and makes Flux use the same execution
path. It also graduates TitanRL to `torchtitan.rl`, gives standalone
trainer/generator services thin Monarch actor adapters, clarifies
microbatch contracts, and keeps RL CI optional while triggering it for
shared files that can affect RL.

Existing RL recipes retain eager trainer execution and dynamic varlen
metadata to preserve their established numerics; CUDA graphs are
available as an explicit shared-config opt-in.

Numerics: deterministic H100 Flux runs were bitwise identical before and
after for all recorded losses and grad norms. Deterministic H100 RL
comparisons against `origin/main` were also bitwise identical for
trainer TP=2 and TP=4, including generator TP=1, TP=2, and TP=4
coverage.

Validation: `pre-commit run --all-files`; `pytest tests/unit_tests/cpu
-x` (1107 passed, 2 skipped); `pytest tests/rl -x` (415 passed, 23
skipped).

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

Supersedes pytorch#4649, which was accidentally merged into its ghstack base
branch instead of `main`.
Replace CUDA-specific device checks and placement in
`test_compile_moe.py` UT with TorchTitan's `device_module` and
`device_type` helpers.

This allows the grouped-MM compile test to run on the selected
accelerator backend, including XPU, while preserving its skip behavior
when no accelerator is available.
get_cuda_flash_attention_impl() gates on has_cuda_capability(), which is
torch.cuda.get_device_capability() >= (major, minor) with no vendor
check. AMD devices report a capability through that same API, and gfx950
(MI350X) reports (9, 5) -- so the (9, 0) test passes and FA3 is selected
on hardware that has no FA3 to select. torch's flash_attn_interface is
CUDA-only, so activate_flash_attention_impl("FA3") then fails.

Return None on a ROCm build, which is what the rest of the function
already does for architectures with no supported implementation, leaving
torch's default attention path in place.

Reproduced on 8x MI350X (gfx950) with the llama3 varlen attention
backend.
MI350X is missing from the peak-FLOPS table, so on that part
get_peak_flops() falls through to the 312 TFLOP/s A100 default and every
reported MFU comes out ~7.4x too high. The table already carries its
liquid-cooled sibling MI355X (2.5 PFLOP/s) as well as MI300X/MI325X.

MI350X is the air-cooled CDNA 4 part: 2.3 PFLOP/s dense BF16.
https://www.amd.com/en/products/accelerators/instinct/mi350/mi350x.html

Measured on an 8x MI350X node running torchtitan llama3:

before: MFU ~152% for 8B -- wrong in a way that is only obvious if you
           happen to notice MFU exceeding 100%
  after:   MFU 20.5% (8B), 24.6% (70B)
Update the eager chunking contracts after padding-mask propagation added
mask keywords to TransformerBlock and MoE forwards. Split each mask
alongside its activation so both eager chunks preserve token alignment,
while continuing to reject unsupported arguments. Add regression
coverage for MoE and TransformerBlock mask chunking.
`apply_fsdp_to_decoder` picks `Shard(0)`/`Shard(1)` for routed experts
by comparing an FSDP
shard degree against `num_experts`, but the two branches compute
different things:

```python
if ep_degree > 1:
    efsdp_ep_size = edp_mesh["efsdp"].size() * ep_degree   # dp_shard * cp * tp
else:
    efsdp_ep_size = fsdp_config["mesh"].size()             # dp_replicate * dp_shard * cp * tp
```

by definition, `efsdp_ep_size` should be "FSDP" size, but since lots of
refactor and at some point ` fsdp_config["mesh"]` included the `DP`
dimension so now `efsdp_ep_size` include DP.

a broken example is 
dp_replicate=2, dp_shard=4, num_experts=4: current gives 8 > 4 →
Shard(1). which should be Shard(0) as its HSDP..
## Summary

### Agent notes

- Capture GDN prefill, mixed batches, and specialized decode using
**vLLM's native FULL CUDA graphs**.
- Stage offsets, cache slots, and initialization masks in persistent
buffers. Preserve decode numerics and correctly initialize fresh
requests on reused slots.
- Add a narrow dispatcher adapter to distinguish packed and decode graph
keys; vLLM retains ownership of capture/replay. Requires
`attn-gym[linear]==0.0.10`.

## Performance

**Actual pre-PR `a3a819c67` (FULL_AND_PIECEWISE) → `1018b0b9c` (FULL):**
Qwen3.5-0.8B AlphabetSort RL, one trainer + one generator GB200,
TP1/DP1, BF16 compute, compile off. Trainer FA2 / generator FA4 b31;
**policy lag 3 and vLLM async ON in both**.

| Unprofiled end-to-end metric | Before | After |
|---|---:|---:|
| Seconds/update interval ↓ | 15.700 | 1.318 |
| Generated tokens/second ↑ | 62.35 | 741.77 |

One sequential pair, two warmup updates + ten measured update intervals;
initialization/capture excluded. Measured between completed weight
pulls, including native generation/control/handoff waits. Each returned
376 completions (9,788 / 9,779 tokens). **Observed latency reduction:
91.6%**, workload-specific—not an isolated kernel speedup or convergence
claim.

**Perfetto:** [generator
before/after](https://fburl.com/perfetto/izryvwep) · [trainer + rollout
+ handoffs](https://fburl.com/perfetto/1sf1yh3j). Separate profiled
runs; do not infer speedup from trace duration. Links are internal with
28-day upload retention.

**Earlier inference-only prefill:** batch 32 × 4096 input tokens, output
1, one GB200, async off: median **1.869 → 0.809 s (2.31×)** over ten
runs. [Before/after trace](https://fburl.com/perfetto/qhb6334q).
Historical `c48650f06` → `1ac48cbbf`, not a current-head rerun.

## Correctness / limits

- **Seven regressions passed.** Eager/FULL matched exactly within each
regular and batch-invariant mode: 96 tokens, 480 logprob entries/ranks,
cumulative logprobs, and 1,584 conv/SSM state hashes; 43 actual FULL
replays per mode. Includes independent NaN-poisoned fresh-slot reuse
checks.
- Real RL runs passed finite-gradient/reward checks, policy-age bounds,
versioned weight delivery, and warmup sampled weight equality.
- Validation used Gym commit `4ac49088a`, **not a rerun against the
pinned 0.0.10 wheel**. Broader topologies remain unvalidated; no TP4
claim.
…h#4790)

## Summary

CUDA graph capture cannot run on ROCm — `wrap_with_cuda_graph()` logs a
warning
and returns the eager callable. But the validators that enforce
CUDA-graph
restrictions never checked the device, so they raised `ValueError` on
ROCm for
configurations that would run fine there. `training.disable_cuda_graphs`
defaults to `False`, so ROCm users hit this by default.

This exports the capability check as `cuda_graphs_supported()` and has
`wrap_with_cuda_graph()` and every validator share it, so the sites
cannot
drift apart.

Gated sites:

| File | Restriction |
| --- | --- |
| `config/validation.py` | varlen attention with `max_num_documents`
unset |
| `config/validation.py` | expert parallelism with a synchronizing token
dispatcher |
| `trainer.py` | pipeline parallelism with a validator |
| `training_engine.py` | looped pipeline schedules |
| `training_engine.py` | SDC replay with `num_replays > 1` |

**No behaviour change on NVIDIA.** `cuda_graphs_supported()` is `True`
on CUDA,
so every existing error path fires exactly as before.

This does *not* touch the ROCm exclusion itself. hipGraph exists and the
blanket
`torch.version.hip is None` may be worth revisiting, but that is a
separate
question — see the issue.

## Tests

The existing CUDA-graph rejection tests in `test_config_manager.py`
asserted
raises that are now device-dependent, and would silently stop asserting
anything
on a CPU-only runner. They now pin the predicate to `True` and keep
asserting
the raises; new tests cover the inert case and the previously untested
varlen
path.

Verified on 8x MI350X (gfx950, torch 2.15.0.dev+rocm7.2):

- Before: varlen without `max_num_documents`, EP=2 with
`LocalTokenDispatcher`,
and PP=2 with a looped schedule each raised `ValueError` at config time.
- After: all three are accepted, and `llama3_debugmodel_varlen_attn`
with
`max_num_documents=None` trains (3 steps, loss 8.18 -> 7.20) with the
expected
  "using eager execution" warning.
- `tests/unit_tests/cpu/`: same 4 pre-existing failures before and after
  (missing `torchvision`/`vllm` locally), +7 new passing tests.

Fixes pytorch#4789
`TestMicrobatchWiseLossSpmdTypes` in
`tests/unit_tests/cpu/test_aux_loss.py` is CPU-only by construction:
`_build_dims` patches
`torchtitan.distributed.parallel_dims.device_type` to "cpu", the dense
and sparse meshes are built on CPU, and the router scores/routing maps
are CPU float64 tensors.

It does not, however, pin the `device_type` it inherits from
`DTensorTestMixin`. That property returns the accelerator type whenever
an accelerator is visible and DEVICE_COUNT >= world_size, and
`DTensorTestBase.backend` derives the process group backend from it via
`dist.get_default_backend_for_device(self.device_type)`. So on a host
with at least 8 accelerator devices the process group is initialized
with the accelerator backend only (xccl on XPU, nccl on CUDA), while the
collectives the test actually issues run on CPU tensors. The all_reduce
that MicrobatchWiseLoadBalanceLoss._reduce_token_partials performs
through spmd.redistribute then fails:

    RuntimeError: No backend type associated with device type cpu

On CPU-only CI hosts torch.accelerator.device_count() is 0, so
device_type already resolves to "cpu" and gloo is selected, which is why
this passes upstream today.

Override device_type to return "cpu" so gloo is selected regardless of
which accelerators happen to be visible. This is the convention the
other CPU SPMD test cases in the same directory already follow:
TestRouterGateLinearSPMD in
tests/unit_tests/cpu/test_router_gate_linear.py and
TestChunkedLossWrapperSPMD in tests/unit_tests/cpu/test_loss.py both pin
device_type this way. Behavior on CPU-only hosts is unchanged; the
change only affects which backend is chosen on accelerator hosts.

Co-authored-by: Claude Opus 5 <[email protected]>
…tokens (pytorch#4301)

With the default validation dataloader (concat-then-split packing,
validate.py Config), a per-rank validation split holding fewer than
num_tokens_per_batch tokens yields zero packed rows, because
`_packing_output_is_full` drops partially filled rows. The validate loop
then breaks on the first StopIteration with `accumulated_loss` still
None, and the bare `assert accumulated_loss is not None` kills the whole
training run with a message-less AssertionError at the first validation
step. Without the assert, `global_loss_sum / num_global_valid_tokens`
raises ZeroDivisionError instead.

This PR replaces the assert with a ValueError naming the cause
(validation dataset supplied fewer than num_tokens_per_batch tokens on
this rank; concat-then-split packing drops partial batches) and the
remedy (decrease training.num_tokens_per_microbatch_per_dp_rank or use a
larger validation set), and guards the zero-valid-token division the
same way. Same fail-fast-with-a-clear-message class as the merged pytorch#4287
and pytorch#4291.

No numerical path changes: this is validation-layer error handling only,
the loss computation is untouched, so no numerics proof applies. No new
CLI flags.

Tests: two unit tests in tests/unit_tests/test_validate.py construct
both zero-batch and zero-valid-token conditions using the file's
existing validator harness. On main they fail with the bare
AssertionError and ZeroDivisionError; with this change they assert the
ValueError messages. pre-commit passes on both touched files.
`Llama3StateDictAdapter._permute` / `_reverse_permute` do a
head-splitting `view()` on the q/k projection weights during HF
checkpoint conversion. In the live save/load path those weights are
DTensors that FSDP shards along dim 0, the exact dim the view
unflattens, so an FSDP degree that does not evenly divide the head count
raises `Cannot unflatten unevenly sharded tensor`. For llama3-8B
(`n_kv_heads=8`) this breaks HF export above an 8-way FSDP degree, i.e.
any typical multi-node run.

## Fix

`muse_glimmer`'s adapter hit the identical failure and fixed it locally
with a `_dtensor_safe` decorator (redistribute to `Replicate`, run the
reshape on the full local tensor, redistribute back). This hoists that
decorator into the shared `torchtitan/protocols/state_dict_adapter.py`
as `dtensor_safe`, applies it to llama3's two permute helpers, and
points `muse_glimmer` at the shared implementation instead of its own
copy.

Net diff is +41/-39: llama3 gains two decorators, muse_glimmer loses its
30-line duplicate.

## Testing

Two new CPU unit tests in `test_state_dict_adapter.py`:
- `test_permute_does_not_raise_when_fsdp_degree_exceeds_head_count`
reproduces the production failure with a fake process group (32-way
mesh, 16 heads) and asserts `to_hf` no longer raises.
- `test_permute_roundtrip_preserves_dtensor_values_and_placement` uses a
real gloo process group to confirm the decorator does not alter values
or placement in the common (evenly-sharded) case.

Both fail on `main` — the first with the exact production `RuntimeError`
— and pass with this change. Full `test_state_dict_adapter.py` file
passes (7 tests). `pre-commit` (flake8, ufmt, pydoclint, codespell,
license headers) is clean on the changed files.

This is a checkpoint-conversion bug fix, not a training-numerics change,
so no loss/grad_norm comparison applies.
## Summary

- Remove pure tensor parallelism for routed experts and require MoE
expert parallelism to be at least the dense tensor-parallel degree.
- Keep routed-expert token activations sequence-sharded under EP,
avoiding duplicated routed-expert computation.
- Keep shared experts and other dense layers tensor-parallel; the
shared-expert path gathers its input and reduce-scatters its output to
the routed-expert layout.
- Update token-count reductions, affected model layouts, and
documentation, and remove GPT-OSS bias scaling that was specific to
expert TP.

## Numerics

Compared `main` (`ab670811b`) against this PR (`b83c9b925`) with the
DeepSeek-V3 debug model for 10 steps. Each configuration used a newly
generated shared seed checkpoint, `--debug.seed=42`, deterministic mode,
and CUDA graphs disabled on both sides.

| Configuration | Average loss (main -> PR) | Final loss (main -> PR) |
Max abs loss diff | Max abs grad-norm diff |
| --- | --- | --- | --- | --- |
| EP=2, dense TP=2 | 4.868575 -> 4.868575 | 3.807293 -> 3.807293 | 0 | 0
|
| EP=2, dense TP=1 | 4.868060 -> 4.868060 | 3.881874 -> 3.881874 | 0 | 0
|

Loss and grad norm are bitwise identical across all 10 steps for both
supported configurations. `EP=1, dense TP=2` is no longer tested because
MoE configurations now require `EP >= TP`.
Relands pytorch#4676 against `main`. pytorch#4676 was accidentally merged into its
ghstack base branch and never landed on `main`. This PR contains the
same reviewed change, rebased onto current `main`.

Followup from pytorch#4535.

W13 currently stores W1 and W3 as interleaved rows in a [2F, D] tensor,
logically [F, 2, D]. This works well for TP, but block-quantization
tiles can span both projections and force them to share scales.

Generalize Linear with num_linears and store W13 as [2, F, D], keeping
each projection contiguous. The GEMM still uses a flattened [2F, D]
view.

State dicts
-----------

Keep native DCP checkpoints and RL weight synchronization in the
physical w13 layout. Split w13 into gate/up projections, and merge them
on load, only at the Hugging Face adapter boundary. This avoids
materializing FFN-sized hook outputs on every state_dict() call.

Quantization
------------

Teach the Float8, MXFP8, and NVFP4 Linear implementations to preserve
the stacked layout. Generalize quantized FSDP gathering to support
weights sharded on dimension 1.

Tensor parallelism
------------------

Shard dimension 1 so every TP rank receives matching feature slices of
W1 and W3.

LoRA
----

Use a shared A weight [r, D] and a stacked B weight [2, F, r]. Carry the
stacked layout through rematerialization, dist-GEMM, fused SwiGLU, and
vLLM state-dict handling.
…ch#4806)

## Summary

`apply_compile` walks `model.layers` and compiles each TransformerBlock.
Muse Glimmer's vision adapter is a two-layer GELU MLP (`c_fc` /
`c_proj`) with no `layers` attribute, so `parallelize_muse_glimmer(...,
compile.components=["model"])` raises `AttributeError` on multimodal
flavors.

Qwen3.5, which this file mirrors, already compiles only the decoder and
vision encoder. The AC path next to this code already skips the adapter
for the same reason. Stop compiling the adapter; FSDP wrapping of
encoder and adapter is unchanged.

Also extend the `skip_dp` AST allowlist to Qwen3.5, gpt-oss, and Muse
Glimmer. Those entry points already accept `skip_dp` for vLLM; the test
list did not. Flux is left out (no `skip_dp`, not a vLLM generator
path).

## Test plan

- [ ] `pytest tests/unit_tests/cpu/test_muse_glimmer_compile.py
tests/unit_tests/cpu/test_skip_dp.py` (9 passed locally)
- [ ] Lint
…orch#4805)

## Summary

Fix four stale paths left after the RL promotion and TrainingEngine
split (pytorch#4773), plus one leftover llama3 adapter path.

- `torchtitan/rl/docs/bitwise_parity.md`: `batch_invariance.py` now
lives under `rl/model/`.
- `torchtitan/rl/README.md`: `TrainingEngine` lives in
`torchtitan.training_engine`, not `torchtitan.trainer`.
- `docs/checkpoint.md`: shared checkpoint fields are on
`BaseCheckpointManager.Config` in `checkpointer/base.py`. `dcp.py` only
adds `async_mode`.
- `torchtitan/models/qwen3/state_dict_adapter.py`: llama3's adapter is
`models/llama3/state_dict_adapter.py` (no `model/` subdirectory).

Docs only. No behavior change.

## Test plan

- [ ] Confirmed each replacement path exists on this branch
- [ ] Lint / docs checks
When a step is passed explicitly, W&B buffers the metrics instead of
committing the row. Charts can therefore lag or remain empty.

This commits each metrics row when it is logged.
…pytorch#4811)

w13 didn't get any fqn match after splitting w123 into w13 and w2. this
PR fixes it:
  * pytorch#4535
  * https://github.com/pytorch/torchtitan/pull/4676/changes#r4058499709
* same problem first raised in
pytorch#4531 by @WhoisZihan

the next follow up is adding validation prevent future cases like above
in optimizer init: pytorch#4816


Co-authored-by: Zihan Yang <[email protected]>

Co-authored-by: Zihan Yang <[email protected]>
## Summary

Fix TorchFT dataloader checkpoint loading to stay aligned with the
selected
main training checkpoint.

## Root Cause

`TorchFTCheckpointManager.load()` independently selected the latest
checkpoint
from the per-replica dataloader checkpoint directory before the base
checkpoint
manager resolved the main checkpoint step.

For example, if the main checkpoint directory contained `step-500` while
the
TorchFT dataloader directory already contained `step-501`, recovery
loaded
model state from `step-500` but dataloader state from `step-501`. This
could skip
data and break exact recovery.

## Changes

- Expose the base checkpoint manager's resolved training step for
subclasses.
- Restrict TorchFT dataloader checkpoint discovery to steps no later
than the
  selected main checkpoint.
- Preserve the existing checkpoint loading order: FT dataloader state is
loaded
  before the main checkpoint state.
- Add a regression test covering automatic recovery when a newer FT
dataloader
  checkpoint exists than the selected main checkpoint.

## Testing

- `python -m pytest
torchtitan/experiments/torchft/tests/test_torchft_checkpoint.py -q`
  (7 passed)
- `flake8` on changed files
- `pre-commit run ufmt`
- `pre-commit run pydoclint`
- `pre-commit run codespell`
- `python -m compileall ...`
- `git diff --check`

---------

Co-authored-by: Serendipity-matong <[email protected]>
## Summary

Rename `PyTorchVarlenInnerAttentionBackend` to
`TorchTitanVarlenInnerAttentionBackend`, following the naming feedback
on pytorch#4738. This is a class-name-only change; vLLM's `CUSTOM` registration
and implementation remain unchanged.

## Validation

- Verified `AttentionBackendEnum.CUSTOM.get_class()` resolves to the
renamed class and its registry name remains `CUSTOM`.
- Scoped pre-commit passed; the global mutating Pyrefly hook was
skipped.
)

## Human's note

- remove `ModelSpec` and refactor fields into `Model` or `Model.Config`
- remove per-model parallelize.py (including GraphTrainer), and instead
use `Model` / `Decoder` / `MultimodalModel` / `FluxModel` to hold the
logic, shared with model subclasses
  - introduced `Model._apply_fsdp()` for the above reason
- remove `train_context` as it only calls into `get_spmd_context`
- make `Module.parallelize()` -> `Module._parallelize()` as it's not
supposed to be overridden


## Summary

- remove `ModelSpec` and make each model class own its config,
checkpoint adapter, optimizer hooks, and high-level parallelization
behavior
- consolidate common decoder and multimodal parallelization in
`BaseModel`, `Decoder`, and `MultimodalModel`, while keeping
`Module._parallelize()` as the low-level primitive
- consolidate the regular GraphTrainer model lifecycle and remove its
four per-model `parallelize.py` files
- centralize SPMD context setup and make vocab-parallel log-prob
computation take its TP process group explicitly
- define `max_context_length` on decoder configs and set it in concrete
model presets

## Why

`ModelSpec` duplicated model identity outside the model class and
allowed invalid combinations such as one model with another model
checkpoint adapter or optimizer hooks. Per-model parallelization files
also repeated behavior that belongs to shared model families. This
change makes those relationships structural: selecting a model class
determines its configuration and associated behavior, while model
subclasses retain focused override points.

Backward compatibility is intentionally not preserved for the removed
`ModelSpec` APIs.

## Testing

- `pre-commit run --all-files`
- `pytest tests/unit_tests/cpu -x -q` (1169 passed, 2 skipped)
- affected CPU tests (64 passed)
- focused RL tests (28 passed)
- affected GPU model tests (28 passed, 1 skipped)
- distributed FSDP/sharding tests (9 passed)
- GraphTrainer distributed regression tests (3 passed)
- GraphTrainer test collection (499 tests)
- Flux fake-PG FSDP+compile integration (passed)

The branch is rebased onto current `main`. This is a regular PR so the
full upstream CI suite will run.
## Summary

Restore the declared model sharding after Hugging Face format
conversion, before extracting plain local tensors.

Qwen3.5's QKV fuse/split operations can change DTensor placements: a TP2
projection expected as `Shard(0)` became `Shard(1)`, producing local
`[2048, 512]` instead of `[1024, 1024]`. Convolution and vision weights
were affected too. The RL checkpoint adapter now redistributes to each
parameter's existing layout before `to_local()`; it does not reshape
incorrect shards or change CUDA-graph behavior.

Adds a two-rank CPU/Gloo regression with independent expected local
slices and runs it in RL CI. Naming-only follow-up pytorch#4786 is the lower
stack layer.

## Validation

- New regression reproduces the original failure on both ranks and
passes with the fix.
- Six focused wrapper/GDN metadata tests passed on this stack; scoped
pre-commit passed. Scoped Pyrefly retains five verified preexisting
errors in unchanged all-reduce code; no new errors.
- Before stacking, the same adapter fix passed regular Qwen3.5-0.8B TP2
eager/FULL inference on two GB200s: exact rank-local weights, 96
tokens/logprobs, 44 state records, and 43 native FULL replays per rank.
- **GPU-run caveat:** both runs completed inference artifacts but hit
the 60-second deadline during shutdown. Clean shutdown and
batch-invariant TP2 remain unvalidated. Runtime used Torch/vLLM Sep13
nightlies, FA4 b31, and Gym commit `4ac49088a`, not a clean release-pin
install.

```sh
.venv/bin/python -m pytest -v -ra tests/unit_tests/rl/test_vllm_wrapper.py tests/unit_tests/rl/test_gdn_graph_metadata.py
```
@saforem2

Copy link
Copy Markdown
Owner Author

Final exact-head validation for 25a49515b4d9b44282bb1c1ff717d79873ead283:

  • Aurora job 8868500: Exit_status=0; PR21_AURORA_NEXT_EVAL_VALID; AGPT TP=1, AGPT TP=2, and MoE each completed 5 optimizer steps and wrote step-5 DCP metadata. Runtime: torch 2.15.0.dev20260919+xpu using the versioned next-eval archive with oneAPI 2026.1 runtime layering.
  • Polaris job 7659365: Exit_status=0; three-arm CUDA matrix VERDICT: ok. AGPT TP=1 completed 3 steps, AGPT TP=2 completed 1 step (bounded by the tiny retained corpus), and MoE completed 3 steps. MoE losses exactly match the retained pre-sync Polaris smoke: 12.98146 -> 12.62001 -> 11.63856.
  • Sunspot job 12478673: Exit_status=0; two-step Sonic replay with NUMERIC_VERDICT=PASS. Step 1 loss/grad deltas 0 / 0.0001; step 2 deltas 0.00011 / 0.0026, within limits 0.005 / 0.05.
  • Perlmutter job 58866972: COMPLETED 0:0; three CUDA optimizer steps and PR21_PERLMUTTER_VALID.
  • Focused local MoE/config suite: 124 passed.
  • CI lint: passed.

The Polaris run initially exposed routed-expert parameters remaining plain tensors under full-SPMD FSDP when EP=1. Commit 25a49515b adds the scoped replicated-DTensor placement before FSDP and a regression test; the exact-head Polaris rerun confirms the fix.

Merge remains held until the two queued GitHub Linux build jobs reach a terminal successful state.

@saforem2
saforem2 merged commit 2824eb0 into ezpz Sep 25, 2026
16 of 17 checks passed
@saforem2

Copy link
Copy Markdown
Owner Author

Merged into ezpz as 2824eb0645698d9098381d4a161f3143e8af3ad6 after final exact-head validation at 1f4aff12bf55a36f2c7cad0cfbf453ac3cde4e35.

Final gates:

  • Aurora 8868654: exit 0; AGPT TP=1, TP=2, and MoE each completed 5 steps with nonempty DCP metadata.
  • Polaris AGPT 7659393: TP=1 and TP=2 passed; dedicated MoE 7659410: exit 0, VERDICT: ok, losses 12.98146 -> 12.62001 -> 11.63856.
  • Sunspot 12478675: exit 0, NUMERIC_VERDICT=PASS; maximum loss delta 0.00036, maximum grad-norm delta 0.0015.
  • Perlmutter 58868718: completed 0:0, three CUDA optimizer steps.
  • Focused MoE/config tests: 124 passed.
  • GitHub lint passed; PyTorch-private runner workflows terminated as skipped on the fork.

Remote ezpz and merge ancestry were verified after merge.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.