[Model] Add DeepSeek-V4 CPU backend (#55355)

Signed-off-by: jiang1.li <jiang1.li@intel.com>
This commit is contained in:
Li, Jiang
2026-09-10 14:14:48 +08:00
committed by GitHub
parent 49632fb3ac
commit c3ccc0e957
47 changed files with 9564 additions and 627 deletions
+397 -37
View File
@@ -3357,31 +3357,6 @@ class CPUQuantMethod(IntEnum):
MXFP4 = 4
if hasattr(torch.ops._C, "fused_experts_cpu"):
@register_fake("_C::fused_experts_cpu")
def fused_experts_cpu_fake(
hidden_states: torch.Tensor,
w1: torch.Tensor,
w2: torch.Tensor,
topk_weights: torch.Tensor,
topk_ids: torch.Tensor,
inplace: bool,
moe_comp_method: CPUQuantMethod,
w1_scale: torch.Tensor | None,
w2_scale: torch.Tensor | None,
w1_zero: torch.Tensor | None,
w2_zero: torch.Tensor | None,
block_size: list[int] | None,
w1_bias: torch.Tensor | None,
w2_bias: torch.Tensor | None,
alpha: float | None,
limit: float | None,
is_vnni: bool,
) -> torch.Tensor:
return torch.empty_like(hidden_states)
if hasattr(torch.ops._C, "dynamic_4bit_int_moe"):
@register_fake("_C::dynamic_4bit_int_moe")
@@ -3401,12 +3376,12 @@ if hasattr(torch.ops._C, "dynamic_4bit_int_moe"):
def fused_experts_cpu(
out: torch.Tensor,
hidden_states: torch.Tensor,
w1: torch.Tensor,
w2: torch.Tensor,
topk_weights: torch.Tensor,
topk_ids: torch.Tensor,
inplace: bool,
moe_comp_method: CPUQuantMethod,
w1_scale: torch.Tensor | None,
w2_scale: torch.Tensor | None,
@@ -3418,14 +3393,14 @@ def fused_experts_cpu(
alpha: float | None = None,
limit: float | None = None,
is_vnni: bool = True,
) -> torch.Tensor:
return torch.ops._C.fused_experts_cpu(
) -> None:
torch.ops._C.fused_experts_cpu(
out,
hidden_states,
w1,
w2,
topk_weights,
topk_ids,
inplace,
moe_comp_method,
w1_scale,
w2_scale,
@@ -4059,6 +4034,393 @@ def amx_mla_concat_and_cache(
torch.ops._C.concat_and_cache_mla_cpu(kv_c_normed, k_pe, kv_cache, slot_mapping)
if hasattr(torch.ops._C, "hc_pre_fused_cpu"):
@register_fake("_C::hc_pre_fused_cpu")
def hc_pre_fused_cpu_fake(
x: torch.Tensor,
hc_fn: torch.Tensor,
hc_scale: torch.Tensor,
hc_base: torch.Tensor,
hc_mult: int,
sinkhorn_iters: int,
rms_eps: float,
hc_eps: float,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
t, _, d = x.shape
y = x.new_empty((t, d))
post = x.new_empty((t, hc_mult), dtype=torch.float32)
comb = x.new_empty((t, hc_mult, hc_mult), dtype=torch.float32)
return y, post, comb
def hc_pre_fused_cpu(
x: torch.Tensor,
hc_fn: torch.Tensor,
hc_scale: torch.Tensor,
hc_base: torch.Tensor,
hc_mult: int,
sinkhorn_iters: int,
rms_eps: float,
hc_eps: float,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
return torch.ops._C.hc_pre_fused_cpu(
x, hc_fn, hc_scale, hc_base, hc_mult, sinkhorn_iters, rms_eps, hc_eps
)
if hasattr(torch.ops._C, "hc_post_fused_cpu"):
@register_fake("_C::hc_post_fused_cpu")
def hc_post_fused_cpu_fake(
x: torch.Tensor,
residual: torch.Tensor,
post: torch.Tensor,
comb: torch.Tensor,
) -> torch.Tensor:
t, d = x.shape
hc = residual.size(1)
return x.new_empty((t, hc, d))
def hc_post_fused_cpu(
x: torch.Tensor,
residual: torch.Tensor,
post: torch.Tensor,
comb: torch.Tensor,
) -> torch.Tensor:
return torch.ops._C.hc_post_fused_cpu(x, residual, post, comb)
if hasattr(torch.ops._C, "hc_head_fused_cpu"):
@register_fake("_C::hc_head_fused_cpu")
def hc_head_fused_cpu_fake(
x: torch.Tensor,
hc_fn: torch.Tensor,
hc_scale: torch.Tensor,
hc_base: torch.Tensor,
hc_eps: float,
norm_eps: float,
) -> torch.Tensor:
t, _, d = x.shape
return x.new_empty((t, d))
def hc_head_fused_cpu(
x: torch.Tensor,
hc_fn: torch.Tensor,
hc_scale: torch.Tensor,
hc_base: torch.Tensor,
hc_eps: float,
norm_eps: float,
) -> torch.Tensor:
return torch.ops._C.hc_head_fused_cpu(x, hc_fn, hc_scale, hc_base, hc_eps, norm_eps)
if hasattr(torch.ops._C, "fused_qnorm_rope_kv_insert_cpu"):
@register_fake("_C::fused_qnorm_rope_kv_insert_cpu")
def fused_qnorm_rope_kv_insert_cpu_fake(
q: torch.Tensor,
kv: torch.Tensor,
positions: torch.Tensor,
swa_kv_cache_2d: torch.Tensor,
slot_mapping: torch.Tensor,
cos_sin_cache: torch.Tensor,
q_head_padded: int,
eps: float,
cache_block_size: int,
) -> torch.Tensor:
num_tokens_full, _, head_dim = q.shape
return q.new_empty((num_tokens_full, q_head_padded, head_dim))
def fused_qnorm_rope_kv_insert_cpu(
q: torch.Tensor,
kv: torch.Tensor,
positions: torch.Tensor,
swa_kv_cache_2d: torch.Tensor,
slot_mapping: torch.Tensor,
cos_sin_cache: torch.Tensor,
q_head_padded: int,
eps: float,
cache_block_size: int,
) -> torch.Tensor:
return torch.ops._C.fused_qnorm_rope_kv_insert_cpu(
q,
kv,
positions,
swa_kv_cache_2d,
slot_mapping,
cos_sin_cache,
q_head_padded,
eps,
cache_block_size,
)
def flash_mla_with_kvcache_cpu(
out: torch.Tensor,
q: torch.Tensor,
window_cache_2d: torch.Tensor,
window_slots: torch.Tensor,
window_block_size: int,
compressed_cache_2d: torch.Tensor,
compressed_slots: torch.Tensor,
compressed_block_size: int,
attn_sink: torch.Tensor,
scale: float,
) -> None:
torch.ops._C.flash_mla_with_kvcache_cpu(
out,
q,
window_cache_2d,
window_slots,
window_block_size,
compressed_cache_2d,
compressed_slots,
compressed_block_size,
attn_sink,
scale,
)
def save_partial_states_cpu(
kv: torch.Tensor,
score: torch.Tensor,
ape: torch.Tensor,
positions: torch.Tensor,
state_cache: torch.Tensor,
slot_mapping: torch.Tensor,
) -> None:
torch.ops._C.save_partial_states_cpu(
kv, score, ape, positions, state_cache, slot_mapping
)
def compress_norm_rope_store_cpu(
state_cache: torch.Tensor,
gather_slots: torch.Tensor,
positions: torch.Tensor,
kv_slot_mapping: torch.Tensor,
rms_norm_weight: torch.Tensor,
rms_norm_eps: float,
cos_sin_cache: torch.Tensor,
kv_cache_2d: torch.Tensor,
kv_cache_block_size: int,
compress_ratio: int,
) -> None:
torch.ops._C.compress_norm_rope_store_cpu(
state_cache,
gather_slots,
positions,
kv_slot_mapping,
rms_norm_weight,
rms_norm_eps,
cos_sin_cache,
kv_cache_2d,
kv_cache_block_size,
compress_ratio,
)
def compress_norm_rope_store_indexer_cpu(
state_cache: torch.Tensor,
gather_slots: torch.Tensor,
positions: torch.Tensor,
kv_slot_mapping: torch.Tensor,
rms_norm_weight: torch.Tensor,
rms_norm_eps: float,
cos_sin_cache: torch.Tensor,
kv_cache_2d: torch.Tensor,
kv_cache_block_size: int,
compress_ratio: int,
) -> None:
torch.ops._C.compress_norm_rope_store_indexer_cpu(
state_cache,
gather_slots,
positions,
kv_slot_mapping,
rms_norm_weight,
rms_norm_eps,
cos_sin_cache,
kv_cache_2d,
kv_cache_block_size,
compress_ratio,
)
if hasattr(torch.ops._C, "fp8_paged_mqa_logits_cpu"):
@register_fake("_C::fp8_paged_mqa_logits_cpu")
def fp8_paged_mqa_logits_cpu_fake(
q_fp8: torch.Tensor,
kvcache_fp8: torch.Tensor,
weight: torch.Tensor,
seq_lens: torch.Tensor,
page_table: torch.Tensor,
block_size: int,
max_seq_len: int,
) -> torch.Tensor:
batch_size = q_fp8.size(0)
return q_fp8.new_empty((batch_size, max_seq_len), dtype=torch.float32)
def fp8_paged_mqa_logits_cpu(
q_fp8: torch.Tensor,
kvcache_fp8: torch.Tensor,
weight: torch.Tensor,
seq_lens: torch.Tensor,
page_table: torch.Tensor,
block_size: int,
max_seq_len: int,
) -> torch.Tensor:
return torch.ops._C.fp8_paged_mqa_logits_cpu(
q_fp8, kvcache_fp8, weight, seq_lens, page_table, block_size, max_seq_len
)
def topk_transform_512_cpu(
scores: torch.Tensor,
seq_lens: torch.Tensor,
page_tables: torch.Tensor,
out_page_indices: torch.Tensor,
page_size: int,
out_raw_indices: torch.Tensor | None = None,
) -> None:
torch.ops._C.topk_transform_512_cpu(
scores, seq_lens, page_tables, out_page_indices, page_size, out_raw_indices
)
def fused_indexer_q_rope_quant_cpu(
positions: torch.Tensor,
index_q: torch.Tensor,
index_q_cos_sin_cache: torch.Tensor,
index_q_fp8: torch.Tensor,
index_weights: torch.Tensor,
index_weights_softmax_scale: float,
index_weights_head_scale: float,
index_weights_out: torch.Tensor,
) -> None:
torch.ops._C.fused_indexer_q_rope_quant_cpu(
positions,
index_q,
index_q_cos_sin_cache,
index_q_fp8,
index_weights,
index_weights_softmax_scale,
index_weights_head_scale,
index_weights_out,
)
if hasattr(torch.ops._C, "biased_topk_cpu"):
@register_fake("_C::biased_topk_cpu")
def biased_topk_cpu_fake(
hidden_states: torch.Tensor,
gating_output: torch.Tensor,
correction_bias: torch.Tensor,
topk: int,
renormalize: bool,
scoring_func: str,
num_fused_shared_experts: int,
routed_scaling_factor: float | None,
apply_routed_scaling_factor_on_output: bool,
) -> tuple[torch.Tensor, torch.Tensor]:
num_tokens = hidden_states.size(0)
topk_weights = hidden_states.new_empty((num_tokens, topk), dtype=torch.float32)
topk_ids = hidden_states.new_empty((num_tokens, topk), dtype=torch.int32)
return topk_weights, topk_ids
def biased_topk_cpu(
hidden_states: torch.Tensor,
gating_output: torch.Tensor,
correction_bias: torch.Tensor,
topk: int,
renormalize: bool,
scoring_func: str,
num_fused_shared_experts: int,
routed_scaling_factor: float | None,
apply_routed_scaling_factor_on_output: bool,
) -> tuple[torch.Tensor, torch.Tensor]:
return torch.ops._C.biased_topk_cpu(
hidden_states,
gating_output,
correction_bias,
topk,
renormalize,
scoring_func,
num_fused_shared_experts,
routed_scaling_factor,
apply_routed_scaling_factor_on_output,
)
if hasattr(torch.ops._C, "hash_topk_cpu"):
@register_fake("_C::hash_topk_cpu")
def hash_topk_cpu_fake(
gating_output: torch.Tensor,
tid2eid: torch.Tensor,
topk: int,
scoring_func: str,
num_fused_shared_experts: int,
num_experts: int,
routed_scaling_factor: float,
) -> tuple[torch.Tensor, torch.Tensor]:
num_tokens = gating_output.size(0)
topk_weights = gating_output.new_empty((num_tokens, topk), dtype=torch.float32)
topk_ids = gating_output.new_empty((num_tokens, topk), dtype=torch.int32)
return topk_weights, topk_ids
def hash_topk_cpu(
gating_output: torch.Tensor,
tid2eid: torch.Tensor,
topk: int,
scoring_func: str,
num_fused_shared_experts: int,
num_experts: int,
routed_scaling_factor: float,
) -> tuple[torch.Tensor, torch.Tensor]:
return torch.ops._C.hash_topk_cpu(
gating_output,
tid2eid,
topk,
scoring_func,
num_fused_shared_experts,
num_experts,
routed_scaling_factor,
)
if hasattr(torch.ops._C, "inverse_gptj_rope_o_proj_cpu"):
@register_fake("_C::inverse_gptj_rope_o_proj_cpu")
def inverse_gptj_rope_o_proj_cpu_fake(
o: torch.Tensor,
positions: torch.Tensor,
cos_sin_cache: torch.Tensor,
rope_dim: int,
) -> torch.Tensor:
return o.new_empty(o.shape, dtype=torch.float32)
def inverse_gptj_rope_o_proj_cpu(
o: torch.Tensor,
positions: torch.Tensor,
cos_sin_cache: torch.Tensor,
rope_dim: int,
) -> torch.Tensor:
return torch.ops._C.inverse_gptj_rope_o_proj_cpu(
o, positions, cos_sin_cache, rope_dim
)
def cpu_gemm_wna16(
input: torch.Tensor,
q_weight: torch.Tensor,
@@ -4107,6 +4469,7 @@ def cpu_prepack_moe_weight_int8(
def cpu_fused_moe(
out: torch.Tensor,
input: torch.Tensor,
w13: torch.Tensor,
w2: torch.Tensor,
@@ -4117,10 +4480,9 @@ def cpu_fused_moe(
act: str,
isa: str,
skip_weighted: bool = False,
) -> torch.Tensor:
output = torch.empty_like(input)
) -> None:
torch.ops._C.cpu_fused_moe(
output,
out,
input,
w13,
w2,
@@ -4132,10 +4494,10 @@ def cpu_fused_moe(
act,
isa,
)
return output
def cpu_fused_moe_int8(
out: torch.Tensor,
input: torch.Tensor,
w13: torch.Tensor,
w2: torch.Tensor,
@@ -4148,10 +4510,9 @@ def cpu_fused_moe_int8(
act: str,
isa: str,
skip_weighted: bool = False,
) -> torch.Tensor:
output = torch.empty_like(input)
) -> None:
torch.ops._C.cpu_fused_moe_int8(
output,
out,
input,
w13,
w2,
@@ -4165,7 +4526,6 @@ def cpu_fused_moe_int8(
act,
isa,
)
return output
if hasattr(torch.ops._qutlass_C, "matmul_mxf4_bf16_tn"):
@@ -6,6 +6,9 @@ import torch
from vllm import _custom_ops as ops
from vllm.model_executor.layers.quantization.utils import replace_parameter
from vllm.model_executor.layers.quantization.utils.fp8_utils import (
_upcast_e8m0_to_fp32,
)
from vllm.model_executor.layers.quantization.utils.w8a8_utils import (
convert_to_channelwise,
)
@@ -281,10 +284,12 @@ class CPUFp8BlockScaledMMKernel(Fp8BlockScaledMMLinearKernel):
else params.weight_scale
)
assert weight_scale is not None
if weight_scale.dtype in (torch.float8_e8m0fnu, torch.uint8):
weight_scale = _upcast_e8m0_to_fp32(weight_scale.data)
replace_parameter(
layer,
scale_attr,
torch.nn.Parameter(weight_scale.data, requires_grad=False),
torch.nn.Parameter(weight_scale.data.contiguous(), requires_grad=False),
)
def apply_weights(
@@ -1,6 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from .aiter import *
from .cpu import *
from .tilelang import *
from .torch import *
from .triton import *
@@ -14,6 +15,9 @@ __all__ = [
"mhc_post_aiter",
"mhc_fused_post_pre_aiter",
"hc_head_fused_aiter",
"mhc_pre_cpu",
"mhc_post_cpu",
"hc_head_fused_cpu",
"mhc_pre_tilelang",
"mhc_post_tilelang",
"mhc_fused_post_pre_tilelang",
+96
View File
@@ -0,0 +1,96 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import torch
from vllm import _custom_ops as ops
def mhc_pre_cpu(
residual: torch.Tensor,
fn: torch.Tensor,
hc_scale: torch.Tensor,
hc_base: torch.Tensor,
rms_eps: float,
hc_pre_eps: float,
hc_sinkhorn_eps: float,
hc_post_mult_value: float,
sinkhorn_repeat: int,
n_splits: int = 1,
norm_weight: torch.Tensor | None = None,
norm_eps: float = 0.0,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""CPU-ported mHC pre block (see `mhc_pre_torch` for the eager reference).
The ported kernel (`hc_pre_fused_cpu`) only exposes one merged `hc_eps`
(used for both `hc_pre_eps`/`hc_sinkhorn_eps`) and hardcodes the post-mix
multiplier to 2.0 -- true of every real call site in
`models/deepseek_v4/cpu/model.py`, so this is not a capability loss here.
"""
assert n_splits == 1, "mhc_pre_cpu does not support n_splits != 1"
assert hc_pre_eps == hc_sinkhorn_eps, (
"mhc_pre_cpu requires hc_pre_eps == hc_sinkhorn_eps (single merged hc_eps)"
)
assert hc_post_mult_value == 2.0, "mhc_pre_cpu hardcodes the post-mix multiplier"
hc_mult, hidden_size = residual.shape[-2:]
outer_shape = residual.shape[:-2]
x_flat = residual.reshape(-1, hc_mult, hidden_size)
layer_input, post, comb = ops.hc_pre_fused_cpu(
x_flat,
fn,
hc_scale,
hc_base,
hc_mult,
sinkhorn_repeat,
rms_eps,
hc_pre_eps,
)
post_mix = post.view(*outer_shape, hc_mult, 1)
comb_mix = comb.view(*outer_shape, hc_mult, hc_mult)
layer_input = layer_input.view(*outer_shape, hidden_size)
return post_mix, comb_mix, layer_input
def mhc_post_cpu(
x: torch.Tensor,
residual: torch.Tensor,
post_layer_mix: torch.Tensor,
comb_res_mix: torch.Tensor,
) -> torch.Tensor:
"""CPU-ported mHC post block (see `mhc_post_torch` for the eager reference)."""
hc_mult, hidden_size = residual.shape[-2:]
outer_shape = residual.shape[:-2]
x_flat = x.reshape(-1, hidden_size)
residual_flat = residual.reshape(-1, hc_mult, hidden_size)
post_flat = post_layer_mix.reshape(-1, hc_mult).float()
comb_flat = comb_res_mix.reshape(-1, hc_mult, hc_mult).float()
out = ops.hc_post_fused_cpu(x_flat, residual_flat, post_flat, comb_flat)
return out.view(*outer_shape, hc_mult, hidden_size)
def hc_head_fused_cpu(
hidden_states: torch.Tensor,
hc_fn: torch.Tensor,
hc_scale: torch.Tensor,
hc_base: torch.Tensor,
rms_norm_eps: float,
hc_eps: float,
) -> torch.Tensor:
"""CPU-ported HC head reduction (see `test_hc_head_cpu` in
tests/kernels/test_mhc_kernels.py for the eager reference this is tested
against).
The ported kernel's C++ signature takes `(hc_eps, norm_eps)` -- the
opposite order from this wrapper's `(rms_norm_eps, hc_eps)`, which matches
the real call site in `models/deepseek_v4/cpu/model.py`.
"""
hc_mult, hidden_size = hidden_states.shape[-2:]
outer_shape = hidden_states.shape[:-2]
hs_flat = hidden_states.reshape(-1, hc_mult, hidden_size)
out = ops.hc_head_fused_cpu(hs_flat, hc_fn, hc_scale, hc_base, hc_eps, rms_norm_eps)
return out.view(*outer_shape, hidden_size)
@@ -218,7 +218,7 @@ class CPUExpertsInt4(mk.FusedMoEExpertsMonolithic):
Returns:
Output tensor after MoE computation
"""
from vllm.model_executor.layers.fused_moe.experts.cpu_moe import (
from vllm.model_executor.layers.fused_moe.router.cpu_router import (
select_experts,
)
@@ -4,7 +4,6 @@
import math
import sys
from collections.abc import Callable
from typing import cast
import torch
@@ -34,6 +33,9 @@ from vllm.model_executor.layers.fused_moe.config import (
FusedMoEQuantConfig,
RoutingMethodType,
)
from vllm.model_executor.layers.fused_moe.topk_weight_and_reduce import (
TopKWeightAndReduceNoOP,
)
from vllm.model_executor.layers.quantization.utils.quant_utils import (
QuantKey,
kFp8Dynamic128Sym,
@@ -48,133 +50,26 @@ from vllm.platforms import CpuArchEnum, current_platform
from vllm.utils.math_utils import round_up
logger = init_logger(__name__)
# ===========================================================================
# Routing
# ===========================================================================
def grouped_topk(
hidden_states: torch.Tensor,
gating_output: torch.Tensor,
topk: int,
renormalize: bool,
num_expert_group: int = 0,
topk_group: int = 0,
scoring_func: str = "softmax",
routed_scaling_factor: float = 1.0,
e_score_correction_bias: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
assert hidden_states.shape[0] == gating_output.shape[0], "Number of tokens mismatch"
gating_output = gating_output.float()
if scoring_func == "softmax":
scores = torch.softmax(gating_output, dim=-1)
elif scoring_func == "sigmoid":
scores = gating_output.sigmoid()
else:
raise ValueError(f"Unsupported scoring function: {scoring_func}")
num_token = scores.shape[0]
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)
)
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_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]
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)
if renormalize:
topk_weights = topk_weights / topk_weights.sum(dim=-1, keepdim=True)
if routed_scaling_factor != 1.0:
topk_weights = topk_weights * routed_scaling_factor
return topk_weights, topk_ids.to(torch.int32)
def select_experts(
hidden_states: torch.Tensor,
router_logits: torch.Tensor,
top_k: int,
use_grouped_topk: bool,
renormalize: bool,
topk_group: int | None = None,
num_expert_group: int | None = None,
custom_routing_function: Callable | None = None,
scoring_func: str = "softmax",
routed_scaling_factor: float = 1.0,
e_score_correction_bias: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
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,
)
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
)
if renormalize:
topk_vals = torch.softmax(topk_logit_vals, dim=-1)
else:
logZ = torch.logsumexp(router_logits, dim=-1, keepdim=True)
topk_vals = (topk_logit_vals - logZ).exp()
return topk_vals.to(torch.float32), topk_idx.to(torch.int32)
else:
topk_weights, topk_ids = custom_routing_function(
hidden_states=hidden_states,
gating_output=router_logits,
topk=top_k,
renormalize=renormalize,
)
# cpu_fused_moe reads routing tensors as contiguous float32/int32
# buffers and does not account for tensor strides.
topk_weights = topk_weights.to(torch.float32).contiguous()
topk_ids = topk_ids.to(torch.int32).contiguous()
return topk_weights, topk_ids
# ===========================================================================
# Unquantized (BF16/FP16/FP32) MoE
# ===========================================================================
class CPUUnquantizedExperts(mk.FusedMoEExpertsMonolithic):
class CPUUnquantizedExperts(mk.FusedMoEExpertsModular):
"""Portable vector grouped-gemm unquantized MoE experts."""
isa = "vec"
output_alignment = 32
reduction_alignment = 1
def __init__(
self,
moe_config: FusedMoEConfig,
quant_config: FusedMoEQuantConfig,
):
super().__init__(moe_config, quant_config)
self._use_zentorch = False
@classmethod
def _intermediate_alignment(cls) -> int:
return math.lcm(cls.output_alignment, cls.reduction_alignment)
@@ -210,20 +105,6 @@ class CPUUnquantizedExperts(mk.FusedMoEExpertsMonolithic):
)
return True, None
def __init__(
self,
moe_config: FusedMoEConfig,
quant_config: FusedMoEQuantConfig,
):
super().__init__(moe_config, quant_config)
# Router configuration that the monolithic apply() signature cannot
# carry. Captured off the layer in process_weights_after_loading.
self.use_grouped_topk = False
self.renormalize = False
self.scoring_func = "softmax"
self.custom_routing_function: Callable | None = None
self._use_zentorch = False
@property
def expects_unquantized_inputs(self) -> bool:
return True
@@ -286,8 +167,8 @@ class CPUUnquantizedExperts(mk.FusedMoEExpertsMonolithic):
weight_key: QuantKey | None,
activation_key: QuantKey | None,
) -> bool:
# Routing runs in select_experts(), which covers every routing method
# a layer can be configured with, including custom routing functions.
# Routing runs in the CPURouter, which covers every routing method a
# layer can be configured with, including custom routing functions.
return True
@staticmethod
@@ -298,10 +179,6 @@ class CPUUnquantizedExperts(mk.FusedMoEExpertsMonolithic):
return True
def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
self.use_grouped_topk = layer.use_grouped_topk
self.renormalize = layer.renormalize
self.scoring_func = layer.scoring_func
self.custom_routing_function = layer.custom_routing_function
self._use_zentorch = is_zentorch_moe_supported(layer)
if self._use_zentorch:
return
@@ -345,65 +222,44 @@ class CPUUnquantizedExperts(mk.FusedMoEExpertsMonolithic):
# this very object, which is what feeds self.w1_bias in apply().
layer.w13_bias.data = new_bias
def _select_experts(
def workspace_shapes(
self,
hidden_states: torch.Tensor,
router_logits: torch.Tensor,
num_expert_group: int | None,
topk_group: int | None,
e_score_correction_bias: torch.Tensor | None,
routed_scaling_factor: float | None,
) -> tuple[torch.Tensor, torch.Tensor]:
return select_experts(
hidden_states=hidden_states,
router_logits=router_logits,
top_k=self.moe_config.experts_per_token,
use_grouped_topk=self.use_grouped_topk,
renormalize=self.renormalize,
topk_group=topk_group,
num_expert_group=num_expert_group,
custom_routing_function=self.custom_routing_function,
scoring_func=self.scoring_func,
routed_scaling_factor=(
routed_scaling_factor if routed_scaling_factor is not None else 1.0
),
e_score_correction_bias=e_score_correction_bias,
)
M: int,
N: int,
K: int,
topk: int,
global_num_experts: int,
local_num_experts: int,
expert_tokens_meta: mk.ExpertTokensMetadata | None,
activation: MoEActivation,
) -> tuple[tuple[int, ...], tuple[int, ...], tuple[int, ...]]:
# cpu_fused_moe manages its own scratch space.
return (0,), (0,), (M, K)
def finalize_weight_and_reduce_impl(self) -> mk.TopKWeightAndReduce:
return TopKWeightAndReduceNoOP()
def apply(
self,
output: torch.Tensor,
hidden_states: torch.Tensor,
w1: torch.Tensor,
w2: torch.Tensor,
router_logits: torch.Tensor,
topk_weights: torch.Tensor,
topk_ids: torch.Tensor,
activation: MoEActivation,
global_num_experts: int,
expert_map: torch.Tensor | None,
a1q_scale: torch.Tensor | None,
a2_scale: torch.Tensor | None,
workspace13: torch.Tensor,
workspace2: torch.Tensor,
expert_tokens_meta: mk.ExpertTokensMetadata | None,
apply_router_weight_on_input: bool,
# grouped topk + fused topk bias parameters
num_expert_group: int | None = None,
e_score_correction_bias: torch.Tensor | None = None,
routed_scaling_factor: float | None = None,
topk_group: int | None = None,
) -> torch.Tensor:
topk_weights, topk_ids = self._select_experts(
hidden_states,
router_logits,
num_expert_group,
topk_group,
e_score_correction_bias,
routed_scaling_factor,
)
if apply_router_weight_on_input:
assert topk_ids.size(1) == 1, (
"apply_router_weight_on_input is only implemented for topk=1"
)
hidden_states.mul_(topk_weights.to(hidden_states.dtype))
) -> None:
# apply_router_weight_on_input (topk=1 only) is already applied to
# hidden_states by MoEPrepareAndFinalizeNoDPEPModular.prepare().
if self._use_zentorch:
output = torch.empty_like(hidden_states)
torch.ops.zentorch.zentorch_fused_moe(
output,
hidden_states,
@@ -416,9 +272,9 @@ class CPUUnquantizedExperts(mk.FusedMoEExpertsMonolithic):
apply_router_weight_on_input,
str(activation.value).lower(),
)
return output
return cpu_fused_moe(
return
cpu_fused_moe(
output,
hidden_states,
w1,
w2,
@@ -460,8 +316,6 @@ class X86CPUUnquantizedExperts(CPUUnquantizedExperts):
)
if not supported:
return supported, reason
if is_zentorch_moe_config_supported(moe_config):
return True, None
if moe_config.in_dtype != torch.bfloat16:
return False, "kernel requires bfloat16 activations"
cpu_cls = cast(type[CPUUnquantizedExperts], cls)
@@ -496,8 +350,6 @@ class ArmCPUUnquantizedExperts(CPUUnquantizedExperts):
)
if not supported:
return supported, reason
if is_zentorch_moe_config_supported(moe_config):
return True, None
if moe_config.in_dtype != torch.bfloat16:
return False, "kernel requires bfloat16 activations"
cpu_cls = cast(type[CPUUnquantizedExperts], cls)
@@ -552,8 +404,8 @@ def prepare_fp8_moe_layer_for_cpu(
return packed_w13, packed_w2
class CPUExpertsFp8(mk.FusedMoEExpertsMonolithic):
"""CPU FP8 W8A16 block-quantized monolithic MoE experts."""
class CPUExpertsFp8(mk.FusedMoEExpertsModular):
"""CPU FP8 W8A16 block-quantized modular MoE experts."""
def __init__(
self,
@@ -615,6 +467,7 @@ class CPUExpertsFp8(mk.FusedMoEExpertsMonolithic):
RoutingMethodType.Default,
RoutingMethodType.Renormalize,
RoutingMethodType.RenormalizeNaive,
RoutingMethodType.DeepseekV4,
]
@staticmethod
@@ -624,42 +477,49 @@ class CPUExpertsFp8(mk.FusedMoEExpertsMonolithic):
) -> bool:
return True
def workspace_shapes(
self,
M: int,
N: int,
K: int,
topk: int,
global_num_experts: int,
local_num_experts: int,
expert_tokens_meta: mk.ExpertTokensMetadata | None,
activation: MoEActivation,
) -> tuple[tuple[int, ...], tuple[int, ...], tuple[int, ...]]:
# fused_experts_cpu manages its own scratch space.
return (0,), (0,), (M, K)
def finalize_weight_and_reduce_impl(self) -> mk.TopKWeightAndReduce:
return TopKWeightAndReduceNoOP()
def apply(
self,
output: torch.Tensor,
hidden_states: torch.Tensor,
w1: torch.Tensor,
w2: torch.Tensor,
router_logits: torch.Tensor,
topk_weights: torch.Tensor,
topk_ids: torch.Tensor,
activation: MoEActivation,
global_num_experts: int,
expert_map: torch.Tensor | None,
a1q_scale: torch.Tensor | None,
a2_scale: torch.Tensor | None,
workspace13: torch.Tensor,
workspace2: torch.Tensor,
expert_tokens_meta: mk.ExpertTokensMetadata | None,
apply_router_weight_on_input: bool,
# grouped topk + fused topk bias parameters
num_expert_group: int | None = None,
e_score_correction_bias: torch.Tensor | None = None,
routed_scaling_factor: float | None = None,
topk_group: int | None = None,
) -> torch.Tensor:
topk_weights, topk_ids = select_experts(
hidden_states=hidden_states,
router_logits=router_logits,
use_grouped_topk=num_expert_group is not None,
top_k=self.moe_config.experts_per_token,
renormalize=self.moe_config.routing_method
in (
RoutingMethodType.Renormalize,
RoutingMethodType.RenormalizeNaive,
),
topk_group=topk_group,
num_expert_group=num_expert_group,
scoring_func="softmax",
routed_scaling_factor=(
routed_scaling_factor if routed_scaling_factor is not None else 1.0
),
e_score_correction_bias=e_score_correction_bias,
)
) -> None:
if apply_router_weight_on_input:
# fused_experts_cpu always applies topk_weights internally on
# combine; MoEPrepareAndFinalizeNoDPEPModular.prepare() would
# also pre-apply it to hidden_states, double-weighting the
# output. Not needed by any CPU FP8 model today.
raise NotImplementedError(
"CPUExpertsFp8 does not support apply_router_weight_on_input=True."
)
block_shape = (
list(self.quant_config.block_shape)
if self.quant_config.block_shape
@@ -670,13 +530,13 @@ class CPUExpertsFp8(mk.FusedMoEExpertsMonolithic):
)
)
return fused_experts_cpu(
fused_experts_cpu(
output,
hidden_states,
w1,
w2,
topk_weights,
topk_ids,
False, # inplace
CPUQuantMethod.FP8_W8A16, # moe_comp_method
self.w1_scale, # w1_scale
self.w2_scale, # w2_scale
@@ -710,8 +570,8 @@ def prepare_mxfp4_moe_layer_for_cpu(
return packed_w13, packed_w2, packed_w13_scale, packed_w2_scale
class CPUExpertsMxfp4(mk.FusedMoEExpertsMonolithic):
"""CPU MXFP4 W4A16 monolithic MoE experts."""
class CPUExpertsMxfp4(mk.FusedMoEExpertsModular):
"""CPU MXFP4 W4A16 modular MoE experts."""
def __init__(
self,
@@ -773,6 +633,7 @@ class CPUExpertsMxfp4(mk.FusedMoEExpertsMonolithic):
RoutingMethodType.Default,
RoutingMethodType.Renormalize,
RoutingMethodType.RenormalizeNaive,
RoutingMethodType.DeepseekV4,
]
@staticmethod
@@ -782,55 +643,62 @@ class CPUExpertsMxfp4(mk.FusedMoEExpertsMonolithic):
) -> bool:
return True
def workspace_shapes(
self,
M: int,
N: int,
K: int,
topk: int,
global_num_experts: int,
local_num_experts: int,
expert_tokens_meta: mk.ExpertTokensMetadata | None,
activation: MoEActivation,
) -> tuple[tuple[int, ...], tuple[int, ...], tuple[int, ...]]:
# fused_experts_cpu manages its own scratch space.
return (0,), (0,), (M, K)
def finalize_weight_and_reduce_impl(self) -> mk.TopKWeightAndReduce:
return TopKWeightAndReduceNoOP()
def apply(
self,
output: torch.Tensor,
hidden_states: torch.Tensor,
w1: torch.Tensor,
w2: torch.Tensor,
router_logits: torch.Tensor,
topk_weights: torch.Tensor,
topk_ids: torch.Tensor,
activation: MoEActivation,
global_num_experts: int,
expert_map: torch.Tensor | None,
a1q_scale: torch.Tensor | None,
a2_scale: torch.Tensor | None,
workspace13: torch.Tensor,
workspace2: torch.Tensor,
expert_tokens_meta: mk.ExpertTokensMetadata | None,
apply_router_weight_on_input: bool,
# grouped topk + fused topk bias parameters
num_expert_group: int | None = None,
e_score_correction_bias: torch.Tensor | None = None,
routed_scaling_factor: float | None = None,
topk_group: int | None = None,
) -> torch.Tensor:
topk_weights, topk_ids = select_experts(
hidden_states=hidden_states,
router_logits=router_logits,
use_grouped_topk=num_expert_group is not None,
top_k=self.moe_config.experts_per_token,
renormalize=self.moe_config.routing_method
in (
RoutingMethodType.Renormalize,
RoutingMethodType.RenormalizeNaive,
),
topk_group=topk_group,
num_expert_group=num_expert_group,
scoring_func="softmax",
routed_scaling_factor=(
routed_scaling_factor if routed_scaling_factor is not None else 1.0
),
e_score_correction_bias=e_score_correction_bias,
)
) -> None:
if apply_router_weight_on_input:
# fused_experts_cpu always applies topk_weights internally on
# combine; MoEPrepareAndFinalizeNoDPEPModular.prepare() would
# also pre-apply it to hidden_states, double-weighting the
# output. Not needed by any CPU MXFP4 model today.
raise NotImplementedError(
"CPUExpertsMxfp4 does not support apply_router_weight_on_input=True."
)
# Get bias and swiglu params from quant config
w1_bias = self.quant_config.w1_bias
w2_bias = self.quant_config.w2_bias
alpha = getattr(self.quant_config, "gemm1_alpha", None)
limit = getattr(self.quant_config, "gemm1_clamp_limit", None)
return fused_experts_cpu(
fused_experts_cpu(
output,
hidden_states,
w1,
w2,
topk_weights,
topk_ids,
False, # inplace
CPUQuantMethod.MXFP4, # moe_comp_method
self.w1_scale, # w1_scale
self.w2_scale, # w2_scale
@@ -911,8 +779,8 @@ def prepare_int4_moe_layer_for_cpu(
return (blocked_w13, blocked_w2, blocked_s13, blocked_s2, blocked_z13, blocked_z2)
class CPUExpertsInt4(mk.FusedMoEExpertsMonolithic):
"""CPU INT4 W4A16 group-quantized monolithic MoE experts.
class CPUExpertsInt4(mk.FusedMoEExpertsModular):
"""CPU INT4 W4A16 group-quantized modular MoE experts.
Weights are int4 (packed), activations are bf16/fp16.
Internally uses int8 compute via fused_experts_cpu with INT4_W4A8.
@@ -992,55 +860,75 @@ class CPUExpertsInt4(mk.FusedMoEExpertsMonolithic):
def supports_expert_map(self) -> bool:
return False
def moe_problem_size(
self,
a1: torch.Tensor,
w1: torch.Tensor,
w2: torch.Tensor,
topk_ids: torch.Tensor,
) -> tuple[int, int, int, int, int]:
# convert_weight_packed_scale_zp blocks w1/w2 into AMX tiles
# (E, Nc, Kc, buffer_bytes), not the (E, N, K) layout the base
# implementation assumes -- N/K aren't recoverable from that shape,
# so read them from moe_config instead.
E = w1.shape[0]
K = a1.size(-1)
N = (
self.moe_config.intermediate_size_per_partition
* self.moe_config.w13_num_shards
)
M = a1.size(0) if a1.dim() == 2 else a1.size(1)
topk = topk_ids.size(1)
return E, M, N, K, topk
def workspace_shapes(
self,
M: int,
N: int,
K: int,
topk: int,
global_num_experts: int,
local_num_experts: int,
expert_tokens_meta: mk.ExpertTokensMetadata | None,
activation: MoEActivation,
) -> tuple[tuple[int, ...], tuple[int, ...], tuple[int, ...]]:
# fused_experts_cpu manages its own scratch space.
return (0,), (0,), (M, K)
def finalize_weight_and_reduce_impl(self) -> mk.TopKWeightAndReduce:
return TopKWeightAndReduceNoOP()
def apply(
self,
output: torch.Tensor,
hidden_states: torch.Tensor,
w1: torch.Tensor,
w2: torch.Tensor,
router_logits: torch.Tensor,
topk_weights: torch.Tensor,
topk_ids: torch.Tensor,
activation: MoEActivation,
global_num_experts: int,
expert_map: torch.Tensor | None,
a1q_scale: torch.Tensor | None,
a2_scale: torch.Tensor | None,
workspace13: torch.Tensor,
workspace2: torch.Tensor,
expert_tokens_meta: mk.ExpertTokensMetadata | None,
apply_router_weight_on_input: bool,
# grouped topk + fused topk bias parameters
num_expert_group: int | None = None,
e_score_correction_bias: torch.Tensor | None = None,
routed_scaling_factor: float | None = None,
topk_group: int | None = None,
) -> torch.Tensor:
) -> None:
if apply_router_weight_on_input:
raise NotImplementedError(
"CPUExpertsInt4 (W4A16) does not support "
"apply_router_weight_on_input=True. "
)
topk_weights, topk_ids = select_experts(
hidden_states=hidden_states,
router_logits=router_logits,
use_grouped_topk=num_expert_group is not None,
top_k=self.moe_config.experts_per_token,
renormalize=self.moe_config.routing_method
in (
RoutingMethodType.Renormalize,
RoutingMethodType.RenormalizeNaive,
),
topk_group=topk_group,
num_expert_group=num_expert_group,
scoring_func="softmax",
routed_scaling_factor=(
routed_scaling_factor if routed_scaling_factor is not None else 1.0
),
e_score_correction_bias=e_score_correction_bias,
)
return fused_experts_cpu(
fused_experts_cpu(
output,
hidden_states,
w1,
w2,
topk_weights,
topk_ids,
False, # inplace
CPUQuantMethod.INT4_W4A8,
self.w1_scale,
self.w2_scale,
@@ -1060,9 +948,9 @@ class CPUExpertsInt4(mk.FusedMoEExpertsMonolithic):
# ===========================================================================
class CPUExpertsInt8(mk.FusedMoEExpertsMonolithic):
class CPUExpertsInt8(mk.FusedMoEExpertsModular):
"""CPU INT8 W8A8 per-channel weight / dynamic per-token activation
monolithic MoE experts."""
modular MoE experts."""
def __init__(
self,
@@ -1172,49 +1060,56 @@ class CPUExpertsInt8(mk.FusedMoEExpertsMonolithic):
replace_parameter(layer, "w13_weight", w13)
replace_parameter(layer, "w2_weight", w2)
def workspace_shapes(
self,
M: int,
N: int,
K: int,
topk: int,
global_num_experts: int,
local_num_experts: int,
expert_tokens_meta: mk.ExpertTokensMetadata | None,
activation: MoEActivation,
) -> tuple[tuple[int, ...], tuple[int, ...], tuple[int, ...]]:
# fused_experts_cpu manages its own scratch space.
return (0,), (0,), (M, K)
def finalize_weight_and_reduce_impl(self) -> mk.TopKWeightAndReduce:
return TopKWeightAndReduceNoOP()
def apply(
self,
output: torch.Tensor,
hidden_states: torch.Tensor,
w1: torch.Tensor,
w2: torch.Tensor,
router_logits: torch.Tensor,
topk_weights: torch.Tensor,
topk_ids: torch.Tensor,
activation: MoEActivation,
global_num_experts: int,
expert_map: torch.Tensor | None,
a1q_scale: torch.Tensor | None,
a2_scale: torch.Tensor | None,
workspace13: torch.Tensor,
workspace2: torch.Tensor,
expert_tokens_meta: mk.ExpertTokensMetadata | None,
apply_router_weight_on_input: bool,
# grouped topk + fused topk bias parameters
num_expert_group: int | None = None,
e_score_correction_bias: torch.Tensor | None = None,
routed_scaling_factor: float | None = None,
topk_group: int | None = None,
) -> torch.Tensor:
topk_weights, topk_ids = select_experts(
hidden_states=hidden_states,
router_logits=router_logits,
use_grouped_topk=num_expert_group is not None,
top_k=self.moe_config.experts_per_token,
renormalize=self.moe_config.routing_method
in (
RoutingMethodType.Renormalize,
RoutingMethodType.RenormalizeNaive,
),
topk_group=topk_group,
num_expert_group=num_expert_group,
scoring_func="softmax",
routed_scaling_factor=(
routed_scaling_factor if routed_scaling_factor is not None else 1.0
),
e_score_correction_bias=e_score_correction_bias,
)
return fused_experts_cpu(
) -> None:
if apply_router_weight_on_input:
# fused_experts_cpu always applies topk_weights internally on
# combine; MoEPrepareAndFinalizeNoDPEPModular.prepare() would
# also pre-apply it to hidden_states, double-weighting the
# output. Not needed by any CPU INT8 W8A8 model today.
raise NotImplementedError(
"CPUExpertsInt8 does not support apply_router_weight_on_input=True."
)
fused_experts_cpu(
output,
hidden_states,
w1,
w2,
topk_weights,
topk_ids,
False, # inplace
CPUQuantMethod.INT8_W8A8,
self.w1_scale,
self.w2_scale,
@@ -1229,7 +1124,7 @@ class CPUExpertsInt8(mk.FusedMoEExpertsMonolithic):
)
class ArmCPUExpertsInt8(mk.FusedMoEExpertsMonolithic):
class ArmCPUExpertsInt8(mk.FusedMoEExpertsModular):
"""Arm INT8 MoE with per-token activation and channelwise weight quantization."""
@property
@@ -1331,48 +1226,47 @@ class ArmCPUExpertsInt8(mk.FusedMoEExpertsMonolithic):
replace_parameter(layer, "w13_weight", w13)
replace_parameter(layer, "w2_weight", w2)
def workspace_shapes(
self,
M: int,
N: int,
K: int,
topk: int,
global_num_experts: int,
local_num_experts: int,
expert_tokens_meta: mk.ExpertTokensMetadata | None,
activation: MoEActivation,
) -> tuple[tuple[int, ...], tuple[int, ...], tuple[int, ...]]:
# cpu_fused_moe_int8 manages its own scratch space.
return (0,), (0,), (M, K)
def finalize_weight_and_reduce_impl(self) -> mk.TopKWeightAndReduce:
return TopKWeightAndReduceNoOP()
def apply(
self,
output: torch.Tensor,
hidden_states: torch.Tensor,
w1: torch.Tensor,
w2: torch.Tensor,
router_logits: torch.Tensor,
topk_weights: torch.Tensor,
topk_ids: torch.Tensor,
activation: MoEActivation,
global_num_experts: int,
expert_map: torch.Tensor | None,
a1q_scale: torch.Tensor | None,
a2_scale: torch.Tensor | None,
workspace13: torch.Tensor,
workspace2: torch.Tensor,
expert_tokens_meta: mk.ExpertTokensMetadata | None,
apply_router_weight_on_input: bool,
num_expert_group: int | None = None,
e_score_correction_bias: torch.Tensor | None = None,
routed_scaling_factor: float | None = None,
topk_group: int | None = None,
) -> torch.Tensor:
topk_weights, topk_ids = select_experts(
hidden_states=hidden_states,
router_logits=router_logits,
use_grouped_topk=num_expert_group is not None,
top_k=self.moe_config.experts_per_token,
renormalize=self.moe_config.routing_method
in (
RoutingMethodType.Renormalize,
RoutingMethodType.RenormalizeNaive,
),
topk_group=topk_group,
num_expert_group=num_expert_group,
scoring_func="softmax",
routed_scaling_factor=(
routed_scaling_factor if routed_scaling_factor is not None else 1.0
),
e_score_correction_bias=e_score_correction_bias,
)
if apply_router_weight_on_input:
assert topk_ids.size(1) == 1
hidden_states.mul_(topk_weights.to(hidden_states.dtype))
) -> None:
# apply_router_weight_on_input (topk=1 only) is already applied to
# hidden_states by MoEPrepareAndFinalizeNoDPEPModular.prepare().
assert self.w1_scale is not None
assert self.w2_scale is not None
return cpu_fused_moe_int8(
cpu_fused_moe_int8(
output,
hidden_states,
w1,
w2,
@@ -1388,7 +1282,7 @@ class ArmCPUExpertsInt8(mk.FusedMoEExpertsMonolithic):
)
class ZenCPUExpertsInt8(mk.FusedMoEExpertsMonolithic):
class ZenCPUExpertsInt8(mk.FusedMoEExpertsModular):
"""AMD Zen INT8 MoE with per-token activation and channelwise weight
quantization, dispatched through zentorch."""
@@ -1424,9 +1318,7 @@ class ZenCPUExpertsInt8(mk.FusedMoEExpertsMonolithic):
if self.w2_bias is None
else self.w2_bias.detach().to(torch.bfloat16).contiguous()
)
logger.info_once(
"[zen_cpu] Using zentorch_fused_moe for W8A8 INT8 MoE (monolithic experts)"
)
logger.info_once("[zen_cpu] Using zentorch_fused_moe for W8A8 INT8 MoE")
@property
def expects_unquantized_inputs(self) -> bool:
@@ -1487,48 +1379,47 @@ class ZenCPUExpertsInt8(mk.FusedMoEExpertsMonolithic):
def supports_expert_map(self) -> bool:
return False
def workspace_shapes(
self,
M: int,
N: int,
K: int,
topk: int,
global_num_experts: int,
local_num_experts: int,
expert_tokens_meta: mk.ExpertTokensMetadata | None,
activation: MoEActivation,
) -> tuple[tuple[int, ...], tuple[int, ...], tuple[int, ...]]:
# zentorch_fused_moe manages its own scratch space.
return (0,), (0,), (M, K)
def finalize_weight_and_reduce_impl(self) -> mk.TopKWeightAndReduce:
return TopKWeightAndReduceNoOP()
def apply(
self,
output: torch.Tensor,
hidden_states: torch.Tensor,
w1: torch.Tensor,
w2: torch.Tensor,
router_logits: torch.Tensor,
topk_weights: torch.Tensor,
topk_ids: torch.Tensor,
activation: MoEActivation,
global_num_experts: int,
expert_map: torch.Tensor | None,
a1q_scale: torch.Tensor | None,
a2_scale: torch.Tensor | None,
workspace13: torch.Tensor,
workspace2: torch.Tensor,
expert_tokens_meta: mk.ExpertTokensMetadata | None,
apply_router_weight_on_input: bool,
num_expert_group: int | None = None,
e_score_correction_bias: torch.Tensor | None = None,
routed_scaling_factor: float | None = None,
topk_group: int | None = None,
) -> torch.Tensor:
topk_weights, topk_ids = select_experts(
hidden_states=hidden_states,
router_logits=router_logits,
use_grouped_topk=num_expert_group is not None,
top_k=self.moe_config.experts_per_token,
renormalize=self.moe_config.routing_method
in (
RoutingMethodType.Renormalize,
RoutingMethodType.RenormalizeNaive,
),
topk_group=topk_group,
num_expert_group=num_expert_group,
scoring_func="softmax",
routed_scaling_factor=(
routed_scaling_factor if routed_scaling_factor is not None else 1.0
),
e_score_correction_bias=e_score_correction_bias,
)
) -> None:
if apply_router_weight_on_input:
assert topk_ids.size(1) == 1, (
"apply_router_weight_on_input is only implemented for topk=1"
)
hidden_states = hidden_states.mul(topk_weights.to(hidden_states.dtype))
output = torch.empty_like(hidden_states)
torch.ops.zentorch.zentorch_fused_moe(
output,
hidden_states,
@@ -1543,4 +1434,3 @@ class ZenCPUExpertsInt8(mk.FusedMoEExpertsMonolithic):
self._w1_scale_bf16,
self._w2_scale_bf16,
)
return output
@@ -1175,6 +1175,24 @@ class FusedMoEKernelModularImpl:
# time we need cache3, we're done with cache1.
# Reuse workspace13 for the output since there is only one chunk.
max_shape_size = max(prod(workspace13_shape), prod(fused_out_shape))
if current_platform.is_cpu():
# Every CPU FusedMoEExpertsModular kernel reports zero-sized
# workspace13/workspace2 (it manages its own scratch space
# internally) and just needs the output buffer, so skip the
# workspace manager entirely here -- it's the one part of this
# call graph Dynamo can't trace (ContextVar-based lane lookup),
# and CPU never actually needs its cross-chunk memory reuse.
common_workspace = torch.empty(
(max_shape_size,), dtype=workspace_dtype, device=device
)
workspace2 = torch.empty(
workspace2_shape, dtype=workspace_dtype, device=device
)
workspace13 = _resize_cache(common_workspace, workspace13_shape)
fused_out = _resize_cache(common_workspace, fused_out_shape)
return workspace13, workspace2, fused_out
common_workspace, workspace2 = current_workspace_manager().get_simultaneous(
((max_shape_size,), workspace_dtype),
(workspace2_shape, workspace_dtype),
@@ -348,6 +348,7 @@ def _get_priority_backends_for_gpt_oss() -> list[Mxfp4MoeBackend]:
Mxfp4MoeBackend.MARLIN,
Mxfp4MoeBackend.BATCHED_MARLIN,
Mxfp4MoeBackend.XPU,
Mxfp4MoeBackend.CPU,
Mxfp4MoeBackend.EMULATION,
]
return _AVAILABLE_BACKENDS
@@ -366,6 +367,8 @@ def _get_priority_backends() -> list[Mxfp4MoeBackend]:
]
if current_platform.is_xpu():
return [Mxfp4MoeBackend.XPU]
if current_platform.is_cpu():
return [Mxfp4MoeBackend.CPU]
_AVAILABLE_BACKENDS = [
Mxfp4MoeBackend.FLASHINFER_TRTLLM_MXFP4_MXFP8,
Mxfp4MoeBackend.DEEPGEMM_MXFP4,
@@ -627,17 +630,6 @@ def select_mxfp4_moe_backend(
activation_format,
)
if current_platform.is_cpu():
backend = Mxfp4MoeBackend.CPU
logger.info_once(_make_log_backend(backend))
return _return_or_raise(
Mxfp4MoeBackend.CPU,
config,
kMxfp4Static,
None,
activation_format,
)
unsupported_log = "; ".join(
[
f"backend: {backend.value}, reason: {reason}"
@@ -1813,11 +1805,36 @@ def convert_weight_to_mxfp4_moe_kernel_format(
w2_bias=w2_bias,
_cache_permute_indices=_cache_permute_indices,
)
elif mxfp4_backend == Mxfp4MoeBackend.CPU:
from vllm.model_executor.layers.fused_moe.experts.cpu_moe import (
prepare_mxfp4_moe_layer_for_cpu,
)
packed_w13, packed_w2, packed_w13_scale, packed_w2_scale = (
prepare_mxfp4_moe_layer_for_cpu(
w13_weight.data,
w2_weight.data,
w13_weight_scale.data,
w2_weight_scale.data,
)
)
if w13_bias is not None:
w13_bias = w13_bias.data.to(torch.float32)
if w2_bias is not None:
w2_bias = w2_bias.data.to(torch.float32)
return (
packed_w13,
packed_w2,
packed_w13_scale,
packed_w2_scale,
w13_bias,
w2_bias,
)
else:
raise ValueError(
f"Unsupported mxfp4_backend for Mxfp4MoEMethod: {mxfp4_backend}. "
"Expected TRTLLM, FlashInfer CUTLASS, Triton, AITER, XPU, or "
"emulation backend."
"Expected TRTLLM, FlashInfer CUTLASS, Triton, AITER, XPU, "
"CPU, or emulation backend."
)
@@ -0,0 +1,294 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Router for CPU MoE experts.
This is the routing logic that used to live inline in each CPU
FusedMoEExpertsMonolithic.apply() (see git history of
experts/cpu_moe.py); factoring it out into a proper FusedMoERouter is what
lets CPU MoE experts be FusedMoEExpertsModular like every other backend.
The math below is unchanged from that prior inline version -- this is a
relocation, not a rewrite.
"""
from collections.abc import Callable
import torch
from vllm._custom_ops import biased_topk_cpu, hash_topk_cpu
from vllm.distributed.eplb.eplb_state import EplbLayerState
from vllm.model_executor.layers.fused_moe.config import (
RoutingMethodType,
get_routing_method_type,
)
from vllm.model_executor.layers.fused_moe.router.base_router import BaseRouter
def _grouped_topk(
gating_output: torch.Tensor,
topk: int,
renormalize: bool,
num_expert_group: int,
topk_group: int,
scoring_func: str,
routed_scaling_factor: float,
e_score_correction_bias: torch.Tensor | None,
) -> tuple[torch.Tensor, torch.Tensor]:
gating_output = gating_output.float()
if scoring_func == "softmax":
scores = torch.softmax(gating_output, dim=-1)
elif scoring_func == "sigmoid":
scores = gating_output.sigmoid()
else:
raise ValueError(f"Unsupported scoring function: {scoring_func}")
num_token = scores.shape[0]
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)
)
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_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]
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)
if renormalize:
topk_weights = topk_weights / topk_weights.sum(dim=-1, keepdim=True)
if routed_scaling_factor != 1.0:
topk_weights = topk_weights * routed_scaling_factor
return topk_weights, topk_ids.to(torch.int32)
def _sqrtsoftplus_bias_topk(
router_logits: torch.Tensor,
top_k: int,
renormalize: bool,
e_score_correction_bias: torch.Tensor | None,
routed_scaling_factor: float,
input_ids: torch.Tensor | None,
hash_indices_table: torch.Tensor | None,
) -> tuple[torch.Tensor, torch.Tensor]:
"""DeepSeek V4's routing: weight = sqrt(softplus(logit)); expert
selection uses a bias-corrected score (weight + correction_bias), but
the returned weight for each selected expert is the *unbiased* value
(the "noaux_tc" pattern -- bias steers selection only). Always
renormalizes selected weights to sum to ``routed_scaling_factor``,
matching the reference Triton kernel
(vllm/model_executor/layers/fused_moe/router/dsv4_topk.py).
When ``hash_indices_table`` is given (hash-routed layers), expert
selection instead comes from ``hash_indices_table[input_ids]`` --
the bias-corrected-score topk is skipped entirely, matching the CUDA
reference kernel (``dsv4HashTopkSoftplusSqrt``).
Backed by the ported SGLang AVX512 kernels `biased_topk_cpu` (the
correction-bias path) and `hash_topk_cpu` (the hash-routed-layer path);
see csrc/cpu/sgl-kernels/topk.cpp.
"""
assert renormalize, "DeepseekV4 routing always renormalizes"
gating_output = router_logits.contiguous()
num_experts = gating_output.shape[1]
if hash_indices_table is not None:
assert input_ids is not None
# hash_indices_table is int32 by construction (see cpu/model.py) and
# advanced indexing always allocates a fresh contiguous tensor.
tid2eid = hash_indices_table[input_ids]
return hash_topk_cpu(
gating_output,
tid2eid,
top_k,
"sqrtsoftplus",
0, # num_fused_shared_experts: never fused into routing on CPU
num_experts,
routed_scaling_factor,
)
assert e_score_correction_bias is not None
return biased_topk_cpu(
gating_output, # only used for num_tokens/device (dtype forced fp32)
gating_output,
e_score_correction_bias.contiguous(),
top_k,
renormalize,
"sqrtsoftplus",
0, # num_fused_shared_experts: never fused into routing on CPU
routed_scaling_factor,
True, # apply_routed_scaling_factor_on_output
)
def _softmax_topk(
router_logits: torch.Tensor,
top_k: int,
renormalize: bool,
) -> tuple[torch.Tensor, torch.Tensor]:
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:
logZ = torch.logsumexp(router_logits, dim=-1, keepdim=True)
topk_vals = (topk_logit_vals - logZ).exp()
return topk_vals.to(torch.float32), topk_idx.to(torch.int32)
class CPURouter(BaseRouter):
"""Router covering every routing scheme CPU MoE experts support: plain
softmax top-k, grouped top-k (with an optional correction bias), an
arbitrary custom_routing_function, and DeepSeek V4's sqrtsoftplus scheme
(bias-corrected or hash-routed via the ported biased_topk_cpu/
hash_topk_cpu kernels). All of the above except sqrtsoftplus are plain
torch ops so Dynamo traces straight through into them like it did when
this logic lived inline in FusedMoEExpertsMonolithic.apply() -- no new
compile boundary is introduced here.
"""
def __init__(
self,
top_k: int,
global_num_experts: int,
use_grouped_topk: bool = False,
num_expert_group: int | None = None,
topk_group: int | None = None,
renormalize: bool = True,
scoring_func: str = "softmax",
routed_scaling_factor: float = 1.0,
e_score_correction_bias: torch.Tensor | None = None,
custom_routing_function: Callable | None = None,
hash_indices_table: torch.Tensor | None = None,
eplb_state: EplbLayerState | None = None,
):
super().__init__(
top_k=top_k,
global_num_experts=global_num_experts,
eplb_state=eplb_state,
)
self.use_grouped_topk = use_grouped_topk
self.num_expert_group = num_expert_group
self.topk_group = topk_group
self.renormalize = renormalize
self.scoring_func = scoring_func
self.routed_scaling_factor = routed_scaling_factor
self.e_score_correction_bias = e_score_correction_bias
self.custom_routing_function = custom_routing_function
self._hash_indices_table = hash_indices_table
@property
def routing_method_type(self) -> RoutingMethodType:
return get_routing_method_type(
scoring_func=self.scoring_func,
top_k=self.top_k,
renormalize=self.renormalize,
num_expert_group=self.num_expert_group,
has_e_score_bias=self.e_score_correction_bias is not None,
routed_scaling_factor=self.routed_scaling_factor,
)
def _compute_routing(
self,
hidden_states: torch.Tensor,
router_logits: torch.Tensor,
indices_type: torch.dtype | None,
*,
input_ids: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
if self.use_grouped_topk:
assert self.topk_group is not None
assert self.num_expert_group is not None
return _grouped_topk(
gating_output=router_logits,
topk=self.top_k,
renormalize=self.renormalize,
num_expert_group=self.num_expert_group,
topk_group=self.topk_group,
scoring_func=self.scoring_func,
routed_scaling_factor=self.routed_scaling_factor,
e_score_correction_bias=self.e_score_correction_bias,
)
elif self.scoring_func == "sqrtsoftplus":
assert (
self._hash_indices_table is not None
or self.e_score_correction_bias is not None
)
return _sqrtsoftplus_bias_topk(
router_logits=router_logits,
top_k=self.top_k,
renormalize=self.renormalize,
e_score_correction_bias=self.e_score_correction_bias,
routed_scaling_factor=self.routed_scaling_factor,
input_ids=input_ids,
hash_indices_table=self._hash_indices_table,
)
elif self.custom_routing_function is None:
assert self.scoring_func == "softmax"
return _softmax_topk(router_logits, self.top_k, self.renormalize)
else:
topk_weights, topk_ids = self.custom_routing_function(
hidden_states=hidden_states,
gating_output=router_logits,
topk=self.top_k,
renormalize=self.renormalize,
)
# cpu_fused_moe reads routing tensors as contiguous float32/int32
# buffers and does not account for tensor strides.
topk_weights = topk_weights.to(torch.float32).contiguous()
topk_ids = topk_ids.to(torch.int32).contiguous()
return topk_weights, topk_ids
def select_experts(
hidden_states: torch.Tensor,
router_logits: torch.Tensor,
top_k: int,
use_grouped_topk: bool,
renormalize: bool,
topk_group: int | None = None,
num_expert_group: int | None = None,
custom_routing_function: Callable | None = None,
scoring_func: str = "softmax",
routed_scaling_factor: float = 1.0,
e_score_correction_bias: torch.Tensor | None = None,
input_ids: torch.Tensor | None = None,
hash_indices_table: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Routing helper for the CPU MoE experts that still use the monolithic
contract and so must compute routing themselves from ``router_logits``
(the zentorch-accelerated path and the ARM W4A8 dynamic-quant kernel,
kept monolithic since zentorch/Arm hardware isn't available to validate
a modular migration here). Modular CPU experts get routing from
``CPURouter`` instead; this is a thin wrapper around the same logic for
the two classes that can't use it.
"""
router = CPURouter(
top_k=top_k,
global_num_experts=router_logits.shape[-1],
use_grouped_topk=use_grouped_topk,
num_expert_group=num_expert_group,
topk_group=topk_group,
renormalize=renormalize,
scoring_func=scoring_func,
routed_scaling_factor=routed_scaling_factor,
e_score_correction_bias=e_score_correction_bias,
custom_routing_function=custom_routing_function,
hash_indices_table=hash_indices_table,
)
return router._compute_routing(
hidden_states, router_logits, None, input_ids=input_ids
)
@@ -14,6 +14,7 @@ from vllm.model_executor.layers.fused_moe.config import (
from vllm.model_executor.layers.fused_moe.router.aiter_shared_routed_fused_moe_router import ( # noqa: E501
AiterSharedRoutedFusedMoERouter,
)
from vllm.model_executor.layers.fused_moe.router.cpu_router import CPURouter
from vllm.model_executor.layers.fused_moe.router.custom_routing_router import (
CustomRoutingRouter,
)
@@ -35,6 +36,7 @@ from vllm.model_executor.layers.fused_moe.router.routing_simulator_router import
from vllm.model_executor.layers.fused_moe.router.zero_expert_router import (
ZeroExpertRouter,
)
from vllm.platforms import current_platform
def create_fused_moe_router(
@@ -141,6 +143,26 @@ def create_fused_moe_router(
routed_scaling_factor=routed_scaling_factor,
)
if current_platform.is_cpu():
# CPURouter covers every routing scheme CPU MoE experts support
# (plain softmax, grouped topk, custom routing functions, and
# DeepSeek V4's sqrtsoftplus/hash routing) in a single class, so it
# takes priority over the scheme-specific routers below.
return CPURouter(
top_k=top_k,
global_num_experts=global_num_experts,
use_grouped_topk=use_grouped_topk,
num_expert_group=num_expert_group,
topk_group=topk_group,
renormalize=renormalize,
scoring_func=scoring_func,
routed_scaling_factor=routed_scaling_factor,
e_score_correction_bias=e_score_correction_bias,
custom_routing_function=custom_routing_function,
hash_indices_table=hash_indices_table,
eplb_state=eplb_state,
)
if use_grouped_topk:
assert custom_routing_function is None
if num_expert_group is None or topk_group is None:
@@ -317,10 +317,17 @@ class MoERunner(MoERunnerInterface):
return self.routed_experts.load_weights(weights)
def _select_forward(self) -> Callable:
if current_platform.is_tpu() or current_platform.is_cpu():
if current_platform.is_tpu():
# TODO: Once the OOM issue for the TPU backend is resolved, we
# will switch to using the moe_forward custom op.
# Note: CPU doesn't require wrapped _forward_impl.
return _moe_forward if self._shared_experts is None else _moe_forward_shared
if current_platform.is_cpu():
# CPU never touches the workspace manager (Monolithic experts
# skip it entirely; Modular experts' _allocate_buffers bypasses
# it too, see modular_kernel.py) -- the ContextVar-based lane
# lookup was the only part of this call graph Dynamo can't
# trace, so CPU can always call the fused-MoE op directly.
return _moe_forward if self._shared_experts is None else _moe_forward_shared
return (
+88
View File
@@ -261,6 +261,36 @@ class MHCPreOp(CustomOp):
sinkhorn_repeat,
)
def forward_cpu(
self,
residual: torch.Tensor,
fn: torch.Tensor,
hc_scale: torch.Tensor,
hc_base: torch.Tensor,
rms_eps: float,
hc_pre_eps: float,
hc_sinkhorn_eps: float,
hc_post_mult_value: float,
sinkhorn_repeat: int,
n_splits: int = 1,
norm_weight: torch.Tensor | None = None,
norm_eps: float = 0.0,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
return mhc_kernels.mhc_pre_cpu(
residual,
fn,
hc_scale,
hc_base,
rms_eps,
hc_pre_eps,
hc_sinkhorn_eps,
hc_post_mult_value,
sinkhorn_repeat,
n_splits,
norm_weight,
norm_eps,
)
# --8<-- [start:mhc_post]
@CustomOp.register("mhc_post")
@@ -337,6 +367,15 @@ class MHCPostOp(CustomOp):
comb_res_mix,
)
def forward_cpu(
self,
x: torch.Tensor,
residual: torch.Tensor,
post_layer_mix: torch.Tensor,
comb_res_mix: torch.Tensor,
) -> torch.Tensor:
return mhc_kernels.mhc_post_cpu(x, residual, post_layer_mix, comb_res_mix)
# --8<-- [start:hc_head]
@CustomOp.register("hc_head")
@@ -444,6 +483,19 @@ class HCHeadOp(CustomOp):
)
return out.view(*outer_shape, hidden_size)
def forward_cpu(
self,
hidden_states: torch.Tensor,
hc_fn: torch.Tensor,
hc_scale: torch.Tensor,
hc_base: torch.Tensor,
rms_norm_eps: float,
hc_eps: float,
) -> torch.Tensor:
return mhc_kernels.hc_head_fused_cpu(
hidden_states, hc_fn, hc_scale, hc_base, rms_norm_eps, hc_eps
)
# --8<-- [start:mhc_fused_post_pre]
@CustomOp.register("mhc_fused_post_pre")
@@ -654,6 +706,42 @@ class MHCFusedPostPreOp(CustomOp):
sinkhorn_repeat,
)
def forward_cpu(
self,
x: torch.Tensor,
residual: torch.Tensor,
post_layer_mix: torch.Tensor,
comb_res_mix: torch.Tensor,
fn: torch.Tensor,
hc_scale: torch.Tensor,
hc_base: torch.Tensor,
rms_eps: float,
hc_pre_eps: float,
hc_sinkhorn_eps: float,
hc_post_mult_value: float,
sinkhorn_repeat: int,
n_splits: int = 1,
tile_n: int = 1,
norm_weight: torch.Tensor | None = None,
norm_eps: float = 0.0,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
# Decompose into post + pre (no fused kernel available).
residual_cur = mhc_kernels.mhc_post_cpu(
x, residual, post_layer_mix, comb_res_mix
)
post_mix_cur, comb_mix_cur, layer_input_cur = mhc_kernels.mhc_pre_cpu(
residual_cur,
fn,
hc_scale,
hc_base,
rms_eps,
hc_pre_eps,
hc_sinkhorn_eps,
hc_post_mult_value,
sinkhorn_repeat,
)
return residual_cur, post_mix_cur, comb_mix_cur, layer_input_cur
def hc_expand(x: torch.Tensor, n: int) -> torch.Tensor:
"""[s, hidden_size] -> [s, n * hidden_size] by replication."""
@@ -828,10 +828,12 @@ class SparseAttnIndexer(CustomOp):
return self.forward_cuda(hidden_states, q_quant, k, weights)
elif current_platform.is_rocm():
return self.forward_hip(hidden_states, q_quant, k, weights)
elif current_platform.is_cpu():
return self.forward_cpu(hidden_states, q_quant, k, weights)
else:
raise NotImplementedError(
"SparseAttnIndexer native forward is only implemented for "
"CUDA, ROCm and XPU platforms."
"CUDA, ROCm, XPU and CPU platforms."
)
def forward_cuda(
@@ -919,3 +921,196 @@ class SparseAttnIndexer(CustomOp):
"Sparse attention indexer ROCm path is only supported on AITER. "
"Please enable aiter with VLLM_ROCM_USE_AITER=1"
)
def forward_cpu(
self,
hidden_states: torch.Tensor,
q_quant: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
k: torch.Tensor | None,
weights: torch.Tensor,
):
"""CPU sparse attention indexer: cache write stays eager Python glue
(own K-cache layout, not shared with the main attention cache
write). PREFILL and DECODE both call the ported
``fp8_paged_mqa_logits_cpu``/``topk_transform_512_cpu`` kernels,
which read the paged K-cache directly via ``page_table`` -- no
eager gather step, no per-request Python loop.
``prefill_metadata.chunks`` always has exactly one entry here:
``DeepseekV4CPUIndexerMetadataBuilder`` overrides the base chunk
split to always return the whole step's prefill batch as one
chunk, since the base chunking only bounds CUDA/XPU's dense M*N
logits tensor and flat K-gather workspace, neither of which this
paged kernel allocates.
"""
assert not self.use_fp4_cache, (
"CPU sparse indexer doesn't support fp4 cache yet"
)
assert isinstance(q_quant, torch.Tensor), (
"CPU sparse_attn_indexer expects a single FP8 q_quant tensor"
)
assert self.dcp_world_size <= 1 and not self.use_pcp, (
"CPU sparse indexer doesn't support decode/prefill context parallelism yet."
)
forward_context = get_forward_context()
attn_metadata = forward_context.attn_metadata
attn_metadata_narrowed: DeepseekV32IndexerMetadata | None = None
if isinstance(attn_metadata, dict):
metadata = attn_metadata[self.k_cache.prefix]
assert isinstance(metadata, DeepseekV32IndexerMetadata)
attn_metadata_narrowed = metadata
if attn_metadata_narrowed is None:
# Profiling/dummy run: no real metadata to act on.
return self.topk_indices_buffer
kv_cache = self.k_cache.kv_cache
topk_tokens = self.topk_tokens
topk_indices_buffer = self.topk_indices_buffer
slot_mapping = attn_metadata_narrowed.slot_mapping
has_decode = attn_metadata_narrowed.num_decodes > 0
has_prefill = attn_metadata_narrowed.num_prefills > 0
num_decode_tokens = attn_metadata_narrowed.num_decode_tokens
num_tokens = slot_mapping.shape[0]
if k is not None:
k = k[:num_tokens]
if not self.skip_k_cache_insert:
# Only reachable via DeepseekV32Attention with
# prefill_context_parallel_size > 1 on CPU -- set_k_cpu/set_s_cpu
# (the kernels this used to call) have been removed as unused/
# untested (csrc/cpu/sgl-kernels/store_cache.cpp).
raise NotImplementedError(
"SparseAttnIndexer.forward_cpu: skip_k_cache_insert=False "
"(prefill context parallel on CPU) is not supported."
)
topk_indices_buffer[: hidden_states.shape[0]] = -1
if has_prefill:
assert topk_tokens == 512, (
"topk_transform_512_cpu only supports index_topk == 512."
)
prefill_metadata = attn_metadata_narrowed.prefill
assert prefill_metadata is not None
assert len(prefill_metadata.chunks) == 1, (
"forward_cpu expects the prefill metadata builder to always "
"produce a single chunk -- see "
"DeepseekV4CPUIndexerMetadataBuilder._split_indexer_prefill_chunks."
)
chunk = prefill_metadata.chunks[0]
# kv_cache is a per-layer view into vLLM's shared multi-layer
# cache allocation, so its block stride generally exceeds
# block_size * page_width; fp8_paged_mqa_logits_cpu reads
# kv_view.stride(0) explicitly, so no copy is needed here.
kv_view = kv_cache.view(kv_cache.shape[0], -1)
block_size = kv_cache.shape[1]
q_slice = q_quant[chunk.token_start : chunk.token_end]
topk_indices = topk_indices_buffer[
chunk.token_start : chunk.token_end, :topk_tokens
]
if chunk.local_total_seq_lens == 0:
topk_indices.fill_(-1)
else:
assert chunk.local_cu_seq_lens is not None
# Each token's own (per-request, DCP-local) causal length.
local_seq_lens = chunk.cu_seqlen_ke - chunk.cu_seqlen_ks
# Recover each token's owning request from its row-start
# tag. Ties (from zero-length requests) are harmless: those
# tokens have local length 0 and never dereference
# page_table.
req_idx = (
torch.searchsorted(
chunk.local_cu_seq_lens, chunk.cu_seqlen_ks, right=True
)
- 1
)
page_table = chunk.block_table[req_idx]
# The true max over this chunk's own rows, NOT
# chunk.max_local_total_seq_lens (that field sums every
# request's length in the chunk, bounding the old
# flat-gather buffer this paged path no longer allocates).
max_seq_len = int(local_seq_lens.max().item())
logits = ops.fp8_paged_mqa_logits_cpu(
q_slice,
kv_view,
weights[chunk.token_start : chunk.token_end],
local_seq_lens,
page_table,
block_size,
max_seq_len,
)
out_page_scratch = torch.empty(
(q_slice.shape[0], topk_tokens),
dtype=torch.int32,
device=kv_cache.device,
)
ops.topk_transform_512_cpu(
logits,
local_seq_lens,
page_table,
out_page_scratch,
block_size,
topk_indices,
)
if has_decode:
decode_metadata = attn_metadata_narrowed.decode
assert decode_metadata is not None
assert not decode_metadata.requires_padding, (
"CPU sparse indexer decode path does not support speculative "
"decoding (native MTP) yet."
)
batch_size = decode_metadata.decode_lens.shape[0]
if batch_size > 0:
# No native MTP on CPU (asserted above) => exactly one
# query token per decode request, so the flat slice below
# is already the batch-major layout
# fp8_paged_mqa_logits_cpu wants.
assert num_decode_tokens == batch_size, (
"CPU sparse indexer decode path expects exactly one query "
"token per decode request."
)
assert topk_tokens == 512, (
"topk_transform_512_cpu only supports index_topk == 512."
)
seq_lens = decode_metadata.seq_lens
seq_lens = (
seq_lens[:, -1].contiguous() if seq_lens.ndim == 2 else seq_lens
)
block_table = decode_metadata.block_table[:batch_size]
block_size = kv_cache.shape[1]
kv_view = kv_cache.view(kv_cache.shape[0], -1)
logits = ops.fp8_paged_mqa_logits_cpu(
q_quant[:num_decode_tokens],
kv_view,
weights[:num_decode_tokens],
seq_lens,
block_table,
block_size,
attn_metadata_narrowed.max_seq_len,
)
# out_page_indices is a required kernel output but unused:
# the indexer's topk output must stay local/compressed-
# context positions (resolved later by
# DeepseekV4CPUAttention.forward_mqa via
# map_local_to_global_slots_cpu).
out_page_scratch = torch.empty(
(batch_size, topk_tokens),
dtype=torch.int32,
device=kv_cache.device,
)
ops.topk_transform_512_cpu(
logits,
seq_lens,
block_table,
out_page_scratch,
block_size,
topk_indices_buffer[:num_decode_tokens, :topk_tokens],
)
return topk_indices_buffer
+7
View File
@@ -30,6 +30,13 @@ elif current_platform.is_xpu():
from .xpu.dspark import DSparkDeepseekV4ForCausalLM # type: ignore[assignment]
from .xpu.model import DeepseekV4ForCausalLM # type: ignore[assignment]
from .xpu.mtp import DeepSeekV4MTP # type: ignore[assignment]
elif current_platform.is_cpu():
from .cpu.dspark import DSparkDeepseekV4ForCausalLM # type: ignore[assignment]
from .cpu.model import DeepseekV4ForCausalLM # type: ignore[assignment]
from .cpu.mtp import DeepSeekV4MTP # type: ignore[assignment]
from .vl_stub import ( # type: ignore[assignment]
DeepseekV4ForConditionalGeneration,
)
else:
from .nvidia.dspark import ( # type: ignore[assignment]
DSparkDeepseekV4ForCausalLM,
@@ -678,6 +678,19 @@ def fused_indexer_q_rope_quant(
index_q_fp8,
index_weights_out,
)
elif current_platform.is_cpu():
from vllm._custom_ops import fused_indexer_q_rope_quant_cpu
fused_indexer_q_rope_quant_cpu(
positions.contiguous(),
index_q.to(torch.float32),
index_q_cos_sin_cache.to(torch.float32).contiguous(),
index_q_fp8,
index_weights.to(torch.float32),
index_weights_softmax_scale,
index_weights_head_scale,
index_weights_out,
)
else:
_FUSED_INDEXER_Q_ROPE_QUANT_TRITON_KERNEL(
positions,
+2
View File
@@ -0,0 +1,2 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
@@ -0,0 +1,112 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""CPU DeepSeek-V4 compressor subclass and dispatch: partial-state-cache
write and the compress -> RMSNorm -> RoPE -> FP8 quant -> KV cache store
step, calling ``torch.ops._C.save_partial_states_cpu``/
``compress_norm_rope_store_cpu``/``compress_norm_rope_store_indexer_cpu``
(``csrc/cpu/sgl-kernels/compressor.cpp``) in place of triton-cpu.
Covers both the head_dim=512 main-attention compressor path and the
head_dim=128 indexer compressor path (fp8 only -- MXFP4, ``use_fp4_cache``,
never occurs on CPU: the indexer's MXFP4 cache requires a Blackwell GPU).
"""
from typing import Any, cast
import torch
from vllm._custom_ops import (
compress_norm_rope_store_cpu,
compress_norm_rope_store_indexer_cpu,
save_partial_states_cpu,
)
from vllm.forward_context import get_forward_context
from vllm.models.deepseek_v4.compressor import CompressorMetadata, DeepseekCompressor
from vllm.models.deepseek_v4.cpu.cpu_utils import map_local_to_global_slots_cpu
class DeepseekV4CPUCompressor(DeepseekCompressor):
"""CPU compressor: same state/weights as the shared base, but
``forward``'s cache-write and compress->RMSNorm->RoPE->quant->store
steps always dispatch straight to the ported CPU kernels above instead
of through the shared method's platform-dispatch chain. This class
only ever runs on CPU, and ``use_fp4_cache`` is always ``False`` here
(the indexer's MXFP4 cache requires a Blackwell GPU), so the shared
method's MXFP4/two-stage/cutedsl/triton branches never apply.
"""
_norm_weight_fp32: torch.Tensor
def cache_norm_weight_fp32(self) -> None:
"""Cache a fp32 contiguous copy of ``norm.weight`` once, right after
weight loading (see
``DeepseekV4CPUAttention.process_weights_after_loading``) -- the CPU
kernel requires fp32/contiguous but the checkpoint loads this weight
in bf16, and it never changes after loading."""
self._norm_weight_fp32 = self.norm.weight.to(torch.float32).contiguous()
def forward(
self,
kv_score: torch.Tensor,
positions: torch.Tensor,
rotary_emb,
) -> None:
kv, score = kv_score.split(
[self.coff * self.head_dim, self.coff * self.head_dim], dim=-1
)
attn_metadata = get_forward_context().attn_metadata
if not isinstance(attn_metadata, dict):
return
state_metadata = attn_metadata[self.state_cache.prefix]
assert isinstance(state_metadata, CompressorMetadata)
token_to_req_indices = state_metadata.token_to_req_indices
assert token_to_req_indices is not None
slot_mapping = state_metadata.slot_mapping
num_actual = slot_mapping.shape[0]
block_table = state_metadata.block_table
block_size = state_metadata.block_size
state_cache = self.state_cache.kv_cache
save_partial_states_cpu(
kv, score, self.ape, positions, state_cache, slot_mapping
)
cos_sin_cache = rotary_emb.cos_sin_cache
k_cache_metadata = cast(Any, attn_metadata[self.k_cache_prefix])
k_cache_layer = self._static_forward_context[self.k_cache_prefix]
kv_cache = k_cache_layer.kv_cache
assert self.head_dim in (512, 128), (
f"unsupported compressor head_dim: {self.head_dim}"
)
window = (1 + self.overlap) * self.compress_ratio
win_offsets = torch.arange(window, device=positions.device)
win_local = positions.unsqueeze(-1) - window + 1 + win_offsets
req_idx = token_to_req_indices[:num_actual]
gather_slots = map_local_to_global_slots_cpu(
win_local, req_idx, block_table, block_size
)
kv_cache_2d = kv_cache.view(kv_cache.shape[0], -1)
kv_cache_block_size = kv_cache.shape[1]
store_fn = (
compress_norm_rope_store_cpu
if self.head_dim == 512
else compress_norm_rope_store_indexer_cpu
)
store_fn(
state_cache,
gather_slots,
positions,
k_cache_metadata.slot_mapping,
self._norm_weight_fp32,
self.rms_norm_eps,
cos_sin_cache,
kv_cache_2d,
kv_cache_block_size,
self.compress_ratio,
)
+126
View File
@@ -0,0 +1,126 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""CPU DeepSeek-V4 sparse-MLA backend descriptor.
DeepSeek-V4 attention runs entirely through
``DeepseekV4Attention``/``DeepseekV4CPUAttention``, never through a generic
``AttentionImpl``. ``DeepseekV4CPUSparseBackend`` exists so the CPU attention
layer has its own backend name and its own metadata-builder class: CPU is not
allowed to run triton-cpu inside the model's forward path, so
``DeepseekV4CPUFlashMLAMetadataBuilder`` overrides the shared base's
``_build_c128a_metadata`` (triton-backed in
``DeepseekV4SparseMLAMetadataBuilder``) with a plain-eager-PyTorch
reimplementation of the same per-token block-table-resolution math.
"""
import torch
from vllm.models.deepseek_v4.sparse_mla import (
DeepseekV4SparseMLABackend,
DeepseekV4SparseMLAMetadataBuilder,
)
from vllm.v1.attention.backend import CommonAttentionMetadata
from vllm.v1.attention.backends.mla.indexer import (
DeepseekV4IndexerBackend,
DeepseekV32IndexerMetadataBuilder,
)
from vllm.v1.attention.backends.mla.sparse_swa import (
_LAYER_TYPE_C4A,
_LAYER_TYPE_C128A,
_LAYER_TYPE_SWAONLY,
DeepseekSparseSWAMetadataBuilder,
)
from vllm.v1.attention.ops.flashmla import FlashMLASchedMeta
class DeepseekV4CPUFlashMLAMetadataBuilder(DeepseekV4SparseMLAMetadataBuilder):
"""CPU sparse-MLA metadata builder: same fields as the shared base, but
skips the C128A dense-topk metadata entirely -- unlike CUDA/XPU/ROCm,
``DeepseekV4CPUAttention.forward_mqa`` never reads
``c128a_global_decode_topk_indices``/``c128a_decode_topk_lens``/
``c128a_prefill_topk_indices``; it recomputes the same local top-k
directly from ``positions`` instead, so building it here (whether
eagerly or via the shared base's triton kernel) would be wasted work.
"""
def _build_c128a_metadata(
self,
cm: CommonAttentionMetadata,
req_id_per_token: torch.Tensor,
) -> dict[str, torch.Tensor | None]:
return {}
class DeepseekV4CPUSparseBackend(DeepseekV4SparseMLABackend):
@staticmethod
def get_name() -> str:
return "CPU_V4_MLA_SPARSE"
@staticmethod
def get_builder_cls() -> type[DeepseekV4CPUFlashMLAMetadataBuilder]:
return DeepseekV4CPUFlashMLAMetadataBuilder
class DeepseekV4CPUIndexerMetadataBuilder(DeepseekV32IndexerMetadataBuilder):
"""CPU indexer metadata builder: same fields as the shared base, but
prefill requests are never split into multiple chunks.
``DeepseekV32IndexerMetadataBuilder._split_indexer_prefill_chunks`` (the
shared base's default) bounds two things the CUDA/XPU indexer kernels
need: the flat-gather workspace size and the dense M*N logits tensor
those kernels allocate for a chunk. The CPU indexer
(``sparse_attn_indexer_cpu``) allocates neither -- it reads the paged
K-cache directly via ``fp8_paged_mqa_logits_cpu``/
``topk_transform_512_cpu``, with no chunk-splitting of its own.
With chunked prefill now enabled for this model on CPU (see
``CpuPlatform.check_and_update_config``'s ``amx_mla_or_dsv4_enabled``),
the total query-token count for one step is already bounded by
``max_num_batched_tokens`` -- there is nothing left here to bound, so
this always returns a single chunk spanning the whole step's prefill
batch.
"""
@staticmethod
def _split_indexer_prefill_chunks(
compressed_seq_lens_cpu: torch.Tensor,
prefill_query_lens_cpu: torch.Tensor,
workspace_size: int,
max_logits_bytes: int,
request_offset: int = 0,
) -> list[tuple[slice, slice]]:
# workspace_size/max_logits_bytes are unused: no flat-gather
# workspace or dense M*N buffer is allocated.
num_reqs = compressed_seq_lens_cpu.shape[0]
total_query_len = int(prefill_query_lens_cpu.sum().item())
return [
(
slice(request_offset, request_offset + num_reqs),
slice(0, total_query_len),
)
]
class DeepseekV4CPUIndexerBackend(DeepseekV4IndexerBackend):
@staticmethod
def get_name() -> str:
return "CPU_V4_INDEXER"
@staticmethod
def get_builder_cls() -> type[DeepseekV4CPUIndexerMetadataBuilder]:
return DeepseekV4CPUIndexerMetadataBuilder
class DeepseekV4CPUSparseSWAMetadataBuilder(DeepseekSparseSWAMetadataBuilder):
"""CPU SWA metadata builder: same fields as the shared base."""
def build_tile_scheduler(
self, num_decode_tokens: int
) -> dict[str, FlashMLASchedMeta | None]:
"""CPU never runs the FlashMLA tile-scheduler planner (that's a CUDA
C++ decode-path concern) -- always return the all-``None`` sentinel
the shared base's own CPU branch returns."""
return {
_LAYER_TYPE_SWAONLY: None,
_LAYER_TYPE_C4A: None,
_LAYER_TYPE_C128A: None,
}
+648
View File
@@ -0,0 +1,648 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""CPU DeepSeek-V4 attention subclass.
``forward_mqa`` resolves SWA/compressed top-k indices to paged-cache slot
ids and calls the fused ``flash_mla_with_kvcache_cpu`` kernel. ``_o_proj``
stays eager -- not on the attention hot path.
"""
from typing import Any, cast
import torch
import torch.nn as nn
import torch.nn.functional as F
from vllm import _custom_ops as ops
from vllm.forward_context import get_forward_context
from vllm.models.deepseek_v4.attention import (
DeepseekV4Attention,
DeepseekV4Indexer,
DeepseekV4IndexerCache,
)
from vllm.models.deepseek_v4.cpu.cpu_compressor import DeepseekV4CPUCompressor
from vllm.models.deepseek_v4.cpu.cpu_mla import (
DeepseekV4CPUIndexerBackend,
DeepseekV4CPUSparseBackend,
)
from vllm.models.deepseek_v4.cpu.cpu_utils import map_local_to_global_slots_cpu
from vllm.models.deepseek_v4.sparse_mla import DeepseekV4FlashMLAMetadata
from vllm.platforms import current_platform
from vllm.utils.torch_utils import (
LayerNameType,
_encode_layer_name,
_resolve_layer_name,
direct_register_custom_op,
)
from vllm.v1.attention.backend import AttentionBackend, AttentionMetadata
from vllm.v1.attention.backends.mla.sparse_swa import DeepseekSparseSWAMetadata
_ROPE_DIM = 64
def _deepseek_v4_cpu_prepare_and_attn(
hidden_states: torch.Tensor,
qr: torch.Tensor,
kv: torch.Tensor,
qr_scale: torch.Tensor | None,
kv_score: torch.Tensor | None,
indexer_kv_score: torch.Tensor | None,
indexer_weights: torch.Tensor | None,
positions: torch.Tensor,
o_padded: torch.Tensor,
layer_name: LayerNameType,
) -> torch.Tensor:
"""Opaque custom-op boundary around attention-prep + sparse-indexer +
MLA attention + output projection -- CPU-only.
Wraps cache writes with no explicit tensor args (SWA/compressor/indexer
state), which torch.compile can't otherwise track as mutations -- one
opaque call sidesteps that. ``_o_proj`` is folded in too because CPU's
``DYNAMO_TRACE_ONCE`` mode traces exactly once, during warmup when
``attn_metadata`` is ``None``; tracing ``_o_proj`` separately would bake
that warmup branch into the compiled graph permanently, dead-code-
eliminating the whole attention computation upstream.
"""
layer_name_str = _resolve_layer_name(layer_name)
self = get_forward_context().no_compile_layers[layer_name_str]
self._prepare_and_attn_fn(
hidden_states,
qr,
kv,
qr_scale,
kv_score,
indexer_kv_score,
indexer_weights,
positions,
o_padded,
)
o = o_padded[:, : self.n_local_heads, :]
return self._o_proj(o, positions)
def _deepseek_v4_cpu_prepare_and_attn_fake(
hidden_states: torch.Tensor,
qr: torch.Tensor,
kv: torch.Tensor,
qr_scale: torch.Tensor | None,
kv_score: torch.Tensor | None,
indexer_kv_score: torch.Tensor | None,
indexer_weights: torch.Tensor | None,
positions: torch.Tensor,
o_padded: torch.Tensor,
layer_name: LayerNameType,
) -> torch.Tensor:
# hidden_states' last dim already equals _o_proj's output width, so we
# don't need to resolve layer_name (an opaque object) here.
return hidden_states.new_empty((hidden_states.shape[0], hidden_states.shape[-1]))
direct_register_custom_op(
op_name="deepseek_v4_cpu_prepare_and_attn",
op_func=_deepseek_v4_cpu_prepare_and_attn,
mutates_args=["o_padded"],
fake_impl=_deepseek_v4_cpu_prepare_and_attn_fake,
)
def _dequant_linear_weight(layer: torch.nn.Module) -> torch.Tensor:
"""Dequantize a linear layer's weight, including FP8 block scales.
``_o_proj`` reads ``wo_a.weight`` directly (not via
``quant_method.apply()``), so the per-block FP8 scale must be applied
here explicitly.
"""
weight = layer.weight
scale = getattr(layer, "weight_scale_inv", None)
if scale is None:
scale = getattr(layer, "weight_scale", None)
if scale is None:
return weight.float()
if scale.dtype == torch.float8_e8m0fnu:
from vllm.model_executor.layers.quantization.utils.fp8_utils import (
_upcast_e8m0_to_fp32,
)
scale = _upcast_e8m0_to_fp32(scale)
scale = scale.to(torch.float32)
if scale.numel() == 1:
return weight.float() * scale
block_size = getattr(layer, "weight_block_size", None)
if block_size is None:
# Per-channel scale: one row-scale per output row.
return weight.float() * scale.view(-1, 1)
block_m, block_k = block_size
m, k = weight.shape
scale = scale.repeat_interleave(block_m, dim=0).repeat_interleave(block_k, dim=1)
return weight.float() * scale[:m, :k]
def _fused_indexer_q_rope_quant_cpu(
positions: torch.Tensor,
index_q: torch.Tensor,
index_q_cos_sin_cache: torch.Tensor,
index_weights: torch.Tensor,
index_weights_softmax_scale: float,
index_weights_head_scale: float,
) -> tuple[torch.Tensor, torch.Tensor]:
"""CPU-only equivalent of ``fused_indexer_q_rope_quant``'s FP8 path
(CPU never reaches its MXFP4 arm -- Blackwell-only). Returns
``(q_fp8, weights_out)``, folding the per-token q scale into
``index_weights``. ``positions``/``index_q_cos_sin_cache`` are already
contiguous int64/fp32, so no conversion is needed here.
"""
assert positions.ndim == 1
assert index_q.ndim == 3
assert index_q_cos_sin_cache.ndim == 2
index_weights_out = torch.empty_like(index_weights, dtype=torch.float32)
index_q_fp8 = torch.empty_like(index_q, dtype=current_platform.fp8_dtype())
ops.fused_indexer_q_rope_quant_cpu(
positions,
index_q.to(torch.float32),
index_q_cos_sin_cache,
index_q_fp8,
index_weights.to(torch.float32),
index_weights_softmax_scale,
index_weights_head_scale,
index_weights_out,
)
return index_q_fp8, index_weights_out
class _NoOpEvent:
"""Stand-in for ``torch.cuda.Event`` on CPU: since CPU never sets an aux
stream list, these events are constructed but never actually used."""
class DeepseekV4CPUIndexerCache(DeepseekV4IndexerCache):
"""CPU indexer K-cache descriptor: same fields as the shared base, just
pointing ``get_attn_backend()`` at ``DeepseekV4CPUIndexerBackend``
instead of the shared, CUDA/XPU-oriented ``DeepseekV4IndexerBackend``."""
def get_attn_backend(self) -> type[AttentionBackend]:
return DeepseekV4CPUIndexerBackend
class DeepseekV4CPUIndexer(DeepseekV4Indexer):
"""CPU indexer: the C4A short-context fallback runs as eager PyTorch
instead of Triton. Never constructed directly -- ``__class__`` is
swapped onto an existing ``DeepseekV4Indexer`` instance post-construction.
"""
def forward(
self,
hidden_states: torch.Tensor,
qr: torch.Tensor,
compressed_kv_score: torch.Tensor,
indexer_weights: torch.Tensor,
positions: torch.Tensor,
rotary_emb: nn.Module,
qr_scale: torch.Tensor | None = None,
) -> tuple[torch.Tensor | None, torch.Tensor | None, torch.Tensor | None]:
"""CPU override: no aux streams, so wq_b_and_q_quant and the
compressor run straight-line instead of through
``maybe_execute_in_parallel``; the short-context check drops the
CUDA-only ``is_current_stream_capturing()`` guard (always False
here)."""
compressor = self.compressor
attn_metadata = get_forward_context().attn_metadata
if isinstance(attn_metadata, dict):
indexer_metadata = cast(Any, attn_metadata[self.k_cache.prefix])
if indexer_metadata.max_seq_len // self.compress_ratio <= self.topk_tokens:
# Fewer candidates than topk: all are selected, but the K
# cache still needs to be built.
compressor(compressed_kv_score, positions, rotary_emb)
assert self.topk_indices_buffer is not None
num_tokens = (
indexer_metadata.num_decode_tokens
+ indexer_metadata.num_prefill_tokens
)
if num_tokens > 0:
self._fill_short_context_topk(positions, num_tokens)
return None, None, None
def wq_b_and_q_quant():
q = self._wq_b_proj(qr, qr_scale)
q = q.view(-1, self.n_head, self.head_dim)
return _fused_indexer_q_rope_quant_cpu(
positions,
q,
rotary_emb.cos_sin_cache,
indexer_weights,
self.softmax_scale,
self.n_head**-0.5,
)
# Order matches the base class's parallel-join contract: compressor
# must complete before indexer_op runs (skip_k_cache_insert=True).
q, weights = wq_b_and_q_quant()
compressor(compressed_kv_score, positions, rotary_emb)
# No q_scale: FP8-only path (MXFP4 needs Blackwell).
return q, None, weights
def _fill_short_context_topk(
self, positions: torch.Tensor, num_tokens: int
) -> None:
assert self.topk_indices_buffer is not None
device = positions.device
arange = torch.arange(self.topk_tokens, device=device)
num_compressed = torch.div(
positions[:num_tokens] + 1, self.compress_ratio, rounding_mode="floor"
)
valid = arange.unsqueeze(0) < num_compressed.unsqueeze(-1)
filled = torch.where(
valid, arange.unsqueeze(0), torch.full_like(arange.unsqueeze(0), -1)
)
self.topk_indices_buffer[:num_tokens, : self.topk_tokens] = filled.to(
self.topk_indices_buffer.dtype
)
class DeepseekV4CPUAttention(DeepseekV4Attention):
"""CPU sparse MLA attention layer for DeepSeek V4."""
backend_cls = DeepseekV4CPUSparseBackend
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
# Swap classes post-construction (no class-swap hook on the shared
# base) so forward()/get_attn_backend() dispatch to CPU kernels.
# SWA-only layers (compress_ratio <= 1) never build a
# compressor/indexer.
if self.compressor is not None:
self.compressor.__class__ = DeepseekV4CPUCompressor
if self.indexer is not None:
self.indexer.__class__ = DeepseekV4CPUIndexer
self.indexer.k_cache.__class__ = DeepseekV4CPUIndexerCache
self.indexer.compressor.__class__ = DeepseekV4CPUCompressor
self._wo_a_packed: torch.Tensor | None = None
self._wrap_wo_a_process_weights_after_loading()
def process_weights_after_loading(self, act_dtype: torch.dtype) -> None:
"""Cache fp32-contiguous copies of tensors CPU kernels want that way
but that arrive bf16 (rotary cos/sin table, compressor RMSNorm
weights) -- cast once here instead of per forward call.
Runs after every quantized layer's own
``process_weights_after_loading`` (see ``is_deferred_attention_layer``);
``wo_a``'s packing must happen *before* that phase instead, so it's a
separate monkeypatch in ``__init__``.
"""
self.rotary_emb.cos_sin_cache = self.rotary_emb.cos_sin_cache.to(
torch.float32
).contiguous()
if self.compressor is not None:
self.compressor.cache_norm_weight_fp32()
if self.indexer is not None:
self.indexer.compressor.cache_norm_weight_fp32()
def _wrap_wo_a_process_weights_after_loading(self) -> None:
"""Snapshot and pack ``wo_a``'s weight into a bf16 copy for
``bmm_cpu`` before the FP8 kernel's own
``process_weights_after_loading`` VNNI-repacks it in place for
row-major reads ``_o_proj`` never does."""
wo_a = self.wo_a
quant_method = wo_a.quant_method
orig_pwal = quant_method.process_weights_after_loading
heads_per_group = self.n_local_heads // self.n_local_groups
k_dim = heads_per_group * self.head_dim
def _capture_and_pack(layer: torch.nn.Module) -> None:
dequant = _dequant_linear_weight(layer).to(torch.bfloat16)
dequant = dequant.view(self.n_local_groups, self.o_lora_rank, k_dim)
self._wo_a_packed = torch.ops._C.convert_weight_packed(dequant.contiguous())
orig_pwal(layer)
# orig_pwal VNNI-repacks layer.weight/scale for ordinary-linear
# use that _o_proj never needs -- free them, same pattern as
# dispatch_cpu_unquantized_gemm's remove_weight=True.
layer.weight = torch.nn.Parameter(torch.empty(0), requires_grad=False)
scale_attr = (
"weight_scale_inv"
if hasattr(layer, "weight_scale_inv")
else "weight_scale"
)
if hasattr(layer, scale_attr):
setattr(
layer,
scale_attr,
torch.nn.Parameter(torch.empty(0), requires_grad=False),
)
quant_method.process_weights_after_loading = ( # type: ignore[method-assign]
_capture_and_pack
)
def forward(
self,
positions: torch.Tensor,
hidden_states: torch.Tensor,
llama_4_scaling: torch.Tensor | None = None,
) -> torch.Tensor:
"""CPU override: wraps attention-prep + MLA + output projection in the
CPU-only opaque custom op (see ``_deepseek_v4_cpu_prepare_and_attn``).
"""
num_tokens = hidden_states.shape[0]
o_padded = torch.empty(
(num_tokens, self.padded_heads, self.head_dim),
dtype=hidden_states.dtype,
device=hidden_states.device,
)
qr_kv = self._fused_wqa_wkv_gemm(hidden_states)
kv_score: torch.Tensor | None = None
if self.compressor is not None:
# Must go through the module's own forward (not a raw matmul on
# its weight): the packed-GEMM kernel frees the raw weight after
# packing, same as wo_a's.
kv_score = self.compressor.fused_wkv_wgate(hidden_states).to(torch.float32)
indexer_weights: torch.Tensor | None = None
indexer_kv_score: torch.Tensor | None = None
if self.indexer is not None:
indexer_weights, _ = self.indexer.weights_proj(hidden_states)
indexer_kv_score = self.indexer.compressor.fused_wkv_wgate(
hidden_states
).to(torch.float32)
qr, qr_scale, kv = self._split_qkv_and_norm(qr_kv)
return torch.ops.vllm.deepseek_v4_cpu_prepare_and_attn(
hidden_states,
qr,
kv,
qr_scale,
kv_score,
indexer_kv_score,
indexer_weights,
positions,
o_padded,
_encode_layer_name(self.prefix),
)
def _fused_qnorm_rope_kv_insert(
self,
q: torch.Tensor,
kv: torch.Tensor,
positions: torch.Tensor,
attn_metadata: (
dict[str, AttentionMetadata] | list[dict[str, AttentionMetadata]] | None
),
) -> torch.Tensor:
"""CPU override: only the fp8_ds_mla (uint8) SWA cache layout is
supported here, so the base method's bf16/per-tensor-fp8 branches
are dropped."""
if not isinstance(attn_metadata, dict):
# Profile run: kernel doesn't fire; produce a padded tensor so
# downstream FlashMLA gets the right shape.
if self.n_local_heads < self.padded_heads:
return F.pad(
q,
(0, 0, 0, self.padded_heads - self.n_local_heads),
value=0.0,
)
return q
swa_metadata = cast(
"DeepseekSparseSWAMetadata | None",
attn_metadata.get(self.swa_cache_layer.prefix),
)
assert swa_metadata is not None
swa_kv_cache = self.swa_cache_layer.kv_cache
# positions is already int64 (the runner's buffer), no cast needed.
assert positions.dtype == torch.int64
assert swa_kv_cache.dtype == torch.uint8, (
"DeepseekV4CPUAttention only supports the fp8_ds_mla cache layout"
)
# Fused: Q side does per-head weight-free RMSNorm + GPT-J RoPE
# (zero-filling padded head slots); KV side does GPT-J RoPE + UE8M0
# FP8 quant + paged insert.
swa_kv_cache_2d = swa_kv_cache.view(swa_kv_cache.shape[0], -1)
return ops.fused_qnorm_rope_kv_insert_cpu(
q,
kv,
positions,
swa_kv_cache_2d,
swa_metadata.slot_mapping,
self.rotary_emb.cos_sin_cache,
self.padded_heads,
self.eps,
swa_metadata.block_size,
)
def _split_qkv_and_norm(
self, qr_kv: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor | None, torch.Tensor]:
"""CPU override: two ``RMSNorm`` calls instead of the shared
``fused_q_kv_rmsnorm``, whose raw ``@triton.jit`` kernel fails to
link under triton-cpu (``undefined symbol: __truncdfbf2``)."""
qr, kv = qr_kv.split([self.q_lora_rank, self.head_dim], dim=-1)
return self.q_norm(qr), None, self.kv_norm(kv)
def _prepare_and_attn(
self,
hidden_states: torch.Tensor,
qr: torch.Tensor,
kv: torch.Tensor,
qr_scale: torch.Tensor | None,
kv_score: torch.Tensor,
indexer_kv_score: torch.Tensor,
indexer_weights: torch.Tensor,
positions: torch.Tensor,
o_padded: torch.Tensor,
) -> None:
"""CPU override: no aux streams, so query-projection+KV-insert, the
indexer, and the compressor run straight-line instead of through
execute_in_parallel/maybe_execute_in_parallel."""
attn_metadata = get_forward_context().attn_metadata
indexer = self.indexer
compressor = self.compressor
q = self._wq_b_proj(qr, qr_scale).view(-1, self.n_local_heads, self.head_dim)
q = self._fused_qnorm_rope_kv_insert(q, kv, positions, attn_metadata)
index_q: torch.Tensor | None = None
index_q_scale: torch.Tensor | None = None
index_weights_out: torch.Tensor | None = None
if indexer is not None:
assert compressor is not None
index_q, index_q_scale, index_weights_out = indexer(
hidden_states,
qr,
indexer_kv_score,
indexer_weights,
positions,
self.indexer_rotary_emb,
qr_scale,
)
compressor(kv_score, positions, self.rotary_emb)
elif compressor is not None:
compressor(kv_score, positions, self.rotary_emb)
self._sparse_indexer_and_attn(
hidden_states,
index_q,
index_q_scale,
index_weights_out,
q,
kv,
positions,
o_padded,
)
def _sparse_indexer_and_attn(
self,
hidden_states: torch.Tensor,
index_q: torch.Tensor | None,
index_q_scale: torch.Tensor | None,
index_weights: torch.Tensor | None,
q: torch.Tensor,
kv: torch.Tensor,
positions: torch.Tensor,
out: torch.Tensor,
) -> None:
"""CPU override: identical body, minus ``@eager_break_during_capture``
(this platform never captures a CUDA graph, so it was a no-op)."""
if self.indexer is not None and index_q is not None:
assert index_weights is not None
# index_q_scale is always None on CPU (FP8-only path).
assert index_q_scale is None
self.indexer.indexer_op(hidden_states, index_q, None, index_weights)
self.forward_mqa(q, kv, positions, out)
@classmethod
def get_padded_num_q_heads(cls, num_heads: int) -> int:
# No head-count padding constraint for the (not yet ported) CPU kernel.
return num_heads
def _o_proj(self, o: torch.Tensor, positions: torch.Tensor) -> torch.Tensor:
if get_forward_context().attn_metadata is None:
# Warmup/profile run: no real metadata, o is a zeroed placeholder.
return torch.zeros(
(o.shape[0], self.hidden_size), dtype=o.dtype, device=o.device
)
num_tokens, num_heads, _ = o.shape
cos_sin_cache = self.rotary_emb.cos_sin_cache
# Undo the query's own GPT-J RoPE rotation: the attention output is
# a weighted sum of KV rows at different positions, so R(-pos_q)
# recovers the translation-invariant quantity wo_a/wo_b expect.
o_derot = ops.inverse_gptj_rope_o_proj_cpu(
o, positions, cos_sin_cache, _ROPE_DIM
)
heads_per_group = num_heads // self.n_local_groups
o_grouped = o_derot.reshape(
num_tokens, self.n_local_groups, heads_per_group * self.head_dim
).to(torch.bfloat16)
assert self._wo_a_packed is not None
z = o_grouped.new_empty((self.n_local_groups, num_tokens, self.o_lora_rank))
ops.bmm_cpu(
z,
o_grouped.transpose(0, 1).contiguous(),
self._wo_a_packed,
True,
None,
)
z = z.transpose(0, 1).to(o.dtype)
return self.wo_b(z.flatten(1))
def forward_mqa(
self,
q: torch.Tensor,
kv: torch.Tensor,
positions: torch.Tensor,
output: torch.Tensor,
) -> None:
forward_context = get_forward_context()
attn_metadata = forward_context.attn_metadata
if attn_metadata is None:
# Warmup/profile run: reserve nothing extra, skip real kernels.
output.zero_()
return
assert isinstance(attn_metadata, dict)
swa_metadata = cast(
DeepseekSparseSWAMetadata,
attn_metadata.get(self.swa_cache_layer.prefix),
)
assert swa_metadata is not None
assert swa_metadata.token_to_req_indices is not None
req_idx = swa_metadata.token_to_req_indices
swa_only = self.compress_ratio <= 1
flashmla_metadata = cast(
DeepseekV4FlashMLAMetadata | None, attn_metadata.get(self.prefix)
)
num_tokens = q.shape[0]
device = q.device
# ---- SWA window: causal sliding window over the raw per-token cache
window = self.window_size
win_offsets = torch.arange(window, device=device)
start_pos = (positions - window + 1).clamp(min=0)
local_pos = start_pos.unsqueeze(-1) + win_offsets
valid_win = local_pos <= positions.unsqueeze(-1)
win_local = torch.where(valid_win, local_pos, torch.full_like(local_pos, -1))
window_slots = map_local_to_global_slots_cpu(
win_local, req_idx, swa_metadata.block_table, swa_metadata.block_size
)
window_cache_2d = self.swa_cache_layer.kv_cache.view(
self.swa_cache_layer.kv_cache.shape[0], -1
)
# ---- Compressed KV: C4A's learned top-k, or C128A's dense top-k ----
if swa_only:
compressed_slots = window_slots.new_full((num_tokens, 0), -1)
# Unused when num_compressed == 0 (only dtype/2D-ness matter);
# reuse the window cache to avoid an allocation.
compressed_cache_2d = window_cache_2d
compressed_block_size = 1
else:
assert flashmla_metadata is not None
main_block_size = flashmla_metadata.block_size // self.compress_ratio
if self.compress_ratio == 4:
assert self.topk_indices_buffer is not None
local_topk = self.topk_indices_buffer[:num_tokens]
else:
width = -(-self.max_model_len // self.compress_ratio)
num_compressed = torch.div(
positions + 1, self.compress_ratio, rounding_mode="floor"
).clamp(max=width)
arange_w = torch.arange(width, device=device)
local_topk = torch.where(
arange_w.unsqueeze(0) < num_compressed.unsqueeze(-1),
arange_w.unsqueeze(0).expand(num_tokens, width),
torch.full(
(num_tokens, width), -1, device=device, dtype=torch.int64
),
)
compressed_slots = map_local_to_global_slots_cpu(
local_topk, req_idx, flashmla_metadata.block_table, main_block_size
)
compressed_cache_2d = self.kv_cache.view(self.kv_cache.shape[0], -1)
compressed_block_size = main_block_size
torch.ops._C.flash_mla_with_kvcache_cpu(
output,
q,
window_cache_2d,
window_slots,
swa_metadata.block_size,
compressed_cache_2d,
compressed_slots,
compressed_block_size,
self.attn_sink,
self.scale,
)
+34
View File
@@ -0,0 +1,34 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Shared helpers for DeepSeek-V4's CPU-ported kernels."""
import torch
def map_local_to_global_slots_cpu(
local_indices: torch.Tensor,
req_idx: torch.Tensor,
block_table: torch.Tensor,
block_size: int,
) -> torch.Tensor:
"""Map per-request-local (token or compressed-token) indices to global
paged-cache slot ids via a block table, mirroring
``compute_global_topk_indices_and_lens``.
Args:
local_indices: [N, K], -1 sentinel for invalid entries.
req_idx: [N], row into ``block_table`` for each of the N rows.
block_table: [num_reqs, max_blocks_per_seq].
block_size: tokens (or compressed tokens) per physical block.
Returns:
[N, K] int64 global slot ids, -1 where ``local_indices`` was invalid.
"""
valid = local_indices >= 0
safe_local = local_indices.clamp(min=0).to(torch.int64)
block_pos = torch.div(safe_local, block_size, rounding_mode="floor")
offset = safe_local % block_size
req_expand = req_idx.to(torch.int64).unsqueeze(-1).expand_as(local_indices)
block_num = block_table[req_expand, block_pos].to(torch.int64)
slot = block_num * block_size + offset
return torch.where(valid, slot, torch.full_like(slot, -1))
+18
View File
@@ -0,0 +1,18 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""CPU DeepSeek-V4 DSpark (speculative decoding) — deferred, not implemented.
``DSparkDeepseekV4ForCausalLM`` is only instantiated when the speculative-
decoding registry resolves it by name for a DSpark speculative config; a
plain (non-spec) DeepSeek-V4 CPU model never constructs this class. This
stub exists solely so ``vllm.models.deepseek_v4.cpu`` is import-clean.
"""
from vllm.config import VllmConfig
class DSparkDeepseekV4ForCausalLM:
def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None:
raise NotImplementedError(
"DeepSeek-V4 speculative decoding (DSpark) is not implemented on CPU."
)
+922
View File
@@ -0,0 +1,922 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import typing
from collections.abc import Callable, Iterable
from itertools import islice
import regex as re
import torch
import torch.nn as nn
from vllm.compilation.decorators import support_torch_compile
from vllm.config import VllmConfig
from vllm.distributed import (
get_pp_group,
get_tensor_model_parallel_rank,
get_tensor_model_parallel_world_size,
)
from vllm.model_executor.layers.activation import SiluAndMul, SiluAndMulWithClamp
from vllm.model_executor.layers.fused_moe import (
FusedMoEFactory,
GateLinear,
fused_moe_make_expert_params_mapping,
)
from vllm.model_executor.layers.fused_moe.utils import (
is_model_fused_shared_expert_compatible,
)
from vllm.model_executor.layers.layernorm import RMSNorm
from vllm.model_executor.layers.linear import (
MergedColumnParallelLinear,
RowParallelLinear,
)
from vllm.model_executor.layers.logits_processor import LogitsProcessor
from vllm.model_executor.layers.mhc import (
HAS_AITER_MHC,
HAS_TILELANG_MHC,
HCHeadOp,
MHCFusedPostPreOp,
MHCPostOp,
MHCPreOp,
)
from vllm.model_executor.layers.quantization import QuantizationConfig
from vllm.model_executor.layers.vocab_parallel_embedding import (
ParallelLMHead,
VocabParallelEmbedding,
)
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
from vllm.model_executor.models.interfaces import (
EagleModelMixin,
SupportsEagle3,
SupportsPP,
)
from vllm.model_executor.models.utils import (
AutoWeightsLoader,
PPMissingLayer,
WeightsMapper,
extract_layer_index,
is_pp_missing_parameter,
make_layers,
maybe_prefix,
)
from vllm.models.deepseek_v4.cpu.cpu_sparse import DeepseekV4CPUAttention
from vllm.platforms import current_platform
from vllm.sequence import IntermediateTensors
class DeepseekV4MLP(nn.Module):
def __init__(
self,
hidden_size: int,
intermediate_size: int,
hidden_act: str,
swiglu_limit: float | None = None,
quant_config: QuantizationConfig | None = None,
reduce_results: bool = True,
is_sequence_parallel: bool = False,
prefix: str = "",
) -> None:
super().__init__()
# is_sequence_parallel: weights are replicated, no collective ops
# needed. Otherwise: standard TP with an allreduce at the end.
self.gate_up_proj = MergedColumnParallelLinear(
hidden_size,
[intermediate_size] * 2,
bias=False,
quant_config=quant_config,
disable_tp=is_sequence_parallel,
prefix=f"{prefix}.gate_up_proj",
)
self.down_proj = RowParallelLinear(
intermediate_size,
hidden_size,
bias=False,
quant_config=quant_config,
reduce_results=reduce_results,
disable_tp=is_sequence_parallel,
prefix=f"{prefix}.down_proj",
)
if hidden_act != "silu":
raise ValueError(
f"Unsupported activation: {hidden_act}. Only silu is supported for now."
)
if swiglu_limit is not None:
self.act_fn = SiluAndMulWithClamp(swiglu_limit)
else:
self.act_fn = SiluAndMul()
def forward(self, x):
gate_up, _ = self.gate_up_proj(x)
x = self.act_fn(gate_up)
x, _ = self.down_proj(x)
return x
class DeepseekV4MoE(nn.Module):
def __init__(
self,
vllm_config: VllmConfig,
prefix: str = "",
):
super().__init__()
self.tp_size = get_tensor_model_parallel_world_size()
config = vllm_config.model_config.hf_config
quant_config = vllm_config.quant_config
self.prefix = prefix
self.routed_scaling_factor = getattr(config, "routed_scaling_factor", 1.0)
self.hidden_size = config.hidden_size
self.n_routed_experts = config.n_routed_experts
self.n_activated_experts = config.num_experts_per_tok
self.moe_intermediate_size = config.moe_intermediate_size
self.swiglu_limit = config.swiglu_limit
self.renormalize = config.norm_topk_prob
self.scoring_func = getattr(config, "scoring_func", "sqrtsoftplus")
self.gate = GateLinear(
input_size=config.hidden_size,
output_size=config.n_routed_experts,
bias=False,
out_dtype=torch.float32,
prefix=f"{prefix}.gate",
)
self.gate.e_score_correction_bias = None
self.gate.tid2eid = None
is_hash_moe = extract_layer_index(prefix) < config.num_hash_layers
self.hash_indices_dtype = torch.int32
if is_hash_moe:
# hash MoE doesn't use e_score_correction_bias
# Use randint instead of empty to avoid garbage values causing
# invalid memory access in dummy mode (--load-format="dummy")
self.gate.tid2eid = nn.Parameter(
torch.randint(
0,
config.n_routed_experts,
(config.vocab_size, config.num_experts_per_tok),
dtype=self.hash_indices_dtype,
),
requires_grad=False,
)
elif getattr(config, "topk_method", None) == "noaux_tc":
self.gate.e_score_correction_bias = nn.Parameter(
torch.empty(config.n_routed_experts, dtype=torch.float32),
requires_grad=False,
)
self.n_shared_experts = config.n_shared_experts
# No CPU fused-shared-expert grouped-GEMM path yet.
self.is_fused_shared_expert_enabled = False
if config.n_shared_experts is None or self.is_fused_shared_expert_enabled:
self.shared_experts = None
else:
intermediate_size = config.moe_intermediate_size * config.n_shared_experts
self.shared_experts = DeepseekV4MLP(
hidden_size=config.hidden_size,
intermediate_size=intermediate_size,
hidden_act=config.hidden_act,
swiglu_limit=self.swiglu_limit,
quant_config=quant_config,
reduce_results=False,
prefix=f"{prefix}.shared_experts",
)
self.tp_rank = get_tensor_model_parallel_rank()
assert config.n_routed_experts % self.tp_size == 0
self.n_local_experts = config.n_routed_experts // self.tp_size
self.experts_start_idx = self.tp_rank * self.n_local_experts
self.experts_end_idx = self.experts_start_idx + self.n_local_experts
self.experts = FusedMoEFactory(
shared_experts=self.shared_experts,
n_shared_experts=(
config.n_shared_experts if self.is_fused_shared_expert_enabled else None
),
fuse_shared_experts=self.is_fused_shared_expert_enabled,
gate=self.gate,
num_experts=config.n_routed_experts,
top_k=config.num_experts_per_tok,
hidden_size=config.hidden_size,
intermediate_size=config.moe_intermediate_size,
renormalize=config.norm_topk_prob,
quant_config=quant_config,
prefix=f"{prefix}.experts",
scoring_func=self.scoring_func,
routed_scaling_factor=self.routed_scaling_factor,
e_score_correction_bias=self.gate.e_score_correction_bias,
hash_indices_table=self.gate.tid2eid,
swiglu_limit=self.swiglu_limit,
router_logits_dtype=torch.float32,
)
if is_hash_moe:
# apply_monolithic() never sees hash_indices_table via the
# router path (modular-only) -- stash it on RoutedExperts
# directly. object.__setattr__ avoids nn.Module re-registering
# (and duplicating in the state_dict) this alias.
object.__setattr__(
self.experts.routed_experts, "hash_indices_table", self.gate.tid2eid
)
def forward(
self, hidden_states: torch.Tensor, input_ids: torch.Tensor | None = None
) -> torch.Tensor:
if self.gate.tid2eid is not None and input_ids is None:
raise ValueError("DeepSeek V4 hash MoE routing requires input_ids.")
org_shape = hidden_states.shape
final_hidden_states = self.experts(
hidden_states=hidden_states,
router_logits=hidden_states,
input_ids=input_ids,
)
return final_hidden_states.view(org_shape)
class DeepseekV4DecoderLayer(nn.Module):
def __init__(
self,
vllm_config,
prefix,
topk_indices_buffer: torch.Tensor | None = None,
):
super().__init__()
# Lazy import to avoid top-level tilelang dependency.
# Registers both torch.ops.vllm.mhc_pre and mhc_post
import vllm.model_executor.layers.mhc # noqa: F401
config = vllm_config.model_config.hf_config
self.hidden_size = config.hidden_size
self.rms_norm_eps = config.rms_norm_eps
self.attn = DeepseekV4CPUAttention(
vllm_config,
prefix=f"{prefix}.attn",
topk_indices_buffer=topk_indices_buffer,
)
self.ffn = DeepseekV4MoE(vllm_config, prefix=f"{prefix}.ffn")
self.attn_norm = RMSNorm(self.hidden_size, self.rms_norm_eps)
self.ffn_norm = RMSNorm(self.hidden_size, self.rms_norm_eps)
self.hc_mult = config.hc_mult
self.hc_sinkhorn_iters = config.hc_sinkhorn_iters
self.hc_eps = config.hc_eps
self.hc_post_alpha = 2.0
mix_hc = (2 + self.hc_mult) * self.hc_mult
hc_dim = self.hc_mult * self.hidden_size
self.hc_attn_fn = nn.Parameter(
torch.empty(
(mix_hc, hc_dim),
dtype=torch.float32,
),
requires_grad=False,
)
self.hc_ffn_fn = nn.Parameter(
torch.empty(
(mix_hc, hc_dim),
dtype=torch.float32,
),
requires_grad=False,
)
self.hc_attn_base = nn.Parameter(
torch.empty(
mix_hc,
dtype=torch.float32,
),
requires_grad=False,
)
self.hc_ffn_base = nn.Parameter(
torch.empty(
mix_hc,
dtype=torch.float32,
),
requires_grad=False,
)
self.hc_attn_scale = nn.Parameter(
torch.empty(
3,
dtype=torch.float32,
),
requires_grad=False,
)
self.hc_ffn_scale = nn.Parameter(
torch.empty(
3,
dtype=torch.float32,
),
requires_grad=False,
)
self.mhc_pre = MHCPreOp()
self.mhc_post = MHCPostOp()
self.mhc_fused_post_pre = MHCFusedPostPreOp()
self.use_fused_mhc = HAS_TILELANG_MHC and not (
HAS_AITER_MHC and self.hidden_size % 256 == 0
)
def hc_pre(
self,
x: torch.Tensor,
hc_fn: torch.Tensor,
hc_scale: torch.Tensor,
hc_base: torch.Tensor,
):
post_mix, res_mix, layer_input = self.mhc_pre(
residual=x,
fn=hc_fn,
hc_scale=hc_scale,
hc_base=hc_base,
rms_eps=self.rms_norm_eps,
hc_pre_eps=self.hc_eps,
hc_sinkhorn_eps=self.hc_eps,
hc_post_mult_value=self.hc_post_alpha,
sinkhorn_repeat=self.hc_sinkhorn_iters,
)
return layer_input, post_mix, res_mix
def hc_post(
self,
x: torch.Tensor,
residual: torch.Tensor,
post: torch.Tensor,
comb: torch.Tensor,
):
return self.mhc_post(x, residual, post, comb)
def _forward_fused_post_pre(
self,
x: torch.Tensor,
positions: torch.Tensor,
input_ids: torch.Tensor | None,
post_mix: torch.Tensor | None = None,
res_mix: torch.Tensor | None = None,
residual: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
if residual is None:
# Run standalone hc_pre on first layer
residual = x
x, post_mix, res_mix = self.hc_pre(
x, self.hc_attn_fn, self.hc_attn_scale, self.hc_attn_base
)
else:
residual, post_mix, res_mix, x = self.mhc_fused_post_pre(
x,
residual,
post_mix,
res_mix,
self.hc_attn_fn,
self.hc_attn_scale,
self.hc_attn_base,
self.rms_norm_eps,
self.hc_eps,
self.hc_eps,
self.hc_post_alpha,
self.hc_sinkhorn_iters,
)
x = self.attn_norm(x)
x = self.attn(positions, x, None)
residual, post_mix, res_mix, x = self.mhc_fused_post_pre(
x,
residual,
post_mix,
res_mix,
self.hc_ffn_fn,
self.hc_ffn_scale,
self.hc_ffn_base,
self.rms_norm_eps,
self.hc_eps,
self.hc_eps,
self.hc_post_alpha,
self.hc_sinkhorn_iters,
)
x = self.ffn_norm(x)
x = self.ffn(x, input_ids)
return x, residual, post_mix, res_mix
def _forward_unfused_post_pre(
self,
x: torch.Tensor,
positions: torch.Tensor,
input_ids: torch.Tensor | None,
post_mix: torch.Tensor | None = None,
res_mix: torch.Tensor | None = None,
residual: torch.Tensor | None = None,
) -> tuple[
torch.Tensor, torch.Tensor | None, torch.Tensor | None, torch.Tensor | None
]:
residual = x
x, post, comb = self.hc_pre(
x, self.hc_attn_fn, self.hc_attn_scale, self.hc_attn_base
)
x = self.attn_norm(x)
x = self.attn(positions, x, None)
x = self.hc_post(x, residual, post, comb)
residual = x
x, post, comb = self.hc_pre(
x, self.hc_ffn_fn, self.hc_ffn_scale, self.hc_ffn_base
)
x = self.ffn_norm(x)
x = self.ffn(x, input_ids)
x = self.hc_post(x, residual, post, comb)
return x, None, None, None
def forward(
self,
x: torch.Tensor,
positions: torch.Tensor,
input_ids: torch.Tensor | None,
post_mix: torch.Tensor | None = None,
res_mix: torch.Tensor | None = None,
residual: torch.Tensor | None = None,
) -> tuple[
torch.Tensor, torch.Tensor | None, torch.Tensor | None, torch.Tensor | None
]:
if not self.use_fused_mhc:
return self._forward_unfused_post_pre(
x, positions, input_ids, post_mix, res_mix, residual
)
return self._forward_fused_post_pre(
x, positions, input_ids, post_mix, res_mix, residual
)
@support_torch_compile(
dynamic_arg_dims={
"input_ids": 0,
"positions": -1,
"intermediate_tensors": 0,
"inputs_embeds": 0,
}
)
class DeepseekV4Model(nn.Module, EagleModelMixin):
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
super().__init__()
config = vllm_config.model_config.hf_config
quant_config = vllm_config.quant_config
self.config = config
self.vocab_size = config.vocab_size
self.hc_eps = config.hc_eps
self.hc_mult = config.hc_mult
self.hc_dim = self.hc_mult * config.hidden_size
self.rms_norm_eps = config.rms_norm_eps
self.device = current_platform.device_type
# Reserved topk indices buffer for all Indexer layers to reuse.
self.topk_indices_buffer = torch.empty(
vllm_config.scheduler_config.max_num_batched_tokens,
config.index_topk,
dtype=torch.int32,
device=self.device,
)
if get_pp_group().is_first_rank:
self.embed_tokens = VocabParallelEmbedding(
config.vocab_size,
config.hidden_size,
quant_config=quant_config,
prefix=f"{prefix}.embed_tokens",
)
else:
self.embed_tokens = PPMissingLayer()
self.start_layer, self.end_layer, self.layers = make_layers(
config.num_hidden_layers,
lambda prefix: DeepseekV4DecoderLayer(
vllm_config,
prefix=prefix,
topk_indices_buffer=self.topk_indices_buffer,
),
prefix=f"{prefix}.layers",
)
self.is_fused_shared_expert_enabled = is_model_fused_shared_expert_compatible(
self.layers,
DeepseekV4MoE,
"ffn",
)
if get_pp_group().is_last_rank:
self.norm = RMSNorm(config.hidden_size, self.rms_norm_eps)
else:
self.norm = PPMissingLayer()
self.hc_head_fn = nn.Parameter(
torch.empty(
self.hc_mult,
self.hc_dim,
dtype=torch.float32,
),
requires_grad=False,
)
self.hc_head_base = nn.Parameter(
torch.empty(
self.hc_mult,
dtype=torch.float32,
),
requires_grad=False,
)
self.hc_head_scale = nn.Parameter(
torch.empty(1, dtype=torch.float32),
requires_grad=False,
)
self.hc_head_op = HCHeadOp()
spec_config = vllm_config.speculative_config
needs_mtp_hidden_states = spec_config is not None and (
spec_config.use_eagle() or spec_config.uses_draft_model()
)
if get_pp_group().is_last_rank and needs_mtp_hidden_states:
self._mtp_hidden_buffer = torch.empty(
vllm_config.scheduler_config.max_num_batched_tokens,
self.hc_dim,
dtype=vllm_config.model_config.dtype,
device=self.device,
)
else:
self._mtp_hidden_buffer = None
def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
return self.embed_tokens(input_ids)
def make_empty_intermediate_tensors(
self,
batch_size: int,
dtype: torch.dtype,
device: torch.device,
) -> IntermediateTensors:
# PP intermediate tensors keep the (num_tokens, hc_mult, hidden_size)
# multi-stream shape until hc_head() collapses it.
return IntermediateTensors(
{
"hidden_states": torch.zeros(
(batch_size, self.hc_mult, self.config.hidden_size),
dtype=dtype,
device=device,
),
}
)
def forward(
self,
input_ids: torch.Tensor,
positions: torch.Tensor,
intermediate_tensors: IntermediateTensors | None,
inputs_embeds: torch.Tensor | None = None,
) -> torch.Tensor | IntermediateTensors:
if get_pp_group().is_first_rank:
if inputs_embeds is not None:
hidden_states = inputs_embeds
else:
hidden_states = self.embed_input_ids(input_ids)
hidden_states = hidden_states.unsqueeze(-2).repeat(1, self.hc_mult, 1)
else:
assert intermediate_tensors is not None
hidden_states = intermediate_tensors["hidden_states"]
residual, post_mix, res_mix = None, None, None
# EAGLE3/DSpark/DFlash aux hidden states: post-mhc hidden state at
# each target layer, averaged over hc_mult streams to [T,
# hidden_size]. Empty unless a draft model set aux_hidden_state_layers.
aux_hidden_states: list[torch.Tensor] = []
# Reused below to avoid computing hc_post twice if the last layer is
# also an aux layer.
final_aux_recon: torch.Tensor | None = None
for idx, layer in enumerate(
islice(self.layers, self.start_layer, self.end_layer),
start=self.start_layer,
):
hidden_states, residual, post_mix, res_mix = layer(
hidden_states,
positions,
input_ids,
post_mix,
res_mix,
residual,
)
if (idx + 1) in self.aux_hidden_state_layers:
# Unfused path already applied hc_post; fused path needs it
# applied here before averaging.
if layer.use_fused_mhc:
aux_recon = layer.hc_post(
hidden_states, residual, post_mix, res_mix
)
final_aux_recon = aux_recon
else:
aux_recon = hidden_states
aux_hidden_states.append(aux_recon.mean(dim=1))
if layer is not None and layer.use_fused_mhc:
# Reuse the last layer's hc_post output if already computed above.
if (
final_aux_recon is not None
and self.end_layer in self.aux_hidden_state_layers
):
hidden_states = final_aux_recon
else:
hidden_states = layer.hc_post(
hidden_states, residual, post_mix, res_mix
)
if not get_pp_group().is_last_rank:
return IntermediateTensors({"hidden_states": hidden_states})
if self._mtp_hidden_buffer is not None:
num_tokens = hidden_states.shape[0]
self._mtp_hidden_buffer[:num_tokens].copy_(hidden_states.flatten(1))
hidden_states = self.hc_head_op(
hidden_states,
self.hc_head_fn,
self.hc_head_scale,
self.hc_head_base,
self.rms_norm_eps,
self.hc_eps,
)
hidden_states = self.norm(hidden_states)
if len(aux_hidden_states) > 0:
return hidden_states, aux_hidden_states
return hidden_states
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
stacked_params_mapping = [
# (param_name, shard_name, shard_id)
("gate_up_proj", "w1", 0),
("gate_up_proj", "w3", 1),
("attn.fused_wqa_wkv", "attn.wq_a", 0),
("attn.fused_wqa_wkv", "attn.wkv", 1),
("compressor.fused_wkv_wgate", "compressor.wkv", 0),
("compressor.fused_wkv_wgate", "compressor.wgate", 1),
]
params_dict = dict(self.named_parameters())
loaded_params: set[str] = set()
def _resolve_param_name(name: str) -> str:
inv_name = f"{name}_inv"
if name not in params_dict and inv_name in params_dict:
return inv_name
return name
# TP for attention
tp_size = get_tensor_model_parallel_world_size()
tp_rank = get_tensor_model_parallel_rank()
n_head = self.config.num_attention_heads
n_local_head = n_head // tp_size
head_rank_start = n_local_head * tp_rank
head_rank_end = n_local_head * (tp_rank + 1)
# Pre-compute expert mapping ONCE.
expert_mapping = self.get_expert_mapping()
# Each MoE's own per-layer fusion decision is the source of truth,
# so the redirect below can't diverge from how it was built.
fuse_by_layer = {
extract_layer_index(mod_name): mod.is_fused_shared_expert_enabled
for mod_name, mod in self.named_modules()
if isinstance(mod, DeepseekV4MoE)
}
n_routed = self.config.n_routed_experts
# Maps the single shared-expert tensor group to one appended slot;
# multiple shared experts would need per-expert slicing (see
# deepseek_v2.py). DeepSeek-V4 has n_shared_experts == 1.
if any(fuse_by_layer.values()) and self.config.n_shared_experts != 1:
raise NotImplementedError(
"deepseek-v4 fused shared-expert loading supports only "
f"n_shared_experts == 1, got {self.config.n_shared_experts}"
)
for name, loaded_weight in weights:
# Shared-expert fusion: redirect shared_experts.w{1,2,3} into
# the appended routed-expert slot so it loads through the
# routed expert (grouped GEMM) loader.
if ".ffn.shared_experts.w" in name and fuse_by_layer.get(
extract_layer_index(name), False
):
name = name.replace(
".ffn.shared_experts.w",
f".ffn.experts.{n_routed}.w",
)
for param_name, weight_name, shard_id in stacked_params_mapping:
# Skip non-stacked layers and experts (experts handled below).
if ".experts." in name:
continue
if weight_name not in name:
continue
name = name.replace(weight_name, param_name)
if is_pp_missing_parameter(name, self):
break
param_name = _resolve_param_name(name)
param = params_dict[param_name]
weight_loader = param.weight_loader
weight_loader(param, loaded_weight, shard_id)
loaded_params.add(param_name)
break
else:
if ".experts." in name:
# E8M0 scales are float8_e8m0fnu in checkpoints but the
# MoE param is uint8; copy_() would numerically convert
# (e.g. 2^-7 -> 0) instead of preserving raw bytes.
if (
"weight_scale" in name
and loaded_weight.dtype == torch.float8_e8m0fnu
):
loaded_weight = loaded_weight.view(torch.uint8)
for mapping in expert_mapping:
param_name, weight_name, expert_id, expert_shard_id = mapping
if weight_name not in name:
continue
name_mapped = name.replace(weight_name, param_name)
if is_pp_missing_parameter(name_mapped, self):
continue
param = params_dict[name_mapped]
# return_success lets us skip experts that have
# another replica available.
weight_loader = typing.cast(
Callable[..., bool], param.weight_loader
)
success = weight_loader(
param,
loaded_weight,
name_mapped,
shard_id=expert_shard_id,
expert_id=expert_id,
return_success=True,
)
if success:
name = name_mapped
break
loaded_params.add(name_mapped)
continue
elif "attn_sink" in name:
if is_pp_missing_parameter(name, self):
continue
narrow_weight = loaded_weight[head_rank_start:head_rank_end]
n = narrow_weight.shape[0]
params_dict[name][:n].copy_(narrow_weight)
loaded_params.add(name)
continue
else:
if is_pp_missing_parameter(name, self):
continue
param_name = _resolve_param_name(name)
param = params_dict[param_name]
weight_loader = getattr(
param, "weight_loader", default_weight_loader
)
weight_loader(param, loaded_weight)
loaded_params.add(param_name)
continue
return loaded_params
def get_expert_mapping(self) -> list[tuple[str, str, int, str]]:
# (param_name, weight_name, expert_id, shard_id). When fusing shared
# experts, include the appended slots so redirected shared-expert
# weights route through the expert loader.
n_shared = getattr(self.config, "n_shared_experts", 0) or 0
num_experts = self.config.n_routed_experts + (
n_shared if self.is_fused_shared_expert_enabled else 0
)
return fused_moe_make_expert_params_mapping(
self,
ckpt_gate_proj_name="w1",
ckpt_down_proj_name="w2",
ckpt_up_proj_name="w3",
num_experts=num_experts,
)
def _make_deepseek_v4_weights_mapper(
expert_dtype: str, fuse_shared_experts: bool = False
) -> WeightsMapper:
if expert_dtype == "fp4":
# MXFP4 experts register scales as ``w{1,2,3}_weight_scale`` (no
# _inv); FP8 linear/shared-expert scales register as
# ``weight_scale_inv``. Route DeepSeek-native ``.scale`` and
# AMD-Quark ``.weight_scale`` keys accordingly, leaving expert/
# shared-expert ``w{1,2,3}.weight_scale`` untouched for the MXFP4
# loader.
scale_regex = {
re.compile(r"(\.experts\.\d+\.w[123])\.scale$"): r"\1.weight_scale",
re.compile(r"\.scale$"): ".weight_scale_inv",
re.compile(r"(?<!\.w[123])\.weight_scale$"): ".weight_scale_inv",
}
else:
# FP8 experts use Fp8MoEMethod (block_quant=True), which registers
# scales as ``w{13,2}_weight_scale_inv``. Map all ``.scale`` keys
# there.
scale_regex = {
re.compile(r"\.scale$"): ".weight_scale_inv",
}
# Fused shared experts are redirected to routed expert slots elsewhere;
# leave their names untouched here.
substr_map: dict[str, str | None] = (
{}
if fuse_shared_experts
else {".shared_experts.w2": ".shared_experts.down_proj"}
)
# No MTP support on CPU yet: drop mtp.* weights (no model.mtp submodule).
substr_map["mtp."] = None
return WeightsMapper(
orig_to_new_prefix={
"layers.": "model.layers.",
"embed.": "model.embed.",
"norm.": "model.norm.",
"hc_head": "model.hc_head",
"mtp.": "model.mtp.",
},
orig_to_new_regex=scale_regex,
orig_to_new_suffix={
"head.weight": "lm_head.weight",
"embed.weight": "embed_tokens.weight",
".ffn.gate.bias": ".ffn.gate.e_score_correction_bias",
".input_scale": ".input_scale_2",
},
orig_to_new_substr=substr_map,
)
class DeepseekV4ForCausalLM(nn.Module, SupportsPP, SupportsEagle3):
model_cls = DeepseekV4Model
# Default mapper assumes the original FP4-expert checkpoint layout.
# Overridden per-instance in __init__ when expert_dtype != "fp4".
hf_to_vllm_mapper = _make_deepseek_v4_weights_mapper("fp4")
packed_modules_mapping = {
"gate_up_proj": ["w1", "w3"],
"fused_wqa_wkv": ["wq_a", "wkv"],
}
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
super().__init__()
config = vllm_config.model_config.hf_config
self.config = config
expert_dtype = getattr(config, "expert_dtype", "fp4")
self.model = self.model_cls(
vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model")
)
if expert_dtype != "fp4" or self.model.is_fused_shared_expert_enabled:
self.hf_to_vllm_mapper = _make_deepseek_v4_weights_mapper(
expert_dtype,
fuse_shared_experts=self.model.is_fused_shared_expert_enabled,
)
if get_pp_group().is_last_rank:
self.lm_head = ParallelLMHead(
config.vocab_size,
config.hidden_size,
prefix=maybe_prefix(prefix, "lm_head"),
)
else:
self.lm_head = PPMissingLayer()
self.logits_processor = LogitsProcessor(config.vocab_size)
self.make_empty_intermediate_tensors = ( # type: ignore[method-assign]
self.model.make_empty_intermediate_tensors
)
def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
return self.model.embed_input_ids(input_ids)
def compute_logits(
self,
hidden_states: torch.Tensor,
) -> torch.Tensor | None:
logits = self.logits_processor(self.lm_head, hidden_states)
return logits
def forward(
self,
input_ids: torch.Tensor,
positions: torch.Tensor,
intermediate_tensors: IntermediateTensors | None = None,
inputs_embeds: torch.Tensor | None = None,
) -> torch.Tensor | IntermediateTensors:
hidden_states = self.model(
input_ids, positions, intermediate_tensors, inputs_embeds
)
return hidden_states
def get_mtp_target_hidden_states(self) -> torch.Tensor | None:
"""Pre-hc_head residual stream buffer (max_num_batched_tokens,
hc_mult * hidden_size) for the MTP draft model. Populated by
forward(); valid after each target step."""
return getattr(self.model, "_mtp_hidden_buffer", None)
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
loader = AutoWeightsLoader(self)
return loader.load_weights(weights, mapper=self.hf_to_vllm_mapper)
def process_weights_after_loading(self) -> None:
# No CPU AMX weight-packing hook yet.
pass
def get_expert_mapping(self) -> list[tuple[str, str, int, str]]:
return self.model.get_expert_mapping()
+19
View File
@@ -0,0 +1,19 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""CPU DeepSeek-V4 MTP (speculative decoding) — deferred, not implemented.
``DeepSeekV4MTP`` is only instantiated when
``vllm/model_executor/models/registry.py``'s speculative-decoding registry
resolves it by name for a speculative-decoding config; a plain (non-spec)
DeepSeek-V4 CPU model never constructs this class. This stub exists solely
so ``vllm.models.deepseek_v4.cpu`` is import-clean.
"""
from vllm.config import VllmConfig
class DeepSeekV4MTP:
def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None:
raise NotImplementedError(
"DeepSeek-V4 speculative decoding (MTP) is not implemented on CPU."
)
+46 -4
View File
@@ -203,14 +203,26 @@ class CpuPlatform(Platform):
cache_config = vllm_config.cache_config
is_deepseek_v4 = (
model_config is not None
and getattr(model_config.hf_config, "model_type", None) == "deepseek_v4"
)
# The CPU MLA decode kernel only compiles with block_size=16 today
# (see csrc/cpu/mla_decode.cpp). If the model uses MLA we override
# the default block size regardless of user preference to avoid a
# runtime kernel dispatch failure. AMX MLA has no such constraint
# (same AMX-available condition as get_attn_backend_cls), so it's
# excluded from this override.
cpu_mla_enabled = model_config is not None and getattr(
model_config, "use_mla", False
# excluded from this override. DeepSeek-V4 is also excluded here and
# handled in its own branch below: its sparse-MLA and indexer
# backends declare block_size=256 as their only supported kernel
# block size (DeepseekV4SparseMLABackend/DeepseekV4IndexerBackend),
# so it needs the same override-regardless-of-preference treatment
# as CPU MLA, just with a different value.
cpu_mla_enabled = (
not is_deepseek_v4
and model_config is not None
and getattr(model_config, "use_mla", False)
)
amx_mla_enabled = (
cpu_mla_enabled
@@ -219,6 +231,21 @@ class CpuPlatform(Platform):
and vllm_config.attention_config.backend != AttentionBackendEnum.CPU_MLA
)
reference_cpu_mla_enabled = cpu_mla_enabled and not amx_mla_enabled
# DeepSeek-V4's CPU attention/indexer kernels
# (csrc/cpu/sgl-kernels/{flash_mla,store_cache,compressor,
# paged_mqa_logits,topk}.cpp) are AMX-kernel-backed and built on the
# same paged/position-indexed conventions as the GPU/XPU backends
# (block_table/slot_mapping addressing throughout, chunk metadata
# that already carries per-token causal offsets for partial/extend
# continuation) -- so they support chunked prefill and prefix
# caching the same way. `amx_mla_enabled` above deliberately
# excludes DeepSeek-V4 (it has its own block-size requirements,
# unrelated to chunked-prefill support), so it can't be reused here.
amx_mla_or_dsv4_enabled = amx_mla_enabled or (
is_deepseek_v4
and cls.get_cpu_architecture() == CpuArchEnum.X86
and torch.cpu._is_amx_tile_supported()
)
if reference_cpu_mla_enabled:
if cache_config.user_specified_block_size and cache_config.block_size != 16:
logger.warning(
@@ -227,6 +254,17 @@ class CpuPlatform(Platform):
cache_config.block_size,
)
cache_config.block_size = 16
elif is_deepseek_v4:
if (
cache_config.user_specified_block_size
and cache_config.block_size != 256
):
logger.warning(
"DeepSeek-V4 CPU backend requires block_size=256, "
"overriding user-specified block_size=%s.",
cache_config.block_size,
)
cache_config.block_size = 256
elif not cache_config.user_specified_block_size:
cache_config.block_size = 128
@@ -439,7 +477,11 @@ class CpuPlatform(Platform):
vllm_config.parallel_config.tensor_parallel_size
)
if model_config is not None and model_config.use_mla and not amx_mla_enabled:
if (
model_config is not None
and model_config.use_mla
and not amx_mla_or_dsv4_enabled
):
logger.info_once(
"MLA is enabled on a non-GPU platform; forcing chunked "
"prefill and prefix caching to be disabled."
+58 -50
View File
@@ -177,55 +177,6 @@ class PrepareUniformDecodeKernel(
)
def split_indexer_prefill_chunks(
seq_lens_cpu: torch.Tensor,
query_lens_cpu: torch.Tensor,
workspace_size: int,
max_logits_bytes: int,
request_offset: int = 0,
) -> list[tuple[slice, slice]]:
"""
Split prefill requests into chunks for the sparse indexer, respecting:
- N constraint: total_seq_lens <= workspace_size (existing O(N) workspace)
- Logits constraint: M * N * 4 <= max_logits_bytes
When a single request-level chunk still exceeds the logits budget,
sub-chunks on the query dimension (M) to bound peak memory.
Returns list of (req_slice, query_slice) tuples.
"""
chunks: list[tuple[slice, slice]] = []
n = len(seq_lens_cpu)
max_logits_elems = max_logits_bytes // 4
end = 0
while end < n:
start, chunk_m, chunk_n = end, 0, 0
while end < n:
q, s = query_lens_cpu[end].item(), seq_lens_cpu[end].item()
new_m, new_n = chunk_m + q, chunk_n + s
if new_n <= workspace_size and new_m * new_n <= max_logits_elems:
chunk_m, chunk_n = new_m, new_n
end += 1
else:
break
# A single request can exceed the budget, requiring sub-chunking
# on the query dimension.
if end == start:
chunk_m, chunk_n = query_lens_cpu[end].item(), seq_lens_cpu[end].item()
end += 1
req_slice = slice(start + request_offset, end + request_offset)
max_q = max(1, max_logits_elems // chunk_n) if chunk_n > 0 else max(1, chunk_m)
for q_off in range(0, chunk_m, max_q):
sub_m = min(max_q, chunk_m - q_off)
chunks.append((req_slice, slice(q_off, q_off + sub_m)))
return chunks
class DeepseekV32IndexerBackend(AttentionBackend):
@classmethod
def supports_pcp(cls) -> bool:
@@ -1020,6 +971,63 @@ class DeepseekV32IndexerMetadataBuilder(AttentionMetadataBuilder):
)
return indices
@staticmethod
def _split_indexer_prefill_chunks(
compressed_seq_lens_cpu: torch.Tensor,
prefill_query_lens_cpu: torch.Tensor,
workspace_size: int,
max_logits_bytes: int,
request_offset: int = 0,
) -> list[tuple[slice, slice]]:
"""Split this step's prefill requests into chunks, respecting:
- N constraint: total_seq_lens <= workspace_size (existing O(N)
workspace)
- Logits constraint: M * N * 4 <= max_logits_bytes
When a single request-level chunk still exceeds the logits budget,
sub-chunks on the query dimension (M) to bound peak memory.
Returns list of (req_slice, query_slice) tuples.
"""
chunks: list[tuple[slice, slice]] = []
n = len(compressed_seq_lens_cpu)
max_logits_elems = max_logits_bytes // 4
end = 0
while end < n:
start, chunk_m, chunk_n = end, 0, 0
while end < n:
q, s = (
prefill_query_lens_cpu[end].item(),
compressed_seq_lens_cpu[end].item(),
)
new_m, new_n = chunk_m + q, chunk_n + s
if new_n <= workspace_size and new_m * new_n <= max_logits_elems:
chunk_m, chunk_n = new_m, new_n
end += 1
else:
break
# A single request can exceed the budget, requiring sub-chunking
# on the query dimension.
if end == start:
chunk_m, chunk_n = (
prefill_query_lens_cpu[end].item(),
compressed_seq_lens_cpu[end].item(),
)
end += 1
req_slice = slice(start + request_offset, end + request_offset)
max_q = (
max(1, max_logits_elems // chunk_n) if chunk_n > 0 else max(1, chunk_m)
)
for q_off in range(0, chunk_m, max_q):
sub_m = min(max_q, chunk_m - q_off)
chunks.append((req_slice, slice(q_off, q_off + sub_m)))
return chunks
def build(
self,
common_prefix_len: int,
@@ -1097,7 +1105,7 @@ class DeepseekV32IndexerMetadataBuilder(AttentionMetadataBuilder):
# slice below).
assert common_attn_metadata.seq_lens_cpu_upper_bound is not None
seq_lens_cpu = common_attn_metadata.seq_lens_cpu_upper_bound
chunk_specs = split_indexer_prefill_chunks(
chunk_specs = self._split_indexer_prefill_chunks(
compressed_seq_lens_cpu[num_decodes:],
prefill_query_lens_cpu,
self.max_prefill_buffer_size,
@@ -148,6 +148,12 @@ class DeepseekSparseSWABackend(AttentionBackend):
)
return DeepseekV4ROCMAiterSparseSWAMetadataBuilder
if current_platform.is_cpu():
from vllm.models.deepseek_v4.cpu.cpu_mla import (
DeepseekV4CPUSparseSWAMetadataBuilder,
)
return DeepseekV4CPUSparseSWAMetadataBuilder
return DeepseekSparseSWAMetadataBuilder