Skip to content

[MoE] Make routed expert projections first-class grouped linears - #4539

Merged
sanketpurandare merged 9 commits into
gh/sanketpurandare/15/basefrom
gh/sanketpurandare/15/head
Sep 24, 2026
Merged

sanketpurandare merged 9 commits into
gh/sanketpurandare/15/basefrom
gh/sanketpurandare/15/head

Conversation

@sanketpurandare

@sanketpurandare sanketpurandare commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Summary:
Replace the opaque RoutedExperts.inner_experts owner with explicit w13,
w2, activation_fn, and token_dispatcher children. Add a reusable,
bias-free GroupedLinear whose structured W13 storage is [E, 2, F, D];
grouped GEMM consumes a zero-copy [E, 2F, D] view. Its public configuration
matches Linear: out_features names one projection's output width and
num_linears=2 retains the gate/up axis.

This removes the temporary expert-owner, replacement, and sharding APIs raised
in review. Eager FSDP, GraphTrainer, quantization converters, model-specific
activations, and checkpoint adapters now share one explicit parameter
hierarchy. Logical initializer names retain their shape suffixes (w1_EFD,
w2_EDF, and w3_EFD), while runtime parameters use standard module keys
(w13.weight and w2.weight). HF checkpoint schemas remain compatible through
adapter-boundary conversion. DeepSeek V4 now performs the same native-to-logical
expert conversion as the other adapters, preventing native W13 keys from
leaking into exported HF checkpoints.

FSDP derives matrix-row shard placements through the shared linear helper for
both stacked Linear and GroupedLinear modules; no W13/W2 FQN special case
remains. MoE.num_experts is the canonical runtime expert count, and GPT-OSS
uses the shared MoE.Config without an empty model-specific subclass. The
existing fused-linear state adapter helpers also own the optional
routed W13 split/merge for HF schemas with separate expert projections, while
GPT-OSS and Qwen3.5 retain their fused HF layouts.

The standard MXFP8 and Float8 converters specialize each grouped linear at the
grouped-MM seam. Kimi retains SiTU and its optimizer metadata addresses the
native W13/W2 parameters. GPT-OSS keeps its grouped bias in a model-specific
GroupedLinear subclass and otherwise follows current main: routed expert
matrices are complete locally unless EP shards the expert axis.

MXFP8 grouped linears retain their existing 1x32 weight-scale format. Structured
W13 is flattened without a copy before quantization. Square 32x32 grouped
weights and preventing a columnwise block from spanning an unaligned gate/up
boundary remain a separate follow-up rather than expanding this ownership
refactor.

The parent W13 layout change already resets DeepSeek V3 and Qwen3 deterministic
goldens. GPT-OSS already used one fused W13 grouped GEMM and initialized W13
before W2. Its numerical reset instead comes from changing W13 storage from
HF-interleaved [E, 2F, D] to blocked [E, 2, F, D]: the same random values
now initialize different gate/up rows. A local fixed-weight comparison converts
the interleaved weight and bias into the blocked layout and produces bitwise
equal forward output; only backward reduction ordering may introduce secondary
rounding differences. GPT-OSS A10G fake-PG and real-PG goldens are regenerated
from full-precision TensorBoard metrics.

Test Plan:

  • python -m pytest tests/unit_tests/cpu -q --deselect tests/unit_tests/cpu/test_lora.py::test_lora_forward (1245 passed, 23 skipped, 1 deselected)
  • Focused GraphTrainer scheduling and chunk tests (108 passed, 120 deselected)
  • python -m pytest -q tests/unit_tests/gpu/test_fsdp_moe_sharding.py tests/unit_tests/gpu/flex_shard/test_dist_muon.py tests/unit_tests/gpu/test_fused_swiglu_override.py tests/unit_tests/gpu/test_compile_moe.py (25 passed)
  • Focused Kimi native-FQN/checkpoint tests (2 passed) and grouped-quantization CPU tests (10 passed)
  • Float8 structured-wrapper tests (2 passed); all 12 Float8 GPU tests collect. The local SM103 TorchAO grouped backward kernel is unsupported, so execution remains a B200 CI gate rather than a local workaround.
  • FSDP expert-placement tests cover expert-axis and matrix-row sharding through the generic linear placement helper.
  • State-dict adapter tests cover separate and fused HF expert schemas, including DTensor placement round-trips and DeepSeek V4 key validation.
  • A local old-interleaved versus new-blocked GPT-OSS fixed-weight forward comparison reports torch_equal=True and max_abs_diff=0.0.
  • A10G GPT-OSS fake-PG and real-PG numerics were exported from the exact CI configurations using full-precision TensorBoard metrics.
  • Scoped formatting, flake8, pydoclint, codespell, link, and targeted Pyrefly checks passed. Project-wide Pyrefly retains one unrelated nullable-video-duration baseline error.

CI notes:

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Sep 9, 2026
sanketpurandare added a commit that referenced this pull request Sep 10, 2026
Summary:
Add the single TorchTitan-owned guide for the standalone Dist-MoE backend. It
documents conversion, checkpoint compatibility, the shared MXFP8/FSDP
lifecycle, memory and VMM ownership, pipeline slot planning, configuration, and
cleanup. Kernel and allocator internals remain in the package documentation.
It distinguishes the direct ordinary-eager entry from the registered
ordered-effect entry used under dispatch and tracing.

This change defines no independent runtime contract and does not duplicate
kernel derivations. Examples must continue to match the registered config schema
and the released package API.

Dependencies and risks:
- Documentation follows #4539-#4542/#4559 and the released annex API.
- Broken links or stale examples are release-blocking documentation drift.

Test Plan:
- `pre-commit run --files README.md docs/dist_moe.md`
- Markdown link check and executable validation of copied configuration examples.

