Skip to content

Use stacked layout for fused feed-forward projections - #4808

Merged
anijain2305 merged 1 commit into
mainfrom
fused-mlp-default-main
Sep 20, 2026
Merged

anijain2305 merged 1 commit into
mainfrom
fused-mlp-default-main

Conversation

@anijain2305

@anijain2305 anijain2305 commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Relands #4676 against main. #4676 was accidentally merged into its ghstack base branch and never landed on main. This PR contains the same reviewed change, rebased onto current main.

Followup from #4535.

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

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

State dicts

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

Quantization

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

Tensor parallelism

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

LoRA

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

@pytorch-bot pytorch-bot Bot added ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl labels Sep 20, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Sep 20, 2026
@anijain2305
anijain2305 force-pushed the fused-mlp-default-main branch from 7296da3 to 03755a7 Compare September 20, 2026 21:40
Followup from #4535.

Generalize Linear with num_linears while keeping ordinary projections in their standard 2D layout. Store fused W13 as [2, F, D], keeping gate and up projections contiguous without changing the flattened GEMM.

Keep native DCP checkpoints and RL weight synchronization in the physical w13 layout. Split and merge gate/up projections only at the Hugging Face adapter boundary, avoiding FFN-sized state_dict hook copies on every RL weight sync.

Shard stacked W13 on its matrix-row dimension for TP and FSDP, propagate the layout through LoRA, dist-GEMM, rematerialization, fused SwiGLU, vLLM, and quantized Linear implementations, and allow DistMuon Owned compute for native batches of matrices.

Update numerical goldens and add coverage for native/HF state-dict round trips, tied Qwen FSDP loads, DeepSeek V4 TP, Kimi DistMuon, stacked initialization, and quantized FSDP gathering.
@anijain2305
anijain2305 force-pushed the fused-mlp-default-main branch from 03755a7 to 98f3493 Compare September 20, 2026 22:17
@anijain2305
anijain2305 merged commit 63c4e9f into main Sep 20, 2026
19 checks passed
rdspring1 added a commit to rdspring1/torchtitan that referenced this pull request Sep 21, 2026
NVFP4Linear.Config.build merges its own entries into the inherited
ShardingConfig and sets local_spmd. Module._maybe_wrap_with_local_region
resolves in_dst_shardings by the names of forward's positional arguments,
and NVFP4Linear.forward takes `input`, so the "x" key left every wrapped
module one entry short:

    AssertionError: NVFP4Linear: local_spmd is set but in_dst_shardings is
    missing entries for: ['input']

The wrong key has been there since the converter was added, but it was
unreachable: _maybe_wrap_with_local_region returns the forward unchanged
when local_spmd is false, and feed_forward w13 used colwise_config(), which
does not set it. pytorch#4808 changed w13 to stacked_colwise_config(), which does,
making the assertion reachable for the first time. It fires on every rank at
construction for any recipe that converts FFN linears.

"input" is the name upstream's own colwise, stacked-colwise, embedding and
norm configs use.

Co-Authored-By: Claude Opus 5 <[email protected]>
rdspring1 added a commit to rdspring1/torchtitan that referenced this pull request Sep 21, 2026
…keys

