Skip to content

Make fused grouped-expert projection the default - #4552

Closed
anijain2305 wants to merge 27 commits into
gh/anijain2305/15/basefrom
gh/anijain2305/15/head
Closed

anijain2305 wants to merge 27 commits into
gh/anijain2305/15/basefrom
gh/anijain2305/15/head

Conversation

[ghstack-poisoned]
[ghstack-poisoned]
submartingales pushed a commit to botcanlearn/torchtitan-upstream that referenced this pull request Sep 9, 2026
[ghstack-poisoned]
Comment thread torchtitan/models/kimi_k3/moe.py Outdated
self.linear_beta = config.linear_beta

def forward(
def _activation(

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.

commented in the linear PR

Comment thread torchtitan/models/common/moe.py Outdated
class GroupedExperts(Module):
"""SwiGLU experts with one physical interleaved gate-up parameter.

``w13`` has shape ``(E, F, 2, D)`` and is flattened to ``(E, 2F, D)`` for

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/common/moe.py Outdated
return init


def _fuse_grouped_experts_param_init(param_init: dict | None) -> dict | 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.

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@anijain2305

anijain2305 commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor Author

Talked to @tianyu-l - we will wait for @jinsooihm to make GroupedExpert to only contain one weight.

Update - We will land this first, and then @jinsooihm will refactor after it.

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
Comment thread torchtitan/overrides/fused_swiglu.py Outdated
self.register_load_state_dict_pre_hook(self._merge_w13_on_load)

def forward(
def _activation(

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.

related to my comment on first PR:

If we remove this, it seems the override only needs to happen on ActivationFn, not GroupedExperts which is nice, because we no longer need to separately override MLP and GroupedExperts

Comment thread torchtitan/models/common/moe.py Outdated
)
)

def build(self, **kwargs):

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 this happen only in init? like in https://github.com/pytorch/torchtitan/blob/main/torchtitan/overrides/fused_swiglu.py#L621

Also, since we are making this default, we don't need to keep unfused sharding anyway. This is somewhat related to "we don't need to keep state_dict unfused" but I prefer we should do it in this PR, to avoid introducing code like _fuse_grouped_experts_sharding, although my opinion is not that strong.

Comment thread torchtitan/models/common/moe.py Outdated
# Convert parameters from DTensors to plain Tensors, to work with
# dynamic-shape inputs in EP which cannot be easily expressed as DTensors.
w1_EFD = self.w1_EFD.to_local()
w13_E2FD = self.w13.to_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.

technically this notation is misleading, because each letter represents a single dim

Here's previous "workaround"

# the grouped GEMM consumes them as one (E, 2F, D) expert weight.

[ghstack-poisoned]
[ghstack-poisoned]
Comment thread torchtitan/models/common/activation.py Outdated
gate: torch.Tensor,
up: torch.Tensor,
*,
offsets: torch.Tensor | None = None,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

to alllow offset aware activations - silu_and_mul_op - for MoE.

[ghstack-poisoned]
Comment thread torchtitan/models/common/activation.py Outdated
gate: torch.Tensor,
up: torch.Tensor,
*,
offsets: torch.Tensor | None = 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.

since this is generic, we don't need to have boilerplate here -- maybe make it **kwargs

state_dict[f"{prefix}w3_EFD"] = gate_up[:, :, 1, :].contiguous()


def split_fused_gate_up_state_dict(

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.

def _make_fused_linear_init(gate_init: Callable, up_init: Callable) -> Callable:
"""Build an initializer for an interleaved 2D gate/up linear weight."""
init_logical_weight = _make_fused_gate_up_init(gate_init, up_init, gate_up_axis=1)
def _make_fused_linear_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.

Comment thread torchtitan/models/common/moe.py Outdated
# Convert parameters from DTensors to plain Tensors, to work with
# dynamic-shape inputs in EP which cannot be easily expressed as DTensors.
w1_EFD = self.w1_EFD.to_local()
w13_E_F_2_D = self.w13.to_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.

EF2D is proper? as there are indeed 4 dims

Comment thread torchtitan/models/common/moe.py Outdated
up_RF = self._grouped_mm(A=x_RD.bfloat16(), weight_EOI=w3_EFD, offs=offsets_E)
h_RF = self.activation_fn(gate_RF, up_RF)
E, F, _, D = w13_E_F_2_D.shape
w13_E_2F_D = w13_E_F_2_D.reshape(E, F * 2, D)

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 comparison, E_2F_D is a reasonable workaround

# Routed-expert layout for the shared ``GroupedExperts`` (w13/w2).
_GROUPED_EXPERTS_PARAM_LAYOUT: dict[str, spmd.PerMeshAxisSpmdType] = {
"w1_EFD": spmd.S(1),
"w13": spmd.S(1),

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.

w13_EF2D


_GROUPED_EXPERTS_PARAM_LAYOUT: dict[str, spmd.PerMeshAxisSpmdType] = {
"w1_EFD": spmd.S(1),
"w13": spmd.S(1),

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.

similar

Comment thread torchtitan/models/kimi_k3/sharding.py Outdated
enable_sp=enable_sp,
expert_param_layout={
"w1_EFD": spmd.S(1),
"w13": spmd.S(1),

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.

and other files

@anijain2305

anijain2305 commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor Author

Will need to revisit this after #4535 lands specifically about the (E, F, 2, D) vs (E, 2F, D) layout. If we can make the two consistent, it will be better for the readability.

Update - The PR now has makes the grouped experts have the same layout of (E, 2F, D) for w13 as we have feedforward w13.

[ghstack-poisoned]
[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.

This version looks very nice.

If @sanketpurandare and we agree with the layout, I'll stamp. O/w I need to take another look on the (E, 2, F, D) version. Thanks!

offs=offsets_E,
)
h_RF = self.activation_fn(gate_RF, up_RF)
gate_RF, up_RF = gate_up_R_2F.reshape(-1, F, 2).unbind(-1)

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 you saying this unbind(-1) is pretty cheap?

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 PR bitwise numerics preserving?

[ghstack-poisoned]
@anijain2305

Copy link
Copy Markdown
Contributor Author

@sanketpurandare will take over the Pr

[ghstack-poisoned]
[ghstack-poisoned]
submartingales pushed a commit to botcanlearn/torchtitan-upstream that referenced this pull request Sep 13, 2026
Summary:
Carry forward the reviewed implementation from pytorch/torchtitan#4552 while
storing routed-expert W13 as `[E, 2, F, D]`. The explicit gate/up axis matches
DistMoE's native parameter layout and keeps the feature axis independently
shardable. Standard grouped GEMM consumes a zero-copy `[E, 2F, D]` view and
returns `[R, 2, F]` before the existing activation.

Logical initialization and checkpoint keys remain `w1_EFD`, `w2_EDF`, and
`w3_EFD`. Routing, activation, grouped-GEMM, and dispatcher behavior are
unchanged. This is the Sanket-owned replacement for #4552; Animesh's PR and
stack remain untouched.

Test Plan:
- `CUDA_VISIBLE_DEVICES='' python -m pytest -q tests/unit_tests/cpu/test_moe.py tests/unit_tests/cpu/test_inference_moe.py tests/unit_tests/cpu/test_quantization.py torchtitan/experiments/transformers_modeling_backend/tests/test_moe_parallelism.py tests/unit_tests/gpu/test_fused_swiglu_override.py -k 'not TestFusedSwiGLUGroupedExpertsNumerics and not TestFusedSwiGLUOverrideKernels'` (69 passed, 3 skipped, 6 deselected)
- TorchTitan pre-commit hooks pass except for the existing unrelated Pyrefly error in `torchtitan/hf_datasets/multimodal/utils/video.py`.
- GPU coverage compares the structured and interleaved layouts bitwise for output, input gradients, and weight gradients; execution requires a grouped-MM-capable CUDA build.


ghstack-source-id: 85b0f87
Pull-Request: pytorch/torchtitan#4643
submartingales pushed a commit to botcanlearn/torchtitan-upstream that referenced this pull request Sep 13, 2026
Summary:
Carry forward the reviewed implementation from pytorch/torchtitan#4552 while
storing routed-expert W13 as `[E, 2, F, D]`. The explicit gate/up axis matches
DistMoE's native parameter layout and keeps the feature axis independently
shardable. Standard grouped GEMM consumes a zero-copy `[E, 2F, D]` view and
returns `[R, 2, F]` before the existing activation.

Logical initialization and checkpoint keys remain `w1_EFD`, `w2_EDF`, and
`w3_EFD`. Routing, activation, grouped-GEMM, and dispatcher behavior are
unchanged. The physical fusion intentionally changes seeded random
initialization order, so the affected real-PG integration goldens are refreshed;
checkpoint-loaded weights retain their logical values.

Fused W13 also adds a second native matrix-batch dimension. DistMuon now accepts
native `[..., rows, columns]` parameters, matching the existing Newton-Schulz
implementation, and its expert redistribution test exercises the production
`[E, 2, F, D]` layout without adding another test case.

This is the Sanket-owned replacement for #4552; Animesh's PR and stack remain
untouched.

Test Plan:
- `python -m pytest -q tests/unit_tests/gpu/flex_shard/test_dist_muon.py` (2 passed)
- `python -m pytest -q tests/unit_tests/gpu/test_fsdp_moe_sharding.py` (4 passed)
- `CUDA_VISIBLE_DEVICES='' python -m pytest -q tests/unit_tests/cpu/test_moe.py tests/unit_tests/cpu/test_inference_moe.py tests/unit_tests/cpu/test_quantization.py torchtitan/experiments/transformers_modeling_backend/tests/test_moe_parallelism.py tests/unit_tests/gpu/test_fused_swiglu_override.py -k 'not TestFusedSwiGLUGroupedExpertsNumerics and not TestFusedSwiGLUOverrideKernels'` (69 passed, 3 skipped, 6 deselected)
- TorchTitan formatting, flake8, pydoclint, codespell, and link checks passed; Pyrefly reports one existing unrelated optional-`av` diagnostic in `torchtitan/hf_datasets/multimodal/utils/video.py`.
- The real-PG A10G model suite produced the refreshed 10-step loss and gradient-norm goldens.

ghstack-source-id: 85b0f87
Pull-Request: pytorch/torchtitan#4643
submartingales pushed a commit to botcanlearn/torchtitan-upstream that referenced this pull request Sep 14, 2026
Summary:
Carry forward the reviewed implementation from pytorch/torchtitan#4552 while
storing routed-expert W13 as `[E, 2, F, D]`. The explicit gate/up axis matches
DistMoE's native parameter layout and keeps the feature axis independently
shardable. Standard grouped GEMM consumes a zero-copy `[E, 2F, D]` view and
returns `[R, 2, F]` before the existing activation.

Logical initialization and checkpoint keys remain `w1_EFD`, `w2_EDF`, and
`w3_EFD`. Routing, activation, grouped-GEMM, and dispatcher behavior are
unchanged. The physical fusion intentionally changes seeded random
initialization order, so the affected real-PG integration goldens are refreshed;
checkpoint-loaded weights retain their logical values.

Fused W13 also adds a second native matrix-batch dimension. DistMuon now accepts
native `[..., rows, columns]` parameters, matching the existing Newton-Schulz
implementation, and its expert redistribution test exercises the production
`[E, 2, F, D]` layout without adding another test case.

This is the Sanket-owned replacement for #4552; Animesh's PR and stack remain
untouched.

Test Plan:
- `python -m pytest -q tests/unit_tests/gpu/flex_shard/test_dist_muon.py` (2 passed)
- `python -m pytest -q tests/unit_tests/gpu/test_fsdp_moe_sharding.py` (4 passed)
- `CUDA_VISIBLE_DEVICES='' python -m pytest -q tests/unit_tests/cpu/test_moe.py tests/unit_tests/cpu/test_inference_moe.py tests/unit_tests/cpu/test_quantization.py torchtitan/experiments/transformers_modeling_backend/tests/test_moe_parallelism.py tests/unit_tests/gpu/test_fused_swiglu_override.py -k 'not TestFusedSwiGLUGroupedExpertsNumerics and not TestFusedSwiGLUOverrideKernels'` (69 passed, 3 skipped, 6 deselected)
- TorchTitan formatting, flake8, pydoclint, codespell, and link checks passed; Pyrefly reports one existing unrelated optional-`av` diagnostic in `torchtitan/hf_datasets/multimodal/utils/video.py`.
- The real-PG A10G model suite produced the refreshed 10-step loss and gradient-norm goldens.

ghstack-source-id: ae440ac
Pull Request resolved: pytorch/torchtitan#4643
submartingales pushed a commit to botcanlearn/torchtitan-upstream that referenced this pull request Sep 15, 2026
Summary:
Carry forward the reviewed implementation from pytorch/torchtitan#4552 while
storing routed-expert W13 as `[E, 2, F, D]`. The explicit gate/up axis matches
DistMoE's native parameter layout and keeps the feature axis independently
shardable. Standard grouped GEMM consumes a zero-copy `[E, 2F, D]` view and
returns `[R, 2, F]` before the existing activation.

Logical initialization and checkpoint keys remain `w1_EFD`, `w2_EDF`, and
`w3_EFD`. Routing, activation, grouped-GEMM, and dispatcher behavior are
unchanged. The physical fusion intentionally changes seeded random
initialization order, so the affected real-PG integration goldens are refreshed;
checkpoint-loaded weights retain their logical values.

Fused W13 also adds a second native matrix-batch dimension. DistMuon now accepts
native `[..., rows, columns]` parameters, matching the existing Newton-Schulz
implementation, and its expert redistribution test exercises the production
`[E, 2, F, D]` layout without adding another test case.

This is the Sanket-owned replacement for #4552; Animesh's PR and stack remain
untouched.

Test Plan:
- `python -m pytest -q tests/unit_tests/gpu/flex_shard/test_dist_muon.py` (2 passed)
- `python -m pytest -q tests/unit_tests/gpu/test_fsdp_moe_sharding.py` (4 passed)
- `CUDA_VISIBLE_DEVICES='' python -m pytest -q tests/unit_tests/cpu/test_moe.py tests/unit_tests/cpu/test_inference_moe.py tests/unit_tests/cpu/test_quantization.py torchtitan/experiments/transformers_modeling_backend/tests/test_moe_parallelism.py tests/unit_tests/gpu/test_fused_swiglu_override.py -k 'not TestFusedSwiGLUGroupedExpertsNumerics and not TestFusedSwiGLUOverrideKernels'` (69 passed, 3 skipped, 6 deselected)
- TorchTitan formatting, flake8, pydoclint, codespell, and link checks passed; Pyrefly reports one existing unrelated optional-`av` diagnostic in `torchtitan/hf_datasets/multimodal/utils/video.py`.
- The real-PG A10G model suite produced the refreshed 10-step loss and gradient-norm goldens.

ghstack-source-id: ae440ac
Pull Request resolved: pytorch/torchtitan#4643
sanketpurandare added a commit that referenced this pull request Sep 24, 2026
… projection the default"

Summary:
Carry forward the reviewed implementation from #4552 while
storing routed-expert W13 as `[E, 2, F, D]`. The explicit gate/up axis matches
DistMoE's native parameter layout and keeps the feature axis independently
shardable. Standard grouped GEMM consumes a zero-copy `[E, 2F, D]` view and
returns `[R, 2, F]` before the existing activation.

Logical initialization and external HF keys remain `w1_EFD`, `w2_EDF`, and
`w3_EFD`. Native model, DCP, optimizer, and EMA state use the physical
`w13_E2FD` key, keeping `named_parameters()` and state-dict FQNs identical.
Adapters split or merge W13 only at the HF boundary; the model installs no
state-dict hooks, so save and load share the same native contract. Routing and
activation semantics are unchanged.

The physical fusion intentionally resets deterministic from-seed numerics. The
old parameter order consumed random values as W1, W2, W3; the fused parameter
initializes its slices as W1, W3 before W2. It also replaces two BF16 grouped
GEMMs with one wider W13 grouped GEMM, whose rounding need not match two
independent launches. Fixed-weight forward/backward tests validate the mapping,
and the affected DeepSeek V3 and Qwen3 A10G goldens are regenerated from
full-precision TensorBoard metrics for fake-PG and real-PG configurations.

Fused W13 also adds a second native matrix-batch dimension. DistMuon now accepts
native `[..., rows, columns]` parameters, matching the existing Newton-Schulz
implementation, and its expert redistribution test exercises the production
`[E, 2, F, D]` layout without adding another test case.

Kimi K3's DistMuon configuration now assigns the physical `w13_E2FD` and
`w2_EDF` expert parameters directly, so the fused W13 weight cannot fall
through to the fallback AdamW group.

This is the Sanket-owned replacement for #4552; Animesh's PR and stack remain
untouched.

Test Plan:
- `python -m pytest tests/unit_tests/cpu -q --deselect tests/unit_tests/cpu/test_lora.py::test_lora_forward` (1244 passed, 23 skipped, 1 deselected)
- `python -m pytest -q tests/unit_tests/cpu/test_convert_ema_to_hf.py tests/unit_tests/cpu/test_state_dict_adapter.py tests/unit_tests/cpu/test_moe.py` (41 passed)
- Transformer-backend native-W13 round-trip and focused MoE/quantization tests (60 passed, 23 skipped)
- `python -m pytest -q tests/unit_tests/gpu/flex_shard/test_dist_muon.py` (7 passed)
- `python -m pytest -q tests/unit_tests/gpu/test_fsdp_moe_sharding.py tests/unit_tests/gpu/test_fused_swiglu_override.py` (20 passed)
- Native state-key, EMA-export, and HF adapter round-trip tests pass without model state-dict hooks.
- The Kimi K3 optimizer-pattern test verifies that native W13/W2 expert parameters are owned by DistMuon and stale logical W1/W3 names are absent.
- A10G fake-PG and real-PG numerics were exported from the exact CI configurations; repeated DeepSeek V3 and Qwen3 runs produced identical full-precision trajectories.
- Scoped formatting, flake8, pydoclint, codespell, link, and targeted Pyrefly checks passed. Project-wide Pyrefly retains one unrelated nullable-video-duration baseline error.

[ghstack-poisoned]
sanketpurandare added a commit that referenced this pull request Sep 24, 2026
…default"

Summary:
Carry forward the reviewed implementation from #4552 while
storing routed-expert W13 as `[E, 2, F, D]`. The explicit gate/up axis matches
DistMoE's native parameter layout and keeps the feature axis independently
shardable. Standard grouped GEMM consumes a zero-copy `[E, 2F, D]` view and
returns `[R, 2, F]` before the existing activation.

Logical initialization and external HF keys remain `w1_EFD`, `w2_EDF`, and
`w3_EFD`. Native model, DCP, optimizer, and EMA state use the physical
`w13_E2FD` key, keeping `named_parameters()` and state-dict FQNs identical.
Adapters split or merge W13 only at the HF boundary; the model installs no
state-dict hooks, so save and load share the same native contract. Routing and
activation semantics are unchanged.

The physical fusion intentionally resets deterministic from-seed numerics. The
old parameter order consumed random values as W1, W2, W3; the fused parameter
initializes its slices as W1, W3 before W2. It also replaces two BF16 grouped
GEMMs with one wider W13 grouped GEMM, whose rounding need not match two
independent launches. Fixed-weight forward/backward tests validate the mapping,
and the affected DeepSeek V3 and Qwen3 A10G goldens are regenerated from
full-precision TensorBoard metrics for fake-PG and real-PG configurations.

Fused W13 also adds a second native matrix-batch dimension. DistMuon now accepts
native `[..., rows, columns]` parameters, matching the existing Newton-Schulz
implementation, and its expert redistribution test exercises the production
`[E, 2, F, D]` layout without adding another test case.

Kimi K3's DistMuon configuration now assigns the physical `w13_E2FD` and
`w2_EDF` expert parameters directly, so the fused W13 weight cannot fall
through to the fallback AdamW group.

This is the Sanket-owned replacement for #4552; Animesh's PR and stack remain
untouched.

Test Plan:
- `python -m pytest tests/unit_tests/cpu -q --deselect tests/unit_tests/cpu/test_lora.py::test_lora_forward` (1244 passed, 23 skipped, 1 deselected)
- `python -m pytest -q tests/unit_tests/cpu/test_convert_ema_to_hf.py tests/unit_tests/cpu/test_state_dict_adapter.py tests/unit_tests/cpu/test_moe.py` (41 passed)
- Transformer-backend native-W13 round-trip and focused MoE/quantization tests (60 passed, 23 skipped)
- `python -m pytest -q tests/unit_tests/gpu/flex_shard/test_dist_muon.py` (7 passed)
- `python -m pytest -q tests/unit_tests/gpu/test_fsdp_moe_sharding.py tests/unit_tests/gpu/test_fused_swiglu_override.py` (20 passed)
- Native state-key, EMA-export, and HF adapter round-trip tests pass without model state-dict hooks.
- The Kimi K3 optimizer-pattern test verifies that native W13/W2 expert parameters are owned by DistMuon and stale logical W1/W3 names are absent.
- A10G fake-PG and real-PG numerics were exported from the exact CI configurations; repeated DeepSeek V3 and Qwen3 runs produced identical full-precision trajectories.
- Scoped formatting, flake8, pydoclint, codespell, link, and targeted Pyrefly checks passed. Project-wide Pyrefly retains one unrelated nullable-video-duration baseline error.

[ghstack-poisoned]
sanketpurandare added a commit that referenced this pull request Sep 24, 2026
…default"

Summary:
Carry forward the reviewed implementation from #4552 while
storing routed-expert W13 as `[E, 2, F, D]`. The explicit gate/up axis matches
DistMoE's native parameter layout and keeps the feature axis independently
shardable. Standard grouped GEMM consumes a zero-copy `[E, 2F, D]` view and
returns `[R, 2, F]` before the existing activation.

Logical initialization and external HF keys remain `w1_EFD`, `w2_EDF`, and
`w3_EFD`. Native model, DCP, optimizer, and EMA state use the physical
`w13_E2FD` key, keeping `named_parameters()` and state-dict FQNs identical.
Adapters split or merge W13 only at the HF boundary; the model installs no
state-dict hooks, so save and load share the same native contract. Routing and
activation semantics are unchanged.

The physical fusion intentionally resets deterministic from-seed numerics. The
old parameter order consumed random values as W1, W2, W3; the fused parameter
initializes its slices as W1, W3 before W2. It also replaces two BF16 grouped
GEMMs with one wider W13 grouped GEMM, whose rounding need not match two
independent launches. Fixed-weight forward/backward tests validate the mapping,
and the affected DeepSeek V3 and Qwen3 A10G goldens are regenerated from
full-precision TensorBoard metrics for fake-PG and real-PG configurations.

Fused W13 also adds a second native matrix-batch dimension. DistMuon now accepts
native `[..., rows, columns]` parameters, matching the existing Newton-Schulz
implementation, and its expert redistribution test exercises the production
`[E, 2, F, D]` layout without adding another test case.

Kimi K3's DistMuon configuration now assigns the physical `w13_E2FD` and
`w2_EDF` expert parameters directly, so the fused W13 weight cannot fall
through to the fallback AdamW group.

This is the Sanket-owned replacement for #4552; Animesh's PR and stack remain
untouched.

Test Plan:
- `python -m pytest tests/unit_tests/cpu -q --deselect tests/unit_tests/cpu/test_lora.py::test_lora_forward` (1244 passed, 23 skipped, 1 deselected)
- `python -m pytest -q tests/unit_tests/cpu/test_convert_ema_to_hf.py tests/unit_tests/cpu/test_state_dict_adapter.py tests/unit_tests/cpu/test_moe.py` (41 passed)
- Transformer-backend native-W13 round-trip and focused MoE/quantization tests (60 passed, 23 skipped)
- `python -m pytest -q tests/unit_tests/gpu/flex_shard/test_dist_muon.py` (7 passed)
- `python -m pytest -q tests/unit_tests/gpu/test_fsdp_moe_sharding.py tests/unit_tests/gpu/test_fused_swiglu_override.py` (20 passed)
- Native state-key, EMA-export, and HF adapter round-trip tests pass without model state-dict hooks.
- The Kimi K3 optimizer-pattern test verifies that native W13/W2 expert parameters are owned by DistMuon and stale logical W1/W3 names are absent.
- A10G fake-PG and real-PG numerics were exported from the exact CI configurations; repeated DeepSeek V3 and Qwen3 runs produced identical full-precision trajectories.
- Scoped formatting, flake8, pydoclint, codespell, link, and targeted Pyrefly checks passed. Project-wide Pyrefly retains one unrelated nullable-video-duration baseline error.



Review history:
This replaces #4643, which retains the original review discussion and approvals.




[ghstack-poisoned]
submartingales pushed a commit to botcanlearn/torchtitan-upstream that referenced this pull request Sep 24, 2026
Summary:
Carry forward the reviewed implementation from pytorch/torchtitan#4552 while
storing routed-expert W13 as `[E, 2, F, D]`. The explicit gate/up axis matches
DistMoE's native parameter layout and keeps the feature axis independently
shardable. Standard grouped GEMM consumes a zero-copy `[E, 2F, D]` view and
returns `[R, 2, F]` before the existing activation.

Logical initialization and external HF keys remain `w1_EFD`, `w2_EDF`, and
`w3_EFD`. Native model, DCP, optimizer, and EMA state use the physical
`w13_E2FD` key, keeping `named_parameters()` and state-dict FQNs identical.
Adapters split or merge W13 only at the HF boundary; the model installs no
state-dict hooks, so save and load share the same native contract. Routing and
activation semantics are unchanged.

The physical fusion intentionally resets deterministic from-seed numerics. The
old parameter order consumed random values as W1, W2, W3; the fused parameter
initializes its slices as W1, W3 before W2. It also replaces two BF16 grouped
GEMMs with one wider W13 grouped GEMM, whose rounding need not match two
independent launches. Fixed-weight forward/backward tests validate the mapping,
and the affected DeepSeek V3 and Qwen3 A10G goldens are regenerated from
full-precision TensorBoard metrics for fake-PG and real-PG configurations.

Fused W13 also adds a second native matrix-batch dimension. DistMuon now accepts
native `[..., rows, columns]` parameters, matching the existing Newton-Schulz
implementation, and its expert redistribution test exercises the production
`[E, 2, F, D]` layout without adding another test case.

Kimi K3's DistMuon configuration now assigns the physical `w13_E2FD` and
`w2_EDF` expert parameters directly, so the fused W13 weight cannot fall
through to the fallback AdamW group.

This is the Sanket-owned replacement for #4552; Animesh's PR and stack remain
untouched.

Test Plan:
- `python -m pytest tests/unit_tests/cpu -q --deselect tests/unit_tests/cpu/test_lora.py::test_lora_forward` (1244 passed, 23 skipped, 1 deselected)
- `python -m pytest -q tests/unit_tests/cpu/test_convert_ema_to_hf.py tests/unit_tests/cpu/test_state_dict_adapter.py tests/unit_tests/cpu/test_moe.py` (41 passed)
- Transformer-backend native-W13 round-trip and focused MoE/quantization tests (60 passed, 23 skipped)
- `python -m pytest -q tests/unit_tests/gpu/flex_shard/test_dist_muon.py` (7 passed)
- `python -m pytest -q tests/unit_tests/gpu/test_fsdp_moe_sharding.py tests/unit_tests/gpu/test_fused_swiglu_override.py` (20 passed)
- Native state-key, EMA-export, and HF adapter round-trip tests pass without model state-dict hooks.
- The Kimi K3 optimizer-pattern test verifies that native W13/W2 expert parameters are owned by DistMuon and stale logical W1/W3 names are absent.
- A10G fake-PG and real-PG numerics were exported from the exact CI configurations; repeated DeepSeek V3 and Qwen3 runs produced identical full-precision trajectories.
- Scoped formatting, flake8, pydoclint, codespell, link, and targeted Pyrefly checks passed. Project-wide Pyrefly retains one unrelated nullable-video-duration baseline error.

ghstack-source-id: 916a644
Pull Request resolved: pytorch/torchtitan#4643
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants