Skip to content

Add MoE support to the transformers modeling backend - #2679

Merged
mreso merged 141 commits into
pytorch:mainfrom
mreso:feature/transformer_hf_moe
Jul 20, 2026
Merged

mreso merged 141 commits into
pytorch:mainfrom
mreso:feature/transformer_hf_moe

Conversation

@mreso

@mreso mreso commented Mar 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Enables training HF Transformers MoE models (Qwen3-MoE, Mixtral, DeepSeek-V3, etc.) with torchtitan's parallelism stack: Expert Parallelism, Tensor Parallelism, FSDP, pipeline parallelism, activation checkpointing, and torch.compile.

Design

The integration preserves the original HF forward passes — no MoE block or experts forward methods are replaced. All parallelism is applied via hooks and standard PyTorch module parallelism APIs:

  • EP: Expert params sharded via distribute_tensor(..., [Shard(0)]) on the EP mesh. Pre/post hooks on the MoE block handle token routing, all-to-all dispatch/combine, and gate mocking with local expert indices. The original HF for-loop runs unchanged on local expert params.
  • TP: Expert weights TP-sharded via distribute_tensor with Shard(1)/Shard(2). PrepareModuleInputOutput handles sequence-parallel boundaries. Pre/post hooks on the experts module convert DTensor params to local via dict shadowing so the HF for-loop operates on plain tensors.
  • FSDP: Expert params separately wrapped on the efsdp mesh with hook re-registration to ensure correct ordering (to_local hooks fire after FSDP unshard, restore hooks fire before reshard).
  • Compile: Non-MoE layers compiled as whole blocks. MoE layers: only the gate is compiled (when not TP-patched). Experts and other sub-modules skipped due to AsyncCollectiveTensor boundary issues with TP.
  • grouped_mm: Enabled via HF's config._experts_implementation = "grouped_mm", replacing the per-expert for-loop with fused torch.grouped_mm. Deterministic accumulation via reshape+sum instead of non-deterministic index_add.

The only forward monkey-patch is on the router gate (when TP is enabled) to insert a DTensor→local boundary between F.linear and topk — necessary because HF routers bundle both operations in one forward, and topk backward doesn't support DTensor.

Key files

  • parallelize.py — EP/TP/FSDP hooks, compile, router patch
  • model.py — grouped_mm config
  • tests/run_moe_tests.sh — 17-configuration integration test matrix

