Skip to content

Saforem2/blendcorpus - #1

Merged
saforem2 merged 43 commits into
saforem2:saforem2/blendcorpusfrom
auroraGPT-ANL:saforem2/blendcorpus
Oct 7, 2025
Merged

saforem2 merged 43 commits into
saforem2:saforem2/blendcorpusfrom
auroraGPT-ANL:saforem2/blendcorpus

Conversation

@saforem2

Copy link
Copy Markdown
Owner

Copilot Summary

This pull request introduces comprehensive support for training with BlendCorpus in TorchTitan. The main changes add a new experiment module, dataset adapters, tokenizer integration, configuration schema, and documentation, enabling seamless use of BlendCorpus datasets and SentencePiece tokenization. These changes allow users to select BlendCorpus as a dataset, configure training via TOML, and resume training accurately from checkpoints.

BlendCorpus experiment integration:

  • Added new module torchtitan/experiments/blendcorpus, including model configs, dataloader builder, tokenizer support, and experiment registration for BlendCorpus training. This enables users to run experiments with BlendCorpus datasets and models such as Llama3 and AuroraGPT.

Tokenizer and dataloader support:

  • Implemented a SentencePiece tokenizer adapter (SPTokenizer) and a tokenizer router that supports both SentencePiece and HuggingFace tokenizers, with configuration via tokenizer_backend. [1] [2]
  • Added an external dataloader adapter (AdapterDL) that wraps BlendCorpus datasets to provide TorchTitan-compatible batches and supports advancing data position after checkpoint restore.

Configuration and experiment wiring:

  • Extended the configuration schema with a new [blendcorpus] TOML section and dataclass, exposing BlendCorpus-specific options such as data paths, batching, and loader behavior.
  • Modified experiment initialization to support dynamic importing of BlendCorpus and other experiments, ensuring robust startup even if some experiment modules are unavailable.

Documentation and usage examples:

  • Added a detailed README (torchtitan/experiments/blendcorpus/README.md) describing all changes, configuration options, example TOML files, and instructions for running BlendCorpus experiments in TorchTitan.

Logging improvements:

  • Updated logging initialization to use get_logger for better consistency and modularity.

Updated instructions for cloning the repository and setting up the environment. Added installation commands for dependencies.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Sorry @saforem2, your pull request is larger than the review limit of 150000 diff characters

mreso and others added 7 commits September 23, 2025 09:08
…tion (pytorch#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 (pytorch#1730)

This PR resolves the `datasets` import error that were introduced in
pytorch#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 pytorch#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
@saforem2
saforem2 merged commit ebd85db into saforem2:saforem2/blendcorpus Oct 7, 2025
saforem2 added a commit that referenced this pull request May 12, 2026
Three lint hits surfaced by CI on the new files in #13:

- **ufmt**: applied the formatter's reformatting to the three new
  `experiments/ezpz/moe/` files (import grouping, comprehension
  collapse, line-wrap nits in `model.py`).
- **flake8 N801**: pre-existing class names `moeTransformerBlock` /
  `moeModel` violate CapWords, but renaming would touch every
  callsite outside of this PR's scope. Suppressed in-place with
  `# noqa: N801` on the two class declarations.
- **codespell**: a quoted upstream PR title in
  `experiments/ezpz/docs/upstream-sync.md` contains "Reenable" which
  codespell flags as "Re-enable". Added a `<!-- codespell:ignore-line -->`
  marker so the historical quote stays verbatim. Strictly inside
  `experiments/ezpz/` per Golden Rule #1 — no edits to core
  `pyproject.toml`.
saforem2 added a commit that referenced this pull request Jun 2, 2026
ProcessGroupXCCL inherits Backend::supportsSplitting() == false (it
never declares an override; NCCL does). DeviceMesh._init_one_process_group
(torch 2.13, device_mesh.py:550-562) still routes nested mesh PG
creation through split_group whenever the default group has
bound_device_id set + the accelerator is available. xccl always sets
bound_device_id under our eager-init pathway, so the gate always
takes the broken branch and raises:

    RuntimeError: No backend for the parent process group or its
                  backend does not support splitting

This blocks every nested mesh build on XPU, including the EP-flavored
sparse mesh that ParallelDims.build_mesh constructs unconditionally
for moe_2b_ep.

Workaround installs from FaultTolerantTrainer.init_distributed. The
wrapper detects xccl, inspects the parent backend's supports_splitting,
and on False temporarily clears bound_device_id so the upstream gate's
first clause falls through to the existing new_group loop (the same
path xccl uses successfully in single-mesh configs). bound_device_id
is restored in the finally so FSDP2 eager-init bookkeeping stays
intact. No-op on cuda/cpu builds; idempotent.

Per Golden Rule #1, no upstream file was touched. Full diagnosis +
removal criteria (upstream needs both an override and a working
xcclCommSplit impl) in docs/upstream-issues/xccl_split_group_unsupported.md.
saforem2 pushed a commit that referenced this pull request Jun 7, 2026
…nto canonicalize_graph_pass (pytorch#3488)

## Summary

Two related graph-pass changes in `graph_trainer`:

1. **Add `remove_b2b_transpose_pass`** — collapses back-to-back
`aten.t(aten.t(x))` transpose pairs. These appear in traced fwd+bwd
graphs from `F.linear` when `simple_fsdp` redistributes weight tensors.
Two consecutive `aten.t` form an involution (identical shape *and*
strides), so removing them is **bitwise numerics-preserving**. The pass
also handles chains (`t(t(t(x))) -> t(x)`) and keeps the inner transpose
when it still feeds other consumers.

2. **Bundle the no-op cleanup passes into a single
`canonicalize_graph_pass` entry** in `compile_time_passes`:
   - `remove_detach_pass`
   - `remove_identity_view_pass`
   - `remove_b2b_transpose_pass`
   - `remove_identity_slice_pass`
   - `normalize_view_ops_as_reshape`

`normalize_view_ops_as_reshape` moves from `passes.py` into
`remove_noop_passes.py` alongside the other graph-cleanup passes. The
sub-passes stay public so each is unit-tested in isolation.

## Why

The cleanup passes are all numerics-preserving local rewrites that ran
as four separate pass-list entries. Folding them into one
`canonicalize_graph_pass` keeps `compile_time_passes` readable and
groups them as one logical step, while the new b2b-transpose rewrite
removes redundant transpose pairs that `F.linear` + FSDP introduce.

## Behavior note

`--compile.disable_passes` now toggles `canonicalize_graph_pass` as a
whole rather than the individual sub-passes. No callsite
(configs/scripts/README) disabled them individually, so nothing breaks.

## Verification

Ran the llama3 debug model (FSDP=4, TP=2, `aot_fx_trace`,
`--compile.debug_graph_passes`). `remove_b2b_transpose_pass` logs its
removal count directly:

```
[rank0]:[titan] - root - INFO - Removed 129 back-to-back transpose node(s) from the graph
```

`canonicalize_graph_pass` is pass #1; its op-count diff confirms the
same 129 nodes (`t.default: 215 -> 86`):

```
nodes: 2460 -> 1851 (-609)
  t.default:        215 -> 86  (-129)   <- remove_b2b_transpose_pass
  detach.default:    40 -> 0   (-40)
  view.default:     634 -> 0   (-634)
  _unsafe_view:      43 -> 0   (-43)
  slice.Tensor:      40 -> 0   (-40)
  reshape.default:    0 -> 277 (+277)
```

3 training steps, loss `8.11353 -> 7.80330 -> 7.09355`.

## Test plan

```bash
pytest torchtitan/experiments/graph_trainer/tests/test_passes.py \
  -k "TestRemoveB2BTransposePass or TestCanonicalizeGraphPass or \
      TestNormalizeViewOpsAsReshape or TestRemoveDetachPass or \
      TestRemoveIdentityViewPass or TestRemoveIdentitySlicePass"
```

Added `TestRemoveB2BTransposePass` (pair removal + numerics, lone
transpose kept, inner transpose with another user kept, chain collapse,
no-op on transpose-free graphs) and `TestCanonicalizeGraphPass`
(end-to-end bundle). All pass; `pre-commit run --all-files` clean.
@saforem2 saforem2 mentioned this pull request Jun 11, 2026
saforem2 added a commit that referenced this pull request Jul 27, 2026
Appendix A (80B NaN): the full run ladder (8574385/8661293 identical NaN ->
optimizer-independent; 8537349 fp32-params clean; 8671046 per-block-fp32res
clean@4N but 8671243 NaN@dp=192; 8673658 full-depth-fp32res NaN@dp=192). Narrows
the overflow to bf16 sublayer compute (attn scores / FFN), not the residual ->
cheap untried fixes = QK-Norm + attention softcap (both in-tree, unused by 80B).

Appendix B (SFT 384-rank fault): deterministic GPU NotPresent-Write at step 1-2
via oneCCL; failing jobs 12470336/338/339 (+12468348/371/398); VERIFIED 2N-clean
repro _diag_bigmix_2n_len1024.sh (12470343, 24 ranks); rank-221-across-nodes,
OOV-ruled-out, base-independent. Onset near the same ~186-192 dp boundary as the
80B wall. Wired asks #1/#3 to the appendices.
saforem2 added a commit that referenced this pull request Jul 29, 2026
The 75/25 owm/edu winner showed the 25% slot is the lever; Wave 3 swaps generic
edu for SCIENCE-dense corpora (DOE-mission version). Same recipe (MDS fork,
constant LR 2e-6, 10B tok, 75/25) -- only the 25% source changes.
- agpt_2b_mds_mix_owm_cosmo_7525: 75%% owm / 25%% cosmopedia-science (synthetic
  STEM textbooks: auto_math_text+khanacademy+openstax+stanford+wikihow, symlinked
  flat -> cosmopedia_science_local, 36 parquet, 'text' col verified). READY.
- agpt_2b_mds_mix_owm_nemotron_7525: 75%% owm / 25%% Nemotron-CC-Math-4+ (memo's
  #1 science lever). GATED corpus -- needs HF access + precache. Config staged.
- _agpt_2b_mds_mix_blend_src: generalized owm/<src> blend builder.
- datasets.py: register cosmopedia_science_local (local parquet).
- build_math_holdout.py: --pes2o flag -> common-pile/peS2o scientific-paper
  holdout (the DISJOINT science judge; allenai/peS2o is a dead loading-script
  repo, common-pile is the parquet mirror). allenai peS2o is in olmo-mix (off
  limits as a stage-2 add) but no arm trains on it -> clean arm-vs-arm signal.
- mix_ab.sh: preflight cases for owm_cosmo_* / owm_nemotron_* (both sources
  resolve before alloc burn); _check_local resolver for registered local dirs.
Eval: peS2o NLL primary + MMLU-STEM confirmatory; FineMath+wikitext retention.
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 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]>
saforem2 added a commit that referenced this pull request Nov 4, 2026
Two-stage lineage proven: B2 (ckpt-900 -> gsm8k-r1cot, 93 steps) = 0.205
GSM8K-CoT, best of everything tried. Single-stage rebuilds (B3/B4) failed
at 0.02-0.065. Next lever per POST-TRAINING-2B.md #1: stronger cold-start
with better CoT data.

B2v2 keeps the two-stage structure, swaps stage-2 data from narrow
GSM8K-only to broad frontier CoT (OpenThoughts-114k-decontam + gsm8k-r1cot,
GSM8K-decontaminated, same <think>/<answer> envelope). Wired via
mix-spec so weights are tunable without code changes.

Queued on Sunspot: 12482292 (consolidate ckpt-900) -> 12482293 (2N/1ep smoke).
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.

6 participants