63c4e9f (pytorch#4808) renamed NVFP4Linear.forward's positional argument:

    -        def forward(self, x: torch.Tensor) -> torch.Tensor:
    +        def forward(self, input: torch.Tensor) -> torch.Tensor:

but left NVFP4Linear.Config.build keying its in_src_shardings and
in_dst_shardings entries "x". Module._maybe_wrap_with_local_region resolves
those keys through inspect.signature(type(self).forward), so the rename
silently invalidated them:

    AssertionError: NVFP4Linear: local_spmd is set but in_dst_shardings is
    missing entries for: ['input']

The same commit made the mismatch reachable. It gave feed_forward w13 a
stacked_colwise_config(), which sets local_spmd, where the previous
colwise_config() did not; _maybe_wrap_with_local_region returns the forward
unchanged when local_spmd is false. Either half alone is inert, so the
assertion appears only from pytorch#4808 onward, on every rank at construction, for
any recipe converting FFN linears.

Float8Linear.forward was renamed by the same commit and MXFP8Linear.forward
already took `input`; neither declares input shardings, so neither is
affected.

Co-Authored-By: Claude Opus 5 <[email protected]>
pianpwk added a commit that referenced this pull request Sep 23, 2026
PR #4808 updated the corresponding A10G baselines after changing fused feed-forward projections to a stacked layout, but left the MI350X baselines unchanged. These loss values were reproduced bit-for-bit by 19 post-merge ROCm CI runs across three PyTorch nightlies. Grad-norm values remain for a follow-up ROCm run because the prior comparator stopped after the first mismatching metric.

ghstack-source-id: bc7585d
Pull Request resolved: #4848
pianpwk added a commit that referenced this pull request Sep 24, 2026
The stacked fused feed-forward layout introduced by #4808 stores weights as [N, F, D]. SimpleFSDP still sharded every parameter on axis 0, unlike core FSDP, so sufficiently large DP meshes produced uneven or empty shards of the small N axis.

Reuse the core FSDP placement selection so stacked weights and biases shard on axis 1. This fixes precompile tracing through uneven DTensor reduce-scatter and prevents non-finite EP-overlap training.

ghstack-source-id: 04fdfa4

Pull Request resolved: #4867
pianpwk added a commit that referenced this pull request Sep 25, 2026
The stacked fused feed-forward layout introduced by #4808 stores dense weights as [N, F, D], and #4539 extends the structured layout to grouped experts as [E, N, F, D]. SimpleFSDP still sharded every parameter on axis 0, unlike core FSDP, so it could split a logical projection or expert-group axis and produce uneven or empty shards.

Reuse the public core FSDP placement selection so stacked dense and grouped weights and biases shard on their matrix-row axis. This fixes precompile tracing through uneven DTensor reduce-scatter and prevents non-finite EP-overlap training.

ghstack-source-id: a5358e3

Pull Request resolved: #4867
pianpwk added a commit that referenced this pull request Sep 26, 2026
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.12.0)
(oldest at bottom):
* __->__ #4867

The stacked fused feed-forward layout introduced by #4808 stores weights
as [N, F, D]. SimpleFSDP still sharded every parameter on axis 0, unlike
core FSDP, so sufficiently large DP meshes produced uneven or empty
shards of the small N axis.

Reuse the core FSDP placement selection so stacked weights and biases
shard on axis 1. This fixes precompile tracing through uneven DTensor
reduce-scatter and prevents non-finite EP-overlap training.
pianpwk added a commit that referenced this pull request Sep 28, 2026
PR #4808 updated the corresponding A10G baselines after changing fused feed-forward projections to a stacked layout, but left the MI350X baselines unchanged. These loss values were reproduced bit-for-bit by 19 post-merge ROCm CI runs across three PyTorch nightlies. Grad-norm values remain for a follow-up ROCm run because the prior comparator stopped after the first mismatching metric.