ghstack-source-id: cc45371
Pull-Request: #4543
@sanketpurandare sanketpurandare changed the title [Do not review] [MoE] Generalize routed expert parameter ownership [MoE] Generalize routed expert parameter ownership Sep 10, 2026
sanketpurandare added a commit that referenced this pull request Sep 10, 2026
Summary:
Add the single TorchTitan-owned guide for the standalone Dist-MoE backend. It
documents conversion, checkpoint compatibility, the shared MXFP8/FSDP
lifecycle, memory and VMM ownership, pipeline slot planning, configuration, and
cleanup. Kernel and allocator internals remain in the package documentation.
It distinguishes the direct ordinary-eager entry from the registered
ordered-effect entry used under dispatch and tracing.

This change defines no independent runtime contract and does not duplicate
kernel derivations. Examples must continue to match the registered config schema
and the released package API.

Dependencies and risks:
- Documentation follows #4539-#4542/#4559 and the released annex API.
- Broken links or stale examples are release-blocking documentation drift.

Test Plan:
- `pre-commit run --files README.md docs/dist_moe.md`
- Markdown link check and executable validation of copied configuration examples.

ghstack-source-id: cc45371
Pull-Request: #4543
@sanketpurandare
sanketpurandare marked this pull request as ready for review September 10, 2026 20:03
sanketpurandare added a commit that referenced this pull request Sep 11, 2026
Summary:
Add the single TorchTitan-owned guide for the standalone Dist-MoE backend. It
documents conversion, checkpoint compatibility, the shared MXFP8/FSDP
lifecycle, memory and VMM ownership, pipeline slot planning, configuration, and
cleanup. Kernel and allocator internals remain in the package documentation.
It distinguishes the direct ordinary-eager entry from the registered
ordered-effect entry used under dispatch and tracing.

This change defines no independent runtime contract and does not duplicate
kernel derivations. Examples must continue to match the registered config schema
and the released package API.

Dependencies and risks:
- Documentation follows #4539-#4542/#4559 and the released annex API.
- Broken links or stale examples are release-blocking documentation drift.

Test Plan:
- `pre-commit run --files README.md docs/dist_moe.md`
- Markdown link check and executable validation of copied configuration examples.

ghstack-source-id: ec33322
Pull-Request: #4543
sanketpurandare added a commit that referenced this pull request Sep 11, 2026
Summary:
Add the single TorchTitan-owned guide for the standalone Dist-MoE backend. It
documents conversion, checkpoint compatibility, the shared MXFP8/FSDP
lifecycle, memory and VMM ownership, pipeline slot planning, configuration, and
cleanup. Kernel and allocator internals remain in the package documentation.
It distinguishes the direct ordinary-eager entry from the registered
ordered-effect entry used under dispatch and tracing.

This change defines no independent runtime contract and does not duplicate
kernel derivations. Examples must continue to match the registered config schema
and the released package API.

Dependencies and risks:
- Documentation follows #4539-#4542/#4559 and the released annex API.
- Broken links or stale examples are release-blocking documentation drift.

Test Plan:
- `pre-commit run --files README.md docs/dist_moe.md`
- Markdown link check and executable validation of copied configuration examples.

ghstack-source-id: a2aec19
Pull-Request: #4543
sanketpurandare added a commit that referenced this pull request Sep 11, 2026
Summary:
Add the single TorchTitan-owned guide for the standalone Dist-MoE backend. It
documents conversion, checkpoint compatibility, the shared MXFP8/FSDP
lifecycle, memory and VMM ownership, pipeline slot planning, configuration, and
cleanup. Kernel and allocator internals remain in the package documentation.
It distinguishes the direct ordinary-eager entry from the registered
ordered-effect entry used under dispatch and tracing.

This change defines no independent runtime contract and does not duplicate
kernel derivations. Examples must continue to match the registered config schema
and the released package API.

Dependencies and risks:
- Documentation follows #4539-#4542/#4559 and the released annex API.
- Broken links or stale examples are release-blocking documentation drift.

Test Plan:
- `pre-commit run --files README.md docs/dist_moe.md`
- Markdown link check and executable validation of copied configuration examples.

ghstack-source-id: a2aec19
Pull-Request: #4543
sanketpurandare added a commit that referenced this pull request Sep 11, 2026
Summary:
Add the single TorchTitan-owned guide for the standalone Dist-MoE backend. It
documents conversion, checkpoint compatibility, the shared MXFP8/FSDP
lifecycle, memory and VMM ownership, pipeline slot planning, configuration, and
cleanup. Kernel and allocator internals remain in the package documentation.
It distinguishes the direct ordinary-eager entry from the registered
ordered-effect entry used under dispatch and tracing.

This change defines no independent runtime contract and does not duplicate
kernel derivations. Examples must continue to match the registered config schema
and the released package API.

Dependencies and risks:
- Documentation follows #4539-#4542/#4559 and the released annex API.
- Broken links or stale examples are release-blocking documentation drift.

Test Plan:
- `pre-commit run --files README.md docs/dist_moe.md`
- Markdown link check and executable validation of copied configuration examples.

ghstack-source-id: d0a1e01
Pull-Request: #4543
sanketpurandare added a commit that referenced this pull request Sep 11, 2026
Summary:
Add the single TorchTitan-owned guide for the standalone Dist-MoE backend. It
documents conversion, checkpoint compatibility, the shared MXFP8/FSDP
lifecycle, memory and VMM ownership, pipeline slot planning, configuration, and
cleanup. Kernel and allocator internals remain in the package documentation.
It distinguishes the direct ordinary-eager entry from the registered
ordered-effect entry used under dispatch and tracing.

This change defines no independent runtime contract and does not duplicate
kernel derivations. Examples must continue to match the registered config schema
and the released package API.

