Repository navigation
Port Llama 4's MoE to the shared experts interface - #49432
IlyasMoutawwakil wants to merge 1 commit into
Conversation
`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>
|
[For maintainers] Suggested jobs to run (before merge) run-slow: llama4 |
|
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. |
CI recapDashboard: View test results in Grafana |
| 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) |
There was a problem hiding this comment.
was basically doing batched_mm always
SunMarc
left a comment
There was a problem hiding this comment.
Thanks a lot for updating this model ! Really happy to see it cleaned ! Just a nit
| 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 |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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
| "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", |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
this is super weird but ig we keep it? llama4 is super weird
There was a problem hiding this comment.
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
There was a problem hiding this comment.
i would definitely prefer that
There was a problem hiding this comment.
Yea let's do that then. Theres no urgency here for now and we can fix it up afterwards then
There was a problem hiding this comment.
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)
Llama4TextExpertsran every expert densely on every token and had no@use_experts_implementation, sogrouped_mm/batched_mmand 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
Llama4TextMoescales 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.Before submitting
Pull Request checks?
to it if that's the case.
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.