vllm.distributed.eplb.eplb_state
¶
Expert parallelism load balancer (EPLB) metrics and states.
Glossary¶
- Logical Expert: An expert that is part of the model's logical structure. It holds a set of weights and is replicated across multiple physical experts.
- Redundant Expert: To achieve load balancing, for some popular logical experts, we create additional copies of the expert weights. During inference, each of these copies can be routed to by the same set of tokens.
- Physical Expert: An expert that is instantiated on a specific device. It is a replica of a logical expert and can be rearranged across devices. I.e., one logical expert may have multiple sets of weights initialized on different devices, and each of these sets is a physical expert.
- Local Physical Expert: A physical expert that is instantiated on the current device.
For example: DeepSeek-R1 has 256 logical experts, so each MoE layer has 256 sets of linear layer weights in the model parameters. If we add 32 redundant experts, DeepSeek-R1 will have 256 + 32 = 288 physical experts in total. And when deploying, we'll have 288 sets of linear layer weights for each MoE layer. If we have 32 EP ranks, then each GPU will hold 288 / 32 = 9 local physical experts.
Classes:
-
EplbLayerState–Runtime EPLB data stored in the MoE layer.
-
EplbModelState–EPLB metrics.
-
EplbState–EplbState of each expert parallel model. Key is the model config hash.
Functions:
-
compute_logical_maps–Derive logical_to_physical_map and logical_replica_count from
EplbLayerState
dataclass
¶
Runtime EPLB data stored in the MoE layer.
Attributes:
-
num_unpadded_tokens_tensors(list[Tensor] | None) –Reference to the parent
EplbModelState's tensor list so the -
should_record_tensor(Tensor | None) –Shared scalar bool tensor controlling whether to accumulate expert load
num_unpadded_tokens_tensors = None
class-attribute
instance-attribute
¶
Reference to the parent EplbModelState's tensor list so the
router can read the correct per-[u]batch unpadded token count.
should_record_tensor = None
class-attribute
instance-attribute
¶
Shared scalar bool tensor controlling whether to accumulate expert load
metrics during this forward pass. All layers reference the same
tensor object, which is owned and updated by EplbState.
Set to False for the first step_interval - window_size steps of
each rearrangement period: those steps would be overwritten in the
sliding window before the next rearrangement, so recording them wastes
GPU work.
EplbModelState
dataclass
¶
EPLB metrics.
Attributes:
-
communicator(EplbCommunicator) –The communicator for expert weight transfers.
-
device_index(int | None) –Device index for the async EPLB worker thread.
-
eplb_stats(EplbStats | None) –EPLB stats for the model.
-
expert_buffer(list[Tensor]) –The buffer to store the expert weights during transfer.
-
expert_load_pass(Tensor) –Expert load during this forward pass.
-
expert_load_pass_buffer(Tensor) –Maximum-capacity buffer backing
expert_load_pass. -
expert_load_window(Tensor) –A sliding window of expert load.
-
last_expert_load(Tensor) –Global logical-expert totals from the last reshuffle; equal demand initially.
-
logical_replica_count(Tensor) –Number of replicas for each logical expert.
-
logical_to_physical_map(Tensor) –Mapping from logical experts to physical experts.
-
num_committed_layers(int) –Number of layers committed by move_to_workspace in the current async EPLB
-
num_unpadded_tokens_tensors(list[Tensor] | None) –Per-ubatch scalar int32 tensors holding the number of real (non-padding)
-
pending_result(AsyncEplbLayerResult | None) –Set by the async worker after all writes to expert_buffer are done. Consumed
-
physical_to_logical_map(Tensor) –Mapping from physical experts to logical experts.
-
physical_to_logical_map_buffer(Tensor) –Maximum-capacity buffer backing
physical_to_logical_map. -
rebalanced(bool) –This flag is only used when running Async EPLB. It is set to True by the main thread
-
worker_progress(int) –Async worker progress in the current rearrangement, written by the worker:
communicator
instance-attribute
¶
The communicator for expert weight transfers.
device_index
instance-attribute
¶
Device index for the async EPLB worker thread.
eplb_stats
instance-attribute
¶
EPLB stats for the model.
expert_buffer
instance-attribute
¶
The buffer to store the expert weights during transfer.
expert_load_pass
instance-attribute
¶
Expert load during this forward pass. We use the token count each expert processes as the load.
Shape: (num_moe_layers, num_physical_experts)
expert_load_pass_buffer
instance-attribute
¶
Maximum-capacity buffer backing expert_load_pass.
expert_load_window
instance-attribute
¶
A sliding window of expert load.
Shape: (window_size, num_moe_layers, num_physical_experts)
NOTE: The expert_load_view now records load for all physical experts rather than just local experts. This ensures consistent load statistics across different dispatch methods (naive all-to-all, DeepEP). The recorded load will be multiplied by dp_size when using naive all-to-all due to each DP rank contributing the same token set to the calculation. See: https://github.com/vllm-project/vllm/pull/22167#pullrequestreview-3086143856
last_expert_load
instance-attribute
¶
Global logical-expert totals from the last reshuffle; equal demand initially.
logical_replica_count
instance-attribute
¶
Number of replicas for each logical expert.
This is exactly the non--1 count in the logical_to_physical_map.
Shape: (num_moe_layers, num_logical_experts)
Example¶
For a 2-layer MoE model with 6 physical experts and 4 logical experts on 3 EP ranks, the count could look like this:
``` [[2, 2, 1, 1], [3, 1, 1, 1]]
logical_to_physical_map
instance-attribute
¶
Mapping from logical experts to physical experts.
This is a sparse matrix, where -1 indicates no mapping.
Shape: (num_moe_layers, num_logical_experts, num_redundant_experts + 1)
Example¶
For a 2-layer MoE model with 6 physical experts and 4 logical experts on 3 EP ranks, the mapping could look like this:
num_committed_layers = 0
class-attribute
instance-attribute
¶
Number of layers committed by move_to_workspace in the current async EPLB rearrangement.
num_unpadded_tokens_tensors = None
class-attribute
instance-attribute
¶
Per-ubatch scalar int32 tensors holding the number of real (non-padding)
tokens. Allocated once in EplbState.add_model so that device
pointers remain stable across CUDA-graph replays. The router kernel
indexes this list with dbo_current_ubatch_id().
pending_result = None
class-attribute
instance-attribute
¶
Set by the async worker after all writes to expert_buffer are done. Consumed and reset to None by the main thread in move_to_workspace() after the contents of expert_buffer have been transferred out. At most one result is pending at a time.
pending_result relies on the GIL to synchronize access between the main thread and the async worker.
physical_to_logical_map
instance-attribute
¶
Mapping from physical experts to logical experts.
Shape: (num_moe_layers, num_physical_experts)
Example¶
For a 2-layer MoE model with 6 physical experts and 4 logical experts on 3 EP ranks, the mapping could look like this:
physical_to_logical_map_buffer
instance-attribute
¶
Maximum-capacity buffer backing physical_to_logical_map.
rebalanced
instance-attribute
¶
This flag is only used when running Async EPLB. It is set to True by the main thread after the new expert maps have been computed. This indicates that the async worker should start transferring weights. move_to_workspace sets this flag to False when all weights have been transferred and the new map has been successfully committed.
rebalanced relies on the GIL to synchronize access between the main thread and the async worker.
worker_progress = -1
class-attribute
instance-attribute
¶
Async worker progress in the current rearrangement, written by the worker: 2 * layer while transferring the layer, plus 1 once it is published. -1 until the worker starts the first layer.
_commit_eplb_maps(new_physical_to_logical_map)
¶
Copies all of the new_* maps into self. After this function completes, the new mappings will become the current mappings and will be visible to the model.
_commit_eplb_maps_for_layer(new_physical_to_logical_map, layer)
¶
Per-layer version of commit_eplb_maps used by the sync portion of async EPLB. Copies all of the new* maps into this model state. After this function completes, the new mappings will become the current mappings and will be visible to the model.
EplbState
¶
EplbState of each expert parallel model. Key is the model config hash.
Methods:
-
add_model–Build the initial EPLB state.
-
build_initial_global_physical_to_logical_map–Build an initial expert arrangement using the following structure:
-
create_model_communicator–Create the communicator used by a model's EPLB transfers.
-
create_policy–Create the policy shared by every model in this EPLB state.
-
drain_async–Drain in-flight async EPLB by consuming all remaining layer results.
-
prepare_forward–Fill the per-[u]batch
num_unpadded_tokenstensors before a -
rearrange–Rearrange the experts according to the current load.
-
reconfigure_physical_expert_slots–Replace physical_to_logical_map and expert_load_pass with views
-
step–Step the EPLB state.
-
stop_async_loop–Cancel and stop the async worker before releasing model resources.
Attributes:
-
async_worker(Thread | None) –Background thread handling async transfers.
-
async_worker_error(Exception | None) –Exception that stopped the async worker thread, if any.
-
device_index(int | None) –Device index for the async EPLB worker thread.
-
expert_load_window_size(int) –Size of the expert load sliding window.
-
expert_load_window_step(int) –Current step in the sliding window.
-
expert_rearrangement_step(int) –Steps after last rearrangement.
-
expert_rearrangement_step_interval(int) –Interval for expert rearrangement steps.
-
ft_reset_epoch(int) –Incremented by FT recovery (reset_eplb_async_state). The async worker
-
is_async(bool) –The flag indicates whether the EPLB is running in async mode.
-
policy(AbstractEplbPolicy) –Selected EPLB algorithm
-
rearrange_event(CpuGpuEvent) –Event to signal when a new rearrangement is needed for the async thread.
-
should_record_tensor(Tensor | None) –Shared scalar bool tensor for all layers. Every
_pending_balancedness = deque()
instance-attribute
¶
Balancedness stats whose copies to the host are in flight, oldest first.
_should_record_value = None
instance-attribute
¶
Last value written to should_record_tensor.
async_worker = None
instance-attribute
¶
Background thread handling async transfers.
async_worker_error = None
instance-attribute
¶
Exception that stopped the async worker thread, if any.
device_index = None
instance-attribute
¶
Device index for the async EPLB worker thread.
expert_load_window_size = 0
instance-attribute
¶
Size of the expert load sliding window. This is a constant and is taken from the config.
expert_load_window_step = 0
instance-attribute
¶
Current step in the sliding window.
Different from expert_rearrangement_step,
each EP rank may have its own expert_load_window_step.
expert_rearrangement_step = 0
instance-attribute
¶
Steps after last rearrangement. Will trigger a rearrangement if it exceeds the threshold. In async mode, it is reset again when the last layer is committed.
NOTE: Keep in mind that all EP ranks need to have the same
expert_rearrangement_step value to ensure synchronization.
Otherwise, the rearrangement will hang at collective
communication calls.
expert_rearrangement_step_interval = 0
instance-attribute
¶
Interval for expert rearrangement steps. This is a constant and is taken from the config.
ft_reset_epoch = 0
instance-attribute
¶
Incremented by FT recovery (reset_eplb_async_state). The async worker snapshots it when a transfer cycle starts; a change in the value means a recovery happened, so the cycle is abandoned.
is_async = False
instance-attribute
¶
The flag indicates whether the EPLB is running in async mode.
policy = self.create_policy()
instance-attribute
¶
Selected EPLB algorithm
rearrange_event = CpuGpuEvent()
instance-attribute
¶
Event to signal when a new rearrangement is needed for the async thread.
should_record_tensor = None
instance-attribute
¶
Shared scalar bool tensor for all layers. Every
EplbLayerState holds a reference to the same object so
a single .fill_() updates all layers at once. Allocated on the
first call to _propagate_shared_tensors.
_allreduce_list(tensor_list)
¶
All-reduce a list of tensors.
_propagate_shared_tensors(model, num_unpadded_tokens_tensors)
¶
Propagate shared tensors to every EplbLayerState.
Allocates should_record_tensor on the first call and then
assigns both it and num_unpadded_tokens_tensors to every
MoE layer's EplbLayerState. All layers reference the
same objects so a single update is visible everywhere.
Must be called after model.set_eplb_state so that each
layer's eplb_state is already populated.
_should_record_current_step(log_stats=False)
¶
Return whether expert-load recording should be enabled this step.
Recording is enabled when we are close to either: 1) The next rearrangement step, so the sliding window is ready. 2) The next balancedness logging step, when log_stats is enabled.
_sync_load_pass()
¶
Sync the expert load pass across all ranks for log stats. Doesn't update the expert load pass in eplb_model_state.
_update_layer_should_record(log_stats=False)
¶
Update the shared should_record_tensor for all layers.
_warn_async_rearrangement_in_progress()
¶
Warn with the EP ranks whose async worker is furthest behind.
Must run on every EP rank, since it all-reduces over the EP CPU group.
add_model(model, model_config, model_name=None)
¶
Build the initial EPLB state.
build_initial_global_physical_to_logical_map(num_routed_experts, num_redundant_experts)
staticmethod
¶
create_model_communicator(model, expert_buffer, group_coordinator)
¶
Create the communicator used by a model's EPLB transfers.
create_policy()
¶
Create the policy shared by every model in this EPLB state.
Async planning runs a serialized copy in a persistent CPU subprocess. Synchronous planning and profiling use this instance on the main thread.
drain_async()
¶
Drain in-flight async EPLB by consuming all remaining layer results.
Each pending result is acknowledged (consumed_event recorded) so the async worker can proceed, but the transferred weights are intentionally NOT applied — a full rearrange is expected to follow.
Ranks are kept in lockstep via _all_ranks_result_ready (all_reduce on the EP CPU group). The async worker's coordinated-stop collectives use the separate EPLB group, so the two sets of collectives do not interfere.
No-op when no async cycle is in progress (rebalanced=False).
prepare_forward(model_config, num_unpadded_tokens, ubatch_slices=None)
¶
Fill the per-[u]batch num_unpadded_tokens tensors before a
forward pass.
Parameters:
-
(model_config¶ModelConfig) –Identifies which
EplbModelStateto update. -
(num_unpadded_tokens¶int) –Total number of real (non-padding) tokens in the batch.
-
(ubatch_slices¶list | None, default:None) –When DBO is active, a list of
UBatchSliceobjects describing each micro-batch's token range. WhenNone, onlytensors[0]is filled.
rearrange(is_profile=False, rank_mapping=None, use_last_expert_load=False)
¶
Rearrange the experts according to the current load.
Parameters:
-
(is_profile¶bool, default:False) –If
True, perform a dummy rearrangement. This is used inprofile_runto reserve enough memory, no memory movement will be performed. Default is False. -
(rank_mapping¶dict[int, int] | None, default:None) –The rank mapping when scaling is done in EEP.
-
(use_last_expert_load¶bool, default:False) –Use the last reshuffle's logical-expert totals.
reconfigure_physical_expert_slots(model_config, num_physical_experts)
¶
Replace physical_to_logical_map and expert_load_pass with views covering the new active size.
step(is_dummy=False, is_profile=False, log_stats=False)
¶
Step the EPLB state.
Parameters:
-
(is_dummy¶bool, default:False) –If
True, this is a dummy step and the load metrics recorded in this forward pass will not count. Defaults toFalse. -
(is_profile¶bool, default:False) –If
True, perform a dummy rearrangement with maximum communication cost. This is used inprofile_runto reserve enough memory for the communication buffer. -
(log_stats¶bool, default:False) –If
True, log the expert load metrics.
Stats¶
The metrics are all summed up across layers.
- `avg_tokens`: The average load across ranks.
- `max_tokens`: The maximum load across ranks.
- `balancedness`: The ratio of average load to maximum load.
stop_async_loop(timeout=5)
¶
Cancel and stop the async worker before releasing model resources.
_rank_load_imbalance(logical_loads, physical_to_logical_map, ep_size)
¶
Per-layer rank load imbalance of a placement: the sum over layers of the busiest rank's load divided by the sum over layers of the mean rank load.
Each MoE layer waits for its busiest rank, so the sum of per-layer maxima tracks MoE time. Summing the load over layers before taking the max would let hot spots on different ranks in different layers cancel out.
Parameters: