Skip to content

Pull in changes from upstream main - #2

Closed
saforem2 wants to merge 66 commits into
saforem2:saforem2/blendcorpusfrom
pytorch:main
Closed

saforem2 wants to merge 66 commits into
saforem2:saforem2/blendcorpusfrom
pytorch:main

Conversation

@saforem2

@saforem2 saforem2 commented Oct 6, 2025

Copy link
Copy Markdown
Owner

Copilot Summary

This pull request introduces several improvements and updates across documentation, testing, and configuration scripts, with a primary focus on standardizing the float8 quantization interface, updating documentation to reflect these changes, and improving test and build infrastructure. The most impactful changes are grouped below.

Float8 Quantization Interface Standardization:

  • Updated all references and configuration flags from the old float8 namespace to the new quantize.linear.float8 namespace in documentation, benchmark commands, integration test configs, and test definitions. This ensures consistency and clarity for users and developers working with float8 quantization. [1] [2] [3] [4] [5] [6] [7]

Documentation Improvements:

  • Added a warning to benchmarks and updated documentation to clarify API changes related to float8 quantization, including migration instructions for reproducing older results.
  • Expanded debugging documentation to explain how to create and use seed checkpoints, and introduced the --checkpoint.load_only flag for debugging without saving new checkpoints.
  • Updated release documentation for clarity and fixed minor typos.
  • Added a news item announcing SkyPilot support for TorchTitan.

Test Infrastructure and Configuration:

  • Added a disabled field to the OverrideDefinitions test configuration class, enabling selective disabling of tests. Updated test lists to use this field for currently disabled or flaky tests, improving test management and CI stability. [1] [2] [3] [4] [5] [6] [7]
  • Updated test runner logic to skip disabled tests automatically.

Build and Script Updates:

  • Updated the default Python version in the Docker build script from 3.11 to 3.12 to ensure compatibility with the latest dependencies.
  • Modified the SLURM multinode training script to use the module form (-m torchtitan.train) for launching training, improving script robustness.

README and Badge Fixes:

  • Fixed README badges to point to the correct CI workflow URLs for 8 GPU feature and model tests.

These changes collectively improve usability, maintainability, and consistency across the codebase and documentation.

