2025-03-03 06:36:40 -08:00
|
|
|
import torch
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def moe_align_block_size(
|
|
|
|
|
topk_ids,
|
|
|
|
|
num_experts,
|
|
|
|
|
block_size,
|
|
|
|
|
sorted_token_ids,
|
|
|
|
|
experts_ids,
|
|
|
|
|
num_tokens_post_pad,
|
|
|
|
|
token_cnts_buffer,
|
|
|
|
|
cumsum_buffer,
|
|
|
|
|
):
|
2025-03-27 19:09:58 -07:00
|
|
|
torch.ops.sgl_kernel.moe_align_block_size.default(
|
2025-03-03 06:36:40 -08:00
|
|
|
topk_ids,
|
|
|
|
|
num_experts,
|
|
|
|
|
block_size,
|
|
|
|
|
sorted_token_ids,
|
|
|
|
|
experts_ids,
|
|
|
|
|
num_tokens_post_pad,
|
|
|
|
|
token_cnts_buffer,
|
|
|
|
|
cumsum_buffer,
|
|
|
|
|
)
|
2025-03-14 12:03:33 -07:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def topk_softmax(
|
|
|
|
|
topk_weights: torch.Tensor,
|
|
|
|
|
topk_ids: torch.Tensor,
|
|
|
|
|
token_expert_indices: torch.Tensor,
|
|
|
|
|
gating_output: float,
|
|
|
|
|
) -> None:
|
2025-03-27 19:09:58 -07:00
|
|
|
torch.ops.sgl_kernel.topk_softmax.default(
|
2025-03-14 12:03:33 -07:00
|
|
|
topk_weights, topk_ids, token_expert_indices, gating_output
|
|
|
|
|
)
|
2025-03-29 11:51:45 -07:00
|
|
|
|
|
|
|
|
|
2025-04-18 14:05:15 +08:00
|
|
|
def moe_fused_gate(
|
|
|
|
|
input_tensor,
|
|
|
|
|
bias,
|
|
|
|
|
num_expert_group,
|
|
|
|
|
topk_group,
|
|
|
|
|
topk,
|
|
|
|
|
n_share_experts_fusion=0,
|
|
|
|
|
routed_scaling_factor=0,
|
|
|
|
|
):
|
2025-03-29 11:51:45 -07:00
|
|
|
# This fused kernel function is used to select topk expert in a hierarchical 2-layer fashion
|
|
|
|
|
# it split group of expert into num_expert_group, and use top2 expert weight sum in each group
|
|
|
|
|
# as the group weight to select exerpt groups and then select topk experts within the selected groups
|
|
|
|
|
# the #experts is decided by the input tensor shape and we currently only support power of 2 #experts
|
|
|
|
|
# and #experts should be divisible by num_expert_group. #expert/num_expert_group <= 32 is limitted for now.
|
|
|
|
|
# for non-supported case, we suggestion to use the biased_grouped_topk func in sglang.srt.layers.moe.topk
|
2025-04-18 14:05:15 +08:00
|
|
|
# n_share_experts_fusion: if > 0, the last expert will be replaced with a round-robin shared expert
|
|
|
|
|
# routed_scaling_factor: if > 0, the last expert will be scaled by this factor
|
2025-03-30 03:31:59 +08:00
|
|
|
return torch.ops.sgl_kernel.moe_fused_gate.default(
|
2025-04-18 14:05:15 +08:00
|
|
|
input_tensor,
|
|
|
|
|
bias,
|
|
|
|
|
num_expert_group,
|
|
|
|
|
topk_group,
|
|
|
|
|
topk,
|
|
|
|
|
n_share_experts_fusion,
|
|
|
|
|
routed_scaling_factor,
|
2025-03-29 11:51:45 -07:00
|
|
|
)
|