Test plan

  • FSDP-only, EP-only (EP=2, EP=4), TP-only (TP=2, TP=4), EP+TP, EP+TP+compile, TP+compile, PP+EP, PP+TP+EP, HSDP+EP, HSDP+TP+EP, with/without SAC
  • Unit tests for dispatch hook data flow, experts to_local hooks, mock gate routing
  • Loss decreases over training steps in all configurations
  ┌─────────────────────────────────────────────────────────────┬───────────────────────────────────────────────────────┐
  │                            Test                             │                      Description                      │
  ├─────────────────────────────────────────────────────────────┼───────────────────────────────────────────────────────┤
  │ TestMoeBlockForward::test_hf_moe_block_backward             │ Backward pass through original HF MoE block forward   │
  ├─────────────────────────────────────────────────────────────┼───────────────────────────────────────────────────────┤
  │ TestMoeBlockForward::test_hf_moe_block_forward_plain_tensor │ Original HF MoE block forward with plain tensor input │
  ├─────────────────────────────────────────────────────────────┼───────────────────────────────────────────────────────┤
  │ TestMoeDetection::test_moe_enabled_all_moe                  │ All layers correctly detected as MoE                  │
  ├─────────────────────────────────────────────────────────────┼───────────────────────────────────────────────────────┤
  │ TestMoeDetection::test_moe_enabled_mixed                    │ Alternating MoE/dense layers correctly detected       │
  ├─────────────────────────────────────────────────────────────┼───────────────────────────────────────────────────────┤
  │ TestEPMoeForwardBackward::test_ep_only_forward_backward     │ EP-only forward/backward with 4 GPUs                  │
  ├─────────────────────────────────────────────────────────────┼───────────────────────────────────────────────────────┤
  │ TestEPMoeForwardBackward::test_ep_tp_forward_backward       │ EP+TP forward/backward with 2D mesh (ep=2, tp=2)      │
  ├─────────────────────────────────────────────────────────────┼───────────────────────────────────────────────────────┤
  │ TestTPOnlyMoeForwardBackward::test_tp_only_forward_backward │ TP-only MoE forward/backward with 4 GPUs              │
  ├─────────────────────────────────────────────────────────────┼───────────────────────────────────────────────────────┤
  │ TestMixedMoeDenseLayers::test_mixed_layers_ep               │ Mixed MoE + dense layers with EP                      │
  └─────────────────────────────────────────────────────────────┴───────────────────────────────────────────────────────┘

  Integration Tests (15/15 passed on 4 GPUs, 2 skipped requiring 8+ GPUs)

  ┌─────┬────────────────────────────────────┬──────┬─────┬─────┬─────┬──────┬─────────┬─────┬─────────────────────────┐
  │  #  │           Configuration            │ FSDP │ TP  │ EP  │ PP  │ HSDP │ Compile │ SAC │         Result          │
  ├─────┼────────────────────────────────────┼──────┼─────┼─────┼─────┼──────┼─────────┼─────┼─────────────────────────┤
  │ 1   │ Baseline                           │ ✓    │ -   │ -   │ -   │ -    │ -       │ ✓   │ PASSED                  │
  ├─────┼────────────────────────────────────┼──────┼─────┼─────┼─────┼──────┼─────────┼─────┼─────────────────────────┤
  │ 2   │ FSDP + EP=2                        │ ✓    │ -   │ 2   │ -   │ -    │ -       │ ✓   │ PASSED                  │
  ├─────┼────────────────────────────────────┼──────┼─────┼─────┼─────┼──────┼─────────┼─────┼─────────────────────────┤
  │ 3   │ FSDP + EP=4                        │ ✓    │ -   │ 4   │ -   │ -    │ -       │ ✓   │ PASSED                  │
  ├─────┼────────────────────────────────────┼──────┼─────┼─────┼─────┼──────┼─────────┼─────┼─────────────────────────┤
  │ 4   │ FSDP + TP=2 (MoE, no EP)           │ ✓    │ 2   │ -   │ -   │ -    │ -       │ ✓   │ PASSED                  │
  ├─────┼────────────────────────────────────┼──────┼─────┼─────┼─────┼──────┼─────────┼─────┼─────────────────────────┤
  │ 5   │ FSDP + TP=4 (MoE, no EP)           │ ✓    │ 4   │ -   │ -   │ -    │ -       │ ✓   │ PASSED                  │
  ├─────┼────────────────────────────────────┼──────┼─────┼─────┼─────┼──────┼─────────┼─────┼─────────────────────────┤
  │ 6   │ FSDP + TP=2 + EP=2                 │ ✓    │ 2   │ 2   │ -   │ -    │ -       │ ✓   │ PASSED                  │
  ├─────┼────────────────────────────────────┼──────┼─────┼─────┼─────┼──────┼─────────┼─────┼─────────────────────────┤
  │ 7   │ FSDP + TP=2 + EP=4                 │ ✓    │ 2   │ 4   │ -   │ -    │ -       │ ✓   │ PASSED                  │
  ├─────┼────────────────────────────────────┼──────┼─────┼─────┼─────┼──────┼─────────┼─────┼─────────────────────────┤
  │ 8   │ FSDP + EP=4 + compile              │ ✓    │ -   │ 4   │ -   │ -    │ ✓       │ ✓   │ PASSED                  │
  ├─────┼────────────────────────────────────┼──────┼─────┼─────┼─────┼──────┼─────────┼─────┼─────────────────────────┤
  │ 9   │ FSDP + TP=2 + EP=2 + compile       │ ✓    │ 2   │ 2   │ -   │ -    │ ✓       │ ✓   │ PASSED                  │
  ├─────┼────────────────────────────────────┼──────┼─────┼─────┼─────┼──────┼─────────┼─────┼─────────────────────────┤
  │ 10  │ FSDP + TP=2 (MoE, no EP) + compile │ ✓    │ 2   │ -   │ -   │ -    │ ✓       │ ✓   │ PASSED                  │
  ├─────┼────────────────────────────────────┼──────┼─────┼─────┼─────┼──────┼─────────┼─────┼─────────────────────────┤
  │ 11  │ FSDP + PP=2 + EP=2                 │ ✓    │ -   │ 2   │ 2   │ -    │ -       │ ✓   │ PASSED                  │
  ├─────┼────────────────────────────────────┼──────┼─────┼─────┼─────┼──────┼─────────┼─────┼─────────────────────────┤
  │ 12  │ FSDP + TP=2 + PP=2 + EP=2          │ ✓    │ 2   │ 2   │ 2   │ -    │ -       │ ✓   │ SKIPPED (needs 8+ GPUs) │
  ├─────┼────────────────────────────────────┼──────┼─────┼─────┼─────┼──────┼─────────┼─────┼─────────────────────────┤
  │ 13  │ HSDP + EP=2                        │ ✓    │ -   │ 2   │ -   │ 2    │ -       │ ✓   │ PASSED                  │
  ├─────┼────────────────────────────────────┼──────┼─────┼─────┼─────┼──────┼─────────┼─────┼─────────────────────────┤
  │ 14  │ HSDP + TP=2 + EP=2                 │ ✓    │ 2   │ 2   │ -   │ 2    │ -       │ ✓   │ SKIPPED (needs 8+ GPUs) │
  ├─────┼────────────────────────────────────┼──────┼─────┼─────┼─────┼──────┼─────────┼─────┼─────────────────────────┤
  │ 15  │ FSDP + EP=2 (no SAC)               │ ✓    │ -   │ 2   │ -   │ -    │ -       │ -   │ PASSED                  │
  ├─────┼────────────────────────────────────┼──────┼─────┼─────┼─────┼──────┼─────────┼─────┼─────────────────────────┤
  │ 16  │ FSDP + TP=2 + EP=2 (no SAC)        │ ✓    │ 2   │ 2   │ -   │ -    │ -       │ -   │ PASSED                  │
  ├─────┼────────────────────────────────────┼──────┼─────┼─────┼─────┼──────┼─────────┼─────┼─────────────────────────┤
  │ 17  │ FSDP + PP=2 + EP=2 + compile       │ ✓    │ -   │ 2   │ 2   │ -    │ ✓       │ ✓   │ PASSED                  │
  └─────┴────────────────────────────────────┴──────┴─────┴─────┴─────┴──────┴─────────┴─────┴─────────────────────────┘

  How to reproduce

  cd torchtitan

  # Unit tests
  ../.venv/bin/python -m pytest torchtitan/experiments/transformers_modeling_backend/tests/test_moe_parallelism.py -x -v

  # Integration tests (adjust NGPU and CUDA_VISIBLE_DEVICES as needed)
  bash torchtitan/experiments/transformers_modeling_backend/tests/run_moe_tests.sh <NGPU> <STEPS>

Qwen3 30B training on 8xH100 for 500 steps: https://gist.github.com/mreso/2acf95959db81777fb3b009e609f6b96

$ NGPU=8 MODULE=transformers_modeling_backend CONFIG=transformers_modeling_backend_full_moe     ./run_train.sh       --parallelism.data_parallel_shard_degree -1       --parallelism.expert_parallel_degree 8       --compile.enable

[rank0]:[titan] 2026-03-25 15:37:41,980 - root - INFO - step:  1  loss: 12.38460  grad_norm: 24842768.0000  memory: 56.95GiB(59.90%)  tps: 154  tflops: 27.61  mfu: 2.79%
....
[rank0]:[titan] 2026-03-25 15:49:17,623 - root - INFO - step: 500  loss:  4.39128  grad_norm: 15089.0879  memory: 78.57GiB(82.64%)  tps: 2,817  tflops: 506.59  mfu: 51.22%

Supported MoE Models

  │      Model       │ HF model_type │          Router           │   Shared Experts    │  Numerical Equiv   │ FSDP │ FSDP+EP │
  ├──────────────────┼───────────────┼───────────────────────────┼─────────────────────┼────────────────────┼──────┼─────────┤
  │ Qwen3-30B-A3B    │ qwen3_moe     │ softmax, norm_topk_prob   │ none                │ PASS (KL 5.31e-07) │ PASS │ PASS    │
  ├──────────────────┼───────────────┼───────────────────────────┼─────────────────────┼────────────────────┼──────┼─────────┤
  │ Mixtral-8x7B     │ mixtral       │ softmax, always norm      │ none                │ WARN (KL 4.62e-05) │ PASS │ PASS    │
  ├──────────────────┼───────────────┼───────────────────────────┼─────────────────────┼────────────────────┼──────┼─────────┤
  │ DeepSeek-V3      │ deepseek_v3   │ sigmoid, group routing    │ additive FFN        │ WARN (KL 3.66e-04) │ PASS │ PASS    │
  ├──────────────────┼───────────────┼───────────────────────────┼─────────────────────┼────────────────────┼──────┼─────────┤
  │ OLMoE-1B-7B      │ olmoe         │ softmax, no norm          │ none                │ PASS (KL 4.04e-07) │ PASS │ PASS    │
  ├──────────────────┼───────────────┼───────────────────────────┼─────────────────────┼────────────────────┼──────┼─────────┤
  │ DeepSeek-V2-Lite │ deepseek_v2   │ softmax, no group routing │ additive FFN        │ PASS (KL 2.64e-07) │ PASS │ PASS    │
  ├──────────────────┼───────────────┼───────────────────────────┼─────────────────────┼────────────────────┼──────┼─────────┤
  │ GLM-4.7          │ glm4_moe      │ sigmoid, group routing    │ additive FFN        │ WARN (KL 5.06e-05) │ PASS │ PASS    │
  ├──────────────────┼───────────────┼───────────────────────────┼─────────────────────┼────────────────────┼──────┼─────────┤
  │ GLM-5 (DSA)      │ glm_moe_dsa   │ sigmoid, group routing    │ additive FFN        │ WARN (KL 2.67e-04) │ PASS │ PASS    │
  ├──────────────────┼───────────────┼───────────────────────────┼─────────────────────┼────────────────────┼──────┼─────────┤
  │ Llama-4-Scout    │ llama4_text   │ sigmoid, no bias          │ additive (singular) │ WARN (KL 2.29e-04) │ PASS │ PASS    │
  ├──────────────────┼───────────────┼───────────────────────────┼─────────────────────┼────────────────────┼──────┼─────────┤
  │ Gemma-4-26B      │ gemma4_text   │ softmax + RMSNorm + scale │ dense MLP as shared │ FAIL (KL 4.19e-03) │ PASS │ PASS    │
  └──────────────────┴───────────────┴───────────────────────────┴─────────────────────┴────────────────────┴──────┴─────────┘

  Numerical equivalence thresholds: PASS (KL < 1e-6), WARN (KL < 1e-3), FAIL (KL >= 1e-3). All WARN models reach max_diff=0.00 with three dispatcher precision fixes (f32 accumulation, reshape+sum, sorted topk). Gemma4 numerical equivalence FAIL is due to unsupported router features (input RMSNorm, learned scale, per_expert_scale) and activation mismatch (GeGLU vs SwiGLU).

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Mar 24, 2026
@mreso
mreso force-pushed the feature/transformer_hf_moe branch from 18307b8 to 3408409 Compare March 24, 2026 17:53
Implement Expert Parallelism and Tensor Parallelism for HF MoE models
using hooks and DTensor — no HF forward methods are replaced except the
router (unavoidable due to topk backward DTensor limitation).

EP: DTensor Shard(0) on EP mesh + pre/post hooks on MoE block for
all-to-all dispatch/combine. Original HF forward runs unchanged on
local expert params (converted via __dict__ shadowing hooks).

TP: PrepareModuleInputOutput for SP boundaries + _moe_to_local_pre_hook
for DTensor→local conversion + _experts_to_local_pre_hook for expert
param conversion. Router uses _tp_router_forward monkey-patch to insert
DTensor→local boundary before topk.

Compile: skip compiling self_attn/layernorms individually for MoE
layers (AsyncCollectiveTensor backward mismatch). Expert compute runs
eagerly via HF grouped_mm implementation.

Tested: 8 unit tests, 17 integration configs (15 on 4 GPUs, 2 need 8+)
covering FSDP, EP, TP, PP, HSDP, compile, SAC combinations.
@mreso
mreso force-pushed the feature/transformer_hf_moe branch from 3408409 to e9e754b Compare March 24, 2026 20:42
Replace _tp_router_forward (30-line model-specific forward copy) with
_wrap_forward_with_safe_topk (thin wrapper using unittest.mock.patch).
The wrapper temporarily replaces torch.topk with a DTensor-safe version
during the router's forward, so the original HF forward runs unchanged.

Also add full_moe flavor for Qwen3-30B-A3B, add CI version compat
comment, and parallelize integration test pairs on 8 GPUs (2x faster).
Comment on lines +108 to +113
if parallel_dims.tp_enabled and not parallel_dims.ep_enabled:
apply_moe_tp(model, tp_mesh=parallel_dims.get_mesh("tp"))

if parallel_dims.ep_enabled:
apply_moe_ep(model, ep_mesh=parallel_dims.get_mesh("ep"))

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.

is it possible for us to use apply_moe_ep_tp like in llama4's parallelize plan?

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.

Done

logger.info("Applied Tensor Parallelism to MoE expert weights")


def _apply_compile_moe(model: nn.Module, compile_config: CompileConfig):

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.

what's the difference between this and apply_compile_sparse?

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.

Serves the same purpose though the internal structure of the hf model is different from the native titan models so we can not use e.g. isinstance(submod, moe_module.MoE)

output_layouts=Shard(1)
)
layer_plan.update(mlp_plan)
elif ep_enabled:

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.

why would there be ep for non moe?

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, moving the moe related part out of there

# params after FSDP. Patch router forward to insert
# DTensor→local boundary before topk (topk backward doesn't
# support DTensor).
_replicate_gate_params(transformer_block.mlp, tp_mesh)

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.

wondering can we achieve this replicate through something like

"moe.router.gate": NoParallel(
instead of this helper function?

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.

The challenge is that transformers combines gate and topk into a single forward where the gate is stored as nn.Parameter and uses the functional interface so there is no entity to attach the hooks that NoParallel provides and we need the input of topk to be local. Any recommentation on how this could be further aligned with native titan?

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.

we need the input of topk to be local

why this is True? can we just use DTensor for topk as well?

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.

topk is not working with DTensor:

# torchrun --nproc_per_node=2 repro_topk_dtensor.py

import torch
import torch.distributed as dist
from torch.distributed.tensor import DTensor, Replicate
from torch.distributed.device_mesh import init_device_mesh


def main():
    dist.init_process_group(backend="nccl")
    torch.cuda.set_device(dist.get_rank())
    mesh = init_device_mesh("cuda", (dist.get_world_size(),))

    x = torch.randn(8, 4, device="cuda", requires_grad=True)
    x_dt = DTensor.from_local(x, mesh, (Replicate(),), run_check=False)

    values, indices = torch.topk(x_dt, k=2, dim=-1)
    values.sum().backward()

    dist.destroy_process_group()


if __name__ == "__main__":
    main()

Error:

[rank0]: Traceback (most recent call last):
[rank0]:   File "/home/mreso/torchtitan_transformers/torchtitan/repro_topk_dtensor.py", line 30, in <module>
[rank0]:     main()
[rank0]:   File "/home/mreso/torchtitan_transformers/torchtitan/repro_topk_dtensor.py", line 24, in main
[rank0]:     values.sum().backward()
[rank0]:   File "/home/mreso/torchtitan_transformers/.venv/lib/python3.12/site-packages/torch/_tensor.py", line 631, in backward
[rank0]:     torch.autograd.backward(
[rank0]:   File "/home/mreso/torchtitan_transformers/.venv/lib/python3.12/site-packages/torch/autograd/__init__.py", line 379, in backward
[rank0]:     _engine_run_backward(
[rank0]:   File "/home/mreso/torchtitan_transformers/.venv/lib/python3.12/site-packages/torch/autograd/graph.py", line 877, in _engine_run_backward
[rank0]:     return Variable._execution_engine.run_backward(  # Calls into the C++ engine to run the backward pass
[rank0]:            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[rank0]: RuntimeError: aten.scatter.src got mixed torch.Tensor and DTensor, need to convert all torch.Tensor to DTensor before calling distributed operators!

@acisseJZhong acisseJZhong Apr 1, 2026 •

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.

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.

interesting, let me check whats the difference there

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.

Seems like the reason is that titan discards the topk value and just uses the indices while transformers implementation continues with the values directly. Thats why backward never gets triggers in titan.

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.

Solved it by replacing torch.topk with the discard + gather combination which does not rewuire backward pass through topk:

_orig_topk = torch.topk

def _topk_with_gather(input, k, dim=-1, largest=True, sorted=True, *, out=None):
    with torch.no_grad():
        _, indices = _orig_topk(input, k, dim=dim, largest=largest, sorted=sorted)
    values = input.gather(dim, indices)
    return torch.return_types.topk((values, indices))

torch.topk = _topk_with_gather

}

# Register dispatch/combine hooks on MoE block
moe_block.register_forward_pre_hook(_ep_dispatch_pre_hook)

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.

is it possible for us to use ParallelStyle wrap this moe block to achieve the dispatch and combine instead of manually register hooks?
https://github.com/pytorch/torchtitan/blob/main/torchtitan/distributed/expert_parallel.py#L74

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.

Newest PR picks up the ParallelStyle pattern but we still need some hooks to apply the to_local which is inside the MoE layer in case of native Titan IIRC.

# Wrap as Replicate DTensor for F.linear with DTensor weight
if isinstance(self.weight, DTensor) and not isinstance(hidden_states, DTensor):
tp_mesh = self.weight.device_mesh
hidden_states = DTensor.from_local(

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.

can you explain more why do we need this _tp_router_forward? For titan moe the router computation should already be local computation as we convert it here

x = x.to_local(grad_placements=(Partial(),))
, can you do sth similar?

fyi: we are in the effort of getting rid of manual from_local/to_local.

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.

In titan the gate/router is an nn.Linear and NoParallel adds a hook to convert the output into a local tensor. Transformers stored the raw parameter uses the functional interface so we can not apply the hook here without upstreaming a change. I can create a wrap around the topk which applies to_local which would probably be equivalent to the post hook on the linear and would be more model agnostic and would be a bit more robust against upstream changes but it would still not be ParallelStyle:

def _dtensor_safe_topk(input, *args, **kwargs):
    if isinstance(input, DTensor):
        input = input.to_local()
    return _orig_topk(input, *args, **kwargs)

mreso added 5 commits March 25, 2026 17:34
Replace manual EP hooks with HFExpertParallel (subclass of
BaseExpertParallel), applied via parallelize_module. Dispatch/combine
hooks are registered by distribute_module following the standard
ParallelStyle pattern.

Replace _wrap_forward_with_safe_topk (mock.patch on torch.topk) with
_gate_to_local_pre_hook (__dict__ shadowing on gate weight). The gate
weight is a Replicate DTensor; shadowing with to_local() ensures
F.linear produces plain output, so topk never sees DTensors.

Eliminated: _MockGate, _ep_dispatch_pre_hook, _ep_combine_post_hook,
_wrap_forward_with_safe_topk, _dtensor_safe_topk, mock.patch import.
Combine the two separate MoE parallelism functions into a single
apply_moe_ep_tp, mirroring native torchtitan's pattern. Handles
EP-only, TP-only, and EP+TP in one place.

- Move gate/expert hook registration from apply_non_moe_tp into
  apply_moe_ep_tp
- Simplify apply_non_moe_tp EP+TP branch to pass (handled by
  apply_moe_ep_tp)
- Expert TP sharding only for TP-only (EP+TP: experts are EP-sharded,
  each TP rank processes independently)
- Single call site: apply_moe_ep_tp(model, tp_mesh=..., ep_mesh=...)
Restructure the MoE TP plan conditions to eliminate the explicit pass
branch. EP+TP MoE layers need no mlp plan (handled by apply_moe_ep_tp),
so they're the implicit fallthrough when neither dense nor TP-only
conditions match.
Move the MoE TP boundary plan (PrepareModuleInputOutput) from
apply_non_moe_tp into apply_moe_ep_tp. Remove the ep_enabled parameter
from apply_non_moe_tp, making it purely non-MoE.

After this change:
- apply_non_moe_tp: attention, layernorms, dense MLP, root modules
- apply_moe_ep_tp: ALL MoE parallelism (EP, TP, boundary handling)

Also add run_tests.sh convenience script for running both unit and
integration tests in one command.
),
),
"debugmodel_moe": HFTransformerModel.Config(
titan_dense_config=TitanDenseModelConfig(

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.

having both dense config and moe config inside an moe model is a little bit confusing to me. Can we have only MoE config?

mreso added 5 commits March 31, 2026 21:25
Patch torch.topk to compute values via gather (scatter_add backward,
DTensor-safe) instead of native topk values (scatter.src backward,
crashes on DTensor). This makes topk safe globally for DTensor.

Replace _gate_to_local_pre_hook/__dict__ shadowing with:
- _gate_input_to_dtensor_pre_hook: wraps plain input as Replicate
  DTensor for F.linear compatibility
- _gate_output_to_local_hook: converts DTensor gate output to local
  for downstream plain-tensor computation

The gate forward now runs on DTensors (F.linear, softmax, topk all
on DTensors). topk backward is safe thanks to _topk_with_gather.
Rename TitanDenseModelConfig to TitanModelConfig. Make
TitanMoeModelConfig inherit from TitanModelConfig instead of being
a separate class. MoE flavors now use a single model_config instead
of two separate titan_dense_config + titan_moe_config objects.

- HFTransformerModel.Config takes model_config (single arg)
- _initialize_attributes replaces _initialize_dense_attributes +
  _initialize_moe_attributes
- Guard grouped_mm config with _has_moe to avoid setting it on
  dense models
Aligns naming with core torchtitan's apply_compile_sparse. Adds
docstring explaining why the core version can't be reused (different
module hierarchy, AsyncCollectiveTensor boundary issues, HF-native
grouped_mm).
Replace _replicate_gate_params + _gate_input_to_dtensor_pre_hook +
_gate_output_to_local_hook (3 functions, 3 hook registrations) with
a single TupleNoParallel applied via parallelize_module.

TupleNoParallel extends NoParallel with tuple return support: the
output hook processes each element individually instead of expecting
a single DTensor. Safe for topk on DTensor because _topk_with_gather
routes backward through gather (scatter_add) instead of scatter.src.

The gate is now handled via the standard ParallelStyle pattern, same
as native titan's NoParallel on moe.router.gate.
Explain why the hook exists (FSDP makes params DTensors, HF for-loop
can't handle them) and how native titan solves it differently (to_local
inside the forward vs our __dict__ shadowing in hooks).
with torch.no_grad():
_, indices = _orig_topk(input, k, dim=dim, largest=largest, sorted=sorted)
values = input.gather(dim, indices)
return torch.return_types.topk((values, indices))

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.

I got the general idea, but can you educate what does torch.return_types.topk do?

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.

topk does not return a plain tuple, but a special namedtuple of type torch.return_types.topk, so this is just creates the right datatype, we can remove the patch tomorrow when the fix appears in nightly

# ---------------------------------------------------------------------------


class TupleNoParallel(NoParallel):

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.

instead of adding a new class here, can we generalize the one in titan? If I understand correctly, this just handles returning tuple?

@mreso mreso Apr 3, 2026 •

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.

yes, let me generalize the NoParallel instead

return _process(outputs)


class HFExpertParallel(BaseExpertParallel):

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.

what's the difference than ExpertParallel?

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.

adding more context to the docstring

return None


def _experts_restore_post_hook(module, args, output):

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.

curious why we need to restore them? central titan seems only convert to local but never restore?

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.

native titan creates local variables for the to_local tensor. We shadow the DTensor which sits in _parameter by adding the to_locals into the __dict which gets checked first when we do an attribute lookup. the restore does not actually restore the DTensor but just removes the plain tensor from dict.

apply_compile_dense(model, compile_config)
has_moe = any(getattr(b, "moe_enabled", False) for b in model.layers)
if has_moe:
_apply_compile_sparse(model, compile_config)

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.

as discussed, let's look into if we can reuse apply_compile_sparse, if not, let's keep _apply_compile_sparse in a separate utils file.

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.

Docstring of _apply_compile_sparse explains the differences, will move it in a separate utils file

mreso added 10 commits April 2, 2026 17:18
Explain how HFExpertParallel differs from native ExpertParallel:
different input/output interface (unsorted HF vs pre-sorted native),
sorting done in dispatch, routing weights transported via all-to-all,
combine includes unsort + top_k sum.
Document three key differences from llama4's apply_moe_ep_tp:
HFExpertParallel vs ExpertParallel (unsorted HF interface),
TupleNoParallel vs NoParallel (tuple returns + topk gather patch),
__dict__ shadowing hooks vs inline to_local (no HF forward modification).
Add Args/Returns with shape annotations to _token_dispatch, matching
the inline shape comments used in native ExpertParallel. Keep
_token_combine docstring brief with output shape.
Update NoParallel._prepare_output_fn to process tuple outputs by
handling each element individually (skipping None and non-DTensor).
Single-tensor behavior is unchanged.

This allows the HF MoE router gate to use NoParallel directly
(same as native titan's moe.router.gate), removing the need for
the TupleNoParallel subclass in the experiment folder.
Register _experts_to_local_pre_hook and _experts_restore_post_hook
once, after apply_fsdp, instead of registering in apply_moe_ep_tp
and re-registering in apply_fsdp. Eliminates hook handle tracking
and the remove + re-register dance.
Extract _apply_compile_sparse from parallelize.py into its own
compile.py file in the transformers backend. Keeps parallelize.py
focused on parallelism logic. Removes unused CheckpointWrapper
import from parallelize.py.
Add shared expert TP warning in apply_moe_ep_tp — shared experts are
not TP-sharded yet, so TP-only mode produces incorrect results for
models with shared experts (Qwen3.5, DeepSeek V3). EP-only works.

Add model sweep to integration tests: runs EP-only with Qwen3-30B-A3B
and Mixtral-8x7B to verify different MoE architectures work. DeepSeek
V3 needs model-specific config attrs (qk_head_dim) not in TitanModelConfig.

Fix unit tests to explicitly register experts_to_local hooks (normally
done in parallelize_hf_transformers after apply_fsdp, which unit tests
don't call).
Apply ColwiseParallel/RowwiseParallel to shared expert MLP weights
(gate_proj, up_proj → ColwiseParallel, down_proj → RowwiseParallel
with Partial output) so shared expert output matches routed expert
Partial placement. Also replicate shared_expert_gate on TP mesh for
FSDP mesh alignment.

Fixes shared expert layer_idx propagation for depth-based init.

Adds Qwen2 MoE (shared experts) to model sweep: EP-only and TP+EP
tests both pass. Total: 21 integration configs.

Supports both attribute names: shared_expert (Qwen-style) and
shared_experts (DeepSeek/GLM-style).
Tested additional MoE models for sweep inclusion:
- Qwen3.5-35B-A3B: VLM (ForConditionalGeneration), not ForCausalLM
- Phi-3.5-MoE: PhiMoEForCausalLM not in transformers 5.x
- GLM-* models: use n_routed_experts instead of num_experts
- DeepSeek-V3: needs qk_head_dim config attr

These need model-specific config support and are documented as
comments in the sweep arrays. Compatible models (Qwen3, Mixtral,
Qwen2 MoE) remain in the active sweep.
…f_moe

# Conflicts:
#	torchtitan/experiments/transformers_modeling_backend/model.py
@mreso mreso added this to the New Feature, Model, Misc milestone Apr 3, 2026
mreso added 6 commits July 8, 2026 15:39
Verify CP+PP correctness at the logit level (loss is confounded by data/batch
and, across world sizes, by weight init):
  1. seed checkpoint -> identical weights for every layout,
  2. CP-only (cp=2, pp=1) loading the seed -> per-shard logits,
  3. CP+PP  (cp=2, pp=2) loading the seed -> per-microbatch logits,
  4. assert every CP-only sample matches some CP+PP microbatch per CP shard
     (best-match ignores the pipeline shape-inference dummy forward).
Covers flex (ptrr) and SDPA (headtail); fp32, small seq, 1 step; self-skips
under 4 GPUs. Result: both match CP-only at rel ~5e-7.

Implemented as a python module (tests/cp_pp_numerical.py) that orchestrates the
1/2/4-GPU subprocess launches plus the comparison -- the single-ngpu
OverrideDefinitions framework can't express it. Logits are dumped by a small
env-gated hook (HF_BACKEND_LOGIT_DUMP) in HFTransformerModel.forward (zero
overhead when unset). Wired into the local run_tests.sh; kept out of the 8-GPU
CI workflow (exotic, multi-launch) -- run manually via
`python -m ...tests.cp_pp_numerical`.
…mments

"native" was overloaded: it meant both TorchTitan's own MoE (the swap target)
and the HF model's own built-in experts kernel (experts_implementation="native").
Clarify every prose occurrence to say Titan or HF explicitly:
- Titan sense: the swapped-in MoE, deepseek_v3 init reference, spmd embedding.
- HF sense: experts_implementation="native" = the HF model's built-in kernel.

Docstrings/comments/skill-doc only. Code symbols (build_and_swap_native_moe,
_native_moe_config, the native_moe locals) and the "native" config value are
left unchanged, per the "native in code is fine as long as comments clarify"
guidance.
- prepare_native_moe_configs docstring: probe each HF MoE layer, store a Titan
  MoE.Config (per review).
- drop the stale "no temporary-swap workaround needed" comment.
- trim the spmd_backend guard comment to the essentials (only "default" is
  wired + TODO to wire spmd_types).
Absorbs 13 upstream commits (RoPE YaRN unification, dataloader resume fix,
qwen3.5 TP vision caches, fsspec checkpoint paths, etc.) and reconciles the HF
transformers backend with upstream's SFT PR (pytorch#3243), keeping our spmd-ready
design while preserving main's SFT.

- Kept our design for the conflicts: the Module-protocol path (convert_hf_to_
  module + declarative hf_sharding), HFFlexKernel + _wrap_flex_kernel_cp for
  flex/CP, EP + native-MoE + MLA kernels. Discarded main's DTensor-era
  HFFlexAttention/apply_cp_to_forward/apply_non_moe_tp where it conflicted.
- Fixed a silent auto-merge break in parallelize.py (main's orphaned
  apply_cp_to_forward(flex_modules) block, which looked for main's _flex_kernel).
- Preserved main's SFT on top of our stack: tokenizer.py, SFT flavors + ChatDataset
  presets, and a unified HFTransformerTrainer (our delegating design, which keeps
  the base Trainer's ntokens_seen and spmd_backend annotation).

Config convergence (Design A): dropped the redundant use_flex_attn bool; the
attention impl is now driven by attn_implementation ("flex_torchtitan" vs
"sdpa_torchtitan", matching main) and the mask by attn_mask_type ("causal" vs
"block_causal"), wired through get_attention_masks. block_causal requires the
flex impl (fail-loud ValueError). SFT block_causal uses main's
get_document_mask_mod (verified bit-identical to the prior efficient fast path).

HFTransformerTrainer raises a ValueError on the SDPA-only "headtail" CP load
balancer under flex, which cannot shard a flex BlockMask.

Verified: flex+CP (loss 11.87->9.31), EP/MoE (12.53->7.31), SFT end-to-end
(11.09->6.99), R4 raise, flex unit tests (3 passed), lint clean.
Gemma4 (google/gemma-4-26B-A4B-it, model_type gemma4_text) failed two ways on
the backend; both are fixed with contained, generic changes.

- model.py: the Llama-like init patch derived class names from the causal-LM
  prefix (e.g. "Gemma4Attention"), but Gemma4's classes carry a "Text" infix
  (Gemma4TextAttention / Gemma4TextDecoderLayer), so the patch was silently
  skipped -- init then ran at initializer_range=1.0 and activations exploded
  (loss ~1980, flat). _patch_hf_llama_like now falls back to "<prefix>Text"
  class names, so the patch applies and Gemma4's own _init_weights runs on the
  patched base. Generic: a no-op for models without the infix.
- hf_sharding.py: Gemma4TextDecoderLayer registers a buffer directly on the
  layer (layer_scalar, used as hidden_states *= layer_scalar), which no sharding
  case covered, so the completeness backstop failed under EP. Decoder layers
  carrying direct params/buffers now get _replicate_config; under FSDP/EP (no TP)
  the replicate placement resolves to a plain local tensor, so no DTensor mixing.
  Guarded: a no-op for layers with no direct-on-layer state.

Verified (debugmodel_moe, NGPU=4, seq_len 512): FSDP 14.46 -> 10.99, EP=2
14.44 -> 11.01. Other models unaffected.

Limitations: attention TP is not viable for this model (num_global_key_value_
heads=2, per transformers); and the layer-level MoE mapping / final_logit_
softcapping bypass mean this is validated for from-scratch training, not for
loading pretrained Gemma4 weights.
Absorbs pytorch#3923 ([common] Move Linear and ScaledBiasRowwiseLinear into
common/linear.py).

- Resolved common/__init__.py: keep our SharedExperts export from feed_forward
  and add main's `from .linear import Linear, ScaledBiasRowwiseLinear`.
- moe_replacement.py: Linear moved out of common/nn_modules into common/linear,
  so update the import (was `from ...nn_modules import Linear`).

Verified: MoE EP=2 trains (12.36 -> 7.16); experiment module + all flavors
import cleanly; lint passes.
@@ -0,0 +1,205 @@
# Copyright (c) Meta Platforms, Inc. and affiliates.

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.

what's the difference between this test and the previous one? seems both are verifying titan MOE vs HF MoE output?

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.

This one is for a particular pretrained model. It load the whole model and compared before and after replacing the MoE block. The previous one created single layer versions of all supported MoE models with random init and compared them. They are meant to be used by the add moe model skill. Will move them under the skill folder. The skill.md documents the purpose.

self._initialize_attributes(model_config)

# block_causal masking can only be expressed via a flex BlockMask;
# the SDPA impl only has is_causal. Fail loud rather than silently

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: we removed sdpa from core titan, no need to mention here and below

kernel.forward = _make_cp_forward(kernel.forward)


def _wire_sdpa_attention_cp(model: nn.Module, cp_mesh: DeviceMesh) -> None:

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.

do we still want to support sdpa? I thought it's removed from core?

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.

purging sdpa from the experiment

return self.w2(F.silu(self.w1(x)) * self.w3(x))


class SharedExperts(FeedForward):

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.

can we rename SharedExperts to sth else? Some model will use FeedForward as the shared experts?

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.

Renaming to SigmoidGatedFeedForward

- `mistralai/Ministral-8B-Instruct-2410`
- MoE (upcoming)
- MoE
- `Qwen/Qwen3-30B-A3B`

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.

is this the only MoE model supported so far?

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.

Oh good catch! let me update the list and also the wrong transformers version at the top

mreso added 7 commits July 17, 2026 10:19
GLM-5 (model_type glm_moe_dsa) crashed under flex with
"'BlockMask' object has no attribute 'dim'": DSA's attention forward inspects
attention_mask.dim() and builds combined_mask = index_mask + causal_mask, so it
needs a dense 4D additive mask, not a flex BlockMask (HF's flex_attention_forward
accepts a dense tensor mask as a score_mask).

- _uses_dsa(config): detect DSA via the index_topk config attr.
- _build_dense_attention_mask(positions): dense [B,1,S,S] additive mask (0/-inf),
  causal (+ same-document for block_causal), mirroring the flex mask mods.
- get_attention_masks returns the dense mask for DSA models; non-DSA flex models
  still get a BlockMask; SDPA path untouched.

Verified causal end-to-end via an A/B logit-leakage test: changing a late token
leaves earlier-position logits bitwise identical (0.0) for GLM-5 flex, matching a
Qwen3 flex positive control; the sensitivity control (early-token change) moves
later logits as expected. GLM-5 flex trains FSDP 12.66 -> 6.69, EP=2 12.29 ->
6.66. Note: the causal term is what DSA's combined_mask adds on top of the
indexer's (dense) top-k selection -- without this dense mask (e.g. the SDPA path,
where create_causal_mask returns None) DSA runs non-causally.
The class is a SwiGLU FeedForward with a per-token sigmoid gate
(sigmoid(gate(x)) * ffn(x)); "SharedExperts" named one use case (the MoE shared
expert) rather than the structure. It can be used as any gated FFN, so rename to
describe what it is. Docstring notes the MoE shared-expert role as the common
(not exclusive) use. Updates all callsites: common exports, qwen3_5, and the HF
backend's moe_replacement.
SDPA is deprecated in core (LM default moved to flex, pytorch#3571) and flex now works
for every architecture this backend supports -- GQA, MLA (all rope variants),
and DSA (GLM-5) -- with DSA verified causal on flex (SDPA+DSA was non-causal:
create_causal_mask returns None for the custom impl, so DSA's combined_mask
dropped the causal term). One path is simpler and removes a silently-wrong mode.

- Dropped the attn_implementation config knob (only one valid value now). Flex is
  wired unconditionally via an internal _ATTN_IMPLEMENTATION="flex_torchtitan"
  constant; removed _uses_flex_attention and all flex/sdpa branching.
- model.py: removed the sdpa_attention_forward import, the SDPA branch in
  _configure_hf_attention, the block_causal-requires-flex guard (moot), and the
  flex early-return / SDPA branches in get_attention_masks / forward. Kept
  _uses_dsa / _build_dense_attention_mask (DSA dense causal mask).
- parallelize.py: removed _wire_sdpa_attention_cp, _cp_sdpa, the SDPA+CP ring
  block and the SDPA+TP+CP guard; kept _wrap_flex_kernel_cp.
- hf_sharding.py: dropped the use_flex param; always attach the flex kernel.
- __init__.py / config_registry.py: base flavors (debugmodel, debugmodel_moe,
  full, full_moe) are flex by default; removed the redundant _flex flavors/configs.
- trainer.py: headtail CP load balancer rejected whenever CP is on.
- tests: dropped the SDPA FSDP+CP integration entry, the sdpa cp_pp_numerical
  case, the --no_flex option, and the SDPA-must-raise unit test.

Verified flex-only across GQA/MLA/DSA/Gemma4/dense/SFT (FSDP/TP/EP/CP/PP combos);
all train with decreasing loss. No SDPA wiring references remain in the backend.
The numerical_equivalence[_pretrained].py diagnostics are skill-driven (invoked
from the add_moe_model workflow, documented only in SKILL.md; not part of the
CI/run_tests.sh harness, not pytest-collected). Move them out of tests/ and into
the skill's own scripts/ folder so the skill is self-contained.

They use absolute lazy imports (from torchtitan...), so they run from any
location -- the invocation just changes from `python -m ...tests.numerical_
equivalence` to `python .../scripts/numerical_equivalence.py`. Updated SKILL.md
(run commands + path refs), the scripts' own usage docstrings, and the
cross-reference comment in tests/test_flex_cp_numerical.py.
Absorbs 3 upstream commits: RL CI fix (pytorch#3930), the FlexAttention spmd_types
output typing change (pytorch#3924), and pytorch#3859 ("[MoE] sibling token_dispatcher +
grouped_experts for composable override"), which refactored the core MoE.

pytorch#3859 required adapting the HF backend (no git conflicts, but silent API/struct
breakage):
- moe_replacement.py: make_experts_config -> make_routed_experts_config +
  make_moe_config(routed_experts=...); dropped the token_dispatcher kwarg from
  the GroupedExperts.Config probe (token_dispatcher moved to RoutedExperts).
- parallelize.py: FSDP expert sharding reads moe.routed_experts.inner_experts
  (was moe.experts).
- state_dict_adapter.py: titan MoE expert FQNs moved experts.* ->
  routed_experts.inner_experts.*; the adapter still emitted the old prefix, so
  load_state_dict(strict=False) silently skipped the expert weights (random init
  -> HF-vs-titan forward cos ~= 0 while the round-trip still passed). Route the
  routed-expert keys through the new prefix; also tighten the gate_up/down
  special-cases to ".experts." so shared_experts can't be misrouted.

Verified: MoE numerical equivalence restored (qwen3_moe/deepseek_v2/olmoe PASS
cos ~= 1.0; mixtral WARN at cos 0.999996 -- the documented bf16-combine band, not
structural); round-trips max_diff=0.00; MoE EP=2 trains 12.33 -> 6.72.
- Reword comments/docstrings to describe attention functionally instead of
  noting it as "the only path" / that SDPA was removed (README, model.py,
  parallelize.py, trainer.py, cp_pp_numerical.py, test_flex_attention.py).
- SigmoidGatedFeedForward docstring: keep the functional description, drop the
  usage prose about MoE shared experts.
- cp_pp_numerical.py: remove the now-single-case --cases flag / _CASES dict;
  inline the flex config + ptrr balancer.

@acisseJZhong acisseJZhong 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.

lgtm, thanks for iterating on this huge PR.

@tianyu-l tianyu-l 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.

Thanks for the hard work!

Some nit comments.

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.

do we really need to add this many items? Can we trim down to those that simultaneously test multiple parallelisms / features?

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.

yeah, will bunch them together to run simultanesouly

## Quick start

- Requirements `transformers==4.57.1`
- Requirements `transformers==5.3.0`

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.

In .ci/docker/requirements-transformers-modeling-backend.txt you had 5.9.0

Comment on lines +49 to +50
Attention runs on **FlexAttention**. The MoE block is swapped to TorchTitan's
grouped-experts MoE to enable expert parallelism and the `grouped_mm` fast path.

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.

mixed attention and MoE description under "Attention" section

@@ -43,7 +73,6 @@ This enables HF transformers models to be trained with `4D parallelism + torch.c

## Further work

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.

Would be great to make titan RL work with this backend out-of-box

output to bf16 before `scatter_add`, causing bf16 accumulation.
HF accumulates in f32 via `reshape+sum`. Additionally, titan uses
`topk(sorted=False)` while HF defaults to `sorted=True`, causing
different f32 rounding in the normalization sum. With all three

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.

what the "three" ones? I only see two.

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.

The first point conflates two of the original points into a single one. Fixed that now.

Comment on lines +30 to +31
Titan's `LocalTokenDispatcher.combine()` casts score-weighted expert
output to bf16 before `scatter_add`, causing bf16 accumulation.

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.

sounds a bit concerning
@acisseJZhong what should be the best practice, could you check some references?

## Numerical Equivalence Summary

All models are tested with production-scale hidden dimensions, reduced
expert count (E=8), and single-layer configs. HF is the gold standard —

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.

what about the KL div after one training step? Will the difference accumulate? And ideally if you turn on those 2 fixes mentioned below, what are the kl div after 1 step?

Titan's `LocalTokenDispatcher.combine()` casts score-weighted expert
output to bf16 before `scatter_add`, causing bf16 accumulation.
HF accumulates in f32 via `reshape+sum`. Additionally, titan uses
`topk(sorted=False)` while HF defaults to `sorted=True`, causing

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.

let's change titan topk to also use topk sorted=True if this aligns better with HF.

scores_for_choice_BLE, k=self.top_k, dim=-1, sorted=False

mreso added 4 commits July 20, 2026 11:49
Absorbs 4 upstream commits (mxfp8 MoE ep=1 pytorch#3935, deepseek mxfp8 debug config
pytorch#3934, model config in Trainer to_dict pytorch#3919, GPU-agnostic AutoParallel tests
pytorch#3805). No conflicts; pytorch#3935 touches common MoE but the HF backend imports and
MoE EP=2 training verified clean (12.35 -> 7.23).
Each test now exercises several parallelism axes at once instead of one per
run, cutting GPU-time ~60-70% while keeping full coverage:

- T1 MoE FSDP+TP+EP+CP (8 GPU): flex attn, MoE swap, FSDP expert-shard, TP,
  EP dispatch, CP all-gather + trainer mask-shard.
- T2 Dense FSDP+TP+PP (8 GPU): dense MLP/attn under FSDP+TP+PP (PP is dense-only
  -- not wired for MoE), last-stage loss.
- T3 Dense CP+PP (4 GPU): CP+PP interaction (CP-sharded BlockMask across stages).
- T4 SFT (2 GPU): block_causal mask, ChatDataset dataloader, weight-load path.

Covers FSDP/TP/EP/CP/PP + MoE + SFT. Verified each combo trains (T1 12.36->6.68,
T2 12.50->9.57, T3 12.60->9.54, T4 10.87->6.72). Known gap accepted: MoE+TP
without EP (experts TP-sharded) is no longer separately tested.
…ture work

- Bump the transformers requirement to 5.9.0 (the version in use).
- Split the mixed Attention/MoE description: Attention section is attention-only
  (flex + attn_mask_type); the MoE-swap description moves under an MoE section
  with the parallelism table.
- Add "spmd_types backend support" and "Support for Titan RL" to Further work.
@mreso
mreso merged commit af35cfb into pytorch:main Jul 20, 2026
18 of 23 checks passed
@github-project-automation github-project-automation Bot moved this from In Progress to Done in TorchTitan Development Jul 20, 2026
Jiarwang77 added a commit to Jiarwang77/torchtitan that referenced this pull request Sep 21, 2026
…ghts

HF rotary modules compute inv_freq in __init__, so meta init + to_empty()
leaves it as uninitialized memory and nothing ever writes real values into it.
The compatibility loop added in pytorch#3772 recomputed it from module.rope_init_fn,
but Transformers 5.0.0 changed that from an instance attribute to a local
variable, so the loop has been a no-op since the pin moved to 5.x in pytorch#2679.
Transformers' own RotaryEmbedding branch in _init_weights does not run either,
because the backend replaces all of that method. Nothing raises, inv_freq is
non-persistent so a checkpoint load does not write it either, and the only
symptom is loss starting at near-random.

Move the population into _init_weights_patched so init_states() reaches it like
any other submodule. The guard is original_inv_freq, the same one Transformers
uses, so the layer-typed rotary modules handled by model-specific _init_weights
overrides are also skipped here. Both buffers are written: dynamic and longrope
re-register inv_freq from original_inv_freq, so leaving that copy uninitialized
corrupts inv_freq a few forwards later.

Add CPU unit tests over meta -> to_empty() -> init_states() that compare
against a rotary module built directly on CPU, so the expected values are
independent of the code under test. unit_test_cpu.yaml skips
torchtitan/experiments, so add a workflow that runs them; it installs from the
pin file, which means the next Transformers bump runs these tests against the
new version instead of silently disabling RoPE again.

Co-authored-by: Cursor <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/rl ciflow/8gpu CLA Signed This label is managed by the Meta Open Source bot.

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

6 participants