mreso and others added 30 commits September 23, 2025 09:08
…tion (#1741)

This PR moves the computation of the shared expert before the possible
scoring of the routed expert output which leads to an implicit overlap
between shared expert compute and token combine communication in MoE
models.

Repro (lowered the layer number to 2):
```
CONFIG_FILE="./torchtitan/models/deepseek_v3/train_configs/deepseek_v3_16b.toml" ./run_train.sh --profiling.enable_profiling --profiling.profile_freq 10  --training.steps 10 
``` 
Trace before the change:
<img width="1503" height="625" alt="Screenshot 2025-09-23 at 12 08
31 AM"
src="https://github.com/user-attachments/assets/bbcc41cf-6497-482e-972e-d917baf4498e"
/>

Trace after the change (note that all-to-all comm is now overlapping
shared expert compute):
<img width="1503" height="625" alt="Screenshot 2025-09-23 at 12 04
56 AM"
src="https://github.com/user-attachments/assets/3504e77c-aa14-46fd-8e47-e247b88d7b9c"
/>

cc @tianyu-l @xmfan
…on (#1730)

This PR resolves the `datasets` import error that were introduced in
#1712. The error causes the following error message:
```Traceback (most recent call last):
  File "./torchtitan/train.py", line 16, in <module>
    import torchtitan.protocols.train_spec as train_spec_module
  File "./torchtitan/__init__.py", line 12, in <module>
    import torchtitan.experiments  # noqa: F401
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "./torchtitan/experiments/__init__.py", line 7, in <module>
    import torchtitan.experiments.llama4  # noqa: F401
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "./torchtitan/experiments/llama4/__init__.py", line 11, in <module>
    from torchtitan.datasets.hf_datasets import build_hf_dataloader
  File "./torchtitan/datasets/hf_datasets.py", line 12, in <module>
    from datasets import Dataset, load_dataset
ImportError: cannot import name 'Dataset' from 'datasets' (./torchtitan/datasets/__init__.py)
```

Why is this happening? It is because #1712 added an `__init__.py` file
to the `datasets` folder. On the surface the PR looks fine, however, it
causes a collision with HF datasets Python package called `datasets`. So
when we try to import the `Dataset` class, we actually want the HF
datasets package and not the local `datasets` folder. This, in turn,
causes an import error. The solution is simple, change the `__init__.py`
name to something else, in our case I changed it to `common.py` as I
found this name most fitting.
My bad that forgot to update qwen3.
This PR appears to pass. I am not sure if it's wise though.

Signed-off-by: Edward Z. Yang <[email protected]>
Allows to configure flight recorder file prefix
[problem]
Using gradient accumulation is incompatible with PipleineSchedule(...,
scale_grads=True) option, which defaults to True.

When this option is set, at each step, all gradients are scaled by the
micro-batch size. This works fine for a single gradient accumulation
step, but when using multiple steps, this will rescale the total
gradient by this factor, not just at the end of gradient accumulation.

The result is that the accumulated gradient is an exponential moving
average, rather than a sum. Overall, the resulting gradients are much
smaller than they should be and using gradient accumulation with PP is
not equivalent to using it without PP -- the loss curves diverge
substantially, as well as the gradient-norms are way off.

A secondary consequence of is that at every step, it divides the
gradients by n_microbatches, which is computationally expensive when
applied to a large model.

[solution]
Set "scale_grads=False" when creating the scheduler instance.

Compute "n_microbatches" in the constructor and apply this factor, along
with gradient_accumulation_steps, to the scale factor in
"rescale_accumulated_loss()". This will cause the loss to be scaled,
rather than the gradients, at each step by the correct factor.

A secondary benifit of this approach is that it avoids having to modify
all of the gradients. It's much cheaper, computationally than modifying
all of the gradients -- and it's correct, which it is not, without the
change.

A side effect of the previous change is that the loss values returned by
the pipeline have been scaled by this factor, which makes them too small
by a factor of n_microbatches. We can correct this by rescaling the
returned loss by the same factor.

[testing]
Witout these changes, a baseline run, with 10 gradient accumulation
steps, on a single GPU is compared against a run (without the changes)
to a 2 GPU pipeline, using 1F1B. The effective batch size is 320 in both
cases, with all other variables controlled. The result is a substantial
divergence between the loss curves and gradient-norm of the two runs.

With this change applied, the results are nearly identical, ignoring
minor differences from non-determinism.

[references]
scale_grads option:
https://github.com/pytorch/pytorch/blob/281bb56cc50073159c8418c5c99c7459c914c4db/torch/distributed/pipelining/schedules.py#L286

scale_grads implementation:
https://github.com/pytorch/pytorch/blob/281bb56cc50073159c8418c5c99c7459c914c4db/torch/distributed/pipelining/stage.py#L567

Test code for reproduction of the issue and the testing the fix:

https://github.com/jdinalt/forgather/tree/main/examples/torchtitan/test_parallelisms
…ention Compilation (#1683)

Flex Attention requires compilation via torch.compile to achieve optimal
performance. Therefore, torch.compile is always applied to Flex
Attention, regardless of the compile.enable flag. However, when
Selective Activation Checkpointing (SAC) is enabled, torch.compile may
be bypassed or invalidated under certain conditions:

1. If compile.enable is set to False, SAC will ignore any torch.compile
calls within the SAC region.
2. If compile.enable is True but the transformer block includes a
Mixture of Experts (MoE) module.

To address this limitation, this PR separates the SAC wrapping of
Attention from MoE and FeedForward modules. This separation ensures that
Flex Attention can be compiled successfully even when SAC is enabled.
Attention module is wrapped with full AC if compile.enable is False.

FIX (workaround) #1631
Async TP related CI started to fail since Sep 22 2025. However even if
we roll back the nightly PyTorch to 0919, the tests still failed.
```
python -m pip install --force-reinstall torch==2.10.0.dev20250917+cu126 --index-url https://download.pytorch.org/whl/nightly/cu126
```

This is not an async TP issue but symmetric memory. This simple line can
cause issues on the CI machine/docker.

```
symm_mem = get_symm_mem_workspace(torch.distributed.group.WORLD.group_name, min_size=1024*1024*64)
```
[Problem]
When gradient accumulation is enabled, the validation loss is incorrect.
This is a consequence of the loss_fn being shared between train and
validation mode. The loss function is wrapped with
rescale_accumulated_loss(), which rescales the loss by the number of
gradient accumulation steps.

This works for train, as the loss from N accumulation steps is summed at
the end of the accumulation, before being logged. In the case of
validation, the loop assumes that each step is a normal step, and the
reported loss is scaled by 1/N.

There are two separate pathways by which this occurs. In the normal
case, the wrapped loss function is used "as-is." In the case of PP, the
loss function is not directly used, but is still applied indirectly
through the pipeline scheduler.

In both cases, the result is that the reported validation loss is
divided by the number of accumulation steps.

[Solution]
The number of gradient accumulation steps is not communicated to the
validation-factory, thus it does not have access to this parameter,
which is computed in the Trainer's constructor.

One possible solution would be to pass this value, as an argument, to
the validator, which could then rescale the loss by this factor, before
logging it. This was the suggested solution to the problem.

My solution is a little different. The function
"rescale_accumulated_loss()" now returns a loss function with a
"no_rescale()" context manager, which we apply before calling the
validator. This transparently disables rescaling while within this
context.

This approach avoids the need to communicate this detail to the
Validator and avoids having to modify the signature of the Validator
factory -- which means modifying quite a few other files.

Note that in the case of PP, we double-wrap the loss function. The
context manager only applies to the outer layer, thus has no impact on
the PP scaling, which is what we want.

[Testing]
First, run the trainer with both a normal, single GPU, run and a 2-stage
pipeline. In both cases, set the number of accumulation steps to be
sufficiently hight that the problem is obvious. This covers both
pathways to the wrapped loss function.

Repeat the tests with the fix. The magnitude of the validation loss
should roughly correlate with the train loss.
…oe training; refactor quantization APIs to use unified API (#1701)

## Context
- We've recently landed prototype mxfp8 MoE training support in torchao,
with **~1.3x speedup** over bf16 in single node. fsdp2 only, llama4 e2e
training with seq_len 8192, 2 experts per device:
pytorch/ao#3037.
- This PR integrates this feature into torchtitan and refactors the
quantized training APIs to use a unified
`"quantize.[mx|float8].[dense|moe]"` API

## Changes
- Replace "float8" and "mx" model converters with the following set of
converters, unified under the `quantize` namespace:
     - `quantize.dense.mx`
     - `quantize.dense.float8`
     - `quantize.moe.mx`
     - `quantize.moe.float8`
- This clean separation allows users more flexibility/control, to use
mxfp8 for dense layers, MoE layers, or both.


## Test plan 
- float8 dense and moe: `NGPU=4
CONFIG_FILE="./torchtitan/experiments/llama4/train_conf
igs/debug_model.toml" sanitize ./run_train.sh
--parallelism.data_parallel_shard_degree=4
--parallelism.expert_parallel_degree=4
--parallelism.tensor_parallel_degree=1 --model.print-after-conversion
--metrics.log_freq=10 --training.steps=30
--model.converters="quantize.dense.mx,quantize.moe.mx"
--quantize.dense.mx.recipe_n
ame="mxfp8_cublas"  --quantize.moe.mx.fqns="experts"`
- mxfp8 dense and moe: `NGPU=4
CONFIG_FILE="./torchtitan/experiments/llama4/train_configs/debug_model.toml"
./run_train.sh --parallelism.data_parallel_shard_degree=4
--parallelism.tensor_parallel_degree=1 --model.print-after-conversion
--metrics.log_freq=10 --training.steps=30 --compile.enable
--model.converters="quantize.dense.float8,quantize.moe.float8"`
In #1701 we split out the `Float8` job config to `Float8Dense` and
`Float8MoE`. This forge config was inadvertently not updated.

cc @tianyu-l
## Summary
- Float8 training and mx training cannot be combined. Add validation to
ensure either one or the other is used.
- Fix tomls which still use old config naming (addresses #1764)
- Refactor quantization config naming so (1) job_config class names are
consistent with converter names, and (2) naming is more explicit and
aligned with semantics of what conversions actually happen
   - Old: 
       - Converter classes: 
           - `Float8Converter`
           - `Float8MoEConverter` 
          - `MXConverter`
           - `MXMoEConverter`
       - User-facing args: 
            - `quantize.dense.float8`
            - `quantize.moe.float8`
            - `quantize.dense.mx`
            - `quantize.moe.mx`
   - New:
       - Converter classes: 
           - `Float8LinearConverter`
           - `Float8GroupedGEMMConverter`
           - `MXLinearConverter`
           - `MXGroupedGEMMConverter`
       - User-facing args: 
            - `quantize.linear.float8`
            - `quantize.grouped_mm.float8`
            - `quantize.linear.mx`
            - `quantize.grouped_mm.mx`

## Tests: mx on B200
- Test new config/args with valid job:
- `NGPU=4
CONFIG_FILE="./torchtitan/experiments/llama4/train_configs/debug_model.toml"
./run_train.sh --parallelism.data_parallel_shard_degree=4
--parallelism.expert_parallel_degree=1
--parallelism.tensor_parallel_degree=1 --model.print-after-conversion
--metrics.log_freq=10 --training.steps=30
--model.converters="quantize.linear.mx,quantize.grouped_mm.mx"
--quantize.linear.mx.recipe_name="mxfp8_cublas" --quantize.groupe
d_mm.mx.fqns="experts" --compile.enable`
    - Result: training as expected 
- Test mixing converters for different quantization methods, validate
error:
- `NGPU=4
CONFIG_FILE="./torchtitan/experiments/llama4/train_configs/debug_model.toml"
./run_train.sh --parallelism.data_parallel_shard_degree=4
--parallelism.expert_parallel_degree=1
--parallelism.tensor_parallel_degree=1 --model.print-after-conversion
--metrics.log_freq=10 --training.steps=30
--model.converters="quantize.linear.fp8,quantize.grouped_mm.mx"
--quantize.linear.mx.recipe_name="mxfp8_cublas"
--quantize.grouped_mm.mx.fqns="experts" --compile.enable`
- Result `AssertionError: Cannot combine model converters with different
quantization types: 'mx' and 'fp8'`

## Tests: FP8 rowwise on H100
- Test new config/args with valid job: 
- `NGPU=4
CONFIG_FILE="./torchtitan/experiments/llama4/train_configs/debug_model.toml"
./run_train.sh --parallelism.data_parallel_shard_degree=4
--parallelism.expert_parallel_degree=1
--parallelism.tensor_parallel_degree=1 --model.print-after-conversion
--metrics.log_freq=10 --training.steps=30
--model.converters="quantize.linear.float8,quantize.grouped_mm.float8"
--quantize.linear.float8.recipe_name="rowwise"
--quantize.grouped_mm.float8.fqns="experts" --compile.enable`
    - Result: training as expected
Unfortunately I went out on leave after opening #1646 so never actually
finished it out to enable bf16 training in the forge experiment, which
is what we ultimately wanted (thanks to @joecummings and @tianyu-l for
pushing it through).

I also see there was some discussion on the original PR which I
belatedly responded to. If there are still concerns there let me know.
Otherwise if we are not gonna revert that PR we should at least that one
so that forge can reap the benefits as intended.
As titled, this pr adds support for simplefsdp+ep. 

#### Profiler Trace & Correctness

The following results are benchmarks on 8 H100. The correctness are
validated on eager (with seed set to 42); I also added profile trace and
tlparse in compile mode.

1. SimpleFSDP
 * Loss:
<img width="1181" height="780" alt="Screenshot 2025-09-23 at 8 56 50 PM"
src="https://github.com/user-attachments/assets/67e48f6a-31c6-496e-a24c-830d6597b931"
/>


* Tlparse:
[Link](https://manifold.edge.x2p.facebook.net/v0/read/tree/logs/.tmpdaDH8h/rank_0/index.html?bucketName=tlparse_reports&apiKey=tlparse_reports-key&withPayload=1&timeoutMsec=10000)

* Profile Trace:
[Link](https://interncache-all.fbcdn.net/manifold/perfetto-artifacts/tree/ui/index.html#!/?url=https://interncache-all.fbcdn.net/manifold/perfetto_internal_traces/tree/shared_trace/ruisizhang123_2025-09-29-09-35-12_rank0_trace.json)
there would be only fsdp comms.

<img width="1061" height="107" alt="Screenshot 2025-09-29 at 9 35 37 AM"
src="https://github.com/user-attachments/assets/20df9de1-9491-4636-8cdc-33a8320c8385"
/>


2. SimpleFSDP + EP(degree=2)

 * Loss: 

<img width="1178" height="780" alt="Screenshot 2025-09-23 at 7 50 07 PM"
src="https://github.com/user-attachments/assets/e60a7af8-9764-41b0-ae29-9237bb67175d"
/>

* Tlparse:
[Link](https://manifold.edge.x2p.facebook.net/v0/read/tree/logs/.tmpAtT9l0/rank_0/index.html?bucketName=tlparse_reports&apiKey=tlparse_reports-key&withPayload=1&timeoutMsec=10000)
* Profile Trace:
([Link](https://interncache-all.fbcdn.net/manifold/perfetto-artifacts/tree/ui/index.html#!/?url=https://interncache-all.fbcdn.net/manifold/perfetto_internal_traces/tree/shared_trace/ruisizhang123_2025-09-23-19-28-52_rank0_trace.json))

<img width="947" height="280" alt="Screenshot 2025-09-23 at 7 35 36 PM"
src="https://github.com/user-attachments/assets/6bac31d8-6cd6-4a18-96d7-e36aa5b9a670"
/>

3. SimpleFSDP + TP(degree=2) + EP(degree=2) + ETP(degree=1)

 * Loss:

<img width="1188" height="786" alt="Screenshot 2025-09-23 at 7 58 18 PM"
src="https://github.com/user-attachments/assets/16374e93-fe0b-4583-b856-8571f26c5a9d"
/>

* Tlparse:
[Link](https://manifold.edge.x2p.facebook.net/v0/read/tree/logs/.tmpLyfHM3/rank_0/index.html?bucketName=tlparse_reports&apiKey=tlparse_reports-key&withPayload=1&timeoutMsec=10000)

* Profile Trace:
([Link](https://interncache-all.fbcdn.net/manifold/perfetto-artifacts/tree/ui/index.html#!/?url=https://interncache-all.fbcdn.net/manifold/perfetto_internal_traces/tree/shared_trace/ruisizhang123_2025-09-23-20-02-47_rank0_trace.json))

<img width="1210" height="297" alt="Screenshot 2025-09-23 at 8 09 41 PM"
src="https://github.com/user-attachments/assets/7703a6c2-6755-4ebc-a184-9f4358102f36"
/>

4.  HSDP(dp_shard=2; dp_replicate=2) + EP (degree=2)

 * Loss: 
<img width="1160" height="719" alt="Screenshot 2025-09-24 at 9 44 48 PM"
src="https://github.com/user-attachments/assets/aa3662e5-dbbd-4415-871c-03a8af9cab35"
/>

* Tlparse:
[Link](https://manifold.edge.x2p.facebook.net/v0/read/tree/logs/.tmp2WSuG3/rank_0/index.html?bucketName=tlparse_reports&apiKey=tlparse_reports-key&withPayload=1&timeoutMsec=10000)

* Profile Trace:
([Link](https://interncache-all.fbcdn.net/manifold/perfetto-artifacts/tree/ui/index.html#!/?url=https://interncache-all.fbcdn.net/manifold/perfetto_internal_traces/tree/shared_trace/ruisizhang123_2025-09-24-21-10-23_rank0_trace.json))

<img width="865" height="270" alt="Screenshot 2025-09-24 at 9 16 44 PM"
src="https://github.com/user-attachments/assets/4607d5ee-6d73-4438-8d52-a9268e10aa90"
/>

5. HSDP(dp_shard=2; dp_replicate=2) + EP (degree=2) + EP(degree=2) +
ETP(degree=1)

 * Loss:
<img width="1168" height="729" alt="Screenshot 2025-09-24 at 9 41 20 PM"
src="https://github.com/user-attachments/assets/f4f74825-e942-43af-96cc-8f1ac918651c"
/>


* Tlparse:
[Link](https://manifold.edge.x2p.facebook.net/v0/read/tree/logs/.tmpZcSbS5/rank_0/index.html?bucketName=tlparse_reports&apiKey=tlparse_reports-key&withPayload=1&timeoutMsec=10000)

* Profile Trace:
([Link](https://interncache-all.fbcdn.net/manifold/perfetto-artifacts/tree/ui/index.html#!/?url=https://interncache-all.fbcdn.net/manifold/perfetto_internal_traces/tree/shared_trace/ruisizhang123_2025-09-24-21-21-41_rank0_trace.json))

<img width="885" height="187" alt="Screenshot 2025-09-24 at 9 30 04 PM"
src="https://github.com/user-attachments/assets/e19dd212-79e1-41c5-9f08-9c97b302793e"
/>


#### Status

1. Currently, SimpleFSDP+EP+AC doesn't work because of graph breaks in
HOP mutation. (see the [comment message
](#1529 (comment)))

2. @ezyang also points out that numerical issues in Float8 training may
be related to this, since quantization calibration involves mutation,
which might not compose well with AC.

3. There are some minor numerical differences after EP is added.
@tianyu-l suggests that it's because the reduce-scatter is averaged over
whole dp_mesh, instead of dp_mod_ep_mesh, for the EP part. We will fix
this in a separate PR.

4. PP(1F1B and Interleaved1F1B)+EP+SimpleFSDP has a series of
composability issues:
#1529 (comment)

cc. @anijain2305
Stacked PRs:
 * __->__#1768


--- --- ---

### config compile backend
#1287 refactors
async_with_pinned_mem to use DCP's implementation but that PR didn't set
staging correctly. This PR fixes it.

Fixes #1773
we can set `DEBUG_FORCE_LOAD_BALANCED=1` to force each experts get same
amount of tokens.

reprodue: `DEBUG_FORCE_LOAD_BALANCED=1
CONFIG_FILE="./torchtitan/models/deepseek_v3/train_configs/debug_model.toml"
NGPU=4 ./run_train.sh --compile.enable`

here is test on 8layers, 8 activate and 64 total experts. Green one is
vanilla one and purple one is with force load balance
<img width="2672" height="1222" alt="image"
src="https://github.com/user-attachments/assets/fa2cdec5-d266-4949-86ef-e86afeaac2c1"
/>

<img width="2712" height="1324" alt="image"
src="https://github.com/user-attachments/assets/f013098f-7538-4870-b2f4-7ac0e93a9706"
/>
As #1789 mentioned, make the 16B default toml config safe for 80GB H100
as well.
<img width="1657" height="770" alt="Screenshot 2025-10-02 at 5 11 32 PM"
src="https://github.com/user-attachments/assets/8199cd9b-2354-4029-bd3e-5b58241e6c45"
/>
Adding a PR to add SkyPilot support in the news section of the readme.
Reuse StateDictAdapter support for DeepSeek V3 model to implement Qwen3 StateDictAdapter. Move the common features of MoE state dict adapter to the subclass MoEStateDictAdapter in torchtitan/models/utils.py.
This code logic was committed prematurely as the final CP UX may be
different. Remove it for now to avoid confusion and future BC issues.
Seed checkpoint loading requires checkpoint.enable to be True. However,
when using seed checkpoints, users typically don't want to save
subsequent checkpoints since seed checkpoints serve verification
purposes only.
mori360 and others added 17 commits October 13, 2025 20:03
Summary:
Composability testing with TorchComms and distributed training in
TorchTitan.
  - Training with `torchcomms.new_comm`
  - Device mesh initialization with `torchcomms.init_device_mesh`
  - Integration and testing with `fully_shard`

Differential Revision: D82171763

Test plan:
TEST_BACKEND=nccl TRAIN_FILE=torchtitan.experiments.torchcomms.train
./run_train.sh --model.name torchcomms

Loss curve:
running 1000 steps on llama3_8b.toml

<img width="1095" height="469" alt="Screenshot 2025-10-13 at 4 14 46 PM"
src="https://github.com/user-attachments/assets/3d9ddf06-af76-44cf-ac75-b9f92e6d0f06"
/>
This PR also
- updates the README of `deepseek_v3` folder.
- move the `generate_permute_indices` triton kernel to
`torchtitan/models/moe` so that core doesn't depend on `experiments`
- deprecate the gpu checkpoint conversion scripts as now we natively
support loading checkpoint from HF using GPUs (although it is only using
GPU when doing online conversion right before training starts)
Originally the OBELICS dataset support was added by @TJ-Solergibert in
#663, which showcased a great
example of how interleaved text + image data could be processed for
vision language model training.

However, since then the `experiments/multimodal` folder has been
inactive for a long time, due to limited support. In fact, there has
never been runnable training code consuming this data loader.

Now that @lkhphuc is providing dedicated support for the
`experiments/vlm` folder, which already has a running example of siglip
+ llama3 training. It can be seen as a spiritual continuation of
`experiments/multimodal` folder, partially resembling the original
OBELICS data loading behavior.

Hence, we are deprecating the `experiments/multimodal` folder. We would
encourage the community to try out, help develop and maintain the
`experiments/vlm` folder.
We originally thought each model should have its own `pipeline.py`
function.

However, for most LLMs, it turns out a single function would suffice,
and all models which needs PP are reusing `pipeline_llama.py` originally
written for llama3.

(For diffusion models, the model size doesn't justify the usage of PP.)

This PR consolidates them and moves `pipeline_llm` into
`torchtitan/distributed/pipeline_parallel.py`.

We can refactor later if things change.
As titled, given the `experiments/deepseek_v3` has been out of
maintenance for long time.

The folder could still be valuable, so I'm keeping the content in the
branch `experiments/deepseek_v3` as reference
https://github.com/pytorch/torchtitan/tree/experiments/deepseek_v3/torchtitan/experiments/deepseek_v3

This PR keeps the symmetric memory kernels for EP communication, whose
integration will come later.
Nightly build is no longer required for MXFP8
As #1867 , thanks @yanboliang for pointing out!

Before the change:
<img width="1547" height="714" alt="Screenshot 2025-10-13 at 10 08
07 PM"
src="https://github.com/user-attachments/assets/d818e4b0-ec30-4d13-a85b-16b4b7aab42b"
/>

After the change:
<img width="1547" height="714" alt="Screenshot 2025-10-13 at 10 08
30 PM"
src="https://github.com/user-attachments/assets/7d2fe949-0a16-4900-9607-d3d85e467261"
/>
…#1871)

In the past, the terms "args" and "config" have been used in a mix.

To make it unambiguous, in torchtitan we use
- "args" as in `ModelArgs` to refer to parameters used to define a model
in model code
- "config" as in `JobConfig` to refer to configurable training job
commands used in training script

This also PR also moves `custom_args_module` (which should be
`custom_config_module` according to the naming rule above) from
`Experimental` to `Job`, as it has been extensively used by various
models in torchtitan, especially those in the `experiments` folder.
This pr adds the autobucketing pass at aten-level to simplefsdp. It runs
autobucketing + aot_eager backend without inductor. The aten fx
autobucketing pass can be find in this PR:
pytorch/pytorch#163960.

Key updates are:

1. Support customized `aot_eger_autobucketing` backend to perform
autobucketing optimization.
2. In simplefsdp, the model_backend can be replaced by user's customized
passes using `compile.model_backend_override`.
)

See
#1806 (comment)
This PR prevents mutation of ReordererSequenceParallel. Because
torch.utils.checkpoint.checkpoint is a HOP and has such constraint.

---------

Co-authored-by: mingheng.w <[email protected]>
Co-authored-by: tianyu-l <[email protected]>
Support ND device mesh among [pp, dp, cp, tp]
Used comm.split() to split the sub device mesh at each parallelism
Flatten the mesh to dp, dp_shard_cp, dp_cp, which will be access in
titan training


`TEST_BACKEND=nccl TRAIN_FILE=torchtitan.experiments.torchcomms.train
CONFIG_FILE="./torchtitan/models/llama3/train_configs/debug_model.toml"
./run_train.sh --parallelism.context_parallel_degree 2
--parallelism.tensor_parallel_degree 2`


[rank0]:[titan] 2025-10-14 14:56:30,464 - root - INFO - step: 1 loss:
8.1440 grad_norm: 1.3609 memory: 0.78GiB(0.82%) tps: 775 tflops: 0.06
mfu: 0.01%
[rank0]:[titan] 2025-10-14 14:56:30,465 - root - INFO - Synchronizing
and adjusting timeout for all ProcessGroups to 0:01:40
[rank0]:[titan] 2025-10-14 14:56:30,615 - root - INFO - step: 2 loss:
7.8313 grad_norm: 1.4321 memory: 0.85GiB(0.89%) tps: 27,316 tflops: 1.96
mfu: 0.20%
[rank0]:[titan] 2025-10-14 14:56:30,736 - root - INFO - step: 3 loss:
7.1126 grad_norm: 1.8422 memory: 0.85GiB(0.89%) tps: 33,869 tflops: 2.42
mfu: 0.25%
[rank0]:[titan] 2025-10-14 14:56:30,849 - root - INFO - step: 4 loss:
6.2534 grad_norm: 2.2657 memory: 0.85GiB(0.89%) tps: 36,315 tflops: 2.60
mfu: 0.26%
[rank0]:[titan] 2025-10-14 14:56:30,960 - root - INFO - step: 5 loss:
5.3031 grad_norm: 2.3692 memory: 0.85GiB(0.89%) tps: 37,302 tflops: 2.67
mfu: 0.27%
[rank0]:[titan] 2025-10-14 14:56:31,078 - root - INFO - step: 6 loss:
4.8114 grad_norm: 2.2013 memory: 0.85GiB(0.89%) tps: 34,679 tflops: 2.48
mfu: 0.25%
[rank0]:[titan] 2025-10-14 14:56:31,188 - root - INFO - step: 7 loss:
4.5279 grad_norm: 2.2304 memory: 0.85GiB(0.89%) tps: 37,238 tflops: 2.67
mfu: 0.27%
[rank0]:[titan] 2025-10-14 14:56:31,302 - root - INFO - step: 8 loss:
4.3251 grad_norm: 2.1220 memory: 0.85GiB(0.89%) tps: 36,187 tflops: 2.59
mfu: 0.26%
[rank0]:[titan] 2025-10-14 14:56:31,413 - root - INFO - step: 9 loss:
4.5047 grad_norm: 1.7700 memory: 0.85GiB(0.89%) tps: 37,154 tflops: 2.66
mfu: 0.27%
[rank0]:[titan] 2025-10-14 14:56:31,528 - root - INFO - step: 10 loss:
4.1099 grad_norm: 1.7139 memory: 0.85GiB(0.89%) tps: 35,564 tflops: 2.55
mfu: 0.26%
[rank0]:[titan] 2025-10-14 14:56:31,528 - root - INFO - Sleeping 2
seconds for other ranks to complete
When TP is used for the matmul / grouped mm between input activations
and routed experts, the same inputs are seeing different parameter
values across TP ranks (inputs Replicate, param Shard) and thus the
gradient flowing back should have `Partial` placement and need to be
reduced. However, since we are using plain Tensor, instead of DTensor
which can properly handle the gradient flow, we have to "manually"
handle it. This PR fixes the issue by specifying the `grad_placements`
field of `to_local`.

One can see that one more all-reduce is inserted in the backward every
time it gets gradient from routed experts matmul.
before
<img width="767" height="74" alt="image"
src="https://github.com/user-attachments/assets/602487e4-57fb-4dd3-b22b-92db1729a857"
/>
after
<img width="790" height="121" alt="image"
src="https://github.com/user-attachments/assets/bc033c50-4bac-4ec7-b96f-ff3464e9bfa8"
/>
nd parallelism is available after
#1876
update readme, and fix the font issue
Introduced by #1776.

Verified with the comment:

```
CONFIG_FILE="./torchtitan/models/llama3/train_configs/debug_model.toml" ./run_train.sh   --training.steps=10 --parallelism.context_parallel_degree=8
```
w/o this PR
```
[rank4]:[titan] 2025-10-14 23:10:44,306 - root - INFO - step:  1  loss:  8.0385  grad_norm:  1.3444  memory:  1.21GiB(1.27%)  tps: 2,904  tflops: 0.21  mfu: 0.02%
[rank4]:[titan] 2025-10-14 23:10:44,306 - root - INFO - Synchronizing and adjusting timeout for all ProcessGroups to 0:01:40
[rank4]:[titan] 2025-10-14 23:10:44,347 - root - INFO - step:  2  loss:  7.6989  grad_norm:  1.4401  memory:  1.34GiB(1.41%)  tps: 49,366  tflops: 3.53  mfu: 0.36%
[rank4]:[titan] 2025-10-14 23:10:44,388 - root - INFO - step:  3  loss:  7.0687  grad_norm:  1.8302  memory:  1.34GiB(1.41%)  tps: 51,400  tflops: 3.68  mfu: 0.37%
[rank4]:[titan] 2025-10-14 23:10:44,425 - root - INFO - step:  4  loss:  6.2672  grad_norm:  2.2684  memory:  1.34GiB(1.41%)  tps: 55,749  tflops: 3.99  mfu: 0.40%
[rank4]:[titan] 2025-10-14 23:10:44,465 - root - INFO - step:  5  loss:  5.3015  grad_norm:  2.5508  memory:  1.34GiB(1.41%)  tps: 50,835  tflops: 3.64  mfu: 0.37%
[rank4]:[titan] 2025-10-14 23:10:44,522 - root - INFO - step:  6  loss:  4.7779  grad_norm:  2.4103  memory:  1.34GiB(1.41%)  tps: 36,188  tflops: 2.59  mfu: 0.26%
[rank4]:[titan] 2025-10-14 23:10:44,573 - root - INFO - step:  7  loss:  4.4823  grad_norm:  2.2675  memory:  1.34GiB(1.41%)  tps: 41,167  tflops: 2.95  mfu: 0.30%
[rank4]:[titan] 2025-10-14 23:10:44,618 - root - INFO - step:  8  loss:  4.3291  grad_norm:  1.9877  memory:  1.34GiB(1.41%)  tps: 45,962  tflops: 3.29  mfu: 0.33%
[rank4]:[titan] 2025-10-14 23:10:44,656 - root - INFO - step:  9  loss:  4.7022  grad_norm:  1.5639  memory:  1.34GiB(1.41%)  tps: 53,689  tflops: 3.84  mfu: 0.39%
[rank4]:[titan] 2025-10-14 23:10:44,695 - root - INFO - step: 10  loss:  4.1905  grad_norm:  1.8200  memory:  1.34GiB(1.41%)  tps: 52,967  tflops: 3.79  mfu: 0.38%
```

w/ this PR
```
[rank4]:[titan] 2025-10-14 23:09:32,084 - root - INFO - step:  1  loss:  8.1003  grad_norm:  1.4468  memory:  0.23GiB(0.24%)  tps: 150  tflops: 0.01  mfu: 0.00%
[rank4]:[titan] 2025-10-14 23:09:32,085 - root - INFO - Synchronizing and adjusting timeout for all ProcessGroups to 0:01:40
[rank4]:[titan] 2025-10-14 23:09:32,151 - root - INFO - step:  2  loss:  7.7710  grad_norm:  1.5711  memory:  0.25GiB(0.26%)  tps: 30,879  tflops: 2.21  mfu: 0.22%
[rank4]:[titan] 2025-10-14 23:09:32,218 - root - INFO - step:  3  loss:  7.0456  grad_norm:  1.9929  memory:  0.25GiB(0.26%)  tps: 30,642  tflops: 2.19  mfu: 0.22%
[rank4]:[titan] 2025-10-14 23:09:32,283 - root - INFO - step:  4  loss:  6.1601  grad_norm:  2.3669  memory:  0.25GiB(0.26%)  tps: 31,723  tflops: 2.27  mfu: 0.23%
[rank4]:[titan] 2025-10-14 23:09:32,349 - root - INFO - step:  5  loss:  5.2561  grad_norm:  2.5374  memory:  0.25GiB(0.26%)  tps: 31,047  tflops: 2.22  mfu: 0.22%
[rank4]:[titan] 2025-10-14 23:09:32,420 - root - INFO - step:  6  loss:  4.8109  grad_norm:  2.8868  memory:  0.25GiB(0.26%)  tps: 29,067  tflops: 2.08  mfu: 0.21%
[rank4]:[titan] 2025-10-14 23:09:32,488 - root - INFO - step:  7  loss:  4.4534  grad_norm:  2.4835  memory:  0.25GiB(0.26%)  tps: 30,383  tflops: 2.17  mfu: 0.22%
[rank4]:[titan] 2025-10-14 23:09:32,554 - root - INFO - step:  8  loss:  4.2613  grad_norm:  2.1554  memory:  0.25GiB(0.26%)  tps: 31,078  tflops: 2.22  mfu: 0.22%
[rank4]:[titan] 2025-10-14 23:09:32,619 - root - INFO - step:  9  loss:  4.6215  grad_norm:  1.7431  memory:  0.25GiB(0.26%)  tps: 31,814  tflops: 2.28  mfu: 0.23%
[rank4]:[titan] 2025-10-14 23:09:32,687 - root - INFO - step: 10  loss:  4.0993  grad_norm:  2.0867  memory:  0.25GiB(0.26%)  tps: 30,272  tflops: 2.17  mfu: 0.22%
```
Now that we are creating FlexAttention block masks outside the model,
the `input_batch` field in model inputs is no longer needed.

This PR also renames `extra_args` to be `extra_kwargs`, as it's a
dictionary of kwargs, technically.
Follow-up to PRs #1583 /
#1611

Fixes a few typos found by running [`codespell`
](https://github.com/codespell-project/codespell)on the repository.

Also see related PR #1899
which adds a `codespell` pre-commit hook.
@saforem2 saforem2 closed this Oct 16, 2025
@saforem2 saforem2 mentioned this pull request Jun 11, 2026
saforem2 added a commit that referenced this pull request Jun 12, 2026
Tight-clip test 8539593 (max_norm=0.1) NaN'd at step 4 instead of
step 6 — earlier than baseline. Three possible causes:
1. clip-norm legitimately changes weights enough to shift the
   overflow trajectory
2. RNG state shifts (FSDP scheduling, dataloader) → different
   forward inputs
3. FP chaos (nan-poisoning during clip_grad_norm)

The deterministic pair removes #2 and #3:
- n32-det.sh: baseline + --debug.seed=42 --debug.deterministic
  (max_norm=1.0 default)
- n32-det-tight-clip.sh: same + --training.max-norm=0.1

With matched seed + deterministic, the two runs are bit-identical
through whatever number of steps until clip diverges them. If clip
changes nothing meaningful, they'll both NaN at the same step.

Per CLAUDE.md: --debug.deterministic only (NEVER
--debug.deterministic_warn_only).
saforem2 added a commit that referenced this pull request Jun 13, 2026
…p313 wheel missing

Job 12468752 verdict: env-scrub fix worked (oneCCL got past init,
KV cache allocated to 25.76 GiB), but hit a second issue at first
inference — `TypeError: 'function' object is not subscriptable` at
`_compute_slot_mapping_kernel[(num_reqs + 1,)](...)`.

Root cause #2: triton-xpu 3.7.1 only ships a cp314 wheel. The
py3.13 rl-actors venv falls back to either:
- vanilla triton 3.7.0 (cp313 wheel, no Intel symbols in libtriton.so)
- pytorch-triton-xpu 3.5.0 (cp313 wheel, no triton.language.target_info)

Neither works with vllm-xpu-kernels 0.1.9.1.

Resolution: use venvs/vllm-test/ (py3.14, has triton-xpu 3.7.1) as
the vLLM worker venv. Three-venv layout:
- venvs/rl-actors/ (py3.13) → Monarch controller (no cp314 wheel)
- venvs/vllm-test/ (py3.14) → vLLM worker (no cp313 wheel)
- .venv/ (py3.14) → torch 2.13 trainer

Monarch's HostMesh.spawn_procs(bootstrap_command=BootstrapCommand(
program=...)) lets a controller in one Python spawn workers in
another, so the venv split doesn't block the actor pattern.

Status doc updated with the triton-xpu finding and the three-venv
table.

Job 12468753 queued.
saforem2 added a commit that referenced this pull request Jul 12, 2026
…attern (2/2)

12470351 hung at ~step 1535 (idle-watchdog rc=124, same ~30min-silence
signature as the head @ ~790) -- HANG #2. afterany recovered: 12470352
resumed from checkpoint-1600 (model+optimizer loaded, loss 0.739 continuous),
new wandb run ghltmvgf dashing-water. Chain topped to 5 H. Both chain links
so far ended in idle hangs (~every 5h); documented as an 8N-stability watch
item -- still recovering cleanly, not yet escalated (<3 threshold... but 2/2).
saforem2 added a commit that referenced this pull request Jul 24, 2026
Reconcile status markers with verified current state:
- blendcorpus-eoferror-race: frontmatter open -> fixed-pending-confirmation
  (body says FIXED 041d015f 2026-06-28, on-hardware confirm still pending)
- cot.md header: Stage 2 no longer next -- Stages 0-2 complete (RL perfects
  CoT format but is not the 2B accuracy lever), matches dated body sections
- known-issues async-mode: pending-dispatch -> RESOLVED (sync is prod default;
  async cascades at 512N+)
- moe_ep_step41_hang: mark the Updates-to-other-docs TODO done (sibling
  Finding #2 already reclassified transient + cross-links back)
- sft/README index: tulu_math_uc_mix_full in-progress -> COMPLETE (8N, step
  8672, loss 0.357), matching its subpage header
saforem2 added a commit that referenced this pull request Aug 17, 2026
…on is loud

Recommendation #2 from the concurrent-job-ckpt-collision writeup. Two jobs
writing one checkpoint.folder is currently silent and physically mixes their
shards: it left step-6200-20260729-142222 and step-6300-20260729-142222 holding
3,072 files each where a healthy 20B-256 checkpoint has 192 -- 906 GB combined,
~560 GB of it orphan bytes. Nothing warned, nothing named the other writer;
they were found weeks later by counting files. Both dirs are still on disk
(verified today, 453 GB each) awaiting a reclaim decision.

Rank 0 now writes a small .owner file (jobid, rank count, start time) before
the checkpointer loads, and reports loudly when a different jobid already holds
one. First 30 seconds of the log instead of a file count weeks later.

WARN, not refuse, deliberately. Any job killed by walltime, a node fault, or a
PBS -14 leaves a stale claim, and a job cannot reliably tell stale from live
from the inside -- PBS state is not visible there and jobids get recycled.
Refusing would turn every crashed predecessor into a failed resume, which is
worse than the failure being prevented. Claims older than 36h are labelled
likely-stale so the warning stays worth reading.

Takes dump_folder explicitly, because omitting it is exactly what made an
earlier detector silently no-op against <cwd>/checkpoints/... while the real
tree is <cwd>/outputs/checkpoints/... -- a test asserts the two paths differ.

Test is stdlib-only and loads the module by path, since importing the ezpz
package pulls in torch; it runs on a laptop. 16 assertions covering resume (same
jobid is not a collision), takeover, staleness, non-rank-0, corrupt claims, and
a missing directory. All pass.
saforem2 added a commit that referenced this pull request Aug 19, 2026
Commit 2fa5d12 is titled "I broke every compiled agpt run" and its message
asserts that emitting positions unconditionally caused the agpt_20b
vc_check/DeviceMesh assertion. That attribution is WRONG and this note
retracts it. Amending is not an option here (no --amend), so the correction
lives beside it.

What killed it: the verification run for that very fix shows the config
dumping "emit_positions": false -- positions are NOT being emitted -- and
agpt_20b fails with the identical assertion anyway.

I reached the wrong conclusion by pattern-matching on timing. My positions
commit landed at 13:38, the last known-good compiled run started at 13:06,
and I treated that ordering as causal without testing the hypothesis first.

Two further hypotheses died the same day, both by measurement:

- "compile is broken / use --compile.no-enable" (from TODO.md #2, written
  about the 80B): the 30B ran 482 compiled FullAC TP=1 steps TODAY on this
  stack, and --compile.no-enable does NOT fix the 20B -- it fails differently,
  level_zero error 40 inside cross_entropy. I gave the user that workaround
  before testing it; it does not work.
- "seq_len / logits capacity": 8192, 4096 and 2048 all fail identically at
  ~7% memory. Failing at 2048 with 4.45 GiB allocated is not a memory wall --
  it dies during graph construction, before real activation memory exists.

The change 2fa5d12 makes is still correct on its own merits and stays:
emitting positions to configs that cannot use a mask is wrong regardless of
whether it causes this particular crash, and the gate keeps the MoE flex fix
working (moe_small 3/3 with it). Only the causal claim is withdrawn.

Root cause of the agpt_20b failure is still open. A commit bisect is running;
its first attempt was itself void (worktree placed in node-local /tmp, so 23
of 24 ranks could not chdir into it -- every arm read 0/3 for a reason
unrelated to the commit under test). The harness now labels that failure mode
explicitly rather than printing "see log".
saforem2 added a commit that referenced this pull request Aug 20, 2026
…ustified uncompiled

Records the agpt_20b/30b vc_check DeviceMesh failure with the full matrix and,
more importantly, the four hypotheses that were proposed and then killed --
because I proposed three of them out loud before testing any.

The measured picture (agpt_20b, 2N, TP=1, seq=8192):

  full_dtensor    compiled   0/3   vc_check (DeviceMesh)
  full_dtensor    no-compile 0/3   level_zero 40 in cross_entropy
  partial_dtensor compiled   3/3   PASS, 84.86%
  partial_dtensor no-compile 0/3   level_zero 40

Two separate axes. full_dtensor breaks the compiled path;
--compile.no-enable is NOT a workaround, it exposes a distinct capacity wall
(~16.8 GB of fp32 logits per rank at seq=8192 with a 256k vocab).

The bisect of 60009b0 used partial_dtensor as a built-in control, since
that commit only edits the full_dtensor branch. Control held (3/3 at both
commits, byte-identical memory). Result: full_dtensor was ALREADY broken
before the commit, with ValueError "all parameters must be DTensors". The
commit fixed that and advanced the failure to the next wall. Reverting would
swap the assertion back for a ValueError, not restore agpt.

The pin in 621ac24 cited job 12473350 as evidence full_dtensor works. That
probe ran --compile.no-enable. The measurement was real; its scope was not.
An uncompiled result got applied to compiled production configs.

Excluded by measurement, not argument: the blendcorpus positions change
(runs log emit_positions:false and fail identically), "compile is broken"
(TODO.md #2 is about the 80B and its workaround does not work here), seq_len
(8192/4096/2048 all fail at ~7% memory), and the environment -- re-ran under
the user's frameworks_rc with intel_gpu_umd_aicoe/2026.06.19 instead of the
frameworks module, same assertion.
saforem2 added a commit that referenced this pull request Aug 24, 2026
…path

Three defects in the combined eval chart, all of the same shape: the code was
right about what it drew and wrong about what it was pointed at.

1. The MDS reference chain plotted 7.06T of its 7.77T tokens.

   TRAJECTORIES reads `agpt-2b-mds`, whose three ntok* stages cover steps
   5,000-140,352. The last 14k steps (140,400-154,391) live in a SIBLING dir,
   `agpt-2b-mds-7771T`, that no trajectory referenced -- so the flagship run
   was drawn as if it stopped ~0.7T short, silently, with the missing segment
   being exactly the tail that makes it the reference. Same layout, same step
   numbering, so `extra_subdirs` merges it in and the existing replicate
   averaging handles the overlap it already handles within one dir.

2. OUT_PATH hardcoded docs/evals/, which the docs reorg retires.

   Post-merge that path does not exist -- and it would not have failed:
   mkdir(parents=True) recreates the retired tree, writes the chart into it,
   exits 0, while every README goes on pointing at docs/records/evals/. The
   dir is now resolved by locating the README.md that embeds the chart. Probing
   on README rather than on the directory matters: BOTH paths exist on the
   pre-reorg branch (records/evals/agpt/{2b,20b} holds per-model overviews
   while docs/evals/ is still the landing page), so a bare is_dir() test is
   wrong on one branch or the other. Verified resolving correctly on each.

   REPO_ROOT likewise moves off parents[4] to a walk-up, same reasoning as the
   plotters fixed in ffbc9c7.

3. _assert_no_missing_live_chains gated on cls == "live" only.

   A chain becomes wandb_only when it stops running; its eval history stays
   valid, so the old gate dropped a chain from the chart on the day it finished
   -- the day its final numbers matter most. Now checks both plotted classes,
   and counts extra_subdirs/corrected_subdir as covered.

   Added a weaker second check: warn about agpt-* eval dirs holding results
   that no trajectory reads. That is precisely how #1 hid, and it is a warning
   rather than a failure because plenty of dirs there are SFT/IFEval/one-off
   sweeps that do not belong on a pretraining-token chart. The point is that
   dropping one becomes a decision, not an oversight.

Note the doc-link checker did not catch #2 -- it scans markdown links and
parents[N] patterns, not string-literal output paths in .py.
saforem2 added a commit that referenced this pull request Sep 8, 2026
…art, second at constant LR

Excursion #2 confirmed: preclip 31.8 -> 58.0, loss reversed 10.358 -> 10.626,
layer_max falling 0.299 -> 0.123. Its step 29 reproduces excursion #1s step 15
to within ~20% on preclip and ~13% on layer_max, same anti-correlation.

SETTLES THREE THINGS. Not a warmup artifact -- the LR has been flat at 1e-6
since step 22 and the second onset came six steps later. Not the LR ramp rate
-- there is no ramp during the second, which kills the hypothesis I offered
after the first. And it repeats, with 13 steps between onsets; one interval is
not a period but it is now measurable, with ~120 steps left to measure it.

WHY IT MATTERS BEYOND THIS RUN. The documented 80B failures are single NaN
events at steps 9, 17, 18 and 37 in different jobs. If those are the tail of a
recurring instability rather than isolated accidents then the step number of a
NaN is a draw from a repeating process, not a property of the configuration --
which would explain why the failure step has never been reproducible. A run
that trains cleanly may simply have sampled the quiet phase, and the relevant
measurement becomes the excursion RATE rather than whether a given run failed.

That reframes every clean-run result here, including tonights five dp arms,
all of which ran 40 steps or fewer at LRs too small to leave the near-uniform
regime.

Still zero non-finite gradients across both excursions.
saforem2 added a commit that referenced this pull request Sep 16, 2026
The native-DDP preflight could never run. Two independent defects, both
on the same call path, both from f5f6ee6:

1. trainer.py passed 6 of the 9 required keyword-only args. Missing:
   fault_tolerance_enabled, create_seed_checkpoint,
   optimizer_has_param_groups -- none of which have defaults. Any run
   with enable_data_parallel_native_ddp=true died with TypeError at
   trainer construction, before anything else was reached.

   All three are available at the callsite and now passed:
   config.fault_tolerance.enable, config.checkpoint.create_seed_checkpoint,
   and whether config.optimizer declares param_groups.

2. Even fixed, the validator read three fields that do not exist here:
   parallelism.enable_fsdp_async_all_reduce,
   pipeline_parallel_fsdp_overlap and pipeline_parallel_fsdp_overlap_policy.
   Those are on the upstream Aurora MoE branch's CORE ParallelismConfig;
   ours is EzpzParallelismConfig, which deliberately ports only the five
   fields our code reads, and core torchtitan never had them. Reading
   them on a slotted dataclass raised AttributeError, and they sit two
   gates before the final check, so they were always reached.

   Now read via getattr with the upstream default. Keeping the checks
   rather than deleting them means the rejection still fires if those
   fields are ever added; deleting would silently accept a combination
   the author explicitly rejected.

Verified by calling the validator against REAL objects -- a real
ParallelDims built from its own dataclass fields, a real TrainingConfig,
and a real EzpzParallelismConfig with the flag on. It now runs every
gate and returns a policy ValueError ("native DDP currently requires
standard CrossEntropyLoss") instead of TypeError or AttributeError.
That is the validator working.

Both found by /code-review on my own PR (#17), findings 1 and 2 of 15.
I shipped f5f6ee6 saying the hooks were wired and 73824cf saying the
flags made the path live. Neither was true, and no test I wrote would
have caught it -- they all exercise the expert backends instead.

Still open from that review: #3 (wrap_native_ddp runs on a meta-device
model before to_empty), #4 (a helper imports _NativeDDPPipelineStage from
core, where I moved it out of), and #15 (scale_native_ddp_loss defined
but never called, leaving gradients dp_degree x off).
saforem2 pushed a commit to samuelwheeler/torchtitan that referenced this pull request Oct 29, 2026
…instead of replaying them (pytorch#5123)

**TLDR:** Under FullAC, and under RegionAC without `ep_communication`
saved, DeepEP computes wrong gradients for the routed experts, the
router and the MoE input: at DeepSeek-V3 671B shapes the routed-expert
weight grads are 1.41 relative L2 off. This PR saves DeepEP's dispatch
and combine instead of replaying them in backward, as SelectiveAC
already does. Gradients now match a run without AC, and FullAC gets 4.8%
faster at 16k tokens per rank, for +1.1 GiB of saved activations per MoE
layer at 16k. A new 2-GPU test fails on main and passes here. It runs in
the H100 workflow, whose DeepEP install this PR also fixes.

**Problem**
1. DeepEP's dispatch op returns the received rows plus a handle that
records where each row came from. The backward of dispatch (a combine)
and of combine (a dispatch) both route gradients with that handle.
2. FullAC replays the block's forward in backward, so the dispatch runs
a second time (and the combine too). RegionAC does the same when
`ep_communication` is not in `save_regions`.
3. DeepEP assigns receive slots with atomics
(`deep_ep/include/deep_ep/impls/dispatch.cuh:345`), so the second
dispatch can receive the rows in another order.
4. The grouped GEMMs' activations now come from the second dispatch,
while their gradients are routed with the first dispatch's handle. Each
token's gradient meets another token's activations and score.
5. At 4k tokens per rank, 1 MoE layer: routed-expert weight grads 1.41
relative L2 off vs no AC, router grads 1.20, input grads 0.93. The
expert and router grads are uncorrelated with the right ones (cosine
similarity 0.01-0.03). The loss barely shows it: DSv3 debugmodel's
step-2 loss is 6.1263 with FullAC vs 6.1208 without.

```text
forward:          dispatch saforem2#1 receives A, B, C   (handle saforem2#1 records this order)
backward replay:  dispatch saforem2#2 receives B, A, C   -> grouped GEMM activations in order B, A, C
backward grads:   routed with handle saforem2#1          -> gradients in order A, B, C
                  A's gradient meets B's activations
```

**Solution**
1. Never replay DeepEP's comm: save the forward's outputs.
2. `deepep::dispatch` and `deepep::combine` are registered as ordered
effects. PyTorch's selective checkpointing saves an ordered-effect op
unless the policy explicitly asks `MUST_RECOMPUTE`
(`torch/utils/checkpoint.py:1618-1626`). That covers FullAC, SelectiveAC
and its subclasses; FullAC's docstring already relies on it.
3. `dispatch_tokens` and `combine_tokens` always retain their remat
regions, which covers RegionAC (torch_remat). Their `recompute` argument
is gone, and `ep_communication` in `save_regions` no longer affects
DeepEP.
4. Combine is saved too, because a replayed combine would look up a
handle the forward combine already removed from `_handle_cache`.
5. Unchanged: no AC, SelectiveAC (it already saved these ops), and
HybridEP, whose receive order is deterministic (FullAC grads bitwise
equal to no AC).

**Test**
1. `tests/unit_tests/gpu/test_deepep_activation_checkpoint.py` (2 GPUs)
applies FullAC, SelectiveAC and RegionAC with no saved regions to a
DeepEP MoE block.
2. It counts `ElasticBuffer.dispatch` and `combine` calls, and compares
every gradient with the same block without AC.
3. On main, FullAC and RegionAC call each op 3 times instead of 2 ("AC
replayed DeepEP: {'dispatch': 3, 'combine': 3}"), and the gradients are
0.95-1.31 relative L2 off. With this PR the counts match and the
gradients are bitwise equal at these sizes.
4. It skips without `deep_ep`, so the unit-test workflows skip it. The
H100 workflow runs it right after installing DeepEP, as the B200
workflow does for Dist-MoE.
5. That install has failed every night since 2026-09-30, so no DeepEP
test ran. It cloned DeepEP's default branch with `--recursive`, and
DeepEP's 2026-09-29 release added an SSH-only submodule there. This PR
clones without `--recursive`; the pinned commit's submodules are still
fetched after checkout.

**Results**
```text
DeepSeek-V3 671B shapes (D=7168, 256 experts, top-8), EP=8 over NVLink, 8x H100, bf16, eager + compiled SwiGLU region, main e5c5552
1 MoE layer, 4k tokens/rank: grad difference vs the same layer without AC, relative L2, worst of 8 ranks
                                               routed experts   router gate   MoE input
  FullAC, main                                 1.41             1.20          0.93
  FullAC, this PR                              2.7e-5           bitwise       6.3e-4
  RegionAC without ep_communication, main      1.41             1.21          0.93
  RegionAC without ep_communication, this PR   2.7e-5           bitwise       6.3e-4
  noise: no AC vs no AC                        2.7e-5           bitwise       6.3e-4
```
The noise comes from DeepEP's receive order (expert weight grads) and
the bf16 atomic adds in torchtitan's eager gather/scatter around the
grouped GEMM (input grads).

```text
2 MoE layers fwd+bwd under FullAC, ms per iteration, main -> this PR, median of 3 processes [range]
  4k tokens/rank     78.21 [77.75-79.04]   ->  74.29 [72.99-74.89]    -5.0%
  16k tokens/rank   274.71 [274.53-275.41] -> 261.41 [260.99-261.41]  -4.8%
saved activations, 2 layers:  114 -> 677 MiB at 4k,  456 -> 2705 MiB at 16k
SelectiveAC on main:          74.10 ms, 744 MiB at 4k;  256.97 ms, 2972 MiB at 16k
```

Training, DSv3 debugmodel, FSDP8+EP8, seed 0, step-2 loss / grad norm:
```text
no AC                6.12075 / 4.4591
SelectiveAC          6.12076 / 4.4592
FullAC, main         6.12634 / 4.4703
FullAC, this PR      6.12075 / 4.4592
```

NOTE: no recipe pairs DeepEP with FullAC or RegionAC today: the DeepEP
recipes and the CI test use SelectiveAC. Nothing rejects the
combination, and on main it trains with these wrong gradients without an
error.

NOTE: in DeepEP MoE layers, FullAC now saves almost as much as
SelectiveAC (677 vs 744 MiB for 2 layers at 4k), at the same speed at 4k
(74.3 vs 74.1 ms) and 1.7% slower at 16k (261.4 vs 257.0 ms). Attention
and dense layers are unchanged: FullAC still recomputes them.

NOTE: RegionAC configs without `ep_communication` now also keep DeepEP's
comm outputs (+281 MiB per MoE layer at 4k).

NOTE: needs torch nightly 20260926 or later: older torch registers the
effect, but its checkpointing still replays the ops. torchtitan's FullAC
already relies on the same mechanism.

NOTE: not run on GPU: pipeline parallelism. On a CPU probe with a fake
DeepEP buffer, FullAC + DeepEP under split input/weight backward (ZBV,
DualPipeV, InterleavedZeroBubble) now raises "Trying to backward an
extra time" instead of silently giving wrong gradients. SelectiveAC
already fails there, so DeepEP with these schedules has no working
activation checkpointing until the split backward supports saved
effectful ops.

You may ask:
- Why `_lib._register_effectful_op`, a private method?
`custom_op(...).register_effect` is the public form, but these ops are
defined with `torch.library.Library("deepep", "DEF")`, and
`register_effect` only calls `_lib._register_effectful_op` itself
(`torch/_library/custom_ops.py:605-606`).
- Why not add a `deepep` check to `_full_ac_policy`? It puts a backend
name in a generic policy, and a SelectiveAC subclass that overrides
`get_save_ops` without the deepep ops would replay them again (1.2
relative L2 on a CPU probe). The effect covers every policy.
- Why not keep replaying with a deterministic DeepEP buffer? DeepEP then
sorts every dispatch's rows: +7% at 4k and +4.5% at 16k per step,
measured without AC, plus the replay itself. It would keep FullAC's
memory.
- Why not replay as a cached dispatch with the forward's handle, which
gives the same order? The replayed call has no link to its forward call,
and a per-layer slot picks the wrong handle once pipeline parallelism
keeps several microbatches of a layer in flight.
- Why not reject FullAC with DeepEP in config validation? It works with
this fix.
- Why is the test not in the multi-GPU unit-test workflow? That workflow
doesn't install `deep_ep`, so the test would always skip there.

**Test plan**
- `pytest tests/unit_tests/gpu/test_deepep_activation_checkpoint.py` on
2x H100: passed all 8 runs on this PR; fails on main with the replay
counts above. Skips without `deep_ep`.
- Gradient check (script not in this PR): torchtitan's DSv3 671B config
cut to 1 MoE layer, EP=8, same inputs and weights, AC applied to the MoE
directly (`FullAC`, `SelectiveAC`, `RegionAC` with and without
`ep_communication`); all gradients compared with a run without AC.
Timing: the same harness with 2 MoE layers, 3 fresh processes per row,
no other process on the GPUs.
- Training: DSv3 debugmodel, FSDP8+EP8, 20 steps, no AC, SelectiveAC and
FullAC.
- CPU MoE and AC tests (`test_moe.py`, `test_expert_parallel.py`,
`test_inference_moe.py`, `test_config_validation.py`,
`test_transforms.py`, the DSv3, Qwen3.5 and GPT-OSS MoE tests) and
`tests/unit_tests/gpu/test_activation_checkpoint.py`: 98 passed.
Pyrefly: same 41 errors as main.
- DeepEP install: cloning without `--recursive`, checking out the pin
and updating submodules fetches only `third-party/fmt` (run locally; the
full CI job needs `ciflow/h100.8`).

Hardware: 8x H100 SXM, no RDMA NIC (`EP_DISABLE_GIN=1`), DeepEP v2.1.0
(`01dc3aa`). Torch 2.15.0.dev20260926 for the layer tests,
2.15.0.dev20261004 for training and the new test.

---------

Co-authored-by: Felipe Mello <[email protected]>
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.