Design Document: MoE Router Replay Feature
1. Overview
This document provides a detailed description of the “Router Replay” feature implemented within the Megatron-LM Core for Mixture-of-Experts (MoE) models.
This feature is designed to enhance determinism and analyzability in MoE model training and inference. It enables the model to load routing decisions from a predefined file and enforce their use during the forward pass, thereby bypassing the real-time routing computation.
2. Motivation
- Determinism & Reproducibility: In distributed training, MoE routing decisions can exhibit minor variations due to factors like floating-point precision. By replaying a fixed routing table, the MoE computation path is guaranteed to be identical across runs, which facilitates debugging and reproducing experimental results.
- Performance Profiling: The router’s own computation (e.g., logits calculation, top-k selection) incurs overhead. In replay mode, this part of the computation can be completely skipped, allowing for more precise isolation and profiling of performance bottlenecks within the Expert Layers themselves.
- Debugging Aid: When issues arise in the model, fixing the routing decisions helps to isolate variables, making it easier to determine whether the problem lies with the routing mechanism or the expert computations.
3. Design and Architecture
The design follows the principles of being non-intrusive and on-demand, with the core idea of activating the replay logic only when explicitly requested by the user.
-
Core Components:
RouterReplay(located inmegatron/core/transformer/moe/router_replay.py): A utility class for replaying MoE routing decisions. When enabled via themoe_enable_routing_replayflag, a separate instance ofRouterReplayis created for each MoE layer’s router. Each instance is responsible for loading routing data and providing the deterministic routing decisions for its corresponding layer during the forward pass.moe_enable_routing_replay(located inmegatron/core/transformer/transformer_config.py): A boolean global configuration flag that serves as the sole entry point for enabling this feature.
-
Workflow: The feature supports different modes, such as recording and replaying, controlled by a
RouterReplayAction.- Enabling the Feature: The user sets
moe_enable_routing_replaytoTruein the model configuration. - Initialization: When
moe_enable_routing_replayis true, eachTopKRoutercreates its ownRouterReplayinstance. - Mode Configuration: The user must programmatically set the desired router replay action (e.g.,
record,forward_replay,backward_replay) on theRouterReplayinstances. - Execution Flow (within a mini-batch):
- Forward Pass:
- For each micro-batch, the
topk_routing_with_score_functionchecks therouter_replay_action. - In
recordmode: The dynamically computedtop-kexpert indices are captured and stored. - In
forward_replaymode: The function retrieves pre-loaded expert indices fromtarget_topk_idx. These indices are used for the forward computation and are also appended to thereplay_backward_listto prepare for the backward pass.
- For each micro-batch, the
- Backward Pass:
- For each micro-batch (processed in reverse order in pipeline parallelism), the
router_replay_actionis checked again. - In
backward_replaymode: The function retrieves the expert indices for the corresponding micro-batch by popping them from thereplay_backward_list. This mode is intended for training recomputation (e.g., activation checkpointing and pipeline recompute) so the same routing decisions are used during recompute/backward as in forward, ensuring determinism and correctness.
- For each micro-batch (processed in reverse order in pipeline parallelism), the
- Forward Pass:
- Enabling the Feature: The user sets
4. Implementation Details
The implementation cleanly separates the replay logic from the router’s core computation.
-
megatron/core/transformer/transformer_config.py:- Adds the configuration option
moe_enable_routing_replay: bool = False.
- Adds the configuration option
-
megatron/core/transformer/moe/moe_utils.py:- Introduces the
RouterReplayclass to manage the state for recording and replaying routing decisions for a single MoE layer.target_topk_idx: An attribute holding the expert indices for the current micro-batch during forward replay mode.recorded_topk_idx: An attribute for storing the computed expert indices when in record mode.replay_backward_list: A list that accumulates thetop-kindices used during the forward passes of a mini-batch. This list is consumed in FIFO order during the backward pass to ensure correctness under pipeline parallelism.set_target_indices(): A method to load the replay indices intotarget_topk_idxfor the forward pass.record_indices(): A method to save the computed indices.
- The
topk_routing_with_score_functionis modified to contain the core logic. It checks therouter_replay_actionon therouter_replayinstance and accordingly performs one of the following actions: computes and records indices, replays indices fromtarget_topk_idx(for forward), replays indices fromreplay_backward_list(for backward), or falls through to the default dynamic routing.
- Introduces the
Training recompute usage
- During forward replay,
set_target_indices()preparesreplay_backward_listso each micro-batch’s indices are available for recomputation. - During recompute/backward, set action to
REPLAY_BACKWARDso indices are consumed in FIFO order to mirror the forward sequence.
5. Usage Guide
- Enable & Instantiate
- Create one
RouterReplayinstance per MoE router layer when building the model. - Optionally use the global helpers to set/clear actions across all layers.
- Create one
- Record Routing Decisions
- Set action:
RouterReplay.set_global_router_replay_action(RouterReplayAction.RECORD). - Run the model; retrieve per-layer indices via
RouterReplay.get_recorded_data()and persist.
- Set action:
- Forward Replay
- Load indices and distribute:
RouterReplay.set_replay_data(list_of_tensors). - Set action:
RouterReplay.set_global_router_replay_action(RouterReplayAction.REPLAY_FORWARD). - Run the model; dynamic top‑k is bypassed and target indices are used.
- Load indices and distribute:
- Backward Replay
- For training recomputation (activation checkpointing or pipeline recompute), set action:
REPLAY_BACKWARDduring recomputation. - Per micro‑batch indices are consumed from
replay_backward_listin FIFO order.
- For training recomputation (activation checkpointing or pipeline recompute), set action:
- Cleanup
- Use
RouterReplay.clear_global_indices(),RouterReplay.clear_global_router_replay_action(), andRouterReplay.clear_global_router_replay_instances()to restore default behavior and prevent memory leaks.
- Use
Quick usage with topk_routing_with_score_function
6. Minimal Demo
Here is a minimal code example showing how to use RouterReplay for recording and replaying: