Skip to content

Refactor model configuration and parallelization ownership - #4810

Merged
tianyu-l merged 1 commit into
mainfrom
model_spec
Sep 22, 2026
Merged

tianyu-l merged 1 commit into
mainfrom
model_spec

Conversation

@tianyu-l

@tianyu-l tianyu-l commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

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.

@pytorch-bot pytorch-bot Bot added ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl labels Sep 21, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Sep 21, 2026
@tianyu-l
tianyu-l force-pushed the model_spec branch 2 times, most recently from fe8f3c1 to 4cf26f9 Compare September 21, 2026 01:25
f"{type(self).__name__} must implement preprocess_inputs()."
)

def verify_module_protocol(self) -> None:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

capability merged into _parallelize() as it's executed recursively for every module already

@tianyu-l

Copy link
Copy Markdown
Contributor Author

GraphTrainer is the same on main
torch.fx.experimental.symbolic_shapes.GuardOnDataDependentSymNode: Could not extract specialized integer from data-dependent expression u41 (unhinted: u41).
cc @aditvenk

)
from torchtitan.models.common.param_init import depth_scaled_std
from torchtitan.models.deepseek_v3.parallelize import (
parallelize_deepseekv3 as parallelize_deepseek_v4,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

It seems like removing this got rid of apply_fsdp_to_mtp_decoder used in parallelize_deepseekv3. And DSv4 just inherits from Decoder not MTPDecoder, so the specific fsdp behavior is lost.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch. DeepSeek V4 was falling back to Decoder._apply_fsdp(), which does not treat its separate mtp_layers as decoder-layer FSDP units. I added a DeepSeekV4Model._apply_fsdp() override that follows MTPDecoder and calls apply_fsdp_to_mtp_decoder(), plus a regression test. Updated in 4c7729c.

@wwwjn wwwjn left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This refactor looks great to me


multimodal_encoder_fqns: tuple[str, ...] = ()

def parallelize(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

nit: in human note part, you note that this fuction should be named as _parallelize() ?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Model.parallelize() still exist as public entry point
Module.parallelize() becomes Module._parallelize()

@tianyu-l
tianyu-l merged commit b9e1d1f into main Sep 22, 2026
27 of 30 checks passed
tianyu-l pushed a commit that referenced this pull request Sep 22, 2026
…4829)

## Summary

#4810 deleted `ModelSpec` and per-model `parallelize.py`.
`Trainer.Config.model` (and `Controller.Config.model`) is the
Suppress-annotated field. Four docs still used the old names, so
copy-paste snippets fail with `TypeError: unexpected keyword argument
'model_spec'` or point at a file that no longer exists.

Same class of stale-path cleanup as #4805.

- `torchtitan/config/README.md`: `Trainer.Config(model=...)` and
`Trainer.Config.model` in the CLI-freeze paragraph
- `torchtitan/rl/README.md`: `Controller.Config(model=...)`
- `torchtitan/overrides/README.md`: FQN example
`model.layers.0.feed_forward`
- `torchtitan/models/llama3/README.md`: point at `sharding.py` and
`BaseModel.parallelize()` instead of `parallelize.py`

Docs only. No behavior change.

Fixes #4827.

## Test plan

- [ ] Confirmed each replacement path exists on this branch
(`Trainer.Config.model`, `Controller.Config.model`,
`llama3/sharding.py`, `BaseModel.parallelize`)
- [ ] Grepped the four files for leftover `model_spec=` Config keywords
and `parallelize.py`
tianyu-l added a commit that referenced this pull request Sep 26, 2026
…age Cache Adapter for Attention Residual (#4312)

### Summary

Adds pipeline parallelism to the Kimi K3 text decoder. Before this
change `parallelize.py` rejects `pipeline_parallel_degree > 1`.

Core's `pipeline_llm` splits the model at layer boundaries and carries
one hidden state tensor per hop, which cannot express Block Attention
Residuals: every later stage needs every earlier block's residual, and
the final aggregation (`output_res_proj`, then `output_res_norm`) must
run only on the stage that owns `lm_head`.

After it, `pipeline_kimi_k3` (`kimi_k3/pipeline_parallel/__init__.py`)
takes core's split through `pipeline_with_first_last_stage_modules`,
which now pins modules to the last stage as well as the first: the
vision tower with the embedding, the aggregation with the head.

The schedule is built on `AttnResPipelineStage`, a
`torch.distributed.pipelining.PipelineStage` subclass. A hop carries
(*hidden*, *delta*), *delta* being the block residuals the receiving
rank has not seen yet; each rank keeps the blocks it has seen in one
store shared by its virtual stages, and the backward returns every
block's gradient along the same routes.

Step 1 is identical to the single GPU reference in every cell. With the
total grad norm taken in fp32, the whole stack pipeline cells (pp2, pp4,
pp2 / pp4 x vp2 / vp4 with the cache off) stay identical to the
reference for 100 steps in the bf16 cells, the loss on every step and
the grad norm on every step but one last-digit print in two of the six.

In bf16 that norm, and the clip factor it sets every step at this scale,
depend on how the pipeline groups the parameters
(pytorch/pytorch#194033).

The cached cells differ only in the order in which a cached block's
gradient contributions are added. A CPU test with integer valued block
gradients shows the routing itself exact, bitwise against a single
device closed form, cache on and off, over three optimizer steps.

### Design

What forces the protocol: every layer attends over all earlier blocks
plus the running partial block. So (R1) the block stack must cross every
stage boundary with the hidden state, (R2) the final aggregation runs
only on the stage that owns `lm_head`, and (R3) the stack grows with
depth, with a boundary inside a block putting a partial block on the
wire.

Sending the whole stack every hop satisfies all three and costs bytes
that grow with the stage index. The delta transport sends only what the
receiver lacks, which needs the routing tables, a micro batch key that
survives P2P, and a way home for the gradient of a block a stage read
from its own rank.

<img width="1080" height="540" alt="pp_attnres_cache"
src="https://github.com/user-attachments/assets/55eb0380-99ec-419e-9a08-d3424c83e781"
/>


Why the rank store is enough: the schedule assigns stages $S = v \cdot P
+ R$, so a micro batch returns to the same rank every $P$ stages, and
that rank already holds every block committed at stages $\le S-P$.

A freshly committed block is therefore new on the wire for $P-1$ hops
and no longer. The same rank consumers of a block are exactly the stages
congruent to its producer modulo $P$, and their number is what the
tables expect as gradient deposits.

<img width="1080" height="540" alt="pp_attnres_cache_example"
src="https://github.com/user-attachments/assets/aa4f7fca-b9f4-4f3b-83fd-2be6f9b18bc9"
/>



- The stage protocol, in the subclass
(`kimi_k3/pipeline_parallel/stage.py`)
- `forward_one_chunk` assembles the full block stack the model expects
from the rank's store plus the received *delta*, runs the stage, keeps
the blocks the stage committed, and sends on only what the next rank
lacks. The model takes and returns the whole stack and knows nothing of
the transport; the chunk id comes with the call.
- `backward_one_chunk` reads the gradient of the assembled stack, an
autograd leaf the stage owns: the received columns go back as the
*delta*'s gradient, dense and in wire order, the stored columns are
deposited in the rank store. The leaf is detached, so whether the
previous stage wants a delta gradient is read off the receive metadata,
which the stage checks describes (hidden, delta).
- The stage that committed or received a block collects those deposits
into its own incoming gradient (`_retrieve_recv_grads`) before its
backward. The store names no schedule class: it relies only on orderings
every schedule gives by data dependency, a rank's stages running forward
in increasing stage order and backward in decreasing, and the deposit
count check fails loudly if one is missing or extra.
- A micro batch's blocks are released after the rank's last stage
forward for it, so the store holds only the in flight micro batches.
- Forward only passes: `schedule.eval`, which the validator runs, calls
`backward_one_chunk` with the backward disabled; the stage returns and
drops the forward's bookkeeping instead of reading a gradient cache it
never filled. A payload whose blocks have nothing trainable upstream (a
frozen embedding under LoRA) gets no gradient, and its deposits are
discarded.
- Metadata inference runs the same assembly (`_compute_outputs`);
`_compute_input_grads` returns dense gradients, which is where the P2P
buffer finding below is handled.
- The routing tables (`kimi_k3/pipeline_parallel/layout.py`)
- `BlockLayoutTables` simulates one micro batch's forward in stage order
over the split the trainer actually applied and tabulates, per stage,
the blocks it commits, the blocks its rank already holds, and the blocks
its P2P must carry; sender and receiver compute the same tables, so
nothing but the delta travels.
- The layer to stage map is read off the split, which every rank
computes, with no collective; the stage to rank map is the schedule's
own `stage_index_to_group_rank`. Uneven stages are allowed; a block
boundary inside a stage is a partial block on the wire.
- Why the delta is bounded: with $P$ ranks a block committed at stage
$S$ is fresh on the wire for $P-1$ hops; from $S+P$ on every receiving
rank already holds it, because its previous virtual stage was $S-P$. The
per hop payload is bounded by the commits of the last $P-1$ stages,
independent of depth.
- `attn_res_cache=False`, a parameter of `pipeline_kimi_k3`, sends the
whole stack on every hop; the two transports differ only in the tables,
which makes them the A/B in the results. With the cache on,
`pipeline_kimi_k3` checks the schedule's stage-to-rank map for the
loop-style assignment the rank store assumes (stage `s` on rank `s %
pp`) and refuses any other, naming the schedule and the first stage off
it; v-shaped schedules are out of scope.
- Plain `1F1B` is the naive transport by construction, so the two are
bitwise there; with more than one stage per rank they are not, since the
cached path sums the same gradient contributions in a different
association.
- The split is core's. `pipeline_with_first_last_stage_modules` takes
`last_stage_module_fqns` and appends the ones the model has to the last
stage, the mirror of what it does for the first; Kimi K3 pins the vision
tower to the first stage, `output_res_proj` and `output_res_norm` to the
last.
- `return_split=True` hands the applied split back to a model that
routes along it, so Kimi K3 reads it off the call rather than deriving
it again; `pipeline_llm` and the trainer's contract are untouched, and
the five upstream models that hand the helper to the trainer as their
`pipelining_fn` only follow the rename.
- The stages: core's `pipeline_llm` constructs plain `PipelineStage`s,
as on main; K3 rebuilds each one the schedule holds as an
`AttnResPipelineStage` from the constructed stage's own fields and puts
it back in the schedule.
- The seam that is missing is a `stage_class` argument on
`pipeline_llm`; until it exists the rebuild reads the schedule's
`_stage` / `_stages` and the stage's mesh callback, and the stage
imports `flatten_args` from `pipelining._utils`.
- The model (`model.py`): the first layer of a block joins the stack
before its sub layers attend, so a stage boundary at a block start needs
nothing special and the stack a stage receives is exactly the stack the
layers read; the head owning stage alone runs the aggregation.
- Core: `module_fqns_per_model_part` becomes
`pipeline_parallel_module_fqns_per_model_part`, the prefix every other
pipeline field carries.
- The helper refuses `layers_per_stage` at its top, since the split it
derives is sized by the schedule's default stage count; the copy it
hands `pipeline_llm` carries that split and nothing else of the user's
config changes. A different stage count is spelled out, as the pp4 x vp4
recipe does.
- The shared `debugmodel` flavor is 17 layers, four runs of (3 KDA + 1
MLA) and a closing MLA as the 93 layer model has, in blocks of 4 (four
full blocks and a partial one): dim 256 with 4 heads, 8 experts with top
2, a 2 layer vision tower, vocabulary 2048 against the 2020 token test
tokenizer, 25.8 M parameters from 1.4 B.
- Why 17: nine layers already have every path the transport takes, and
17 is the least depth in that pattern whose 19 units split into the 16
stages of pp4 x vp4, which the results below run.
- The CI cell is pp4 x vp4 on its own recipe
(`kimi_k3_debugmodel_pp4_vp4`, `torchtitan_recipes/tests/b200.py`),
typechecking off as in every pipeline recipe upstream: sixteen stages,
one layer per stage from layer 5 on, the head alone on the last, the
second block opening inside stage 2; every path of the transport and
every gradient deposit on four GPUs.
- The pp2 x vp2, pp4 x vp2 and pp2 x vp4 rows of the results run from
local flavors (core's default split for the vp2 shapes, an 8 stage split
spelled out for pp2 x vp4); nothing of them is in the PR.
- What this replaced: the first reviewed version carried the same
protocol in a 1228 line adapter that wrapped `forward_one_chunk`,
`backward_one_chunk` and `step`, kept a thread local micro batch id, and
bridged the same rank gradient path with a tensor grad hook and an
autograd Function. The subclass implements it once, on the stage's own
methods.

### Results

4 x H100, `kimi_k3_debugmodel` (17 layers, dim 256) reading `c4_test` as
text-only 256-token rows, four 256-token micro-batches per rank, one
seed checkpoint per batch shape, total grad norm in fp32. Each cell
gives the raw value and, beneath it, the change against the reference.
Measured at `ce67cece4` on main `7349a2282` (the two commits after it
change a guard's form and an error's type, not a computation).

One compile lineage per table: the reference runs once cold to fill the
inductor and Triton caches and once more on a copy of both, and that
second run is the reference; every other cell runs on a copy of the same
two caches. The bf16 cold fill is the last row of the first table: on
this box it reproduces the warm rerun bitwise, as the fp32 one does,
while the dp2 lineage's cold fill picks other kernels and differs from
step 2, which is why every cell runs on the warm reference's cache.

None of the following is part of this PR:

- the c4 flavors (`kimi_k3_debugmodel_c4`, `_pp_naive`, `_8stages`,
`_16stages`, the last the CI recipe's split), the switches
`ATTN_RES_NAIVE` (after #4810 the model owns its pipelining, so a switch
stands in for the removed `pipelining_fn` partial), `NOSYNC_GA`,
`MB_REVERSE`, `GN_FP32`, and the KDA capability guard lifted for SM90:
[probe_apply_h100.py](https://github.com/QIU023/torchtitan_attention_residual/blob/ed66938/Raising_PRs/PR_K3_PARALLELISM/logs_pp_round4_2026-09-23_h100/kit/probe_apply_h100.py)
- the whole matrix, and the seed checkpoint and cache handling above:
[run_pp_h100.sh](https://github.com/QIU023/torchtitan_attention_residual/blob/ed66938/Raising_PRs/PR_K3_PARALLELISM/logs_pp_round4_2026-09-23_h100/kit/run_pp_h100.sh)

```bash
python probe_apply_h100.py . && export GN_FP32=1   # c4 flavors, the switches, the total grad norm in fp32
COMMON="-m torchtitan.train --module kimi_k3 --debug.seed 42 --debug.deterministic --metrics.log_freq 1 --training.num-tokens-per-train-step 1024 --training.num-tokens-per-microbatch-per-dp-rank 256 --parallelism.data_parallel_shard_degree 1"
torchrun --nproc_per_node=1 $COMMON --config kimi_k3_debugmodel_c4_seed --training.steps 1 --dump-folder seed
cell() { d=$1; n=$2; c=$3; src=$4; shift 4; rm -rf $d; mkdir -p $d; cp -r seed/checkpoint $d/; [ -d cache_$src ] && cp -r cache_$src cache_$d; TORCHINDUCTOR_CACHE_DIR=cache_$d/inductor TRITON_CACHE_DIR=cache_$d/triton torchrun --nproc_per_node=$n $COMMON --config $c --training.steps 100 "$@" --dump-folder $d; }
P2="--parallelism.pipeline_parallel_degree 2 --parallelism.num-pp-microbatches 4"; P4="--parallelism.pipeline_parallel_degree 4 --parallelism.num-pp-microbatches 4"; IL="--parallelism.pipeline_parallel_schedule Interleaved1F1B"
NOSYNC_GA=1 cell ref_cold 1 kimi_k3_debugmodel_c4 none; NOSYNC_GA=1 cell ref 1 kimi_k3_debugmodel_c4 ref_cold   # the second run is the reference
cell dp1 1 kimi_k3_debugmodel_c4 ref; MB_REVERSE=1 cell reversed 1 kimi_k3_debugmodel_c4 ref
cell pp2 2 kimi_k3_debugmodel_c4 ref $P2; cell pp4 4 kimi_k3_debugmodel_c4 ref $P4
cell vp2_cached 2 kimi_k3_debugmodel_c4 ref $P2 $IL; cell vp2_naive 2 kimi_k3_debugmodel_c4_pp_naive ref $P2 $IL   # pp4 x vp2 likewise with $P4
cell pp2vp4_cached 2 kimi_k3_debugmodel_c4_8stages ref $P2 $IL; cell pp4vp4_cached 4 kimi_k3_debugmodel_c4_16stages ref $P4 $IL   # local flavors with the splits spelled out; _naive variants likewise
# dp2 table: --parallelism.data_parallel_shard_degree 2 --training.num-tokens-per-train-step 2048, its own seed checkpoint, reference and cache
```

| cell | loss, step 1 | step 10 | step 50 | step 100 | grad norm, step 1
| step 10 | step 50 | step 100 |
| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| dp1 [1] | `8.003520` | `3.488880` | `2.584620` | `2.511720` | `2.2337`
| `1.3804` | `0.6772` | `0.7861` |
| dp1, stock accumulation [4] | `8.003520`<br>identical |
`3.485760`<br>-0.09% | `2.588440`<br>+0.15% | `2.511260`<br>-0.02% |
`2.2337`<br>identical | `1.3846`<br>+0.30% | `0.6855`<br>+1.23% |
`0.7832`<br>-0.37% |
| dp1, micro-batches reversed [5] | `8.003520`<br>identical |
`3.485890`<br>-0.09% | `2.587830`<br>+0.12% | `2.509630`<br>-0.08% |
`2.2338`<br>+0.00% | `1.3743`<br>-0.44% | `0.6857`<br>+1.26% |
`0.7884`<br>+0.29% |
| pp2 | `8.003520`<br>identical | `3.488880`<br>identical |
`2.584620`<br>identical | `2.511720`<br>identical |
`2.2337`<br>identical | `1.3804`<br>identical | `0.6772`<br>identical |
`0.7861`<br>identical |
| pp4 | `8.003520`<br>identical | `3.488880`<br>identical |
`2.584620`<br>identical | `2.511720`<br>identical |
`2.2337`<br>identical | `1.3804`<br>identical | `0.6772`<br>identical |
`0.7861`<br>identical |
| pp2 x vp2, naive [2] | `8.003520`<br>identical |
`3.488880`<br>identical | `2.584620`<br>identical |
`2.511720`<br>identical | `2.2337`<br>identical | `1.3804`<br>identical
| `0.6772`<br>identical | `0.7861`<br>identical |
| pp2 x vp2, cached | `8.003520`<br>identical | `3.484850`<br>-0.12% |
`2.586430`<br>+0.07% | `2.510560`<br>-0.05% | `2.2337`<br>identical |
`1.3904`<br>+0.72% | `0.6782`<br>+0.15% | `0.7908`<br>+0.60% |
| pp2 x vp4, naive [2][3] | `8.003520`<br>identical |
`3.488880`<br>identical | `2.584620`<br>identical |
`2.511720`<br>identical | `2.2337`<br>identical | `1.3804`<br>identical
| `0.6772`<br>identical | `0.7861`<br>identical |
| pp2 x vp4, cached [3] | `8.003520`<br>identical | `3.484350`<br>-0.13%
| `2.585380`<br>+0.03% | `2.509430`<br>-0.09% | `2.2337`<br>identical |
`1.3920`<br>+0.84% | `0.6719`<br>-0.78% | `0.7819`<br>-0.53% |
| pp4 x vp2, naive [2] | `8.003520`<br>identical |
`3.488880`<br>identical | `2.584620`<br>identical |
`2.511720`<br>identical | `2.2337`<br>identical | `1.3804`<br>identical
| `0.6772`<br>identical | `0.7861`<br>identical |
| pp4 x vp2, cached | `8.003520`<br>identical | `3.487100`<br>-0.05% |
`2.584950`<br>+0.01% | `2.508500`<br>-0.13% | `2.2337`<br>identical |
`1.3682`<br>-0.88% | `0.6786`<br>+0.21% | `0.7855`<br>-0.08% |
| pp4 x vp4, naive [2][3] | `8.003520`<br>identical |
`3.488880`<br>identical | `2.584620`<br>identical |
`2.511720`<br>identical | `2.2337`<br>identical | `1.3804`<br>identical
| `0.6772`<br>identical | `0.7861`<br>identical |
| pp4 x vp4, cached [3] | `8.003520`<br>identical | `3.486570`<br>-0.07%
| `2.585890`<br>+0.05% | `2.509130`<br>-0.10% | `2.2339`<br>+0.01% |
`1.3861`<br>+0.41% | `0.6705`<br>-0.99% | `0.7889`<br>+0.36% |
| dp1, second cold compile [6] | `8.003520`<br>identical |
`3.488880`<br>identical | `2.584620`<br>identical |
`2.511720`<br>identical | `2.2337`<br>identical | `1.3804`<br>identical
| `0.6772`<br>identical | `0.7861`<br>identical |

- [1] reference: the micro-batches accumulate with the gradient sync on
the last one, as the pipeline does (`NOSYNC_GA`); the logged loss is the
sum of the four micro-batch losses in one reduction, as the pipeline's
last stage logs it
- [2] naive transport, the whole block stack on every hop
(`attn_res_cache=False`); "cached" rows use the rank store, the default
- [3] 8 and 16 stages with the split spelled out, since no
`layers_per_stage` reaches them for 19 units: the 16 stage split is the
CI recipe's, the 8 stage one a local flavor's (`probe_apply.py` above)
- [4] stock accumulation: the gradient sync on every micro-batch (the
flavor's default), the same data and cache
- [5] the four micro-batches in reverse order, the same data and cache:
the floor of a bf16 sum order change
- [6] the same code, data and seed compiled a second time from an empty
cache: on this box it picks the same kernels and is identical to the
reference on all 100 steps
- pp2, pp4 and the four naive rows are identical to the reference on all
100 steps in the loss; in the grad norm pp4 and three naive rows on all
100 steps, pp2 and pp2 x vp4 naive on 99, with step 37 printing `1.2084`
against `1.2085`, one unit in the last digit: under PP core's
`clip_grad_norm_` squares each rank's norm, all-reduces and takes the
root, another summation order than one device's single `vector_norm`,
and the bf16 parameters absorb it
- the fp32 end to end comparison the review thread asked for, cache on
and off, is in that thread

dp2, 2048 tokens per step, same protocol.

| cell | loss, step 1 | step 10 | step 50 | step 100 | grad norm, step 1
| step 10 | step 50 | step 100 |
| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| dp2 [1] | `8.059690` | `3.411970` | `2.565870` | `2.366000` | `2.0111`
| `1.4686` | `0.5743` | `0.6493` |
| dp2 x pp2 | `8.059690`<br>identical | `3.411970`<br>identical |
`2.565870`<br>identical | `2.366000`<br>identical |
`2.0111`<br>identical | `1.4686`<br>identical | `0.5743`<br>identical |
`0.6493`<br>identical |
| dp2 x pp2 x vp2, naive [2] | `8.059690`<br>identical |
`3.411970`<br>identical | `2.565870`<br>identical |
`2.366000`<br>identical | `2.0111`<br>identical | `1.4686`<br>identical
| `0.5743`<br>identical | `0.6493`<br>identical |
| dp2 x pp2 x vp2, cached | `8.059690`<br>identical |
`3.412200`<br>+0.01% | `2.564320`<br>-0.06% | `2.368620`<br>+0.11% |
`2.0111`<br>identical | `1.4784`<br>+0.67% | `0.5711`<br>-0.56% |
`0.6455`<br>-0.59% |

- [1] [2] as above; dp2 x pp2 and the naive row are identical to the
reference on all 100 steps, loss and grad norm. This lineage's cold fill
differs from its warm rerun from step 2 (autotune), so every row runs on
the warm reference's cache

The KDA capability guard was widened locally to admit SM 9.0 for these
runs; it is not part of this PR.

### Test plan

- CPU, in the default unit test suite: `test_kimi_k3_pp_block_grads.py`
(the real `AttnResPipelineStage` under `ScheduleInterleaved1F1B` on four
gloo ranks with integer block gradients, bitwise against cache off and a
single device closed form over three steps, bf16 and fp32, a forward
only pass between steps), `test_kimi_k3_pp_layout.py` (the routing
tables on uneven splits, the 8 and 16 stage splits, the loop-style
guard), `test_kimi_k3_pp_stage.py` (assembly, routing, the gradient
split, the forward only return, the stage rebuild on one gloo rank),
`test_pipeline_parallel.py` (the helper: both ends pinned, the split
handed back, the caller's config untouched), `test_config_manager.py`
(the renamed field), `test_integration_test_definitions.py` (the two
B200 cells): `pytest tests/unit_tests/cpu -k "kimi_k3 or pipeline or cli
or integration_test or config_manager" -q`, 107 passed.
- B200 suite: `kimi_k3_pp4_vp4` (four GPUs, sixteen stages, one layer
per stage from layer 5 on, the head alone on the last stage, the second
block opening inside stage 2); `kimi_k3_mm` unchanged.
- The tables above: 100 steps per cell on 4 x H100, every cell against a
single device reference on the same seed checkpoint and compile lineage.

### A `torch.distributed.pipelining` finding

With one layer per stage the last stage holds only the head, whose first
op on the block stack is a `cat`, so autograd hands the stage's input
gradients back as views.

`PipelineStage._backward_metadata_inference` records those strides,
`_create_grad_recv_info` allocates the receive buffer with
`torch.empty_strided`, and c10d rejects it at the first `RECV_B` with
"Tensors for P2P must be non-overlapping and dense".

Every other split passed because a later op consumed the input and
autograd accumulated a dense gradient. The subclass returns dense
gradients from `_compute_input_grads`; the library-side fix would be a
dense `torch.empty` receive buffer and `.contiguous()` before the send.

---------

Co-authored-by: tianyu-l <[email protected]>
aryamazaheri added a commit to PanocularAI/torchtitan that referenced this pull request Sep 30, 2026
Controller._start_rollout_producers/_stop_rollout_producers factor the
producer pipeline (rollout workers + data input) out of run(), and
RolloutGroupWorkBuffer gains pause()/resume(), so panofabric-engine's
decentralized_rl windowed loop can drive the consume side itself and keep
rollouts from straddling an outer weight merge.

Rebased onto upstream a182e53 (torchtitan/experiments/rl -> torchtitan/rl,
pytorch#4773). Dropped from this commit versus the 1c7ab80 rebase:
- the HF transformers-backend vLLM glue (vllm_wrapper/vllm_registry/
  attention): it composed at ModelSpec, which pytorch#4810 deleted, and only served
  the never-working rl_*_hf* A/B baseline presets.
- the global torch._dynamo recompile_limit = 10: a stale copy of code
  upstream moved into models/gpt_oss in pytorch#3737.
- a comment-only hunk in training_sample_builder.py.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
tianyu-l pushed a commit that referenced this pull request Oct 29, 2026
#4810 made `BaseEPTokenDispatcher.ep_mesh` slice
`spmd_sparse_mesh()["ep"]` on every read, and `DeviceMesh.__getitem__`
builds a new submesh each time. DeepSeek-V3 16B with EP=8 reads it
hundreds of times per step, spending tens to hundreds of milliseconds of
CPU per step on mesh slicing while GPU compute stays unchanged.

This removes `ep_mesh` and resolves the existing EP process group
through `spmd_mesh_group(MeshAxisName.EP)`, avoiding submesh
construction and mutable cache state on every dispatcher module.

## Test plan

- `python -m pytest -q
tests/unit_tests/cpu/distributed/test_expert_parallel.py
tests/unit_tests/cpu/models/common/test_moe.py`: 36 passed.
- On 2x4 GB200 with DeepSeek-V3 16B and EP=8, the process-group version
is within 0.15% of the cached version and 6.2% faster than uncached
`main`.
- A deterministic 50-step cache/process-group A/B finished with final
loss 5.861 / 5.864. The trajectories were close but not bit-identical.

<details>
<summary>Performance measurements</summary>

DeepSeek-V3 16B, bf16, EP=8, local batch 4, sequence length 4096, forced
expert load balance, eager, 2 nodes x 4 GB200.

| implementation | tokens/s, run 1 | tokens/s, run 2 | mean |
|---|---:|---:|---:|
| uncached `main` | 19,388 | 19,389 | 19,388 |
| cached submesh | 20,617 | 20,619 | 20,618 |
| EP process group | 20,579 | 20,596 | 20,588 |

Rank-0 instrumentation records 12,999 `DeviceMesh.__getitem__` calls
from `ep_mesh` over 50 steps on uncached `main`, totaling 2.99 seconds.
The process-group implementation makes no `DeviceMesh` slices from the
token dispatcher. All three arms used the same image, recipe, node pair,
and source base.

An independent 2x4 GB200 validation, pinned to the same software base
for both arms, measured 19,578 tokens/s without the change and 21,397
with the process-group implementation (+9.3%). The scheduler placed the
arms on different node pairs.

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

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants