Skip to content

[MoE replication 2/4] Add online hot-expert replica planner - #6300

Open
Shuwen-Fang wants to merge 1 commit into
AI-Hypercomputer:mainfrom
Shuwen-Fang:moe-replica-planner
Open

Shuwen-Fang wants to merge 1 commit into
AI-Hypercomputer:mainfrom
Shuwen-Fang:moe-replica-planner

Conversation

@Shuwen-Fang

@Shuwen-Fang Shuwen-Fang commented Nov 12, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Adds the pure-JAX online hot-expert replication planner (src/maxtext/layers/moe_replica_planner.py, 176 lines) for the ragged all-to-all MoE path (part 2 of the hot-expert replication stack; no callers wired yet):

  • ReplicaPlan: @flax.struct.dataclass PyTree holding route_table ([EP, E]), rep_home ([EP, R]), rep_slot ([EP, R]), send_slots ([EP, C]), and send_peer_index ([EP, EP]) as array children and num_slots / num_replicas as static fields (pytree_node=False), documenting the three sender/receiver invariants relied on by moe_replica_weights.extend_with_replicas (at most one replica per (home, receiver) pair, distinct valid home IDs across each receiver's R slots, and valid sends compacted at send_slots[h, :k] in ascending receiver order).
  • compute_plan_iter: loop-free vectorized planner executing 2 * R unrolled rounds of hottest-to-coldest device matching (at most one replica per logical expert per step). Redirects whole source shards (same-board sources first, never the home device's own shard) so no intra-shard token split or extra sort is needed, with a conservative starvation heuristic skipping experts whose positive non-home shards all exceed half the global max-to-min load gap.
  • identity_route_table & _finalize_plan: constructs the physical slot routing table and sender/receiver metadata using order-independent .max reductions so empty replica slots (-1) never clobber expert 0.

Tests

  • JAX_PLATFORMS=cpu pytest -v tests/unit/moe_replica_planner_test.py (14 passed):
    • ReplicaPlannerTest::test_disabled_plan_is_identity
    • ReplicaPlannerTest::test_expert_zero_not_clobbered_by_empty_slots
    • ReplicaPlannerTest::test_identity_route_table
    • ReplicaPlannerTest::test_invalid_arguments_raise
    • ReplicaPlannerTest::test_more_replica_slots_than_experts_supported
    • ReplicaPlannerTest::test_plan_is_valid
    • ReplicaPlannerTest::test_plan_reduces_max_load_vs_greedy_oracle0 .. test_plan_reduces_max_load_vs_greedy_oracle3
    • ReplicaPlannerTest::test_plan_satisfies_weight_move_invariants
    • ReplicaPlannerTest::test_replica_plan_pytree_jit_and_cond
    • ReplicaPlannerTest::test_same_board_sources_preferred
    • ReplicaPlannerTest::test_unmovable_hottest_expert_does_not_starve_second_hottest

Checklist

Before submitting this PR, please make sure (put X in square brackets):

  • I have performed a self-review of my code.
  • I have commented my code, particularly in hard-to-understand areas.
  • I have run end-to-end tests locally and provided test artifacts above, if applicable.
  • I have made or will make corresponding changes to the doc if needed.

@github-actions github-actions Bot added the skip-ci-tests Add this label to the PR to skip running CI tests label Nov 12, 2026
Shuwen-Fang added a commit to Shuwen-Fang/maxtext that referenced this pull request Nov 13, 2026
@Shuwen-Fang Shuwen-Fang changed the title [MoE replication 3/5] Add replica planners for online hot-expert replication [MoE replication 2/4] Add replica planners for online hot-expert replication Nov 13, 2026
@codecov

codecov Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 15.62500% with 81 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/maxtext/layers/moe_replica_planner.py 15.62% 81 Missing ⚠️

📢 Thoughts on this report? Let us know!

@Shuwen-Fang

Copy link
Copy Markdown
Collaborator Author

@gemini-cli /review

@github-actions

Copy link
Copy Markdown
Contributor

🤖 Hi @Shuwen-Fang, I've received your request, and I'm working on it now! You can track my progress in the logs for more details.

@Shuwen-Fang

Copy link
Copy Markdown
Collaborator Author

@gemini-cli /review

@github-actions

Copy link
Copy Markdown
Contributor

🤖 Hi @Shuwen-Fang, I've received your request, and I'm working on it now! You can track my progress in the logs for more details.

@gemini-code-assist

Copy link
Copy Markdown

Summary of Changes

Hello, 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 implements the second phase of the hot-expert replication stack for MoE models. It provides a JAX-based planner that dynamically computes expert replication plans to alleviate load imbalances in expert-parallel setups. The solution focuses on performance by using vectorized operations to match hot experts with available replica slots on lighter devices, while respecting board-level constraints and communication invariants.

Highlights

  • Replica Planner Implementation: Introduced a pure-JAX online hot-expert replication planner that executes vectorized, loop-free rounds of hottest-to-coldest device matching to balance expert load.
  • ReplicaPlan Container: Added a new data structure to hold routing tables and metadata, ensuring strict invariants for replica placement and sender/receiver communication.
  • Comprehensive Testing: Added a suite of unit tests covering edge cases, load balancing efficiency against a greedy oracle, and invariant validation for the replication plan.
New Features

🧠 You can now enable Memory (public preview) to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

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 the 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 counterproductive. 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.

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

@github-actions

Copy link
Copy Markdown
Contributor

🤖 Hi @Shuwen-Fang, I'm running an automatic MaxText review of this pull request. You can track my progress in the logs. To request another review later, add the gemini-review label or comment @gemini-cli /review.

@Shuwen-Fang

Copy link
Copy Markdown
Collaborator Author

@gemini-cli /review

@github-actions

Copy link
Copy Markdown
Contributor

🤖 Hi @Shuwen-Fang, I've received your request, and I'm working on it now! You can track my progress in the logs for more details.

@github-actions github-actions Bot 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.

📋 Review Summary

Verdict: Spec partially met; the planner gets stuck on unsplittable experts.

Top issues:

  1. 🔴 [Bug] Unsplittable experts cause an infinite loop in the planner. sent[h, loc] is only updated if ok is True, so if an expert's source shards are too large to move, the sender gets stuck retrying the same expert in all subsequent rounds. → Update sent unconditionally so the planner moves on to the next hottest expert.
  2. 🟠 [Alignment] ReplicaPlan is defined as a plain Python class. While this works for local variables, passing it through jax.lax.cond or jax.lax.scan will crash with a TypeError. → Convert ReplicaPlan to a registered PyTree (e.g. @flax.struct.dataclass).
Inferred spec & validation
  • Sources: PR description, code after.
  • Problem: The ragged all-to-all MoE path lacks a planner for online hot-expert replication.
Spec item Implementation Validating test
R1 (stated): at most one replica per (home, receiver) pair ✅ met test_plan_satisfies_weight_move_invariants ✅
R2 (stated): distinct valid home IDs across each receiver's R slots ✅ met test_plan_satisfies_weight_move_invariants ✅
R3 (stated): valid sends compacted in ascending receiver order ✅ met test_plan_satisfies_weight_move_invariants ✅
R4 (stated): loop-free vectorized planner matching hottest to coldest ⚠️ partial (gets stuck on unsplittable experts) test_plan_reduces_max_load_vs_greedy_oracle ⚠️ superficial (skewed distribution doesn't trigger the unsplittable expert bug)
R5 (stated): Redirects whole source shards, preferring same-board sources ✅ met test_same_board_sources_preferred ✅
C1 (inferred): enabled=False returns identity plan ✅ preserved test_disabled_plan_is_identity ✅
C2 (inferred): Empty slots do not clobber expert 0 ✅ preserved test_expert_zero_not_clobbered_by_empty_slots ✅

import jax.numpy as jnp


class ReplicaPlan:

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.

🟠 [Alignment] ReplicaPlan is explicitly documented as 'not a pytree'. In JAX/Flax codebases like MaxText, data structures holding jax.Arrays that are passed between layer components should be registered PyTrees. While a plain class works as a local variable, if this plan is eventually passed through jax.lax.cond (e.g., to conditionally enable replication) or jax.lax.scan, JAX will crash with a TypeError: Cannot return a non-PyTree. Convert it to a @flax.struct.dataclass (or typing.NamedTuple) to avoid this.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 822ea14: converted ReplicaPlan to @flax.struct.dataclass with num_slots and num_replicas marked pytree_node=False and array fields as PyTree children, covered by test_replica_plan_pytree_jit_and_cond.

rep_mask = rep_mask.at[r, slot].set(jnp.where(ok[:, None], take, rep_mask[r, slot]))
free = free.at[r].add(-ok.astype(jnp.int32))
send_cnt = send_cnt.at[h].add(ok.astype(jnp.int32))
pair_used = pair_used.at[h, r].set(pair_used[h, r] | ok)

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.

🔴 [Bug] If a hot expert's source shards are fundamentally unsplittable (i.e. the first source shard > half the load gap to the receiver), take evaluates to False and moved == 0. ok becomes False, so sent[h, loc] remains False. The sender will repeatedly select this exact same unsplittable expert in every subsequent round, failing each time, and completely starving its other experts of replication opportunities.

Suggested change
pair_used = pair_used.at[h, r].set(pair_used[h, r] | ok)
sent = sent.at[h, loc].set(True)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 822ea14 with a conservative starvation heuristic: instead of unconditionally setting sent[h, loc] = True (which would prematurely skip an expert that merely paired with a warm partner or full receiver on round j before shift=True rotates it to a colder receiver on round j+1), unmovable marks sent[h, loc] when all positive non-home shards exceed half the current global max-to-min load gap (or there are zero non-home tokens), covered by test_unmovable_hottest_expert_does_not_starve_second_hottest.

@Shuwen-Fang

Copy link
Copy Markdown
Collaborator Author

@gemini-cli /review

@github-actions

Copy link
Copy Markdown
Contributor

🤖 Hi @Shuwen-Fang, I've received your request, and I'm working on it now! You can track my progress in the logs for more details.

@github-actions github-actions Bot 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.

📋 Review Summary

Verdict: No significant issues found.

Inferred spec & validation
  • Sources: PR description; code before/after.
  • Problem: Online hot-expert replication planner is needed for the ragged all-to-all MoE path to balance load across devices without intra-shard token splitting.
Spec item Implementation Validating test
R1 (stated): Loop-free vectorized planner executing 2 * R unrolled rounds of hottest-to-coldest device matching. ✅ ReplicaPlannerTest::test_plan_reduces_max_load_vs_greedy_oracle0 ✅
R2 (stated): Redirects whole source shards, preferring same-board sources first, never the home device's own shard. ✅ ReplicaPlannerTest::test_same_board_sources_preferred ✅
R3 (stated): Starvation heuristic skips experts whose non-home shards exceed half the global max-to-min load gap. ✅ ReplicaPlannerTest::test_unmovable_hottest_expert_does_not_starve_second_hottest ✅
C1 (stated): At most one replica per (home, receiver) device pair. ✅ preserved ReplicaPlannerTest::test_plan_satisfies_weight_move_invariants ✅
C2 (stated): Valid sends are compacted at send_slots[h, :k] in ascending receiver order. ✅ preserved ReplicaPlannerTest::test_plan_satisfies_weight_move_invariants ✅
C3 (stated): Empty replica slots (-1) never clobber expert 0 in the route table. ✅ preserved ReplicaPlannerTest::test_expert_zero_not_clobbered_by_empty_slots ✅

@Shuwen-Fang Shuwen-Fang changed the title [MoE replication 2/4] Add replica planners for online hot-expert replication [MoE replication 2/4] Add online hot-expert replica planner Nov 13, 2026
"""Online hot-expert replication planner for the ragged all-to-all MoE path.
Each expert-parallel (EP) device owns L = E / EP "home" experts and R extra
replica slots, so the physical slot space has EP * (L + R) slots. Each step,

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.

Are all R extra replica slots always filled?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

No. R is an upper bound on replica slots per device, not a fill count. A slot is filled only when the planner finds a useful offload (positive token gain, free slot on the receiver, sender under expert_replica_max_send). Unfilled slots keep rep_home = -1, get no tokens in route_table, and receive no weights in extend_with_replicas. test_disabled_plan_is_identity and test_expert_zero_not_clobbered_by_empty_slots cover this.

This branch has not been deployed

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants