Convert formatting to use ruff instead of yapf + isort (#26247)
Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com>
This commit is contained in:
@@ -6,10 +6,15 @@ from typing import Any, Optional
|
||||
|
||||
from vllm.model_executor.layers.fused_moe.config import FusedMoEConfig
|
||||
from vllm.model_executor.layers.fused_moe.layer import (
|
||||
FusedMoE, FusedMoEMethodBase, FusedMoeWeightScaleSupported)
|
||||
FusedMoE,
|
||||
FusedMoEMethodBase,
|
||||
FusedMoeWeightScaleSupported,
|
||||
)
|
||||
from vllm.model_executor.layers.fused_moe.modular_kernel import (
|
||||
FusedMoEActivationFormat, FusedMoEPermuteExpertsUnpermute,
|
||||
FusedMoEPrepareAndFinalize)
|
||||
FusedMoEActivationFormat,
|
||||
FusedMoEPermuteExpertsUnpermute,
|
||||
FusedMoEPrepareAndFinalize,
|
||||
)
|
||||
from vllm.model_executor.layers.fused_moe.utils import activation_without_mul
|
||||
from vllm.triton_utils import HAS_TRITON
|
||||
|
||||
@@ -46,21 +51,31 @@ if HAS_TRITON:
|
||||
# import to register the custom ops
|
||||
import vllm.model_executor.layers.fused_moe.fused_marlin_moe # noqa
|
||||
from vllm.model_executor.layers.fused_moe.batched_deep_gemm_moe import (
|
||||
BatchedDeepGemmExperts)
|
||||
BatchedDeepGemmExperts,
|
||||
)
|
||||
from vllm.model_executor.layers.fused_moe.batched_triton_or_deep_gemm_moe import ( # noqa: E501
|
||||
BatchedTritonOrDeepGemmExperts)
|
||||
BatchedTritonOrDeepGemmExperts,
|
||||
)
|
||||
from vllm.model_executor.layers.fused_moe.cutlass_moe import (
|
||||
CutlassBatchedExpertsFp8, CutlassExpertsFp8, cutlass_moe_fp4,
|
||||
cutlass_moe_fp8)
|
||||
from vllm.model_executor.layers.fused_moe.deep_gemm_moe import (
|
||||
DeepGemmExperts)
|
||||
CutlassBatchedExpertsFp8,
|
||||
CutlassExpertsFp8,
|
||||
cutlass_moe_fp4,
|
||||
cutlass_moe_fp8,
|
||||
)
|
||||
from vllm.model_executor.layers.fused_moe.deep_gemm_moe import DeepGemmExperts
|
||||
from vllm.model_executor.layers.fused_moe.fused_batched_moe import (
|
||||
BatchedTritonExperts)
|
||||
BatchedTritonExperts,
|
||||
)
|
||||
from vllm.model_executor.layers.fused_moe.fused_moe import (
|
||||
TritonExperts, fused_experts, fused_topk, get_config_file_name,
|
||||
grouped_topk)
|
||||
TritonExperts,
|
||||
fused_experts,
|
||||
fused_topk,
|
||||
get_config_file_name,
|
||||
grouped_topk,
|
||||
)
|
||||
from vllm.model_executor.layers.fused_moe.triton_deep_gemm_moe import (
|
||||
TritonOrDeepGemmExperts)
|
||||
TritonOrDeepGemmExperts,
|
||||
)
|
||||
|
||||
__all__ += [
|
||||
"fused_topk",
|
||||
@@ -82,8 +97,7 @@ else:
|
||||
# Some model classes directly use the custom ops. Add placeholders
|
||||
# to avoid import errors.
|
||||
def _raise_exception(method: str):
|
||||
raise NotImplementedError(
|
||||
f"{method} is not implemented as lack of triton.")
|
||||
raise NotImplementedError(f"{method} is not implemented as lack of triton.")
|
||||
|
||||
fused_topk = lambda *args, **kwargs: _raise_exception("fused_topk")
|
||||
fused_experts = lambda *args, **kwargs: _raise_exception("fused_experts")
|
||||
|
||||
@@ -8,15 +8,14 @@ import torch
|
||||
import vllm.model_executor.layers.fused_moe.modular_kernel as mk
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.fused_moe.config import FusedMoEQuantConfig
|
||||
from vllm.model_executor.layers.fused_moe.deep_gemm_utils import (
|
||||
deep_gemm_block_shape)
|
||||
from vllm.model_executor.layers.fused_moe.deep_gemm_utils import deep_gemm_block_shape
|
||||
from vllm.model_executor.layers.fused_moe.topk_weight_and_reduce import (
|
||||
TopKWeightAndReduceDelegate)
|
||||
TopKWeightAndReduceDelegate,
|
||||
)
|
||||
from vllm.model_executor.layers.fused_moe.utils import _resize_cache
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import tl, triton
|
||||
from vllm.utils.deep_gemm import (fp8_m_grouped_gemm_nt_masked,
|
||||
is_deep_gemm_e8m0_used)
|
||||
from vllm.utils.deep_gemm import fp8_m_grouped_gemm_nt_masked, is_deep_gemm_e8m0_used
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
@@ -73,17 +72,14 @@ def _silu_mul_fp8_quant_deep_gemm(
|
||||
base_input_offset = e * stride_i_e + g * GROUP_SIZE * stride_i_h
|
||||
base_gate_offset = base_input_offset + cols * stride_i_h
|
||||
base_up_offset = base_input_offset + H * stride_i_h + cols * stride_i_h
|
||||
base_yq_offset = (e * stride_yq_e + g * GROUP_SIZE * stride_yq_h +
|
||||
cols * stride_yq_h)
|
||||
base_yq_offset = e * stride_yq_e + g * GROUP_SIZE * stride_yq_h + cols * stride_yq_h
|
||||
base_ys_offset = e * stride_ys_e + g * stride_ys_g
|
||||
|
||||
for t in tl.range(0, n_tokens, num_stages=NUM_STAGES):
|
||||
gate = tl.load(input_ptr + base_gate_offset + t * stride_i_t,
|
||||
mask=mask,
|
||||
other=0.0).to(tl.float32)
|
||||
up = tl.load(input_ptr + base_up_offset + t * stride_i_t,
|
||||
mask=mask,
|
||||
other=0.0)
|
||||
gate = tl.load(
|
||||
input_ptr + base_gate_offset + t * stride_i_t, mask=mask, other=0.0
|
||||
).to(tl.float32)
|
||||
up = tl.load(input_ptr + base_up_offset + t * stride_i_t, mask=mask, other=0.0)
|
||||
|
||||
gate = gate * (1.0 / (1.0 + tl.exp(-gate)))
|
||||
y = gate * up
|
||||
@@ -120,8 +116,7 @@ def silu_mul_fp8_quant_deep_gemm_cuda(
|
||||
assert group_size == 128, "H must be divisible by 8"
|
||||
assert tokens_per_expert.ndim == 1 and tokens_per_expert.shape[0] == E
|
||||
|
||||
tokens_per_expert = tokens_per_expert.to(device=y.device,
|
||||
dtype=torch.int32)
|
||||
tokens_per_expert = tokens_per_expert.to(device=y.device, dtype=torch.int32)
|
||||
|
||||
fp8_dtype = torch.float8_e4m3fn
|
||||
y_q = torch.empty((E, T, H), dtype=fp8_dtype, device=y.device)
|
||||
@@ -129,10 +124,12 @@ def silu_mul_fp8_quant_deep_gemm_cuda(
|
||||
stride_ys_e = T * G
|
||||
stride_ys_t = 1
|
||||
stride_ys_g = T
|
||||
y_s = torch.empty_strided((E, T, G),
|
||||
(stride_ys_e, stride_ys_t, stride_ys_g),
|
||||
dtype=torch.float32,
|
||||
device=y.device)
|
||||
y_s = torch.empty_strided(
|
||||
(E, T, G),
|
||||
(stride_ys_e, stride_ys_t, stride_ys_g),
|
||||
dtype=torch.float32,
|
||||
device=y.device,
|
||||
)
|
||||
|
||||
use_ue8m0 = is_deep_gemm_e8m0_used()
|
||||
|
||||
@@ -146,17 +143,16 @@ def silu_mul_fp8_quant_deep_gemm_cuda(
|
||||
# We never want to launch more than Tx number of threads
|
||||
# This computes the clip.
|
||||
num_parallel_tokens = max(
|
||||
1,
|
||||
min(max_empirical_parallelism, 2**int(log2(min(num_parallel_tokens,
|
||||
T)))))
|
||||
1, min(max_empirical_parallelism, 2 ** int(log2(min(num_parallel_tokens, T))))
|
||||
)
|
||||
cuda_arch = current_platform.get_device_capability(
|
||||
device_id=y.device.index).to_int()
|
||||
device_id=y.device.index
|
||||
).to_int()
|
||||
|
||||
if cuda_arch >= 80:
|
||||
torch.ops._C.silu_mul_fp8_quant_deep_gemm_cuda(y, tokens_per_expert,
|
||||
y_q, y_s, group_size,
|
||||
use_ue8m0,
|
||||
num_parallel_tokens)
|
||||
torch.ops._C.silu_mul_fp8_quant_deep_gemm_cuda(
|
||||
y, tokens_per_expert, y_q, y_s, group_size, use_ue8m0, num_parallel_tokens
|
||||
)
|
||||
else:
|
||||
# Default to triton if not on cuda or if arch is too old
|
||||
y_q = torch.empty((E, T, H), dtype=fp8_dtype, device=y.device)
|
||||
@@ -165,7 +161,7 @@ def silu_mul_fp8_quant_deep_gemm_cuda(
|
||||
|
||||
# Static grid over experts and H-groups.
|
||||
# A loop inside the kernel handles the token dim
|
||||
grid = (E * G, )
|
||||
grid = (E * G,)
|
||||
# strides (elements)
|
||||
stride_i_e, stride_i_t, stride_i_h = y.stride()
|
||||
stride_yq_e, stride_yq_t, stride_yq_h = y_q.stride()
|
||||
@@ -214,7 +210,6 @@ def silu_mul_fp8_quant_deep_gemm_cuda(
|
||||
|
||||
|
||||
class BatchedDeepGemmExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
max_num_tokens: int,
|
||||
@@ -233,10 +228,12 @@ class BatchedDeepGemmExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
|
||||
@property
|
||||
def activation_formats(
|
||||
self
|
||||
self,
|
||||
) -> tuple[mk.FusedMoEActivationFormat, mk.FusedMoEActivationFormat]:
|
||||
return (mk.FusedMoEActivationFormat.BatchedExperts,
|
||||
mk.FusedMoEActivationFormat.BatchedExperts)
|
||||
return (
|
||||
mk.FusedMoEActivationFormat.BatchedExperts,
|
||||
mk.FusedMoEActivationFormat.BatchedExperts,
|
||||
)
|
||||
|
||||
def supports_chunking(self) -> bool:
|
||||
return False
|
||||
@@ -266,10 +263,10 @@ class BatchedDeepGemmExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
# end up sending their tokens. This needs to be fixed.
|
||||
num_dispatchers = self.num_dispatchers
|
||||
num_experts = local_num_experts
|
||||
max_num_tokens = a.size(
|
||||
0) if self.max_num_tokens is None else self.max_num_tokens
|
||||
workspace13 = (num_experts, max_num_tokens * num_dispatchers,
|
||||
max(K, N))
|
||||
max_num_tokens = (
|
||||
a.size(0) if self.max_num_tokens is None else self.max_num_tokens
|
||||
)
|
||||
workspace13 = (num_experts, max_num_tokens * num_dispatchers, max(K, N))
|
||||
workspace2 = (num_experts, max_num_tokens * num_dispatchers, (N // 2))
|
||||
output = (num_experts, max_num_tokens * num_dispatchers, K)
|
||||
return (workspace13, workspace2, output, a.dtype)
|
||||
@@ -304,7 +301,8 @@ class BatchedDeepGemmExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
assert w2.size(1) == K
|
||||
|
||||
E, max_num_tokens, N, K, top_k_num = self.moe_problem_size(
|
||||
hidden_states, w1, w2, topk_ids)
|
||||
hidden_states, w1, w2, topk_ids
|
||||
)
|
||||
|
||||
workspace1 = _resize_cache(workspace13, (E, max_num_tokens, N))
|
||||
|
||||
@@ -312,11 +310,18 @@ class BatchedDeepGemmExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
# for the M expectation of each batch, correctly setting this value
|
||||
# may lead to better performance.
|
||||
expected_m = max_num_tokens
|
||||
fp8_m_grouped_gemm_nt_masked((a1q, a1q_scale), (w1, self.w1_scale),
|
||||
workspace1, expert_num_tokens, expected_m)
|
||||
fp8_m_grouped_gemm_nt_masked(
|
||||
(a1q, a1q_scale),
|
||||
(w1, self.w1_scale),
|
||||
workspace1,
|
||||
expert_num_tokens,
|
||||
expected_m,
|
||||
)
|
||||
|
||||
a2q, a2q_scale = silu_mul_fp8_quant_deep_gemm_cuda(
|
||||
workspace1, expert_num_tokens)
|
||||
workspace1, expert_num_tokens
|
||||
)
|
||||
|
||||
fp8_m_grouped_gemm_nt_masked((a2q, a2q_scale), (w2, self.w2_scale),
|
||||
output, expert_num_tokens, expected_m)
|
||||
fp8_m_grouped_gemm_nt_masked(
|
||||
(a2q, a2q_scale), (w2, self.w2_scale), output, expert_num_tokens, expected_m
|
||||
)
|
||||
|
||||
@@ -6,16 +6,14 @@ import torch
|
||||
|
||||
import vllm.model_executor.layers.fused_moe.modular_kernel as mk
|
||||
from vllm.model_executor.layers.fused_moe.batched_deep_gemm_moe import (
|
||||
BatchedDeepGemmExperts)
|
||||
BatchedDeepGemmExperts,
|
||||
)
|
||||
from vllm.model_executor.layers.fused_moe.config import FusedMoEQuantConfig
|
||||
from vllm.model_executor.layers.fused_moe.deep_gemm_utils import (
|
||||
deep_gemm_block_shape)
|
||||
from vllm.model_executor.layers.fused_moe.fused_batched_moe import (
|
||||
BatchedTritonExperts)
|
||||
from vllm.model_executor.layers.fused_moe.deep_gemm_utils import deep_gemm_block_shape
|
||||
from vllm.model_executor.layers.fused_moe.fused_batched_moe import BatchedTritonExperts
|
||||
|
||||
|
||||
class BatchedTritonOrDeepGemmExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
max_num_tokens: int,
|
||||
@@ -31,27 +29,37 @@ class BatchedTritonOrDeepGemmExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
quant_config=self.quant_config,
|
||||
)
|
||||
|
||||
self.allow_deep_gemm = (allow_deep_gemm
|
||||
and self.quant_config.use_fp8_w8a8 and
|
||||
self.block_shape == deep_gemm_block_shape())
|
||||
self.allow_deep_gemm = (
|
||||
allow_deep_gemm
|
||||
and self.quant_config.use_fp8_w8a8
|
||||
and self.block_shape == deep_gemm_block_shape()
|
||||
)
|
||||
|
||||
self.batched_deep_gemm_experts = BatchedDeepGemmExperts(
|
||||
max_num_tokens=max_num_tokens,
|
||||
num_dispatchers=num_dispatchers,
|
||||
quant_config=self.quant_config,
|
||||
) if self.allow_deep_gemm else None
|
||||
self.batched_deep_gemm_experts = (
|
||||
BatchedDeepGemmExperts(
|
||||
max_num_tokens=max_num_tokens,
|
||||
num_dispatchers=num_dispatchers,
|
||||
quant_config=self.quant_config,
|
||||
)
|
||||
if self.allow_deep_gemm
|
||||
else None
|
||||
)
|
||||
|
||||
assert (self.batched_deep_gemm_experts is not None
|
||||
or self.batched_triton_experts is not None)
|
||||
assert (
|
||||
self.batched_deep_gemm_experts is not None
|
||||
or self.batched_triton_experts is not None
|
||||
)
|
||||
|
||||
@property
|
||||
def activation_formats(
|
||||
self
|
||||
self,
|
||||
) -> tuple[mk.FusedMoEActivationFormat, mk.FusedMoEActivationFormat]:
|
||||
if self.batched_triton_experts is not None:
|
||||
assert (self.batched_deep_gemm_experts is None
|
||||
or self.batched_deep_gemm_experts.activation_formats
|
||||
== self.batched_triton_experts.activation_formats)
|
||||
assert (
|
||||
self.batched_deep_gemm_experts is None
|
||||
or self.batched_deep_gemm_experts.activation_formats
|
||||
== self.batched_triton_experts.activation_formats
|
||||
)
|
||||
return self.batched_triton_experts.activation_formats
|
||||
else:
|
||||
assert self.batched_deep_gemm_experts is not None
|
||||
@@ -60,14 +68,16 @@ class BatchedTritonOrDeepGemmExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
def supports_chunking(self) -> bool:
|
||||
bdge = self.batched_deep_gemm_experts
|
||||
bte = self.batched_triton_experts
|
||||
return ((bdge is None or bdge.supports_chunking())
|
||||
and (bte is None or bte.supports_chunking()))
|
||||
return (bdge is None or bdge.supports_chunking()) and (
|
||||
bte is None or bte.supports_chunking()
|
||||
)
|
||||
|
||||
def supports_expert_map(self) -> bool:
|
||||
bdge = self.batched_deep_gemm_experts
|
||||
bte = self.batched_triton_experts
|
||||
return ((bdge is None or bdge.supports_expert_map())
|
||||
and (bte is None or bte.supports_expert_map()))
|
||||
return (bdge is None or bdge.supports_expert_map()) and (
|
||||
bte is None or bte.supports_expert_map()
|
||||
)
|
||||
|
||||
def finalize_weight_and_reduce_impl(self) -> mk.TopKWeightAndReduce:
|
||||
bdge = self.batched_deep_gemm_experts
|
||||
@@ -80,7 +90,8 @@ class BatchedTritonOrDeepGemmExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
if is_bdge_war and is_bte_war:
|
||||
assert bdge_war == bte_war, (
|
||||
"Both implementations should agree on WeightAndReduce impls. "
|
||||
f"Got bdge_war: {bdge_war}, and bte_war: {bte_war}")
|
||||
f"Got bdge_war: {bdge_war}, and bte_war: {bte_war}"
|
||||
)
|
||||
|
||||
if bdge_war is not None:
|
||||
return bdge_war
|
||||
@@ -106,13 +117,29 @@ class BatchedTritonOrDeepGemmExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
if self.allow_deep_gemm:
|
||||
assert self.batched_deep_gemm_experts is not None
|
||||
return self.batched_deep_gemm_experts.workspace_shapes(
|
||||
a, aq, M, N, K, topk, global_num_experts, local_num_experts,
|
||||
expert_tokens_metadata)
|
||||
a,
|
||||
aq,
|
||||
M,
|
||||
N,
|
||||
K,
|
||||
topk,
|
||||
global_num_experts,
|
||||
local_num_experts,
|
||||
expert_tokens_metadata,
|
||||
)
|
||||
else:
|
||||
assert self.batched_triton_experts is not None
|
||||
return self.batched_triton_experts.workspace_shapes(
|
||||
a, aq, M, N, K, topk, global_num_experts, local_num_experts,
|
||||
expert_tokens_metadata)
|
||||
a,
|
||||
aq,
|
||||
M,
|
||||
N,
|
||||
K,
|
||||
topk,
|
||||
global_num_experts,
|
||||
local_num_experts,
|
||||
expert_tokens_metadata,
|
||||
)
|
||||
|
||||
def apply(
|
||||
self,
|
||||
@@ -132,10 +159,26 @@ class BatchedTritonOrDeepGemmExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
expert_tokens_meta: Optional[mk.ExpertTokensMetadata],
|
||||
apply_router_weight_on_input: bool,
|
||||
):
|
||||
experts = (self.batched_deep_gemm_experts
|
||||
if self.allow_deep_gemm else self.batched_triton_experts)
|
||||
experts = (
|
||||
self.batched_deep_gemm_experts
|
||||
if self.allow_deep_gemm
|
||||
else self.batched_triton_experts
|
||||
)
|
||||
assert experts is not None
|
||||
experts.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)
|
||||
experts.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,
|
||||
)
|
||||
|
||||
@@ -9,8 +9,7 @@ import vllm.envs as envs
|
||||
from vllm.config import ParallelConfig
|
||||
from vllm.distributed import get_dp_group, get_tensor_model_parallel_rank
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import (
|
||||
GroupShape)
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import GroupShape
|
||||
from vllm.utils import cdiv, has_triton_kernels
|
||||
from vllm.utils.flashinfer import has_flashinfer_cutlass_fused_moe
|
||||
|
||||
@@ -22,7 +21,8 @@ if has_triton_kernels():
|
||||
except ImportError:
|
||||
logger.error(
|
||||
"Failed to import Triton kernels. Please make sure your triton "
|
||||
"version is compatible.")
|
||||
"version is compatible."
|
||||
)
|
||||
|
||||
|
||||
def _get_config_dtype_str(
|
||||
@@ -163,8 +163,9 @@ class FusedMoEQuantConfig:
|
||||
_w2: FusedMoEQuantDesc
|
||||
|
||||
def __post_init__(self):
|
||||
assert (not self.per_act_token_quant
|
||||
or self.block_shape is None), "illegal quantization"
|
||||
assert not self.per_act_token_quant or self.block_shape is None, (
|
||||
"illegal quantization"
|
||||
)
|
||||
|
||||
#
|
||||
# Convenience accessors for various properties.
|
||||
@@ -196,9 +197,11 @@ class FusedMoEQuantConfig:
|
||||
|
||||
@property
|
||||
def block_shape(self) -> Optional[list[int]]:
|
||||
if (self._a1.shape is not None
|
||||
and self._a1.shape != GroupShape.PER_TENSOR
|
||||
and self._a1.shape != GroupShape.PER_TOKEN):
|
||||
if (
|
||||
self._a1.shape is not None
|
||||
and self._a1.shape != GroupShape.PER_TENSOR
|
||||
and self._a1.shape != GroupShape.PER_TOKEN
|
||||
):
|
||||
return [self._a1.shape.row, self._a1.shape.col]
|
||||
else:
|
||||
return None
|
||||
@@ -209,8 +212,7 @@ class FusedMoEQuantConfig:
|
||||
|
||||
@property
|
||||
def a1_scale(self) -> Optional[torch.Tensor]:
|
||||
assert self._a1.scale is None or isinstance(self._a1.scale,
|
||||
torch.Tensor)
|
||||
assert self._a1.scale is None or isinstance(self._a1.scale, torch.Tensor)
|
||||
return self._a1.scale
|
||||
|
||||
@property
|
||||
@@ -219,8 +221,7 @@ class FusedMoEQuantConfig:
|
||||
|
||||
@property
|
||||
def a2_scale(self) -> Optional[torch.Tensor]:
|
||||
assert self._a2.scale is None or isinstance(self._a2.scale,
|
||||
torch.Tensor)
|
||||
assert self._a2.scale is None or isinstance(self._a2.scale, torch.Tensor)
|
||||
return self._a2.scale
|
||||
|
||||
@property
|
||||
@@ -229,8 +230,7 @@ class FusedMoEQuantConfig:
|
||||
|
||||
@property
|
||||
def w1_scale(self) -> Optional[torch.Tensor]:
|
||||
assert self._w1.scale is None or isinstance(self._w1.scale,
|
||||
torch.Tensor)
|
||||
assert self._w1.scale is None or isinstance(self._w1.scale, torch.Tensor)
|
||||
return self._w1.scale
|
||||
|
||||
@property
|
||||
@@ -243,8 +243,7 @@ class FusedMoEQuantConfig:
|
||||
|
||||
@property
|
||||
def w1_precision(self) -> Optional["PrecisionConfig"]:
|
||||
assert self._w1.scale is None or isinstance(self._w1.scale,
|
||||
PrecisionConfig)
|
||||
assert self._w1.scale is None or isinstance(self._w1.scale, PrecisionConfig)
|
||||
return self._w1.scale
|
||||
|
||||
@property
|
||||
@@ -253,8 +252,7 @@ class FusedMoEQuantConfig:
|
||||
|
||||
@property
|
||||
def w2_scale(self) -> Optional[torch.Tensor]:
|
||||
assert self._w2.scale is None or isinstance(self._w2.scale,
|
||||
torch.Tensor)
|
||||
assert self._w2.scale is None or isinstance(self._w2.scale, torch.Tensor)
|
||||
return self._w2.scale
|
||||
|
||||
@property
|
||||
@@ -267,8 +265,7 @@ class FusedMoEQuantConfig:
|
||||
|
||||
@property
|
||||
def w2_precision(self) -> Optional["PrecisionConfig"]:
|
||||
assert self._w2.scale is None or isinstance(self._w2.scale,
|
||||
PrecisionConfig)
|
||||
assert self._w2.scale is None or isinstance(self._w2.scale, PrecisionConfig)
|
||||
return self._w2.scale
|
||||
|
||||
@property
|
||||
@@ -285,19 +282,19 @@ class FusedMoEQuantConfig:
|
||||
|
||||
@property
|
||||
def use_int8_w8a16(self) -> bool:
|
||||
return (self._a1.dtype is None and self._w1.dtype == torch.int8)
|
||||
return self._a1.dtype is None and self._w1.dtype == torch.int8
|
||||
|
||||
@property
|
||||
def use_int4_w4a16(self) -> bool:
|
||||
return (self._a1.dtype is None and self._w1.dtype == "int4")
|
||||
return self._a1.dtype is None and self._w1.dtype == "int4"
|
||||
|
||||
@property
|
||||
def use_mxfp4_w4a4(self) -> bool:
|
||||
return (self._a1.dtype == "mxfp4" and self._w1.dtype == "mxfp4")
|
||||
return self._a1.dtype == "mxfp4" and self._w1.dtype == "mxfp4"
|
||||
|
||||
@property
|
||||
def use_mxfp4_w4a16(self) -> bool:
|
||||
return (self._a1.dtype is None and self._w1.dtype == "mxfp4")
|
||||
return self._a1.dtype is None and self._w1.dtype == "mxfp4"
|
||||
|
||||
@property
|
||||
def use_nvfp4_w4a4(self) -> bool:
|
||||
@@ -398,19 +395,23 @@ class FusedMoEQuantConfig:
|
||||
- w1_zp: Optional w1 zero points for int4/int8 quantization.
|
||||
- w2_zp: Optional w2 zero points for int4/int8 quantization.
|
||||
"""
|
||||
assert (not isinstance(quant_dtype, str) or quant_dtype == "nvfp4"
|
||||
or quant_dtype == "mxfp4")
|
||||
a_shape, w_shape = _quant_flags_to_group_shape(quant_dtype,
|
||||
per_act_token_quant,
|
||||
per_out_ch_quant,
|
||||
block_shape)
|
||||
assert (
|
||||
not isinstance(quant_dtype, str)
|
||||
or quant_dtype == "nvfp4"
|
||||
or quant_dtype == "mxfp4"
|
||||
)
|
||||
a_shape, w_shape = _quant_flags_to_group_shape(
|
||||
quant_dtype, per_act_token_quant, per_out_ch_quant, block_shape
|
||||
)
|
||||
quant_config = FusedMoEQuantConfig(
|
||||
_a1=FusedMoEQuantDesc(quant_dtype, a_shape, a1_scale, a1_gscale),
|
||||
_a2=FusedMoEQuantDesc(quant_dtype, a_shape, a2_scale, a2_gscale),
|
||||
_w1=FusedMoEQuantDesc(quant_dtype, w_shape, w1_scale, g1_alphas,
|
||||
w1_zp, w1_bias),
|
||||
_w2=FusedMoEQuantDesc(quant_dtype, w_shape, w2_scale, g2_alphas,
|
||||
w2_zp, w2_bias),
|
||||
_w1=FusedMoEQuantDesc(
|
||||
quant_dtype, w_shape, w1_scale, g1_alphas, w1_zp, w1_bias
|
||||
),
|
||||
_w2=FusedMoEQuantDesc(
|
||||
quant_dtype, w_shape, w2_scale, g2_alphas, w2_zp, w2_bias
|
||||
),
|
||||
)
|
||||
assert quant_config.per_act_token_quant == per_act_token_quant
|
||||
assert quant_config.per_out_ch_quant == per_out_ch_quant
|
||||
@@ -430,14 +431,16 @@ def fp8_w8a8_moe_quant_config(
|
||||
"""
|
||||
Construct a quant config for fp8 activations and fp8 weights.
|
||||
"""
|
||||
return FusedMoEQuantConfig.make(torch.float8_e4m3fn,
|
||||
w1_scale=w1_scale,
|
||||
w2_scale=w2_scale,
|
||||
a1_scale=a1_scale,
|
||||
a2_scale=a2_scale,
|
||||
per_act_token_quant=per_act_token_quant,
|
||||
per_out_ch_quant=per_out_ch_quant,
|
||||
block_shape=block_shape)
|
||||
return FusedMoEQuantConfig.make(
|
||||
torch.float8_e4m3fn,
|
||||
w1_scale=w1_scale,
|
||||
w2_scale=w2_scale,
|
||||
a1_scale=a1_scale,
|
||||
a2_scale=a2_scale,
|
||||
per_act_token_quant=per_act_token_quant,
|
||||
per_out_ch_quant=per_out_ch_quant,
|
||||
block_shape=block_shape,
|
||||
)
|
||||
|
||||
|
||||
def int8_w8a8_moe_quant_config(
|
||||
@@ -463,10 +466,11 @@ def int8_w8a8_moe_quant_config(
|
||||
|
||||
|
||||
def mxfp4_w4a16_moe_quant_config(
|
||||
w1_scale: Union[torch.Tensor, "PrecisionConfig"],
|
||||
w2_scale: Union[torch.Tensor, "PrecisionConfig"],
|
||||
w1_bias: Optional[torch.Tensor] = None,
|
||||
w2_bias: Optional[torch.Tensor] = None) -> FusedMoEQuantConfig:
|
||||
w1_scale: Union[torch.Tensor, "PrecisionConfig"],
|
||||
w2_scale: Union[torch.Tensor, "PrecisionConfig"],
|
||||
w1_bias: Optional[torch.Tensor] = None,
|
||||
w2_bias: Optional[torch.Tensor] = None,
|
||||
) -> FusedMoEQuantConfig:
|
||||
"""
|
||||
Construct a quant config for unquantized activations and mxfp4 weights.
|
||||
"""
|
||||
@@ -605,22 +609,26 @@ class FusedMoEParallelConfig:
|
||||
|
||||
@property
|
||||
def use_pplx_kernels(self):
|
||||
return (self.use_all2all_kernels
|
||||
and envs.VLLM_ALL2ALL_BACKEND == "pplx")
|
||||
return self.use_all2all_kernels and envs.VLLM_ALL2ALL_BACKEND == "pplx"
|
||||
|
||||
@property
|
||||
def use_deepep_ht_kernels(self):
|
||||
return (self.use_all2all_kernels
|
||||
and envs.VLLM_ALL2ALL_BACKEND == "deepep_high_throughput")
|
||||
return (
|
||||
self.use_all2all_kernels
|
||||
and envs.VLLM_ALL2ALL_BACKEND == "deepep_high_throughput"
|
||||
)
|
||||
|
||||
@property
|
||||
def use_deepep_ll_kernels(self):
|
||||
return (self.use_all2all_kernels
|
||||
and envs.VLLM_ALL2ALL_BACKEND == "deepep_low_latency")
|
||||
return (
|
||||
self.use_all2all_kernels
|
||||
and envs.VLLM_ALL2ALL_BACKEND == "deepep_low_latency"
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def make(tp_size_: int, dp_size_: int,
|
||||
vllm_parallel_config: ParallelConfig) -> "FusedMoEParallelConfig":
|
||||
def make(
|
||||
tp_size_: int, dp_size_: int, vllm_parallel_config: ParallelConfig
|
||||
) -> "FusedMoEParallelConfig":
|
||||
"""
|
||||
Determine MoE parallel configuration. Based on the input `tp_size_`,
|
||||
`dp_size_` and vllm's parallel config, determine what
|
||||
@@ -700,34 +708,37 @@ class FusedMoEParallelConfig:
|
||||
tp_rank = dp_rank * tp_size_ + tp_rank
|
||||
return tp_size, tp_rank
|
||||
|
||||
use_ep = (dp_size_ * tp_size_ > 1
|
||||
and vllm_parallel_config.enable_expert_parallel)
|
||||
use_ep = dp_size_ * tp_size_ > 1 and vllm_parallel_config.enable_expert_parallel
|
||||
|
||||
dp_size = dp_size_
|
||||
dp_rank = get_dp_group().rank_in_group if dp_size > 1 else 0
|
||||
tp_size, tp_rank = flatten_tp_across_dp(dp_rank)
|
||||
|
||||
if not use_ep:
|
||||
return FusedMoEParallelConfig(tp_size=tp_size,
|
||||
tp_rank=tp_rank,
|
||||
dp_size=dp_size,
|
||||
dp_rank=dp_rank,
|
||||
ep_size=1,
|
||||
ep_rank=0,
|
||||
use_ep=False)
|
||||
return FusedMoEParallelConfig(
|
||||
tp_size=tp_size,
|
||||
tp_rank=tp_rank,
|
||||
dp_size=dp_size,
|
||||
dp_rank=dp_rank,
|
||||
ep_size=1,
|
||||
ep_rank=0,
|
||||
use_ep=False,
|
||||
)
|
||||
# DP + EP / TP + EP / DP + TP + EP
|
||||
assert use_ep
|
||||
# In EP, each device owns a set of experts fully. There is no tensor
|
||||
# parallel update tp_size, tp_rank, ep_size and ep_rank to reflect that.
|
||||
ep_size = tp_size
|
||||
ep_rank = tp_rank
|
||||
return FusedMoEParallelConfig(tp_size=1,
|
||||
tp_rank=0,
|
||||
dp_size=dp_size,
|
||||
dp_rank=dp_rank,
|
||||
ep_size=ep_size,
|
||||
ep_rank=ep_rank,
|
||||
use_ep=True)
|
||||
return FusedMoEParallelConfig(
|
||||
tp_size=1,
|
||||
tp_rank=0,
|
||||
dp_size=dp_size,
|
||||
dp_rank=dp_rank,
|
||||
ep_size=ep_size,
|
||||
ep_rank=ep_rank,
|
||||
use_ep=True,
|
||||
)
|
||||
|
||||
|
||||
# Adapted from pplx-kernels tests/all_to_all_utils.py
|
||||
@@ -749,8 +760,9 @@ class FusedMoEConfig:
|
||||
|
||||
def __post_init__(self):
|
||||
if self.dp_size > 1:
|
||||
logger.debug_once("Using FusedMoEConfig::max_num_tokens=%d",
|
||||
self.max_num_tokens)
|
||||
logger.debug_once(
|
||||
"Using FusedMoEConfig::max_num_tokens=%d", self.max_num_tokens
|
||||
)
|
||||
|
||||
assert self.max_num_tokens > 0
|
||||
|
||||
@@ -799,6 +811,8 @@ class FusedMoEConfig:
|
||||
"""
|
||||
Whether to use FlashInfer cutlass kernels for NVFP4 MoE.
|
||||
"""
|
||||
return (envs.VLLM_USE_FLASHINFER_MOE_FP4
|
||||
and has_flashinfer_cutlass_fused_moe()
|
||||
and envs.VLLM_FLASHINFER_MOE_BACKEND == "throughput")
|
||||
return (
|
||||
envs.VLLM_USE_FLASHINFER_MOE_FP4
|
||||
and has_flashinfer_cutlass_fused_moe()
|
||||
and envs.VLLM_FLASHINFER_MOE_BACKEND == "throughput"
|
||||
)
|
||||
|
||||
@@ -22,10 +22,9 @@ def grouped_topk(
|
||||
topk_group: int = 0,
|
||||
scoring_func: str = "softmax",
|
||||
routed_scaling_factor: float = 1.0,
|
||||
e_score_correction_bias: Optional[torch.Tensor] = None
|
||||
e_score_correction_bias: Optional[torch.Tensor] = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
assert hidden_states.shape[0] == gating_output.shape[0], (
|
||||
"Number of tokens mismatch")
|
||||
assert hidden_states.shape[0] == gating_output.shape[0], "Number of tokens mismatch"
|
||||
|
||||
gating_output = gating_output.float()
|
||||
if scoring_func == "softmax":
|
||||
@@ -39,29 +38,30 @@ def grouped_topk(
|
||||
if e_score_correction_bias is not None:
|
||||
original_scores = scores
|
||||
scores = scores + e_score_correction_bias.unsqueeze(0)
|
||||
group_scores = (scores.view(num_token, num_expert_group,
|
||||
-1).topk(2, dim=-1)[0].sum(dim=-1))
|
||||
group_scores = (
|
||||
scores.view(num_token, num_expert_group, -1).topk(2, dim=-1)[0].sum(dim=-1)
|
||||
)
|
||||
else:
|
||||
group_scores = scores.view(num_token, num_expert_group,
|
||||
-1).max(dim=-1).values # [n, n_group]
|
||||
group_idx = torch.topk(group_scores, k=topk_group, dim=-1,
|
||||
sorted=False)[1] # [n, top_k_group]
|
||||
group_scores = (
|
||||
scores.view(num_token, num_expert_group, -1).max(dim=-1).values
|
||||
) # [n, n_group]
|
||||
group_idx = torch.topk(group_scores, k=topk_group, dim=-1, sorted=False)[
|
||||
1
|
||||
] # [n, top_k_group]
|
||||
group_mask = torch.zeros_like(group_scores) # [n, n_group]
|
||||
group_mask.scatter_(1, group_idx, 1) # [n, n_group]
|
||||
score_mask = group_mask.unsqueeze(-1).expand(
|
||||
num_token, num_expert_group,
|
||||
scores.shape[-1] // num_expert_group).reshape(num_token, -1) # [n, e]
|
||||
tmp_scores = scores.masked_fill(~score_mask.bool(),
|
||||
float("-inf")) # [n, e]
|
||||
score_mask = (
|
||||
group_mask.unsqueeze(-1)
|
||||
.expand(num_token, num_expert_group, scores.shape[-1] // num_expert_group)
|
||||
.reshape(num_token, -1)
|
||||
) # [n, e]
|
||||
tmp_scores = scores.masked_fill(~score_mask.bool(), float("-inf")) # [n, e]
|
||||
|
||||
if e_score_correction_bias is not None:
|
||||
topk_ids = torch.topk(tmp_scores, k=topk, dim=-1, sorted=False)[1]
|
||||
topk_weights = original_scores.gather(1, topk_ids)
|
||||
else:
|
||||
topk_weights, topk_ids = torch.topk(tmp_scores,
|
||||
k=topk,
|
||||
dim=-1,
|
||||
sorted=False)
|
||||
topk_weights, topk_ids = torch.topk(tmp_scores, k=topk, dim=-1, sorted=False)
|
||||
|
||||
if renormalize:
|
||||
topk_weights = topk_weights / topk_weights.sum(dim=-1, keepdim=True)
|
||||
@@ -87,21 +87,22 @@ def select_experts(
|
||||
if use_grouped_topk:
|
||||
assert topk_group is not None
|
||||
assert num_expert_group is not None
|
||||
return grouped_topk(hidden_states=hidden_states,
|
||||
gating_output=router_logits,
|
||||
topk=top_k,
|
||||
renormalize=renormalize,
|
||||
num_expert_group=num_expert_group,
|
||||
topk_group=topk_group,
|
||||
scoring_func=scoring_func,
|
||||
routed_scaling_factor=routed_scaling_factor,
|
||||
e_score_correction_bias=e_score_correction_bias)
|
||||
return grouped_topk(
|
||||
hidden_states=hidden_states,
|
||||
gating_output=router_logits,
|
||||
topk=top_k,
|
||||
renormalize=renormalize,
|
||||
num_expert_group=num_expert_group,
|
||||
topk_group=topk_group,
|
||||
scoring_func=scoring_func,
|
||||
routed_scaling_factor=routed_scaling_factor,
|
||||
e_score_correction_bias=e_score_correction_bias,
|
||||
)
|
||||
elif custom_routing_function is None:
|
||||
assert scoring_func == "softmax"
|
||||
topk_logit_vals, topk_idx = torch.topk(router_logits,
|
||||
k=top_k,
|
||||
dim=-1,
|
||||
sorted=False)
|
||||
topk_logit_vals, topk_idx = torch.topk(
|
||||
router_logits, k=top_k, dim=-1, sorted=False
|
||||
)
|
||||
if renormalize:
|
||||
topk_vals = torch.softmax(topk_logit_vals, dim=-1)
|
||||
else:
|
||||
@@ -109,16 +110,18 @@ def select_experts(
|
||||
topk_vals = (topk_logit_vals - logZ).exp()
|
||||
return topk_vals.to(torch.float32), topk_idx.to(torch.int32)
|
||||
else:
|
||||
return custom_routing_function(hidden_states=hidden_states,
|
||||
gating_output=router_logits,
|
||||
topk=top_k,
|
||||
renormalize=renormalize)
|
||||
return custom_routing_function(
|
||||
hidden_states=hidden_states,
|
||||
gating_output=router_logits,
|
||||
topk=top_k,
|
||||
renormalize=renormalize,
|
||||
)
|
||||
|
||||
|
||||
class IPEXFusedMOE:
|
||||
|
||||
def __init__(self, layer: torch.nn.Module) -> None:
|
||||
import intel_extension_for_pytorch as ipex
|
||||
|
||||
layer.ipex_fusion = ipex.llm.modules.GatedMLPMOE(
|
||||
layer.w13_weight,
|
||||
layer.w2_weight,
|
||||
@@ -146,8 +149,9 @@ class IPEXFusedMOE:
|
||||
) -> torch.Tensor:
|
||||
assert activation == "silu", f"{activation} is not supported."
|
||||
assert not apply_router_weight_on_input
|
||||
assert routed_scaling_factor == 1.0, \
|
||||
assert routed_scaling_factor == 1.0, (
|
||||
f"routed_scaling_factor {routed_scaling_factor} is not supported."
|
||||
)
|
||||
return layer.ipex_fusion(
|
||||
x,
|
||||
use_grouped_topk,
|
||||
@@ -163,7 +167,6 @@ class IPEXFusedMOE:
|
||||
|
||||
|
||||
class SGLFusedMOE:
|
||||
|
||||
def __init__(self, layer: torch.nn.Module) -> None:
|
||||
pass
|
||||
|
||||
@@ -222,7 +225,6 @@ class SGLFusedMOE:
|
||||
|
||||
|
||||
class CPUFusedMOE:
|
||||
|
||||
def __init__(self, layer: torch.nn.Module) -> None:
|
||||
pass
|
||||
|
||||
@@ -289,12 +291,15 @@ class CPUFusedMOE:
|
||||
outputs.append(expert_out)
|
||||
start_idx = end_idx
|
||||
|
||||
outs = torch.cat(outputs,
|
||||
dim=0) if len(outputs) else sorted_tokens.new_empty(0)
|
||||
outs = torch.cat(outputs, dim=0) if len(outputs) else sorted_tokens.new_empty(0)
|
||||
new_x = torch.empty_like(outs)
|
||||
|
||||
new_x[idxs] = outs
|
||||
final_out = (new_x.view(
|
||||
*topk_ids.shape, -1).type(topk_weights.dtype).mul_(
|
||||
topk_weights.unsqueeze(dim=-1)).sum(dim=1).type(new_x.dtype))
|
||||
final_out = (
|
||||
new_x.view(*topk_ids.shape, -1)
|
||||
.type(topk_weights.dtype)
|
||||
.mul_(topk_weights.unsqueeze(dim=-1))
|
||||
.sum(dim=1)
|
||||
.type(new_x.dtype)
|
||||
)
|
||||
return final_out
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
""" CUTLASS based Fused MoE kernels."""
|
||||
"""CUTLASS based Fused MoE kernels."""
|
||||
|
||||
from typing import Callable, Optional
|
||||
|
||||
import torch
|
||||
@@ -10,13 +11,17 @@ from vllm import _custom_ops as ops
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.fused_moe.config import FusedMoEQuantConfig
|
||||
from vllm.model_executor.layers.fused_moe.moe_permute_unpermute import (
|
||||
moe_permute, moe_unpermute)
|
||||
moe_permute,
|
||||
moe_unpermute,
|
||||
)
|
||||
from vllm.model_executor.layers.fused_moe.prepare_finalize import (
|
||||
MoEPrepareAndFinalizeNoEP)
|
||||
MoEPrepareAndFinalizeNoEP,
|
||||
)
|
||||
from vllm.model_executor.layers.fused_moe.topk_weight_and_reduce import (
|
||||
TopKWeightAndReduceDelegate, TopKWeightAndReduceNoOP)
|
||||
from vllm.model_executor.layers.fused_moe.utils import (_fp8_quantize,
|
||||
_resize_cache)
|
||||
TopKWeightAndReduceDelegate,
|
||||
TopKWeightAndReduceNoOP,
|
||||
)
|
||||
from vllm.model_executor.layers.fused_moe.utils import _fp8_quantize, _resize_cache
|
||||
from vllm.scalar_type import scalar_types
|
||||
|
||||
logger = init_logger(__name__)
|
||||
@@ -56,20 +61,28 @@ def run_cutlass_moe_fp8(
|
||||
assert w2.dtype == torch.float8_e4m3fn
|
||||
assert a1q.size(-1) == w1.size(2), "Hidden size mismatch w1"
|
||||
assert w1.size(1) == w2.size(2) * 2, "Hidden size mismatch w2"
|
||||
assert w1_scale.dim() == 1 or w1_scale.size(
|
||||
1) == 1 or w1_scale.shape[1] == w1.size(1), "W1 scale shape mismatch"
|
||||
assert w2_scale.dim() == 1 or w2_scale.size(
|
||||
1) == 1 or w2_scale.shape[1] == w2.size(1), "W2 scale shape mismatch"
|
||||
assert (
|
||||
w1_scale.dim() == 1 or w1_scale.size(1) == 1 or w1_scale.shape[1] == w1.size(1)
|
||||
), "W1 scale shape mismatch"
|
||||
assert (
|
||||
w2_scale.dim() == 1 or w2_scale.size(1) == 1 or w2_scale.shape[1] == w2.size(1)
|
||||
), "W2 scale shape mismatch"
|
||||
assert w1.size(0) == w2.size(0), "Expert number mismatch"
|
||||
assert a1q_scale is None or a1q_scale.dim() == 0 or a1q_scale.size(
|
||||
0) == 1 or a1q_scale.size(
|
||||
0) == a1q.shape[0], "Input scale shape mismatch"
|
||||
assert (
|
||||
a1q_scale is None
|
||||
or a1q_scale.dim() == 0
|
||||
or a1q_scale.size(0) == 1
|
||||
or a1q_scale.size(0) == a1q.shape[0]
|
||||
), "Input scale shape mismatch"
|
||||
assert w1.size(0) == w2.size(0), "Weights expert number mismatch"
|
||||
assert w1.size(0) == w1_scale.size(0), "w1 scales expert number mismatch"
|
||||
assert w1.size(0) == w2_scale.size(0), "w2 scales expert number mismatch"
|
||||
assert a2_scale is None or a2_scale.dim() == 0 or a2_scale.size(
|
||||
0) == 1 or a2_scale.size(
|
||||
0) == a1q.shape[0], "Intermediate scale shape mismatch"
|
||||
assert (
|
||||
a2_scale is None
|
||||
or a2_scale.dim() == 0
|
||||
or a2_scale.size(0) == 1
|
||||
or a2_scale.size(0) == a1q.shape[0]
|
||||
), "Intermediate scale shape mismatch"
|
||||
assert out_dtype in [torch.half, torch.bfloat16], "Invalid output dtype"
|
||||
if expert_map is not None:
|
||||
assert expert_num_tokens is None
|
||||
@@ -97,8 +110,9 @@ def run_cutlass_moe_fp8(
|
||||
|
||||
if expert_map is not None:
|
||||
"Translate info from expert_map to topk_ids"
|
||||
local_topk_ids = torch.where(expert_map[topk_ids] != -1,
|
||||
expert_map[topk_ids], -1)
|
||||
local_topk_ids = torch.where(
|
||||
expert_map[topk_ids] != -1, expert_map[topk_ids], -1
|
||||
)
|
||||
else:
|
||||
local_topk_ids = topk_ids
|
||||
|
||||
@@ -108,35 +122,39 @@ def run_cutlass_moe_fp8(
|
||||
if use_batched_format:
|
||||
mm1_out = _resize_cache(workspace13, (local_E * padded_M, N * 2))
|
||||
act_out = _resize_cache(workspace2, (local_E * padded_M, N))
|
||||
quant_out = _resize_cache(workspace13.view(dtype=torch.float8_e4m3fn),
|
||||
(local_E * padded_M, N))
|
||||
quant_out = _resize_cache(
|
||||
workspace13.view(dtype=torch.float8_e4m3fn), (local_E * padded_M, N)
|
||||
)
|
||||
mm2_out = _resize_cache(workspace2, (local_E * padded_M, K))
|
||||
else:
|
||||
a1q_perm = _resize_cache(workspace2.view(dtype=torch.float8_e4m3fn),
|
||||
(M * topk, K))
|
||||
a1q_perm = _resize_cache(
|
||||
workspace2.view(dtype=torch.float8_e4m3fn), (M * topk, K)
|
||||
)
|
||||
mm1_out = _resize_cache(workspace13, (M * topk, N * 2))
|
||||
act_out = _resize_cache(workspace2, (M * topk, N))
|
||||
# original workspace are based on input hidden_states dtype (bf16)
|
||||
quant_out = _resize_cache(workspace13.view(dtype=torch.float8_e4m3fn),
|
||||
(M * topk, N))
|
||||
quant_out = _resize_cache(
|
||||
workspace13.view(dtype=torch.float8_e4m3fn), (M * topk, N)
|
||||
)
|
||||
mm2_out = _resize_cache(workspace2, (M * topk, K))
|
||||
|
||||
if use_batched_format:
|
||||
assert expert_num_tokens is not None
|
||||
|
||||
expert_offsets = torch.empty((local_E),
|
||||
dtype=torch.int32,
|
||||
device=device)
|
||||
problem_sizes1 = torch.empty((local_E, 3),
|
||||
dtype=torch.int32,
|
||||
device=device)
|
||||
problem_sizes2 = torch.empty((local_E, 3),
|
||||
dtype=torch.int32,
|
||||
device=device)
|
||||
expert_offsets = torch.empty((local_E), dtype=torch.int32, device=device)
|
||||
problem_sizes1 = torch.empty((local_E, 3), dtype=torch.int32, device=device)
|
||||
problem_sizes2 = torch.empty((local_E, 3), dtype=torch.int32, device=device)
|
||||
|
||||
ops.get_cutlass_pplx_moe_mm_data(expert_offsets, problem_sizes1,
|
||||
problem_sizes2, expert_num_tokens,
|
||||
local_E, padded_M, N, K)
|
||||
ops.get_cutlass_pplx_moe_mm_data(
|
||||
expert_offsets,
|
||||
problem_sizes1,
|
||||
problem_sizes2,
|
||||
expert_num_tokens,
|
||||
local_E,
|
||||
padded_M,
|
||||
N,
|
||||
K,
|
||||
)
|
||||
|
||||
w1_scale = w1_scale.reshape(w1_scale.size(0), -1)
|
||||
w2_scale = w2_scale.reshape(w2_scale.size(0), -1)
|
||||
@@ -146,15 +164,14 @@ def run_cutlass_moe_fp8(
|
||||
# during offset calculations
|
||||
expert_offsets = expert_offsets.to(torch.int64)
|
||||
else:
|
||||
problem_sizes1 = torch.empty((global_num_experts, 3),
|
||||
dtype=torch.int32,
|
||||
device=device)
|
||||
problem_sizes2 = torch.empty((global_num_experts, 3),
|
||||
dtype=torch.int32,
|
||||
device=device)
|
||||
problem_sizes1 = torch.empty(
|
||||
(global_num_experts, 3), dtype=torch.int32, device=device
|
||||
)
|
||||
problem_sizes2 = torch.empty(
|
||||
(global_num_experts, 3), dtype=torch.int32, device=device
|
||||
)
|
||||
|
||||
num_expert = global_num_experts if expert_map is None \
|
||||
else expert_map.size(0)
|
||||
num_expert = global_num_experts if expert_map is None else expert_map.size(0)
|
||||
# permuted a1q reuses workspace2
|
||||
a1q, a1q_scale, expert_offsets, inv_perm, _ = moe_permute(
|
||||
a1q,
|
||||
@@ -163,12 +180,13 @@ def run_cutlass_moe_fp8(
|
||||
num_expert,
|
||||
local_E,
|
||||
expert_map,
|
||||
permuted_hidden_states=a1q_perm)
|
||||
permuted_hidden_states=a1q_perm,
|
||||
)
|
||||
expert_offsets = expert_offsets[:-1]
|
||||
|
||||
ops.get_cutlass_moe_mm_problem_sizes(local_topk_ids, problem_sizes1,
|
||||
problem_sizes2,
|
||||
global_num_experts, N, K)
|
||||
ops.get_cutlass_moe_mm_problem_sizes(
|
||||
local_topk_ids, problem_sizes1, problem_sizes2, global_num_experts, N, K
|
||||
)
|
||||
|
||||
if not per_act_token and (expert_map is not None or use_batched_format):
|
||||
# this is necessary to avoid imprecise scale calculation caused by
|
||||
@@ -176,38 +194,59 @@ def run_cutlass_moe_fp8(
|
||||
# this rank handles only partial tokens, or when it is batched .
|
||||
mm1_out.fill_(0)
|
||||
|
||||
ops.cutlass_moe_mm(mm1_out, a1q, w1, a1q_scale, w1_scale, expert_offsets,
|
||||
problem_sizes1, ab_strides1, ab_strides1, c_strides1,
|
||||
per_act_token, per_out_ch)
|
||||
ops.cutlass_moe_mm(
|
||||
mm1_out,
|
||||
a1q,
|
||||
w1,
|
||||
a1q_scale,
|
||||
w1_scale,
|
||||
expert_offsets,
|
||||
problem_sizes1,
|
||||
ab_strides1,
|
||||
ab_strides1,
|
||||
c_strides1,
|
||||
per_act_token,
|
||||
per_out_ch,
|
||||
)
|
||||
|
||||
activation_callable(act_out, mm1_out)
|
||||
|
||||
a2q, a2q_scale = ops.scaled_fp8_quant(
|
||||
act_out,
|
||||
a2_scale,
|
||||
use_per_token_if_dynamic=per_act_token,
|
||||
output=quant_out)
|
||||
act_out, a2_scale, use_per_token_if_dynamic=per_act_token, output=quant_out
|
||||
)
|
||||
|
||||
if expert_map is not None:
|
||||
mm2_out.fill_(0)
|
||||
|
||||
ops.cutlass_moe_mm(mm2_out, a2q, w2, a2q_scale, w2_scale, expert_offsets,
|
||||
problem_sizes2, ab_strides2, ab_strides2, c_strides2,
|
||||
per_act_token, per_out_ch)
|
||||
ops.cutlass_moe_mm(
|
||||
mm2_out,
|
||||
a2q,
|
||||
w2,
|
||||
a2q_scale,
|
||||
w2_scale,
|
||||
expert_offsets,
|
||||
problem_sizes2,
|
||||
ab_strides2,
|
||||
ab_strides2,
|
||||
c_strides2,
|
||||
per_act_token,
|
||||
per_out_ch,
|
||||
)
|
||||
|
||||
if use_batched_format:
|
||||
output.copy_(mm2_out.reshape(local_E, padded_M, K), non_blocking=True)
|
||||
else:
|
||||
# for non-chunking mode the output is resized from workspace13
|
||||
# so we need to make sure mm2_out uses workspace2.
|
||||
moe_unpermute(out=output,
|
||||
permuted_hidden_states=mm2_out,
|
||||
topk_weights=topk_weights,
|
||||
inv_permuted_idx=inv_perm)
|
||||
moe_unpermute(
|
||||
out=output,
|
||||
permuted_hidden_states=mm2_out,
|
||||
topk_weights=topk_weights,
|
||||
inv_permuted_idx=inv_perm,
|
||||
)
|
||||
|
||||
|
||||
class CutlassExpertsFp8Base(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
out_dtype: Optional[torch.dtype],
|
||||
@@ -256,23 +295,40 @@ class CutlassExpertsFp8Base(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
|
||||
activation_callable = lambda o, i: self.activation(activation, o, i)
|
||||
|
||||
use_batched_format = self.activation_formats[
|
||||
0] == mk.FusedMoEActivationFormat.BatchedExperts
|
||||
use_batched_format = (
|
||||
self.activation_formats[0] == mk.FusedMoEActivationFormat.BatchedExperts
|
||||
)
|
||||
|
||||
in_dtype = hidden_states.dtype
|
||||
run_cutlass_moe_fp8(
|
||||
output, hidden_states, w1, w2, topk_ids, activation_callable,
|
||||
global_num_experts, expert_map, self.w1_scale, self.w2_scale,
|
||||
a1q_scale, a2_scale, self.ab_strides1, self.ab_strides2,
|
||||
self.c_strides1, self.c_strides2, workspace13, workspace2,
|
||||
output,
|
||||
hidden_states,
|
||||
w1,
|
||||
w2,
|
||||
topk_ids,
|
||||
activation_callable,
|
||||
global_num_experts,
|
||||
expert_map,
|
||||
self.w1_scale,
|
||||
self.w2_scale,
|
||||
a1q_scale,
|
||||
a2_scale,
|
||||
self.ab_strides1,
|
||||
self.ab_strides2,
|
||||
self.c_strides1,
|
||||
self.c_strides2,
|
||||
workspace13,
|
||||
workspace2,
|
||||
expert_num_tokens,
|
||||
self.out_dtype if self.out_dtype is not None else in_dtype,
|
||||
self.per_act_token_quant, self.per_out_ch_quant,
|
||||
use_batched_format, topk_weights)
|
||||
self.per_act_token_quant,
|
||||
self.per_out_ch_quant,
|
||||
use_batched_format,
|
||||
topk_weights,
|
||||
)
|
||||
|
||||
|
||||
class CutlassExpertsFp8(CutlassExpertsFp8Base):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
out_dtype: Optional[torch.dtype],
|
||||
@@ -293,10 +349,12 @@ class CutlassExpertsFp8(CutlassExpertsFp8Base):
|
||||
|
||||
@property
|
||||
def activation_formats(
|
||||
self
|
||||
self,
|
||||
) -> tuple[mk.FusedMoEActivationFormat, mk.FusedMoEActivationFormat]:
|
||||
return (mk.FusedMoEActivationFormat.Standard,
|
||||
mk.FusedMoEActivationFormat.Standard)
|
||||
return (
|
||||
mk.FusedMoEActivationFormat.Standard,
|
||||
mk.FusedMoEActivationFormat.Standard,
|
||||
)
|
||||
|
||||
def supports_chunking(self) -> bool:
|
||||
return True
|
||||
@@ -323,12 +381,15 @@ class CutlassExpertsFp8(CutlassExpertsFp8Base):
|
||||
workspace1 = (M * topk, max(N, K))
|
||||
workspace2 = (M * topk, max(N // 2, K))
|
||||
output = (M, K)
|
||||
return (workspace1, workspace2, output,
|
||||
self.out_dtype if self.out_dtype is not None else a.dtype)
|
||||
return (
|
||||
workspace1,
|
||||
workspace2,
|
||||
output,
|
||||
self.out_dtype if self.out_dtype is not None else a.dtype,
|
||||
)
|
||||
|
||||
|
||||
class CutlassBatchedExpertsFp8(CutlassExpertsFp8Base):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
max_experts_per_worker: int,
|
||||
@@ -354,10 +415,12 @@ class CutlassBatchedExpertsFp8(CutlassExpertsFp8Base):
|
||||
|
||||
@property
|
||||
def activation_formats(
|
||||
self
|
||||
self,
|
||||
) -> tuple[mk.FusedMoEActivationFormat, mk.FusedMoEActivationFormat]:
|
||||
return (mk.FusedMoEActivationFormat.BatchedExperts,
|
||||
mk.FusedMoEActivationFormat.BatchedExperts)
|
||||
return (
|
||||
mk.FusedMoEActivationFormat.BatchedExperts,
|
||||
mk.FusedMoEActivationFormat.BatchedExperts,
|
||||
)
|
||||
|
||||
def supports_chunking(self) -> bool:
|
||||
return False
|
||||
@@ -381,13 +444,15 @@ class CutlassBatchedExpertsFp8(CutlassExpertsFp8Base):
|
||||
padded_M = aq.size(1)
|
||||
num_dp = self.num_dispatchers
|
||||
assert num_dp is not None
|
||||
workspace1 = (self.max_experts_per_worker, padded_M * num_dp,
|
||||
max(N, K))
|
||||
workspace2 = (self.max_experts_per_worker, padded_M * num_dp,
|
||||
max(N // 2, K))
|
||||
workspace1 = (self.max_experts_per_worker, padded_M * num_dp, max(N, K))
|
||||
workspace2 = (self.max_experts_per_worker, padded_M * num_dp, max(N // 2, K))
|
||||
output = (self.max_experts_per_worker, padded_M, K)
|
||||
return (workspace1, workspace2, output,
|
||||
self.out_dtype if self.out_dtype is not None else a.dtype)
|
||||
return (
|
||||
workspace1,
|
||||
workspace2,
|
||||
output,
|
||||
self.out_dtype if self.out_dtype is not None else a.dtype,
|
||||
)
|
||||
|
||||
|
||||
def cutlass_moe_fp8(
|
||||
@@ -456,18 +521,15 @@ def cutlass_moe_fp8(
|
||||
assert quant_config is not None
|
||||
|
||||
if quant_config.a1_scale is not None:
|
||||
assert (quant_config.per_act_token_quant ==
|
||||
quant_config.a1_scale.numel() != 1)
|
||||
assert quant_config.per_act_token_quant == quant_config.a1_scale.numel() != 1
|
||||
if quant_config.a2_scale is not None:
|
||||
assert (quant_config.per_act_token_quant ==
|
||||
quant_config.a2_scale.numel() != 1)
|
||||
assert quant_config.per_act_token_quant == quant_config.a2_scale.numel() != 1
|
||||
|
||||
assert (quant_config.w1_scale is None
|
||||
or (quant_config.per_out_ch_quant == (quant_config.w1_scale.size(1)
|
||||
== w1_q.size(1))))
|
||||
assert quant_config.w1_scale is None or (
|
||||
quant_config.per_out_ch_quant == (quant_config.w1_scale.size(1) == w1_q.size(1))
|
||||
)
|
||||
|
||||
num_experts = global_num_experts if global_num_experts != -1 else w1_q.size(
|
||||
0)
|
||||
num_experts = global_num_experts if global_num_experts != -1 else w1_q.size(0)
|
||||
|
||||
fn = mk.FusedMoEModularKernel(
|
||||
MoEPrepareAndFinalizeNoEP(),
|
||||
@@ -550,25 +612,30 @@ def run_cutlass_moe_fp4(
|
||||
assert topk_weights.shape == topk_ids.shape, "topk shape mismatch"
|
||||
assert w1_fp4.dtype == torch.uint8, "weight 1 must be uint8"
|
||||
assert w2_fp4.dtype == torch.uint8, "weight 2 must be uint8"
|
||||
assert (w1_fp4.ndim == 3 and w2_fp4.ndim == 3 and w1_blockscale.ndim == 3
|
||||
and w2_blockscale.ndim
|
||||
== 3), ("All Weights must be of rank 3 for cutlass_moe_fp4")
|
||||
assert (
|
||||
w1_fp4.ndim == 3
|
||||
and w2_fp4.ndim == 3
|
||||
and w1_blockscale.ndim == 3
|
||||
and w2_blockscale.ndim == 3
|
||||
), "All Weights must be of rank 3 for cutlass_moe_fp4"
|
||||
m_a, k_a = a.shape
|
||||
e_w1, nx2_w1, half_k_w1 = w1_fp4.shape
|
||||
e_w2, k_w2, half_n_w2 = w2_fp4.shape
|
||||
|
||||
assert (e_w1 == e_w2
|
||||
and e_w1 == e), ("Number of experts must match",
|
||||
f" between weights. {e_w1}, {e_w2}, {e}")
|
||||
assert (k_a == half_k_w1 * 2
|
||||
and k == k_w2), ("Hidden size mismatch between a, w1 and w2")
|
||||
assert (nx2_w1 == n * 2 and half_n_w2 * 2 == n), ("mismatch in "
|
||||
"expected `n`")
|
||||
assert (m == m_a), "input shape mismatch"
|
||||
assert e_w1 == e_w2 and e_w1 == e, (
|
||||
"Number of experts must match",
|
||||
f" between weights. {e_w1}, {e_w2}, {e}",
|
||||
)
|
||||
assert k_a == half_k_w1 * 2 and k == k_w2, (
|
||||
"Hidden size mismatch between a, w1 and w2"
|
||||
)
|
||||
assert nx2_w1 == n * 2 and half_n_w2 * 2 == n, "mismatch in expected `n`"
|
||||
assert m == m_a, "input shape mismatch"
|
||||
assert 2 * half_k_w1 == k_w2, "Hidden size mismatch w2 and w1"
|
||||
assert a.dtype in [torch.half, torch.bfloat16], "Invalid input dtype"
|
||||
assert (topk_weights.size(0) == m and topk_ids.size(0)
|
||||
== m), ("topk must be provided for each row of a")
|
||||
assert topk_weights.size(0) == m and topk_ids.size(0) == m, (
|
||||
"topk must be provided for each row of a"
|
||||
)
|
||||
topk = topk_ids.size(1)
|
||||
out_dtype = a.dtype
|
||||
num_topk = topk_ids.size(1)
|
||||
@@ -585,15 +652,25 @@ def run_cutlass_moe_fp4(
|
||||
|
||||
if apply_router_weight_on_input:
|
||||
# TODO: this only works for topK=1, will need to update for topK>1
|
||||
assert num_topk == 1, \
|
||||
assert num_topk == 1, (
|
||||
"apply_router_weight_on_input is only implemented for topk=1"
|
||||
)
|
||||
a.mul_(topk_weights.to(out_dtype))
|
||||
|
||||
# problem shapes should have [m, n, k]
|
||||
# Note that problem sizes are based on logical number of elements.
|
||||
ops.get_cutlass_moe_mm_data(topk_ids, expert_offsets, problem_sizes1,
|
||||
problem_sizes2, a_map, c_map, e, n, k,
|
||||
blockscale_offsets)
|
||||
ops.get_cutlass_moe_mm_data(
|
||||
topk_ids,
|
||||
expert_offsets,
|
||||
problem_sizes1,
|
||||
problem_sizes2,
|
||||
a_map,
|
||||
c_map,
|
||||
e,
|
||||
n,
|
||||
k,
|
||||
blockscale_offsets,
|
||||
)
|
||||
|
||||
a = ops.shuffle_rows(a, a_map)
|
||||
rep_a_fp4, rep_a_blockscale = ops.scaled_fp4_experts_quant(
|
||||
@@ -606,17 +683,34 @@ def run_cutlass_moe_fp4(
|
||||
c1 = _resize_cache(workspace13, (m * topk, n * 2))
|
||||
c2 = _resize_cache(workspace2, (m * topk, n))
|
||||
c3 = _resize_cache(workspace13, (m * topk, k))
|
||||
ops.cutlass_fp4_moe_mm(c1, rep_a_fp4, w1_fp4, rep_a_blockscale,
|
||||
w1_blockscale, w1_alphas, problem_sizes1,
|
||||
expert_offsets[:-1], blockscale_offsets[:-1])
|
||||
ops.cutlass_fp4_moe_mm(
|
||||
c1,
|
||||
rep_a_fp4,
|
||||
w1_fp4,
|
||||
rep_a_blockscale,
|
||||
w1_blockscale,
|
||||
w1_alphas,
|
||||
problem_sizes1,
|
||||
expert_offsets[:-1],
|
||||
blockscale_offsets[:-1],
|
||||
)
|
||||
del rep_a_fp4, rep_a_blockscale
|
||||
torch.ops._C.silu_and_mul(c2, c1)
|
||||
int_fp4, int_blockscale = ops.scaled_fp4_experts_quant(
|
||||
c2, a2_gscale, expert_offsets, blockscale_offsets, num_topk)
|
||||
c2, a2_gscale, expert_offsets, blockscale_offsets, num_topk
|
||||
)
|
||||
|
||||
ops.cutlass_fp4_moe_mm(c3, int_fp4, w2_fp4, int_blockscale, w2_blockscale,
|
||||
w2_alphas, problem_sizes2, expert_offsets[:-1],
|
||||
blockscale_offsets[:-1])
|
||||
ops.cutlass_fp4_moe_mm(
|
||||
c3,
|
||||
int_fp4,
|
||||
w2_fp4,
|
||||
int_blockscale,
|
||||
w2_blockscale,
|
||||
w2_alphas,
|
||||
problem_sizes2,
|
||||
expert_offsets[:-1],
|
||||
blockscale_offsets[:-1],
|
||||
)
|
||||
del int_fp4, int_blockscale
|
||||
|
||||
c3 = ops.shuffle_rows(c3, c_map)
|
||||
@@ -624,9 +718,12 @@ def run_cutlass_moe_fp4(
|
||||
assert output.dtype == out_dtype
|
||||
if not apply_router_weight_on_input:
|
||||
output.copy_(
|
||||
(c3.view(m, num_topk, k) *
|
||||
topk_weights.view(m, num_topk, 1).to(out_dtype)).sum(dim=1),
|
||||
non_blocking=True)
|
||||
(
|
||||
c3.view(m, num_topk, k)
|
||||
* topk_weights.view(m, num_topk, 1).to(out_dtype)
|
||||
).sum(dim=1),
|
||||
non_blocking=True,
|
||||
)
|
||||
else:
|
||||
output.copy_(c3.view(m, num_topk, k).sum(dim=1), non_blocking=True)
|
||||
return
|
||||
@@ -634,7 +731,6 @@ def run_cutlass_moe_fp4(
|
||||
|
||||
# Split into batched and non-batched
|
||||
class CutlassExpertsFp4(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
max_experts_per_worker: int,
|
||||
@@ -649,14 +745,18 @@ class CutlassExpertsFp4(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
|
||||
@property
|
||||
def activation_formats(
|
||||
self
|
||||
self,
|
||||
) -> tuple[mk.FusedMoEActivationFormat, mk.FusedMoEActivationFormat]:
|
||||
if self.use_batched_format:
|
||||
return (mk.FusedMoEActivationFormat.BatchedExperts,
|
||||
mk.FusedMoEActivationFormat.BatchedExperts)
|
||||
return (
|
||||
mk.FusedMoEActivationFormat.BatchedExperts,
|
||||
mk.FusedMoEActivationFormat.BatchedExperts,
|
||||
)
|
||||
else:
|
||||
return (mk.FusedMoEActivationFormat.Standard,
|
||||
mk.FusedMoEActivationFormat.Standard)
|
||||
return (
|
||||
mk.FusedMoEActivationFormat.Standard,
|
||||
mk.FusedMoEActivationFormat.Standard,
|
||||
)
|
||||
|
||||
def supports_expert_map(self) -> bool:
|
||||
return False
|
||||
@@ -691,8 +791,12 @@ class CutlassExpertsFp4(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
workspace1 = (M * topk, max(2 * N, K))
|
||||
workspace2 = (M * topk, N)
|
||||
output = (M, K)
|
||||
return (workspace1, workspace2, output,
|
||||
self.out_dtype if self.out_dtype is not None else a.dtype)
|
||||
return (
|
||||
workspace1,
|
||||
workspace2,
|
||||
output,
|
||||
self.out_dtype if self.out_dtype is not None else a.dtype,
|
||||
)
|
||||
|
||||
def apply(
|
||||
self,
|
||||
@@ -740,21 +844,24 @@ class CutlassExpertsFp4(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
|
||||
|
||||
def cutlass_moe_fp4(
|
||||
a: torch.Tensor,
|
||||
w1_fp4: torch.Tensor,
|
||||
w2_fp4: torch.Tensor,
|
||||
topk_weights: torch.Tensor,
|
||||
topk_ids: torch.Tensor,
|
||||
quant_config: FusedMoEQuantConfig,
|
||||
m: int,
|
||||
n: int,
|
||||
k: int,
|
||||
e: int,
|
||||
expert_map: Optional[torch.Tensor] = None,
|
||||
apply_router_weight_on_input: bool = False) -> torch.Tensor:
|
||||
assert expert_map is None, ("Expert Parallelism / expert_map "
|
||||
"is currently not supported for "
|
||||
"ModelOptNvFp4FusedMoE's cutlass_moe_fp4.")
|
||||
a: torch.Tensor,
|
||||
w1_fp4: torch.Tensor,
|
||||
w2_fp4: torch.Tensor,
|
||||
topk_weights: torch.Tensor,
|
||||
topk_ids: torch.Tensor,
|
||||
quant_config: FusedMoEQuantConfig,
|
||||
m: int,
|
||||
n: int,
|
||||
k: int,
|
||||
e: int,
|
||||
expert_map: Optional[torch.Tensor] = None,
|
||||
apply_router_weight_on_input: bool = False,
|
||||
) -> torch.Tensor:
|
||||
assert expert_map is None, (
|
||||
"Expert Parallelism / expert_map "
|
||||
"is currently not supported for "
|
||||
"ModelOptNvFp4FusedMoE's cutlass_moe_fp4."
|
||||
)
|
||||
|
||||
# TODO(bnell): this feels a bit hacky
|
||||
# NVFP4 requires two levels of quantization, which involves
|
||||
@@ -799,10 +906,13 @@ def cutlass_moe_fp4(
|
||||
|
||||
|
||||
def _valid_cutlass_block_scaled_grouped_gemm(
|
||||
w1: torch.Tensor, w2: torch.Tensor, inplace: bool, activation: str,
|
||||
apply_router_weight_on_input: bool,
|
||||
expert_map: Optional[torch.Tensor]) -> bool:
|
||||
|
||||
w1: torch.Tensor,
|
||||
w2: torch.Tensor,
|
||||
inplace: bool,
|
||||
activation: str,
|
||||
apply_router_weight_on_input: bool,
|
||||
expert_map: Optional[torch.Tensor],
|
||||
) -> bool:
|
||||
def _valid_cutlass_block_scaled_grouped_gemm_shape(N: int, K: int):
|
||||
return N % 128 == 0 and K % 128 == 0
|
||||
|
||||
@@ -816,7 +926,7 @@ def _valid_cutlass_block_scaled_grouped_gemm(
|
||||
)
|
||||
return False
|
||||
|
||||
if (w1.dtype != torch.float8_e4m3fn or w2.dtype != torch.float8_e4m3fn):
|
||||
if w1.dtype != torch.float8_e4m3fn or w2.dtype != torch.float8_e4m3fn:
|
||||
logger.debug_once(
|
||||
"CutlassBlockScaledGroupedGemm disabled: invalid weight dtype(s). "
|
||||
"w1.dtype: %s, w2.dtype: %s",
|
||||
@@ -827,19 +937,21 @@ def _valid_cutlass_block_scaled_grouped_gemm(
|
||||
|
||||
if expert_map is not None:
|
||||
logger.debug_once(
|
||||
"CutlassBlockScaledGroupedGemm disabled: expert_parallel is"
|
||||
" not supported.")
|
||||
"CutlassBlockScaledGroupedGemm disabled: expert_parallel is not supported."
|
||||
)
|
||||
return False
|
||||
|
||||
if activation != "silu":
|
||||
logger.debug_once(
|
||||
"CutlassBlockScaledGroupedGemm disabled: only activation silu is"
|
||||
" supported.")
|
||||
"CutlassBlockScaledGroupedGemm disabled: only activation silu is supported."
|
||||
)
|
||||
return False
|
||||
|
||||
if apply_router_weight_on_input:
|
||||
logger.debug_once("CutlassBlockScaledGroupedGemm disabled:"
|
||||
" apply_router_weight_on_input is not supported.")
|
||||
logger.debug_once(
|
||||
"CutlassBlockScaledGroupedGemm disabled:"
|
||||
" apply_router_weight_on_input is not supported."
|
||||
)
|
||||
return False
|
||||
|
||||
if inplace:
|
||||
@@ -867,17 +979,16 @@ def run_cutlass_block_scaled_fused_experts(
|
||||
w2_scale = w2_scale.transpose(1, 2)
|
||||
|
||||
assert topk_weights.shape == topk_ids.shape, "topk shape mismatch"
|
||||
assert a.shape[0] == topk_ids.shape[
|
||||
0], "a and topk_ids must have the same batch size"
|
||||
assert a.shape[0] == topk_ids.shape[0], (
|
||||
"a and topk_ids must have the same batch size"
|
||||
)
|
||||
assert w1_q.dtype == torch.float8_e4m3fn, "w1_q must be float8_e4m3fn"
|
||||
assert w2_q.dtype == torch.float8_e4m3fn, "w2_q must be float8_e4m3fn"
|
||||
assert a.shape[1] == w1_q.shape[1], "Hidden size mismatch w1"
|
||||
assert w1_q.shape[2] == w2_q.shape[1] * 2, "Hidden size mismatch w2"
|
||||
assert w1_q.shape[0] == w2_q.shape[0], "Expert number mismatch"
|
||||
assert w1_q.shape[0] == w1_scale.shape[
|
||||
0], "w1_scale expert number mismatch"
|
||||
assert w1_q.shape[0] == w2_scale.shape[
|
||||
0], "w2_scale expert number mismatch"
|
||||
assert w1_q.shape[0] == w1_scale.shape[0], "w1_scale expert number mismatch"
|
||||
assert w1_q.shape[0] == w2_scale.shape[0], "w2_scale expert number mismatch"
|
||||
assert a.dtype in [torch.half, torch.bfloat16], "Invalid output dtype"
|
||||
|
||||
out_dtype = a.dtype
|
||||
@@ -888,21 +999,14 @@ def run_cutlass_block_scaled_fused_experts(
|
||||
|
||||
topk = topk_ids.size(1)
|
||||
|
||||
a_q, a1_scale = _fp8_quantize(a,
|
||||
A_scale=None,
|
||||
per_act_token=False,
|
||||
block_shape=[128, 128])
|
||||
a_q, a1_scale = _fp8_quantize(
|
||||
a, A_scale=None, per_act_token=False, block_shape=[128, 128]
|
||||
)
|
||||
device = a_q.device
|
||||
|
||||
expert_offsets = torch.empty((num_experts + 1, ),
|
||||
dtype=torch.int32,
|
||||
device=device)
|
||||
problem_sizes1 = torch.empty((num_experts, 3),
|
||||
dtype=torch.int32,
|
||||
device=device)
|
||||
problem_sizes2 = torch.empty((num_experts, 3),
|
||||
dtype=torch.int32,
|
||||
device=device)
|
||||
expert_offsets = torch.empty((num_experts + 1,), dtype=torch.int32, device=device)
|
||||
problem_sizes1 = torch.empty((num_experts, 3), dtype=torch.int32, device=device)
|
||||
problem_sizes2 = torch.empty((num_experts, 3), dtype=torch.int32, device=device)
|
||||
|
||||
a_map = torch.empty((topk_ids.numel()), dtype=torch.int32, device=device)
|
||||
c_map = torch.empty((topk_ids.numel()), dtype=torch.int32, device=device)
|
||||
@@ -938,10 +1042,9 @@ def run_cutlass_block_scaled_fused_experts(
|
||||
intermediate = torch.empty((m * topk, n), dtype=out_dtype, device=device)
|
||||
torch.ops._C.silu_and_mul(intermediate, c1)
|
||||
|
||||
intermediate_q, a2_scale = _fp8_quantize(intermediate,
|
||||
A_scale=None,
|
||||
per_act_token=False,
|
||||
block_shape=[128, 128])
|
||||
intermediate_q, a2_scale = _fp8_quantize(
|
||||
intermediate, A_scale=None, per_act_token=False, block_shape=[128, 128]
|
||||
)
|
||||
|
||||
ops.cutlass_blockwise_scaled_grouped_mm(
|
||||
c2,
|
||||
@@ -953,5 +1056,6 @@ def run_cutlass_block_scaled_fused_experts(
|
||||
expert_offsets[:-1],
|
||||
)
|
||||
|
||||
return (c2[c_map].view(m, topk, k) *
|
||||
topk_weights.view(m, topk, 1).to(out_dtype)).sum(dim=1)
|
||||
return (
|
||||
c2[c_map].view(m, topk, k) * topk_weights.view(m, topk, 1).to(out_dtype)
|
||||
).sum(dim=1)
|
||||
|
||||
@@ -9,17 +9,25 @@ import vllm.envs as env
|
||||
import vllm.model_executor.layers.fused_moe.modular_kernel as mk
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.fused_moe.config import (
|
||||
FusedMoEQuantConfig, fp8_w8a8_moe_quant_config)
|
||||
FusedMoEQuantConfig,
|
||||
fp8_w8a8_moe_quant_config,
|
||||
)
|
||||
from vllm.model_executor.layers.fused_moe.deep_gemm_utils import (
|
||||
compute_aligned_M, deep_gemm_block_shape, deepgemm_moe_permute,
|
||||
deepgemm_unpermute_and_reduce)
|
||||
compute_aligned_M,
|
||||
deep_gemm_block_shape,
|
||||
deepgemm_moe_permute,
|
||||
deepgemm_unpermute_and_reduce,
|
||||
)
|
||||
from vllm.model_executor.layers.fused_moe.prepare_finalize import (
|
||||
MoEPrepareAndFinalizeNoEP)
|
||||
MoEPrepareAndFinalizeNoEP,
|
||||
)
|
||||
from vllm.model_executor.layers.fused_moe.topk_weight_and_reduce import (
|
||||
TopKWeightAndReduceNoOP)
|
||||
TopKWeightAndReduceNoOP,
|
||||
)
|
||||
from vllm.model_executor.layers.fused_moe.utils import _resize_cache
|
||||
from vllm.model_executor.layers.quantization.utils.fp8_utils import (
|
||||
per_token_group_quant_fp8)
|
||||
per_token_group_quant_fp8,
|
||||
)
|
||||
from vllm.utils import has_deep_gemm, run_once
|
||||
from vllm.utils.deep_gemm import m_grouped_fp8_gemm_nt_contiguous
|
||||
|
||||
@@ -31,8 +39,9 @@ def _valid_deep_gemm_shape(M: int, N: int, K: int) -> bool:
|
||||
return align <= M and N % align == 0 and K % align == 0
|
||||
|
||||
|
||||
def _valid_deep_gemm(hidden_states: torch.Tensor, w1: torch.Tensor,
|
||||
w2: torch.Tensor) -> bool:
|
||||
def _valid_deep_gemm(
|
||||
hidden_states: torch.Tensor, w1: torch.Tensor, w2: torch.Tensor
|
||||
) -> bool:
|
||||
"""
|
||||
Check if the given problem size is supported by the DeepGemm grouped
|
||||
gemm kernel. All of M, N, K and the quantization block_shape must be
|
||||
@@ -71,17 +80,19 @@ def _valid_deep_gemm(hidden_states: torch.Tensor, w1: torch.Tensor,
|
||||
)
|
||||
return False
|
||||
|
||||
if (w1.dtype != torch.float8_e4m3fn or w2.dtype != torch.float8_e4m3fn):
|
||||
if w1.dtype != torch.float8_e4m3fn or w2.dtype != torch.float8_e4m3fn:
|
||||
logger.debug_once(
|
||||
"DeepGemm disabled: invalid weight dtype(s). "
|
||||
"w1.dtype: %s, w2.dtype: %s",
|
||||
"DeepGemm disabled: invalid weight dtype(s). w1.dtype: %s, w2.dtype: %s",
|
||||
w1.dtype,
|
||||
w2.dtype,
|
||||
)
|
||||
return False
|
||||
|
||||
if (not hidden_states.is_contiguous() or not w1.is_contiguous()
|
||||
or not w2.is_contiguous()):
|
||||
if (
|
||||
not hidden_states.is_contiguous()
|
||||
or not w1.is_contiguous()
|
||||
or not w2.is_contiguous()
|
||||
):
|
||||
logger.debug_once(
|
||||
"DeepGemm disabled: weights or activations not contiguous. "
|
||||
"hidden_states.is_contiguous(): %s, w1.is_contiguous(): %s, "
|
||||
@@ -96,10 +107,13 @@ def _valid_deep_gemm(hidden_states: torch.Tensor, w1: torch.Tensor,
|
||||
|
||||
|
||||
@run_once
|
||||
def warmup_deepgemm_gg_contiguous_kernels(w1: torch.Tensor, w2: torch.Tensor,
|
||||
w1_scale: torch.Tensor,
|
||||
w2_scale: torch.Tensor,
|
||||
num_topk: int):
|
||||
def warmup_deepgemm_gg_contiguous_kernels(
|
||||
w1: torch.Tensor,
|
||||
w2: torch.Tensor,
|
||||
w1_scale: torch.Tensor,
|
||||
w2_scale: torch.Tensor,
|
||||
num_topk: int,
|
||||
):
|
||||
"""
|
||||
DeepGemm JITs the grouped-gemm kernels. The JIT'ing happens based on the
|
||||
input tensor shapes. In this function, we construct all possible input
|
||||
@@ -108,8 +122,7 @@ def warmup_deepgemm_gg_contiguous_kernels(w1: torch.Tensor, w2: torch.Tensor,
|
||||
call and not during actual model inference.
|
||||
"""
|
||||
|
||||
assert w1.size(0) == w2.size(0), (
|
||||
"w1 and w2 must have the same number of experts")
|
||||
assert w1.size(0) == w2.size(0), "w1 and w2 must have the same number of experts"
|
||||
|
||||
block_m = deep_gemm_block_shape()[0]
|
||||
num_experts = w1.size(0)
|
||||
@@ -117,36 +130,39 @@ def warmup_deepgemm_gg_contiguous_kernels(w1: torch.Tensor, w2: torch.Tensor,
|
||||
|
||||
# This is the maximum GroupedGemm M size that we expect to run
|
||||
# the grouped_gemm with.
|
||||
MAX_M = compute_aligned_M(env.VLLM_FUSED_MOE_CHUNK_SIZE,
|
||||
num_topk,
|
||||
num_experts,
|
||||
block_m,
|
||||
expert_tokens_meta=None)
|
||||
MAX_M = compute_aligned_M(
|
||||
env.VLLM_FUSED_MOE_CHUNK_SIZE,
|
||||
num_topk,
|
||||
num_experts,
|
||||
block_m,
|
||||
expert_tokens_meta=None,
|
||||
)
|
||||
# Distribute expert-ids evenly.
|
||||
MAX_BLOCKS = MAX_M // block_m
|
||||
expert_ids_block = torch.randint(low=0,
|
||||
high=num_experts,
|
||||
size=(MAX_BLOCKS, ),
|
||||
device=device,
|
||||
dtype=torch.int32)
|
||||
expert_ids_block = torch.randint(
|
||||
low=0, high=num_experts, size=(MAX_BLOCKS,), device=device, dtype=torch.int32
|
||||
)
|
||||
expert_ids = torch.repeat_interleave(expert_ids_block, block_m, dim=0)
|
||||
|
||||
def _warmup(w: torch.Tensor, w_scale: torch.Tensor):
|
||||
|
||||
_, n, k = w.size()
|
||||
a1q = torch.empty((MAX_M, k), device=device).to(torch.float8_e4m3fn)
|
||||
a1q_scales = torch.empty((MAX_M, k // block_m),
|
||||
device=device,
|
||||
dtype=torch.float32)
|
||||
a1q_scales = torch.empty(
|
||||
(MAX_M, k // block_m), device=device, dtype=torch.float32
|
||||
)
|
||||
out = torch.empty((MAX_M, n), device=device, dtype=torch.bfloat16)
|
||||
|
||||
pbar = tqdm(total=MAX_BLOCKS,
|
||||
desc=f"DeepGemmExperts GEMM warmup (MAX_M={MAX_M})")
|
||||
pbar = tqdm(
|
||||
total=MAX_BLOCKS, desc=f"DeepGemmExperts GEMM warmup (MAX_M={MAX_M})"
|
||||
)
|
||||
num_tokens = MAX_M
|
||||
while num_tokens > 0:
|
||||
m_grouped_fp8_gemm_nt_contiguous(
|
||||
(a1q[:num_tokens], a1q_scales[:num_tokens]), (w, w_scale),
|
||||
out[:num_tokens], expert_ids[:num_tokens])
|
||||
(a1q[:num_tokens], a1q_scales[:num_tokens]),
|
||||
(w, w_scale),
|
||||
out[:num_tokens],
|
||||
expert_ids[:num_tokens],
|
||||
)
|
||||
pbar.update(1)
|
||||
num_tokens = num_tokens - block_m
|
||||
|
||||
@@ -155,7 +171,6 @@ def warmup_deepgemm_gg_contiguous_kernels(w1: torch.Tensor, w2: torch.Tensor,
|
||||
|
||||
|
||||
class DeepGemmExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
|
||||
def __init__(self, quant_config: FusedMoEQuantConfig):
|
||||
super().__init__(quant_config)
|
||||
assert quant_config.block_shape == deep_gemm_block_shape()
|
||||
@@ -165,10 +180,12 @@ class DeepGemmExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
|
||||
@property
|
||||
def activation_formats(
|
||||
self
|
||||
self,
|
||||
) -> tuple[mk.FusedMoEActivationFormat, mk.FusedMoEActivationFormat]:
|
||||
return (mk.FusedMoEActivationFormat.Standard,
|
||||
mk.FusedMoEActivationFormat.Standard)
|
||||
return (
|
||||
mk.FusedMoEActivationFormat.Standard,
|
||||
mk.FusedMoEActivationFormat.Standard,
|
||||
)
|
||||
|
||||
def supports_chunking(self) -> bool:
|
||||
return True
|
||||
@@ -193,8 +210,9 @@ class DeepGemmExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
) -> tuple[tuple[int, ...], tuple[int, ...], tuple[int, ...], torch.dtype]:
|
||||
assert self.block_shape is not None
|
||||
block_m = self.block_shape[0]
|
||||
M_sum = compute_aligned_M(M, topk, local_num_experts, block_m,
|
||||
expert_tokens_meta)
|
||||
M_sum = compute_aligned_M(
|
||||
M, topk, local_num_experts, block_m, expert_tokens_meta
|
||||
)
|
||||
assert M_sum % block_m == 0
|
||||
|
||||
workspace1 = (M_sum, max(N, K))
|
||||
@@ -235,18 +253,20 @@ class DeepGemmExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
|
||||
assert w2.size(1) == K
|
||||
|
||||
M_sum = compute_aligned_M(M=topk_ids.size(0),
|
||||
num_topk=topk_ids.size(1),
|
||||
local_num_experts=local_num_experts,
|
||||
alignment=deep_gemm_block_shape()[0],
|
||||
expert_tokens_meta=expert_tokens_meta)
|
||||
M_sum = compute_aligned_M(
|
||||
M=topk_ids.size(0),
|
||||
num_topk=topk_ids.size(1),
|
||||
local_num_experts=local_num_experts,
|
||||
alignment=deep_gemm_block_shape()[0],
|
||||
expert_tokens_meta=expert_tokens_meta,
|
||||
)
|
||||
|
||||
a1q_perm = _resize_cache(workspace2.view(dtype=torch.float8_e4m3fn),
|
||||
(M_sum, K))
|
||||
a1q_perm = _resize_cache(workspace2.view(dtype=torch.float8_e4m3fn), (M_sum, K))
|
||||
mm1_out = _resize_cache(workspace13, (M_sum, N))
|
||||
act_out = _resize_cache(workspace2, (M_sum, N // 2))
|
||||
quant_out = _resize_cache(workspace13.view(dtype=torch.float8_e4m3fn),
|
||||
(M_sum, N // 2))
|
||||
quant_out = _resize_cache(
|
||||
workspace13.view(dtype=torch.float8_e4m3fn), (M_sum, N // 2)
|
||||
)
|
||||
mm2_out = _resize_cache(workspace2, (M_sum, K))
|
||||
|
||||
a1q, a1q_scale, expert_ids, inv_perm = deepgemm_moe_permute(
|
||||
@@ -256,32 +276,36 @@ class DeepGemmExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
local_num_experts=local_num_experts,
|
||||
expert_map=expert_map,
|
||||
expert_tokens_meta=expert_tokens_meta,
|
||||
aq_out=a1q_perm)
|
||||
aq_out=a1q_perm,
|
||||
)
|
||||
assert a1q.size(0) == M_sum
|
||||
|
||||
m_grouped_fp8_gemm_nt_contiguous((a1q, a1q_scale), (w1, self.w1_scale),
|
||||
mm1_out, expert_ids)
|
||||
m_grouped_fp8_gemm_nt_contiguous(
|
||||
(a1q, a1q_scale), (w1, self.w1_scale), mm1_out, expert_ids
|
||||
)
|
||||
|
||||
self.activation(activation, act_out, mm1_out.view(-1, N))
|
||||
|
||||
a2q_scale: Optional[torch.Tensor] = None
|
||||
a2q, a2q_scale = per_token_group_quant_fp8(act_out,
|
||||
self.block_shape[1],
|
||||
column_major_scales=True,
|
||||
out_q=quant_out)
|
||||
a2q, a2q_scale = per_token_group_quant_fp8(
|
||||
act_out, self.block_shape[1], column_major_scales=True, out_q=quant_out
|
||||
)
|
||||
|
||||
m_grouped_fp8_gemm_nt_contiguous((a2q, a2q_scale), (w2, self.w2_scale),
|
||||
mm2_out, expert_ids)
|
||||
m_grouped_fp8_gemm_nt_contiguous(
|
||||
(a2q, a2q_scale), (w2, self.w2_scale), mm2_out, expert_ids
|
||||
)
|
||||
|
||||
if apply_router_weight_on_input:
|
||||
topk_weights = torch.ones_like(topk_weights)
|
||||
|
||||
deepgemm_unpermute_and_reduce(a=mm2_out,
|
||||
topk_ids=topk_ids,
|
||||
topk_weights=topk_weights,
|
||||
inv_perm=inv_perm,
|
||||
expert_map=expert_map,
|
||||
output=output)
|
||||
deepgemm_unpermute_and_reduce(
|
||||
a=mm2_out,
|
||||
topk_ids=topk_ids,
|
||||
topk_weights=topk_weights,
|
||||
inv_perm=inv_perm,
|
||||
expert_map=expert_map,
|
||||
output=output,
|
||||
)
|
||||
|
||||
|
||||
def deep_gemm_moe_fp8(
|
||||
@@ -342,7 +366,8 @@ def deep_gemm_moe_fp8(
|
||||
w2_scale=w2_scale,
|
||||
a1_scale=a1_scale,
|
||||
a2_scale=a2_scale,
|
||||
block_shape=deep_gemm_block_shape())
|
||||
block_shape=deep_gemm_block_shape(),
|
||||
)
|
||||
|
||||
fn = mk.FusedMoEModularKernel(
|
||||
MoEPrepareAndFinalizeNoEP(),
|
||||
|
||||
@@ -20,27 +20,33 @@ from vllm.utils import round_up
|
||||
def deep_gemm_block_shape() -> list[int]:
|
||||
# Lazy import to avoid CUDA initialization problems.
|
||||
import deep_gemm as dg
|
||||
|
||||
block = dg.get_m_alignment_for_contiguous_layout()
|
||||
return [block, block]
|
||||
|
||||
|
||||
def expert_num_tokens_round_up_and_sum(expert_num_tokens: torch.Tensor,
|
||||
alignment: int) -> int:
|
||||
def expert_num_tokens_round_up_and_sum(
|
||||
expert_num_tokens: torch.Tensor, alignment: int
|
||||
) -> int:
|
||||
# Round up each element in expert_num_tokens to the nearest multiple of
|
||||
# alignment.
|
||||
ent = (expert_num_tokens.to(torch.int64) +
|
||||
(alignment - 1)) // alignment * alignment
|
||||
ent = (expert_num_tokens.to(torch.int64) + (alignment - 1)) // alignment * alignment
|
||||
return torch.sum(ent).item()
|
||||
|
||||
|
||||
def compute_aligned_M(M: int, num_topk: int, local_num_experts: int,
|
||||
alignment: int,
|
||||
expert_tokens_meta: Optional[mk.ExpertTokensMetadata]):
|
||||
|
||||
if ((expert_tokens_meta is not None)
|
||||
and (expert_tokens_meta.expert_num_tokens_cpu is not None)):
|
||||
def compute_aligned_M(
|
||||
M: int,
|
||||
num_topk: int,
|
||||
local_num_experts: int,
|
||||
alignment: int,
|
||||
expert_tokens_meta: Optional[mk.ExpertTokensMetadata],
|
||||
):
|
||||
if (expert_tokens_meta is not None) and (
|
||||
expert_tokens_meta.expert_num_tokens_cpu is not None
|
||||
):
|
||||
return expert_num_tokens_round_up_and_sum(
|
||||
expert_tokens_meta.expert_num_tokens_cpu, alignment=alignment)
|
||||
expert_tokens_meta.expert_num_tokens_cpu, alignment=alignment
|
||||
)
|
||||
|
||||
# expert_num_tokens information is not available on the cpu.
|
||||
# compute the max required size.
|
||||
@@ -74,14 +80,14 @@ def _fwd_kernel_ep_scatter_1(
|
||||
cur_expert = tl.program_id(0)
|
||||
|
||||
offset_cumsum = tl.arange(0, BLOCK_EXPERT_NUM)
|
||||
tokens_per_expert = tl.load(num_recv_tokens_per_expert + offset_cumsum,
|
||||
mask=offset_cumsum < num_experts,
|
||||
other=0)
|
||||
tokens_per_expert = tl.load(
|
||||
num_recv_tokens_per_expert + offset_cumsum,
|
||||
mask=offset_cumsum < num_experts,
|
||||
other=0,
|
||||
)
|
||||
tokens_per_expert = round_up_128(tokens_per_expert)
|
||||
cumsum = tl.cumsum(tokens_per_expert) - tokens_per_expert
|
||||
tl.store(expert_start_loc + offset_cumsum,
|
||||
cumsum,
|
||||
mask=offset_cumsum < num_experts)
|
||||
tl.store(expert_start_loc + offset_cumsum, cumsum, mask=offset_cumsum < num_experts)
|
||||
|
||||
cur_expert_start = tl.load(expert_start_loc + cur_expert)
|
||||
cur_expert_token_num = tl.load(num_recv_tokens_per_expert + cur_expert)
|
||||
@@ -136,34 +142,31 @@ def _fwd_kernel_ep_scatter_2(
|
||||
mask_s = offset_in_s < SCALE_HIDDEN_SIZE
|
||||
|
||||
for token_id in range(start_token_id, total_token_num, grid_num):
|
||||
to_copy = tl.load(recv_x + token_id * recv_x_stride0 + offset_in,
|
||||
mask=mask)
|
||||
to_copy_s = tl.load(recv_x_scale + token_id * recv_x_scale_stride0 +
|
||||
offset_in_s,
|
||||
mask=mask_s)
|
||||
to_copy = tl.load(recv_x + token_id * recv_x_stride0 + offset_in, mask=mask)
|
||||
to_copy_s = tl.load(
|
||||
recv_x_scale + token_id * recv_x_scale_stride0 + offset_in_s, mask=mask_s
|
||||
)
|
||||
|
||||
for topk_index in tl.range(0, topk_num, 1, num_stages=4):
|
||||
expert_id = tl.load(recv_topk + token_id * recv_topk_stride0 +
|
||||
topk_index)
|
||||
expert_id = tl.load(recv_topk + token_id * recv_topk_stride0 + topk_index)
|
||||
|
||||
if HAS_EXPERT_MAP:
|
||||
expert_id = apply_expert_map(expert_id, expert_map)
|
||||
|
||||
if expert_id >= 0:
|
||||
dest_token_index = tl.atomic_add(expert_start_loc + expert_id,
|
||||
1)
|
||||
dest_token_index = tl.atomic_add(expert_start_loc + expert_id, 1)
|
||||
tl.store(
|
||||
output_index + token_id * output_index_stride0 +
|
||||
topk_index, dest_token_index)
|
||||
output_tensor_ptr = (output_tensor +
|
||||
dest_token_index * output_tensor_stride0)
|
||||
output_index + token_id * output_index_stride0 + topk_index,
|
||||
dest_token_index,
|
||||
)
|
||||
output_tensor_ptr = (
|
||||
output_tensor + dest_token_index * output_tensor_stride0
|
||||
)
|
||||
output_tensor_scale_ptr = (
|
||||
output_tensor_scale +
|
||||
dest_token_index * output_tensor_scale_stride0)
|
||||
output_tensor_scale + dest_token_index * output_tensor_scale_stride0
|
||||
)
|
||||
tl.store(output_tensor_ptr + offset_in, to_copy, mask=mask)
|
||||
tl.store(output_tensor_scale_ptr + offset_in_s,
|
||||
to_copy_s,
|
||||
mask=mask_s)
|
||||
tl.store(output_tensor_scale_ptr + offset_in_s, to_copy_s, mask=mask_s)
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
@@ -189,7 +192,7 @@ def ep_scatter(
|
||||
|
||||
assert m_indices.shape[0] % BLOCK_E == 0
|
||||
|
||||
_fwd_kernel_ep_scatter_1[(grid, )](
|
||||
_fwd_kernel_ep_scatter_1[(grid,)](
|
||||
num_recv_tokens_per_expert,
|
||||
expert_start_loc,
|
||||
m_indices,
|
||||
@@ -201,7 +204,7 @@ def ep_scatter(
|
||||
|
||||
grid = min(recv_topk.shape[0], 1024 * 8)
|
||||
|
||||
_fwd_kernel_ep_scatter_2[(grid, )](
|
||||
_fwd_kernel_ep_scatter_2[(grid,)](
|
||||
recv_topk.shape[0],
|
||||
expert_start_loc,
|
||||
recv_x,
|
||||
@@ -265,27 +268,33 @@ def _fwd_kernel_ep_gather(
|
||||
off_d = tl.arange(0, BLOCK_D)
|
||||
accumulator = tl.zeros([BLOCK_D], dtype=tl.float32)
|
||||
for topk_index in range(0, topk_num):
|
||||
expert_id = tl.load(recv_topk_ids +
|
||||
cur_token * recv_topk_ids_stride0 + topk_index)
|
||||
expert_id = tl.load(
|
||||
recv_topk_ids + cur_token * recv_topk_ids_stride0 + topk_index
|
||||
)
|
||||
|
||||
if HAS_EXPERT_MAP:
|
||||
expert_id = apply_expert_map(expert_id, expert_map)
|
||||
|
||||
if expert_id >= 0:
|
||||
source_token_index = tl.load(input_index +
|
||||
cur_token * input_index_stride0 +
|
||||
topk_index)
|
||||
acc_weight = tl.load(recv_topk_weight +
|
||||
cur_token * recv_topk_weight_stride0 +
|
||||
topk_index)
|
||||
tmp = tl.load(input_tensor +
|
||||
source_token_index * input_tensor_stride0 +
|
||||
cur_block * BLOCK_D + off_d)
|
||||
source_token_index = tl.load(
|
||||
input_index + cur_token * input_index_stride0 + topk_index
|
||||
)
|
||||
acc_weight = tl.load(
|
||||
recv_topk_weight + cur_token * recv_topk_weight_stride0 + topk_index
|
||||
)
|
||||
tmp = tl.load(
|
||||
input_tensor
|
||||
+ source_token_index * input_tensor_stride0
|
||||
+ cur_block * BLOCK_D
|
||||
+ off_d
|
||||
)
|
||||
accumulator += tmp.to(tl.float32) * acc_weight
|
||||
|
||||
tl.store(
|
||||
output_tensor + cur_token * output_tensor_stride0 +
|
||||
cur_block * BLOCK_D + off_d,
|
||||
output_tensor
|
||||
+ cur_token * output_tensor_stride0
|
||||
+ cur_block * BLOCK_D
|
||||
+ off_d,
|
||||
accumulator.to(output_tensor.dtype.element_ty),
|
||||
)
|
||||
|
||||
@@ -332,44 +341,46 @@ def ep_gather(
|
||||
return
|
||||
|
||||
|
||||
def deepgemm_moe_permute(aq: torch.Tensor,
|
||||
aq_scale: torch.Tensor,
|
||||
topk_ids: torch.Tensor,
|
||||
local_num_experts: int,
|
||||
expert_map: Optional[torch.Tensor],
|
||||
expert_tokens_meta: Optional[mk.ExpertTokensMetadata],
|
||||
aq_out: Optional[torch.Tensor] = None):
|
||||
|
||||
def deepgemm_moe_permute(
|
||||
aq: torch.Tensor,
|
||||
aq_scale: torch.Tensor,
|
||||
topk_ids: torch.Tensor,
|
||||
local_num_experts: int,
|
||||
expert_map: Optional[torch.Tensor],
|
||||
expert_tokens_meta: Optional[mk.ExpertTokensMetadata],
|
||||
aq_out: Optional[torch.Tensor] = None,
|
||||
):
|
||||
assert aq.ndim == 2
|
||||
assert topk_ids.dtype.is_signed, (
|
||||
"The kernel uses -1 to represent invalid topk_ids")
|
||||
assert topk_ids.dtype.is_signed, "The kernel uses -1 to represent invalid topk_ids"
|
||||
H = aq.size(1)
|
||||
device = aq.device
|
||||
|
||||
block_m = deep_gemm_block_shape()[0]
|
||||
block_k = deep_gemm_block_shape()[1]
|
||||
|
||||
M_sum = compute_aligned_M(M=topk_ids.size(0),
|
||||
num_topk=topk_ids.size(1),
|
||||
local_num_experts=local_num_experts,
|
||||
alignment=block_m,
|
||||
expert_tokens_meta=expert_tokens_meta)
|
||||
M_sum = compute_aligned_M(
|
||||
M=topk_ids.size(0),
|
||||
num_topk=topk_ids.size(1),
|
||||
local_num_experts=local_num_experts,
|
||||
alignment=block_m,
|
||||
expert_tokens_meta=expert_tokens_meta,
|
||||
)
|
||||
|
||||
expert_start_loc = torch.empty((local_num_experts),
|
||||
device=device,
|
||||
dtype=torch.int32)
|
||||
expert_start_loc = torch.empty(
|
||||
(local_num_experts), device=device, dtype=torch.int32
|
||||
)
|
||||
|
||||
assert aq_out is None or aq_out.shape == (M_sum, H)
|
||||
if aq_out is None:
|
||||
aq_out = torch.empty((M_sum, H), device=device, dtype=aq.dtype)
|
||||
|
||||
aq_scale_out = torch.empty((M_sum, H // block_k),
|
||||
device=device,
|
||||
dtype=torch.float32)
|
||||
aq_scale_out = torch.empty(
|
||||
(M_sum, H // block_k), device=device, dtype=torch.float32
|
||||
)
|
||||
|
||||
maybe_has_empty_blocks = ((expert_tokens_meta is None)
|
||||
or (expert_tokens_meta.expert_num_tokens_cpu
|
||||
is None))
|
||||
maybe_has_empty_blocks = (expert_tokens_meta is None) or (
|
||||
expert_tokens_meta.expert_num_tokens_cpu is None
|
||||
)
|
||||
expert_ids_init = torch.zeros if maybe_has_empty_blocks else torch.empty
|
||||
|
||||
expert_ids = expert_ids_init((M_sum), device=device, dtype=torch.int32)
|
||||
@@ -379,35 +390,39 @@ def deepgemm_moe_permute(aq: torch.Tensor,
|
||||
if expert_tokens_meta is not None:
|
||||
expert_num_tokens = expert_tokens_meta.expert_num_tokens
|
||||
else:
|
||||
expert_num_tokens = count_expert_num_tokens(topk_ids,
|
||||
local_num_experts,
|
||||
expert_map)
|
||||
expert_num_tokens = count_expert_num_tokens(
|
||||
topk_ids, local_num_experts, expert_map
|
||||
)
|
||||
|
||||
ep_scatter(recv_x=aq,
|
||||
recv_x_scale=aq_scale,
|
||||
recv_topk=topk_ids,
|
||||
num_recv_tokens_per_expert=expert_num_tokens,
|
||||
expert_start_loc=expert_start_loc,
|
||||
expert_map=expert_map,
|
||||
output_tensor=aq_out,
|
||||
output_tensor_scale=aq_scale_out,
|
||||
m_indices=expert_ids,
|
||||
output_index=inv_perm)
|
||||
ep_scatter(
|
||||
recv_x=aq,
|
||||
recv_x_scale=aq_scale,
|
||||
recv_topk=topk_ids,
|
||||
num_recv_tokens_per_expert=expert_num_tokens,
|
||||
expert_start_loc=expert_start_loc,
|
||||
expert_map=expert_map,
|
||||
output_tensor=aq_out,
|
||||
output_tensor_scale=aq_scale_out,
|
||||
m_indices=expert_ids,
|
||||
output_index=inv_perm,
|
||||
)
|
||||
|
||||
return aq_out, aq_scale_out, expert_ids, inv_perm
|
||||
|
||||
|
||||
def deepgemm_unpermute_and_reduce(
|
||||
a: torch.Tensor, # Grouped gemm output
|
||||
topk_ids: torch.Tensor,
|
||||
topk_weights: torch.Tensor,
|
||||
inv_perm: torch.Tensor,
|
||||
expert_map: Optional[torch.Tensor],
|
||||
output: torch.Tensor):
|
||||
|
||||
return ep_gather(input_tensor=a,
|
||||
recv_topk_ids=topk_ids,
|
||||
recv_topk_weight=topk_weights,
|
||||
input_index=inv_perm,
|
||||
expert_map=expert_map,
|
||||
output_tensor=output)
|
||||
a: torch.Tensor, # Grouped gemm output
|
||||
topk_ids: torch.Tensor,
|
||||
topk_weights: torch.Tensor,
|
||||
inv_perm: torch.Tensor,
|
||||
expert_map: Optional[torch.Tensor],
|
||||
output: torch.Tensor,
|
||||
):
|
||||
return ep_gather(
|
||||
input_tensor=a,
|
||||
recv_topk_ids=topk_ids,
|
||||
recv_topk_weight=topk_weights,
|
||||
input_index=inv_perm,
|
||||
expert_map=expert_map,
|
||||
output_tensor=output,
|
||||
)
|
||||
|
||||
@@ -8,15 +8,20 @@ import torch
|
||||
import vllm.model_executor.layers.fused_moe.modular_kernel as mk
|
||||
from vllm.model_executor.layers.fused_moe.config import FusedMoEQuantConfig
|
||||
from vllm.model_executor.layers.fused_moe.topk_weight_and_reduce import (
|
||||
TopKWeightAndReduceContiguous, TopKWeightAndReduceDelegate)
|
||||
from vllm.model_executor.layers.fused_moe.utils import (
|
||||
moe_kernel_quantize_input)
|
||||
TopKWeightAndReduceContiguous,
|
||||
TopKWeightAndReduceDelegate,
|
||||
)
|
||||
from vllm.model_executor.layers.fused_moe.utils import moe_kernel_quantize_input
|
||||
from vllm.utils import round_up
|
||||
from vllm.v1.worker.ubatching import (
|
||||
dbo_current_ubatch_id, dbo_enabled, dbo_switch_to_comm,
|
||||
dbo_switch_to_compute, dbo_switch_to_compute_sync,
|
||||
dbo_current_ubatch_id,
|
||||
dbo_enabled,
|
||||
dbo_switch_to_comm,
|
||||
dbo_switch_to_compute,
|
||||
dbo_switch_to_compute_sync,
|
||||
dbo_yield_and_switch_from_comm_to_compute,
|
||||
dbo_yield_and_switch_from_compute_to_comm)
|
||||
dbo_yield_and_switch_from_compute_to_comm,
|
||||
)
|
||||
|
||||
|
||||
class DeepEPHTPrepareAndFinalize(mk.FusedMoEPrepareAndFinalize):
|
||||
@@ -25,8 +30,7 @@ class DeepEPHTPrepareAndFinalize(mk.FusedMoEPrepareAndFinalize):
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def maybe_roundup_layer_hidden_size(hidden_size: int,
|
||||
dtype: torch.dtype) -> int:
|
||||
def maybe_roundup_layer_hidden_size(hidden_size: int, dtype: torch.dtype) -> int:
|
||||
# Round up hidden size so it is compatible with DeepEP High Throughput
|
||||
# kernels.
|
||||
# DeepEP intranode kernels make copies in units of,
|
||||
@@ -41,8 +45,13 @@ class DeepEPHTPrepareAndFinalize(mk.FusedMoEPrepareAndFinalize):
|
||||
hidden_size_bytes = round_up(hidden_size_bytes, xfer_atom_size)
|
||||
return hidden_size_bytes // dtype.itemsize
|
||||
|
||||
def __init__(self, buffer: deep_ep.Buffer, num_dispatchers: int,
|
||||
dp_size: int, rank_expert_offset: int):
|
||||
def __init__(
|
||||
self,
|
||||
buffer: deep_ep.Buffer,
|
||||
num_dispatchers: int,
|
||||
dp_size: int,
|
||||
rank_expert_offset: int,
|
||||
):
|
||||
super().__init__()
|
||||
self.buffer = buffer
|
||||
self.num_dispatchers_ = num_dispatchers
|
||||
@@ -91,7 +100,6 @@ class DeepEPHTPrepareAndFinalize(mk.FusedMoEPrepareAndFinalize):
|
||||
a1_scale: Optional[torch.Tensor],
|
||||
quant_config: FusedMoEQuantConfig,
|
||||
) -> Callable:
|
||||
|
||||
has_scales = token_scales is not None
|
||||
|
||||
# We yield before launching the dispatch kernel since the dispatch
|
||||
@@ -99,22 +107,31 @@ class DeepEPHTPrepareAndFinalize(mk.FusedMoEPrepareAndFinalize):
|
||||
# for the other ubatch before the dispatch kernel starts.
|
||||
dbo_yield_and_switch_from_compute_to_comm()
|
||||
|
||||
(num_tokens_per_rank, num_tokens_per_rdma_rank,
|
||||
dispatch_expert_num_tokens, is_token_in_rank,
|
||||
event) = self.buffer.get_dispatch_layout(
|
||||
topk_idx=rank_topk_ids,
|
||||
num_experts=num_experts,
|
||||
previous_event=None,
|
||||
async_finish=False,
|
||||
allocate_on_comm_stream=False)
|
||||
(
|
||||
num_tokens_per_rank,
|
||||
num_tokens_per_rdma_rank,
|
||||
dispatch_expert_num_tokens,
|
||||
is_token_in_rank,
|
||||
event,
|
||||
) = self.buffer.get_dispatch_layout(
|
||||
topk_idx=rank_topk_ids,
|
||||
num_experts=num_experts,
|
||||
previous_event=None,
|
||||
async_finish=False,
|
||||
allocate_on_comm_stream=False,
|
||||
)
|
||||
|
||||
token_data = tokens
|
||||
if has_scales:
|
||||
token_data = (tokens, token_scales)
|
||||
|
||||
(
|
||||
token_data, expert_topk_ids, expert_topk_weights,
|
||||
expert_num_tokens_per_expert_list, handle, event
|
||||
token_data,
|
||||
expert_topk_ids,
|
||||
expert_topk_weights,
|
||||
expert_num_tokens_per_expert_list,
|
||||
handle,
|
||||
event,
|
||||
) = self.buffer.dispatch(
|
||||
x=token_data,
|
||||
handle=None,
|
||||
@@ -130,7 +147,8 @@ class DeepEPHTPrepareAndFinalize(mk.FusedMoEPrepareAndFinalize):
|
||||
config=self._get_dispatch_config(),
|
||||
previous_event=None,
|
||||
async_finish=self.async_prepare and not dbo_enabled(),
|
||||
allocate_on_comm_stream=False)
|
||||
allocate_on_comm_stream=False,
|
||||
)
|
||||
|
||||
# record the handle for this ubatch
|
||||
a2a_idx = dbo_current_ubatch_id()
|
||||
@@ -185,13 +203,15 @@ class DeepEPHTPrepareAndFinalize(mk.FusedMoEPrepareAndFinalize):
|
||||
expert_topk_ids = torch.where(
|
||||
expert_topk_ids == -1,
|
||||
num_experts - 1 if self.rank_expert_offset == 0 else 0,
|
||||
expert_topk_ids + self.rank_expert_offset)
|
||||
expert_topk_ids + self.rank_expert_offset,
|
||||
)
|
||||
|
||||
# Makes a GPU-CPU copy.
|
||||
# TODO (varun): Maybe it is better to re-compute the expert_num_tokens
|
||||
# on GPU.
|
||||
expert_tokens_meta = mk.ExpertTokensMetadata.make_from_list(
|
||||
expert_num_tokens_per_expert_list, device=expert_x.device)
|
||||
expert_num_tokens_per_expert_list, device=expert_x.device
|
||||
)
|
||||
|
||||
# Dispatch and Quant
|
||||
# DeepEP kernels only support dispatching block-quantized
|
||||
@@ -206,10 +226,16 @@ class DeepEPHTPrepareAndFinalize(mk.FusedMoEPrepareAndFinalize):
|
||||
a1_scale,
|
||||
quant_dtype=quant_config.quant_dtype,
|
||||
per_act_token_quant=False,
|
||||
block_shape=quant_config.block_shape)
|
||||
block_shape=quant_config.block_shape,
|
||||
)
|
||||
|
||||
return (expert_x, expert_x_scale, expert_tokens_meta, expert_topk_ids,
|
||||
expert_topk_weights)
|
||||
return (
|
||||
expert_x,
|
||||
expert_x_scale,
|
||||
expert_tokens_meta,
|
||||
expert_topk_ids,
|
||||
expert_topk_weights,
|
||||
)
|
||||
|
||||
def supports_async(self) -> bool:
|
||||
return True
|
||||
@@ -224,12 +250,12 @@ class DeepEPHTPrepareAndFinalize(mk.FusedMoEPrepareAndFinalize):
|
||||
apply_router_weight_on_input: bool,
|
||||
quant_config: FusedMoEQuantConfig,
|
||||
) -> mk.ReceiverType:
|
||||
|
||||
if apply_router_weight_on_input:
|
||||
topk = topk_ids.size(1)
|
||||
# TODO: this only works for topK=1, will need to update for topK>1
|
||||
assert topk == 1, (
|
||||
"apply_router_weight_on_input is only implemented for topk=1")
|
||||
"apply_router_weight_on_input is only implemented for topk=1"
|
||||
)
|
||||
a1 = a1 * topk_weights.to(a1.dtype)
|
||||
|
||||
if quant_config.is_block_quantized:
|
||||
@@ -249,13 +275,15 @@ class DeepEPHTPrepareAndFinalize(mk.FusedMoEPrepareAndFinalize):
|
||||
a1q_scale = None
|
||||
a1_post_scale = quant_config.a1_scale
|
||||
|
||||
return self._do_dispatch(tokens=a1q,
|
||||
token_scales=a1q_scale,
|
||||
rank_topk_ids=topk_ids,
|
||||
rank_topk_weights=topk_weights,
|
||||
num_experts=num_experts,
|
||||
a1_scale=a1_post_scale,
|
||||
quant_config=quant_config)
|
||||
return self._do_dispatch(
|
||||
tokens=a1q,
|
||||
token_scales=a1q_scale,
|
||||
rank_topk_ids=topk_ids,
|
||||
rank_topk_weights=topk_weights,
|
||||
num_experts=num_experts,
|
||||
a1_scale=a1_post_scale,
|
||||
quant_config=quant_config,
|
||||
)
|
||||
|
||||
def prepare(
|
||||
self,
|
||||
@@ -267,9 +295,15 @@ class DeepEPHTPrepareAndFinalize(mk.FusedMoEPrepareAndFinalize):
|
||||
apply_router_weight_on_input: bool,
|
||||
quant_config: FusedMoEQuantConfig,
|
||||
) -> mk.PrepareResultType:
|
||||
receiver = self.prepare_async(a1, topk_weights, topk_ids, num_experts,
|
||||
expert_map, apply_router_weight_on_input,
|
||||
quant_config)
|
||||
receiver = self.prepare_async(
|
||||
a1,
|
||||
topk_weights,
|
||||
topk_ids,
|
||||
num_experts,
|
||||
expert_map,
|
||||
apply_router_weight_on_input,
|
||||
quant_config,
|
||||
)
|
||||
return receiver()
|
||||
|
||||
def _finalize(
|
||||
@@ -282,7 +316,6 @@ class DeepEPHTPrepareAndFinalize(mk.FusedMoEPrepareAndFinalize):
|
||||
weight_and_reduce_impl: mk.TopKWeightAndReduce,
|
||||
do_async: bool,
|
||||
) -> Optional[Callable]:
|
||||
|
||||
a2a_idx = dbo_current_ubatch_id()
|
||||
handle = self.handles[a2a_idx]
|
||||
assert handle is not None
|
||||
@@ -307,7 +340,8 @@ class DeepEPHTPrepareAndFinalize(mk.FusedMoEPrepareAndFinalize):
|
||||
config=self._get_combine_config(),
|
||||
previous_event=None,
|
||||
async_finish=do_async and not dbo_enabled(),
|
||||
allocate_on_comm_stream=False)
|
||||
allocate_on_comm_stream=False,
|
||||
)
|
||||
|
||||
dbo_switch_to_compute()
|
||||
|
||||
@@ -341,9 +375,15 @@ class DeepEPHTPrepareAndFinalize(mk.FusedMoEPrepareAndFinalize):
|
||||
apply_router_weight_on_input: bool,
|
||||
weight_and_reduce_impl: mk.TopKWeightAndReduce,
|
||||
) -> Callable:
|
||||
receiver = self._finalize(output, fused_expert_output, topk_weights,
|
||||
topk_ids, apply_router_weight_on_input,
|
||||
weight_and_reduce_impl, True)
|
||||
receiver = self._finalize(
|
||||
output,
|
||||
fused_expert_output,
|
||||
topk_weights,
|
||||
topk_ids,
|
||||
apply_router_weight_on_input,
|
||||
weight_and_reduce_impl,
|
||||
True,
|
||||
)
|
||||
assert receiver is not None
|
||||
return receiver
|
||||
|
||||
@@ -356,6 +396,12 @@ class DeepEPHTPrepareAndFinalize(mk.FusedMoEPrepareAndFinalize):
|
||||
apply_router_weight_on_input: bool,
|
||||
weight_and_reduce_impl: mk.TopKWeightAndReduce,
|
||||
) -> None:
|
||||
self._finalize(output, fused_expert_output, topk_weights, topk_ids,
|
||||
apply_router_weight_on_input, weight_and_reduce_impl,
|
||||
False)
|
||||
self._finalize(
|
||||
output,
|
||||
fused_expert_output,
|
||||
topk_weights,
|
||||
topk_ids,
|
||||
apply_router_weight_on_input,
|
||||
weight_and_reduce_impl,
|
||||
False,
|
||||
)
|
||||
|
||||
@@ -8,19 +8,26 @@ import torch
|
||||
import vllm.model_executor.layers.fused_moe.modular_kernel as mk
|
||||
from vllm.model_executor.layers.fused_moe.config import FusedMoEQuantConfig
|
||||
from vllm.model_executor.layers.fused_moe.topk_weight_and_reduce import (
|
||||
TopKWeightAndReduceDelegate)
|
||||
TopKWeightAndReduceDelegate,
|
||||
)
|
||||
from vllm.model_executor.layers.fused_moe.utils import (
|
||||
moe_kernel_quantize_input, normalize_batched_scales_shape)
|
||||
from vllm.v1.worker.ubatching import (dbo_current_ubatch_id, dbo_enabled,
|
||||
dbo_maybe_run_recv_hook)
|
||||
moe_kernel_quantize_input,
|
||||
normalize_batched_scales_shape,
|
||||
)
|
||||
from vllm.v1.worker.ubatching import (
|
||||
dbo_current_ubatch_id,
|
||||
dbo_enabled,
|
||||
dbo_maybe_run_recv_hook,
|
||||
)
|
||||
|
||||
# DeepEP kernels quantize dispatch inputs in 128 element chunks.
|
||||
DEEPEP_QUANT_BLOCK_SIZE = 128
|
||||
DEEPEP_QUANT_BLOCK_SHAPE = [DEEPEP_QUANT_BLOCK_SIZE, DEEPEP_QUANT_BLOCK_SIZE]
|
||||
|
||||
|
||||
def dequant_fp8(expert_x_fp8: torch.Tensor,
|
||||
expert_x_scales: torch.Tensor) -> torch.Tensor:
|
||||
def dequant_fp8(
|
||||
expert_x_fp8: torch.Tensor, expert_x_scales: torch.Tensor
|
||||
) -> torch.Tensor:
|
||||
"""
|
||||
Return dequantized tensor in fp32
|
||||
"""
|
||||
@@ -30,7 +37,8 @@ def dequant_fp8(expert_x_fp8: torch.Tensor,
|
||||
num_experts = expert_x_fp8.size(0)
|
||||
|
||||
expert_x_fp32 = expert_x_fp8.to(torch.float32).view(
|
||||
num_experts, -1, DEEPEP_QUANT_BLOCK_SIZE)
|
||||
num_experts, -1, DEEPEP_QUANT_BLOCK_SIZE
|
||||
)
|
||||
expert_x_scales = expert_x_scales.view(num_experts, -1, 1)
|
||||
return (expert_x_fp32 * expert_x_scales).view(expert_x_fp8.size())
|
||||
|
||||
@@ -44,11 +52,13 @@ class DeepEPLLPrepareAndFinalize(mk.FusedMoEPrepareAndFinalize):
|
||||
# specific hidden sizes.
|
||||
SUPPORTED_HIDDEN_SIZES = [2048, 2560, 4096, 5120, 6144, 7168]
|
||||
|
||||
def __init__(self,
|
||||
buffer: deep_ep.Buffer,
|
||||
max_tokens_per_rank: int,
|
||||
num_dispatchers: int,
|
||||
use_fp8_dispatch: bool = False):
|
||||
def __init__(
|
||||
self,
|
||||
buffer: deep_ep.Buffer,
|
||||
max_tokens_per_rank: int,
|
||||
num_dispatchers: int,
|
||||
use_fp8_dispatch: bool = False,
|
||||
):
|
||||
super().__init__()
|
||||
|
||||
self.buffer = buffer
|
||||
@@ -79,10 +89,12 @@ class DeepEPLLPrepareAndFinalize(mk.FusedMoEPrepareAndFinalize):
|
||||
a1_dtype: torch.dtype,
|
||||
quant_config: FusedMoEQuantConfig,
|
||||
) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
|
||||
|
||||
if self.use_fp8_dispatch:
|
||||
block_k = quant_config.block_shape[
|
||||
1] if quant_config.block_shape is not None else None
|
||||
block_k = (
|
||||
quant_config.block_shape[1]
|
||||
if quant_config.block_shape is not None
|
||||
else None
|
||||
)
|
||||
if block_k == DEEPEP_QUANT_BLOCK_SIZE:
|
||||
# DeepEP kernels did the quantization for us.
|
||||
x, x_scales = x
|
||||
@@ -99,8 +111,12 @@ class DeepEPLLPrepareAndFinalize(mk.FusedMoEPrepareAndFinalize):
|
||||
# TODO (varun): Optimization - Use a batched version of quant
|
||||
x = x.view((-1, hidden_dim))
|
||||
x, x_scales = moe_kernel_quantize_input(
|
||||
x, quant_config.a1_scale, quant_config.quant_dtype,
|
||||
quant_config.per_act_token_quant, quant_config.block_shape)
|
||||
x,
|
||||
quant_config.a1_scale,
|
||||
quant_config.quant_dtype,
|
||||
quant_config.per_act_token_quant,
|
||||
quant_config.block_shape,
|
||||
)
|
||||
x = x.view((num_experts, -1, hidden_dim))
|
||||
|
||||
if quant_config.quant_dtype is not None:
|
||||
@@ -122,47 +138,62 @@ class DeepEPLLPrepareAndFinalize(mk.FusedMoEPrepareAndFinalize):
|
||||
apply_router_weight_on_input: bool,
|
||||
quant_config: FusedMoEQuantConfig,
|
||||
) -> tuple[Callable, mk.ReceiverType]:
|
||||
|
||||
hidden_size = a1.size(1)
|
||||
assert hidden_size in self.SUPPORTED_HIDDEN_SIZES, \
|
||||
(f"Hidden Size {hidden_size} not in supported list of hidden sizes"
|
||||
f"{self.SUPPORTED_HIDDEN_SIZES}")
|
||||
assert hidden_size in self.SUPPORTED_HIDDEN_SIZES, (
|
||||
f"Hidden Size {hidden_size} not in supported list of hidden sizes"
|
||||
f"{self.SUPPORTED_HIDDEN_SIZES}"
|
||||
)
|
||||
|
||||
a2a_idx = dbo_current_ubatch_id()
|
||||
|
||||
if self.use_fp8_dispatch:
|
||||
assert hidden_size % 128 == 0, \
|
||||
"DeepEP kernels quantize the inputs in blocks of shape 128"
|
||||
assert hidden_size % 128 == 0, (
|
||||
"DeepEP kernels quantize the inputs in blocks of shape 128"
|
||||
)
|
||||
|
||||
has_per_token_scales = quant_config.a1_scale.numel(
|
||||
) != 1 if quant_config.a1_scale is not None else (
|
||||
quant_config.a2_scale.numel() != 1
|
||||
if quant_config.a2_scale is not None else False)
|
||||
has_per_token_scales = (
|
||||
quant_config.a1_scale.numel() != 1
|
||||
if quant_config.a1_scale is not None
|
||||
else (
|
||||
quant_config.a2_scale.numel() != 1
|
||||
if quant_config.a2_scale is not None
|
||||
else False
|
||||
)
|
||||
)
|
||||
assert not has_per_token_scales, (
|
||||
"low_latency kernels doesn't support dispatching per-token scales")
|
||||
"low_latency kernels doesn't support dispatching per-token scales"
|
||||
)
|
||||
|
||||
if apply_router_weight_on_input:
|
||||
topk = topk_ids.size(1)
|
||||
# TODO: this only works for topK=1, will need to update for topK>1
|
||||
assert topk == 1, (
|
||||
"apply_router_weight_on_input is only implemented for topk=1")
|
||||
"apply_router_weight_on_input is only implemented for topk=1"
|
||||
)
|
||||
a1 = a1 * topk_weights.to(a1.dtype)
|
||||
|
||||
# Dispatch
|
||||
expert_x, expert_num_tokens, handle, _, hook= \
|
||||
self.buffer.low_latency_dispatch(a1,
|
||||
topk_ids,
|
||||
self.max_tokens_per_rank,
|
||||
num_experts,
|
||||
use_fp8=self.use_fp8_dispatch,
|
||||
async_finish=False,
|
||||
return_recv_hook=True)
|
||||
expert_x, expert_num_tokens, handle, _, hook = self.buffer.low_latency_dispatch(
|
||||
a1,
|
||||
topk_ids,
|
||||
self.max_tokens_per_rank,
|
||||
num_experts,
|
||||
use_fp8=self.use_fp8_dispatch,
|
||||
async_finish=False,
|
||||
return_recv_hook=True,
|
||||
)
|
||||
self.handles[a2a_idx] = handle
|
||||
|
||||
return (
|
||||
hook,
|
||||
lambda: self._receiver(expert_x, expert_num_tokens, quant_config.
|
||||
a1_scale, a1.dtype, quant_config))
|
||||
lambda: self._receiver(
|
||||
expert_x,
|
||||
expert_num_tokens,
|
||||
quant_config.a1_scale,
|
||||
a1.dtype,
|
||||
quant_config,
|
||||
),
|
||||
)
|
||||
|
||||
def _receiver(
|
||||
self,
|
||||
@@ -172,11 +203,11 @@ class DeepEPLLPrepareAndFinalize(mk.FusedMoEPrepareAndFinalize):
|
||||
a1_dtype: torch.dtype,
|
||||
quant_config: FusedMoEQuantConfig,
|
||||
) -> mk.PrepareResultType:
|
||||
expert_x, expert_x_scale = self._do_quant(expert_x, a1_dtype,
|
||||
quant_config)
|
||||
expert_x, expert_x_scale = self._do_quant(expert_x, a1_dtype, quant_config)
|
||||
|
||||
expert_tokens_meta = mk.ExpertTokensMetadata(
|
||||
expert_num_tokens=expert_num_tokens, expert_num_tokens_cpu=None)
|
||||
expert_num_tokens=expert_num_tokens, expert_num_tokens_cpu=None
|
||||
)
|
||||
|
||||
return expert_x, expert_x_scale, expert_tokens_meta, None, None
|
||||
|
||||
@@ -190,10 +221,15 @@ class DeepEPLLPrepareAndFinalize(mk.FusedMoEPrepareAndFinalize):
|
||||
apply_router_weight_on_input: bool,
|
||||
quant_config: FusedMoEQuantConfig,
|
||||
) -> mk.PrepareResultType:
|
||||
hook, receiver = self.prepare_async(a1, topk_weights, topk_ids,
|
||||
num_experts, expert_map,
|
||||
apply_router_weight_on_input,
|
||||
quant_config)
|
||||
hook, receiver = self.prepare_async(
|
||||
a1,
|
||||
topk_weights,
|
||||
topk_ids,
|
||||
num_experts,
|
||||
expert_map,
|
||||
apply_router_weight_on_input,
|
||||
quant_config,
|
||||
)
|
||||
hook()
|
||||
return receiver()
|
||||
|
||||
@@ -207,9 +243,9 @@ class DeepEPLLPrepareAndFinalize(mk.FusedMoEPrepareAndFinalize):
|
||||
weight_and_reduce_impl: mk.TopKWeightAndReduce,
|
||||
do_async: bool,
|
||||
) -> tuple[Callable, Callable]:
|
||||
assert isinstance(
|
||||
weight_and_reduce_impl, TopKWeightAndReduceDelegate
|
||||
), ("Weight application and reduction happens in the combine kernel.")
|
||||
assert isinstance(weight_and_reduce_impl, TopKWeightAndReduceDelegate), (
|
||||
"Weight application and reduction happens in the combine kernel."
|
||||
)
|
||||
|
||||
a2a_idx = dbo_current_ubatch_id()
|
||||
do_recv_hook = dbo_enabled() or do_async
|
||||
@@ -231,7 +267,8 @@ class DeepEPLLPrepareAndFinalize(mk.FusedMoEPrepareAndFinalize):
|
||||
async_finish=False,
|
||||
zero_copy=False,
|
||||
return_recv_hook=do_recv_hook,
|
||||
out=output)
|
||||
out=output,
|
||||
)
|
||||
|
||||
return recv_hook, lambda: None
|
||||
|
||||
|
||||
@@ -8,40 +8,47 @@ import vllm.model_executor.layers.fused_moe.modular_kernel as mk
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.fused_moe.config import FusedMoEQuantConfig
|
||||
from vllm.model_executor.layers.fused_moe.flashinfer_cutlass_prepare_finalize import ( # noqa: E501
|
||||
create_flashinfer_prepare_finalize)
|
||||
create_flashinfer_prepare_finalize,
|
||||
)
|
||||
from vllm.model_executor.layers.fused_moe.topk_weight_and_reduce import (
|
||||
TopKWeightAndReduceNoOP)
|
||||
from vllm.utils.flashinfer import (flashinfer_cutlass_fused_moe,
|
||||
has_flashinfer_cutlass_fused_moe)
|
||||
TopKWeightAndReduceNoOP,
|
||||
)
|
||||
from vllm.utils.flashinfer import (
|
||||
flashinfer_cutlass_fused_moe,
|
||||
has_flashinfer_cutlass_fused_moe,
|
||||
)
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def is_valid_flashinfer_cutlass_fused_moe(hidden_states: torch.Tensor,
|
||||
w1: torch.Tensor,
|
||||
w2: torch.Tensor) -> bool:
|
||||
def is_valid_flashinfer_cutlass_fused_moe(
|
||||
hidden_states: torch.Tensor, w1: torch.Tensor, w2: torch.Tensor
|
||||
) -> bool:
|
||||
"""
|
||||
Check if the given problem size is supported by the FlashInfer CUTLASS MoE
|
||||
kernel.
|
||||
"""
|
||||
if not has_flashinfer_cutlass_fused_moe():
|
||||
logger.debug_once("FlashInferExperts disabled: "
|
||||
"flashinfer_cutlass_fused_moe not available.")
|
||||
logger.debug_once(
|
||||
"FlashInferExperts disabled: flashinfer_cutlass_fused_moe not available."
|
||||
)
|
||||
return False
|
||||
# Data type checks
|
||||
if (w1.dtype != torch.uint8 or w2.dtype != torch.uint8
|
||||
or hidden_states.dtype
|
||||
not in [torch.float32, torch.float16, torch.bfloat16]):
|
||||
if (
|
||||
w1.dtype != torch.uint8
|
||||
or w2.dtype != torch.uint8
|
||||
or hidden_states.dtype not in [torch.float32, torch.float16, torch.bfloat16]
|
||||
):
|
||||
logger.debug_once(
|
||||
"FlashInferExperts disabled: w1/w2 must be torch.uint8 "
|
||||
f"(got w1={w1.dtype}, w2={w2.dtype}), hidden_states must be "
|
||||
f"float32, float16, or bfloat16 (got {hidden_states.dtype}).")
|
||||
f"float32, float16, or bfloat16 (got {hidden_states.dtype})."
|
||||
)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
class FlashInferExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
out_dtype: torch.dtype,
|
||||
@@ -52,10 +59,10 @@ class FlashInferExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
tp_size: int = 1,
|
||||
):
|
||||
super().__init__(quant_config)
|
||||
assert quant_config.quant_dtype in (
|
||||
"nvfp4", torch.float8_e4m3fn,
|
||||
None), ("Only nvfp4, fp8, bfloat16 and"
|
||||
" float16 quantization are currently supported.")
|
||||
assert quant_config.quant_dtype in ("nvfp4", torch.float8_e4m3fn, None), (
|
||||
"Only nvfp4, fp8, bfloat16 and"
|
||||
" float16 quantization are currently supported."
|
||||
)
|
||||
self.ep_rank = ep_rank
|
||||
self.ep_size = ep_size
|
||||
self.tp_rank = tp_rank
|
||||
@@ -64,10 +71,12 @@ class FlashInferExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
|
||||
@property
|
||||
def activation_formats(
|
||||
self
|
||||
self,
|
||||
) -> tuple[mk.FusedMoEActivationFormat, mk.FusedMoEActivationFormat]:
|
||||
return (mk.FusedMoEActivationFormat.Standard,
|
||||
mk.FusedMoEActivationFormat.Standard)
|
||||
return (
|
||||
mk.FusedMoEActivationFormat.Standard,
|
||||
mk.FusedMoEActivationFormat.Standard,
|
||||
)
|
||||
|
||||
def supports_expert_map(self) -> bool:
|
||||
return False
|
||||
@@ -110,10 +119,8 @@ class FlashInferExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
of each tuple must be the number of tokens.
|
||||
"""
|
||||
aq_m, aq_n = aq.shape
|
||||
workspace2 = (0, )
|
||||
output_shape = (aq_m,
|
||||
aq_n * 2) if self.quant_dtype == "nvfp4" else (aq_m,
|
||||
aq_n)
|
||||
workspace2 = (0,)
|
||||
output_shape = (aq_m, aq_n * 2) if self.quant_dtype == "nvfp4" else (aq_m, aq_n)
|
||||
workspace_dtype = a.dtype
|
||||
workspace1 = output_shape
|
||||
# The workspace is determined by `aq`, since it comes after any
|
||||
@@ -138,13 +145,16 @@ class FlashInferExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
expert_tokens_meta: Optional[mk.ExpertTokensMetadata],
|
||||
apply_router_weight_on_input: Optional[bool],
|
||||
):
|
||||
|
||||
assert activation == "silu", ("Only activation silu is supported in "
|
||||
"FlashInferExperts")
|
||||
assert activation == "silu", (
|
||||
"Only activation silu is supported in FlashInferExperts"
|
||||
)
|
||||
|
||||
if self.quant_dtype == torch.float8_e4m3fn:
|
||||
quant_scales = [
|
||||
self.g1_alphas, self.a2_gscale, self.g2_alphas, self.a1_gscale
|
||||
self.g1_alphas,
|
||||
self.a2_gscale,
|
||||
self.g2_alphas,
|
||||
self.a1_gscale,
|
||||
]
|
||||
|
||||
a1q_scale = None # not passing input_sf in fp8
|
||||
@@ -153,8 +163,8 @@ class FlashInferExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
elif self.quant_dtype == "nvfp4":
|
||||
# Ensure w1_scale and w2_scale are not None before calling view
|
||||
assert self.w1_scale is not None and self.w2_scale is not None, (
|
||||
"w1_scale and w2_scale must not "
|
||||
"be None for FlashInferExperts")
|
||||
"w1_scale and w2_scale must not be None for FlashInferExperts"
|
||||
)
|
||||
# Flashinfer CUTLASS kernel takes scalar global scales,
|
||||
# min because inv_scale.
|
||||
quant_scales = [
|
||||
@@ -209,7 +219,8 @@ def flashinfer_cutlass_moe_fp4(
|
||||
FlashInferExperts(
|
||||
out_dtype=hidden_states.dtype,
|
||||
quant_config=quant_config,
|
||||
))
|
||||
),
|
||||
)
|
||||
|
||||
return fused_experts(
|
||||
hidden_states=hidden_states,
|
||||
@@ -252,7 +263,8 @@ def flashinfer_cutlass_moe(
|
||||
tp_size=tp_size,
|
||||
ep_rank=ep_rank,
|
||||
ep_size=ep_size,
|
||||
))
|
||||
),
|
||||
)
|
||||
|
||||
return fused_experts(
|
||||
hidden_states=hidden_states,
|
||||
|
||||
@@ -7,11 +7,11 @@ import torch
|
||||
import vllm.model_executor.layers.fused_moe.modular_kernel as mk
|
||||
from vllm.distributed import get_dp_group, get_ep_group
|
||||
from vllm.distributed.device_communicators.base_device_communicator import (
|
||||
All2AllManagerBase)
|
||||
All2AllManagerBase,
|
||||
)
|
||||
from vllm.forward_context import get_forward_context
|
||||
from vllm.model_executor.layers.fused_moe.config import FusedMoEQuantConfig
|
||||
from vllm.model_executor.layers.fused_moe.utils import (
|
||||
moe_kernel_quantize_input)
|
||||
from vllm.model_executor.layers.fused_moe.utils import moe_kernel_quantize_input
|
||||
from vllm.utils.flashinfer import nvfp4_block_scale_interleave
|
||||
|
||||
|
||||
@@ -55,13 +55,13 @@ class FlashInferCutlassMoEPrepareAndFinalize(mk.FusedMoEPrepareAndFinalize):
|
||||
"""Apply router weight on input if needed."""
|
||||
if apply_router_weight_on_input:
|
||||
topk = topk_ids.size(1)
|
||||
assert topk == 1, \
|
||||
assert topk == 1, (
|
||||
"apply_router_weight_on_input is only implemented for topk=1"
|
||||
)
|
||||
a1.mul_(topk_weights.to(a1.dtype))
|
||||
|
||||
|
||||
class FlashInferAllToAllMoEPrepareAndFinalize(
|
||||
FlashInferCutlassMoEPrepareAndFinalize):
|
||||
class FlashInferAllToAllMoEPrepareAndFinalize(FlashInferCutlassMoEPrepareAndFinalize):
|
||||
"""FlashInfer implementation using AllToAll communication."""
|
||||
|
||||
def __init__(
|
||||
@@ -75,8 +75,7 @@ class FlashInferAllToAllMoEPrepareAndFinalize(
|
||||
# Initialize all2all_manager only for DP case
|
||||
self.all2all_manager = None
|
||||
if self.use_dp:
|
||||
self.all2all_manager = get_ep_group(
|
||||
).device_communicator.all2all_manager
|
||||
self.all2all_manager = get_ep_group().device_communicator.all2all_manager
|
||||
|
||||
def prepare(
|
||||
self,
|
||||
@@ -88,9 +87,9 @@ class FlashInferAllToAllMoEPrepareAndFinalize(
|
||||
apply_router_weight_on_input: bool,
|
||||
quant_config: FusedMoEQuantConfig,
|
||||
) -> mk.PrepareResultType:
|
||||
|
||||
self._apply_router_weight_on_input(a1, topk_weights, topk_ids,
|
||||
apply_router_weight_on_input)
|
||||
self._apply_router_weight_on_input(
|
||||
a1, topk_weights, topk_ids, apply_router_weight_on_input
|
||||
)
|
||||
|
||||
if not self.use_dp:
|
||||
# Non-DP case: standard quantization
|
||||
@@ -107,18 +106,19 @@ class FlashInferAllToAllMoEPrepareAndFinalize(
|
||||
global_num_tokens_cpu = get_local_sizes()
|
||||
top_k = topk_ids.size(1)
|
||||
|
||||
(self.alltoall_info, topk_ids, topk_weights, a1q,
|
||||
a1q_scale) = flashinfer_alltoall_dispatch(
|
||||
self.all2all_manager,
|
||||
global_num_tokens_cpu,
|
||||
a1,
|
||||
quant_config.a1_gscale,
|
||||
topk_ids,
|
||||
topk_weights,
|
||||
top_k,
|
||||
num_experts,
|
||||
quant_config,
|
||||
)
|
||||
(self.alltoall_info, topk_ids, topk_weights, a1q, a1q_scale) = (
|
||||
flashinfer_alltoall_dispatch(
|
||||
self.all2all_manager,
|
||||
global_num_tokens_cpu,
|
||||
a1,
|
||||
quant_config.a1_gscale,
|
||||
topk_ids,
|
||||
topk_weights,
|
||||
top_k,
|
||||
num_experts,
|
||||
quant_config,
|
||||
)
|
||||
)
|
||||
|
||||
return a1q, a1q_scale, None, topk_ids, topk_weights
|
||||
|
||||
@@ -144,9 +144,7 @@ class FlashInferAllToAllMoEPrepareAndFinalize(
|
||||
output.copy_(fused_expert_output)
|
||||
|
||||
|
||||
class FlashInferAllGatherMoEPrepareAndFinalize(
|
||||
FlashInferCutlassMoEPrepareAndFinalize):
|
||||
|
||||
class FlashInferAllGatherMoEPrepareAndFinalize(FlashInferCutlassMoEPrepareAndFinalize):
|
||||
def __init__(
|
||||
self,
|
||||
use_dp: bool,
|
||||
@@ -164,9 +162,9 @@ class FlashInferAllGatherMoEPrepareAndFinalize(
|
||||
apply_router_weight_on_input: bool,
|
||||
quant_config: FusedMoEQuantConfig,
|
||||
) -> mk.PrepareResultType:
|
||||
|
||||
self._apply_router_weight_on_input(a1, topk_weights, topk_ids,
|
||||
apply_router_weight_on_input)
|
||||
self._apply_router_weight_on_input(
|
||||
a1, topk_weights, topk_ids, apply_router_weight_on_input
|
||||
)
|
||||
|
||||
a1q, a1q_scale = moe_kernel_quantize_input(
|
||||
a1,
|
||||
@@ -177,12 +175,11 @@ class FlashInferAllGatherMoEPrepareAndFinalize(
|
||||
is_fp4_scale_swizzled=not self.use_dp,
|
||||
)
|
||||
if self.use_dp:
|
||||
topk_weights, topk_ids, a1q, a1q_scale = \
|
||||
get_dp_group().all_gatherv(
|
||||
[topk_weights, topk_ids, a1q, a1q_scale],
|
||||
dim=0,
|
||||
sizes=get_local_sizes(),
|
||||
)
|
||||
topk_weights, topk_ids, a1q, a1q_scale = get_dp_group().all_gatherv(
|
||||
[topk_weights, topk_ids, a1q, a1q_scale],
|
||||
dim=0,
|
||||
sizes=get_local_sizes(),
|
||||
)
|
||||
if quant_config.quant_dtype == "nvfp4":
|
||||
a1q_scale = nvfp4_block_scale_interleave(a1q_scale)
|
||||
|
||||
@@ -197,10 +194,10 @@ class FlashInferAllGatherMoEPrepareAndFinalize(
|
||||
apply_router_weight_on_input: bool,
|
||||
weight_and_reduce_impl: mk.TopKWeightAndReduce,
|
||||
) -> None:
|
||||
|
||||
if self.use_dp:
|
||||
fused_expert_output = get_dp_group().reduce_scatterv(
|
||||
fused_expert_output, dim=0, sizes=get_local_sizes())
|
||||
fused_expert_output, dim=0, sizes=get_local_sizes()
|
||||
)
|
||||
output.copy_(fused_expert_output)
|
||||
|
||||
|
||||
@@ -216,13 +213,16 @@ def flashinfer_alltoall_dispatch(
|
||||
quant_config: FusedMoEQuantConfig,
|
||||
):
|
||||
from flashinfer.comm.trtllm_alltoall import MnnvlMoe
|
||||
assert (all2all_manager.ensure_alltoall_workspace_initialized()
|
||||
), "FlashInfer AllToAll workspace not available"
|
||||
|
||||
assert all2all_manager.ensure_alltoall_workspace_initialized(), (
|
||||
"FlashInfer AllToAll workspace not available"
|
||||
)
|
||||
|
||||
ep_rank = all2all_manager.rank
|
||||
ep_size = all2all_manager.world_size
|
||||
max_num_token = max(global_num_tokens_cpu
|
||||
) if global_num_tokens_cpu is not None else x.shape[0]
|
||||
max_num_token = (
|
||||
max(global_num_tokens_cpu) if global_num_tokens_cpu is not None else x.shape[0]
|
||||
)
|
||||
alltoall_info, topk_ids, topk_weights, _ = (
|
||||
MnnvlMoe.mnnvl_moe_alltoallv_prepare_without_allgather(
|
||||
topk_ids,
|
||||
@@ -235,7 +235,8 @@ def flashinfer_alltoall_dispatch(
|
||||
num_experts,
|
||||
num_experts,
|
||||
top_k,
|
||||
))
|
||||
)
|
||||
)
|
||||
|
||||
x, x_sf = moe_kernel_quantize_input(
|
||||
x,
|
||||
@@ -272,8 +273,10 @@ def flashinfer_alltoall_combine(
|
||||
alltoall_info,
|
||||
):
|
||||
from flashinfer.comm.trtllm_alltoall import MnnvlMoe
|
||||
assert (all2all_manager.ensure_alltoall_workspace_initialized()
|
||||
), "FlashInfer AllToAll workspace not available"
|
||||
|
||||
assert all2all_manager.ensure_alltoall_workspace_initialized(), (
|
||||
"FlashInfer AllToAll workspace not available"
|
||||
)
|
||||
return MnnvlMoe.mnnvl_moe_alltoallv_combine(
|
||||
output,
|
||||
alltoall_info,
|
||||
|
||||
@@ -1,37 +1,42 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from typing import List # noqa: UP035
|
||||
from typing import Optional
|
||||
from typing import (
|
||||
List, # noqa: UP035
|
||||
Optional,
|
||||
)
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.model_executor.layers.fused_moe.utils import (
|
||||
moe_kernel_quantize_input)
|
||||
from vllm.model_executor.layers.fused_moe.utils import moe_kernel_quantize_input
|
||||
from vllm.model_executor.layers.quantization.utils.flashinfer_utils import (
|
||||
calculate_tile_tokens_dim)
|
||||
calculate_tile_tokens_dim,
|
||||
)
|
||||
from vllm.model_executor.layers.quantization.utils.fp8_utils import (
|
||||
per_token_group_quant_fp8)
|
||||
per_token_group_quant_fp8,
|
||||
)
|
||||
from vllm.utils import direct_register_custom_op
|
||||
|
||||
|
||||
def flashinfer_fused_moe_blockscale_fp8(
|
||||
routing_logits: torch.Tensor,
|
||||
routing_bias: torch.Tensor,
|
||||
x: torch.Tensor,
|
||||
w13_weight: torch.Tensor,
|
||||
w13_weight_scale_inv: torch.Tensor,
|
||||
w2_weight: torch.Tensor,
|
||||
w2_weight_scale_inv: torch.Tensor,
|
||||
global_num_experts: int,
|
||||
top_k: int,
|
||||
num_expert_group: int,
|
||||
topk_group: int,
|
||||
intermediate_size: int,
|
||||
expert_offset: int,
|
||||
local_num_experts: int,
|
||||
block_shape: List[int], #noqa: UP006
|
||||
routed_scaling: float = 1.0) -> torch.Tensor:
|
||||
routing_logits: torch.Tensor,
|
||||
routing_bias: torch.Tensor,
|
||||
x: torch.Tensor,
|
||||
w13_weight: torch.Tensor,
|
||||
w13_weight_scale_inv: torch.Tensor,
|
||||
w2_weight: torch.Tensor,
|
||||
w2_weight_scale_inv: torch.Tensor,
|
||||
global_num_experts: int,
|
||||
top_k: int,
|
||||
num_expert_group: int,
|
||||
topk_group: int,
|
||||
intermediate_size: int,
|
||||
expert_offset: int,
|
||||
local_num_experts: int,
|
||||
block_shape: List[int], # noqa: UP006
|
||||
routed_scaling: float = 1.0,
|
||||
) -> torch.Tensor:
|
||||
from vllm.utils.flashinfer import flashinfer_trtllm_fp8_block_scale_moe
|
||||
|
||||
assert top_k <= global_num_experts
|
||||
assert top_k <= 8
|
||||
assert topk_group <= 4
|
||||
@@ -63,30 +68,32 @@ def flashinfer_fused_moe_blockscale_fp8(
|
||||
local_expert_offset=expert_offset,
|
||||
local_num_experts=local_num_experts,
|
||||
routed_scaling_factor=routed_scaling,
|
||||
tile_tokens_dim=calculate_tile_tokens_dim(x.shape[0], top_k,
|
||||
global_num_experts),
|
||||
tile_tokens_dim=calculate_tile_tokens_dim(
|
||||
x.shape[0], top_k, global_num_experts
|
||||
),
|
||||
routing_method_type=2, # DeepSeek-styled routing method
|
||||
use_shuffled_weight=False,
|
||||
)
|
||||
|
||||
|
||||
def flashinfer_fused_moe_blockscale_fp8_fake(
|
||||
routing_logits: torch.Tensor,
|
||||
routing_bias: torch.Tensor,
|
||||
x: torch.Tensor,
|
||||
w13_weight: torch.Tensor,
|
||||
w13_weight_scale_inv: torch.Tensor,
|
||||
w2_weight: torch.Tensor,
|
||||
w2_weight_scale_inv: torch.Tensor,
|
||||
global_num_experts: int,
|
||||
top_k: int,
|
||||
num_expert_group: int,
|
||||
topk_group: int,
|
||||
intermediate_size: int,
|
||||
expert_offset: int,
|
||||
local_num_experts: int,
|
||||
block_shape: list[int],
|
||||
routed_scaling: float = 1.0) -> torch.Tensor:
|
||||
routing_logits: torch.Tensor,
|
||||
routing_bias: torch.Tensor,
|
||||
x: torch.Tensor,
|
||||
w13_weight: torch.Tensor,
|
||||
w13_weight_scale_inv: torch.Tensor,
|
||||
w2_weight: torch.Tensor,
|
||||
w2_weight_scale_inv: torch.Tensor,
|
||||
global_num_experts: int,
|
||||
top_k: int,
|
||||
num_expert_group: int,
|
||||
topk_group: int,
|
||||
intermediate_size: int,
|
||||
expert_offset: int,
|
||||
local_num_experts: int,
|
||||
block_shape: list[int],
|
||||
routed_scaling: float = 1.0,
|
||||
) -> torch.Tensor:
|
||||
return torch.empty_like(x)
|
||||
|
||||
|
||||
@@ -95,30 +102,31 @@ direct_register_custom_op(
|
||||
op_name="flashinfer_fused_moe_blockscale_fp8",
|
||||
op_func=flashinfer_fused_moe_blockscale_fp8,
|
||||
fake_impl=flashinfer_fused_moe_blockscale_fp8_fake,
|
||||
tags=(torch.Tag.needs_fixed_stride_order, ),
|
||||
tags=(torch.Tag.needs_fixed_stride_order,),
|
||||
)
|
||||
|
||||
|
||||
def flashinfer_fused_moe_per_tensor_scale_fp8(
|
||||
routing_logits: torch.Tensor,
|
||||
routing_bias: Optional[torch.Tensor],
|
||||
hidden_states: torch.Tensor,
|
||||
input_scale: torch.Tensor,
|
||||
gemm1_weights: torch.Tensor,
|
||||
gemm2_weights: torch.Tensor,
|
||||
output1_scales_scalar: torch.Tensor,
|
||||
output1_scales_gate_scalar: torch.Tensor,
|
||||
output2_scales_scalar: torch.Tensor,
|
||||
num_experts: int,
|
||||
top_k: int,
|
||||
num_expert_group: Optional[int],
|
||||
topk_group: Optional[int],
|
||||
intermediate_size: int,
|
||||
local_expert_offset: int,
|
||||
local_num_experts: int,
|
||||
use_routing_scales_on_input: bool,
|
||||
routing_method_type: int,
|
||||
routed_scaling_factor: float = 1.0) -> torch.Tensor:
|
||||
routing_logits: torch.Tensor,
|
||||
routing_bias: Optional[torch.Tensor],
|
||||
hidden_states: torch.Tensor,
|
||||
input_scale: torch.Tensor,
|
||||
gemm1_weights: torch.Tensor,
|
||||
gemm2_weights: torch.Tensor,
|
||||
output1_scales_scalar: torch.Tensor,
|
||||
output1_scales_gate_scalar: torch.Tensor,
|
||||
output2_scales_scalar: torch.Tensor,
|
||||
num_experts: int,
|
||||
top_k: int,
|
||||
num_expert_group: Optional[int],
|
||||
topk_group: Optional[int],
|
||||
intermediate_size: int,
|
||||
local_expert_offset: int,
|
||||
local_num_experts: int,
|
||||
use_routing_scales_on_input: bool,
|
||||
routing_method_type: int,
|
||||
routed_scaling_factor: float = 1.0,
|
||||
) -> torch.Tensor:
|
||||
num_expert_group = num_expert_group if num_expert_group is not None else 0
|
||||
topk_group = topk_group if topk_group is not None else 0
|
||||
|
||||
@@ -126,10 +134,11 @@ def flashinfer_fused_moe_per_tensor_scale_fp8(
|
||||
hidden_states,
|
||||
input_scale,
|
||||
quant_dtype=torch.float8_e4m3fn,
|
||||
per_act_token_quant=False)
|
||||
per_act_token_quant=False,
|
||||
)
|
||||
|
||||
from vllm.utils.flashinfer import flashinfer_trtllm_fp8_per_tensor_scale_moe
|
||||
|
||||
from vllm.utils.flashinfer import (
|
||||
flashinfer_trtllm_fp8_per_tensor_scale_moe)
|
||||
return flashinfer_trtllm_fp8_per_tensor_scale_moe(
|
||||
routing_logits=routing_logits,
|
||||
routing_bias=routing_bias,
|
||||
@@ -148,31 +157,34 @@ def flashinfer_fused_moe_per_tensor_scale_fp8(
|
||||
local_num_experts=local_num_experts,
|
||||
routed_scaling_factor=routed_scaling_factor,
|
||||
use_routing_scales_on_input=use_routing_scales_on_input,
|
||||
tile_tokens_dim=calculate_tile_tokens_dim(hidden_states.shape[0],
|
||||
top_k, num_experts),
|
||||
routing_method_type=routing_method_type)
|
||||
tile_tokens_dim=calculate_tile_tokens_dim(
|
||||
hidden_states.shape[0], top_k, num_experts
|
||||
),
|
||||
routing_method_type=routing_method_type,
|
||||
)
|
||||
|
||||
|
||||
def flashinfer_fused_moe_per_tensor_scale_fp8_fake(
|
||||
routing_logits: torch.Tensor,
|
||||
routing_bias: Optional[torch.Tensor],
|
||||
hidden_states: torch.Tensor,
|
||||
input_scale: torch.Tensor,
|
||||
gemm1_weights: torch.Tensor,
|
||||
gemm2_weights: torch.Tensor,
|
||||
output1_scales_scalar: torch.Tensor,
|
||||
output1_scales_gate_scalar: torch.Tensor,
|
||||
output2_scales_scalar: torch.Tensor,
|
||||
num_experts: int,
|
||||
top_k: int,
|
||||
num_expert_group: Optional[int],
|
||||
topk_group: Optional[int],
|
||||
intermediate_size: int,
|
||||
local_expert_offset: int,
|
||||
local_num_experts: int,
|
||||
use_routing_scales_on_input: bool,
|
||||
routing_method_type: int,
|
||||
routed_scaling_factor: float = 1.0) -> torch.Tensor:
|
||||
routing_logits: torch.Tensor,
|
||||
routing_bias: Optional[torch.Tensor],
|
||||
hidden_states: torch.Tensor,
|
||||
input_scale: torch.Tensor,
|
||||
gemm1_weights: torch.Tensor,
|
||||
gemm2_weights: torch.Tensor,
|
||||
output1_scales_scalar: torch.Tensor,
|
||||
output1_scales_gate_scalar: torch.Tensor,
|
||||
output2_scales_scalar: torch.Tensor,
|
||||
num_experts: int,
|
||||
top_k: int,
|
||||
num_expert_group: Optional[int],
|
||||
topk_group: Optional[int],
|
||||
intermediate_size: int,
|
||||
local_expert_offset: int,
|
||||
local_num_experts: int,
|
||||
use_routing_scales_on_input: bool,
|
||||
routing_method_type: int,
|
||||
routed_scaling_factor: float = 1.0,
|
||||
) -> torch.Tensor:
|
||||
return torch.empty_like(hidden_states)
|
||||
|
||||
|
||||
@@ -182,5 +194,5 @@ direct_register_custom_op(
|
||||
op_func=flashinfer_fused_moe_per_tensor_scale_fp8,
|
||||
mutates_args=["hidden_states"],
|
||||
fake_impl=flashinfer_fused_moe_per_tensor_scale_fp8_fake,
|
||||
tags=(torch.Tag.needs_fixed_stride_order, ),
|
||||
tags=(torch.Tag.needs_fixed_stride_order,),
|
||||
)
|
||||
|
||||
@@ -1,21 +1,25 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Fused batched MoE kernel."""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
import torch
|
||||
|
||||
import vllm.model_executor.layers.fused_moe.modular_kernel as mk
|
||||
from vllm.model_executor.layers.fused_moe.config import FusedMoEQuantConfig
|
||||
from vllm.model_executor.layers.fused_moe.fused_moe import (
|
||||
try_get_optimal_moe_config)
|
||||
from vllm.model_executor.layers.fused_moe.fused_moe import try_get_optimal_moe_config
|
||||
from vllm.model_executor.layers.fused_moe.topk_weight_and_reduce import (
|
||||
TopKWeightAndReduceDelegate, TopKWeightAndReduceNaiveBatched)
|
||||
TopKWeightAndReduceDelegate,
|
||||
TopKWeightAndReduceNaiveBatched,
|
||||
)
|
||||
from vllm.model_executor.layers.fused_moe.utils import (
|
||||
_resize_cache, moe_kernel_quantize_input, normalize_batched_scales_shape,
|
||||
normalize_scales_shape)
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import (
|
||||
group_broadcast)
|
||||
_resize_cache,
|
||||
moe_kernel_quantize_input,
|
||||
normalize_batched_scales_shape,
|
||||
normalize_scales_shape,
|
||||
)
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import group_broadcast
|
||||
from vllm.triton_utils import tl, triton
|
||||
|
||||
|
||||
@@ -56,12 +60,12 @@ def moe_mmk(
|
||||
use_w8a16: tl.constexpr,
|
||||
per_act_token_quant: tl.constexpr,
|
||||
):
|
||||
|
||||
offs_k = tl.arange(0, BLOCK_K)
|
||||
|
||||
if use_w8a16:
|
||||
b_scale_ptrs = b_scale_ptr + expert_id * stride_bse + offs_n[
|
||||
None, :] * stride_bsn
|
||||
b_scale_ptrs = (
|
||||
b_scale_ptr + expert_id * stride_bse + offs_n[None, :] * stride_bsn
|
||||
)
|
||||
b_scale = tl.load(b_scale_ptrs)
|
||||
|
||||
if use_w8a8:
|
||||
@@ -94,9 +98,11 @@ def moe_mmk(
|
||||
for k in range(0, tl.cdiv(K, BLOCK_K)):
|
||||
# Load the next block of A and B, generate a mask by checking the
|
||||
# K dimension.
|
||||
a = tl.load(a_ptrs,
|
||||
mask=mask_m[:, None] & (offs_k[None, :] < K - k * BLOCK_K),
|
||||
other=0.0)
|
||||
a = tl.load(
|
||||
a_ptrs,
|
||||
mask=mask_m[:, None] & (offs_k[None, :] < K - k * BLOCK_K),
|
||||
other=0.0,
|
||||
)
|
||||
b = tl.load(b_ptrs, mask=offs_k[:, None] < K - k * BLOCK_K, other=0.0)
|
||||
# We accumulate along the K dimension.
|
||||
if use_w8a16:
|
||||
@@ -105,13 +111,12 @@ def moe_mmk(
|
||||
if group_k > 0 and group_n > 0:
|
||||
k_start = k * BLOCK_K
|
||||
offs_ks = k_start // group_k
|
||||
a_scale = tl.load(a_scale_ptrs + offs_ks * stride_ask,
|
||||
mask=mask_m,
|
||||
other=0.0)
|
||||
a_scale = tl.load(
|
||||
a_scale_ptrs + offs_ks * stride_ask, mask=mask_m, other=0.0
|
||||
)
|
||||
b_scale = tl.load(b_scale_ptrs + offs_ks * stride_bsk)
|
||||
|
||||
accumulator += tl.dot(a, b) * a_scale[:,
|
||||
None] * b_scale[None, :]
|
||||
accumulator += tl.dot(a, b) * a_scale[:, None] * b_scale[None, :]
|
||||
else:
|
||||
# acc used to enable fp8_fast_accum
|
||||
accumulator = tl.dot(a, b, acc=accumulator)
|
||||
@@ -137,9 +142,9 @@ def moe_mmk(
|
||||
|
||||
@triton.jit
|
||||
def expert_triton_kernel(
|
||||
a_ptr, #[max_tokens, K]
|
||||
b_ptr, #[K, N]
|
||||
c_ptr, #[max_tokens, N]
|
||||
a_ptr, # [max_tokens, K]
|
||||
b_ptr, # [K, N]
|
||||
c_ptr, # [max_tokens, N]
|
||||
expert_id,
|
||||
compute_type: tl.constexpr,
|
||||
# Dimensions
|
||||
@@ -177,7 +182,6 @@ def expert_triton_kernel(
|
||||
BLOCK_N: tl.constexpr,
|
||||
BLOCK_K: tl.constexpr,
|
||||
):
|
||||
|
||||
offs_m = tl.arange(0, BLOCK_M)
|
||||
offs_n = tl.arange(0, BLOCK_N) % N
|
||||
offs_k = tl.arange(0, BLOCK_K)
|
||||
@@ -221,7 +225,8 @@ def expert_triton_kernel(
|
||||
compute_type,
|
||||
use_fp8_w8a8,
|
||||
use_int8_w8a16,
|
||||
per_act_token_quant)
|
||||
per_act_token_quant,
|
||||
)
|
||||
|
||||
# store in C
|
||||
offs_cn = tl.arange(0, BLOCK_N)
|
||||
@@ -284,7 +289,7 @@ def batched_triton_kernel(
|
||||
|
||||
# axis 1 is M_blocks * N_blocks
|
||||
pid_mn = tl.program_id(axis=1)
|
||||
#num_pid_m = tl.cdiv(max_num_tokens, BLOCK_M)
|
||||
# num_pid_m = tl.cdiv(max_num_tokens, BLOCK_M)
|
||||
num_pid_n = tl.cdiv(N, BLOCK_N)
|
||||
pid_m = pid_mn // num_pid_n
|
||||
pid_n = pid_mn % num_pid_n
|
||||
@@ -300,8 +305,12 @@ def batched_triton_kernel(
|
||||
|
||||
a_ptr = a_ptr + expert_id * stride_ae + cta_m_start * stride_am
|
||||
b_ptr = b_ptr + expert_id * stride_be + cta_n_start * stride_bn
|
||||
c_ptr = (c_ptr + expert_id * stride_ce + cta_m_start * stride_cm +
|
||||
cta_n_start * stride_cn)
|
||||
c_ptr = (
|
||||
c_ptr
|
||||
+ expert_id * stride_ce
|
||||
+ cta_m_start * stride_cm
|
||||
+ cta_n_start * stride_cn
|
||||
)
|
||||
|
||||
offs_bn = (pid_n * BLOCK_N + tl.arange(0, BLOCK_N).to(tl.int64)) % N
|
||||
|
||||
@@ -350,50 +359,54 @@ def batched_triton_kernel(
|
||||
# Kernel config
|
||||
BLOCK_M,
|
||||
BLOCK_N,
|
||||
BLOCK_K)
|
||||
BLOCK_K,
|
||||
)
|
||||
|
||||
|
||||
def invoke_moe_batched_triton_kernel(
|
||||
A: torch.Tensor, # [E, max_tokens, K]
|
||||
B: torch.Tensor, # [E, N, K]
|
||||
C: torch.Tensor, # [E, max_tokens, N]
|
||||
expert_num_tokens: torch.Tensor, # [E]
|
||||
compute_type: tl.dtype,
|
||||
# Quantization data
|
||||
A_scale: Optional[torch.Tensor],
|
||||
B_scale: Optional[torch.Tensor],
|
||||
B_zp: torch.Tensor,
|
||||
# Quantization schemes
|
||||
use_fp8_w8a8: bool,
|
||||
use_int8_w8a16: bool,
|
||||
use_int4_w4a16: bool,
|
||||
config: dict[str, int],
|
||||
per_act_token_quant: bool,
|
||||
block_shape: Optional[list[int]] = None):
|
||||
|
||||
A: torch.Tensor, # [E, max_tokens, K]
|
||||
B: torch.Tensor, # [E, N, K]
|
||||
C: torch.Tensor, # [E, max_tokens, N]
|
||||
expert_num_tokens: torch.Tensor, # [E]
|
||||
compute_type: tl.dtype,
|
||||
# Quantization data
|
||||
A_scale: Optional[torch.Tensor],
|
||||
B_scale: Optional[torch.Tensor],
|
||||
B_zp: torch.Tensor,
|
||||
# Quantization schemes
|
||||
use_fp8_w8a8: bool,
|
||||
use_int8_w8a16: bool,
|
||||
use_int4_w4a16: bool,
|
||||
config: dict[str, int],
|
||||
per_act_token_quant: bool,
|
||||
block_shape: Optional[list[int]] = None,
|
||||
):
|
||||
assert not use_int4_w4a16
|
||||
max_num_tokens = A.size(1)
|
||||
K = A.size(2)
|
||||
N = C.size(2)
|
||||
|
||||
BLOCK_M = config['BLOCK_SIZE_M']
|
||||
BLOCK_N = config['BLOCK_SIZE_N']
|
||||
BLOCK_K = config['BLOCK_SIZE_K']
|
||||
BLOCK_M = config["BLOCK_SIZE_M"]
|
||||
BLOCK_N = config["BLOCK_SIZE_N"]
|
||||
BLOCK_K = config["BLOCK_SIZE_K"]
|
||||
|
||||
grid = (expert_num_tokens.size(0), triton.cdiv(max_num_tokens, BLOCK_M) *
|
||||
triton.cdiv(B.size(1), BLOCK_N))
|
||||
grid = (
|
||||
expert_num_tokens.size(0),
|
||||
triton.cdiv(max_num_tokens, BLOCK_M) * triton.cdiv(B.size(1), BLOCK_N),
|
||||
)
|
||||
|
||||
A_scale = normalize_batched_scales_shape(A_scale,
|
||||
expert_num_tokens.shape[0])
|
||||
A_scale = normalize_batched_scales_shape(A_scale, expert_num_tokens.shape[0])
|
||||
|
||||
if B_scale is not None and B_scale.ndim == 1:
|
||||
assert B_scale.numel() == expert_num_tokens.shape[0]
|
||||
B_scale = B_scale.view(-1, 1, 1)
|
||||
|
||||
assert A_scale is None or A_scale.ndim == 3, (
|
||||
f"{0 if A_scale is None else A_scale.shape}")
|
||||
f"{0 if A_scale is None else A_scale.shape}"
|
||||
)
|
||||
assert B_scale is None or B_scale.ndim == 1 or B_scale.ndim == 3, (
|
||||
f"{0 if B_scale is None else B_scale.shape}")
|
||||
f"{0 if B_scale is None else B_scale.shape}"
|
||||
)
|
||||
|
||||
if B_scale is not None:
|
||||
if B_scale.ndim == 1:
|
||||
@@ -459,7 +472,8 @@ def invoke_moe_batched_triton_kernel(
|
||||
# Kernel config
|
||||
BLOCK_M=BLOCK_M,
|
||||
BLOCK_N=BLOCK_N,
|
||||
BLOCK_K=BLOCK_K)
|
||||
BLOCK_K=BLOCK_K,
|
||||
)
|
||||
|
||||
|
||||
class BatchedPrepareAndFinalize(mk.FusedMoEPrepareAndFinalize):
|
||||
@@ -512,16 +526,15 @@ class BatchedPrepareAndFinalize(mk.FusedMoEPrepareAndFinalize):
|
||||
if apply_router_weight_on_input:
|
||||
topk = topk_ids.size(1)
|
||||
# TODO: this only works for topK=1, will need to update for topK>1
|
||||
assert topk == 1, \
|
||||
assert topk == 1, (
|
||||
"apply_router_weight_on_input is only implemented for topk=1"
|
||||
)
|
||||
a1.mul_(topk_weights.to(a1.dtype))
|
||||
|
||||
num_tokens, hidden_dim = a1.size()
|
||||
topk = topk_ids.size(1)
|
||||
|
||||
tokens_per_expert = torch.zeros(num_experts,
|
||||
dtype=torch.int,
|
||||
device=a1.device)
|
||||
tokens_per_expert = torch.zeros(num_experts, dtype=torch.int, device=a1.device)
|
||||
|
||||
num_local_experts = self.num_local_experts
|
||||
|
||||
@@ -533,15 +546,15 @@ class BatchedPrepareAndFinalize(mk.FusedMoEPrepareAndFinalize):
|
||||
b_a1 = torch.zeros(
|
||||
(num_local_experts, self.max_num_tokens, hidden_dim),
|
||||
dtype=b_type,
|
||||
device=a1.device)
|
||||
device=a1.device,
|
||||
)
|
||||
|
||||
if quant_config.is_quantized:
|
||||
scale_shape = quant_config.batched_scale_shape(
|
||||
num_local_experts, self.max_num_tokens, hidden_dim)
|
||||
num_local_experts, self.max_num_tokens, hidden_dim
|
||||
)
|
||||
|
||||
b_a1_scale = torch.empty(scale_shape,
|
||||
dtype=torch.float32,
|
||||
device=a1.device)
|
||||
b_a1_scale = torch.empty(scale_shape, dtype=torch.float32, device=a1.device)
|
||||
else:
|
||||
assert quant_config.a1_scale is None
|
||||
b_a1_scale = None
|
||||
@@ -558,11 +571,11 @@ class BatchedPrepareAndFinalize(mk.FusedMoEPrepareAndFinalize):
|
||||
continue
|
||||
idx = expert_id - first_expert
|
||||
tokens_per_expert[idx] = rows
|
||||
rhs = a1[:topks.numel()][topks]
|
||||
rhs = a1[: topks.numel()][topks]
|
||||
if quant_config.quant_dtype is not None:
|
||||
if a1_scale is not None:
|
||||
if quant_config.is_per_act_token:
|
||||
rhs_a1_scale = a1_scale[:topks.numel()][topks]
|
||||
rhs_a1_scale = a1_scale[: topks.numel()][topks]
|
||||
else:
|
||||
rhs_a1_scale = a1_scale
|
||||
else:
|
||||
@@ -578,14 +591,15 @@ class BatchedPrepareAndFinalize(mk.FusedMoEPrepareAndFinalize):
|
||||
if quant_config.is_per_act_token:
|
||||
b_a1_scale[idx, :rows] = b_s[:rows]
|
||||
else:
|
||||
b_a1_scale[idx, :b_s.shape[0]] = b_s
|
||||
b_a1_scale[idx, : b_s.shape[0]] = b_s
|
||||
else:
|
||||
b_a1[idx, :rows, :] = rhs
|
||||
|
||||
assert b_a1_scale is None or b_a1_scale.ndim == 3
|
||||
|
||||
expert_tokens_meta = mk.ExpertTokensMetadata(
|
||||
expert_num_tokens=tokens_per_expert, expert_num_tokens_cpu=None)
|
||||
expert_num_tokens=tokens_per_expert, expert_num_tokens_cpu=None
|
||||
)
|
||||
|
||||
return b_a1, b_a1_scale, expert_tokens_meta, None, None
|
||||
|
||||
@@ -632,10 +646,12 @@ class NaiveBatchedExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
|
||||
@property
|
||||
def activation_formats(
|
||||
self
|
||||
self,
|
||||
) -> tuple[mk.FusedMoEActivationFormat, mk.FusedMoEActivationFormat]:
|
||||
return (mk.FusedMoEActivationFormat.BatchedExperts,
|
||||
mk.FusedMoEActivationFormat.BatchedExperts)
|
||||
return (
|
||||
mk.FusedMoEActivationFormat.BatchedExperts,
|
||||
mk.FusedMoEActivationFormat.BatchedExperts,
|
||||
)
|
||||
|
||||
def supports_chunking(self) -> bool:
|
||||
return False
|
||||
@@ -670,8 +686,7 @@ class NaiveBatchedExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
def dequant(self, t: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:
|
||||
assert self.quant_config.is_quantized
|
||||
f32 = torch.float32
|
||||
if (self.quant_config.is_per_act_token
|
||||
or self.quant_config.is_per_tensor):
|
||||
if self.quant_config.is_per_act_token or self.quant_config.is_per_tensor:
|
||||
return t.to(f32) * scale
|
||||
else:
|
||||
return t.to(f32) * group_broadcast(scale, t.shape)
|
||||
@@ -699,15 +714,16 @@ class NaiveBatchedExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
expert_num_tokens = expert_tokens_meta.expert_num_tokens
|
||||
|
||||
num_local_experts = w1.size(0)
|
||||
assert num_local_experts == w1.size(0), (
|
||||
f"{num_local_experts} == {w1.size(0)}")
|
||||
assert num_local_experts == w1.size(0), f"{num_local_experts} == {w1.size(0)}"
|
||||
|
||||
N = w1.size(1) // 2
|
||||
|
||||
for expert in range(num_local_experts):
|
||||
# Indexing expert_num_tokens doesn't work w/cudagraphs or inductor
|
||||
if (torch.compiler.is_compiling()
|
||||
or torch.cuda.is_current_stream_capturing()):
|
||||
if (
|
||||
torch.compiler.is_compiling()
|
||||
or torch.cuda.is_current_stream_capturing()
|
||||
):
|
||||
num = hidden_states.shape[1]
|
||||
else:
|
||||
num = int(expert_num_tokens[expert].item())
|
||||
@@ -719,13 +735,11 @@ class NaiveBatchedExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
|
||||
if self.quant_config.is_quantized:
|
||||
assert a1q_scale is not None and self.w1_scale is not None
|
||||
input = self.dequant(hidden_states[expert, :, :],
|
||||
a1q_scale[expert])
|
||||
input = self.dequant(hidden_states[expert, :, :], a1q_scale[expert])
|
||||
w1_dq = self.dequant(w1[expert], self.w1_scale[expert])
|
||||
input = input[:num] @ w1_dq.transpose(0, 1)
|
||||
else:
|
||||
input = hidden_states[expert, :num, :] @ w1[expert].transpose(
|
||||
0, 1)
|
||||
input = hidden_states[expert, :num, :] @ w1[expert].transpose(0, 1)
|
||||
|
||||
self.activation(activation, tmp, input.to(tmp.dtype))
|
||||
|
||||
@@ -749,17 +763,16 @@ def batched_moe_kernel_quantize_input(
|
||||
per_act_token_quant: bool,
|
||||
block_shape: Optional[list[int]] = None,
|
||||
) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
|
||||
if (torch.compiler.is_compiling()
|
||||
or torch.cuda.is_current_stream_capturing()):
|
||||
if torch.compiler.is_compiling() or torch.cuda.is_current_stream_capturing():
|
||||
# Note: this does a bunch of extra work because expert_num_tokens is
|
||||
# ignored but it does support torch.compile + cudagraphs.
|
||||
hidden_dim = A.size(-1)
|
||||
assert A_scale is None or A_scale.ndim <= 2, (
|
||||
f"{A_scale.shape if A_scale is not None else None}")
|
||||
A_q, A_q_scale = moe_kernel_quantize_input(A.view(-1,
|
||||
hidden_dim), A_scale,
|
||||
qtype, per_act_token_quant,
|
||||
block_shape)
|
||||
f"{A_scale.shape if A_scale is not None else None}"
|
||||
)
|
||||
A_q, A_q_scale = moe_kernel_quantize_input(
|
||||
A.view(-1, hidden_dim), A_scale, qtype, per_act_token_quant, block_shape
|
||||
)
|
||||
A_q = A_q.view(E, -1, hidden_dim)
|
||||
A_q_scale = normalize_batched_scales_shape(A_q_scale, E)
|
||||
|
||||
@@ -779,9 +792,7 @@ def batched_moe_kernel_quantize_input(
|
||||
else:
|
||||
scale_shape = (E, 1, 1)
|
||||
|
||||
A_q_scale = torch.zeros(scale_shape,
|
||||
dtype=torch.float32,
|
||||
device=A.device)
|
||||
A_q_scale = torch.zeros(scale_shape, dtype=torch.float32, device=A.device)
|
||||
|
||||
num_experts = expert_num_tokens.numel()
|
||||
|
||||
@@ -791,7 +802,7 @@ def batched_moe_kernel_quantize_input(
|
||||
num_tokens = int(expert_num_tokens[e].item())
|
||||
if num_tokens > 0:
|
||||
if A_scale is not None:
|
||||
scales = A_scale[e, :min(num_tokens, A_scale.shape[1])]
|
||||
scales = A_scale[e, : min(num_tokens, A_scale.shape[1])]
|
||||
else:
|
||||
scales = None
|
||||
A_q[e, :num_tokens], tmp_scale = moe_kernel_quantize_input(
|
||||
@@ -802,7 +813,7 @@ def batched_moe_kernel_quantize_input(
|
||||
block_shape,
|
||||
)
|
||||
assert tmp_scale is not None
|
||||
A_q_scale[e, :tmp_scale.shape[0]] = tmp_scale
|
||||
A_q_scale[e, : tmp_scale.shape[0]] = tmp_scale
|
||||
|
||||
return A_q, A_q_scale
|
||||
|
||||
@@ -832,10 +843,12 @@ class BatchedTritonExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
|
||||
@property
|
||||
def activation_formats(
|
||||
self
|
||||
self,
|
||||
) -> tuple[mk.FusedMoEActivationFormat, mk.FusedMoEActivationFormat]:
|
||||
return (mk.FusedMoEActivationFormat.BatchedExperts,
|
||||
mk.FusedMoEActivationFormat.BatchedExperts)
|
||||
return (
|
||||
mk.FusedMoEActivationFormat.BatchedExperts,
|
||||
mk.FusedMoEActivationFormat.BatchedExperts,
|
||||
)
|
||||
|
||||
def supports_chunking(self) -> bool:
|
||||
return False
|
||||
@@ -888,26 +901,28 @@ class BatchedTritonExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
):
|
||||
# Check constraints.
|
||||
if self.quant_config.use_int4_w4a16:
|
||||
assert hidden_states.size(-1) // 2 == w1.size(2), (
|
||||
"Hidden size mismatch")
|
||||
assert hidden_states.size(-1) // 2 == w1.size(2), "Hidden size mismatch"
|
||||
else:
|
||||
assert hidden_states.size(-1) == w1.size(2), (
|
||||
f"Hidden size mismatch {hidden_states.size(-1)} "
|
||||
f"!= {w1.size(2)}")
|
||||
f"Hidden size mismatch {hidden_states.size(-1)} != {w1.size(2)}"
|
||||
)
|
||||
|
||||
assert hidden_states.is_contiguous(
|
||||
), "Hidden_states must be contiguous"
|
||||
assert hidden_states.is_contiguous(), "Hidden_states must be contiguous"
|
||||
assert w1.stride(-1) == 1, "Stride of last dimension must be 1"
|
||||
assert w2.stride(-1) == 1, "Stride of last dimension must be 1"
|
||||
assert hidden_states.dtype in [
|
||||
torch.float32, torch.float16, torch.bfloat16, torch.float8_e4m3fn
|
||||
torch.float32,
|
||||
torch.float16,
|
||||
torch.bfloat16,
|
||||
torch.float8_e4m3fn,
|
||||
]
|
||||
assert expert_tokens_meta is not None
|
||||
|
||||
expert_num_tokens = expert_tokens_meta.expert_num_tokens
|
||||
|
||||
E, max_num_tokens, N, K, top_k_num = self.moe_problem_size(
|
||||
hidden_states, w1, w2, topk_ids)
|
||||
hidden_states, w1, w2, topk_ids
|
||||
)
|
||||
|
||||
assert w1.size(0) == E
|
||||
assert w2.size(0) == E
|
||||
@@ -932,15 +947,12 @@ class BatchedTritonExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
elif hidden_states.dtype == torch.float8_e4m3fn:
|
||||
compute_type = tl.bfloat16
|
||||
else:
|
||||
raise ValueError(
|
||||
f"Unsupported compute_type: {hidden_states.dtype}")
|
||||
raise ValueError(f"Unsupported compute_type: {hidden_states.dtype}")
|
||||
|
||||
# We can reuse the memory between these because by the time we need
|
||||
# cache3, we're done with cache1
|
||||
intermediate_cache1 = _resize_cache(workspace13,
|
||||
(E, max_num_tokens, N))
|
||||
intermediate_cache2 = _resize_cache(workspace2,
|
||||
(E, max_num_tokens, N // 2))
|
||||
intermediate_cache1 = _resize_cache(workspace13, (E, max_num_tokens, N))
|
||||
intermediate_cache2 = _resize_cache(workspace2, (E, max_num_tokens, N // 2))
|
||||
|
||||
# TODO(bnell): should this be done for any quantized type?
|
||||
if self.quant_config.use_fp8_w8a8:
|
||||
@@ -963,18 +975,29 @@ class BatchedTritonExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
use_int4_w4a16=self.quant_config.use_int4_w4a16,
|
||||
config=config,
|
||||
per_act_token_quant=self.per_act_token_quant,
|
||||
block_shape=self.block_shape)
|
||||
block_shape=self.block_shape,
|
||||
)
|
||||
|
||||
intermediate_cache2.fill_(0)
|
||||
|
||||
# TODO (bnell): use triton utility from batched deep gemm.
|
||||
self.activation(activation, intermediate_cache2.view(-1, N // 2),
|
||||
intermediate_cache1.view(-1, N))
|
||||
self.activation(
|
||||
activation,
|
||||
intermediate_cache2.view(-1, N // 2),
|
||||
intermediate_cache1.view(-1, N),
|
||||
)
|
||||
|
||||
qintermediate_cache2, a2q_scale = batched_moe_kernel_quantize_input(
|
||||
intermediate_cache2, a2_scale, max_num_tokens, E, N,
|
||||
expert_num_tokens, self.quant_dtype, self.per_act_token_quant,
|
||||
self.block_shape)
|
||||
intermediate_cache2,
|
||||
a2_scale,
|
||||
max_num_tokens,
|
||||
E,
|
||||
N,
|
||||
expert_num_tokens,
|
||||
self.quant_dtype,
|
||||
self.per_act_token_quant,
|
||||
self.block_shape,
|
||||
)
|
||||
|
||||
invoke_moe_batched_triton_kernel(
|
||||
A=qintermediate_cache2,
|
||||
@@ -990,4 +1013,5 @@ class BatchedTritonExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
use_int4_w4a16=self.quant_config.use_int4_w4a16,
|
||||
config=config,
|
||||
per_act_token_quant=self.per_act_token_quant,
|
||||
block_shape=self.block_shape)
|
||||
block_shape=self.block_shape,
|
||||
)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Fused MoE utilities for GPTQ."""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
import torch
|
||||
@@ -11,44 +12,49 @@ import vllm.model_executor.layers.fused_moe.modular_kernel as mk
|
||||
from vllm.model_executor.layers.fused_moe.config import FusedMoEQuantConfig
|
||||
from vllm.model_executor.layers.fused_moe.fused_moe import moe_align_block_size
|
||||
from vllm.model_executor.layers.fused_moe.topk_weight_and_reduce import (
|
||||
TopKWeightAndReduceNoOP)
|
||||
TopKWeightAndReduceNoOP,
|
||||
)
|
||||
from vllm.model_executor.layers.fused_moe.utils import _resize_cache
|
||||
from vllm.model_executor.layers.quantization.utils.marlin_utils import (
|
||||
marlin_make_workspace_new, marlin_moe_intermediate_size,
|
||||
maybe_warn_marlin_atomic_add)
|
||||
marlin_make_workspace_new,
|
||||
marlin_moe_intermediate_size,
|
||||
maybe_warn_marlin_atomic_add,
|
||||
)
|
||||
from vllm.scalar_type import ScalarType, scalar_types
|
||||
from vllm.utils import direct_register_custom_op
|
||||
|
||||
|
||||
def fused_marlin_moe(hidden_states: torch.Tensor,
|
||||
w1: torch.Tensor,
|
||||
w2: torch.Tensor,
|
||||
bias1: Optional[torch.Tensor],
|
||||
bias2: Optional[torch.Tensor],
|
||||
w1_scale: torch.Tensor,
|
||||
w2_scale: torch.Tensor,
|
||||
gating_output: Optional[torch.Tensor],
|
||||
topk_weights: torch.Tensor,
|
||||
topk_ids: torch.Tensor,
|
||||
quant_type_id: int,
|
||||
apply_router_weight_on_input: bool = False,
|
||||
global_num_experts: int = -1,
|
||||
activation: Optional[str] = "silu",
|
||||
expert_map: Optional[torch.Tensor] = None,
|
||||
global_scale1: Optional[torch.Tensor] = None,
|
||||
global_scale2: Optional[torch.Tensor] = None,
|
||||
g_idx1: Optional[torch.Tensor] = None,
|
||||
g_idx2: Optional[torch.Tensor] = None,
|
||||
sort_indices1: Optional[torch.Tensor] = None,
|
||||
sort_indices2: Optional[torch.Tensor] = None,
|
||||
w1_zeros: Optional[torch.Tensor] = None,
|
||||
w2_zeros: Optional[torch.Tensor] = None,
|
||||
workspace: Optional[torch.Tensor] = None,
|
||||
intermediate_cache13: Optional[torch.Tensor] = None,
|
||||
intermediate_cache2: Optional[torch.Tensor] = None,
|
||||
is_k_full: bool = True,
|
||||
output: Optional[torch.Tensor] = None,
|
||||
inplace: bool = False) -> torch.Tensor:
|
||||
def fused_marlin_moe(
|
||||
hidden_states: torch.Tensor,
|
||||
w1: torch.Tensor,
|
||||
w2: torch.Tensor,
|
||||
bias1: Optional[torch.Tensor],
|
||||
bias2: Optional[torch.Tensor],
|
||||
w1_scale: torch.Tensor,
|
||||
w2_scale: torch.Tensor,
|
||||
gating_output: Optional[torch.Tensor],
|
||||
topk_weights: torch.Tensor,
|
||||
topk_ids: torch.Tensor,
|
||||
quant_type_id: int,
|
||||
apply_router_weight_on_input: bool = False,
|
||||
global_num_experts: int = -1,
|
||||
activation: Optional[str] = "silu",
|
||||
expert_map: Optional[torch.Tensor] = None,
|
||||
global_scale1: Optional[torch.Tensor] = None,
|
||||
global_scale2: Optional[torch.Tensor] = None,
|
||||
g_idx1: Optional[torch.Tensor] = None,
|
||||
g_idx2: Optional[torch.Tensor] = None,
|
||||
sort_indices1: Optional[torch.Tensor] = None,
|
||||
sort_indices2: Optional[torch.Tensor] = None,
|
||||
w1_zeros: Optional[torch.Tensor] = None,
|
||||
w2_zeros: Optional[torch.Tensor] = None,
|
||||
workspace: Optional[torch.Tensor] = None,
|
||||
intermediate_cache13: Optional[torch.Tensor] = None,
|
||||
intermediate_cache2: Optional[torch.Tensor] = None,
|
||||
is_k_full: bool = True,
|
||||
output: Optional[torch.Tensor] = None,
|
||||
inplace: bool = False,
|
||||
) -> torch.Tensor:
|
||||
"""
|
||||
This function computes a Mixture of Experts (MoE) layer using two sets of
|
||||
weights, w1 and w2, and top-k gating mechanism.
|
||||
@@ -78,23 +84,29 @@ def fused_marlin_moe(hidden_states: torch.Tensor,
|
||||
"""
|
||||
quant_type = ScalarType.from_id(quant_type_id)
|
||||
assert quant_type in [
|
||||
scalar_types.uint4, scalar_types.uint8b128, scalar_types.uint4b8,
|
||||
scalar_types.float8_e4m3fn, scalar_types.float4_e2m1f
|
||||
scalar_types.uint4,
|
||||
scalar_types.uint8b128,
|
||||
scalar_types.uint4b8,
|
||||
scalar_types.float8_e4m3fn,
|
||||
scalar_types.float4_e2m1f,
|
||||
]
|
||||
|
||||
bit4_scalar_types = [
|
||||
scalar_types.uint4, scalar_types.uint4b8, scalar_types.float4_e2m1f
|
||||
scalar_types.uint4,
|
||||
scalar_types.uint4b8,
|
||||
scalar_types.float4_e2m1f,
|
||||
]
|
||||
num_bits = 4 if quant_type in bit4_scalar_types else 8
|
||||
|
||||
# Check constraints.
|
||||
if gating_output is not None:
|
||||
assert hidden_states.shape[0] == gating_output.shape[
|
||||
0], "Number of tokens mismatch"
|
||||
assert hidden_states.shape[
|
||||
1] == w1.shape[1] * 16, "Hidden size mismatch w1"
|
||||
assert hidden_states.shape[1] == w2.shape[2] // (
|
||||
num_bits // 2), "Hidden size mismatch w2"
|
||||
assert hidden_states.shape[0] == gating_output.shape[0], (
|
||||
"Number of tokens mismatch"
|
||||
)
|
||||
assert hidden_states.shape[1] == w1.shape[1] * 16, "Hidden size mismatch w1"
|
||||
assert hidden_states.shape[1] == w2.shape[2] // (num_bits // 2), (
|
||||
"Hidden size mismatch w2"
|
||||
)
|
||||
assert hidden_states.is_contiguous(), "Hidden_states must be contiguous"
|
||||
assert w1.is_contiguous(), "Expert weights1 must be contiguous"
|
||||
assert w2.is_contiguous(), "Expert weights2 must be contiguous"
|
||||
@@ -115,9 +127,9 @@ def fused_marlin_moe(hidden_states: torch.Tensor,
|
||||
|
||||
if global_num_experts == -1:
|
||||
global_num_experts = E
|
||||
sorted_token_ids, expert_ids, num_tokens_post_padded = \
|
||||
moe_align_block_size(topk_ids, block_size_m, global_num_experts,
|
||||
expert_map)
|
||||
sorted_token_ids, expert_ids, num_tokens_post_padded = moe_align_block_size(
|
||||
topk_ids, block_size_m, global_num_experts, expert_map
|
||||
)
|
||||
|
||||
if workspace is None:
|
||||
workspace = marlin_make_workspace_new(hidden_states.device, 4)
|
||||
@@ -131,19 +143,20 @@ def fused_marlin_moe(hidden_states: torch.Tensor,
|
||||
|
||||
if intermediate_cache13 is None:
|
||||
intermediate_cache13 = torch.empty(
|
||||
(M * topk * max(2 * N, K), ),
|
||||
(M * topk * max(2 * N, K),),
|
||||
device=hidden_states.device,
|
||||
dtype=hidden_states.dtype,
|
||||
)
|
||||
|
||||
intermediate_cache1 = _resize_cache(intermediate_cache13,
|
||||
(M * topk, 2 * N))
|
||||
intermediate_cache1 = _resize_cache(intermediate_cache13, (M * topk, 2 * N))
|
||||
intermediate_cache3 = _resize_cache(intermediate_cache13, (M * topk, K))
|
||||
intermediate_cache2 = _resize_cache(intermediate_cache2, (M * topk, N))
|
||||
|
||||
maybe_warn_marlin_atomic_add(hidden_states.device, hidden_states.dtype)
|
||||
use_atomic_add = hidden_states.dtype == torch.half or \
|
||||
torch.cuda.get_device_capability(hidden_states.device)[0] >= 9
|
||||
use_atomic_add = (
|
||||
hidden_states.dtype == torch.half
|
||||
or torch.cuda.get_device_capability(hidden_states.device)[0] >= 9
|
||||
)
|
||||
|
||||
intermediate_cache1 = ops.moe_wna16_marlin_gemm(
|
||||
hidden_states,
|
||||
@@ -171,18 +184,23 @@ def fused_marlin_moe(hidden_states: torch.Tensor,
|
||||
is_k_full=is_k_full,
|
||||
use_atomic_add=use_atomic_add,
|
||||
use_fp32_reduce=True,
|
||||
is_zp_float=False)
|
||||
is_zp_float=False,
|
||||
)
|
||||
|
||||
if activation == "silu":
|
||||
torch.ops._C.silu_and_mul(intermediate_cache2,
|
||||
intermediate_cache1.view(-1, 2 * N))
|
||||
torch.ops._C.silu_and_mul(
|
||||
intermediate_cache2, intermediate_cache1.view(-1, 2 * N)
|
||||
)
|
||||
elif activation == "swigluoai":
|
||||
# alpha = 1.702, limit = 7.0
|
||||
torch.ops._C.swigluoai_and_mul(intermediate_cache2,
|
||||
intermediate_cache1.view(-1, 2 * N))
|
||||
torch.ops._C.swigluoai_and_mul(
|
||||
intermediate_cache2, intermediate_cache1.view(-1, 2 * N)
|
||||
)
|
||||
else:
|
||||
raise ValueError(f"Unsupported activation: {activation}. "
|
||||
"Only silu and swigluoai activations are supported.")
|
||||
raise ValueError(
|
||||
f"Unsupported activation: {activation}. "
|
||||
"Only silu and swigluoai activations are supported."
|
||||
)
|
||||
|
||||
if expert_map is not None:
|
||||
intermediate_cache3.zero_()
|
||||
@@ -213,39 +231,42 @@ def fused_marlin_moe(hidden_states: torch.Tensor,
|
||||
is_k_full=is_k_full,
|
||||
use_atomic_add=use_atomic_add,
|
||||
use_fp32_reduce=True,
|
||||
is_zp_float=False).view(-1, topk, K)
|
||||
is_zp_float=False,
|
||||
).view(-1, topk, K)
|
||||
|
||||
if output is None:
|
||||
output = hidden_states if inplace else torch.empty_like(hidden_states)
|
||||
return torch.sum(intermediate_cache3.view(-1, topk, K), dim=1, out=output)
|
||||
|
||||
|
||||
def fused_marlin_moe_fake(hidden_states: torch.Tensor,
|
||||
w1: torch.Tensor,
|
||||
w2: torch.Tensor,
|
||||
w1_scale: torch.Tensor,
|
||||
w2_scale: torch.Tensor,
|
||||
gating_output: Optional[torch.Tensor],
|
||||
topk_weights: torch.Tensor,
|
||||
topk_ids: torch.Tensor,
|
||||
quant_type_id: int,
|
||||
apply_router_weight_on_input: bool = False,
|
||||
global_num_experts: int = -1,
|
||||
global_scale1: Optional[torch.Tensor] = None,
|
||||
global_scale2: Optional[torch.Tensor] = None,
|
||||
expert_map: Optional[torch.Tensor] = None,
|
||||
g_idx1: Optional[torch.Tensor] = None,
|
||||
g_idx2: Optional[torch.Tensor] = None,
|
||||
sort_indices1: Optional[torch.Tensor] = None,
|
||||
sort_indices2: Optional[torch.Tensor] = None,
|
||||
w1_zeros: Optional[torch.Tensor] = None,
|
||||
w2_zeros: Optional[torch.Tensor] = None,
|
||||
workspace: Optional[torch.Tensor] = None,
|
||||
intermediate_cache13: Optional[torch.Tensor] = None,
|
||||
intermediate_cache2: Optional[torch.Tensor] = None,
|
||||
is_k_full: bool = True,
|
||||
output: Optional[torch.Tensor] = None,
|
||||
inplace: bool = False) -> torch.Tensor:
|
||||
def fused_marlin_moe_fake(
|
||||
hidden_states: torch.Tensor,
|
||||
w1: torch.Tensor,
|
||||
w2: torch.Tensor,
|
||||
w1_scale: torch.Tensor,
|
||||
w2_scale: torch.Tensor,
|
||||
gating_output: Optional[torch.Tensor],
|
||||
topk_weights: torch.Tensor,
|
||||
topk_ids: torch.Tensor,
|
||||
quant_type_id: int,
|
||||
apply_router_weight_on_input: bool = False,
|
||||
global_num_experts: int = -1,
|
||||
global_scale1: Optional[torch.Tensor] = None,
|
||||
global_scale2: Optional[torch.Tensor] = None,
|
||||
expert_map: Optional[torch.Tensor] = None,
|
||||
g_idx1: Optional[torch.Tensor] = None,
|
||||
g_idx2: Optional[torch.Tensor] = None,
|
||||
sort_indices1: Optional[torch.Tensor] = None,
|
||||
sort_indices2: Optional[torch.Tensor] = None,
|
||||
w1_zeros: Optional[torch.Tensor] = None,
|
||||
w2_zeros: Optional[torch.Tensor] = None,
|
||||
workspace: Optional[torch.Tensor] = None,
|
||||
intermediate_cache13: Optional[torch.Tensor] = None,
|
||||
intermediate_cache2: Optional[torch.Tensor] = None,
|
||||
is_k_full: bool = True,
|
||||
output: Optional[torch.Tensor] = None,
|
||||
inplace: bool = False,
|
||||
) -> torch.Tensor:
|
||||
return torch.empty_like(hidden_states)
|
||||
|
||||
|
||||
@@ -257,7 +278,6 @@ direct_register_custom_op(
|
||||
|
||||
|
||||
class MarlinExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
|
||||
def __init__(self, quant_config: FusedMoEQuantConfig):
|
||||
# TODO (varun) : Enable activation quantization
|
||||
assert quant_config.use_mxfp4_w4a16, "Supports only mxfp4_w4a16"
|
||||
@@ -279,8 +299,7 @@ class MarlinExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
|
||||
if a1.dim() == 2:
|
||||
# Make sure we are using the correct a1 (pre-permute).
|
||||
assert topk_ids.size(0) == a1.size(0), \
|
||||
f"{topk_ids.size(0)} != {a1.size(0)}"
|
||||
assert topk_ids.size(0) == a1.size(0), f"{topk_ids.size(0)} != {a1.size(0)}"
|
||||
M = a1.size(0)
|
||||
else:
|
||||
assert a1.dim() == 3
|
||||
@@ -300,18 +319,27 @@ class MarlinExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
|
||||
@property
|
||||
def activation_formats(
|
||||
self
|
||||
self,
|
||||
) -> tuple[mk.FusedMoEActivationFormat, mk.FusedMoEActivationFormat]:
|
||||
return (mk.FusedMoEActivationFormat.Standard,
|
||||
mk.FusedMoEActivationFormat.Standard)
|
||||
return (
|
||||
mk.FusedMoEActivationFormat.Standard,
|
||||
mk.FusedMoEActivationFormat.Standard,
|
||||
)
|
||||
|
||||
def supports_chunking(self) -> bool:
|
||||
return True
|
||||
|
||||
def workspace_shapes(
|
||||
self, a: torch.Tensor, aq: torch.Tensor, M: int, N: int, K: int,
|
||||
topk: int, global_num_experts: int, local_num_experts: int,
|
||||
expert_tokens_meta: Optional[mk.ExpertTokensMetadata]
|
||||
self,
|
||||
a: torch.Tensor,
|
||||
aq: torch.Tensor,
|
||||
M: int,
|
||||
N: int,
|
||||
K: int,
|
||||
topk: int,
|
||||
global_num_experts: int,
|
||||
local_num_experts: int,
|
||||
expert_tokens_meta: Optional[mk.ExpertTokensMetadata],
|
||||
) -> tuple[tuple[int, ...], tuple[int, ...], tuple[int, ...], torch.dtype]:
|
||||
# Modular Kernel provisions output buffer from workspace1. However in
|
||||
# the fused_marlin_moe() function, the final torch.sum(), is defined
|
||||
@@ -323,13 +351,13 @@ class MarlinExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
# workspace2.
|
||||
|
||||
# Workspace/IntermediateCache allocation matching fused_marlin_moe()
|
||||
#workspace1 = (M * topk * max(2 * N, K),)
|
||||
#workspace2 = (M * topk, N)
|
||||
# workspace1 = (M * topk * max(2 * N, K),)
|
||||
# workspace2 = (M * topk, N)
|
||||
|
||||
# Workspace/IntermediateCache allocation accounting for output buffer
|
||||
# provisioning
|
||||
workspace1 = (M * topk, max(N, K))
|
||||
workspace2 = (M * topk * max(2 * N, K), )
|
||||
workspace2 = (M * topk * max(2 * N, K),)
|
||||
output = (M, K)
|
||||
|
||||
return (workspace1, workspace2, output, a.dtype)
|
||||
@@ -374,4 +402,5 @@ class MarlinExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
# Workspaces are swapped in workspace_shapes() to account for proper
|
||||
# output buffer allocation. Please refer to workspace_shapes().
|
||||
intermediate_cache13=workspace2,
|
||||
intermediate_cache2=workspace13)
|
||||
intermediate_cache2=workspace13,
|
||||
)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -7,9 +7,12 @@ import torch
|
||||
import vllm.model_executor.layers.fused_moe.modular_kernel as mk
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.fused_moe.config import (
|
||||
FUSED_MOE_UNQUANTIZED_CONFIG, FusedMoEQuantConfig)
|
||||
FUSED_MOE_UNQUANTIZED_CONFIG,
|
||||
FusedMoEQuantConfig,
|
||||
)
|
||||
from vllm.model_executor.layers.fused_moe.topk_weight_and_reduce import (
|
||||
TopKWeightAndReduceNoOP)
|
||||
TopKWeightAndReduceNoOP,
|
||||
)
|
||||
from vllm.triton_utils import tl, triton
|
||||
from vllm.utils import has_triton_kernels
|
||||
|
||||
@@ -18,24 +21,24 @@ logger = init_logger(__name__)
|
||||
if has_triton_kernels():
|
||||
try:
|
||||
import triton_kernels.swiglu
|
||||
from triton_kernels.matmul_ogs import (FnSpecs, FusedActivation,
|
||||
matmul_ogs)
|
||||
from triton_kernels.routing import (RoutingData, routing,
|
||||
routing_from_bitmatrix)
|
||||
from triton_kernels.matmul_ogs import FnSpecs, FusedActivation, matmul_ogs
|
||||
from triton_kernels.routing import RoutingData, routing, routing_from_bitmatrix
|
||||
from triton_kernels.tensor import Bitmatrix
|
||||
except (AttributeError, ImportError) as e:
|
||||
logger.error(
|
||||
"Failed to import Triton kernels. Please make sure your triton "
|
||||
"version is compatible. Error: %s", e)
|
||||
"version is compatible. Error: %s",
|
||||
e,
|
||||
)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def pack_bitmatrix(
|
||||
bitmatrix,
|
||||
topk_ids,
|
||||
n_rows, # n_rows in bitmatrix / topk_ids
|
||||
n_rows, # n_rows in bitmatrix / topk_ids
|
||||
bm_cols: tl.constexpr, # n int32_t bitpacks in bitmatrix
|
||||
n_expts_act, # num_topk
|
||||
n_expts_act, # num_topk
|
||||
BLOCK_SIZE_M: tl.constexpr,
|
||||
BLOCK_SIZE_K: tl.constexpr,
|
||||
):
|
||||
@@ -60,12 +63,12 @@ def pack_bitmatrix(
|
||||
offs = tl.arange(0, BLOCK_SIZE_K // 32) + i * (BLOCK_SIZE_K // 32)
|
||||
# All topks that need to go into this column has the correct bit set.
|
||||
# Other bits are 0. x is a 2D tensor.
|
||||
x = tl.where(div[:, :, None] == offs[None, None, :],
|
||||
(one << rem)[:, :, None], 0)
|
||||
x = tl.where(
|
||||
div[:, :, None] == offs[None, None, :], (one << rem)[:, :, None], 0
|
||||
)
|
||||
# Reduce x to get a single int32_t bitpack.
|
||||
y = tl.reduce_or(x, axis=1)
|
||||
bitmatrix_ptrs = bitmatrix + offsets_m[:,
|
||||
None] * bm_cols + offs[None, :]
|
||||
bitmatrix_ptrs = bitmatrix + offsets_m[:, None] * bm_cols + offs[None, :]
|
||||
tl.store(bitmatrix_ptrs, y, mask=offsets_m[:, None] < n_rows)
|
||||
|
||||
|
||||
@@ -82,10 +85,9 @@ def triton_kernel_moe_forward(
|
||||
global_num_experts: int = -1,
|
||||
expert_map: Optional[torch.Tensor] = None,
|
||||
) -> torch.Tensor:
|
||||
|
||||
routing_data, gather_idx, scatter_idx = routing(gating_output,
|
||||
topk,
|
||||
sm_first=not renormalize)
|
||||
routing_data, gather_idx, scatter_idx = routing(
|
||||
gating_output, topk, sm_first=not renormalize
|
||||
)
|
||||
|
||||
return triton_kernel_fused_experts(
|
||||
None,
|
||||
@@ -99,7 +101,8 @@ def triton_kernel_moe_forward(
|
||||
quant_config=quant_config,
|
||||
apply_router_weight_on_input=apply_router_weight_on_input,
|
||||
global_num_experts=global_num_experts,
|
||||
expert_map=expert_map)
|
||||
expert_map=expert_map,
|
||||
)
|
||||
|
||||
|
||||
# This is a triton implementation of the fused_experts function
|
||||
@@ -125,10 +128,8 @@ def triton_kernel_fused_experts(
|
||||
|
||||
# type check, uint8 means mxfp4
|
||||
assert hidden_states.dtype == torch.bfloat16
|
||||
assert (quant_config.w1_bias is None
|
||||
or quant_config.w1_bias.dtype == torch.float32)
|
||||
assert (quant_config.w2_bias is None
|
||||
or quant_config.w2_bias.dtype == torch.float32)
|
||||
assert quant_config.w1_bias is None or quant_config.w1_bias.dtype == torch.float32
|
||||
assert quant_config.w2_bias is None or quant_config.w2_bias.dtype == torch.float32
|
||||
|
||||
# Shape check, only check non-mxfp4
|
||||
assert hidden_states.shape[-1] == w1.shape[-2]
|
||||
@@ -141,7 +142,9 @@ def triton_kernel_fused_experts(
|
||||
|
||||
act = FusedActivation(
|
||||
FnSpecs("swiglu", triton_kernels.swiglu.swiglu_fn, ("alpha", "limit")),
|
||||
(swiglu_alpha, swiglu_limit), 2)
|
||||
(swiglu_alpha, swiglu_limit),
|
||||
2,
|
||||
)
|
||||
gammas = routing_data.gate_scal if routing_data else None
|
||||
|
||||
intermediate_cache1 = matmul_ogs(
|
||||
@@ -152,7 +155,8 @@ def triton_kernel_fused_experts(
|
||||
gather_indx=gather_indx,
|
||||
precision_config=quant_config.w1_precision,
|
||||
gammas=gammas if apply_router_weight_on_input else None,
|
||||
fused_activation=act)
|
||||
fused_activation=act,
|
||||
)
|
||||
|
||||
intermediate_cache3 = matmul_ogs(
|
||||
intermediate_cache1,
|
||||
@@ -172,7 +176,6 @@ def make_routing_data(
|
||||
topk_weights: torch.Tensor,
|
||||
num_local_experts: int,
|
||||
) -> tuple["RoutingData", torch.Tensor, torch.Tensor]:
|
||||
|
||||
topk_ids = topk_ids.to(torch.int16)
|
||||
topk_weights = topk_weights.to(torch.bfloat16)
|
||||
|
||||
@@ -182,11 +185,11 @@ def make_routing_data(
|
||||
BLOCK_SIZE_K = 32
|
||||
|
||||
bm_cols = triton.cdiv(num_local_experts, BLOCK_SIZE_K) # n_bitpacks
|
||||
bitmatrix = torch.zeros((n_rows, bm_cols),
|
||||
dtype=torch.uint32,
|
||||
device=topk_ids.device)
|
||||
bitmatrix = torch.zeros(
|
||||
(n_rows, bm_cols), dtype=torch.uint32, device=topk_ids.device
|
||||
)
|
||||
|
||||
grid = (triton.cdiv(n_rows, BLOCK_SIZE_M), )
|
||||
grid = (triton.cdiv(n_rows, BLOCK_SIZE_M),)
|
||||
pack_bitmatrix[grid](
|
||||
bitmatrix,
|
||||
topk_ids,
|
||||
@@ -199,21 +202,20 @@ def make_routing_data(
|
||||
|
||||
bitmatrix_shape = [n_rows, bm_cols * 32]
|
||||
bitmatrix_shape_max = [n_rows, None]
|
||||
bitmatrix = Bitmatrix(bitmatrix,
|
||||
shape=bitmatrix_shape,
|
||||
shape_max=bitmatrix_shape_max,
|
||||
scratchpad=None)
|
||||
bitmatrix = Bitmatrix(
|
||||
bitmatrix, shape=bitmatrix_shape, shape_max=bitmatrix_shape_max, scratchpad=None
|
||||
)
|
||||
|
||||
# matmul_ogs expects invalid topk_weights to be -1s
|
||||
topk_weights = torch.where(topk_ids == -1, -1.0, topk_weights)
|
||||
routing_data, gather_indx, scatter_indx = routing_from_bitmatrix(
|
||||
bitmatrix, topk_weights, topk_ids, num_local_experts, num_topk)
|
||||
bitmatrix, topk_weights, topk_ids, num_local_experts, num_topk
|
||||
)
|
||||
|
||||
return routing_data, gather_indx, scatter_indx
|
||||
|
||||
|
||||
class BaseOAITritonExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
|
||||
def __init__(self, quant_config: FusedMoEQuantConfig):
|
||||
super().__init__(quant_config)
|
||||
|
||||
@@ -234,7 +236,6 @@ class BaseOAITritonExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
|
||||
|
||||
class OAITritonExperts(BaseOAITritonExperts):
|
||||
|
||||
def __init__(self, quant_config: FusedMoEQuantConfig):
|
||||
# TODO (varun) : Enable activation quantization
|
||||
assert quant_config.use_mxfp4_w4a16, "Supports only mxfp4_w4a16"
|
||||
@@ -242,18 +243,27 @@ class OAITritonExperts(BaseOAITritonExperts):
|
||||
|
||||
@property
|
||||
def activation_formats(
|
||||
self
|
||||
self,
|
||||
) -> tuple[mk.FusedMoEActivationFormat, mk.FusedMoEActivationFormat]:
|
||||
return (mk.FusedMoEActivationFormat.Standard,
|
||||
mk.FusedMoEActivationFormat.Standard)
|
||||
return (
|
||||
mk.FusedMoEActivationFormat.Standard,
|
||||
mk.FusedMoEActivationFormat.Standard,
|
||||
)
|
||||
|
||||
def supports_chunking(self) -> bool:
|
||||
return True
|
||||
|
||||
def workspace_shapes(
|
||||
self, a: torch.Tensor, aq: torch.Tensor, M: int, N: int, K: int,
|
||||
topk: int, global_num_experts: int, local_num_experts: int,
|
||||
expert_tokens_meta: Optional[mk.ExpertTokensMetadata]
|
||||
self,
|
||||
a: torch.Tensor,
|
||||
aq: torch.Tensor,
|
||||
M: int,
|
||||
N: int,
|
||||
K: int,
|
||||
topk: int,
|
||||
global_num_experts: int,
|
||||
local_num_experts: int,
|
||||
expert_tokens_meta: Optional[mk.ExpertTokensMetadata],
|
||||
) -> tuple[tuple[int, ...], tuple[int, ...], tuple[int, ...], torch.dtype]:
|
||||
# workspace are allocated inside the kernel
|
||||
workspace1 = (M, K)
|
||||
@@ -287,7 +297,8 @@ class OAITritonExperts(BaseOAITritonExperts):
|
||||
global_num_experts = local_num_experts
|
||||
|
||||
routing_data, gather_indx, scatter_indx = self._make_routing_data(
|
||||
topk_ids, topk_weights, local_num_experts)
|
||||
topk_ids, topk_weights, local_num_experts
|
||||
)
|
||||
|
||||
experts_output = triton_kernel_fused_experts(
|
||||
None,
|
||||
@@ -302,6 +313,7 @@ class OAITritonExperts(BaseOAITritonExperts):
|
||||
apply_router_weight_on_input=False,
|
||||
global_num_experts=local_num_experts,
|
||||
expert_map=None, # applied already
|
||||
a1q_scale=a1q_scale)
|
||||
a1q_scale=a1q_scale,
|
||||
)
|
||||
|
||||
output.copy_(experts_output, non_blocking=True)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -11,11 +11,17 @@ import torch
|
||||
import vllm.envs as envs
|
||||
from vllm.model_executor.layers.fused_moe.config import FusedMoEQuantConfig
|
||||
from vllm.model_executor.layers.fused_moe.utils import ( # yapf: disable
|
||||
_resize_cache, count_expert_num_tokens)
|
||||
_resize_cache,
|
||||
count_expert_num_tokens,
|
||||
)
|
||||
from vllm.utils import cdiv
|
||||
from vllm.v1.worker.ubatching import (dbo_current_ubatch_id, dbo_enabled,
|
||||
dbo_maybe_run_recv_hook,
|
||||
dbo_register_recv_hook, dbo_yield)
|
||||
from vllm.v1.worker.ubatching import (
|
||||
dbo_current_ubatch_id,
|
||||
dbo_enabled,
|
||||
dbo_maybe_run_recv_hook,
|
||||
dbo_register_recv_hook,
|
||||
dbo_yield,
|
||||
)
|
||||
|
||||
#
|
||||
# This file defines a set of base classes used to make MoE kernels more modular.
|
||||
@@ -59,31 +65,34 @@ class FusedMoEActivationFormat(Enum):
|
||||
"""
|
||||
The standard activation format (num_tokens, hidden dim).
|
||||
"""
|
||||
Standard = "standard",
|
||||
|
||||
Standard = ("standard",)
|
||||
"""
|
||||
The batched experts format (num experts, max tokens per expert, hidden dim)
|
||||
"""
|
||||
BatchedExperts = "batched_experts",
|
||||
BatchedExperts = ("batched_experts",)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ExpertTokensMetadata:
|
||||
"""
|
||||
Metadata regarding expert-token routing.
|
||||
"""
|
||||
Metadata regarding expert-token routing.
|
||||
"""
|
||||
|
||||
expert_num_tokens: torch.Tensor
|
||||
expert_num_tokens_cpu: Optional[torch.Tensor]
|
||||
|
||||
@staticmethod
|
||||
def make_from_list(expert_num_tokens_list: list[int],
|
||||
device: str) -> "ExpertTokensMetadata":
|
||||
expert_num_tokens_cpu = torch.tensor(expert_num_tokens_list,
|
||||
device="cpu",
|
||||
dtype=torch.int32)
|
||||
def make_from_list(
|
||||
expert_num_tokens_list: list[int], device: str
|
||||
) -> "ExpertTokensMetadata":
|
||||
expert_num_tokens_cpu = torch.tensor(
|
||||
expert_num_tokens_list, device="cpu", dtype=torch.int32
|
||||
)
|
||||
return ExpertTokensMetadata(
|
||||
expert_num_tokens=expert_num_tokens_cpu.to(device,
|
||||
non_blocking=True),
|
||||
expert_num_tokens_cpu=expert_num_tokens_cpu)
|
||||
expert_num_tokens=expert_num_tokens_cpu.to(device, non_blocking=True),
|
||||
expert_num_tokens_cpu=expert_num_tokens_cpu,
|
||||
)
|
||||
|
||||
|
||||
class TopKWeightAndReduce(ABC):
|
||||
@@ -92,10 +101,14 @@ class TopKWeightAndReduce(ABC):
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
def apply(self, output: Optional[torch.Tensor],
|
||||
fused_expert_output: torch.Tensor, topk_weights: torch.Tensor,
|
||||
topk_ids: torch.Tensor,
|
||||
apply_router_weight_on_input: bool) -> torch.Tensor:
|
||||
def apply(
|
||||
self,
|
||||
output: Optional[torch.Tensor],
|
||||
fused_expert_output: torch.Tensor,
|
||||
topk_weights: torch.Tensor,
|
||||
topk_ids: torch.Tensor,
|
||||
apply_router_weight_on_input: bool,
|
||||
) -> torch.Tensor:
|
||||
"""
|
||||
Apply topk_weights to the fused_experts_outputs and/or reduce.
|
||||
If an output tensor is not passed, it will be created in the
|
||||
@@ -200,16 +213,16 @@ class FusedMoEPrepareAndFinalize(ABC):
|
||||
- apply_router_weight_on_input: When True, apply the weights to the
|
||||
activations, before quantization + dispatching.
|
||||
|
||||
Returns a callback or a hook callback pair that when invoked waits for
|
||||
results from other workers and has the same return signature as
|
||||
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
|
||||
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()
|
||||
@@ -270,10 +283,10 @@ class FusedMoEPrepareAndFinalize(ABC):
|
||||
- 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
|
||||
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
|
||||
the recv is complete without doing extra work (used by DBO, will be
|
||||
refactored in the very near future)
|
||||
|
||||
ret = obj.finalize_async(output, ...)
|
||||
@@ -344,7 +357,8 @@ class FusedMoEPermuteExpertsUnpermute(ABC):
|
||||
@property
|
||||
@abstractmethod
|
||||
def activation_formats(
|
||||
self) -> tuple[FusedMoEActivationFormat, FusedMoEActivationFormat]:
|
||||
self,
|
||||
) -> tuple[FusedMoEActivationFormat, FusedMoEActivationFormat]:
|
||||
"""
|
||||
A property which is a tuple of the input and output activation formats
|
||||
for the 'apply' method.
|
||||
@@ -382,8 +396,7 @@ class FusedMoEPermuteExpertsUnpermute(ABC):
|
||||
|
||||
if a1.dim() == 2:
|
||||
# Make sure we are using the correct a1 (pre-permute).
|
||||
assert topk_ids.size(0) == a1.size(0), \
|
||||
f"{topk_ids.size(0)} != {a1.size(0)}"
|
||||
assert topk_ids.size(0) == a1.size(0), f"{topk_ids.size(0)} != {a1.size(0)}"
|
||||
M = a1.size(0)
|
||||
else:
|
||||
assert a1.dim() == 3
|
||||
@@ -511,8 +524,9 @@ class FusedMoEPermuteExpertsUnpermute(ABC):
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def activation(self, activation: str, output: torch.Tensor,
|
||||
input: torch.Tensor) -> None:
|
||||
def activation(
|
||||
self, activation: str, output: torch.Tensor, input: torch.Tensor
|
||||
) -> None:
|
||||
assert output.size(-1) * 2 == input.size(-1)
|
||||
if activation == "silu":
|
||||
torch.ops._C.silu_and_mul(output, input)
|
||||
@@ -522,8 +536,9 @@ class FusedMoEPermuteExpertsUnpermute(ABC):
|
||||
raise ValueError(f"Unsupported FusedMoe activation: {activation}")
|
||||
|
||||
def enable_chunking(self):
|
||||
return envs.VLLM_ENABLE_FUSED_MOE_ACTIVATION_CHUNKING and \
|
||||
self.supports_chunking()
|
||||
return (
|
||||
envs.VLLM_ENABLE_FUSED_MOE_ACTIVATION_CHUNKING and self.supports_chunking()
|
||||
)
|
||||
|
||||
def finalize_weight_and_reduce_impl(self) -> TopKWeightAndReduce:
|
||||
raise NotImplementedError
|
||||
@@ -585,8 +600,9 @@ class FusedMoEPermuteExpertsUnpermute(ABC):
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
def _chunk_scales(scales: Optional[torch.Tensor], start: int,
|
||||
end: int) -> Optional[torch.Tensor]:
|
||||
def _chunk_scales(
|
||||
scales: Optional[torch.Tensor], start: int, end: int
|
||||
) -> Optional[torch.Tensor]:
|
||||
if scales is not None:
|
||||
if scales.numel() == 1:
|
||||
return scales
|
||||
@@ -596,17 +612,19 @@ def _chunk_scales(scales: Optional[torch.Tensor], start: int,
|
||||
|
||||
|
||||
class SharedResizableBuffer:
|
||||
|
||||
def __init__(self):
|
||||
self.buffer = None
|
||||
|
||||
def get(self, shape: tuple[int, ...], device: torch.device,
|
||||
dtype: torch.dtype):
|
||||
def get(self, shape: tuple[int, ...], device: torch.device, dtype: torch.dtype):
|
||||
if shape == () or shape is None:
|
||||
return None
|
||||
shape_numel = prod(shape)
|
||||
if (self.buffer is None or self.buffer.numel() < shape_numel
|
||||
or self.buffer.device != device or self.buffer.dtype != dtype):
|
||||
if (
|
||||
self.buffer is None
|
||||
or self.buffer.numel() < shape_numel
|
||||
or self.buffer.device != device
|
||||
or self.buffer.dtype != dtype
|
||||
):
|
||||
self.buffer = torch.empty(shape_numel, device=device, dtype=dtype)
|
||||
return self.buffer[:shape_numel].view(*shape)
|
||||
|
||||
@@ -626,7 +644,6 @@ class FusedMoEModularKernel(torch.nn.Module):
|
||||
"""
|
||||
|
||||
class SharedBuffers:
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.fused_out = SharedResizableBuffer()
|
||||
self.workspace13 = SharedResizableBuffer()
|
||||
@@ -652,12 +669,14 @@ class FusedMoEModularKernel(torch.nn.Module):
|
||||
self.prepare_finalize = prepare_finalize
|
||||
self.fused_experts = fused_experts
|
||||
self.shared_experts = shared_experts
|
||||
assert prepare_finalize.activation_format == \
|
||||
fused_experts.activation_formats[0], (
|
||||
f"{prepare_finalize.__class__.__name__}."
|
||||
f"{prepare_finalize.activation_format} == "
|
||||
f"{fused_experts.__class__.__name__}."
|
||||
f"{fused_experts.activation_formats[0]}")
|
||||
assert (
|
||||
prepare_finalize.activation_format == fused_experts.activation_formats[0]
|
||||
), (
|
||||
f"{prepare_finalize.__class__.__name__}."
|
||||
f"{prepare_finalize.activation_format} == "
|
||||
f"{fused_experts.__class__.__name__}."
|
||||
f"{fused_experts.activation_formats[0]}"
|
||||
)
|
||||
|
||||
def _do_fused_experts(
|
||||
self,
|
||||
@@ -677,14 +696,21 @@ class FusedMoEModularKernel(torch.nn.Module):
|
||||
expert_tokens_meta: Optional[ExpertTokensMetadata],
|
||||
apply_router_weight_on_input: bool,
|
||||
) -> torch.Tensor:
|
||||
_, M, N, K, top_k = self.fused_experts.moe_problem_size(a1q, w1, w2, topk_ids)
|
||||
|
||||
_, M, N, K, top_k = self.fused_experts.moe_problem_size(
|
||||
a1q, w1, w2, topk_ids)
|
||||
|
||||
(workspace13_shape, workspace2_shape, fused_out_shape,
|
||||
workspace_dtype) = self.fused_experts.workspace_shapes(
|
||||
a1, a1q, M, N, K, top_k, global_num_experts, local_num_experts,
|
||||
expert_tokens_meta)
|
||||
(workspace13_shape, workspace2_shape, fused_out_shape, workspace_dtype) = (
|
||||
self.fused_experts.workspace_shapes(
|
||||
a1,
|
||||
a1q,
|
||||
M,
|
||||
N,
|
||||
K,
|
||||
top_k,
|
||||
global_num_experts,
|
||||
local_num_experts,
|
||||
expert_tokens_meta,
|
||||
)
|
||||
)
|
||||
|
||||
# select per-ubatch buffers to avoid cross-ubatch reuse under DBO
|
||||
ubatch_idx = dbo_current_ubatch_id()
|
||||
@@ -692,15 +718,16 @@ class FusedMoEModularKernel(torch.nn.Module):
|
||||
|
||||
# We can reuse the memory between cache1 and cache3 because by the
|
||||
# time we need cache3, we're done with cache1.
|
||||
workspace13 = buffers.workspace13.get(workspace13_shape,
|
||||
device=a1.device,
|
||||
dtype=workspace_dtype)
|
||||
workspace2 = buffers.workspace2.get(workspace2_shape,
|
||||
device=a1.device,
|
||||
dtype=workspace_dtype)
|
||||
workspace13 = buffers.workspace13.get(
|
||||
workspace13_shape, device=a1.device, dtype=workspace_dtype
|
||||
)
|
||||
workspace2 = buffers.workspace2.get(
|
||||
workspace2_shape, device=a1.device, dtype=workspace_dtype
|
||||
)
|
||||
|
||||
assert fused_out is None or fused_out.shape == fused_out_shape, (
|
||||
f"fused_out {fused_out.shape} but expected {fused_out_shape}")
|
||||
f"fused_out {fused_out.shape} but expected {fused_out_shape}"
|
||||
)
|
||||
if fused_out is None:
|
||||
# reuse workspace13 for the output
|
||||
fused_out = _resize_cache(workspace13, fused_out_shape)
|
||||
@@ -741,9 +768,7 @@ class FusedMoEModularKernel(torch.nn.Module):
|
||||
expert_tokens_meta: Optional[ExpertTokensMetadata],
|
||||
apply_router_weight_on_input: bool,
|
||||
) -> torch.Tensor:
|
||||
|
||||
_, M, N, K, top_k = self.fused_experts.moe_problem_size(
|
||||
a1q, w1, w2, topk_ids)
|
||||
_, M, N, K, top_k = self.fused_experts.moe_problem_size(a1q, w1, w2, topk_ids)
|
||||
|
||||
CHUNK_SIZE = envs.VLLM_FUSED_MOE_CHUNK_SIZE
|
||||
num_chunks = cdiv(M, CHUNK_SIZE)
|
||||
@@ -775,18 +800,31 @@ class FusedMoEModularKernel(torch.nn.Module):
|
||||
|
||||
# Construct the entire output that can then be processed in chunks.
|
||||
(_, _, fused_out_shape, _) = self.fused_experts.workspace_shapes(
|
||||
a1, a1q, M, N, K, top_k, global_num_experts, local_num_experts,
|
||||
expert_tokens_meta)
|
||||
a1,
|
||||
a1q,
|
||||
M,
|
||||
N,
|
||||
K,
|
||||
top_k,
|
||||
global_num_experts,
|
||||
local_num_experts,
|
||||
expert_tokens_meta,
|
||||
)
|
||||
ubatch_idx = dbo_current_ubatch_id()
|
||||
buffers = self.shared_buffers[ubatch_idx]
|
||||
fused_out = buffers.fused_out.get(fused_out_shape,
|
||||
device=a1q.device,
|
||||
dtype=a1.dtype)
|
||||
fused_out = buffers.fused_out.get(
|
||||
fused_out_shape, device=a1q.device, dtype=a1.dtype
|
||||
)
|
||||
|
||||
def slice_input_tensors(
|
||||
chunk_idx: int
|
||||
) -> tuple[torch.Tensor, Optional[torch.Tensor],
|
||||
Optional[torch.Tensor], torch.Tensor, torch.Tensor]:
|
||||
chunk_idx: int,
|
||||
) -> tuple[
|
||||
torch.Tensor,
|
||||
Optional[torch.Tensor],
|
||||
Optional[torch.Tensor],
|
||||
torch.Tensor,
|
||||
torch.Tensor,
|
||||
]:
|
||||
s = chunk_idx * CHUNK_SIZE
|
||||
e = min(s + CHUNK_SIZE, M)
|
||||
return (
|
||||
@@ -799,7 +837,8 @@ class FusedMoEModularKernel(torch.nn.Module):
|
||||
|
||||
def slice_output_tensor(chunk_idx: int) -> torch.Tensor:
|
||||
assert fused_out.size(0) % M == 0, (
|
||||
f"fused_out shape {fused_out.shape} vs M {M}")
|
||||
f"fused_out shape {fused_out.shape} vs M {M}"
|
||||
)
|
||||
factor = fused_out.size(0) // M
|
||||
out_chunk_size = CHUNK_SIZE * factor
|
||||
s = chunk_idx * out_chunk_size
|
||||
@@ -807,38 +846,45 @@ class FusedMoEModularKernel(torch.nn.Module):
|
||||
return fused_out[s:e]
|
||||
|
||||
def slice_expert_tokens_metadata(
|
||||
full_expert_tokens_meta: ExpertTokensMetadata,
|
||||
chunk_topk_ids: torch.Tensor, local_num_experts: int,
|
||||
expert_map: Optional[torch.Tensor]) -> ExpertTokensMetadata:
|
||||
full_expert_tokens_meta: ExpertTokensMetadata,
|
||||
chunk_topk_ids: torch.Tensor,
|
||||
local_num_experts: int,
|
||||
expert_map: Optional[torch.Tensor],
|
||||
) -> ExpertTokensMetadata:
|
||||
# The existing expert_num_tokens is for the entire a1q
|
||||
# input. Chunking forces recomputation of the number
|
||||
# of tokens assigned to each expert.
|
||||
c_expert_num_tokens = count_expert_num_tokens(
|
||||
chunk_topk_ids, local_num_experts, expert_map)
|
||||
chunk_topk_ids, local_num_experts, expert_map
|
||||
)
|
||||
|
||||
c_expert_num_tokens_cpu = None
|
||||
need_expert_num_tokens_cpu = (
|
||||
full_expert_tokens_meta.expert_num_tokens_cpu is not None)
|
||||
full_expert_tokens_meta.expert_num_tokens_cpu is not None
|
||||
)
|
||||
if need_expert_num_tokens_cpu:
|
||||
# This is blocking as some implementations need the count
|
||||
# on the CPU to determine appropriate input/out fused-moe
|
||||
# buffers
|
||||
c_expert_num_tokens_cpu = c_expert_num_tokens.to(
|
||||
"cpu", non_blocking=False)
|
||||
"cpu", non_blocking=False
|
||||
)
|
||||
|
||||
return ExpertTokensMetadata(
|
||||
expert_num_tokens=c_expert_num_tokens,
|
||||
expert_num_tokens_cpu=c_expert_num_tokens_cpu)
|
||||
expert_num_tokens_cpu=c_expert_num_tokens_cpu,
|
||||
)
|
||||
|
||||
for chunk_idx in range(num_chunks):
|
||||
c_a1q, c_a1q_scale, c_a2_scale, c_topk_ids, c_topk_weights = (
|
||||
slice_input_tensors(chunk_idx))
|
||||
slice_input_tensors(chunk_idx)
|
||||
)
|
||||
|
||||
c_expert_tokens_meta = None
|
||||
if expert_tokens_meta is not None:
|
||||
c_expert_tokens_meta = slice_expert_tokens_metadata(
|
||||
expert_tokens_meta, c_topk_ids, local_num_experts,
|
||||
expert_map)
|
||||
expert_tokens_meta, c_topk_ids, local_num_experts, expert_map
|
||||
)
|
||||
|
||||
self._do_fused_experts(
|
||||
fused_out=slice_output_tensor(chunk_idx),
|
||||
@@ -917,16 +963,21 @@ class FusedMoEModularKernel(torch.nn.Module):
|
||||
# TODO(lucas): enable in follow-up
|
||||
assert not dbo_enabled()
|
||||
|
||||
(a1q, a1q_scale, expert_tokens_meta, _expert_topk_ids,
|
||||
_expert_topk_weights) = self.prepare_finalize.prepare(
|
||||
a1,
|
||||
topk_weights,
|
||||
topk_ids,
|
||||
global_num_experts,
|
||||
expert_map,
|
||||
apply_router_weight_on_input,
|
||||
self.fused_experts.quant_config,
|
||||
)
|
||||
(
|
||||
a1q,
|
||||
a1q_scale,
|
||||
expert_tokens_meta,
|
||||
_expert_topk_ids,
|
||||
_expert_topk_weights,
|
||||
) = self.prepare_finalize.prepare(
|
||||
a1,
|
||||
topk_weights,
|
||||
topk_ids,
|
||||
global_num_experts,
|
||||
expert_map,
|
||||
apply_router_weight_on_input,
|
||||
self.fused_experts.quant_config,
|
||||
)
|
||||
else:
|
||||
# Overlap shared expert compute with all2all dispatch.
|
||||
dbo_maybe_run_recv_hook()
|
||||
@@ -943,8 +994,9 @@ class FusedMoEModularKernel(torch.nn.Module):
|
||||
# TODO(lucas): refactor this in the alternative schedules followup
|
||||
# currently unpack if we have hook + receiver pair or just
|
||||
# receiver (see finalize_async docstring)
|
||||
hook, receiver = prepare_ret \
|
||||
if isinstance(prepare_ret, tuple) else (None, prepare_ret)
|
||||
hook, receiver = (
|
||||
prepare_ret if isinstance(prepare_ret, tuple) else (None, prepare_ret)
|
||||
)
|
||||
|
||||
if hook is not None:
|
||||
if dbo_enabled():
|
||||
@@ -956,13 +1008,19 @@ class FusedMoEModularKernel(torch.nn.Module):
|
||||
else:
|
||||
hook()
|
||||
|
||||
(a1q, a1q_scale, expert_tokens_meta, _expert_topk_ids,
|
||||
_expert_topk_weights) = receiver()
|
||||
(
|
||||
a1q,
|
||||
a1q_scale,
|
||||
expert_tokens_meta,
|
||||
_expert_topk_ids,
|
||||
_expert_topk_weights,
|
||||
) = receiver()
|
||||
|
||||
# Maybe prepare gathered topk_ids and topk_weights from other EP ranks.
|
||||
topk_ids = topk_ids if _expert_topk_ids is None else _expert_topk_ids
|
||||
topk_weights = (topk_weights if _expert_topk_weights is None else
|
||||
_expert_topk_weights)
|
||||
topk_weights = (
|
||||
topk_weights if _expert_topk_weights is None else _expert_topk_weights
|
||||
)
|
||||
|
||||
fused_out = None
|
||||
|
||||
@@ -1022,8 +1080,11 @@ class FusedMoEModularKernel(torch.nn.Module):
|
||||
# TODO(lucas): refactor this in the alternative schedules followup
|
||||
# currently unpack if we have hook + receiver pair or just
|
||||
# receiver (see finalize_async docstring)
|
||||
hook, receiver = finalize_ret \
|
||||
if isinstance(finalize_ret, tuple) else (None, finalize_ret)
|
||||
hook, receiver = (
|
||||
finalize_ret
|
||||
if isinstance(finalize_ret, tuple)
|
||||
else (None, finalize_ret)
|
||||
)
|
||||
|
||||
if hook is not None:
|
||||
if dbo_enabled():
|
||||
|
||||
@@ -14,7 +14,7 @@ def moe_align_block_size(
|
||||
block_size: int,
|
||||
num_experts: int,
|
||||
expert_map: Optional[torch.Tensor] = None,
|
||||
pad_sorted_ids: bool = False
|
||||
pad_sorted_ids: bool = False,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
"""
|
||||
Aligns the token distribution across experts to be compatible with block
|
||||
@@ -68,19 +68,18 @@ def moe_align_block_size(
|
||||
max_num_tokens_padded = topk_ids.numel() + num_experts * (block_size - 1)
|
||||
if pad_sorted_ids:
|
||||
max_num_tokens_padded = round_up(max_num_tokens_padded, block_size)
|
||||
sorted_ids = torch.empty((max_num_tokens_padded, ),
|
||||
dtype=torch.int32,
|
||||
device=topk_ids.device)
|
||||
sorted_ids = torch.empty(
|
||||
(max_num_tokens_padded,), dtype=torch.int32, device=topk_ids.device
|
||||
)
|
||||
max_num_m_blocks = triton.cdiv(max_num_tokens_padded, block_size)
|
||||
expert_ids = torch.empty((max_num_m_blocks, ),
|
||||
dtype=torch.int32,
|
||||
device=topk_ids.device)
|
||||
num_tokens_post_pad = torch.empty((1),
|
||||
dtype=torch.int32,
|
||||
device=topk_ids.device)
|
||||
expert_ids = torch.empty(
|
||||
(max_num_m_blocks,), dtype=torch.int32, device=topk_ids.device
|
||||
)
|
||||
num_tokens_post_pad = torch.empty((1), dtype=torch.int32, device=topk_ids.device)
|
||||
|
||||
ops.moe_align_block_size(topk_ids, num_experts, block_size, sorted_ids,
|
||||
expert_ids, num_tokens_post_pad)
|
||||
ops.moe_align_block_size(
|
||||
topk_ids, num_experts, block_size, sorted_ids, expert_ids, num_tokens_post_pad
|
||||
)
|
||||
if expert_map is not None:
|
||||
expert_ids = expert_map[expert_ids]
|
||||
|
||||
|
||||
@@ -7,18 +7,20 @@ import torch.nn.functional as F
|
||||
|
||||
def _histogram(input: torch.Tensor, min: int, max: int) -> torch.Tensor:
|
||||
"""
|
||||
Compute the histogram of an int32 tensor. The bin edges are defined by the
|
||||
min and max values, with step = 1.
|
||||
"""
|
||||
Compute the histogram of an int32 tensor. The bin edges are defined by the
|
||||
min and max values, with step = 1.
|
||||
"""
|
||||
assert input.dtype == torch.int32, "input must be of torch.int32 dtype."
|
||||
assert min <= max, "min must be less than or equal to max."
|
||||
|
||||
def searchsorted(sorted_sequence: torch.Tensor,
|
||||
values_to_search: torch.Tensor) -> torch.Tensor:
|
||||
def searchsorted(
|
||||
sorted_sequence: torch.Tensor, values_to_search: torch.Tensor
|
||||
) -> torch.Tensor:
|
||||
return (sorted_sequence.unsqueeze(1) == values_to_search).sum(dim=1)
|
||||
|
||||
bin_edges = torch.linspace(min, max, max - min + 1,
|
||||
dtype=input.dtype).to(input.device)
|
||||
bin_edges = torch.linspace(min, max, max - min + 1, dtype=input.dtype).to(
|
||||
input.device
|
||||
)
|
||||
return searchsorted(bin_edges, input).to(torch.int32)
|
||||
|
||||
|
||||
@@ -41,6 +43,7 @@ def fused_moe(
|
||||
"""
|
||||
assert expert_map is None, "expert_map is not supported for pallas MoE."
|
||||
import torch_xla.experimental.custom_kernel # noqa: F401
|
||||
|
||||
orig_shape = hidden_states.shape
|
||||
hidden_size = hidden_states.shape[-1]
|
||||
num_tokens = hidden_states.shape[:-1].numel()
|
||||
@@ -50,7 +53,8 @@ def fused_moe(
|
||||
dtype = hidden_states.dtype
|
||||
assert (num_tokens * topk) % 16 == 0, (
|
||||
"The Pallas GMM kernel requires num_tokens * topk to be a multiple of "
|
||||
f"16 but got {num_tokens * topk}")
|
||||
f"16 but got {num_tokens * topk}"
|
||||
)
|
||||
|
||||
hidden_states = hidden_states.view(num_tokens, hidden_size)
|
||||
gating_output = gating_output.view(num_tokens, num_experts)
|
||||
@@ -63,8 +67,7 @@ def fused_moe(
|
||||
topk_indices = topk_indices.flatten()
|
||||
topk_argsort_indices = topk_indices.argsort()
|
||||
topk_argsort_revert_indices = topk_argsort_indices.argsort()
|
||||
token_indices = torch.arange(num_tokens,
|
||||
device=device).repeat_interleave(topk)
|
||||
token_indices = torch.arange(num_tokens, device=device).repeat_interleave(topk)
|
||||
token_indices = token_indices[topk_argsort_indices]
|
||||
group_sizes = _histogram(topk_indices.to(torch.int32), 0, num_experts - 1)
|
||||
|
||||
|
||||
@@ -6,7 +6,8 @@ import torch
|
||||
|
||||
from vllm import _custom_ops as ops
|
||||
from vllm.model_executor.layers.fused_moe.moe_align_block_size import (
|
||||
moe_align_block_size)
|
||||
moe_align_block_size,
|
||||
)
|
||||
from vllm.model_executor.layers.fused_moe.utils import _fp8_perm
|
||||
|
||||
|
||||
@@ -17,8 +18,9 @@ def _moe_permute(
|
||||
global_num_experts: int,
|
||||
expert_map: Optional[torch.Tensor],
|
||||
block_m: int,
|
||||
) -> tuple[torch.Tensor, Optional[torch.Tensor], torch.Tensor, torch.Tensor,
|
||||
torch.Tensor]:
|
||||
) -> tuple[
|
||||
torch.Tensor, Optional[torch.Tensor], torch.Tensor, torch.Tensor, torch.Tensor
|
||||
]:
|
||||
"""
|
||||
Determine the sorted_token_ids, expert_ids for the given problem size.
|
||||
Permute the hidden states and scales according to `sorted_token_ids`.
|
||||
@@ -27,12 +29,9 @@ def _moe_permute(
|
||||
|
||||
tokens_in_chunk = curr_hidden_states.size(0)
|
||||
|
||||
sorted_token_ids, expert_ids, num_tokens_post_padded = (
|
||||
moe_align_block_size(curr_topk_ids,
|
||||
block_m,
|
||||
global_num_experts,
|
||||
expert_map,
|
||||
pad_sorted_ids=True))
|
||||
sorted_token_ids, expert_ids, num_tokens_post_padded = moe_align_block_size(
|
||||
curr_topk_ids, block_m, global_num_experts, expert_map, pad_sorted_ids=True
|
||||
)
|
||||
|
||||
inv_perm: Optional[torch.Tensor] = None
|
||||
|
||||
@@ -43,14 +42,12 @@ def _moe_permute(
|
||||
# Permute according to sorted token ids.
|
||||
sorted_token_ids = sorted_token_ids.clamp(max=num_tokens - 1)
|
||||
|
||||
curr_hidden_states = _fp8_perm(curr_hidden_states,
|
||||
sorted_token_ids // top_k_num)
|
||||
curr_hidden_states = _fp8_perm(curr_hidden_states, sorted_token_ids // top_k_num)
|
||||
|
||||
if a1q_scale is not None:
|
||||
a1q_scale = a1q_scale[sorted_token_ids // top_k_num]
|
||||
|
||||
return (curr_hidden_states, a1q_scale, sorted_token_ids, expert_ids,
|
||||
inv_perm)
|
||||
return (curr_hidden_states, a1q_scale, sorted_token_ids, expert_ids, inv_perm)
|
||||
|
||||
|
||||
def _moe_unpermute_and_reduce(
|
||||
@@ -84,8 +81,9 @@ def moe_permute(
|
||||
align_block_size: Optional[int] = None,
|
||||
fill_invalid_expert: int = -1,
|
||||
permuted_hidden_states: Optional[torch.Tensor] = None,
|
||||
) -> tuple[torch.Tensor, Optional[torch.Tensor], torch.Tensor, torch.Tensor,
|
||||
torch.Tensor]:
|
||||
) -> tuple[
|
||||
torch.Tensor, Optional[torch.Tensor], torch.Tensor, torch.Tensor, torch.Tensor
|
||||
]:
|
||||
"""
|
||||
This function expands and permutes activation to gather uncontinuous tokens
|
||||
for each expert.
|
||||
@@ -117,13 +115,21 @@ def moe_permute(
|
||||
"""
|
||||
n_token, n_hidden = hidden_states.size()
|
||||
topk = topk_ids.size(1)
|
||||
assert (n_hidden * hidden_states.element_size()
|
||||
) % 16 == 0, "permue kernel need hidden dim align to 16B"
|
||||
assert (n_hidden * hidden_states.element_size()) % 16 == 0, (
|
||||
"permue kernel need hidden dim align to 16B"
|
||||
)
|
||||
permuted_row_size = n_token * topk
|
||||
if align_block_size is not None:
|
||||
permuted_row_size = (permuted_row_size + n_expert *
|
||||
(align_block_size - 1) + align_block_size -
|
||||
1) // align_block_size * align_block_size
|
||||
permuted_row_size = (
|
||||
(
|
||||
permuted_row_size
|
||||
+ n_expert * (align_block_size - 1)
|
||||
+ align_block_size
|
||||
- 1
|
||||
)
|
||||
// align_block_size
|
||||
* align_block_size
|
||||
)
|
||||
if n_local_expert == -1:
|
||||
n_local_expert = n_expert
|
||||
if permuted_hidden_states is None:
|
||||
@@ -134,40 +140,57 @@ def moe_permute(
|
||||
)
|
||||
assert permuted_hidden_states.size() == (permuted_row_size, n_hidden), (
|
||||
f"Expected permuted hidden states to be {(permuted_row_size, n_hidden)}"
|
||||
f" but got {permuted_hidden_states.size()}")
|
||||
f" but got {permuted_hidden_states.size()}"
|
||||
)
|
||||
|
||||
token_expert_indices = torch.arange(0,
|
||||
n_token * topk,
|
||||
dtype=torch.int32,
|
||||
device=hidden_states.device).reshape(
|
||||
(n_token, topk))
|
||||
token_expert_indices = torch.arange(
|
||||
0, n_token * topk, dtype=torch.int32, device=hidden_states.device
|
||||
).reshape((n_token, topk))
|
||||
|
||||
m_indices = torch.full((permuted_row_size, ),
|
||||
fill_invalid_expert,
|
||||
dtype=torch.int32,
|
||||
device=hidden_states.device)
|
||||
expert_first_token_offset = torch.empty(n_local_expert + 1,
|
||||
dtype=torch.int64,
|
||||
device=hidden_states.device)
|
||||
permuted_idx = torch.full((permuted_row_size, ),
|
||||
n_token * topk,
|
||||
dtype=torch.int32,
|
||||
device=hidden_states.device)
|
||||
inv_permuted_idx = torch.empty((n_token, topk),
|
||||
dtype=torch.int32,
|
||||
device=hidden_states.device)
|
||||
m_indices = torch.full(
|
||||
(permuted_row_size,),
|
||||
fill_invalid_expert,
|
||||
dtype=torch.int32,
|
||||
device=hidden_states.device,
|
||||
)
|
||||
expert_first_token_offset = torch.empty(
|
||||
n_local_expert + 1, dtype=torch.int64, device=hidden_states.device
|
||||
)
|
||||
permuted_idx = torch.full(
|
||||
(permuted_row_size,),
|
||||
n_token * topk,
|
||||
dtype=torch.int32,
|
||||
device=hidden_states.device,
|
||||
)
|
||||
inv_permuted_idx = torch.empty(
|
||||
(n_token, topk), dtype=torch.int32, device=hidden_states.device
|
||||
)
|
||||
topk_ids = topk_ids.to(torch.int32)
|
||||
torch.ops._moe_C.moe_permute(hidden_states, topk_ids, token_expert_indices,
|
||||
expert_map, n_expert, n_local_expert, topk,
|
||||
align_block_size, permuted_hidden_states,
|
||||
expert_first_token_offset, inv_permuted_idx,
|
||||
permuted_idx, m_indices)
|
||||
torch.ops._moe_C.moe_permute(
|
||||
hidden_states,
|
||||
topk_ids,
|
||||
token_expert_indices,
|
||||
expert_map,
|
||||
n_expert,
|
||||
n_local_expert,
|
||||
topk,
|
||||
align_block_size,
|
||||
permuted_hidden_states,
|
||||
expert_first_token_offset,
|
||||
inv_permuted_idx,
|
||||
permuted_idx,
|
||||
m_indices,
|
||||
)
|
||||
|
||||
if a1q_scale is not None and a1q_scale.dim() > 1:
|
||||
a1q_scale = a1q_scale[permuted_idx.clamp(max=n_token * topk - 1) //
|
||||
topk]
|
||||
return (permuted_hidden_states, a1q_scale, expert_first_token_offset,
|
||||
inv_permuted_idx.flatten(), m_indices)
|
||||
a1q_scale = a1q_scale[permuted_idx.clamp(max=n_token * topk - 1) // topk]
|
||||
return (
|
||||
permuted_hidden_states,
|
||||
a1q_scale,
|
||||
expert_first_token_offset,
|
||||
inv_permuted_idx.flatten(),
|
||||
m_indices,
|
||||
)
|
||||
|
||||
|
||||
def moe_unpermute(
|
||||
@@ -185,7 +208,7 @@ def moe_unpermute(
|
||||
- permuted_hidden_states (torch.Tensor): permuted activation.
|
||||
- topk_weights (torch.Tensor): topk expert route weight for each token.
|
||||
- inv_permuted_idx (torch.Tensor): row idx map for moe_unpermute.
|
||||
- expert_first_token_offset (Optional[torch.Tensor]): offset of the first
|
||||
- expert_first_token_offset (Optional[torch.Tensor]): offset of the first
|
||||
token of each expert for grouped gemm.
|
||||
Returns:
|
||||
- hidden_states (torch.Tensor): The reduced and unpermuted activation
|
||||
@@ -193,12 +216,18 @@ def moe_unpermute(
|
||||
"""
|
||||
topk = topk_weights.size(1)
|
||||
n_hidden = permuted_hidden_states.size(-1)
|
||||
assert (n_hidden * permuted_hidden_states.element_size()
|
||||
) % 16 == 0, "unpermue kernel need hidden dim align to 16B"
|
||||
assert (n_hidden * permuted_hidden_states.element_size()) % 16 == 0, (
|
||||
"unpermue kernel need hidden dim align to 16B"
|
||||
)
|
||||
|
||||
torch.ops._moe_C.moe_unpermute(permuted_hidden_states, topk_weights,
|
||||
inv_permuted_idx, expert_first_token_offset,
|
||||
topk, out)
|
||||
torch.ops._moe_C.moe_unpermute(
|
||||
permuted_hidden_states,
|
||||
topk_weights,
|
||||
inv_permuted_idx,
|
||||
expert_first_token_offset,
|
||||
topk,
|
||||
out,
|
||||
)
|
||||
|
||||
|
||||
def moe_permute_unpermute_supported():
|
||||
|
||||
@@ -45,7 +45,7 @@ def fused_moe(
|
||||
for expert_idx in range(num_experts):
|
||||
expert_w1 = w1[expert_idx]
|
||||
expert_w2 = w2[expert_idx]
|
||||
expert_mask = (selected_experts == expert_idx)
|
||||
expert_mask = selected_experts == expert_idx
|
||||
expert_weights = (topk_weights * expert_mask).sum(dim=-1, keepdim=True)
|
||||
x = F.linear(hidden_states, expert_w1)
|
||||
gate = F.silu(x[:, :intermediate_size])
|
||||
|
||||
@@ -9,9 +9,12 @@ import vllm.model_executor.layers.fused_moe.modular_kernel as mk
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.fused_moe.config import FusedMoEQuantConfig
|
||||
from vllm.model_executor.layers.fused_moe.topk_weight_and_reduce import (
|
||||
TopKWeightAndReduceDelegate)
|
||||
TopKWeightAndReduceDelegate,
|
||||
)
|
||||
from vllm.model_executor.layers.fused_moe.utils import (
|
||||
_validate_scale_shape, moe_kernel_quantize_input)
|
||||
_validate_scale_shape,
|
||||
moe_kernel_quantize_input,
|
||||
)
|
||||
from vllm.utils import cdiv, round_up
|
||||
|
||||
logger = init_logger(__name__)
|
||||
@@ -60,7 +63,6 @@ def pplx_hidden_dim_scale_bytes(
|
||||
|
||||
|
||||
class PplxPrepareAndFinalize(mk.FusedMoEPrepareAndFinalize):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
a2a: pplx.AllToAll,
|
||||
@@ -113,8 +115,9 @@ class PplxPrepareAndFinalize(mk.FusedMoEPrepareAndFinalize):
|
||||
if expert_map is not None:
|
||||
logger.warning_once(
|
||||
"The PPLX backend does not support expert mapping. "
|
||||
"The provided `expert_map` will be ignored.")
|
||||
expert_map = None #noqa: F841
|
||||
"The provided `expert_map` will be ignored."
|
||||
)
|
||||
expert_map = None # noqa: F841
|
||||
|
||||
# Is this always going to be a1.device?
|
||||
device = a1.device
|
||||
@@ -123,21 +126,24 @@ class PplxPrepareAndFinalize(mk.FusedMoEPrepareAndFinalize):
|
||||
topk = topk_ids.size(1)
|
||||
# TODO: this only works for topK=1, will need to update for topK>1
|
||||
assert topk == 1, (
|
||||
"apply_router_weight_on_input is only implemented for topk=1")
|
||||
"apply_router_weight_on_input is only implemented for topk=1"
|
||||
)
|
||||
a1 = a1 * topk_weights.to(a1.dtype)
|
||||
|
||||
repeat_cols = 4
|
||||
repeat_rows = 1 if quant_config.per_act_token_quant else a1.size(0)
|
||||
# TODO(bnell): always pass quant_config.a1_scale?
|
||||
a1q, a1q_scale = moe_kernel_quantize_input(
|
||||
a1, (None if quant_config.per_act_token_quant else
|
||||
quant_config.a1_scale),
|
||||
a1,
|
||||
(None if quant_config.per_act_token_quant else quant_config.a1_scale),
|
||||
quant_dtype=quant_config.quant_dtype,
|
||||
per_act_token_quant=quant_config.per_act_token_quant,
|
||||
block_shape=quant_config.block_shape)
|
||||
block_shape=quant_config.block_shape,
|
||||
)
|
||||
|
||||
_validate_scale_shape(a1q, a1q_scale, quant_config.per_act_token_quant,
|
||||
quant_config.block_shape)
|
||||
_validate_scale_shape(
|
||||
a1q, a1q_scale, quant_config.per_act_token_quant, quant_config.block_shape
|
||||
)
|
||||
|
||||
orig_a_scale_block_shape: Optional[int] = None
|
||||
|
||||
@@ -155,8 +161,9 @@ class PplxPrepareAndFinalize(mk.FusedMoEPrepareAndFinalize):
|
||||
# TODO (bnell): use group_broadcast instead?
|
||||
a1q_scale = a1q_scale.repeat(repeat_rows, repeat_cols)
|
||||
|
||||
assert a1q_scale is None or a1q_scale.ndim == 2, \
|
||||
assert a1q_scale is None or a1q_scale.ndim == 2, (
|
||||
f"{0 if a1q_scale is None else (a1q_scale.ndim, a1q_scale.shape)}"
|
||||
)
|
||||
|
||||
expert_num_tokens = torch.empty(
|
||||
self.num_local_experts,
|
||||
@@ -165,8 +172,11 @@ class PplxPrepareAndFinalize(mk.FusedMoEPrepareAndFinalize):
|
||||
)
|
||||
|
||||
expert_x = torch.empty(
|
||||
(self.num_local_experts,
|
||||
self.max_num_tokens * self.num_dispatchers(), hidden_dim),
|
||||
(
|
||||
self.num_local_experts,
|
||||
self.max_num_tokens * self.num_dispatchers(),
|
||||
hidden_dim,
|
||||
),
|
||||
dtype=a1q.dtype,
|
||||
device=device,
|
||||
)
|
||||
@@ -182,14 +192,13 @@ class PplxPrepareAndFinalize(mk.FusedMoEPrepareAndFinalize):
|
||||
else:
|
||||
# (M x K_tiles) -> (E x M x K_tiles)
|
||||
assert quant_config.block_shape is not None
|
||||
num_blocks = cdiv(expert_x.size(2),
|
||||
quant_config.block_shape[1])
|
||||
num_blocks = cdiv(expert_x.size(2), quant_config.block_shape[1])
|
||||
final_dim = num_blocks
|
||||
|
||||
expert_x_scale_shape = (
|
||||
self.num_local_experts,
|
||||
expert_x.size(1),
|
||||
round_up(final_dim, 4) # round up for alignment
|
||||
round_up(final_dim, 4), # round up for alignment
|
||||
)
|
||||
|
||||
expert_x_scale = torch.empty(
|
||||
@@ -226,12 +235,15 @@ class PplxPrepareAndFinalize(mk.FusedMoEPrepareAndFinalize):
|
||||
do_recv=True,
|
||||
)
|
||||
|
||||
return (hook, lambda: self._receiver(
|
||||
expert_num_tokens,
|
||||
expert_x,
|
||||
expert_x_scale,
|
||||
orig_a_scale_block_shape,
|
||||
))
|
||||
return (
|
||||
hook,
|
||||
lambda: self._receiver(
|
||||
expert_num_tokens,
|
||||
expert_x,
|
||||
expert_x_scale,
|
||||
orig_a_scale_block_shape,
|
||||
),
|
||||
)
|
||||
|
||||
def _receiver(
|
||||
self,
|
||||
@@ -240,13 +252,13 @@ class PplxPrepareAndFinalize(mk.FusedMoEPrepareAndFinalize):
|
||||
expert_x_scale: Optional[torch.Tensor],
|
||||
orig_a_scale_block_shape: Optional[int],
|
||||
) -> mk.PrepareResultType:
|
||||
|
||||
if expert_x_scale is not None:
|
||||
expert_x_scale = expert_x_scale[:, :, :orig_a_scale_block_shape]
|
||||
assert expert_x_scale.ndim == 3
|
||||
|
||||
expert_tokens_meta = mk.ExpertTokensMetadata(
|
||||
expert_num_tokens=expert_num_tokens, expert_num_tokens_cpu=None)
|
||||
expert_num_tokens=expert_num_tokens, expert_num_tokens_cpu=None
|
||||
)
|
||||
|
||||
return expert_x, expert_x_scale, expert_tokens_meta, None, None
|
||||
|
||||
@@ -281,22 +293,24 @@ class PplxPrepareAndFinalize(mk.FusedMoEPrepareAndFinalize):
|
||||
apply_router_weight_on_input: bool,
|
||||
weight_and_reduce_impl: mk.TopKWeightAndReduce,
|
||||
) -> Callable:
|
||||
assert isinstance(
|
||||
weight_and_reduce_impl, TopKWeightAndReduceDelegate
|
||||
), ("Weight application and reduction happens in the combine kernel.")
|
||||
assert isinstance(weight_and_reduce_impl, TopKWeightAndReduceDelegate), (
|
||||
"Weight application and reduction happens in the combine kernel."
|
||||
)
|
||||
|
||||
# This argument is optional
|
||||
# There's not much point setting this unless it is != topk_ids.size(0)
|
||||
bound_m: Optional[torch.Tensor] = None
|
||||
|
||||
# TODO (bnell): fails in test_pplx_moe.py, figure out what's going on
|
||||
#num_tokens = output.size(0) # M
|
||||
#assert topk_ids.size(0) == num_tokens, (
|
||||
# num_tokens = output.size(0) # M
|
||||
# assert topk_ids.size(0) == num_tokens, (
|
||||
# f"{topk_ids.size(0)} == {num_tokens}")
|
||||
assert topk_ids.size() == topk_weights.size(), (
|
||||
f"{topk_ids.size()} == {topk_weights.size()}")
|
||||
f"{topk_ids.size()} == {topk_weights.size()}"
|
||||
)
|
||||
assert output.size(0) <= self.max_num_tokens, (
|
||||
f"{output.size(0)} <= {self.max_num_tokens}")
|
||||
f"{output.size(0)} <= {self.max_num_tokens}"
|
||||
)
|
||||
assert output.size(1) == fused_expert_output.size(-1)
|
||||
|
||||
# Set weights to 1 if we did them in dispatch. This is hacky.
|
||||
@@ -305,21 +319,25 @@ class PplxPrepareAndFinalize(mk.FusedMoEPrepareAndFinalize):
|
||||
|
||||
topk_ids_u32 = topk_ids.view(dtype=torch.uint32)
|
||||
|
||||
self.a2a.combine(out_tokens=output,
|
||||
indices=topk_ids_u32,
|
||||
weights=topk_weights,
|
||||
expert_y=fused_expert_output,
|
||||
bound_m=bound_m,
|
||||
do_send=True,
|
||||
do_recv=False)
|
||||
self.a2a.combine(
|
||||
out_tokens=output,
|
||||
indices=topk_ids_u32,
|
||||
weights=topk_weights,
|
||||
expert_y=fused_expert_output,
|
||||
bound_m=bound_m,
|
||||
do_send=True,
|
||||
do_recv=False,
|
||||
)
|
||||
|
||||
return lambda: self.a2a.combine(out_tokens=output,
|
||||
indices=topk_ids_u32,
|
||||
weights=topk_weights,
|
||||
expert_y=fused_expert_output,
|
||||
bound_m=bound_m,
|
||||
do_send=False,
|
||||
do_recv=True)
|
||||
return lambda: self.a2a.combine(
|
||||
out_tokens=output,
|
||||
indices=topk_ids_u32,
|
||||
weights=topk_weights,
|
||||
expert_y=fused_expert_output,
|
||||
bound_m=bound_m,
|
||||
do_send=False,
|
||||
do_recv=True,
|
||||
)
|
||||
|
||||
def finalize(
|
||||
self,
|
||||
|
||||
@@ -7,13 +7,13 @@ import torch
|
||||
import vllm.model_executor.layers.fused_moe.modular_kernel as mk
|
||||
from vllm.model_executor.layers.fused_moe.config import FusedMoEQuantConfig
|
||||
from vllm.model_executor.layers.fused_moe.topk_weight_and_reduce import (
|
||||
TopKWeightAndReduceContiguous, TopKWeightAndReduceDelegate)
|
||||
from vllm.model_executor.layers.fused_moe.utils import (
|
||||
moe_kernel_quantize_input)
|
||||
TopKWeightAndReduceContiguous,
|
||||
TopKWeightAndReduceDelegate,
|
||||
)
|
||||
from vllm.model_executor.layers.fused_moe.utils import moe_kernel_quantize_input
|
||||
|
||||
|
||||
class MoEPrepareAndFinalizeNoEP(mk.FusedMoEPrepareAndFinalize):
|
||||
|
||||
@property
|
||||
def activation_format(self) -> mk.FusedMoEActivationFormat:
|
||||
return mk.FusedMoEActivationFormat.Standard
|
||||
@@ -37,17 +37,21 @@ class MoEPrepareAndFinalizeNoEP(mk.FusedMoEPrepareAndFinalize):
|
||||
apply_router_weight_on_input: bool,
|
||||
quant_config: FusedMoEQuantConfig,
|
||||
) -> mk.PrepareResultType:
|
||||
|
||||
if apply_router_weight_on_input:
|
||||
topk = topk_ids.size(1)
|
||||
# TODO: this only works for topK=1, will need to update for topK>1
|
||||
assert topk == 1, \
|
||||
assert topk == 1, (
|
||||
"apply_router_weight_on_input is only implemented for topk=1"
|
||||
)
|
||||
a1.mul_(topk_weights.to(a1.dtype))
|
||||
|
||||
a1q, a1q_scale = moe_kernel_quantize_input(
|
||||
a1, quant_config.a1_scale, quant_config.quant_dtype,
|
||||
quant_config.per_act_token_quant, quant_config.block_shape)
|
||||
a1,
|
||||
quant_config.a1_scale,
|
||||
quant_config.quant_dtype,
|
||||
quant_config.per_act_token_quant,
|
||||
quant_config.block_shape,
|
||||
)
|
||||
|
||||
return a1q, a1q_scale, None, None, None
|
||||
|
||||
@@ -67,4 +71,5 @@ class MoEPrepareAndFinalizeNoEP(mk.FusedMoEPrepareAndFinalize):
|
||||
fused_expert_output=fused_expert_output,
|
||||
topk_weights=topk_weights,
|
||||
topk_ids=topk_ids,
|
||||
apply_router_weight_on_input=apply_router_weight_on_input)
|
||||
apply_router_weight_on_input=apply_router_weight_on_input,
|
||||
)
|
||||
|
||||
@@ -8,7 +8,9 @@ import torch
|
||||
|
||||
from vllm import envs
|
||||
from vllm.model_executor.layers.fused_moe.config import (
|
||||
FUSED_MOE_UNQUANTIZED_CONFIG, FusedMoEQuantConfig)
|
||||
FUSED_MOE_UNQUANTIZED_CONFIG,
|
||||
FusedMoEQuantConfig,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils import direct_register_custom_op
|
||||
|
||||
@@ -38,138 +40,162 @@ class ActivationMethod(IntEnum):
|
||||
|
||||
@cache
|
||||
def is_rocm_aiter_moe_enabled() -> bool:
|
||||
return current_platform.is_rocm() \
|
||||
and envs.VLLM_ROCM_USE_AITER_MOE \
|
||||
return (
|
||||
current_platform.is_rocm()
|
||||
and envs.VLLM_ROCM_USE_AITER_MOE
|
||||
and envs.VLLM_ROCM_USE_AITER
|
||||
)
|
||||
|
||||
|
||||
def rocm_aiter_asm_moe_tkw1_impl(
|
||||
hidden_states: torch.Tensor,
|
||||
w1: torch.Tensor,
|
||||
w2: torch.Tensor,
|
||||
topk_weights: torch.Tensor,
|
||||
topk_ids: torch.Tensor,
|
||||
fc1_scale: Optional[torch.Tensor] = None,
|
||||
fc2_scale: Optional[torch.Tensor] = None,
|
||||
fc1_smooth_scale: Optional[torch.Tensor] = None,
|
||||
fc2_smooth_scale: Optional[torch.Tensor] = None,
|
||||
a16: bool = False,
|
||||
per_tensor_quant_scale: Optional[torch.Tensor] = None,
|
||||
expert_mask: Optional[torch.Tensor] = None,
|
||||
activation_method: int = ActivationMethod.SILU.value) -> torch.Tensor:
|
||||
|
||||
hidden_states: torch.Tensor,
|
||||
w1: torch.Tensor,
|
||||
w2: torch.Tensor,
|
||||
topk_weights: torch.Tensor,
|
||||
topk_ids: torch.Tensor,
|
||||
fc1_scale: Optional[torch.Tensor] = None,
|
||||
fc2_scale: Optional[torch.Tensor] = None,
|
||||
fc1_smooth_scale: Optional[torch.Tensor] = None,
|
||||
fc2_smooth_scale: Optional[torch.Tensor] = None,
|
||||
a16: bool = False,
|
||||
per_tensor_quant_scale: Optional[torch.Tensor] = None,
|
||||
expert_mask: Optional[torch.Tensor] = None,
|
||||
activation_method: int = ActivationMethod.SILU.value,
|
||||
) -> torch.Tensor:
|
||||
from aiter import ActivationType
|
||||
from aiter.fused_moe_bf16_asm import asm_moe_tkw1
|
||||
|
||||
activation = ActivationType(activation_method)
|
||||
|
||||
return asm_moe_tkw1(hidden_states,
|
||||
w1,
|
||||
w2,
|
||||
topk_weights,
|
||||
topk_ids,
|
||||
fc1_scale=fc1_scale,
|
||||
fc2_scale=fc2_scale,
|
||||
fc1_smooth_scale=fc1_smooth_scale,
|
||||
fc2_smooth_scale=fc2_smooth_scale,
|
||||
a16=a16,
|
||||
per_tensor_quant_scale=per_tensor_quant_scale,
|
||||
expert_mask=expert_mask,
|
||||
activation=activation)
|
||||
return asm_moe_tkw1(
|
||||
hidden_states,
|
||||
w1,
|
||||
w2,
|
||||
topk_weights,
|
||||
topk_ids,
|
||||
fc1_scale=fc1_scale,
|
||||
fc2_scale=fc2_scale,
|
||||
fc1_smooth_scale=fc1_smooth_scale,
|
||||
fc2_smooth_scale=fc2_smooth_scale,
|
||||
a16=a16,
|
||||
per_tensor_quant_scale=per_tensor_quant_scale,
|
||||
expert_mask=expert_mask,
|
||||
activation=activation,
|
||||
)
|
||||
|
||||
|
||||
def rocm_aiter_asm_moe_tkw1_fake(
|
||||
hidden_states: torch.Tensor,
|
||||
w1: torch.Tensor,
|
||||
w2: torch.Tensor,
|
||||
topk_weights: torch.Tensor,
|
||||
topk_ids: torch.Tensor,
|
||||
fc1_scale: Optional[torch.Tensor] = None,
|
||||
fc2_scale: Optional[torch.Tensor] = None,
|
||||
fc1_smooth_scale: Optional[torch.Tensor] = None,
|
||||
fc2_smooth_scale: Optional[torch.Tensor] = None,
|
||||
a16: bool = False,
|
||||
per_tensor_quant_scale: Optional[torch.Tensor] = None,
|
||||
expert_mask: Optional[torch.Tensor] = None,
|
||||
activation_method: int = ActivationMethod.SILU.value) -> torch.Tensor:
|
||||
hidden_states: torch.Tensor,
|
||||
w1: torch.Tensor,
|
||||
w2: torch.Tensor,
|
||||
topk_weights: torch.Tensor,
|
||||
topk_ids: torch.Tensor,
|
||||
fc1_scale: Optional[torch.Tensor] = None,
|
||||
fc2_scale: Optional[torch.Tensor] = None,
|
||||
fc1_smooth_scale: Optional[torch.Tensor] = None,
|
||||
fc2_smooth_scale: Optional[torch.Tensor] = None,
|
||||
a16: bool = False,
|
||||
per_tensor_quant_scale: Optional[torch.Tensor] = None,
|
||||
expert_mask: Optional[torch.Tensor] = None,
|
||||
activation_method: int = ActivationMethod.SILU.value,
|
||||
) -> torch.Tensor:
|
||||
return torch.empty_like(hidden_states)
|
||||
|
||||
|
||||
def rocm_aiter_topk_softmax_impl(topk_weights: torch.Tensor,
|
||||
topk_indices: torch.Tensor,
|
||||
token_expert_indices: torch.Tensor,
|
||||
gating_output: torch.Tensor,
|
||||
renormalize: bool) -> None:
|
||||
def rocm_aiter_topk_softmax_impl(
|
||||
topk_weights: torch.Tensor,
|
||||
topk_indices: torch.Tensor,
|
||||
token_expert_indices: torch.Tensor,
|
||||
gating_output: torch.Tensor,
|
||||
renormalize: bool,
|
||||
) -> None:
|
||||
from aiter import topk_softmax
|
||||
topk_softmax(topk_weights, topk_indices, token_expert_indices,
|
||||
gating_output, renormalize)
|
||||
|
||||
topk_softmax(
|
||||
topk_weights, topk_indices, token_expert_indices, gating_output, renormalize
|
||||
)
|
||||
|
||||
|
||||
def rocm_aiter_topk_softmax_fake(topk_weights: torch.Tensor,
|
||||
topk_indices: torch.Tensor,
|
||||
token_expert_indices: torch.Tensor,
|
||||
gating_output: torch.Tensor,
|
||||
renormalize: bool) -> None:
|
||||
def rocm_aiter_topk_softmax_fake(
|
||||
topk_weights: torch.Tensor,
|
||||
topk_indices: torch.Tensor,
|
||||
token_expert_indices: torch.Tensor,
|
||||
gating_output: torch.Tensor,
|
||||
renormalize: bool,
|
||||
) -> None:
|
||||
pass
|
||||
|
||||
|
||||
def rocm_aiter_biased_grouped_topk_impl(
|
||||
gating_output: torch.Tensor,
|
||||
correction_bias: torch.Tensor,
|
||||
topk_weights: torch.Tensor,
|
||||
topk_ids: torch.Tensor,
|
||||
num_expert_group: int,
|
||||
topk_group: int,
|
||||
need_renorm: bool,
|
||||
routed_scaling_factor: float = 1.0 # mul to topk_weights
|
||||
gating_output: torch.Tensor,
|
||||
correction_bias: torch.Tensor,
|
||||
topk_weights: torch.Tensor,
|
||||
topk_ids: torch.Tensor,
|
||||
num_expert_group: int,
|
||||
topk_group: int,
|
||||
need_renorm: bool,
|
||||
routed_scaling_factor: float = 1.0, # mul to topk_weights
|
||||
) -> None:
|
||||
|
||||
from aiter import biased_grouped_topk
|
||||
|
||||
biased_grouped_topk(gating_output, correction_bias, topk_weights, topk_ids,
|
||||
num_expert_group, topk_group, need_renorm,
|
||||
routed_scaling_factor)
|
||||
biased_grouped_topk(
|
||||
gating_output,
|
||||
correction_bias,
|
||||
topk_weights,
|
||||
topk_ids,
|
||||
num_expert_group,
|
||||
topk_group,
|
||||
need_renorm,
|
||||
routed_scaling_factor,
|
||||
)
|
||||
|
||||
|
||||
def rocm_aiter_biased_grouped_topk_fake(
|
||||
gating_output: torch.Tensor,
|
||||
correction_bias: torch.Tensor,
|
||||
topk_weights: torch.Tensor,
|
||||
topk_ids: torch.Tensor,
|
||||
num_expert_group: int,
|
||||
topk_group: int,
|
||||
need_renorm: bool,
|
||||
routed_scaling_factor: float = 1.0 # mul to topk_weights
|
||||
gating_output: torch.Tensor,
|
||||
correction_bias: torch.Tensor,
|
||||
topk_weights: torch.Tensor,
|
||||
topk_ids: torch.Tensor,
|
||||
num_expert_group: int,
|
||||
topk_group: int,
|
||||
need_renorm: bool,
|
||||
routed_scaling_factor: float = 1.0, # mul to topk_weights
|
||||
) -> None:
|
||||
pass
|
||||
|
||||
|
||||
def rocm_aiter_grouped_topk_impl(
|
||||
gating_output: torch.Tensor,
|
||||
topk_weights: torch.Tensor,
|
||||
topk_ids: torch.Tensor,
|
||||
num_expert_group: int,
|
||||
topk_group: int,
|
||||
need_renorm: bool,
|
||||
scoring_func: str = "softmax",
|
||||
routed_scaling_factor: float = 1.0 # mul to topk_weights
|
||||
gating_output: torch.Tensor,
|
||||
topk_weights: torch.Tensor,
|
||||
topk_ids: torch.Tensor,
|
||||
num_expert_group: int,
|
||||
topk_group: int,
|
||||
need_renorm: bool,
|
||||
scoring_func: str = "softmax",
|
||||
routed_scaling_factor: float = 1.0, # mul to topk_weights
|
||||
) -> None:
|
||||
|
||||
from aiter import grouped_topk
|
||||
|
||||
grouped_topk(gating_output, topk_weights, topk_ids, num_expert_group,
|
||||
topk_group, need_renorm, scoring_func, routed_scaling_factor)
|
||||
grouped_topk(
|
||||
gating_output,
|
||||
topk_weights,
|
||||
topk_ids,
|
||||
num_expert_group,
|
||||
topk_group,
|
||||
need_renorm,
|
||||
scoring_func,
|
||||
routed_scaling_factor,
|
||||
)
|
||||
|
||||
|
||||
def rocm_aiter_grouped_topk_fake(
|
||||
gating_output: torch.Tensor,
|
||||
topk_weights: torch.Tensor,
|
||||
topk_ids: torch.Tensor,
|
||||
num_expert_group: int,
|
||||
topk_group: int,
|
||||
need_renorm: bool,
|
||||
scoring_func: str = "softmax",
|
||||
routed_scaling_factor: float = 1.0 # mul to topk_weights
|
||||
gating_output: torch.Tensor,
|
||||
topk_weights: torch.Tensor,
|
||||
topk_ids: torch.Tensor,
|
||||
num_expert_group: int,
|
||||
topk_group: int,
|
||||
need_renorm: bool,
|
||||
scoring_func: str = "softmax",
|
||||
routed_scaling_factor: float = 1.0, # mul to topk_weights
|
||||
) -> None:
|
||||
pass
|
||||
|
||||
@@ -195,9 +221,21 @@ def rocm_aiter_fused_moe_impl(
|
||||
activation = ActivationType(activation_method)
|
||||
quant_type = QuantType(quant_method)
|
||||
|
||||
return fused_moe(hidden_states, w1, w2, topk_weight, topk_ids, expert_mask,
|
||||
activation, quant_type, doweight_stage1, w1_scale,
|
||||
w2_scale, a1_scale, a2_scale)
|
||||
return fused_moe(
|
||||
hidden_states,
|
||||
w1,
|
||||
w2,
|
||||
topk_weight,
|
||||
topk_ids,
|
||||
expert_mask,
|
||||
activation,
|
||||
quant_type,
|
||||
doweight_stage1,
|
||||
w1_scale,
|
||||
w2_scale,
|
||||
a1_scale,
|
||||
a2_scale,
|
||||
)
|
||||
|
||||
|
||||
def rocm_aiter_fused_moe_fake(
|
||||
@@ -219,7 +257,6 @@ def rocm_aiter_fused_moe_fake(
|
||||
|
||||
|
||||
if current_platform.is_rocm():
|
||||
|
||||
direct_register_custom_op(
|
||||
op_name="rocm_aiter_asm_moe_tkw1",
|
||||
op_func=rocm_aiter_asm_moe_tkw1_impl,
|
||||
@@ -263,14 +300,12 @@ def rocm_aiter_grouped_topk(
|
||||
topk_group: int = 0,
|
||||
scoring_func: str = "softmax",
|
||||
routed_scaling_factor: float = 1.0,
|
||||
e_score_correction_bias: Optional[torch.Tensor] = None
|
||||
e_score_correction_bias: Optional[torch.Tensor] = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
token = hidden_states.shape[0]
|
||||
device = hidden_states.device
|
||||
topk_ids = torch.empty((token, topk), dtype=torch.int32, device=device)
|
||||
topk_weights = torch.empty((token, topk),
|
||||
dtype=torch.float32,
|
||||
device=device)
|
||||
topk_weights = torch.empty((token, topk), dtype=torch.float32, device=device)
|
||||
|
||||
if e_score_correction_bias is not None:
|
||||
torch.ops.vllm.rocm_aiter_biased_grouped_topk(
|
||||
@@ -283,7 +318,7 @@ def rocm_aiter_grouped_topk(
|
||||
renormalize,
|
||||
)
|
||||
else:
|
||||
assert (scoring_func == "softmax" or scoring_func == "sigmoid")
|
||||
assert scoring_func == "softmax" or scoring_func == "sigmoid"
|
||||
torch.ops.vllm.rocm_aiter_grouped_topk(
|
||||
gating_output,
|
||||
topk_weights,
|
||||
@@ -313,8 +348,9 @@ def rocm_aiter_fused_experts(
|
||||
if quant_config is None:
|
||||
quant_config = FUSED_MOE_UNQUANTIZED_CONFIG
|
||||
|
||||
activation_method = (ActivationMethod.SILU
|
||||
if activation == "silu" else ActivationMethod.GELU)
|
||||
activation_method = (
|
||||
ActivationMethod.SILU if activation == "silu" else ActivationMethod.GELU
|
||||
)
|
||||
# All AITER Fused MoE kernels are expecting the following datatypes
|
||||
topk_weights = topk_weights.to(torch.float32)
|
||||
topk_ids = topk_ids.to(torch.int32)
|
||||
@@ -325,16 +361,20 @@ def rocm_aiter_fused_experts(
|
||||
expert_mask = None
|
||||
|
||||
# w8a8 per-channel quantization
|
||||
if (quant_config.per_act_token_quant and apply_router_weight_on_input
|
||||
and quant_config.use_fp8_w8a8):
|
||||
if (
|
||||
quant_config.per_act_token_quant
|
||||
and apply_router_weight_on_input
|
||||
and quant_config.use_fp8_w8a8
|
||||
):
|
||||
# AITER tkw1 kernel for FP8 models with `apply_router_weight_on_input`
|
||||
# This applies topk_weights on the GEMM output of the first FC layer
|
||||
# rather than the second FC.
|
||||
assert (topk_weights.dim() == 2
|
||||
), "`topk_weights` should be in shape (num_tokens, topk)"
|
||||
assert topk_weights.dim() == 2, (
|
||||
"`topk_weights` should be in shape (num_tokens, topk)"
|
||||
)
|
||||
assert topk_weights.shape[-1] == 1, (
|
||||
"Only support topk=1 when"
|
||||
" `apply_router_weight_on_input` is True")
|
||||
"Only support topk=1 when `apply_router_weight_on_input` is True"
|
||||
)
|
||||
|
||||
return torch.ops.vllm.rocm_aiter_asm_moe_tkw1(
|
||||
hidden_states,
|
||||
@@ -349,7 +389,8 @@ def rocm_aiter_fused_experts(
|
||||
a16=False,
|
||||
per_tensor_quant_scale=None,
|
||||
expert_mask=expert_mask,
|
||||
activation_method=activation_method)
|
||||
activation_method=activation_method,
|
||||
)
|
||||
|
||||
else:
|
||||
quant_method = QuantMethod.NO.value
|
||||
@@ -358,7 +399,8 @@ def rocm_aiter_fused_experts(
|
||||
if quant_config.block_shape is not None and quant_config.use_fp8_w8a8:
|
||||
assert not apply_router_weight_on_input, (
|
||||
"apply_router_weight_on_input is\
|
||||
not supported for block scaled moe")
|
||||
not supported for block scaled moe"
|
||||
)
|
||||
assert quant_config.w1_scale is not None
|
||||
assert quant_config.w2_scale is not None
|
||||
quant_method = QuantMethod.BLOCK_128x128.value
|
||||
@@ -367,12 +409,13 @@ def rocm_aiter_fused_experts(
|
||||
quant_method = QuantMethod.PER_TENSOR.value
|
||||
|
||||
if apply_router_weight_on_input:
|
||||
assert (topk_weights.dim() == 2
|
||||
), "`topk_weights` should be in shape (num_tokens, topk)"
|
||||
assert topk_weights.dim() == 2, (
|
||||
"`topk_weights` should be in shape (num_tokens, topk)"
|
||||
)
|
||||
_, topk = topk_weights.shape
|
||||
assert (
|
||||
topk == 1
|
||||
), "Only support topk=1 when `apply_router_weight_on_input` is True"
|
||||
assert topk == 1, (
|
||||
"Only support topk=1 when `apply_router_weight_on_input` is True"
|
||||
)
|
||||
|
||||
return torch.ops.vllm.rocm_aiter_fused_moe(
|
||||
hidden_states,
|
||||
@@ -387,17 +430,20 @@ def rocm_aiter_fused_experts(
|
||||
w2_scale=quant_config.w2_scale,
|
||||
a1_scale=quant_config.a1_scale,
|
||||
a2_scale=quant_config.a2_scale,
|
||||
doweight_stage1=apply_router_weight_on_input)
|
||||
doweight_stage1=apply_router_weight_on_input,
|
||||
)
|
||||
|
||||
|
||||
def rocm_aiter_topk_softmax(topk_weights: torch.Tensor,
|
||||
topk_indices: torch.Tensor,
|
||||
token_expert_indices: torch.Tensor,
|
||||
gating_output: torch.Tensor,
|
||||
renormalize: bool) -> tuple[torch.Tensor, ...]:
|
||||
torch.ops.vllm.rocm_aiter_topk_softmax(topk_weights, topk_indices,
|
||||
token_expert_indices, gating_output,
|
||||
renormalize)
|
||||
def rocm_aiter_topk_softmax(
|
||||
topk_weights: torch.Tensor,
|
||||
topk_indices: torch.Tensor,
|
||||
token_expert_indices: torch.Tensor,
|
||||
gating_output: torch.Tensor,
|
||||
renormalize: bool,
|
||||
) -> tuple[torch.Tensor, ...]:
|
||||
torch.ops.vllm.rocm_aiter_topk_softmax(
|
||||
topk_weights, topk_indices, token_expert_indices, gating_output, renormalize
|
||||
)
|
||||
return topk_weights, topk_indices
|
||||
|
||||
|
||||
@@ -413,7 +459,7 @@ def shuffle_weights(
|
||||
|
||||
Args:
|
||||
*tensors: Variable number of torch.Tensor objects.
|
||||
layout: A pair of integers specifying the block sizes used to divide
|
||||
layout: A pair of integers specifying the block sizes used to divide
|
||||
the tensors during shuffling. Default is (16, 16).
|
||||
|
||||
Returns:
|
||||
|
||||
@@ -50,9 +50,7 @@ class DistributionBasedRouting(RoutingStrategy):
|
||||
distributions for testing different routing patterns.
|
||||
"""
|
||||
|
||||
def __init__(self,
|
||||
distribution: str = "uniform",
|
||||
**distribution_params: Any):
|
||||
def __init__(self, distribution: str = "uniform", **distribution_params: Any):
|
||||
"""
|
||||
Initialize distribution-based routing.
|
||||
|
||||
@@ -76,8 +74,10 @@ class DistributionBasedRouting(RoutingStrategy):
|
||||
valid_distributions = ["uniform", "normal"]
|
||||
|
||||
if self.distribution not in valid_distributions:
|
||||
raise ValueError(f"Unsupported distribution: {self.distribution}. "
|
||||
f"Supported distributions: {valid_distributions}")
|
||||
raise ValueError(
|
||||
f"Unsupported distribution: {self.distribution}. "
|
||||
f"Supported distributions: {valid_distributions}"
|
||||
)
|
||||
|
||||
# Set default parameters if not provided
|
||||
if self.distribution == "normal":
|
||||
@@ -112,12 +112,12 @@ class DistributionBasedRouting(RoutingStrategy):
|
||||
indices_type = torch.long
|
||||
|
||||
# Generate expert IDs based on the specified distribution
|
||||
topk_ids = self._sample_expert_ids(num_tokens, num_experts, top_k,
|
||||
hidden_states.device, indices_type)
|
||||
topk_ids = self._sample_expert_ids(
|
||||
num_tokens, num_experts, top_k, hidden_states.device, indices_type
|
||||
)
|
||||
|
||||
# Generate weights based on the distribution
|
||||
topk_weights = self._generate_weights(num_tokens, top_k,
|
||||
hidden_states.device)
|
||||
topk_weights = self._generate_weights(num_tokens, top_k, hidden_states.device)
|
||||
|
||||
return topk_weights, topk_ids
|
||||
|
||||
@@ -145,7 +145,8 @@ class DistributionBasedRouting(RoutingStrategy):
|
||||
# For normal distribution, sample continuous values and map to
|
||||
# expert IDs
|
||||
continuous_samples = self._sample_continuous_distribution(
|
||||
num_tokens, top_k, device)
|
||||
num_tokens, top_k, device
|
||||
)
|
||||
|
||||
# Map continuous samples to expert indices
|
||||
# Normalize to [0, 1] range and scale to [0, num_experts)
|
||||
@@ -158,8 +159,9 @@ class DistributionBasedRouting(RoutingStrategy):
|
||||
else:
|
||||
raise ValueError(f"Unsupported distribution: {self.distribution}")
|
||||
|
||||
def _sample_continuous_distribution(self, num_tokens: int, top_k: int,
|
||||
device: torch.device) -> torch.Tensor:
|
||||
def _sample_continuous_distribution(
|
||||
self, num_tokens: int, top_k: int, device: torch.device
|
||||
) -> torch.Tensor:
|
||||
"""Sample from continuous distributions."""
|
||||
shape = (num_tokens, top_k)
|
||||
|
||||
@@ -170,7 +172,8 @@ class DistributionBasedRouting(RoutingStrategy):
|
||||
|
||||
else:
|
||||
raise ValueError(
|
||||
f"Unsupported continuous distribution: {self.distribution}")
|
||||
f"Unsupported continuous distribution: {self.distribution}"
|
||||
)
|
||||
|
||||
def _normalize_samples(self, samples: torch.Tensor) -> torch.Tensor:
|
||||
"""Normalize samples to [0, 1] range."""
|
||||
@@ -179,11 +182,13 @@ class DistributionBasedRouting(RoutingStrategy):
|
||||
return torch.sigmoid(samples)
|
||||
|
||||
else:
|
||||
raise ValueError(f"Unsupported distribution for normalization: "
|
||||
f"{self.distribution}")
|
||||
raise ValueError(
|
||||
f"Unsupported distribution for normalization: {self.distribution}"
|
||||
)
|
||||
|
||||
def _generate_weights(self, num_tokens: int, top_k: int,
|
||||
device: torch.device) -> torch.Tensor:
|
||||
def _generate_weights(
|
||||
self, num_tokens: int, top_k: int, device: torch.device
|
||||
) -> torch.Tensor:
|
||||
"""Generate weights based on the distribution."""
|
||||
if self.distribution == "uniform":
|
||||
# All-ones weights for uniform distribution
|
||||
@@ -197,7 +202,8 @@ class DistributionBasedRouting(RoutingStrategy):
|
||||
# For normal distribution, generate weights from the same
|
||||
# distribution
|
||||
continuous_weights = self._sample_continuous_distribution(
|
||||
num_tokens, top_k, device)
|
||||
num_tokens, top_k, device
|
||||
)
|
||||
# Normalize to positive values and sum to 1
|
||||
weights = torch.abs(continuous_weights)
|
||||
weights = weights / weights.sum(dim=-1, keepdim=True)
|
||||
@@ -205,14 +211,14 @@ class DistributionBasedRouting(RoutingStrategy):
|
||||
|
||||
else:
|
||||
raise ValueError(
|
||||
f"Unsupported distribution for weight generation: "
|
||||
f"{self.distribution}")
|
||||
f"Unsupported distribution for weight generation: {self.distribution}"
|
||||
)
|
||||
|
||||
def get_distribution_info(self) -> dict:
|
||||
"""Get information about the current distribution configuration."""
|
||||
return {
|
||||
"distribution": self.distribution,
|
||||
"parameters": self.distribution_params.copy()
|
||||
"parameters": self.distribution_params.copy(),
|
||||
}
|
||||
|
||||
|
||||
@@ -228,10 +234,12 @@ class RoutingSimulator:
|
||||
# Class-level registry of routing strategies
|
||||
_routing_strategies: dict[str, RoutingStrategy] = {
|
||||
# Basic routing strategies
|
||||
"uniform_random":
|
||||
DistributionBasedRouting(distribution="uniform", mean=0.0, std=1.0),
|
||||
"normal_routing":
|
||||
DistributionBasedRouting(distribution="normal", mean=0.0, std=1.0),
|
||||
"uniform_random": DistributionBasedRouting(
|
||||
distribution="uniform", mean=0.0, std=1.0
|
||||
),
|
||||
"normal_routing": DistributionBasedRouting(
|
||||
distribution="normal", mean=0.0, std=1.0
|
||||
),
|
||||
}
|
||||
|
||||
@classmethod
|
||||
@@ -280,7 +288,8 @@ class RoutingSimulator:
|
||||
raise ValueError(
|
||||
f"Unknown routing strategy: {strategy_name}. "
|
||||
f"Available strategies: "
|
||||
f"{list(RoutingSimulator._routing_strategies.keys())}")
|
||||
f"{list(RoutingSimulator._routing_strategies.keys())}"
|
||||
)
|
||||
|
||||
strategy = RoutingSimulator._routing_strategies[strategy_name]
|
||||
return strategy.route_tokens(
|
||||
|
||||
@@ -19,7 +19,7 @@ class TopKWeightAndReduceDelegate(mk.TopKWeightAndReduce):
|
||||
PplxPrepareAndFinalize and BatchedPrepareAndFinalize. PplxPrepareAndFinalize
|
||||
does the weight-application + reduction as part of the pplx combine kernel.
|
||||
But the BatchedPrepareAndFinalize needs an implementation. To facilitate
|
||||
this case, the BatchedTritonExperts could use TopKWeightAndReduceDelegate
|
||||
this case, the BatchedTritonExperts could use TopKWeightAndReduceDelegate
|
||||
so the PrepareAndFinalize implementations could choose how to
|
||||
weight + reduce.
|
||||
"""
|
||||
@@ -27,12 +27,18 @@ class TopKWeightAndReduceDelegate(mk.TopKWeightAndReduce):
|
||||
def __eq__(self, other):
|
||||
return isinstance(other, TopKWeightAndReduceDelegate)
|
||||
|
||||
def apply(self, output: Optional[torch.Tensor],
|
||||
fused_expert_output: torch.Tensor, topk_weights: torch.Tensor,
|
||||
topk_ids: torch.Tensor,
|
||||
apply_router_weight_on_input: bool) -> torch.Tensor:
|
||||
raise RuntimeError("The caller is expected to choose an appropriate "
|
||||
"TopKWeightAndReduce implementation.")
|
||||
def apply(
|
||||
self,
|
||||
output: Optional[torch.Tensor],
|
||||
fused_expert_output: torch.Tensor,
|
||||
topk_weights: torch.Tensor,
|
||||
topk_ids: torch.Tensor,
|
||||
apply_router_weight_on_input: bool,
|
||||
) -> torch.Tensor:
|
||||
raise RuntimeError(
|
||||
"The caller is expected to choose an appropriate "
|
||||
"TopKWeightAndReduce implementation."
|
||||
)
|
||||
|
||||
|
||||
class TopKWeightAndReduceNoOP(mk.TopKWeightAndReduce):
|
||||
@@ -44,10 +50,14 @@ class TopKWeightAndReduceNoOP(mk.TopKWeightAndReduce):
|
||||
def __eq__(self, other):
|
||||
return isinstance(other, TopKWeightAndReduceNoOP)
|
||||
|
||||
def apply(self, output: Optional[torch.Tensor],
|
||||
fused_expert_output: torch.Tensor, topk_weights: torch.Tensor,
|
||||
topk_ids: torch.Tensor,
|
||||
apply_router_weight_on_input: bool) -> torch.Tensor:
|
||||
def apply(
|
||||
self,
|
||||
output: Optional[torch.Tensor],
|
||||
fused_expert_output: torch.Tensor,
|
||||
topk_weights: torch.Tensor,
|
||||
topk_ids: torch.Tensor,
|
||||
apply_router_weight_on_input: bool,
|
||||
) -> torch.Tensor:
|
||||
# Weight application and reduction operations are already done.
|
||||
if output is None:
|
||||
return fused_expert_output
|
||||
@@ -57,7 +67,8 @@ class TopKWeightAndReduceNoOP(mk.TopKWeightAndReduce):
|
||||
assert output.size() == fused_expert_output.size(), (
|
||||
"output shape is expected to match the fused_expert_output shape. "
|
||||
f"But got output={output.size()}, "
|
||||
f"used_expert_output={fused_expert_output.size()}")
|
||||
f"used_expert_output={fused_expert_output.size()}"
|
||||
)
|
||||
output.copy_(fused_expert_output, non_blocking=True)
|
||||
return output
|
||||
|
||||
@@ -71,11 +82,14 @@ class TopKWeightAndReduceContiguous(mk.TopKWeightAndReduce):
|
||||
def __eq__(self, other):
|
||||
return isinstance(other, TopKWeightAndReduceContiguous)
|
||||
|
||||
def apply(self, output: Optional[torch.Tensor],
|
||||
fused_expert_output: torch.Tensor, topk_weights: torch.Tensor,
|
||||
topk_ids: torch.Tensor,
|
||||
apply_router_weight_on_input: bool) -> torch.Tensor:
|
||||
|
||||
def apply(
|
||||
self,
|
||||
output: Optional[torch.Tensor],
|
||||
fused_expert_output: torch.Tensor,
|
||||
topk_weights: torch.Tensor,
|
||||
topk_ids: torch.Tensor,
|
||||
apply_router_weight_on_input: bool,
|
||||
) -> torch.Tensor:
|
||||
m, num_topk = topk_ids.size()
|
||||
k = fused_expert_output.size(-1)
|
||||
if fused_expert_output.ndim == 2:
|
||||
@@ -83,17 +97,21 @@ class TopKWeightAndReduceContiguous(mk.TopKWeightAndReduce):
|
||||
|
||||
assert fused_expert_output.size() == (m, num_topk, k), (
|
||||
f"Expected fused_expert_output size {(m, num_topk, k)}. But got "
|
||||
f"{fused_expert_output.size()}")
|
||||
f"{fused_expert_output.size()}"
|
||||
)
|
||||
|
||||
if not apply_router_weight_on_input:
|
||||
fused_expert_output.mul_(topk_weights.view(m, -1, 1))
|
||||
|
||||
if output is None:
|
||||
output = torch.empty((m, k),
|
||||
device=fused_expert_output.device,
|
||||
dtype=fused_expert_output.dtype)
|
||||
output = torch.empty(
|
||||
(m, k),
|
||||
device=fused_expert_output.device,
|
||||
dtype=fused_expert_output.dtype,
|
||||
)
|
||||
assert output.size() == (m, k), (
|
||||
f"Expected output size {(m, k)}. But got {output.size()}")
|
||||
f"Expected output size {(m, k)}. But got {output.size()}"
|
||||
)
|
||||
|
||||
ops.moe_sum(fused_expert_output, output)
|
||||
return output
|
||||
@@ -109,27 +127,35 @@ class TopKWeightAndReduceNaiveBatched(mk.TopKWeightAndReduce):
|
||||
self.rank = rank
|
||||
|
||||
def __eq__(self, other):
|
||||
return (isinstance(other, TopKWeightAndReduceNaiveBatched)
|
||||
and (other.rank == self.rank))
|
||||
return isinstance(other, TopKWeightAndReduceNaiveBatched) and (
|
||||
other.rank == self.rank
|
||||
)
|
||||
|
||||
def apply(self, output: Optional[torch.Tensor],
|
||||
fused_expert_output: torch.Tensor, topk_weights: torch.Tensor,
|
||||
topk_ids: torch.Tensor,
|
||||
apply_router_weight_on_input: bool) -> torch.Tensor:
|
||||
def apply(
|
||||
self,
|
||||
output: Optional[torch.Tensor],
|
||||
fused_expert_output: torch.Tensor,
|
||||
topk_weights: torch.Tensor,
|
||||
topk_ids: torch.Tensor,
|
||||
apply_router_weight_on_input: bool,
|
||||
) -> torch.Tensor:
|
||||
assert fused_expert_output.ndim == 3
|
||||
num_tokens = topk_ids.size(0)
|
||||
num_local_experts = fused_expert_output.size(0)
|
||||
K = fused_expert_output.size(-1)
|
||||
|
||||
if output is None:
|
||||
output = torch.zeros((num_tokens, K),
|
||||
device=fused_expert_output.device,
|
||||
dtype=fused_expert_output.dtype)
|
||||
output = torch.zeros(
|
||||
(num_tokens, K),
|
||||
device=fused_expert_output.device,
|
||||
dtype=fused_expert_output.dtype,
|
||||
)
|
||||
else:
|
||||
output.fill_(0)
|
||||
|
||||
assert output.size() == (num_tokens, K), (
|
||||
f"Expected output size {(num_tokens, K)}, but got {output.size()}")
|
||||
f"Expected output size {(num_tokens, K)}, but got {output.size()}"
|
||||
)
|
||||
|
||||
first_expert = num_local_experts * self.rank
|
||||
last_expert = first_expert + num_local_experts
|
||||
|
||||
@@ -7,15 +7,16 @@ import torch
|
||||
import vllm.model_executor.layers.fused_moe.modular_kernel as mk
|
||||
from vllm.model_executor.layers.fused_moe.config import FusedMoEQuantConfig
|
||||
from vllm.model_executor.layers.fused_moe.deep_gemm_moe import (
|
||||
DeepGemmExperts, _valid_deep_gemm, _valid_deep_gemm_shape)
|
||||
from vllm.model_executor.layers.fused_moe.deep_gemm_utils import (
|
||||
deep_gemm_block_shape)
|
||||
DeepGemmExperts,
|
||||
_valid_deep_gemm,
|
||||
_valid_deep_gemm_shape,
|
||||
)
|
||||
from vllm.model_executor.layers.fused_moe.deep_gemm_utils import deep_gemm_block_shape
|
||||
from vllm.model_executor.layers.fused_moe.fused_moe import TritonExperts
|
||||
from vllm.utils.deep_gemm import is_deep_gemm_e8m0_used
|
||||
|
||||
|
||||
class TritonOrDeepGemmExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
quant_config: FusedMoEQuantConfig,
|
||||
@@ -25,33 +26,40 @@ class TritonOrDeepGemmExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
|
||||
self.triton_expert = TritonExperts(quant_config)
|
||||
|
||||
self.allow_deep_gemm = (allow_deep_gemm
|
||||
and self.quant_config.use_fp8_w8a8 and
|
||||
self.block_shape == deep_gemm_block_shape())
|
||||
self.allow_deep_gemm = (
|
||||
allow_deep_gemm
|
||||
and self.quant_config.use_fp8_w8a8
|
||||
and self.block_shape == deep_gemm_block_shape()
|
||||
)
|
||||
|
||||
self.deep_gemm_expert = DeepGemmExperts(
|
||||
self.quant_config) if self.allow_deep_gemm else None
|
||||
self.deep_gemm_expert = (
|
||||
DeepGemmExperts(self.quant_config) if self.allow_deep_gemm else None
|
||||
)
|
||||
|
||||
@property
|
||||
def activation_formats(
|
||||
self
|
||||
self,
|
||||
) -> tuple[mk.FusedMoEActivationFormat, mk.FusedMoEActivationFormat]:
|
||||
assert (self.deep_gemm_expert is None
|
||||
or self.triton_expert.activation_formats
|
||||
== self.deep_gemm_expert.activation_formats)
|
||||
assert (
|
||||
self.deep_gemm_expert is None
|
||||
or self.triton_expert.activation_formats
|
||||
== self.deep_gemm_expert.activation_formats
|
||||
)
|
||||
return self.triton_expert.activation_formats
|
||||
|
||||
def supports_chunking(self) -> bool:
|
||||
dge = self.deep_gemm_expert
|
||||
te = self.triton_expert
|
||||
return ((dge is None or dge.supports_chunking())
|
||||
and (te is None or te.supports_chunking()))
|
||||
return (dge is None or dge.supports_chunking()) and (
|
||||
te is None or te.supports_chunking()
|
||||
)
|
||||
|
||||
def supports_expert_map(self) -> bool:
|
||||
dge = self.deep_gemm_expert
|
||||
te = self.triton_expert
|
||||
return ((dge is None or dge.supports_expert_map())
|
||||
and (te is None or te.supports_expert_map()))
|
||||
return (dge is None or dge.supports_expert_map()) and (
|
||||
te is None or te.supports_expert_map()
|
||||
)
|
||||
|
||||
def finalize_weight_and_reduce_impl(self) -> mk.TopKWeightAndReduce:
|
||||
dge = self.deep_gemm_expert
|
||||
@@ -64,7 +72,8 @@ class TritonOrDeepGemmExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
if is_dge_war and is_te_war:
|
||||
assert dge_war == te_war, (
|
||||
"Both implementations should agree on WeightAndReduce impls. "
|
||||
f"Got dge_war: {dge_war}, and te_war: {te_war}")
|
||||
f"Got dge_war: {dge_war}, and te_war: {te_war}"
|
||||
)
|
||||
|
||||
if dge_war is not None:
|
||||
return dge_war
|
||||
@@ -87,17 +96,33 @@ class TritonOrDeepGemmExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
# Note: the deep gemm workspaces are strictly larger than the triton
|
||||
# workspaces so we can be pessimistic here and allocate for DeepGemm
|
||||
# even if we fall back to triton later, e.g. if expert maps are set.
|
||||
if self.allow_deep_gemm and (is_deep_gemm_e8m0_used()
|
||||
or _valid_deep_gemm_shape(M, N, K)):
|
||||
if self.allow_deep_gemm and (
|
||||
is_deep_gemm_e8m0_used() or _valid_deep_gemm_shape(M, N, K)
|
||||
):
|
||||
assert self.deep_gemm_expert is not None
|
||||
return self.deep_gemm_expert.workspace_shapes(
|
||||
a, aq, M, N, K, topk, global_num_experts, local_num_experts,
|
||||
expert_tokens_meta)
|
||||
a,
|
||||
aq,
|
||||
M,
|
||||
N,
|
||||
K,
|
||||
topk,
|
||||
global_num_experts,
|
||||
local_num_experts,
|
||||
expert_tokens_meta,
|
||||
)
|
||||
else:
|
||||
return self.triton_expert.workspace_shapes(a, aq, M, N, K, topk,
|
||||
global_num_experts,
|
||||
local_num_experts,
|
||||
expert_tokens_meta)
|
||||
return self.triton_expert.workspace_shapes(
|
||||
a,
|
||||
aq,
|
||||
M,
|
||||
N,
|
||||
K,
|
||||
topk,
|
||||
global_num_experts,
|
||||
local_num_experts,
|
||||
expert_tokens_meta,
|
||||
)
|
||||
|
||||
def apply(
|
||||
self,
|
||||
@@ -117,9 +142,9 @@ class TritonOrDeepGemmExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
expert_tokens_meta: Optional[mk.ExpertTokensMetadata],
|
||||
apply_router_weight_on_input: bool,
|
||||
):
|
||||
use_deep_gemm = (self.allow_deep_gemm
|
||||
and (_valid_deep_gemm(hidden_states, w1, w2)
|
||||
or is_deep_gemm_e8m0_used()))
|
||||
use_deep_gemm = self.allow_deep_gemm and (
|
||||
_valid_deep_gemm(hidden_states, w1, w2) or is_deep_gemm_e8m0_used()
|
||||
)
|
||||
|
||||
experts = self.deep_gemm_expert if use_deep_gemm else self.triton_expert
|
||||
assert experts is not None
|
||||
|
||||
@@ -5,15 +5,17 @@ from typing import Optional
|
||||
import torch
|
||||
|
||||
import vllm.model_executor.layers.fused_moe.modular_kernel as mk
|
||||
from vllm.model_executor.layers.fused_moe.config import (FusedMoEConfig,
|
||||
FusedMoEQuantConfig)
|
||||
from vllm.model_executor.layers.fused_moe.config import (
|
||||
FusedMoEConfig,
|
||||
FusedMoEQuantConfig,
|
||||
)
|
||||
from vllm.model_executor.layers.fused_moe.topk_weight_and_reduce import (
|
||||
TopKWeightAndReduceNoOP)
|
||||
TopKWeightAndReduceNoOP,
|
||||
)
|
||||
from vllm.utils import next_power_of_2
|
||||
|
||||
|
||||
class TrtLlmGenExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
moe: FusedMoEConfig,
|
||||
@@ -32,10 +34,12 @@ class TrtLlmGenExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
|
||||
@property
|
||||
def activation_formats(
|
||||
self
|
||||
self,
|
||||
) -> tuple[mk.FusedMoEActivationFormat, mk.FusedMoEActivationFormat]:
|
||||
return (mk.FusedMoEActivationFormat.Standard,
|
||||
mk.FusedMoEActivationFormat.Standard)
|
||||
return (
|
||||
mk.FusedMoEActivationFormat.Standard,
|
||||
mk.FusedMoEActivationFormat.Standard,
|
||||
)
|
||||
|
||||
def supports_chunking(self) -> bool:
|
||||
return True
|
||||
@@ -66,8 +70,7 @@ class TrtLlmGenExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
output = (M, K)
|
||||
return (workspace1, workspace2, output, a.dtype)
|
||||
|
||||
def _get_tile_tokens_dim(self, x: torch.Tensor, top_k: int,
|
||||
local_num_experts: int):
|
||||
def _get_tile_tokens_dim(self, x: torch.Tensor, top_k: int, local_num_experts: int):
|
||||
# Number of tokens in the input tensor.
|
||||
num_tokens = x.shape[0]
|
||||
# Factor to account for the imbalance of the experts.
|
||||
@@ -117,75 +120,49 @@ class TrtLlmGenExperts(mk.FusedMoEPermuteExpertsUnpermute):
|
||||
x_quant = hidden_states
|
||||
x_scale = a1q_scale
|
||||
if x_scale is not None:
|
||||
x_scale = x_scale.view(torch.float8_e4m3fn).reshape(
|
||||
*x_quant.shape[:-1], -1)
|
||||
x_scale = x_scale.view(torch.float8_e4m3fn).reshape(*x_quant.shape[:-1], -1)
|
||||
|
||||
packed_tensor = (topk_ids.to(torch.int32) << 16) | topk_weights.to(
|
||||
torch.bfloat16).view(torch.int16)
|
||||
torch.bfloat16
|
||||
).view(torch.int16)
|
||||
|
||||
assert self.w1_scale is not None
|
||||
assert self.w2_scale is not None
|
||||
kwargs = {
|
||||
"topk_ids":
|
||||
packed_tensor,
|
||||
"routing_bias":
|
||||
None,
|
||||
"hidden_states":
|
||||
x_quant,
|
||||
"hidden_states_scale":
|
||||
x_scale,
|
||||
"gemm1_weights":
|
||||
w1,
|
||||
"gemm1_weights_scale":
|
||||
self.w1_scale,
|
||||
"gemm1_bias":
|
||||
self.w1_bias,
|
||||
"gemm1_alpha":
|
||||
self.gemm1_alpha,
|
||||
"gemm1_beta":
|
||||
self.gemm1_beta,
|
||||
"gemm1_clamp_limit":
|
||||
self.gemm1_clamp_limit,
|
||||
"gemm2_weights":
|
||||
w2,
|
||||
"gemm2_weights_scale":
|
||||
self.w2_scale,
|
||||
"gemm2_bias":
|
||||
self.w2_bias,
|
||||
"output1_scale_scalar":
|
||||
None,
|
||||
"output1_scale_gate_scalar":
|
||||
None,
|
||||
"output2_scale_scalar":
|
||||
None,
|
||||
"num_experts":
|
||||
global_num_experts,
|
||||
"top_k":
|
||||
topk,
|
||||
"n_group":
|
||||
None,
|
||||
"topk_group":
|
||||
None,
|
||||
"intermediate_size":
|
||||
intermediate_size,
|
||||
"local_expert_offset":
|
||||
local_expert_offset,
|
||||
"local_num_experts":
|
||||
local_num_experts,
|
||||
"routed_scaling_factor":
|
||||
None,
|
||||
"tile_tokens_dim":
|
||||
self._get_tile_tokens_dim(x_quant, topk, local_num_experts),
|
||||
"routing_method_type":
|
||||
1,
|
||||
"do_finalize":
|
||||
True,
|
||||
"output":
|
||||
output,
|
||||
"tune_max_num_tokens":
|
||||
self.max_capture_size,
|
||||
"topk_ids": packed_tensor,
|
||||
"routing_bias": None,
|
||||
"hidden_states": x_quant,
|
||||
"hidden_states_scale": x_scale,
|
||||
"gemm1_weights": w1,
|
||||
"gemm1_weights_scale": self.w1_scale,
|
||||
"gemm1_bias": self.w1_bias,
|
||||
"gemm1_alpha": self.gemm1_alpha,
|
||||
"gemm1_beta": self.gemm1_beta,
|
||||
"gemm1_clamp_limit": self.gemm1_clamp_limit,
|
||||
"gemm2_weights": w2,
|
||||
"gemm2_weights_scale": self.w2_scale,
|
||||
"gemm2_bias": self.w2_bias,
|
||||
"output1_scale_scalar": None,
|
||||
"output1_scale_gate_scalar": None,
|
||||
"output2_scale_scalar": None,
|
||||
"num_experts": global_num_experts,
|
||||
"top_k": topk,
|
||||
"n_group": None,
|
||||
"topk_group": None,
|
||||
"intermediate_size": intermediate_size,
|
||||
"local_expert_offset": local_expert_offset,
|
||||
"local_num_experts": local_num_experts,
|
||||
"routed_scaling_factor": None,
|
||||
"tile_tokens_dim": self._get_tile_tokens_dim(
|
||||
x_quant, topk, local_num_experts
|
||||
),
|
||||
"routing_method_type": 1,
|
||||
"do_finalize": True,
|
||||
"output": output,
|
||||
"tune_max_num_tokens": self.max_capture_size,
|
||||
}
|
||||
|
||||
from flashinfer import trtllm_fp4_block_scale_routed_moe
|
||||
|
||||
trtllm_fp4_block_scale_routed_moe(**kwargs)
|
||||
return output
|
||||
|
||||
@@ -7,13 +7,16 @@ import torch
|
||||
|
||||
from vllm import _custom_ops as ops
|
||||
from vllm.model_executor.layers.quantization.utils.fp8_utils import (
|
||||
per_token_group_quant_fp8)
|
||||
per_token_group_quant_fp8,
|
||||
)
|
||||
from vllm.model_executor.layers.quantization.utils.int8_utils import (
|
||||
per_token_group_quant_int8, per_token_quant_int8)
|
||||
per_token_group_quant_int8,
|
||||
per_token_quant_int8,
|
||||
)
|
||||
from vllm.model_executor.layers.quantization.utils.mxfp4_utils import (
|
||||
quant_dequant_mxfp4)
|
||||
from vllm.model_executor.layers.quantization.utils.mxfp8_utils import (
|
||||
mxfp8_quantize)
|
||||
quant_dequant_mxfp4,
|
||||
)
|
||||
from vllm.model_executor.layers.quantization.utils.mxfp8_utils import mxfp8_quantize
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import tl, triton
|
||||
from vllm.utils import cdiv
|
||||
@@ -21,26 +24,28 @@ from vllm.utils.flashinfer import fp4_quantize
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _count_expert_num_tokens(topk_ids_ptr, expert_num_tokens_ptr, num_experts,
|
||||
topk_numel, expert_map,
|
||||
HAS_EXPERT_MAP: tl.constexpr,
|
||||
BLOCK_SIZE: tl.constexpr):
|
||||
|
||||
def _count_expert_num_tokens(
|
||||
topk_ids_ptr,
|
||||
expert_num_tokens_ptr,
|
||||
num_experts,
|
||||
topk_numel,
|
||||
expert_map,
|
||||
HAS_EXPERT_MAP: tl.constexpr,
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
):
|
||||
curr_expert = tl.program_id(0)
|
||||
|
||||
offsets = tl.arange(0, BLOCK_SIZE)
|
||||
topk_ids_ptrs = topk_ids_ptr + offsets
|
||||
|
||||
acc = tl.zeros((BLOCK_SIZE, ), dtype=tl.int32)
|
||||
acc = tl.zeros((BLOCK_SIZE,), dtype=tl.int32)
|
||||
for x in range(tl.cdiv(topk_numel, BLOCK_SIZE)):
|
||||
mask = offsets < (topk_numel - x * BLOCK_SIZE)
|
||||
expert_ids = tl.load(topk_ids_ptrs, mask=mask, other=-1)
|
||||
if HAS_EXPERT_MAP:
|
||||
expert_map_ptrs = expert_map + expert_ids
|
||||
expert_map_mask = expert_ids >= 0
|
||||
expert_ids = tl.load(expert_map_ptrs,
|
||||
mask=expert_map_mask,
|
||||
other=-1)
|
||||
expert_ids = tl.load(expert_map_ptrs, mask=expert_map_mask, other=-1)
|
||||
|
||||
has_curr_expert = tl.where(expert_ids == curr_expert, 1, 0)
|
||||
acc = acc + has_curr_expert
|
||||
@@ -51,8 +56,8 @@ def _count_expert_num_tokens(topk_ids_ptr, expert_num_tokens_ptr, num_experts,
|
||||
|
||||
|
||||
def count_expert_num_tokens(
|
||||
topk_ids: torch.Tensor, num_local_experts: int,
|
||||
expert_map: Optional[torch.Tensor]) -> torch.Tensor:
|
||||
topk_ids: torch.Tensor, num_local_experts: int, expert_map: Optional[torch.Tensor]
|
||||
) -> torch.Tensor:
|
||||
"""
|
||||
Count the number to tokens assigned to each expert.
|
||||
|
||||
@@ -68,17 +73,16 @@ def count_expert_num_tokens(
|
||||
A tensor of size num_local_experts, where tensor[i] holds the number
|
||||
of tokens assigned to the ith expert.
|
||||
"""
|
||||
assert topk_ids.dtype.is_signed, (
|
||||
"The kernel uses -1 to represent invalid topk_ids")
|
||||
expert_num_tokens = torch.empty((num_local_experts),
|
||||
device=topk_ids.device,
|
||||
dtype=torch.int32)
|
||||
assert topk_ids.dtype.is_signed, "The kernel uses -1 to represent invalid topk_ids"
|
||||
expert_num_tokens = torch.empty(
|
||||
(num_local_experts), device=topk_ids.device, dtype=torch.int32
|
||||
)
|
||||
|
||||
grid = num_local_experts
|
||||
BLOCK_SIZE = min(topk_ids.numel(), 1024)
|
||||
BLOCK_SIZE = triton.next_power_of_2(BLOCK_SIZE)
|
||||
|
||||
_count_expert_num_tokens[(grid, )](
|
||||
_count_expert_num_tokens[(grid,)](
|
||||
topk_ids,
|
||||
expert_num_tokens,
|
||||
num_local_experts,
|
||||
@@ -96,9 +100,10 @@ def _resize_cache(x: torch.Tensor, v: tuple[int, ...]) -> torch.Tensor:
|
||||
Shrink the given tensor and apply the given view to it. This is
|
||||
used to resize the intermediate fused_moe caches.
|
||||
"""
|
||||
assert prod(v) <= x.numel(
|
||||
), f"{v} ({prod(v)}) <= {x.shape} ({x.numel()})" # CUDAGRAPH unfriendly?
|
||||
return x.flatten()[:prod(v)].view(*v)
|
||||
assert prod(v) <= x.numel(), (
|
||||
f"{v} ({prod(v)}) <= {x.shape} ({x.numel()})"
|
||||
) # CUDAGRAPH unfriendly?
|
||||
return x.flatten()[: prod(v)].view(*v)
|
||||
|
||||
|
||||
def _fp4_quantize(
|
||||
@@ -106,9 +111,7 @@ def _fp4_quantize(
|
||||
A_scale: Optional[torch.Tensor],
|
||||
is_sf_swizzled_layout: bool,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
return fp4_quantize(A,
|
||||
A_scale,
|
||||
is_sf_swizzled_layout=is_sf_swizzled_layout)
|
||||
return fp4_quantize(A, A_scale, is_sf_swizzled_layout=is_sf_swizzled_layout)
|
||||
|
||||
|
||||
def _fp8_quantize(
|
||||
@@ -125,7 +128,8 @@ def _fp8_quantize(
|
||||
# TODO(luka): use QuantFP8 custom op
|
||||
# https://github.com/vllm-project/vllm/issues/20711
|
||||
A, A_scale = ops.scaled_fp8_quant(
|
||||
A, A_scale, use_per_token_if_dynamic=per_act_token)
|
||||
A, A_scale, use_per_token_if_dynamic=per_act_token
|
||||
)
|
||||
else:
|
||||
assert not per_act_token
|
||||
assert len(block_shape) == 2
|
||||
@@ -151,8 +155,7 @@ def _int8_quantize(
|
||||
# activations apply per-token quantization. Otherwise, assume
|
||||
# activation tensor-wise fp8/int8 quantization, dynamic or static
|
||||
if block_shape is None:
|
||||
assert per_act_token, \
|
||||
"int8 quantization only supports block or channel-wise"
|
||||
assert per_act_token, "int8 quantization only supports block or channel-wise"
|
||||
A, A_scale = per_token_quant_int8(A)
|
||||
else:
|
||||
assert not per_act_token
|
||||
@@ -204,9 +207,7 @@ def moe_kernel_quantize_input(
|
||||
elif quant_dtype == torch.int8:
|
||||
return _int8_quantize(A, A_scale, per_act_token_quant, block_shape)
|
||||
elif quant_dtype == "nvfp4":
|
||||
return _fp4_quantize(A,
|
||||
A_scale,
|
||||
is_sf_swizzled_layout=is_fp4_scale_swizzled)
|
||||
return _fp4_quantize(A, A_scale, is_sf_swizzled_layout=is_fp4_scale_swizzled)
|
||||
elif quant_dtype == "mxfp4":
|
||||
return _mxfp4_quantize(A, A_scale, per_act_token_quant, block_shape)
|
||||
elif quant_dtype == "mxfp8":
|
||||
@@ -225,8 +226,7 @@ def _fp8_perm(m: torch.Tensor, idx: torch.Tensor) -> torch.Tensor:
|
||||
return m[idx, ...]
|
||||
|
||||
|
||||
def normalize_scales_shape(
|
||||
scales: Optional[torch.Tensor]) -> Optional[torch.Tensor]:
|
||||
def normalize_scales_shape(scales: Optional[torch.Tensor]) -> Optional[torch.Tensor]:
|
||||
if scales is not None:
|
||||
if scales.numel() == 1:
|
||||
scales = scales.view(1, 1)
|
||||
@@ -242,8 +242,9 @@ def normalize_batched_scales_shape(
|
||||
if scales is not None and scales.ndim < 3:
|
||||
if scales.numel() == 1:
|
||||
scales = scales.view(1)
|
||||
scales = torch.repeat_interleave(scales, num_experts,
|
||||
dim=0).view(num_experts, 1, 1)
|
||||
scales = torch.repeat_interleave(scales, num_experts, dim=0).view(
|
||||
num_experts, 1, 1
|
||||
)
|
||||
else:
|
||||
scales = scales.view(num_experts, -1, scales.size(-1))
|
||||
|
||||
@@ -263,7 +264,8 @@ def _validate_scale_shape(
|
||||
assert a_scale.numel() == 1, f"{a_scale.shape}"
|
||||
elif per_act_token_quant:
|
||||
assert a_scale.shape[0] == a.shape[0] and a_scale.shape[1] == 1, (
|
||||
f"{a_scale.shape[0]} == {a.shape[0]} and {a_scale.shape[1]} == 1")
|
||||
f"{a_scale.shape[0]} == {a.shape[0]} and {a_scale.shape[1]} == 1"
|
||||
)
|
||||
else:
|
||||
assert block_shape is not None
|
||||
expected = (a.shape[0], cdiv(a.shape[1], block_shape[1]))
|
||||
|
||||
Reference in New Issue
Block a user