vllm.model_executor.layers.fused_moe
¶
Modules:
-
activation–MoE activation function enum and utilities.
-
all2all_utils– -
b12x–b12x modular tensor-parallel fused MoE backend.
-
config– -
deep_gemm_mega_moe–DeepGEMM MegaMoE experts: fused EP dispatch, expert GEMMs and combine.
-
deep_gemm_utils–Taken from https://github.com/ModelTC/LightLLM/blob/8ed97c74c18f11505b048b1ba00ba5c0cef8bff6/lightllm/common/fused_moe/deepep_scatter_gather.py
-
eplb_triton–EPLB replica mapping and expert-load recording shared by Triton kernels.
-
expert_map_manager–Expert Map Manager for MoE layers.
-
expert_substitution–Constant expert substitution for MoNE-pruned checkpoints.
-
experts– -
flashinfer_moe_ep– -
fused_flydsl_moe–Fused MoE Triton kernels.
-
fused_globalize_align_block_size– -
fused_moe–Fused MoE Triton kernels.
-
fused_moe_method_base– -
hpc_moe– -
layer– -
modular_kernel– -
moe_align_block_size– -
moe_fused_mul_sum– -
moe_output–Output contract between a MoE layer and a consumer that fuses its tail.
-
moe_permute_unpermute– -
oracle– -
prepare_finalize– -
prepare_megamoe–Triton input-staging kernels for DeepGEMM MegaMoE.
-
routed_experts– -
routed_experts_capturer– -
router– -
runner– -
silu_mul_token_quant–SiLU-and-mul fused with dynamic per-token FP8 quantization.
-
topk_weight_and_reduce– -
unquantized_fused_moe_method– -
utils–
Classes:
-
AiterFp8BlockExperts–128x128 block-quantized weight scale, 128-grouped dynamic
-
AiterFp8ChannelExperts–Per-output-channel static weight scale, per-token dynamic
-
AiterFp8TensorExperts–Per-tensor static weight scale, either per-tensor static or
-
AiterMxfp4Experts–MXFP4-quantized weights, with either unquantized (bf16/fp16) or
-
AiterUnquantizedExperts–Unquantized (bf16/fp16) weights and activations.
-
ApplyMoEActivationConfig–Configuration forwarded to
apply_moe_activation. -
BatchedDeepGemmExperts– -
BatchedTritonExperts–A Triton based MoE expert class that operates on expert batched format,
-
CutlassBatchedExpertsFp8–Batched CUTLASS FP8 fused MoE expert implementation.
-
CutlassExpertsFp8–CUTLASS FP8 fused MoE expert implementation.
-
DeepGemmExperts–DeepGemm-based fused MoE expert implementation.
-
FusedMoEActivationFormat–The standard activation format (num_tokens, hidden dim).
-
FusedMoEConfig– -
FusedMoEExpertsModular–An abstract base class for the [Permute-Experts-Unpermute] step described
-
FusedMoEMethodBase– -
FusedMoEParallelConfig– -
FusedMoEPrepareAndFinalizeModular–An abstract base class for the [Quantize-Prepare] and [Finalize] steps
-
FusedMoEQuantConfig–The FusedMoEQuantConfig contains all the quantization parameters for
-
FusedMoERouter–FusedMoERouter is an abstract class that provides a 'select_experts'
-
GateLinear–MoE gate linear layer with multi-tier GEMM dispatch:
-
GroupedTopk–GroupedTopk used by the Deepseek-V2 and Deepseek-V3 model.
-
MoEActivation–Activation functions for MoE layers.
-
MoERunner–Standard MoE runner implementation for executing Mixture of Experts layers.
-
RoutedExperts–Container for routed expert weights and execution logic.
-
RoutedScaleMode–Where routed_scaling_factor is applied in a MoE layer.
-
SharedExperts– -
TritonExperts–Triton-based fused MoE expert implementation.
-
TritonOrDeepGemmExperts–DeepGemm with fallback to Triton for low latency shapes.
-
UnquantizedFusedMoEMethod–MoE method without quantization.
-
XPUExperts–
Functions:
-
FusedMoEFactory–Factory function for creating MoE execution pipeline.
-
activation_without_mul–Get the non-gated variant of an activation function.
-
apply_moe_activation–Apply MoE activation function.
-
fused_experts–Run fused MoE expert computation using Triton kernels.
-
fused_moe_make_expert_params_mapping–Delegate to EPLB manager.
AiterFp8BlockExperts
¶
AiterFp8ChannelExperts
¶
AiterFp8TensorExperts
¶
Bases: AiterExperts
Per-tensor static weight scale, either per-tensor static or per-tensor dynamic activation scale.
AiterMxfp4Experts
¶
Bases: AiterExperts
MXFP4-quantized weights, with either unquantized (bf16/fp16) or MXFP4-quantized dynamic activations. gfx950-only (not gfx1250).
AiterUnquantizedExperts
¶
ApplyMoEActivationConfig
dataclass
¶
Configuration forwarded to apply_moe_activation.
Methods:
-
from_configs–Build from the model and quantization configurations.
from_configs(moe_config, quant_config)
classmethod
¶
Build from the model and quantization configurations.
BatchedDeepGemmExperts
¶
Bases: FusedMoEExpertsModular
Methods:
-
__init__–max_num_tokens: Maximum number of tokens from a DP Rank
-
supports_packed_ue8m0_act_scales–DeepGemm supports packed ue8m0 activation scales on Blackwell-family
__init__(moe_config, quant_config, max_num_tokens, num_dispatchers)
¶
max_num_tokens: Maximum number of tokens from a DP Rank num_dispatchers: The number of DP dispatchers. quant_config: Quantization configuration
supports_packed_ue8m0_act_scales()
¶
DeepGemm supports packed ue8m0 activation scales on Blackwell-family GPUs (SM100 datacenter and SM120 consumer).
BatchedTritonExperts
¶
Bases: FusedMoEExpertsModular
A Triton based MoE expert class that operates on expert batched format, i.e. E x max_num_tokens x K. This is the format that the batched dispatch/combine kernels use.
CutlassBatchedExpertsFp8
¶
Bases: CutlassExpertsFp8Base
Batched CUTLASS FP8 fused MoE expert implementation.
CutlassExpertsFp8
¶
Bases: CutlassExpertsFp8Base
CUTLASS FP8 fused MoE expert implementation.
DeepGemmExperts
¶
FusedMoEActivationFormat
¶
Bases: Enum
The standard activation format (num_tokens, hidden dim).
Methods:
-
is_superset–Whether this (experts) format is a superset of
pf_format, i.e.
Attributes:
-
BatchedExperts–Like 'Standard' (num_tokens, hidden dim), but the row count is an upper
-
Standard–The batched experts format (num experts, max tokens per expert, hidden dim)
-
is_batched(bool) –Whether this is the disjoint
BatchedExpertsformat.
BatchedExperts = ('batched_experts',)
class-attribute
instance-attribute
¶
Like 'Standard' (num_tokens, hidden dim), but the row count is an upper bound rather than the exact token count, so some rows are inactive padding.
Produced by all2all backends (DeepEP v2) that cannot report the received token count on the host without a device sync. Padding comes from the worst-case recv allocation (decode/cudagraph mode, where the tail rows are left uninitialized) and from per-expert block alignment (prefill mode, where the gaps are zeroed).
Inactive rows are marked by setting all of their topk_ids slots to -1;
when available, ExpertTokensMetadata.psum_recv_per_rank carries the
real/padding boundary on device. Consuming kernels must therefore either
skip such rows or produce results for them that are safe to discard --
padding rows may hold uninitialized garbage, so an expert that derives
routing by scanning every row will corrupt real tokens if it ignores the
-1 markers. Only experts declaring this format are paired with such a
prepare/finalize step; see is_superset.
Standard = ('standard',)
class-attribute
instance-attribute
¶
The batched experts format (num experts, max tokens per expert, hidden dim)
is_batched
property
¶
Whether this is the disjoint BatchedExperts format.
is_superset(pf_format)
¶
Whether this (experts) format is a superset of pf_format, i.e.
an experts kernel declaring self can consume activations produced
by a prepare/finalize step in pf_format.
The relation is directional: self is the experts format and
pf_format is the prepare/finalize format. PaddedStandard is a
superset of Standard (a padding-aware kernel treats unpadded input
as the zero-padding case), but not vice versa. All other formats are
only supersets of themselves.
FusedMoEConfig
dataclass
¶
Methods:
-
defer_moe_finalize–Ask the experts to leave the top-k reduction to the layer's consumer.
-
limit_deferred_moe_finalize–Finalize calls above
max_num_tokenseven when deferring. -
should_defer_moe_finalize–Return whether this invocation may defer the top-k reduction.
Attributes:
-
activation_format(FusedMoEActivationFormat) –The all2all activation format.
-
use_deferred_moe_finalize(bool) –Whether experts may return an unfinalized output on this deployment.
-
w13_num_shards(int) –Number of shards fused into w13: gate and up for gated, up only.
activation_format
property
¶
The all2all activation format.
use_deferred_moe_finalize
property
¶
Whether experts may return an unfinalized output on this deployment.
Evaluated on read rather than in __post_init__ because deferral is
requested after construction, like skip_final_all_reduce.
w13_num_shards
property
¶
Number of shards fused into w13: gate and up for gated, up only.
defer_moe_finalize(max_num_tokens=-1)
¶
Ask the experts to leave the top-k reduction to the layer's consumer.
A layer whose consumer can fuse the top-k reduction (e.g. into its TP
all-reduce) calls this once while the model is built, and only when its
experts are TRTLLM-Gen ones that can stop after GEMM2 (the
do_finalize=False path). Other experts ignore the request and
always finalize, which should_defer_moe_finalize can't see, so the
layer checks the quant method's experts_cls first, as Kimi-K3 does.
From then on:
- The experts return an
UnfinalizedMoEOutputinstead of finalized states for every callshould_defer_moe_finalizeaccepts. should_defer_moe_finalize(num_tokens)is the answer for a call: it requires a TP-only deployment without hidden-dim padding (use_deferred_moe_finalize), a non-empty call and at mostdefer_moe_finalize_max_num_tokenstokens. The cap starts atmax_num_tokensand only ever goes down: experts that would split a larger call across kernel launches lower it to their single-launch size when they are built, since each launch permutes into its own buffer.- The model asks
should_defer_moe_finalizebefore each call and takes the matching path. A deferred call runs the runner's_forward_impldirectly, since the MoE custom op returns tensors only, and the consumer then owns the top-k reduction, the shared-expert add and the all-reduce.
Parameters:
limit_deferred_moe_finalize(max_num_tokens)
¶
Finalize calls above max_num_tokens even when deferring.
Negative means no limit, and leaves the current one in place.
should_defer_moe_finalize(num_tokens)
¶
Return whether this invocation may defer the top-k reduction.
FusedMoEExpertsModular
¶
Bases: FusedMoEExperts
An abstract base class for the [Permute-Experts-Unpermute] step described above.
Methods:
-
adjust_N_for_activation–Calculate the output dimension for the activation function.
-
apply–This function computes the intermediate result of a Mixture of Experts
-
moe_problem_size–Extract the MoE problem size from the given tensor arguments:
-
output_hidden_dim–Hidden size of the finalized output. Experts that drop the hidden
-
workspace_dtype–Workspace type: The dtype to use for the workspace tensors.
-
workspace_shapes–Compute the shapes for the temporary and final outputs of the two gemms
adjust_N_for_activation(N, activation)
staticmethod
¶
Calculate the output dimension for the activation function.
For *_no_mul activations (e.g. relu2_no_mul), there's no gate/up split, so output size equals input size (N).
For regular gated activations (e.g., silu, gelu, swigluoai), output size is N // 2 due to gate × activation(up) multiplication.
Parameters:
-
(N¶int) –The intermediate size (width of w1/w3 weights).
-
(activation¶MoEActivation) –The activation function enum.
Returns:
-
int–The output dimension after activation.
apply(output, hidden_states, w1, w2, topk_weights, topk_ids, activation, global_num_experts, expert_map, a1q_scale, a2_scale, workspace13, workspace2, expert_tokens_meta, apply_router_weight_on_input)
abstractmethod
¶
This function computes the intermediate result of a Mixture of Experts (MoE) layer using two sets of weights, w1 and w2.
Writes into output and returns None, unless the implementation stopped
after GEMM2 and left the top-k reduction to a fused consumer, in which
case output is untouched and the unfinalized result is returned.
Parameters:
-
(output¶Tensor) –(torch.Tensor): The unweighted, unreduced output tensor.
-
(hidden_states¶Tensor) –(torch.Tensor): The (quantized) input tensor to the MoE layer.
-
(w1¶Tensor) –The first set of expert weights.
-
(w2¶Tensor) –The second set of expert weights.
-
(topk_weights¶Tensor) –A map of row to expert weights. Some implementations choose to do weight application.
-
(topk_ids¶Tensor) –A map of row to expert id.
-
(activation¶str) –The activation function to apply after the first MoE layer.
-
(global_num_experts¶int) –The total number of experts in the global expert space.
-
(expert_map¶Optional[Tensor]) –A tensor mapping expert indices from the global expert space to the local expert space of the expert parallel shard.
-
(a1q_scale¶Optional[Tensor]) –Optional quantized scale to be used for a1. Result of quantization from prepare/finalize and not from the FusedMoEQuantConfig.
-
(a2_scale¶Optional[Tensor]) –Optional quantized scale to be used for the second gemm's activations.
-
(workspace13¶Tensor) –A scratch tensor used for gemm outputs must be large enough to hold output of either MoE gemm.
-
(workspace2¶Tensor) –A scratch tensor used for the activation function.
-
(expert_tokens_meta¶Optional[ExpertTokensMetadata]) –An optional ExpertTokensMetadata object containing gpu/cpu tensors as big as the number of local experts with the information about the number of tokens assigned to each local expert.
-
(apply_router_weight_on_input¶bool) –True if router weights are already applied on the input. This is relevant if the implementation chooses to do weight application.
moe_problem_size(a1, w1, w2, topk_ids)
¶
Extract the MoE problem size from the given tensor arguments: - a: The hidden states, input to the MoE layer. - w1: The first set of expert weights. - w2: The second set of expert weights. - topk_ids: The topk ids.
Note: extracting the problem shape from the weight and activation tensors is not obvious. It needs to be done this way specifically due to subtle issues with particular kernels, e.g. the int4 kernels divide the trailing dimension by two, so it's not "correct" to extract N or K from the trailing dimension of w1 or w2. Similarly, some kernels transpose the weights, so this needs to be kept in mind.
Note: This implementation covers most cases. However, if experts require a specialized implementation, like MarlinExperts, they are free to override this function.
output_hidden_dim(hidden_dim)
¶
Hidden size of the finalized output. Experts that drop the hidden padding return the unpadded size.
workspace_dtype(act_dtype)
¶
Workspace type: The dtype to use for the workspace tensors.
workspace_shapes(M, N, K, topk, global_num_experts, local_num_experts, expert_tokens_meta, activation)
abstractmethod
¶
Compute the shapes for the temporary and final outputs of the two gemms and activation in the fused expert function. Since the gemms are independent, the workspace for the first gemm can be shared with the workspace for the last gemm.
Inputs: - M: number of tokens. - N: Row (or column) dimension of expert weights. - K: hidden dimension - topk: The number of top-k experts to select. - global_num_experts: global number of experts. - local_num_experts: local number of experts due to DP/EP. - expert_tokens_meta: number of tokens per expert metadata for batched format.
Returns a tuple of: - workspace13 shape tuple: must be large enough to hold the result of either expert gemm. - workspace2 shape tuple: must be large enough to hold the result of the activation function. - output shape tuple: must be exact size of the final gemm output. - Note: workspace shapes can be 0 if the workspace is not needed. But in order for activation chunking to work, the first dimension of each tuple must be the number of tokens when the shape is not 0.
FusedMoEMethodBase
¶
Bases: QuantizeMethodBase
Methods:
-
apply–Apply the MoE operation using modular kernels.
-
apply_monolithic–Apply the MoE operation using monolithic kernels.
-
maybe_roundup_sizes–Given layer hidden size and intermediate size per partition and MoE
-
uses_weight_scale_2_pattern–Returns True if this quantization method uses 'weight_scale_2' pattern
Attributes:
-
has_unpadded_output(bool) –Indicates that the hidden_states output might be the unpadded
-
skip_forward_padding(bool) –Whether to skip the padding in the forward before applying the moe method.
has_unpadded_output
property
¶
Indicates that the hidden_states output might be the unpadded hidden_states shape rather than the full padded shape.
skip_forward_padding
property
¶
Whether to skip the padding in the forward before applying the moe method.
apply(layer, x, topk_weights, topk_ids, shared_experts, shared_experts_input)
¶
Apply the MoE operation using modular kernels.
Parameters:
-
(layer¶RoutedExperts) –RoutedExperts instance containing weight parameters
-
(x¶Tensor) –Input tensor
-
(topk_weights¶Tensor) –Expert weights from router
-
(topk_ids¶Tensor) –Selected expert IDs from router
-
(shared_experts_input¶Tensor | None) –Input for shared experts (if any)
-
(shared_experts¶SharedExperts | None) –The shared experts module, if any
Returns:
-
Tensor | UnfinalizedMoEOutput–Finalized routed states or a deferred-finalize output.
apply_monolithic(layer, x, router_logits, input_ids=None)
¶
Apply the MoE operation using monolithic kernels.
Parameters:
-
(layer¶RoutedExperts) –RoutedExperts instance containing weight parameters
-
(x¶Tensor) –Input tensor
-
(router_logits¶Tensor) –Router logits (routing done internally)
-
(input_ids¶Tensor | None, default:None) –Token ids, for routers that condition on them
Returns:
-
Tensor | UnfinalizedMoEOutput–Finalized routed states or a deferred-finalize output.
maybe_roundup_sizes(hidden_size, intermediate_size_per_partition, act_dtype, moe_parallel_config)
¶
Given layer hidden size and intermediate size per partition and MoE configurations, round up hidden_size and intermediate_size_per_partition if necessary.
Parameters:
-
(hidden_size¶int) –Layer hidden-size
-
(intermediate_size_per_partition¶int) –Intermediate size per partition for the layer.
-
(act_dtype¶dtype) –Data type of the layer activations.
-
(moe_parallel_config¶FusedMoEParallelConfig) –Fused MoE parallelization strategy configuration.
Return
A tuple of (rounded_hidden_size, rounded_intermediate_size_per_partition), where: - rounded_hidden_size is the possibly rounded up hidden size. - rounded_intermediate_size_per_partition is the possibly rounded up intermediate size per partition.
uses_weight_scale_2_pattern()
¶
Returns True if this quantization method uses 'weight_scale_2' pattern for per-tensor weight scales (e.g., FP4 variants), False otherwise.
This method should be overridden by subclasses that use the 'weight_scale_2' pattern instead of the standard 'weight_scale' pattern.
FusedMoEParallelConfig
dataclass
¶
Methods:
-
make–Determine MoE parallel configuration. Based on the input
tp_size_, -
make_no_parallel–For usage in CI/CD and testing.
make(tp_size_, pcp_size_, dp_size_, sp_size_, vllm_parallel_config)
staticmethod
¶
Determine MoE parallel configuration. Based on the input tp_size_,
dp_size_ and vllm's parallel config, determine what
level's of parallelism to use in the fused moe layer.
Parameters:
-
(tp_size_¶int) –tp_sizepassed into the FusedMoEFactory constructor. -
(pcp_size_¶int) –pcp_sizepassed into the FusedMoEFactory constructor. -
(dp_size_¶int) –dp_sizepassed into the FusedMoEFactory constructor. -
(sp_size_¶int) –sp_sizepassed into the FusedMoEFactory constructor. -
(vllm_parallel_config¶ParallelConfig) –vLLM's parallel config object which contains the
enable_expert_parallelflag.
Examples:
When there is no parallelism requested,
i.e. tp_size_ = pcp_size_ = dp_size_ = 1, we simply return the sizes
unaltered and the ranks set to 0.
Expert Parallelism is considered only when either dp_size_, pcp_size_ or
tp_size_ is non trivial.
Note that PCP serves the same function as DP here.
When TP = 2, DP(PCP) = 1 and EP = False, the configuration on different devices:
- device 0 : TP = {2, 0} DP = {1, 0} EP = {1, 0} // legend : {size, rank}
- device 1 : TP = {2, 1} DP = {1, 0} EP = {1, 0}
- Comment : Tensors are sharded across 2 devices.
When TP = 1, DP(PCP) = 2 and EP = False, the configuration on different devices:
- device 0 : TP = {2, 0} DP = {2, 0} EP = {1, 0}
- device 1 : TP = {2, 1} DP = {2, 1} EP = {1, 0}
- Comment: There are 2 engine instances and the tensors are sharded across 2 decvices.
When TP = 2, DP(PCP) = 2 and EP = False, the configuration on different devices:
- device 0: TP = {4, 0} DP = {2, 0} EP = {1, 0}
- device 1: TP = {4, 1} DP = {2, 0} EP = {1, 0}
- device 2: TP = {4, 2} DP = {2, 1} EP = {1, 0}
- device 3: TP = {4, 3} DP = {2, 1} EP = {1, 0}
- Comment: There are 2 engine instances and the tensors are sharded across 4 devices.
When, TP = 2, DP(PCP) = 1 and EP = True, the configuration on different devices:
- device 0: TP = {1, 0} DP = {1, 0} EP = {2, 0}
- device 1: TP = {1, 0} DP = {1, 0} EP = {2, 1}
- Comment: The experts are split between the 2 devices.
When, TP = 1, DP(PCP) = 2 and EP = True, the configuration on different devices:
- device 0: TP = {1, 0} DP = {2, 0} EP = {2, 0}
- device 1: TP = {1, 0} DP = {2, 1} EP = {2, 1}
- Comment: There are 2 engine instances and the experts are split between the 2 devices.
When TP = 2, DP(PCP) = 2 and EP = True, the configuration on different devices:
- device 0: TP = {1, 0} DP = {2, 0} EP = {4, 0}
- device 1: TP = {1, 0} DP = {2, 0} EP = {4, 1}
- device 2: TP = {1, 0} DP = {2, 1} EP = {4, 2}
- device 3: TP = {1, 0} DP = {2, 1} EP = {4, 3}
- Comment: There are 2 engine instances and the experts are split between the 4 devices.
make_no_parallel()
classmethod
¶
For usage in CI/CD and testing.
FusedMoEPrepareAndFinalizeModular
¶
Bases: FusedMoEPrepareAndFinalize
An abstract base class for the [Quantize-Prepare] and [Finalize] steps described above for the Modular case.
Methods:
-
finalize–Perform any combine plus apply weights and perform a reduction on the
-
finalize_async–Perform any combine plus apply weights and perform a reduction on the
-
prepare–Perform any quantization (and/or) dispatching needed for this kernel.
-
prepare_async–Perform any quantization (and/or) dispatching needed for this kernel
finalize(output, fused_expert_output, topk_weights, topk_ids, apply_router_weight_on_input, weight_and_reduce_impl)
abstractmethod
¶
Perform any combine plus apply weights and perform a reduction on the fused experts output. - output: The output tensor, written in place. Must be (M, K) shape. - fused_expert_output: The unweighted, unreduced output of the fused experts, it will have (M, topk, K) shape. - topk_weights: The weights to be applied to the fused_experts_output. - topk_ids: The topk_ids. - apply_router_weight_on_input: When False, apply the weights to fused_expert_output. - weight_and_reduce_impl: An optional TopKWeightAndReduce implementation.
finalize_async(output, fused_expert_output, topk_weights, topk_ids, apply_router_weight_on_input, weight_and_reduce_impl)
¶
Perform any combine plus apply weights and perform a reduction on the fused experts output but do not wait for results from other workers. - output: The output tensor, written in place. Must be (M, K) shape. - fused_expert_output: The unweighted, unreduced output of the fused experts, it will have (M, topk, K) shape. - topk_weights: The weights to be applied to the fused_experts_output. - topk_ids: The topk_ids. - apply_router_weight_on_input: When False, apply the weights to fused_expert_output. - weight_and_reduce_impl: An optional TopKWeightAndReduce implementation.
Returns a callback or a hook callback pair that when invoked waits for
results from other workers and has the same return signature as
finalize, if a hook is returned this is more lightweight check that
the recv is complete without doing extra work (used by DBO, will be
refactored in the very near future)
ret = obj.finalize_async(output, ...) ... output not valid yet ... if isinstance(ret, tuple): hook, receiver = ret hook() receiver() ... output valid here ...
is equivalent to:
obj.finalize(output, ...)
prepare(a1, topk_weights, topk_ids, num_experts, expert_map, apply_router_weight_on_input, quant_config, defer_input_quant)
abstractmethod
¶
Perform any quantization (and/or) dispatching needed for this kernel. - a1: The (unquantized) input to the MoE layer. - topk_ids: The topk ids. - topk_weights: The topk weights. - num_experts: The total number of experts in the global expert space. - expert_map: A tensor mapping expert indices from the global expert space to the local expert space of the expert parallel shard. - apply_router_weight_on_input: When True, apply the weights to the activations, before quantization + dispatching. - quant_config: Quantization info provided by the fused experts. - defer_input_quant: Runtime parameter indicating whether or not to defer input quantization to the FusedMoEExpertsModular in cases where the compute kernel expects unquantized inputs
Returns a tuple of: - quantized + dispatched a. - Optional quantized + dispatched a1_scales. - Optional ExpertTokensMetadata containing gpu/cpu tensors as big as the number of local experts with the information about the number of tokens assigned to each local expert. - Optional dispatched expert topk IDs - Optional dispatched expert topk weight
prepare_async(a1, topk_weights, topk_ids, num_experts, expert_map, apply_router_weight_on_input, quant_config, defer_input_quant)
¶
Perform any quantization (and/or) dispatching needed for this kernel but do not wait for results from other workers. - a1: The (unquantized) input to the MoE layer. - a1_scale: Optional scales for a1 - a2_scale: Optional scales for the second MoE gemm. Required to make sure the quantization is consistent for both gemms. - topk_ids: The topk ids. - topk_weights: The topk weights. - num_experts: The total number of experts in the global expert space. - expert_map: A tensor mapping expert indices from the global expert space to the local expert space of the expert parallel shard. - apply_router_weight_on_input: When True, apply the weights to the activations, before quantization + dispatching. - defer_input_quant: Runtime parameter indicating whether or not to defer input quantization to the FusedMoEExpertsModular in cases where the compute kernel expects unquantized inputs
Returns a callback or a hook callback pair that when invoked waits for
results from other workers and has the same return signature as
prepare, if a hook is returned this is more lightweight check that
the recv is complete without doing extra work (used by DBO, will be
refactored in the very near future)
e.g.
ret = obj.prepare_async(...)
if isinstance(ret, tuple): hook, receiver = ret hook()
if hook is not None: a, a_scales, expert_meta, topk_ids, topk_weights = receiver()
is equivalent to:
a, a_scales, expert_meta, topk_ids, topk_weights = obj.prepare(...)
FusedMoEQuantConfig
dataclass
¶
The FusedMoEQuantConfig contains all the quantization parameters for a single FusedMoEMethodBase operation. It consists of four FusedMoEQuantDescs, one for each activation and set of weights.
Each FusedMoEMethodBase must implement a get_fused_moe_quant_config method to construct a FusedMoEQuantConfig for use with that class.
FusedMoEQuant configs are only used for modular kernels, fused_experts (from fused_moe.py), cutlass_moe_fp[48], rocm_aiter_fused_experts and triton_kernel_moe_forward. Other MoE methods can ignore the FusedMoEQuantConfig (for now) and hardcode it to None.
There are currently some restrictions on what can be expressed: - Most MoE ops only support similar quantization strategies for each parameter, e.g. both weights must have the same GroupShape and both activations must share the same GroupShape. One exception to this is the cutlass moe which allows per channel quantization on the outputs. Note: this restrictions are not always rigorously checked. - Not all fused MoE functions support all the parameters, e.g. zero points, global scales, alphas and biases are not universally supported. - Fully general GroupShapes are not allowed. Activations only support per token, per tensor or K-blocked. - Weights are not required to have a GroupShape since they have already been quantized.
Other notes: - PrecisionConfigs are specific to GPT OSS Triton. - As a follow up it would probably make sense to subclass FusedMoEQuantDesc or FusedMoEQuantConfig for particular FusedMoEMethodBase subclasses so that only the required quantization parameters are used/stored.
Methods:
-
act_scale_is_tensor_wide–Whether
scaleis a runtime-reduced, tensor-wide act scale. -
batched_scale_shape–Construct the proper activation batched scale shape for this
-
config_name–Return a string used to construct the filename that contains the
-
make–General builder function for a FusedMoEQuantConfig.
-
scale_shape–Construct the proper activation scale shape for this
act_scale_is_tensor_wide(scale)
¶
Whether scale is a runtime-reduced, tensor-wide act scale.
Only native fp8/int8 per-tensor quantization derives its scale from
every element of the activation, so only that scheme is affected by
rows that hold no route (e.g. PaddedStandard padding) and must be
masked out of the reduction. Per-token and block scales are row-local,
and a static scale does not depend on the data at all.
Parameters:
Returns:
-
bool–True if the scale has to be computed over routed rows only.
batched_scale_shape(num_experts, max_tokens, hidden_dim)
¶
Construct the proper activation batched scale shape for this config, e.g. (num experts, *scale_shape).
config_name(dtype)
¶
Return a string used to construct the filename that contains the tuning info for a particular quantization scheme. See try_get_optimal_moe_config in fused_moe.py.
make(quant_dtype=None, per_act_token_quant=False, per_out_ch_quant=False, block_shape=None, w1_scale=None, w2_scale=None, a1_scale=None, a2_scale=None, g1_alphas=None, g2_alphas=None, a1_gscale=None, a2_gscale=None, w1_bias=None, w2_bias=None, w1_zp=None, w2_zp=None, weight_dtype=None, is_scale_swizzled=True, is_scale_transposed=False, gemm1_alpha=None, gemm1_beta=None, gemm1_clamp_limit=None)
staticmethod
¶
General builder function for a FusedMoEQuantConfig. - quant_dtype: Optional quantization type. None if activations are unquantized or quantized prior to calling. Note: "nvfp4", "mxfp4", "mxfp6_e3m2", "mxfp6_e2m3" are the only valid string values for quant_dtype. - per_act_token_quant: Activations have per token quantization. - per_out_ch_quant: Weights have per output channel scales. It controls how the MoE kernels (Triton, CUTLASS, AITER) index the weight scales, independently of the activation scale layout. - block_shape: Optional block size for block-wise quantization. Incompatible with per_act_token and per_out_ch quant. - w1_scale: Optional scale to be used for w1. - w2_scale: Optional scale to be used for w2. - a1_scale: Optional scale to be used for a1. - a2_scale: Optional scale to be used for a2. - g1_alphas: Optional global quantization scales for w1 (for nvfp4). Optional per-channel scales for w1 (for W4A8 FP8). Optional dq scale i.e. w_scale * a_scale (for W8A8 fp8). - g2_alphas: Optional global quantization scales for w2 (for nvfp4). Optional per-channel scales for w2 (for W4A8 FP8). Optional dq scale i.e. w_scale * a_scale (for W8A8 fp8). - a1_gscale: Optional global quantization scales for a1 (1.0 /a2_scale). - a2_gscale: Optional global quantization scales for a2 (1.0 /a2_scale).
- w1_bias: Optional biases for w1 (GPT OSS Triton).
- w2_bias: Optional biases for w1 (GPT OSS Triton).
- w1_zp: Optional w1 zero points for int4/int8 quantization.
- w2_zp: Optional w2 zero points for int4/int8 quantization.
- is_scale_swizzled: Whether the activation scale-factor layout is swizzled. Pass through to the underlying quantization kernel for dtypes that distinguish layouts (nvfp4, mxfp8). Defaults to True.
- is_scale_transposed: Whether block-quantized activation scales are emitted column-major (physical [num_groups, num_tokens] layout) by the quantize step. Defaults to False.
- gemm1_alpha: Optional MXFP4 TRTLLM SwiGLU alpha parameter.
- gemm1_beta: Optional MXFP4 TRTLLM SwiGLU beta parameter.
- gemm1_clamp_limit: Optional MXFP4 TRTLLM SwiGLU clamp limit.
scale_shape(max_tokens, hidden_dim)
¶
Construct the proper activation scale shape for this config.
FusedMoERouter
¶
Bases: PluggableLayer, ABC
FusedMoERouter is an abstract class that provides a 'select_experts' method that is used for routing hidden states based on router logits.
Methods:
-
select_experts–Route the input hidden states to the top-k experts based on the
Attributes:
-
kernel_routing_method_type(RoutingMethodType) –Routing method executed by kernels, before any router override.
-
masks_padding(bool) –Whether
select_expertsalready gives padding rows expert id -1.
kernel_routing_method_type
property
¶
Routing method executed by kernels, before any router override.
masks_padding
property
¶
Whether select_experts already gives padding rows expert id -1.
select_experts(hidden_states, router_logits, topk_indices_dtype=None, *, input_ids=None)
¶
Route the input hidden states to the top-k experts based on the router logits.
Returns:
-
Tensor–(topk_weights, topk_ids)
-
tuple[Tensor, Tensor]– -
tuple[Tensor, Tensor]–The weights and expert ids computation result.
-
tuple[Tensor, Tensor]–Compatibility: When EPLB is not enabled, the returned ids are
-
tuple[Tensor, Tensor]–equivalent to global logical ids, so should be compatible with
-
tuple[Tensor, Tensor]–plain MoE implementations without redundant experts.
GateLinear
¶
Bases: ReplicatedLinear
MoE gate linear layer with multi-tier GEMM dispatch:
- cuteDSL ll_bf16_gemm (SM90+, M<=16, bf16 in, fp32 out, any shape w/ K divisible by 8)
- fp32 specialized kernel (bf16/fp32 in, fp32 out; SM90+ model-specific shapes and batch limits, gfx950 any shape with M<=32)
- cuteDSL ll_fp32w_gemm (SM90+, M<=32, bf16/fp32 in, fp32 out, any shape)
- bf16x3 CuteDSL kernel (SM90 or SM100, bf16 in, fp32 weight)
- ROCm bf16x3 router GEMM (gfx950, bf16 in, fp32 weight, fp32 out, M>=2048)
- cuBLAS bf16×bf16→fp32 (SM90+ + bf16 weight + fp32 out_dtype); gfx950 routes low M through the tier 2 kernel
- F.linear via ReplicatedLinear (ultimate fallback)
The out_dtype attribute is mutable and can be set after init
(e.g. when the required dtype depends on the expert quantization
method which is only known later).
A quant_config that actually quantizes the gate disables every
specialized tier, leaving plain ReplicatedLinear behavior.
VLLM_BATCH_INVARIANT also disables tiers 1-5: they pick kernels and
split-K from the token count and skip the batch-invariant linear path.
Methods:
-
set_out_dtype–Set output dtype for the router logits after init.
set_out_dtype(out_dtype)
¶
Set output dtype for the router logits after init.
Useful when the required dtype depends on the expert quantization method which is only known after the gate is constructed.
MoEActivation
¶
Bases: Enum
Activation functions for MoE layers.
Methods:
-
from_str–Parse from string for backward compatibility.
-
without_mul–Get the non-gated variant of this activation.
Attributes:
-
custom_op_name(str) –Maps to the CustomOp name of activations
-
is_gated(bool) –Returns True if activation expects gate*activation(up) pattern.
custom_op_name
property
¶
Maps to the CustomOp name of activations in vllm/model_executor/layers/activation.py.
is_gated
property
¶
Returns True if activation expects gate*activation(up) pattern.
Gated activations expect input tensor with 2x the output size, where the first half is the gate and second half is the up projection.
from_str(s)
classmethod
¶
Parse from string for backward compatibility.
without_mul()
¶
Get the non-gated variant of this activation.
For activations that have a _no_mul variant, returns that variant. For activations without a _no_mul variant (or already _no_mul), returns self.
MoERunner
¶
Bases: MoERunnerInterface
Standard MoE runner implementation for executing Mixture of Experts layers.
This is the primary concrete implementation of MoE execution logic, providing comprehensive support for standard MoE operations. It handles: - Expert routing and token dispatching using various routing strategies - Shared experts computation with optional parallel execution using CUDA streams - Tensor model parallel and expert parallel operations - Multiple quantization methods and optimized kernel selection - Both monolithic and decomposed expert execution paths - Integration with various parallel execution modes (TP, EP, DP)
The runner orchestrates the complete MoE forward pass including routing tokens to experts, executing expert computations in parallel, and combining results. It supports advanced features like overlapped execution of shared experts, optimized kernels for different parallel configurations, and seamless integration with vLLM's distributed execution framework.
Eventually, this class may be split into more specialized implementations for different configurations (e.g., with/without shared experts, gates, etc.).
Methods:
-
apply_routed_input_transform–Apply transform for routed experts (e.g., latent projection).
-
apply_routed_output_transform–Apply transform to routed expert output (e.g., latent to full dim).
-
forward–Invoke the fused moe layer.
-
process_weights_after_loading–Fuse router and shared expert gate weights.
-
set_eplb_state–Register the EPLB state in this layer.
Attributes:
-
expert_local_to_global(Tensor | None) –Routing table: local expert ID to global expert ID.
-
expert_map_manager–Forward to routed_experts.expert_map_manager for backward compatibility.
-
expert_physical_to_global(Tensor | None) –Routing table: physical expert ID to global expert ID.
expert_local_to_global
property
¶
Routing table: local expert ID to global expert ID.
expert_map_manager
property
¶
Forward to routed_experts.expert_map_manager for backward compatibility.
expert_physical_to_global
property
¶
Routing table: physical expert ID to global expert ID.
_apply_quant_method(hidden_states, router_logits, shared_experts_input, input_ids=None, shared_experts_overlapping=False, hidden_states_scale=None)
¶
Run expert routing and the fused MoE kernel via the quant method.
Orchestrates shared expert execution (before/after), expert selection via the router, and the actual fused MoE computation. Returns (shared_expert_output, fused_expert_output).
shared_experts_overlapping should be True only if using multi-stream
overlap. Then the shared expert was already launched in a separate
stream, so the results only have to be awaited here.
hidden_states_scale is set when hidden_states were quantized before
the PCP all-gather.
_forward_impl(hidden_states, router_logits, shared_experts_input, input_ids=None)
¶
Entry point called by the custom op to run the MoE computation.
Handles pre-dispatch setup (gate application, external shared expert triggering, quant config init) then performs the following steps within the sequence-parallel context.
- Performs expert routing
- fused MoE kernel execution
- shared expert computation.
Returns routed output, optionally paired with shared-expert output. A fused consumer may request the routed output in deferred-finalize form.
_map_global_expert_id_to_local_expert_id(expert_id)
¶
Map global expert ID to local expert ID.
_maybe_add_zero_expert_output(result)
¶
Add the zero expert's contribution to the final result.
When a ZeroExpertRouter is used, it computes a bias-like output from the "zero expert" that is added to the combined routed+shared expert output.
_maybe_apply_routed_scale_to_output(shared_output, fused_output)
¶
Apply routed_scaling_factor to the output.
Scale the fused expert output by routed_scaling_factor. With RoutedScaleMode.OUTPUT_FP16_GUARD, FP16 outputs with shared experts avoid overflow by dividing shared_output by the scale instead; the model's decoder layer must compensate with matching divisions.
_maybe_pad_hidden_states(shared_experts_input, hidden_states)
¶
Pad hidden_states to moe_config.hidden_dim and compute the original dimension for later truncation.
For latent MoE, the routed hidden_states may be smaller than hidden_dim. Padding ensures uniform tensor sizes through the fused MoE kernel. The returned trunc_size is used by _maybe_reduce_final_output to strip the padding from the result.
_maybe_reduce_final_output(states, trunc_size, output_is_reduced=None)
¶
All-reduce the combined output if needed.
This is the "late" all-reduce path. When neither fused nor shared output was individually reduced, the combined sum is all-reduced here. Skipped when sequence-parallel is active (SP handles its own reduction) or when the early path already reduced both outputs.
_maybe_reduce_routed_output_before_transform(fused_output, fused_output_is_reduced)
¶
All-reduce latent routed output before its output transform.
Latent MoE output transforms may contain non-linear ops, e.g. RMSNorm. TP partial routed outputs must be summed in latent space before such transforms are applied.
A transform that commutes with the TP sum is exempt: if
sum_r T(x_r) == T(sum_r x_r), applying the transform to the local
partial output and letting the existing late all-reduce sum the
combined result is equivalent, and costs one collective instead of two.
Such a transform opts out by setting reduce_commutative = True.
The default is False, so transforms that do not declare themselves
keep being reduced early.
_maybe_reduce_shared_expert_output(shared_output, fused_output_is_reduced=None)
¶
All-reduce shared expert output when the combine kernel already reduced fused output.
- If the combine kernel does the reduction for fused_output, reduce shared_output separately. O.w, reduce fused_output+shared_output later.
- If we have SP (TP=N, DP=M, EP), there is a separate AG step handled in the model.
_quantizes_before_pcp_gather()
¶
Whether the routed experts take input quantized row by row by a plain monolithic prepare: dynamic per-token-group fp8, or NVFP4 with a static global scale and unswizzled block scales.
_sequence_parallel_context()
¶
Return a context manager for sequence-parallel token redistribution.
When sequence parallelism is active, returns a context that handles local size tracking for proper token scatter/gather. Otherwise returns a no-op context.
apply_routed_input_transform(hidden_states)
¶
Apply transform for routed experts (e.g., latent projection).
This is called by MoERunner.forward_native. The original hidden_states is saved separately so shared experts get [S, hidden_size] while routed experts get the transformed [S, moe_latent_size].
Returns (possibly transformed) hidden states and the input for shared experts (or None if there are no shared experts).
apply_routed_output_transform(fused_output, residual=None)
¶
Apply transform to routed expert output (e.g., latent to full dim).
Used by latent MoE models (e.g., NemotronH) where routed experts
operate in a compressed latent space and need projection back to
the full hidden dimension before combining with shared expert output.
residual is passed only to transforms that set accumulates_residual.
forward(hidden_states, router_logits, input_ids=None, shared_experts_input=None)
¶
Invoke the fused moe layer.
Input: - hidden_states - router_logits
Output: - The new hidden_states.
Calling sequence - forward - self._forward_entry (_moe_forward or _moe_forward_shared custom op) - _forward_impl
Note: The existence of _moe_forward and _moe_forward_shared custom ops are due to the following reason: 1. pytorch cannot handle union types in custom op signatures so _moe_forward and _moe_forward_shared must be split.
process_weights_after_loading()
¶
Fuse router and shared expert gate weights.
Cannot be done at init because gate weights are loaded after module construction (via weight_loader). The loader runs this after every load or reload, refilling the fused tensor in place so captured CUDA graphs see updated gates.
set_eplb_state(moe_layer_idx, expert_load_view, logical_to_physical_map, logical_replica_count)
¶
Register the EPLB state in this layer.
This is used later in forward pass, where we get the expert mapping
and record the load metrics in expert_load_view.
RoutedExperts
¶
Bases: PluggableLayer
Container for routed expert weights and execution logic.
This module owns the expert weight parameters (w13_weight, w2_weight, scales, etc.) and handles: - Loading checkpoint weights into parameters - Executing routed experts via quant_method.apply()
Methods:
-
build_expert_params_mapping–Create expert parameter mapping for weight loading with redundant experts.
-
forward_modular–Execute routed experts using the quantization method's apply function.
-
forward_monolithic–Execute routed experts using the quantization method's apply function.
-
forward_monolithic_routed–Run a monolithic kernel on vLLM's routing, where padding rows are -1
-
make_expert_params_mapping–Build the expert mapping, detecting the LoRA
base_layer.prefix by
Attributes:
-
supports_precomputed_routing(bool) –Whether a monolithic kernel can take vLLM's routing instead.
supports_precomputed_routing
property
¶
Whether a monolithic kernel can take vLLM's routing instead.
_flag_padding_for_reload()
¶
Flag the params a direct reload zero-fills whole at begin; decided from the sizes at construction, before post-load processing.
_get_hidden_dim(shard_dim, ndim)
staticmethod
¶
Compute the hidden dimension index from the shard (intermediate) dimension and tensor rank.
For 2D weight tensors the two data dims are (0, 1). For 3D tensors
with an expert dimension at dim 0, they are (1, 2). shard_dim
occupies one of these; the hidden dimension is the other.
For 1D tensors (e.g. per-channel scales) returns 0.
_get_quant_method(prefix, quant_config, moe_config)
¶
Helper method to ensure quant_method is never None and of the proper type.
_load_combined_w13_weight_scale(shard_dim, loaded_weight, param, tp_rank)
¶
Load w13 weight scales assuming that w1 weight scales and w3 weight scales are stored in the same loaded_weight tensor.
_load_model_weight_or_group_weight_scale(shard_dim, expert_data, shard_id, loaded_weight, tp_rank, is_scale=False)
¶
Load grouped weight scales for group quantization or model weights
Parameters:
-
(shard_dim¶int) –dimension to shard
-
(expert_data¶Tensor) –parameter for a particular expert
-
(shard_id¶str) –either w1, w2, or w3
-
(loaded_weight¶Tensor) –checkpoint weight to load into the param
-
(tp_rank¶int) –tensor parallel rank
-
(is_scale¶bool, default:False) –whether padding should use unit scales instead of zero weights.
_map_global_expert_id_to_local_expert_id(expert_id)
¶
Map global expert ID to local expert ID.
_narrow_expert_data_for_padding(expert_data, loaded_weight, hidden_dim, shard_dim=None)
staticmethod
¶
Narrow expert_data to match loaded_weight for padded dimensions.
When backends (e.g., DeepEP) round up hidden_size, weight parameters are larger than checkpoint weights. Narrow the padded hidden dimension before copying. Similarly, when padding occurs on the shard (intermediate) dimension (e.g. for MXFP4 GEMM), narrow that dimension as well.
Parameters:
-
(expert_data¶Tensor) –The (possibly padded) parameter tensor to narrow.
-
(loaded_weight¶Tensor) –The checkpoint weight tensor with original size.
-
(hidden_dim¶int) –The dimension index corresponding to hidden_size. Must be non-negative.
-
(shard_dim¶int | None, default:None) –The dimension index corresponding to the shard (intermediate) dimension. Defaults to
None.
_orient_fused_weight(fused_weight, is_fused_checkpoint_transposed)
staticmethod
¶
Normalise a fused expert tensor to the vLLM weight layout.
build_expert_params_mapping(ckpt_gate_proj_name, ckpt_down_proj_name, ckpt_up_proj_name, num_experts, num_redundant_experts=0, routed_experts_prefix='routed_experts', lora_base_layer_prefix='', lora_base_layer_prefix_on_param_name='', include_fused=False, is_gated=True)
staticmethod
¶
Create expert parameter mapping for weight loading with redundant experts.
This mapping handles the physical-to-logical expert ID conversion needed when loading weights with EPLB redundant experts.
Parameters:
-
(ckpt_gate_proj_name¶str) –Name of gate projection in checkpoint
-
(ckpt_down_proj_name¶str) –Name of down projection in checkpoint
-
(ckpt_up_proj_name¶str | None) –Name of up projection in checkpoint
-
(num_experts¶int) –Number of logical (non-redundant) experts
-
(num_redundant_experts¶int, default:0) –Number of redundant experts
-
(lora_base_layer_prefix¶str, default:'') –LoRA
base_layer.prefix for theweight_name(checkpoint) side -
(lora_base_layer_prefix_on_param_name¶str, default:'') –same, for the
param_nameside. Independent becauseget_expert_mappingresolvesparam_nameviagetattragainst this layer's barew13_weight/w2_weight(no prefix), whilemake_expert_params_mappingindexes the model-wideparams_dict(prefix included). -
(include_fused¶bool, default:False) –Prepend the fused pre-fused-checkpoint entries
-
(is_gated¶bool, default:True) –Whether w13 holds gate and up (gated activation) or a single up projection. Selects the fused checkpoint layout.
-
(routed_experts_prefix¶str, default:'routed_experts') –Prefix of the routed experts submodule
Returns:
-
list[tuple[str, str, int, str]]–List of tuples (param_name, weight_name, expert_id, shard_id)
-
where(list[tuple[str, str, int, str]]) – -
list[tuple[str, str, int, str]]–- param_name: Parameter name in the layer
-
list[tuple[str, str, int, str]]–- weight_name: Weight name in checkpoint
-
list[tuple[str, str, int, str]]–- expert_id: Physical expert ID
-
list[tuple[str, str, int, str]]–- shard_id: Shard identifier (w1, w2, w3)
forward_modular(x, topk_weights, topk_ids, shared_experts=None, shared_experts_input=None)
¶
Execute routed experts using the quantization method's apply function.
This is called by the runner after router selection (for modular kernels) quant_method.apply() which accesses the weights on this RoutedExperts instance.
Parameters:
-
(x¶Tensor) –Input tensor after any transforms
-
(topk_weights¶Tensor) –Routing weights from router (for modular kernels)
-
(topk_ids¶Tensor) –Selected expert IDs from router (for modular kernels)
-
(shared_experts¶SharedExperts | None, default:None) –The shared experts (if any)
-
(shared_experts_input¶Tensor | None, default:None) –Input for shared experts (if any)
Returns:
-
Tensor | UnfinalizedMoEOutput–Finalized routed states or a deferred-finalize output.
forward_monolithic(x, router_logits=None, input_ids=None, x_scale=None)
¶
Execute routed experts using the quantization method's apply function.
This is called by the runner after router selection (for modular kernels) or with router logits (for monolithic kernels). It delegates to quant_method.apply() which accesses the weights on this RoutedExperts instance.
Parameters:
-
(x¶Tensor) –Input tensor after any transforms
-
(router_logits¶Tensor | None, default:None) –Router logits (for monolithic kernels)
-
(input_ids¶Tensor | None, default:None) –input ids for DeepSeek V4
-
(x_scale¶Tensor | None, default:None) –Scales of
xwhen the caller already quantized it (needsquant_method.accepts_quantized_input)
Returns:
-
Tensor | UnfinalizedMoEOutput–Finalized routed states or a deferred-finalize output.
forward_monolithic_routed(x, topk_weights, topk_ids)
¶
Run a monolithic kernel on vLLM's routing, where padding rows are -1 and activate no expert, which the kernel's own routing cannot do.
make_expert_params_mapping(model, ckpt_gate_proj_name, ckpt_down_proj_name, ckpt_up_proj_name, num_experts, num_redundant_experts=0, routed_experts_prefix='routed_experts')
staticmethod
¶
Build the expert mapping, detecting the LoRA base_layer. prefix by
scanning model's parameters.
Legacy entry point for models that still hand-roll load_weights; the
RoutedExperts weight loader uses get_expert_mapping /
build_expert_params_mapping instead (which take the prefix directly).
See build_expert_params_mapping for the returned tuple format.
SharedExperts
¶
Bases: Module
Methods:
-
maybe_forward_async–Enqueue shared experts on the aux stream without waiting for them.
-
wait–Block the main stream until
maybe_forward_asyncoutput is ready.
maybe_forward_async(shared_experts_input)
¶
Enqueue shared experts on the aux stream without waiting for them.
Returns true if the shared experts were enqueued, false otherwise. Call
wait to wait for the shared experts to finish if this returns true.
wait()
¶
Block the main stream until maybe_forward_async output is ready.
TritonExperts
¶
TritonOrDeepGemmExperts
¶
UnquantizedFusedMoEMethod
¶
Bases: FusedMoEMethodBase, CustomOp
MoE method without quantization.
_init_moe_kernel(layer)
¶
Build the MoE kernel from the layer's current (shuffled) weights.
XPUExperts
¶
Bases: LoRAExpertsMixin, FusedMoEExpertsModular
Methods:
-
initialize_weights–Bind XpuFusedMoe without prepacking; reuse while weight bindings match.
-
process_weights_after_loading–Bind XpuFusedMoe and prepack weights in place for this device's GEMM.
_lora_hooks(ctx, hidden_states, w1, w2, topk_weights, topk_ids, expert_map)
¶
Builds XpuFusedMoe hooks that add the LoRA deltas in place.
gemm1_output / act_output / gemm2_output hold one row per
(token, topk) pair grouped by expert; row_map gives each pair's
row (-1 for skipped pairs), so the LoRA kernels read and accumulate
into those rows directly.
initialize_weights(w1, w2, topk, activation, expert_map)
¶
Bind XpuFusedMoe without prepacking; reuse while weight bindings match.
process_weights_after_loading(layer)
¶
Bind XpuFusedMoe and prepack weights in place for this device's GEMM.
FusedMoEFactory(num_experts, top_k, hidden_size, intermediate_size, intermediate_pad=None, params_dtype=None, renormalize=True, use_grouped_topk=False, num_expert_group=None, topk_group=None, quant_config=None, tp_size=None, dp_size=None, pcp_size=None, prefix='', custom_routing_function=None, router=None, scoring_func='softmax', routed_scaling_factor=1.0, swiglu_limit=None, swiglu_alpha=None, swiglu_beta=None, activation_situ_beta=None, activation_situ_linear_beta=None, qat_activation_key=None, e_score_correction_bias=None, apply_router_weight_on_input=False, activation='silu', enable_eplb=False, num_redundant_experts=0, has_bias=False, is_sequence_parallel=False, reduce_results=True, ckpt_names=('gate_proj', 'down_proj', 'up_proj'), is_fused_checkpoint_transposed=False, n_shared_experts=None, fuse_shared_experts=False, shared_expert_prefix=None, router_logits_dtype=None, gate=None, shared_experts=None, shared_expert_gate=None, routed_input_transform=None, routed_output_transform=None, routed_scale_mode=RoutedScaleMode.ROUTER, zero_expert_type=None, hash_indices_table=None, bias_vl=None, image_sentinel_lo=0, runner_cls=None, runner_args=None, routed_experts_cls=None, moe_config_cls=None, routed_experts_args=None, skip_padding=False, intermediate_size_unpadded=None)
¶
Factory function for creating MoE execution pipeline.
Creates and configures a complete MoE execution pipeline including: - Router (for token-to-expert assignment) - RoutedExperts (containing expert weight parameters) - MoERunner (orchestrates the complete forward pass)
The experts contain both MergedColumnParallel weights (gate_up_proj/w13) and RowParallelLinear weights (down_proj/w2).
Note: Mixtral uses w1, w2, and w3 for gate, up, and down_proj. We copy that naming convention here and handle any remapping in the load_weights function in each model implementation.
Parameters:
-
(intermediate_pad¶int | None, default:None) –Padding added to the intermediate size, if any.
-
(swiglu_alpha¶float | None, default:None) –Optional alpha parameter for the SwiGLU activation.
-
(swiglu_beta¶float | None, default:None) –Optional beta parameter for the SwiGLU activation.
Parameters:
-
(num_experts¶int) –Number of experts in the model (global count)
-
(top_k¶int) –Number of experts selected for each token
-
(hidden_size¶int) –Input hidden state size of the transformer
-
(intermediate_size¶int) –Intermediate size of the experts
-
(params_dtype¶dtype | None, default:None) –Data type for the parameters
-
(renormalize¶bool, default:True) –Whether to renormalize the logits in the router
-
(use_grouped_topk¶bool, default:False) –Whether to use grouped top-k routing
-
(num_expert_group¶int | None, default:None) –Number of expert groups for grouped top-k
-
(topk_group¶int | None, default:None) –Top-k value per group for grouped top-k
-
(quant_config¶QuantizationConfig | None, default:None) –Quantization configuration
-
(tp_size¶int | None, default:None) –Tensor parallelism size (None = use global default)
-
(dp_size¶int | None, default:None) –Data parallelism size (None = use global default)
-
(pcp_size¶int | None, default:None) –Pipeline context parallelism size (None = use global default)
-
(prefix¶str, default:'') –Layer name prefix for weight loading
-
(custom_routing_function¶Callable | None, default:None) –Custom routing function override
-
(router¶FusedMoERouter | None, default:None) –Pre-configured router instance (None = create default)
-
(scoring_func¶str, default:'softmax') –Scoring function for routing ("softmax" or others)
-
(routed_scaling_factor¶float, default:1.0) –Scaling factor applied to topk_weights or output
-
(swiglu_limit¶float | None, default:None) –SwiGLU activation limit
-
(activation_situ_beta¶float | None, default:None) –SituGLU activation beta
-
(activation_situ_linear_beta¶float | None, default:None) –SituGLU linear beta
-
(qat_activation_key¶QuantKey | None, default:None) –Activation quantization scheme the experts were trained against, for checkpoints that do not record it
-
(e_score_correction_bias¶Tensor | None, default:None) –Expert score correction bias tensor
-
(apply_router_weight_on_input¶bool, default:False) –Whether to apply router weights on input
-
(activation¶str, default:'silu') –Activation function name ("silu", "gelu", etc.)
-
(enable_eplb¶bool, default:False) –Whether to enable expert parallelism load balancer
-
(num_redundant_experts¶int, default:0) –Number of redundant experts for EPLB
-
(has_bias¶bool, default:False) –Whether expert layers have bias terms
-
(is_sequence_parallel¶bool, default:False) –Whether sequence parallelism is enabled
-
(reduce_results¶bool, default:True) –Whether to all-reduce the final output. Setting this to False (to fuse the all-reduce downstream) is only honored on the late-AR path.
-
(ckpt_names¶tuple[str, str, str | None], default:('gate_proj', 'down_proj', 'up_proj')) –Checkpoint parameter name tuple (gate_proj, down_proj, up_proj) used for weight loading
-
(is_fused_checkpoint_transposed¶bool, default:False) –Whether fused checkpoint weights and block scales use transposed storage.
-
(n_shared_experts¶int | None, default:None) –Number of shared experts to fuse into the routed grouped GEMM (ROCm; requires aiter FSE or the router-append path)
-
(fuse_shared_experts¶bool, default:False) –Whether to enable shared-expert fusion.
-
(shared_expert_prefix¶str | None, default:None) –Checkpoint prefix for the fused shared expert.
-
(router_logits_dtype¶dtype | None, default:None) –Data type for router logits buffers
-
(gate¶Module | None, default:None) –Pre-configured gate module
-
(shared_experts¶Module | None, default:None) –Pre-configured shared experts module
-
(shared_expert_gate¶Module | None, default:None) –Pre-configured shared expert gate module
-
(routed_input_transform¶Module | None, default:None) –Input transformation module
-
(routed_output_transform¶Module | None, default:None) –Output transformation module
-
(routed_scale_mode¶RoutedScaleMode, default:ROUTER) –Where routed_scaling_factor is applied: folded into the top-k weights (ROUTER), or applied by the runner to the output (OUTPUT, OUTPUT_FP16_GUARD). See RoutedScaleMode.
-
(zero_expert_type¶str | None, default:None) –Type of zero expert handling
-
(hash_indices_table¶Tensor | None, default:None) –Hash table for expert indices
-
(bias_vl¶Tensor | None, default:None) –Vision routing bias for image tokens (Deepseek V4)
-
(image_sentinel_lo¶int, default:0) –First of five consecutive in-vocab image sentinel ids (0 = vision routing disabled)
-
(runner_cls¶type[MoERunner] | None, default:None) –Custom MoERunner class (None = use default MoERunner)
-
(runner_args¶dict[str, Any] | None, default:None) –Additional arguments for runner constructor
-
(routed_experts_cls¶type[RoutedExperts] | None, default:None) –Custom RoutedExperts class (None = use default)
-
(moe_config_cls¶type[FusedMoEConfig] | None, default:None) –Custom FusedMoEConfig class (None = use default)
-
(routed_experts_args¶dict[str, Any] | None, default:None) –Additional arguments for routed_experts constructor
-
(skip_padding¶bool, default:False) –With ROCm AITER fused MoE, let grouped routing mask padding rows under DeepEP v2; otherwise it follows VLLM_MOE_SKIP_PADDING.
-
(intermediate_size_unpadded¶int | None, default:None) –Global intermediate size the checkpoint holds, when
intermediate_sizeis padded (None = not padded)
Returns:
-
MoERunner(MoERunner) –Configured MoE execution pipeline ready for forward passes
activation_without_mul(activation)
¶
apply_moe_activation(activation, output, input, *, activation_config=None, topk_ids=None, expert_map=None, valid_token_counts=None)
¶
Apply MoE activation function.
The configuration drives specialized activation behavior. Routing tensors
and valid token counts remain per-call inputs because they depend on the
current token assignment. A single token count masks a flat [T, D]
buffer; one count per expert masks each prefix in a padded [E, T, D]
buffer.
fused_experts(hidden_states, w1, w2, topk_weights, topk_ids, activation=MoEActivation.SILU, apply_router_weight_on_input=False, global_num_experts=-1, expert_map=None, quant_config=None)
¶
Run fused MoE expert computation using Triton kernels.
fused_moe_make_expert_params_mapping(model, ckpt_gate_proj_name, ckpt_down_proj_name, ckpt_up_proj_name, num_experts, num_redundant_experts=0, routed_experts_prefix='routed_experts')
¶
Delegate to EPLB manager.