Skip to content

Port Llama 4's MoE to the shared experts interface - #49432

Closed
IlyasMoutawwakil wants to merge 1 commit into
mainfrom
llama4-experts-interface
Closed

IlyasMoutawwakil wants to merge 1 commit into
mainfrom
llama4-experts-interface

Conversation

@IlyasMoutawwakil

@IlyasMoutawwakil IlyasMoutawwakil commented Oct 8, 2026 •

Copy link
Copy Markdown
Member

CPU CI GPU run-slow

Llama4TextExperts ran every expert densely on every token and had no @use_experts_implementation, so grouped_mm/batched_mm and expert parallelism could not apply. It now takes (hidden_states, top_k_index, top_k_weights) like every other experts class and each token runs only its routed expert.

The router score scales the experts' input, not their output, so Llama4TextMoe scales the input and passes each (token, slot) pair as a top-1 route with unit weight. The router returns
(logits, scores, indices); the logits recorder follows.

The EP plan is the standard experts plan (grouped_gemm + ep_dispatch_experts): main's plan matched no EP mode and was never applied. The shared-expert add is out of place, since the TP rowwise output is a view autograd forbids modifying in place.

The fbgemm and sequential (compressed-tensors / bnb) Llama 4 experts take the same routed signature.

What does this PR do?

Fixes # (issue)

Code Agent Policy

The Transformers repo is currently being overwhelmed by a large number of PRs and issue comments written by
code agents. These often are low-quality, or fix extremely minor issues that occur rarely or never in practice.
As a result, we're instituting a rule that first-time contributors should not use code agents to submit PRs or issues.
We'd also ask autonomous "OpenClaw"-like agents not to open any PRs or issues.

Issues/PRs from first-time contributors that violate this rule will probably just be closed without review, and we
might block you, especially if you open more than one or appear to be deliberately ignoring this. We especially do not
want new contributors to jump in on random issues to contribute an agent-written fix. This creates lots of noise
for reviewers and other users and will almost certainly get you blocked.

For more information, please read CONTRIBUTING.md.

  • (First-time contributors only): I confirm that this PR description and code is not written by an LLM or code agent

Before submitting

  • This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
  • Did you read the contributor guideline and the
    Pull Request checks?
  • Was this discussed/approved via a Github issue or the forum? Please add a link
    to it if that's the case.
  • Did you make sure to update the documentation with your changes according to the guidelines?
  • Did you write any new necessary tests?

Who can review?

Anyone in the community is free to review the PR once the tests have passed. Feel free to tag
members/contributors who may be interested in your PR.

`Llama4TextExperts` ran every expert densely on every token and had no
`@use_experts_implementation`, so `grouped_mm`/`batched_mm` and expert
parallelism could not apply. It now takes `(hidden_states, top_k_index,
top_k_weights)` like every other experts class and each token runs only
its routed expert.

The router score scales the experts' input, not their output, so
`Llama4TextMoe` scales the input and passes each (token, slot) pair as a
top-1 route with unit weight. The router returns
`(logits, scores, indices)`; the logits recorder follows.

The EP plan is the standard experts plan (`grouped_gemm` +
`ep_dispatch_experts`): main's plan matched no EP mode and was never
applied. The shared-expert add is out of place, since the TP rowwise
output is a view autograd forbids modifying in place.

The fbgemm and sequential (compressed-tensors / bnb) Llama 4 experts take
the same routed signature.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@github-actions

github-actions Bot commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

[For maintainers] Suggested jobs to run (before merge)

run-slow: llama4

@HuggingFaceDocBuilderDev

Copy link
Copy Markdown

The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

@github-actions

github-actions Bot commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

CI recap

Dashboard: View test results in Grafana
Latest run: 37787920759:1
Result: success | Jobs: 16 | Tests: 136,560 | Failures: 0 | Duration: 8h 41m

@IlyasMoutawwakil
IlyasMoutawwakil marked this pull request as ready for review October 12, 2026 09:00
@zucchini-nlp
zucchini-nlp removed their request for review October 12, 2026 09:43
@SunMarc
SunMarc requested a review from ArthurZucker October 12, 2026 15:14
Comment on lines -78 to -82
hidden_states = hidden_states.view(self.gate_up_proj.shape[0], -1, self.hidden_size)
gate_up = torch.bmm(hidden_states, self.gate_up_proj)
gate, up = gate_up.chunk(2, dim=-1) # not supported for DTensors
next_states = torch.bmm((up * self.act_fn(gate)), self.down_proj)
next_states = next_states.view(-1, self.hidden_size)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

was basically doing batched_mm always

@SunMarc SunMarc left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks a lot for updating this model ! Really happy to see it cleaned ! Just a nit

Comment on lines 154 to +158
def forward(self, hidden_states):
router_logits = super().forward(hidden_states)
router_top_value, router_indices = torch.topk(router_logits, self.top_k, dim=1)
router_scores = torch.full_like(router_logits, float("-inf")).scatter_(1, router_indices, router_top_value)
router_scores = torch.nn.functional.sigmoid(router_scores.float()).to(router_scores.dtype)
return router_scores, router_logits
router_scores = torch.nn.functional.sigmoid(router_top_value.float()).to(router_top_value.dtype)
return router_logits, router_scores, router_indices

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

even though we are don't use modular here, let's try to keep the syntax as close as possible as other impl in the lib maybe ? This is what we have for Qwen3MoeTopKRouter

    def forward(self, hidden_states):
        hidden_states = hidden_states.reshape(-1, self.hidden_dim)
        router_logits = F.linear(hidden_states, self.weight)  # (seq_len, num_experts)
        router_probs = torch.nn.functional.softmax(router_logits, dtype=torch.float, dim=-1)
        router_top_value, router_indices = torch.topk(router_probs, self.top_k, dim=-1)  # (seq_len, top_k)
        if self.norm_topk_prob:
            router_top_value /= router_top_value.sum(dim=-1, keepdim=True)
        router_top_value = router_top_value.to(router_logits.dtype)
        router_scores = router_top_value
        return router_logits, router_scores, router_indices

@vasqu vasqu left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Some initial thoughts because there are a lot of workarounds maybe best to wait for finegrained to land? And accept llama4 to be special until then

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🚨 it's breaking

Comment on lines -128 to -137
"layers.*.self_attn.q_proj": "colwise",
"layers.*.self_attn.k_proj": "colwise",
"layers.*.self_attn.v_proj": "colwise",
"layers.*.self_attn.o_proj": "rowwise",
"layers.*.feed_forward.experts.gate_up_proj": "grouped_gemm", # row because not linear
"layers.*.feed_forward.experts.down_proj": "grouped_gemm", # col because not linear
"layers.*.feed_forward.gate_proj": "colwise",
"layers.*.feed_forward.up_proj": "colwise",
"layers.*.feed_forward.down_proj": "rowwise",
"layers.*.feed_forward.router": "ep_router",

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

this shouldnt have been a thing in the first place 💀

current_hidden_states = current_hidden_states * top_k_weights[token_idx, top_k_pos, None]
final_hidden_states.index_add_(0, token_idx, current_hidden_states.to(final_hidden_states.dtype))

return final_hidden_states

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

this is super weird but ig we keep it? llama4 is super weird

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Wondering whether we should not just go hard at this and deprecate all these weird stuff for llama4 and integrate it properly into fp8 / finegrained

I dont think we are in a rush here and id rather have a proper llama4

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

i would definitely prefer that

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Yea let's do that then. Theres no urgency here for now and we can fix it up afterwards then

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

yeh just checked the quant recipe and it would need to be added to fg-fp8/fg-kernels for it work (per-channel/per-token)

@IlyasMoutawwakil

Copy link
Copy Markdown
Member Author

closing, superseded by the EP strategies stack (#49429 → #49615): #49615 drops Llama 4's unused ep_router rule and leaves Llama 4 as it is on main.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants