Skip to content

Conversation

@dsikka
Copy link
Collaborator

@dsikka dsikka commented Dec 6, 2025

SUMMARY:
"please provide a brief summary"

TEST PLAN:
"please outline how the changes were tested"

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @dsikka, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request addresses a bug in the Llama4 calibration process by refactoring the model's forward pass. The changes aim to improve the accuracy and consistency of expert routing and output accumulation, while also enhancing compatibility with recent versions of the transformers library.

Highlights

  • Llama4 Calibration Logic Refactor: The core logic for calculating router scores and accumulating expert outputs within the Llama4 model's forward method has been significantly revised to address calibration issues.
  • Transformers Library Compatibility: The change introduces explicit handling for router_logits potentially being a tuple, ensuring compatibility with transformers versions 4.53 and greater.
  • Simplified Expert Output Accumulation: The previous conditional logic for calibrate_all_experts and top_token_mask has been replaced with a more direct method of applying router scores and summing expert contributions.
  • Debugging Statement Added: A print statement for self.calibrate_all_experts has been added to the __init__ method, likely for debugging purposes during development.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request refactors the forward pass of SequentialLlama4TextMoe to fix an issue with MoE calibration. The new implementation correctly handles different transformers library versions and uses a dense pass for calibration. However, it introduces a couple of issues. A debug print statement has been left in the code. More importantly, the calibrate_all_experts flag is now ignored, causing the module to always perform a dense pass and breaking the sparse routing functionality expected when the flag is False. My review includes suggestions to address these points.

Comment on lines 50 to 70
def forward(self, hidden_states: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
hidden_states = hidden_states.reshape(-1, self.hidden_dim)
router_scores, router_logits = self.router(hidden_states) # transformers>=4.54
router_logits = self.router(hidden_states)
# support transformers 4.53 and greater
if isinstance(router_logits, tuple):
router_logits = router_logits[-1]

out = self.shared_expert(hidden_states)

for expert_index in range(self.num_experts):
# find expert scores
expert_score = router_scores[:, expert_index].unsqueeze(-1)
top_token_mask = expert_score[:, 0] > 0

# llama4 applies scores before expert relu
expert_in = hidden_states * expert_score
router_top_value, router_indices = torch.topk(router_logits, self.top_k, dim=1)

# calibrate experts
if self.calibrate_all_experts:
expert_out = self.experts[expert_index](expert_in)[top_token_mask]
else:
expert_out = self.experts[expert_index](expert_in[top_token_mask])
router_scores = (
torch.full_like(router_logits, float("-inf"))
.scatter_(1, router_indices, router_top_value)
.transpose(0, 1)
)
router_scores = torch.sigmoid(router_scores.float()).to(hidden_states.dtype)

# accumulate output
out[top_token_mask] += expert_out
out = self.shared_expert(hidden_states)
for i in range(self.num_experts):
out += self.experts[i](hidden_states) * router_scores[i].reshape(-1, 1)

return out, router_logits
Copy link
Contributor

Choose a reason for hiding this comment

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

high

The refactored forward method now implements a dense pass where all tokens are processed by all experts, which is a valid approach for calibration. However, the self.calibrate_all_experts flag is no longer used. This is a regression, as the module will now behave incorrectly when calibrate_all_experts is False by not performing the expected sparse routing.

Please reintroduce the conditional logic based on self.calibrate_all_experts. The new dense implementation should be within the if self.calibrate_all_experts: block. An else block should be added to implement the sparse expert routing, which is the expected behavior when not calibrating all experts. You can look at other MoE implementations in the codebase for reference on implementing an efficient sparse forward pass.

self.router = original.router
self.shared_expert = original.shared_expert
self.calibrate_all_experts = calibrate_all_experts
print(self.calibrate_all_experts, "CALIBRATE ALL EXPERTS")
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

This print statement appears to be for debugging and should be removed before merging.

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.

2 participants