Dependencies and risks:
- Documentation follows #4539-#4542/#4559 and the released annex API.
- Broken links or stale examples are release-blocking documentation drift.

Test Plan:
- `pre-commit run --files README.md docs/dist_moe.md`
- Markdown link check and executable validation of copied configuration examples.

ghstack-source-id: 8b8aaed
Pull-Request: #4543
Comment on lines 101 to -104
"num_shared_experts": (
moe.shared_experts.w13.out_features
// 2
// moe.routed_experts.inner_experts.hidden_dim

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 is confusing, and sounds buggy? cc @shuhuayu

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.

the existing script needs a refactor to adapt to inner_experts change, so it should be fine.

Comment on lines 48 to 53
return _quantize_then_scaled_grouped_mm(
A,
input_RI,
weight_EOI.bfloat16().transpose(-2, -1),
config=self._mxfp8_op_config,
offs=offs,
offs=offsets_E,
)

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.

Does this work with fused layout out of box? cc @anijain2305

@anijain2305 anijain2305 Sep 15, 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.

yes, it works.

Although there are pre-existing problems here that we should tackle separately

  • MxFP8GroupedLinear only supports 1x32 scales (not 32x32 as we do for MxFP8Linear and very soon for DistMoE). We have paused mxfp8 work for experts for dist_moe.
  • Again this is pre-existing, on the backward colwise quantization, there is no check that a block should only contain values from either gate or up logical tensors. So, it is possible that we end up with few blocks spanning the two matrices.

We should treat this as a followup (if we decide to do this).

w13=GroupedLinear.Config(
group_size=num_experts,
in_features=dim,
out_features=(2, hidden_dim),

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.

API different from your stacked linear, better to align (to either) @anijain2305

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 am not using stacked linear anymore, its folded into Linear - #4676 (still wip though).

Comment thread torchtitan/models/gpt_oss/moe.py Outdated
from torchtitan.models.common.moe import MoE


class ScaleBiasForward(torch.autograd.Function):

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.

Comment thread torchtitan/models/gpt_oss/moe.py Outdated
return output_RO + bias_RO.to(output_RO.dtype)


class GptOssDownGroupedLinear(GptOssGroupedLinear):

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.

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review this PR and check my latest comments. In particular, focus on

  • quantization correctness after output_features can have multiple dims
  • state_dict_adapter correctness / invariance

@claude

claude Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 21m 17s —— View job


Review — focus: quantization multi-dim output_features & state_dict adapter invariance

  • Read GroupedLinear and the structured-W13 forward
  • Quantization correctness (mxfp8/experts.py, float8.py, utils.py)
  • state_dict adapter correctness / invariance (v3/v4/qwen3/qwen3_5/gpt_oss/kimi_k3)
  • Cross-check @tianyu-l's latest inline comments

1. Quantization after output_features can be multi-dim — looks correct ✅

This addresses the concern on mxfp8/experts.py:53 ("Does this work with the fused layout out of the box?"). It does, and the reason is that the structured axis never reaches the quantized GEMM:

# torchtitan/models/common/linear.py:91-98
output_shape = self.weight.shape[1:-1]        # (2, F) for w13
weight_EOI   = self.weight.flatten(1, -2)     # [E, 2, F, D] -> [E, 2F, D]  (zero-copy view, contiguous)
output_RO    = self._grouped_mm(input_RI=input_RI, weight_EOI=weight_EOI, offsets_E=offsets_E)  # [R, 2F]
return output_RO.reshape(*output_RO.shape[:-1], *output_shape)   # [R, 2, F]

Both _quantize_then_scaled_grouped_mm overrides (float8 float8.py:67-77, mxfp8 experts.py:43-53) receive the already-flattened weight_EOI = [E, 2F, D], identical to the base torch._grouped_mm path. The [R, 2, F] reshape is a pure view applied to the GEMM output, after quantization. So:

  • Rowwise fp8: per-output-row scales over the 2F rows — equivalent to quantizing gate and up as two independent rowwise GEMMs.
  • MXFP8: block scales run along the contraction dim D; 2F is just the batched output-feature dim, so fusing gate+up doesn't perturb block-scale computation.

Numerically the fused [E, 2F, D] quantization equals per-projection quantization. The flatten(1, -2) is a view (weight is contiguous [E,2,F,D]), so no copy. This is consistent with the PR's claim of bitwise match vs. the per-expert BF16 reference. No issue here.


2. state_dict adapters — one real bug in DeepSeek V4 to_hf 🐞

torchtitan/models/utils.py — the round-trip helpers are correct and invariant. _to_logical_expert_state (select(1,0)/select(1,1)) and _to_native_expert_state (torch.stack(..., dim=1)) are exact inverses, and torch.stack at dim=1 correctly shifts a Shard(2) placement back onto the 4D expert weight — this is what test_roundtrip_preserves_mtp_expert_placements covers for both Shard(0) and Shard(2). V3, Qwen3, Qwen3.5, GPT-OSS, and Kimi K3 all pre-convert via _to_logical_expert_state at the top of to_hf and re-fuse via _to_native_expert_state at the end of from_hf, so their gate/up handling is sound.

But DeepSeekV4StateDictAdapter.to_hf never runs the logical conversion, and its delegation gate silently drops the fused gate/up weights:

# torchtitan/models/utils.py:109-118  — note w13.weight is NOT in this tuple
def _is_expert_weight_key(key: str) -> bool:
    """Return whether ``key`` is a canonical or logical expert projection."""
    return key.endswith(
        (".moe.routed_experts.w1_EFD",
         ".moe.routed_experts.w2.weight",
         ".moe.routed_experts.w3_EFD"))
# torchtitan/models/deepseek_v4/state_dict_adapter.py:147-159
def _can_delegate_titan_key(self, key, to_hf_map):
    if key in to_hf_map or self._is_expert_weight_key(key):   # w13.weight matches neither
        return True
    ...
    if "layers" in key:
        return self._abstract_key(key, count=1) in to_hf_map  # "...routed_experts.w13.weight" not in map either
    return False

V4's to_hf operates on the native state dict (it does not call _to_logical_expert_state). For a routed layer:

  • layers.N.moe.routed_experts.w2.weight → matched by _is_expert_weight_key → delegated to super().to_hf() → split into HF ...ffn.experts.M.w2.weight. ✅
  • layers.N.moe.routed_experts.w13.weight → matches nothing → falls into the else: hf_state_dict[key] = value branch → leaked verbatim as a torchtitan key, never split into ffn.experts.M.w1/w3.weight.

So the exported "HF" checkpoint is asymmetric: down-proj experts are present under proper HF names, but gate/up experts are missing (emitted as a stray layers.N.moe.routed_experts.w13.weight). The V4 round-trip test passes only because from_hf mirrors the leak (that key isn't recognized on the way back either, so it passes through), giving TT→HF→TT identity while the intermediate HF dict is wrong. test_full_model_roundtrip_with_optional_mtp asserts key/value identity and attn_sink, but never checks the expert HF key names, so the gap is uncaught.

Note from_hf from a real HF checkpoint is fine: ffn.experts.* contains the hf_experts_key_fragment, so it delegates to super().from_hf() which re-fuses via _to_native_expert_state. Only the export direction is broken.

Fix (one line): make _is_expert_weight_key also match the canonical fused key — this matches its own docstring ("canonical or logical expert projection") and routes w13.weight into super().to_hf(), which calls _to_logical_expert_state and splits correctly. It's inert for the adapters that pre-convert (they no longer have a w13.weight key by the time the matcher runs):

return key.endswith(
    (".moe.routed_experts.w1_EFD",
     ".moe.routed_experts.w13.weight",   # canonical fused param (DeepSeek V4 delegates natively)
     ".moe.routed_experts.w2.weight",
     ".moe.routed_experts.w3_EFD"))

Please also add a V4 assertion on the produced HF keys (e.g. layers.{n}.ffn.experts.{e}.w1.weight / .w3.weight present, no routed_experts.w13 leakage) so this can't regress. Fix this →


3. Other observations on @tianyu-l's latest comments

  • config_utils.py:461 (reviewer: "API different from your stacked linear, better to align") — confirmed inconsistency: make_routed_experts_config uses the structured out_features=(2, hidden_dim) for W13, while the dense make_ffn_config (config_utils.py:319) uses the flat out_features=2 * hidden_dim. Two spellings of the same fused gate/up shape. Worth aligning on one (the structured tuple reads better and is what RoutedExperts.Config.__post_init__ validates against).
  • gpt_oss/moe.py:22 / :146 (reviewer: delete ScaleBiasForward in favor of the linear.py:146 PartialBiasRowwiseLinear style) — agreed. GptOssDownGroupedLinear re-implements the "scale bias by 1/tp in forward, identity in backward" logic that PartialBiasRowwiseLinear already expresses declaratively via spmd.convert(..., src=I, dst=P). The grouped case differs only in that the bias is expert-grouped, but the forward-scaling concern is the same; consolidating would remove the custom autograd Function.
  • numerical_tests_kimi_k3.py:104 (reviewer: "confusing, sounds buggy") — num_shared_experts = shared_experts.w13.out_features // 2 // routed_experts.w2.in_features infers a count from the ratio of the shared hidden size to the routed expert hidden size. It's correct only if the shared FFN hidden is an exact integer multiple of the routed expert hidden; otherwise it silently floors. Deferring to @shuhuayu as the reviewer noted, but a comment explaining the invariant (or an assert on exact divisibility) would remove the "sounds buggy" smell.
  • GPT-OSS interleave (gpt_oss/state_dict_adapter.py:108,142) — verified correct and invariant: to_hf does transpose(1,2).flatten(1,2) ([E,2,F,D]→[E,F,2,D]→[E,2F,D], interleaved gate/up per feature) and from_hf does unflatten(1,(-1,2)).transpose(1,2), exact inverse. Bias likewise.

Net: the quantization path is sound; the actionable item is the DeepSeek V4 to_hf gate/up leakage above.
· branch gh/sanketpurandare/15/head

Comment thread torchtitan/models/kimi_k3/sharding.py Outdated

if TYPE_CHECKING:
from torchtitan.models.kimi_k3.model import KimiK3Model
from torchtitan.models.kimi_k3.vision_encoder import KimiK3VisionEncoder

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.

Are the removals in this file intended?

Comment thread torchtitan/models/gpt_oss/moe.py Outdated
@@ -61,105 +62,110 @@ def backward(ctx, grad_output):

def swiglu(x, alpha: float = 1.702, limit: float = 7.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.

is anyone using this function now? If not then move swiglu_components inside the GptOssSwiGLU __call__?

Comment thread torchtitan/models/gpt_oss/moe.py Outdated
super().__init__(config)
self.tp_degree = 1

def parallelize(self, parallel_dims) -> None:

@anijain2305 anijain2305 Sep 15, 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.

I have been asked to not override parallelize method in the past. I have not yet fully understood why. Just pointing out.

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.

parallelize is more like Module-internal, which is used for recursively apply sharding, rather than plugging in attributes -- I had been wanting to make it private.

To get TP degree, use spmd_types.py context

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.

Use

tp_group = spmd_mesh_group(MeshAxisName.TP)
if tp_group is None:
    ....

missing = {"w1_EFD", "w3_EFD"} - param_init.keys()
if missing:
raise ValueError(f"Missing routed-expert initializers: {sorted(missing)}")
return {"weight": _fused_grouped_gate_up_init(param_init)}

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 - inline _fused_grouped_gate_up_init - codex insane error checking just keeps adding helper indirections.

Comment thread torchtitan/models/kimi_k3/sharding.py Outdated
for layer in config.layers:
if layer.delta_attention is not None:
_set_inner_kda_sharding(layer.delta_attention.inner_kda)
if layer.moe is not 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.

It seems like you have accidentally removed the kda sharding. This seems to be unintentional.

Comment thread torchtitan/models/kimi_k3/sharding.py Outdated
)


def _set_vision_buffer_sharding(config: "KimiK3VisionEncoder.Config") -> 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.

same here - seems unintentional.

@anijain2305

Copy link
Copy Markdown
Contributor

Overall looks great. Left a few comments. The changes in kimi3 seems wrong, and gpt-oss as others have pointed out might use a refactors.

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]

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

I'd say it might be easier to review if you merged the two PRs together.

Comment thread torchtitan/distributed/fsdp.py Outdated
Comment on lines +328 to +329
**{param: Shard(2) for param in routed_experts.w13.parameters()},
**{param: Shard(1) for param in routed_experts.w2.parameters()},

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 hardcoding w13, do something similar or in _linear_param_shard_placements

Comment thread torchtitan/models/common/linear.py Outdated
group_size: Number of independently selected linear weights.
in_features: Input features for each linear.
out_features: Output features for each linear.
num_linears: Number of projections stored per group. Values greater

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.

"Number of projections stored per group" is not correct -- the entire GroupedLinear is a single group.

Maybe something like "number of stacked linears per element in the group"

Comment thread torchtitan/models/utils.py Outdated
@@ -55,37 +55,47 @@ def __init__(
def _to_logical_expert_state(

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.

Comment on lines -112 to -115
# if no EP, convert to V for grouped_mm, which would otherwise see
# x:R, w1:V, offsets:P in local SPMD typechecking.
# spmd.P is not currently allowed to mix with spmd.V.
# TODO(pianpwk): likely relax this in spmd_types.

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.

comments and todos are gone

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.

Restored the local-SPMD comment and TODO at the new ownership boundary. It now explains why offsets are retyped from P to V when EP is absent and records the existing spmd_types restriction that should eventually be relaxed.

[ghstack-poisoned]

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

please address final nits

Comment thread torchtitan/models/gpt_oss/moe.py Outdated
return output_RO + bias_RO.to(output_RO.dtype)


class GptOssMoE(MoE):

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.

seems useless, can remove

Comment thread torchtitan/distributed/fsdp.py Outdated
experts = transformer_block.moe.routed_experts.inner_experts
num_experts = experts.num_experts
routed_experts = transformer_block.moe.routed_experts
num_experts = routed_experts.w13.group_size

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.

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude
Please review gpt-oss MoE changes

  • Question 1: is it preserving the correctness, under various parallelisms?
  • Question 2: where does the numerics change come from, exactly?

@claude

claude Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 3m 30s —— View job


GPT-OSS MoE review

  • Read the GPT-OSS moe.py, sharding.py, state_dict_adapter.py and __init__.py diffs, plus the shared GroupedLinear, RoutedExperts, FSDP and MoE-sharding code
  • Q1: correctness under each parallelism
  • Q2: where the numerics change comes from

Q1: Is correctness preserved under the different parallelisms?

Yes, as far as I can tell from reading the code. With fixed weights, the new forward does the same work as the old one. Only the storage layout changed: the old interleaved [E, 2F, D] (row 2f = gate, 2f+1 = up) became a blocked [E, 2, F, D].

Path Old (GptOssGroupedExperts) New (GptOssGroupedLinear for w13 and w2) Verdict
w13 GEMM one _grouped_mm on mlp1_weight_EGD [E,2F,D] one _grouped_mm on the zero-copy view w13.weight.flatten(1,-2) → [E,2F,D] Same shape. Output columns are just permuted.
w13 bias repeat_interleave of [E+1, 2F] with tail slack, .to(bf16), add bias.flatten(1) → the same expansion (counts come from diff(offsets), which equals num_tokens_per_expert), reshape_as, .to(bf16), add Equivalent
Activation x[..., ::2] / x[..., 1::2], then clamp / sigmoid / addcmul unbind(-2), then the same element-wise formula (GptOssSwiGLU) Same per element
w2 and bias GEMM plus expanded bias; no TP scaling (already gone on base) Same Equivalent
Output dtype returned bf16 as-is .type_as(routed_input_RD) in RoutedExperts.forward Changes nothing when activations are bf16 (every CI config uses FSDP bf16). In fp32-activation runs the routed output is now upcast before combine. This matches what common experts already did.
EP (sparse state) GPT-OSS overrode all 4 params with expert_param_placement_sparse() common code sets weight; gpt_oss/sharding.py:123-130 adds bias to w13 and w2 Correct. Each layer, and each of w13/w2, gets its own ShardingConfig object from _routed_experts_sharding_configs, so mutating state_shardings in place doesn't alias across layers.
FSDP / EFSDP, efsdp_ep_size <= E Shard(0) for every expert param Shard(0) for every routed_experts param Same
FSDP / EFSDP, efsdp_ep_size > E (row shard) Shard(1) on all four (mlp1_weight_EGD row 2F, mlp1_bias_EG 2F, mlp2_weight_EDF D, mlp2_bias_ED D) _linear_param_shard_placements(include_unstacked_grouped=True): w13.weight Shard(2) (F), w13.bias Shard(2) (F), w2.weight Shard(1) (D), w2.bias Shard(1) (D) Correct. The gate/up axis is never split, so every rank holds matching gate/up rows. This is slightly nicer than before, when the interleaved 2F split was only correct because each shard had an even size.
TP without EP expert sharding is None, so params are replicated over TP and there is no bias scaling same (w13_config / w2_config are None) Same
CP / PP (gpt_oss_pp: FSDP2 · CP2 · EP4 · PP2) offsets P→V retype on dp/cp when EP=1 the retype moved into RoutedExperts.forward and is applied to offsets_E rather than to the counts Equivalent
MXFP8 / Float8 subclassed GptOssGroupedExperts and overrode _grouped_mm _get_*_grouped_linear_cls(GptOssGroupedLinear) subclasses the GPT-OSS class, so its biased forward is kept and only _grouped_mm is swapped Correct. test_quantization.py:434-440 checks this.
HF checkpoint [E,2F,D] mapped 1:1 onto the HF interleaved gate_up_proj to_hf: transpose(1,2).flatten(1,2); from_hf: unflatten(1,(-1,2)).transpose(1,2) Exact inverses, and they reproduce HF's interleaved layout. The HF-side shape is still [E,2F,D], so QuantizedHuggingFaceStorageReader (MXFP4 dequant) still matches. Under row-sharded DTensors (Shard(2) → Shard(1) after the transpose → flatten), the sharded dim is the outer one of the flattened pair, so the view is legal.

Some smaller points:

  • _expand_grouped_bias rebuilds counts with torch.diff(cat(0, offsets_E)). RoutedExperts already had num_global_tokens_per_local_expert_e and threw it away. Passing the counts through would save a cat and a diff per call, but it would widen the GroupedLinear.forward signature, so I'd leave it.
  • I couldn't find a unit test that checks old vs new GPT-OSS expert output with fixed weights. The PR body says "Fixed-weight tests cover the layout and operator mapping", but the GPT-OSS tests I found only cover the activation formula (test_gpt_oss_moe.py), subclass preservation under quantization, and the adapter round-trip. A small CPU test would lock in the layout mapping: build the old interleaved reference inline, copy weights through unflatten(1,(-1,2)).transpose(1,2), and check torch.equal on the forward. I tried to run this comparison locally, but the Python command needed approval in this environment, so the equivalence above comes from reading the code, not from a run.

Q2: Where exactly does the numerics change come from?

Only the parameter initialization changes the forward. The compute graph does not. The backward also differs, but only at the rounding level.

1. Main cause: the same RNG stream now lands in a different logical layout.
init_states goes through RoutedExperts children in order: w13 (weight, bias), then w2 (weight, bias). The old order was mlp1_weight, mlp1_bias, mlp2_weight, mlp2_bias. So the RNG is consumed in the same order and in the same amounts (E·2F·D, E·2F, …). trunc_normal_ writes in flat storage order, so:

  • old: flat row r → gate if r is even (gate[r/2]), up if odd
  • new: flat row r → gate[r] for r < F, up[r-F] otherwise

The random values are the same, but the new gate/up pairs are (r, F+r) where they used to be (2f, 2f+1). The w2 columns didn't move to match, so the new from-seed model is not a hidden-unit permutation of the old one. It is a different sample from the same distribution. The w13 bias [E,2F] → [E,2,F] gets the same treatment. This explains why the loss differs already at step 1 (fake-PG 7.2469 → 7.6392, real-PG 8.1556 → 7.9562). A compute-only change would give ulp-level differences at step 1, not a gap of 0.2–0.4.

2. Secondary, rounding-level: the order of reduction in the backward.
Once weights are mapped through the adapter, the forward should be bit-identical. Each output element of the w13 GEMM is the same D-length dot product; its column just moved. In the backward, however, dX = dH_R(2F) @ W_(2F)D sums over the 2F axis, and that axis now runs in blocked rather than interleaved order. That changes the fp accumulation order, so the input gradients (and everything upstream of them) are not bitwise equal. The grad_norm reduction over the permuted w13/bias gradients is affected the same way. These effects are tiny next to #1.

3. What does not contribute: the GEMM count and shape (still one [E,2F,D] w13 GEMM plus one w2 GEMM), bias dtype handling, the activation formula, sharding placements under the CI configs, and the type_as (a no-op with bf16 activations).

The PR description is inaccurate for GPT-OSS. It says the move "changes its from-seed RNG order from W1, W2, W3 to W1, W3, W2 and replaces two BF16 grouped GEMMs with one wider W13 grouped GEMM". That describes the DeepSeek/Qwen path in #4643. GPT-OSS on base already had a single fused mlp1_weight_EGD GEMM and already initialized in w13 → w2 order. The accurate description for GPT-OSS is: "gate/up storage changes from HF-interleaved [E,2F,D] to blocked [E,2,F,D], so the same from-seed RNG values are assigned to different gate/up rows. Compute is unchanged with fixed weights."

One way to prove this is to regenerate a golden with a one-off init hook: initialize an [E,2F,D] temporary exactly as before, then copy it into w13.weight with unflatten(1,(-1,2)).transpose(1,2) (same for the bias). The loss at step 1 should match the old golden to within ulp. Fix this →


Summary: I found no correctness issue in the GPT-OSS changes under EP, EFSDP (both the expert-dim and row-shard paths), TP-without-EP, CP, PP, MXFP8/Float8, or the HF round-trip. The golden shift comes from the init-layout change, plus rounding-level backward differences. The PR description's explanation of it is wrong for GPT-OSS and should be fixed. It would also be worth adding a fixed-weight old-vs-new test for GPT-OSS.

[ghstack-poisoned]
…inears"

Summary:
Replace the opaque `RoutedExperts.inner_experts` owner with explicit `w13`,
`w2`, `activation_fn`, and `token_dispatcher` children. Add a reusable,
bias-free `GroupedLinear` whose structured W13 storage is `[E, 2, F, D]`;
grouped GEMM consumes a zero-copy `[E, 2F, D]` view. Its public configuration
matches `Linear`: `out_features` names one projection's output width and
`num_linears=2` retains the gate/up axis.

This removes the temporary expert-owner, replacement, and sharding APIs raised
in review. Eager FSDP, GraphTrainer, quantization converters, model-specific
activations, and checkpoint adapters now share one explicit parameter
hierarchy. Logical initializer names retain their shape suffixes (`w1_EFD`,
`w2_EDF`, and `w3_EFD`), while runtime parameters use standard module keys
(`w13.weight` and `w2.weight`). HF checkpoint schemas remain compatible through
adapter-boundary conversion. DeepSeek V4 now performs the same native-to-logical
expert conversion as the other adapters, preventing native W13 keys from
leaking into exported HF checkpoints.

FSDP derives matrix-row shard placements through the shared linear helper for
both stacked `Linear` and `GroupedLinear` modules; no W13/W2 FQN special case
remains. `MoE.num_experts` is the canonical runtime expert count, and GPT-OSS
uses the shared `MoE.Config` without an empty model-specific subclass. The
existing fused-linear state adapter helpers also own the optional
routed W13 split/merge for HF schemas with separate expert projections, while
GPT-OSS and Qwen3.5 retain their fused HF layouts.

The standard MXFP8 and Float8 converters specialize each grouped linear at the
grouped-MM seam. Kimi retains SiTU and its optimizer metadata addresses the
native W13/W2 parameters. GPT-OSS keeps its grouped bias in a model-specific
`GroupedLinear` subclass and otherwise follows current main: routed expert
matrices are complete locally unless EP shards the expert axis.

MXFP8 grouped linears retain their existing 1x32 weight-scale format. Structured
W13 is flattened without a copy before quantization. Square 32x32 grouped
weights and preventing a columnwise block from spanning an unaligned gate/up
boundary remain a separate follow-up rather than expanding this ownership
refactor.

The parent W13 layout change already resets DeepSeek V3 and Qwen3 deterministic
goldens. GPT-OSS already used one fused W13 grouped GEMM and initialized W13
before W2. Its numerical reset instead comes from changing W13 storage from
HF-interleaved `[E, 2F, D]` to blocked `[E, 2, F, D]`: the same random values
now initialize different gate/up rows. A local fixed-weight comparison converts
the interleaved weight and bias into the blocked layout and produces bitwise
equal forward output; only backward reduction ordering may introduce secondary
rounding differences. GPT-OSS A10G fake-PG and real-PG goldens are regenerated
from full-precision TensorBoard metrics.

Test Plan:
- `python -m pytest tests/unit_tests/cpu -q --deselect tests/unit_tests/cpu/test_lora.py::test_lora_forward` (1245 passed, 23 skipped, 1 deselected)
- Focused GraphTrainer scheduling and chunk tests (108 passed, 120 deselected)
- `python -m pytest -q tests/unit_tests/gpu/test_fsdp_moe_sharding.py tests/unit_tests/gpu/flex_shard/test_dist_muon.py tests/unit_tests/gpu/test_fused_swiglu_override.py tests/unit_tests/gpu/test_compile_moe.py` (25 passed)
- Focused Kimi native-FQN/checkpoint tests (2 passed) and grouped-quantization CPU tests (10 passed)
- Float8 structured-wrapper tests (2 passed); all 12 Float8 GPU tests collect. The local SM103 TorchAO grouped backward kernel is unsupported, so execution remains a B200 CI gate rather than a local workaround.
- FSDP expert-placement tests cover expert-axis and matrix-row sharding through the generic linear placement helper.
- State-dict adapter tests cover separate and fused HF expert schemas, including DTensor placement round-trips and DeepSeek V4 key validation.
- A local old-interleaved versus new-blocked GPT-OSS fixed-weight forward comparison reports `torch_equal=True` and `max_abs_diff=0.0`.
- A10G GPT-OSS fake-PG and real-PG numerics were exported from the exact CI configurations using full-precision TensorBoard metrics.
- Scoped formatting, flake8, pydoclint, codespell, link, and targeted Pyrefly checks passed. Project-wide Pyrefly retains one unrelated nullable-video-duration baseline error.

CI notes:
- The B200 run https://github.com/pytorch/torchtitan/actions/runs/35924519733 failed while extracting the repository checkout (`gzip: unexpected end of file`) before tests executed.
- The GraphTrainer failures in https://github.com/pytorch/torchtitan/actions/runs/35924514118 and https://github.com/pytorch/torchtitan/actions/runs/35924514111 reproduce in scheduled upstream-main runs https://github.com/pytorch/torchtitan/actions/runs/35860469802 and https://github.com/pytorch/torchtitan/actions/runs/35859018087, respectively.

[ghstack-poisoned]
@sanketpurandare

Copy link
Copy Markdown
Contributor Author

Kept these as two PRs because they have separate ownership and review surfaces: #4643 introduces the structured physical W13 layout, while this PR introduces first-class GroupedLinear ownership and migrates the model, sharding, quantization, and checkpoint integrations. Each PR remains independently coherent and tested.

@sanketpurandare

Copy link
Copy Markdown
Contributor Author

Addressed the final nits and reconciled the older displaced comments: GPT-OSS now uses the shared GroupedLinear and BinaryActivationFn paths; the unused activation and initializer helpers and custom TP parallelize() path are gone; Kimi KDA and multimodal sharding are restored; FSDP placement is generic; the num_linears documentation is corrected; state conversion uses the shared fused-linear adapter; the local-SPMD rationale and TODO are restored; the empty GptOssMoE is removed; and MoE.num_experts is the canonical expert count used by FSDP. The current lint run passes, including Pyrefly.

@sanketpurandare

sanketpurandare commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor Author

The GPT-OSS description now states the precise source of the deterministic reset: GPT-OSS already had one fused W13 grouped GEMM and initialized W13 before W2; changing storage from HF-interleaved [E, 2F, D] to blocked [E, 2, F, D] assigns the same random values to different gate/up rows. I also removed the empty GptOssMoE, made MoE.num_experts the canonical runtime expert count, and made FSDP consume that value. I kept the requested old/new comparison local rather than adding redundant permanent test coverage.

…inears"

Summary:
Replace the opaque `RoutedExperts.inner_experts` owner with explicit `w13`,
`w2`, `activation_fn`, and `token_dispatcher` children. Add a reusable,
bias-free `GroupedLinear` whose structured W13 storage is `[E, 2, F, D]`;
grouped GEMM consumes a zero-copy `[E, 2F, D]` view. Its public configuration
matches `Linear`: `out_features` names one projection's output width and
`num_linears=2` retains the gate/up axis.

This removes the temporary expert-owner, replacement, and sharding APIs raised
in review. Eager FSDP, GraphTrainer, quantization converters, model-specific
activations, and checkpoint adapters now share one explicit parameter
hierarchy. Logical initializer names retain their shape suffixes (`w1_EFD`,
`w2_EDF`, and `w3_EFD`), while runtime parameters use standard module keys
(`w13.weight` and `w2.weight`). HF checkpoint schemas remain compatible through
adapter-boundary conversion. DeepSeek V4 now performs the same native-to-logical
expert conversion as the other adapters, preventing native W13 keys from
leaking into exported HF checkpoints.

FSDP derives matrix-row shard placements through the shared linear helper for
both stacked `Linear` and `GroupedLinear` modules; no W13/W2 FQN special case
remains. `MoE.num_experts` is the canonical runtime expert count, and GPT-OSS
uses the shared `MoE.Config` without an empty model-specific subclass. The
existing fused-linear state adapter helpers also own the optional
routed W13 split/merge for HF schemas with separate expert projections, while
GPT-OSS and Qwen3.5 retain their fused HF layouts.

The standard MXFP8 and Float8 converters specialize each grouped linear at the
grouped-MM seam. Kimi retains SiTU and its optimizer metadata addresses the
native W13/W2 parameters. GPT-OSS keeps its grouped bias in a model-specific
`GroupedLinear` subclass and otherwise follows current main: routed expert
matrices are complete locally unless EP shards the expert axis.

MXFP8 grouped linears retain their existing 1x32 weight-scale format. Structured
W13 is flattened without a copy before quantization. Square 32x32 grouped
weights and preventing a columnwise block from spanning an unaligned gate/up
boundary remain a separate follow-up rather than expanding this ownership
refactor.

The parent W13 layout change already resets DeepSeek V3 and Qwen3 deterministic
goldens. GPT-OSS already used one fused W13 grouped GEMM and initialized W13
before W2. Its numerical reset instead comes from changing W13 storage from
HF-interleaved `[E, 2F, D]` to blocked `[E, 2, F, D]`: the same random values
now initialize different gate/up rows. A local fixed-weight comparison converts
the interleaved weight and bias into the blocked layout and produces bitwise
equal forward output; only backward reduction ordering may introduce secondary
rounding differences. GPT-OSS A10G fake-PG and real-PG goldens are regenerated
from full-precision TensorBoard metrics.

Test Plan:
- `python -m pytest tests/unit_tests/cpu -q --deselect tests/unit_tests/cpu/test_lora.py::test_lora_forward` (1245 passed, 23 skipped, 1 deselected)
- Focused GraphTrainer scheduling and chunk tests (108 passed, 120 deselected)
- `python -m pytest -q tests/unit_tests/gpu/test_fsdp_moe_sharding.py tests/unit_tests/gpu/flex_shard/test_dist_muon.py tests/unit_tests/gpu/test_fused_swiglu_override.py tests/unit_tests/gpu/test_compile_moe.py` (25 passed)
- Focused Kimi native-FQN/checkpoint tests (2 passed) and grouped-quantization CPU tests (10 passed)
- Float8 structured-wrapper tests (2 passed); all 12 Float8 GPU tests collect. The local SM103 TorchAO grouped backward kernel is unsupported, so execution remains a B200 CI gate rather than a local workaround.
- FSDP expert-placement tests cover expert-axis and matrix-row sharding through the generic linear placement helper.
- State-dict adapter tests cover separate and fused HF expert schemas, including DTensor placement round-trips and DeepSeek V4 key validation.
- A local old-interleaved versus new-blocked GPT-OSS fixed-weight forward comparison reports `torch_equal=True` and `max_abs_diff=0.0`.
- A10G GPT-OSS fake-PG and real-PG numerics were exported from the exact CI configurations using full-precision TensorBoard metrics.
- Scoped formatting, flake8, pydoclint, codespell, link, and targeted Pyrefly checks passed. Project-wide Pyrefly retains one unrelated nullable-video-duration baseline error.

CI notes:
- The B200 run https://github.com/pytorch/torchtitan/actions/runs/35924519733 failed while extracting the repository checkout (`gzip: unexpected end of file`) before tests executed.
- The GraphTrainer failures in https://github.com/pytorch/torchtitan/actions/runs/35924514118 and https://github.com/pytorch/torchtitan/actions/runs/35924514111 reproduce in scheduled upstream-main runs https://github.com/pytorch/torchtitan/actions/runs/35860469802 and https://github.com/pytorch/torchtitan/actions/runs/35859018087, respectively.

[ghstack-poisoned]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/b200 Trigger B200 CI ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/h100.8 Trigger H100.8 CI 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.

6 participants