Repository navigation
feat(ezpz): sync current TorchTitan and validate Aurora XPU RL - #21
Merged
Merged
Conversation
## 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.
Verifiers uses the `/v1/models` endpoint for the prompt-truncation path: - uses this endpoint to discover max_model_len: [link](https://github.com/PrimeIntellect-ai/renderers/blob/fdc03f2861e8f41334502eee49fd35f7cecb4ba6/renderers/client.py#L67-L105) - rejects the overlong prompt before generation: [link](https://github.com/PrimeIntellect-ai/renderers/blob/fdc03f2861e8f41334502eee49fd35f7cecb4ba6/renderers/client.py#L182-L189) - translates the renderer error: [link](https://github.com/PrimeIntellect-ai/verifiers/blob/b2e4e8157783b2c0dffc7821044c87f29f1c3ccf/verifiers/v1/clients/train.py#L439-L440) - cleanly stops the trace as context_length: [link](https://github.com/PrimeIntellect-ai/verifiers/blob/b2e4e8157783b2c0dffc7821044c87f29f1c3ccf/verifiers/v1/interception/server.py#L600-L610) This PR adds it.
…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
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0) (oldest at bottom): * __->__ pytorch#4815 As title
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 ```
This reverts commit 0c1ce54.
Owner
Author
|
Final exact-head validation for
The Polaris run initially exposed routed-expert parameters remaining plain tensors under full-SPMD FSDP when EP=1. Commit Merge remains held until the two queued GitHub Linux build jobs reach a terminal successful state. |
Owner
Author
|
Merged into Final gates:
Remote |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
This integrates the
ezpzbranch with TorchTitan upstream through0fd69d0band ports the Aurora/XPU paths to the resulting current stack.The branch also adds and validates:
aurora_full_sonicMoE backend on current TorchTitan;stage3-mix/global_step154391conversion.Validation
aurora_full_sonic: trains successfully on current TorchTitan withactivation_checkpoint_mode="none".2.14.0+xpu, Triton-XPU 3.8.0, vLLM XPU, torchmonarch 0.6.0.global_step154391direct control: coherent pretrained continuations.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
mpi4py, then PMIx initialization); neither produced or validated a candidate checkpoint.