ghstack-source-id: b6c9938
Pull Request resolved: #4848
tianyu-l pushed a commit that referenced this pull request Sep 28, 2026
…om current main (#4926)

## Summary

Follow-up to #4848. Every ROCm `--assert-equal` loss-parity test against
`tests/assets/losses/real_pg/mi350x/*.txt` is currently red. #4808 ("Use
stacked layout for fused
feed-forward projections") refreshed the CUDA/a10g reference losses in
the same PR, but never touched the ROCm/mi350x baselines.

#4848 only updated `loss`, not `grad_norm` and some other tests have
drifted as well. This PR regenerates all the affected loss files (both
`loss` and `grad_norm`) from a single current-`main` CI run ([run
36459264445
(https://github.com/pytorch/torchtitan/actions/runs/36459264445), commit
`60e4ac6254`).

Co-authored-by: Claude Sonnet 5 <[email protected]>
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Nov 12, 2026
* feat(ezpz): add replicated AGPT comparison and accumulated DDP

* fix(ezpz): capture training memory before optimizer diagnostics

* fix(ezpz): rebind copied console entrypoint for benchmark

* feat(ezpz): isolate gradient wire precision and record consumed batches

* feat(ezpz): add isolated Aurora replicated comparison launcher

* fix(ezpz): checkpoint native DDP models with unwrapped keys

NativeDDP adds a module. prefix to every FQN, so loading the audited
native-weight DCP failed with missing module.layers.* keys. Point the
checkpointer's model state at the unwrapped modules; parameters are
shared, so saves and loads still act on the live DDP model.

* feat(ezpz): watch replicated campaign jobs across Sunspot and Aurora

* fix(ezpz): report benchmark failures before device diagnostics

MDS job 12481849 exited training on all 24 ranks, then hung in the
finally-block Sophia witness: its .item() reads waited on device work
left by the aborted step, so the original exception was never printed.
Print the traceback first and skip witness reductions after a failure.

* fix(ezpz): disable in-place WGRAD accumulation under native DDP

Native DDP always runs the model under autocast, and Linear rejects
inplace_wgrad_accum=True there. Full-model run 12481850 failed in the
first forward on all 24 ranks. Turn it off when wrapping.

* feat(ezpz): add activation-checkpoint and memory-snapshot knobs to TT replicated launcher

* docs(ezpz): record replicated-comparison jobs 12481846-12481855 and TT memory breakdown

* feat(ezpz): add MDS_AC activation-checkpoint knob to MDS replicated launcher

* fix(ezpz): use per-layer uniform recompute for MDS_AC=full

MDS rejects --checkpoint-activations without a recompute method (job
12481858: Invalid activation recompute method). One layer per uniform
chunk matches TT activation-checkpoint:full.

* feat(ezpz): add ZeRO stage and optimizer knobs to MDS replicated launcher

ZeRO-0 SophiaG runs fail at the first training step three ways
(hang 12481849, OUT_OF_RESOURCES 12481855, GPU page fault 12481859),
while the Oct 23 ZeRO-1 AdamW baseline ran on the same runtime. These
knobs bisect stage and optimizer at the 24-rank geometry.

* feat(ezpz): make ranks per node configurable in replicated launchers

AGPT-2B stacked w13 [2, 11008, 2048] shards on dim 1, which FSDP2 rejects
unless 11008 divides the shard degree. TT FSDP job 12481864 failed at 24
ranks; PPN=8 gives 16 ranks (11008 / 16 = 688) for a matched pair.

* docs(ezpz): record ZeRO-0 bisect and matched 16-rank MDS ZeRO-1 vs TT FSDP

* feat(ezpz): add DS 0.17.5 ZeRO-0 optimizer path knob to MDS replicated launcher

DeepSpeed <=0.17.5 defaulted bf16 without ZeRO to FP32 gradient
accumulation and BF16_Optimizer (DP-sharded FP32 masters and optimizer
state). DeepSpeed 0.18.5 defaults to BF16 accumulation and
FP16_UnfusedOptimizer (unsharded), and rejects ZeRO-0 with FP32
accumulation. MDS_ZERO0_PATH=ds0175 selects BF16_Optimizer through ZeRO
stage 1 plus grad_accum_dtype=fp32 and asserts the wrapper at init.
TT_ROOT can now point at a separate worktree.

* feat(ezpz): add CCL sync and FSDP comm ablation knobs to replicated TT launcher

* fix(ezpz): fall back to padded Shard(0) for uneven stacked-linear rows

AGPT-2B w13 is [2, 11008, 2048]. The Shard(1) override from cde3c93
(core linear_param_shard_placements, upstream pytorch#4808) makes fully_shard
raise NotImplementedError at 12 or 24 ranks because FSDP2 only pads
dim 0 and 11008 % 12 != 0. Drop the override for params whose local
row count does not divide the FSDP shard degree (shard axes only, so
HSDP replicate axes do not count) and warn once with the shapes.

* feat(ezpz): add HSDP arm to the replicated TT launcher

ARM=hsdp-{eager,losscompile} shards over HSDP_SHARD ranks (default PPN,
one replica per node) and replicates across the rest of the world.

* feat(ezpz): apply FSDP comm knobs to the HSDP arm of the replicated TT launcher

* fix(ezpz): export FLAT device hierarchy in the TT ablation runner

* feat(ezpz): add ZeRO-1 flat optimizer sharding for native DDP

Rebind trainable parameters to one padded FP32 buffer before DDP wraps
the model, retarget the recipe's single elementwise optimizer group to
this rank's contiguous shard, and all-gather the updated buffer after
each step. native_ddp_zero1_allgather_dtype=bfloat16 keeps an FP32
master shard and BF16-rounded replicated parameters, as MDS's
BF16_Optimizer does.

* feat(ezpz): add ZeRO-1 and DDP bucket knobs to replicated TT launchers

BENCH_DDP_ZERO1 selects the ZeRO-1 all-gather dtype, and
BENCH_DDP_BUCKET_FIRST bucketizes DDP's first backward. The ablation
launcher accepts per-variant KEY=VALUE overrides, so DDP and FSDP arms
can share one allocation. The Sophia witness records ZeRO-1 shard state.

* fix(ezpz): separate ablation overrides with '+' and export FLAT hierarchy

qsub -v splits on commas, so comma-separated per-variant overrides
could not be submitted.

* feat(ezpz): add XPU attention fwd/bwd microbenchmark at AGPT-2B shape

* feat(ezpz): add block-causal XPU flash attention that skips masked blocks

* feat(ezpz): gate block-causal XPU attention behind causal_blocks / EZPZ_XPU_ATTN_CAUSAL_BLOCKS

Batch each block diagonal into one flash call; wire the flag into
XPUScaledDotProductAttention and the TT ablation launcher.

* perf(ezpz): merge block-causal diagonals in BSHD with one fused op each

* feat(ezpz): add FSDP reduce-precision probe and deterministic launcher knobs

* fix(ezpz): lazy-init FSDP state before reading reduce dtypes in probe

* feat(ezpz): add XCCL compute/communication overlap microbenchmark

* feat(ezpz): read XCCL overlap sweep configs from a file

* fix(ezpz): keep mpiexec off the overlap sweep's stdin; faulthandler and per-case markers

* feat(ezpz): overlap bench reports mapped libs, per-phase markers, copy-engine configs

* fix(ezpz): archive evidence from immutable run source revisions

* fix(ezpz): distinguish scheduler and application archive outcomes

* feat(ezpz): record explicit per-rank benchmark step timings

* fix(ezpz): let W&B finish flush archive summary fields

* docs(ezpz): reconcile the MDS TorchTitan handoff and exact timing evidence

* fix(ezpz): launch overlap probes through ezpz and propagate failures

* docs(ezpz): align retained timing prose and MFU units

* docs(ezpz): record all-rank memory compile cost and verified collective exposure

* feat(ezpz): bracket TT variants with MDS controls in one allocation

* feat(ezpz): expose supported model-region compilation in benchmark arms

* docs(ezpz): distinguish historical nominal stage from optimizer layout

* Add opt-in AGPT initial parameter audit

* feat(ezpz): expose live native DDP parameter witness in benchmark launcher

* fix(ezpz): preserve training metadata during evidence uploads

* fix(ezpz): avoid nested launch command separators in benchmark arms

* fix(ezpz): preserve TT payload across the launch delimiter

* Add opt-in DTensor initial parameter audit

* feat(ezpz): expose DP-sharded initial parameter audit in benchmark launcher

* Revert "fix(ezpz): preserve TT payload across the launch delimiter"

This reverts commit 3ec5481.

* Revert "fix(ezpz): avoid nested launch command separators in benchmark arms"

This reverts commit a32035a.

* fix(ezpz): preserve MDS payload through legacy Click launcher

* feat(ezpz): opt-in per-TransformerBlock torch.compile for agpt

* feat(ezpz): add microbatch, block-compile and MDS accumulation knobs to replicated launchers

* feat(ezpz): add serial MDS/TT matrix runner for one allocation

* feat(ezpz): add historical AGPT-2B TT throughput anchor job

* fix(ezpz): disable in-place WGRAD accumulation in compiled agpt blocks

* fix(ezpz): give RoPE per-row positions when a blendcorpus microbatch holds several sequences

* feat(ezpz): add AdamW replicated benchmark config and TT optimizer knob

* docs(ezpz): record AGPT-2B XPU throughput recovery on Sunspot

* agpt: attribute the anchor gap to a slow cold first launch; MDS reaches 109 at the 2025 shape

The 6.1% anchor gap is a first-launch effect on cold nodes, not the node
image: later launches on the same node reach 92.6-95.1 TFLOP/s/tile.
benchmark_agpt_historical_anchor.sh gains env-profile, prewarm, page-cache,
CPU-sampler and allocator knobs used to rule out causes.
benchmark_mds_historical_shape.sh reruns z2rrt02w's argv on today's
Sunspot MDS stack (109.18 vs 102.9 TFLOP/s/tile in July 2025).

* agpt: add the z2rrt02w MDS shape as a TT benchmark config

mds-4096x10 (hidden 4096, 10 layers, GQA 32/8, FFN 11008, vocab 32000) and
agpt_mds_shape_benchmark_adamw. The replicated TT launcher takes BENCH_SEQ,
BENCH_SEQS_PER_RANK and BENCH_TT_CONFIG; the matrix gains an mdsshape phase.

* agpt docs: TT at the z2rrt02w shape is 26% behind MDS; attention backward is the outlier

* agpt docs: block-causal attention is worth 7-10% at the z2rrt02w shape; TT still 14% behind MDS

* agpt docs: qualify the FSDP arm, name both FLOP normalizations, surface the wide-shape gap in Results

* agpt docs: block-causal attention is 9.5% faster at AGPT-2B; losses not yet equivalent

* agpt docs: fix profiled update number

* agpt: add a same-batch gradient probe for block-causal attention

probe_block_causal_grads.py replays chosen updates under default and
block-causal (4, 8 chunks) attention and compares the all-reduced gradients
on rank 0. The TT launcher selects it with BENCH_BLOCK_PROBE=1.

* agpt: add a one-tile eager vs compiled gradient check for block-causal attention

* agpt docs: block-causal gradients are wrong under per-block compile

* agpt: calibrate the block-causal gradient probe with known q/k/v gradient noise

* agpt docs: compile is not the cause of the block-causal gradient gap

* agpt: capture training attention calls and replay them in the block-causal check

* agpt docs: gradient noise at op-level size does not reproduce the block-causal gap

* agpt: add a single-call block-causal variant to the gradient probe

* agpt docs: block-causal is correct on real training attention calls; update-1 gap open

* agpt: add forward-output noise variants to the block-causal gradient probe

* agpt docs: blk1 matches default; the block-causal gradient gap comes with chunking

* agpt docs: block-causal gradients diverge like any rounding-level forward change; op is correct

* agpt: accept dash-separated probe updates

* agpt docs: lead with the forward/backward noise asymmetry; scope the block-causal claims

* agpt journal: scope the block-causal gradient entry

* agpt docs: block-causal gradient divergence sits inside the forward-noise range at five updates

* agpt: add a random-init AGPT-2B loss A/B config and a seed knob

agpt_2b_loss_ab trains 2b-mds from random init with AdamW 3e-4. The TT
launcher takes BENCH_SEED for --debug.seed and logs the attention mode.

* agpt docs: block-causal attention matches default loss over 400 updates and three seeds

* ezpz docs: keep block-causal attention opt-in

* ezpz: MDS wide-shape profile knob and XPU trace summarizer

* ezpz: optional BF16 model storage for native-DDP ZeRO-1

* ezpz: wrap long lines in ZeRO-1 BF16 storage change

* ezpz docs: MDS vs TT kernel breakdown at the z2rrt02w shape

* ezpz docs: BF16 ZeRO-1 model storage speed at the z2rrt02w shape

* ezpz docs: BF16 ZeRO-1 storage loss A/B

* ezpz docs: name the MDS baseline per shape; scope BF16 storage claims

* ezpz docs: TT vs MDS AdamW/ZeRO-1 at AGPT-2B, same allocation

* ezpz docs: loss A/B of block-causal plus BF16 ZeRO-1 storage

* ezpz docs: two-node 2000-update loss A/B of block-causal plus BF16 storage

* fix(ezpz): smoke script drop broken --metrics.enable-wandb False

tyro parses the bare "False" as a positional, not a value for the
boolean flag — every rank exits with "Unrecognized options: False".
wandb is off by default so the flag is unnecessary; removing it.

* style(ezpz): lint the throughput-recovery tooling

License header on 16 files, ufmt, wrap long lines in the
watch_agpt_replicated remote script, rename the _null context
manager, explicit weights_only on torch.load, plain attribute
access instead of constant getattr in blendcorpus_builder.

* fix(ezpz): rebuild ZeRO-1 BF16 master after checkpoint load

A DCP resume builds optimizer state (init_optim_state steps, firing
pre_step -> ensure_master) before the checkpoint's model weights are
copied in. The FP32 master latched the pre-load weights and the first
real step all-gathered them over the restored model: max |param - ckpt|
36 after one step, vs 0.005 in FP32 mode. Reset master_initialized from
an optimizer load_state_dict post-hook and keep the forward pre-hook
registered so the master is rebuilt from the loaded weights.

Document that the FP32 master is not checkpointed, so a resume rounds
it to BF16.

Reject fsdp_defer_gradient_reduction under native DDP: the engine casts
the model to FSDPModule and NativeDDP has no set_is_last_backward.

Tests: resume-order regression (fails on the old code), validator.

* docs(ezpz): document ZeRO-1 BF16 resume fix and XPU check

* docs(ezpz): fix broken journal links and codespell in production READMEs

* fix(ezpz): default BlendCorpusDataLoader._batch_input_witness at class level

__iter__ reads the witness, which only __init__ set, so a loader built with
object.__new__ raised AttributeError. Six tests in test_blendcorpus_fold_batch_dim
and test_blendcorpus_resume_position do exactly that and failed on this branch.

---------

Co-authored-by: sim <sim@localhost>
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.

2 participants