Merge remote-tracking branch 'origin/main' into sync/lesj/qwen4exp-bugfixes

Signed-off-by: lesj0610 <lesj0610@users.noreply.github.com>
This commit is contained in:
lesj0610
2026-09-23 00:40:48 +09:00
512 changed files with 29298 additions and 6783 deletions
+28 -5
View File
@@ -44,6 +44,7 @@ from vllm.model_executor.layers.vocab_parallel_embedding import (
)
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
from vllm.model_executor.models.qwen3_dspark import (
DSparkConfidenceHead,
DSparkMarkovHead,
)
from vllm.model_executor.models.utils import maybe_prefix
@@ -102,7 +103,7 @@ class DSparkDeepseekV4Model(nn.Module):
]
)
# Heads: final norm + hc_head, and the Markov head
# Heads: final norm + hc_head, and the Markov + confidence heads
# Loaded from the "final" MTP layer weights (mtp.*) in the target checkpoint
self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
hc_dim = self.hc_mult * config.hidden_size
@@ -125,6 +126,12 @@ class DSparkDeepseekV4Model(nn.Module):
config.dspark_markov_rank,
prefix=maybe_prefix(prefix, "markov_head"),
)
self.confidence_head: DSparkConfidenceHead | None = None
if getattr(config, "enable_confidence_head", True):
self.confidence_head = DSparkConfidenceHead(
config.hidden_size + config.dspark_markov_rank,
prefix=maybe_prefix(prefix, "confidence_head"),
)
# MHC head CustomOp dispatcher (aiter / tilelang / triton / torch),
# replacing the direct nvidia tilelang kernel call.
@@ -358,6 +365,17 @@ class DSparkDeepseekV4ForCausalLM(nn.Module):
def markov_bias(self, markov_embed: torch.Tensor) -> torch.Tensor:
return self.model.markov_head.bias(markov_embed, self.logits_processor)
def compute_confidence(
self, head_hidden: torch.Tensor, markov_embed: torch.Tensor
) -> torch.Tensor:
"""Per-position acceptance probability for each drafted token."""
if self.model.confidence_head is None:
raise RuntimeError(
"compute_confidence() requires a confidence head, but the "
"checkpoint did not provide confidence_head weights."
)
return torch.sigmoid(self.model.confidence_head(head_hidden, markov_embed))
# --- Weight loading ----------------------------------------------------
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
@@ -391,6 +409,7 @@ class DSparkDeepseekV4ForCausalLM(nn.Module):
params_dict = dict(self.named_parameters())
loaded_params: set[str] = set()
loaded_confidence_head = False
tp_size = get_tensor_model_parallel_world_size()
tp_rank = get_tensor_model_parallel_rank()
@@ -403,6 +422,8 @@ class DSparkDeepseekV4ForCausalLM(nn.Module):
if mapped is None:
continue
name = mapped
if "confidence_head." in name:
loaded_confidence_head = True
# ``.scale`` -> per-method scale suffix.
if name.endswith(".scale"):
@@ -439,8 +460,8 @@ class DSparkDeepseekV4ForCausalLM(nn.Module):
continue
# Stacked rules only apply to decoder-layer weights. Head-stack params
# (main_proj/norm/hc_head/markov_head) load directly — otherwise e.g.
# "markov_w1" would collide with the "w1" shard rule.
# (main_proj/norm/hc_head/markov_head/confidence_head) load directly —
# otherwise e.g. "markov_w1" would collide with the "w1" shard rule.
is_layer_param = name.startswith("model.layers.")
for param_name, weight_name, stacked_shard_id in stacked_params_mapping:
if not is_layer_param or weight_name not in name:
@@ -469,6 +490,8 @@ class DSparkDeepseekV4ForCausalLM(nn.Module):
weight_loader(param, loaded_weight)
loaded_params.add(name)
if self.model.confidence_head is not None and not loaded_confidence_head:
self.model.confidence_head = None
logger.info_once("DSpark draft model loaded: %d params", len(loaded_params))
return loaded_params
@@ -482,8 +505,7 @@ class DSparkDeepseekV4ForCausalLM(nn.Module):
return None
stage = int(m.group(1))
rest = m.group(2)
# The confidence head is not wired into inference yet; drop its weights.
if rest.startswith("confidence_head."):
if rest.startswith("confidence_head.") and self.model.confidence_head is None:
return None
# Head-stack params live at model level (mtp.last), context combiner at
# model level (mtp.0); everything else is a per-layer decoder block.
@@ -493,6 +515,7 @@ class DSparkDeepseekV4ForCausalLM(nn.Module):
"hc_head_base",
"hc_head_scale",
"markov_head.",
"confidence_head.",
)
if rest.startswith(("main_proj.", "main_norm.")) or rest.startswith(
head_prefixes
+21 -4
View File
@@ -12,7 +12,7 @@ import torch.nn as nn
import vllm.envs as envs
from vllm._aiter_ops import rocm_aiter_ops
from vllm.config import VllmConfig, get_current_vllm_config
from vllm.config import ParallelConfig, VllmConfig
from vllm.distributed import (
get_pp_group,
get_tensor_model_parallel_rank,
@@ -504,11 +504,28 @@ class DeepseekV4HeterogeneousSharedRoutedExperts(RoutedExperts):
return routed + shared_out
def _fuse_shared_experts_enabled(config) -> bool:
def _fuse_shared_experts_enabled(config, parallel_config: ParallelConfig) -> bool:
if (
getattr(config, "n_shared_experts", None)
and envs.VLLM_ROCM_USE_AITER_FUSION_SHARED_EXPERTS
and not parallel_config.enable_expert_parallel
and parallel_config.data_parallel_size > 1
):
# Fused shared experts are not supported under data parallelism:
# the fused path cannot load the FP8 shared expert into the MXFP4
# routed slot, which fails obscurely during weight loading. Fail
# fast with an actionable message instead.
raise ValueError(
"DeepSeek-V4 fused shared experts "
"(VLLM_ROCM_USE_AITER_FUSION_SHARED_EXPERTS=1) are not supported "
"with data parallelism (data_parallel_size > 1). Set "
"VLLM_ROCM_USE_AITER_FUSION_SHARED_EXPERTS=0 to run the shared "
"expert as an unfused FP8 MLP."
)
return bool(
getattr(config, "n_shared_experts", None)
and envs.VLLM_ROCM_USE_AITER_FUSION_SHARED_EXPERTS
and not get_current_vllm_config().parallel_config.enable_expert_parallel
and not parallel_config.enable_expert_parallel
)
@@ -586,7 +603,7 @@ class DeepseekV4MoE(nn.Module):
# This should be cleaned up and use `resolve_layer_fused_shared_expert`.
self.fuse_heterogeneous_shared_expert = fuse_heterogeneous_shared_expert
fse_requested = (
_fuse_shared_experts_enabled(config)
_fuse_shared_experts_enabled(config, vllm_config.parallel_config)
and not self.fuse_heterogeneous_shared_expert
)
fse_compatible = False
+31
View File
@@ -8,6 +8,7 @@ from typing import cast
import torch
from vllm import envs
from vllm.config import VllmConfig
from vllm.distributed import (
get_tensor_model_parallel_world_size,
tensor_model_parallel_all_reduce,
@@ -26,6 +27,7 @@ from vllm.platforms.rocm import _ON_GFX950
from vllm.triton_utils import tl, triton
from vllm.utils.multi_stream_utils import execute_in_parallel
from vllm.v1.attention.backend import (
AttentionCGSupport,
CommonAttentionMetadata,
)
from vllm.v1.attention.backends.mla.sparse_swa import (
@@ -38,6 +40,7 @@ from vllm.v1.attention.ops.rocm_aiter_mla_sparse import (
rocm_sparse_attn_decode,
rocm_sparse_attn_prefill,
)
from vllm.v1.kv_cache_interface import KVCacheSpec
from vllm.v1.worker.workspace import current_workspace_manager
logger = init_logger(__name__)
@@ -445,6 +448,20 @@ class DeepseekV4ROCMAiterSparseSWAMetadata(DeepseekSparseSWAMetadata):
class DeepseekV4ROCMAiterMLASparseMetadataBuilder(DeepseekV4SparseMLAMetadataBuilder):
@classmethod
def get_cudagraph_support(
cls,
vllm_config: VllmConfig,
kv_cache_spec: KVCacheSpec,
) -> AttentionCGSupport:
spec_config = vllm_config.speculative_config
if spec_config is not None and spec_config.enable_adaptive_verification:
# All per-token metadata is built from device query boundaries into
# persistent buffers, so adaptive verification can replay varlen
# FULL decode graphs after reallocating drafts across requests.
return AttentionCGSupport.ALWAYS
return super().get_cudagraph_support(vllm_config, kv_cache_spec)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.c128a_decode_topk_ragged_indices_buffer: torch.Tensor | None = None
@@ -512,6 +529,20 @@ class DeepseekV4ROCMAiterMLASparseMetadataBuilder(DeepseekV4SparseMLAMetadataBui
class DeepseekV4ROCMAiterSparseSWAMetadataBuilder(DeepseekSparseSWAMetadataBuilder):
@classmethod
def get_cudagraph_support(
cls,
vllm_config: VllmConfig,
kv_cache_spec: KVCacheSpec,
) -> AttentionCGSupport:
spec_config = vllm_config.speculative_config
if spec_config is not None and spec_config.enable_adaptive_verification:
# SWA indices, lengths, and token-to-request mappings are built from
# device boundaries into persistent buffers, so adaptive verification
# can replay varlen FULL decode graphs safely.
return AttentionCGSupport.ALWAYS
return super().get_cudagraph_support(vllm_config, kv_cache_spec)
# Keep fused multi-step decode disabled until update_draft_decode_metadata()
# also refreshes the ROCm-specific ragged SWA indices and indptrs.
supports_draft_decode_metadata_update = False
+3
View File
@@ -793,6 +793,7 @@ class DeepseekV4MoE(nn.Module):
use_sequence_parallel: bool = False,
*,
num_hash_layers: int,
reduce_results: bool = True,
n_routed_experts: int | None = None,
n_activated_experts: int | None = None,
image_sentinel_lo: int = IMAGE_SENTINEL_BASE_ID,
@@ -804,6 +805,7 @@ class DeepseekV4MoE(nn.Module):
quant_config = vllm_config.quant_config
self.prefix = prefix
self.use_sequence_parallel = use_sequence_parallel
self.reduce_results = reduce_results
moe_backend = vllm_config.kernel_config.moe_backend
validate_fi_moe_ep_config(vllm_config)
self.use_mega_moe = moe_backend in MEGA_MOE_BACKENDS
@@ -1010,6 +1012,7 @@ class DeepseekV4MoE(nn.Module):
self.physical_expert_end = self.experts_end_idx
self.experts = FusedMoEFactory(
reduce_results=self.reduce_results,
shared_experts=self.shared_experts,
gate=self.gate,
num_experts=self.n_routed_experts,
+6 -2
View File
@@ -1,5 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections.abc import Callable
import torch
import torch.nn as nn
@@ -31,7 +33,7 @@ def deep_gemm_fp8_o_proj(
positions: torch.Tensor,
cos_sin_cache: torch.Tensor,
wo_a: nn.Module,
wo_b: nn.Module,
wo_b: Callable[[torch.Tensor], torch.Tensor],
*,
n_groups: int,
heads_per_group: int,
@@ -44,7 +46,9 @@ def deep_gemm_fp8_o_proj(
"""O projection: inverse RoPE + grouped wo_a + wo_b.
Shared by the FlashMLA and FlashInfer CUDA backends. The attention
layer selects the recipe at initialization.
layer selects the recipe at initialization. ``wo_b`` is any callable over
the flattened ``z``: the projection module itself, or a wrapper that also
reduce-scatters its output (DeepSeek-V4.1 GEMM-RS).
"""
use_fp8 = wo_a.weight.dtype == torch.float8_e4m3fn
o_proj_input, o_scale = fused_inv_rope_fp8_quant(
+5 -1
View File
@@ -61,9 +61,13 @@ from vllm.utils.math_utils import cdiv
from vllm.v1.attention.backends.registry import AttentionBackendEnum
from vllm.v1.worker.ubatching import dbo_current_ubatch_id
from ..common.engram import Engram, EngramLayout, NgramHashState
from ..common.engram import EngramLayout, NgramHashState
from ..common.mm_preprocess import IMAGE_SENTINEL_BASE_ID, image_sentinel_mask
# Engram host offload and its prefetch stream are neither ROCm- nor
# NVIDIA-specific, so they are imported rather than duplicated.
from ..nvidia.engram import Engram
if typing.TYPE_CHECKING:
from vllm.v1.attention.backends.mla.sparse_swa import DeepseekSparseSWAMetadata
+49
View File
@@ -26,6 +26,7 @@ from vllm.model_executor.layers.linear import (
from vllm.model_executor.layers.sparse_attn_indexer import SparseAttnIndexer
from vllm.model_executor.layers.sparse_mqa_indexer import SparseMQAIndexer
from vllm.models.common.ops import fused_q_kv_rmsnorm
from vllm.models.common.ops.sequence_parallel import sp_reduce_scatter
from vllm.models.deepseek_v41.common.ops import (
MXFP4_BLOCK_SIZE,
fused_indexer_q_rope_quant,
@@ -33,6 +34,7 @@ from vllm.models.deepseek_v41.common.ops import (
)
if TYPE_CHECKING:
from vllm.model_executor.kernels.linear.cute_dsl.gemm_rs_ar import GemmRsAr
from vllm.v1.attention.backends.mla.sparse_swa import (
DeepseekSparseSWAMetadata,
)
@@ -389,6 +391,9 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
return_bias=False,
prefix=f"{prefix}.wo_b",
)
# Set by ``bind_gemm_rs`` when the decoder layer runs sequence
# parallel and the fused GEMM + reduce-scatter kernel accepts wo_b.
self.gemm_rs: GemmRsAr | None = None
# Initialize rotary embedding before the indexer/compressor consume it.
self.rotary_emb = build_deepseek_v4_rope(
@@ -531,6 +536,15 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
"instead."
)
swa_bounded_replay = False
if swa_bounded_replay and current_platform.is_rocm():
logger.warning_once(
"SWA bounded replay is off on ROCm (the sparse SWA metadata "
"builders forward replay_start, but the window clamp it relies "
"on lives in the FlashInfer and FlashMLA prefill kernels, so "
"the padded slots fault); the sliding-window cache takes part "
"in prefix caching instead."
)
swa_bounded_replay = False
self.swa_cache_layer = DeepseekV4SWACache(
head_dim=self.head_dim,
window_size=self.window_size,
@@ -663,6 +677,41 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
)
return self._o_proj(attn_out, positions)
def bind_gemm_rs(self) -> None:
"""Fuse ``wo_b`` with the sequence-parallel TP reduce-scatter.
The decoder layer calls this after the model initialized the
process-wide GEMM-RS workspace and before weights load: the
eligibility check inspects the projection's linear kernel and weight
shape, which online quantization may later re-layout.
"""
from vllm.model_executor.kernels.linear.cute_dsl.gemm_rs_ar import (
get_gemm_rs_ar,
)
# The layer owns the reduction under sequence parallel.
assert not self.wo_b.reduce_results
gemm_rs = get_gemm_rs_ar()
if gemm_rs.can_run(self.wo_b):
self.gemm_rs = gemm_rs
else:
gemm_rs.warn_incompatible_projection()
def _wo_b_proj(self, z: torch.Tensor) -> torch.Tensor:
"""Apply ``wo_b``; with GEMM-RS bound, also reduce-scatter the result.
Every ``_o_proj`` implementation projects through this so the decoder
layer sees one contract: when ``gemm_rs`` is bound the output is
already the local sequence-parallel shard, otherwise it is the
unreduced TP partial.
"""
if self.gemm_rs is None:
return self.wo_b(z)
if self.gemm_rs.should_run(z):
return self.gemm_rs.apply(z, self.wo_b)
# Small batches stay on the unfused path, which is faster there.
return sp_reduce_scatter(self.wo_b(z))
def _alloc_attn_out(
self, num_tokens: int, hidden_states: torch.Tensor
) -> "torch.Tensor | QuantizedActivation":
@@ -58,6 +58,7 @@ from .model import (
_linear_scale_param_name,
_use_sequence_parallel,
make_deepseek_v4_expert_params_mapping,
maybe_init_gemm_rs,
prepare_mega_gate_routing_metadata,
)
@@ -113,12 +114,18 @@ class DSparkDeepseekV4Model(nn.Module):
)
current_vllm_config = get_current_vllm_config()
# The target model already holds the GEMM-RS workspace (same hidden
# size, same TP group); this only re-checks and binds the draft layers.
run_gemm_rs = maybe_init_gemm_rs(
current_vllm_config, self.use_sequence_parallel
)
self.layers = nn.ModuleList(
[
DeepseekV4DecoderLayer(
current_vllm_config,
prefix=maybe_prefix(prefix, f"layers.{self.num_hidden_layers + i}"),
topk_indices_buffer=self.topk_indices_buffer,
run_gemm_rs=run_gemm_rs,
)
for i in range(self.num_dspark_layers)
]
+23 -1
View File
@@ -3,6 +3,7 @@
"""NVIDIA Engram DP sharding, shared host storage, and asynchronous prefetch."""
import mmap
import shutil
import tempfile
import weakref
from contextlib import ExitStack
@@ -89,6 +90,27 @@ def gather_engram_hashes(
return dp_group.all_gather(hash_ids, dim=0)
def can_share_engram_tables(layout: EngramLayout, block_size: int = 32) -> bool:
"""Whether co-located DP replicas exist and /dev/shm can hold the full tables."""
if get_engram_dp_size() == 1:
logger.warning_once(
"Engram DP replicas are not co-located on one node; "
"storing the offloaded tables per rank instead of sharing them."
)
return False
num_bytes = sum(layout.num_embeddings) * (
layout.head_dim + layout.head_dim // block_size
)
if shutil.disk_usage("/dev/shm").total < num_bytes:
logger.warning_once(
"Sharing Engram tables across DP replicas needs %.1f GiB of /dev/shm "
"(--shm-size or --ipc=host); sharding them across replicas instead.",
num_bytes / 1024**3,
)
return False
return True
class DPSharedEngramStorage:
"""Registered host weights shared by a node-local DP group with one writer."""
@@ -362,7 +384,7 @@ class Engram(BaseEngram):
layout.head_dim,
tuple(size for order in layout.primes[layer_hash_index] for size in order),
cpu_offload=engram_config.cpu_offload,
dp_shared_memory=engram_config.dp_shared_memory,
dp_shared_memory=bool(engram_config.dp_shared_memory),
)
def _init_staging(self, max_tokens: int, head_dim: int) -> None:
@@ -225,7 +225,7 @@ class DeepseekV4MegaAttnAttention(DeepseekV4FlashMLAAttention):
z,
recipe=self._einsum_recipe,
)
return self.wo_b(z.flatten(1))
return self._wo_b_proj(z.flatten(1))
# ---- weights -----------------------------------------------------------
@@ -248,7 +248,7 @@ class DeepseekV4FlashInferMLAAttention(DeepseekV4Attention):
positions,
self.rotary_emb.cos_sin_cache,
self.wo_a,
self.wo_b,
self._wo_b_proj,
n_groups=self.n_local_groups,
heads_per_group=self.n_local_heads // self.n_local_groups,
nope_dim=self.nope_head_dim,
@@ -627,7 +627,7 @@ class DeepseekV4FlashInferSM120Attention(DeepseekV4Attention):
positions,
self.rotary_emb.cos_sin_cache,
self.wo_a,
self.wo_b,
self._wo_b_proj,
n_groups=self.n_local_groups,
heads_per_group=self.n_local_heads // self.n_local_groups,
nope_dim=self.nope_head_dim,
+1 -1
View File
@@ -65,7 +65,7 @@ class DeepseekV4FlashMLAAttention(DeepseekV4Attention):
positions,
self.rotary_emb.cos_sin_cache,
self.wo_a,
self.wo_b,
self._wo_b_proj,
n_groups=self.n_local_groups,
heads_per_group=self.n_local_heads // self.n_local_groups,
nope_dim=self.nope_head_dim,
+125 -20
View File
@@ -2,6 +2,7 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import typing
from collections.abc import Callable, Iterable
from functools import partial
from itertools import islice
import regex as re
@@ -16,8 +17,13 @@ from vllm.distributed import (
get_pp_group,
get_tensor_model_parallel_rank,
get_tensor_model_parallel_world_size,
tensor_model_parallel_all_reduce,
)
from vllm.forward_context import (
get_forward_context,
in_piecewise_cudagraph,
is_forward_context_available,
)
from vllm.forward_context import get_forward_context, is_forward_context_available
from vllm.logger import init_logger
from vllm.model_executor.kernels.mhc.tilelang import (
mhc_post_tilelang,
@@ -82,8 +88,14 @@ from vllm.v1.worker.ubatching import dbo_current_ubatch_id
from ..common.engram import EngramLayout, NgramHashState
from ..common.mm_preprocess import IMAGE_SENTINEL_BASE_ID, image_sentinel_mask
from .engram import Engram, gather_engram_hashes
from .ops.mega_mhc import mhc_shifted_post_pre
from .engram import Engram, can_share_engram_tables, gather_engram_hashes
from .ops.mhc import (
MHC_OVERLAP_MAX_TOKENS,
mhc_pre_delayed_overlap,
mhc_shifted_post_pre,
supports_mhc_all_reduce,
supports_mhc_overlap,
)
if typing.TYPE_CHECKING:
from vllm.v1.attention.backends.mla.sparse_swa import DeepseekSparseSWAMetadata
@@ -97,6 +109,7 @@ class DeepseekV4MoE(DeepseekV4MoEBase):
vllm_config: VllmConfig,
prefix: str = "",
use_sequence_parallel: bool = False,
reduce_results: bool = True,
):
config = vllm_config.model_config.hf_config
n_routed_experts = config.n_routed_experts
@@ -115,6 +128,7 @@ class DeepseekV4MoE(DeepseekV4MoEBase):
n_routed_experts=n_routed_experts,
n_activated_experts=n_activated_experts,
num_hash_layers=0,
reduce_results=reduce_results,
image_sentinel_lo=IMAGE_SENTINEL_BASE_ID,
)
@@ -179,6 +193,30 @@ def _use_sequence_parallel(vllm_config: VllmConfig) -> bool:
)
def maybe_init_gemm_rs(vllm_config: VllmConfig, use_sequence_parallel: bool) -> bool:
"""Set up the fused ``wo_b`` GEMM + reduce-scatter when opted in.
Sequence parallel is the only topology where ``wo_b`` ends in a
reduce-scatter, so the kernel is bound to RS mode. The workspace is a
process-wide singleton shared with any other model code in this worker
(the DSpark drafter reuses it), and its NVLink multicast rendezvous is
collective, so every TP rank must take the same decision here.
"""
if not (use_sequence_parallel and envs.VLLM_ENABLE_GEMM_RS):
return False
# The kernel module pulls in cute_dsl, so import it only once opted in.
from vllm.model_executor.kernels.linear.cute_dsl.gemm_rs_ar import (
maybe_init_gemm_rs_ar,
)
hidden_size = vllm_config.model_config.hf_config.hidden_size
if not maybe_init_gemm_rs_ar(vllm_config, N=hidden_size, all_reduce=False):
return False
logger.info_once("To disable DeepSeek-V4.1 GEMM-RS, set VLLM_ENABLE_GEMM_RS=0.")
return True
class DeepseekV4DecoderLayer(nn.Module):
def __init__(
self,
@@ -188,11 +226,16 @@ class DeepseekV4DecoderLayer(nn.Module):
aux_stream_list: list[torch.cuda.Stream] | None = None,
candidate_block_buffer: torch.Tensor | None = None,
engram_layout: EngramLayout | None = None,
run_gemm_rs: bool = False,
mhc_stream: torch.cuda.Stream | None = None,
fuse_mhc_all_reduce: bool = False,
):
super().__init__()
config = vllm_config.model_config.hf_config
self.hidden_size = config.hidden_size
self.mhc_stream = mhc_stream
self.fuse_mhc_all_reduce = fuse_mhc_all_reduce
self.use_sequence_parallel = _use_sequence_parallel(vllm_config)
self.engram: Engram | None = None
@@ -216,12 +259,17 @@ class DeepseekV4DecoderLayer(nn.Module):
aux_stream_list=aux_stream_list,
candidate_block_buffer=candidate_block_buffer,
)
if self.use_sequence_parallel:
if self.use_sequence_parallel or fuse_mhc_all_reduce:
self.attn.wo_b.reduce_results = False
if run_gemm_rs:
# Binds only when wo_b's kernel and shape qualify; otherwise
# forward keeps the separate reduce-scatter below.
self.attn.bind_gemm_rs()
self.ffn = DeepseekV4MoE(
vllm_config,
prefix=f"{prefix}.ffn",
use_sequence_parallel=self.use_sequence_parallel,
reduce_results=not fuse_mhc_all_reduce,
)
self.attn_norm = RMSNorm(self.hidden_size, self.rms_norm_eps)
@@ -269,19 +317,30 @@ class DeepseekV4DecoderLayer(nn.Module):
variants.append(
{**hc_stream, "use_pre_mix_in": True, "write_aux": True}
)
# Shifted mHC splits the epilogue in two: the input collapse on the
# caller stream and coefficient generation on a side stream.
split_modes = (
("fused", "stats", "input") if mhc_stream is not None else ("fused",)
)
for variant in variants:
MHC_PRE_NORM_KERNEL.register_warmup(
max_tokens=max_tokens,
hidden_size=self.hidden_size,
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,
norm_eps=self.rms_norm_eps,
hc_mult=self.hc_mult,
**variant,
)
for split_mode in split_modes:
MHC_PRE_NORM_KERNEL.register_warmup(
split_mode=split_mode,
max_tokens=(
max_tokens
if split_mode == "fused"
else min(max_tokens, MHC_OVERLAP_MAX_TOKENS)
),
hidden_size=self.hidden_size,
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,
norm_eps=self.rms_norm_eps,
hc_mult=self.hc_mult,
**variant,
)
mix_hc = (2 + self.hc_mult) * self.hc_mult
hc_dim = self.hc_mult * self.hidden_size
self.hc_attn_fn = nn.Parameter(
@@ -351,6 +410,19 @@ class DeepseekV4DecoderLayer(nn.Module):
torch.Tensor | None,
]:
previous_aux: torch.Tensor | None = None
mhc_stream = self.mhc_stream
if mhc_stream is not None and (
in_piecewise_cudagraph()
or not 0 < positions.shape[0] <= MHC_OVERLAP_MAX_TOKENS
or not torch.cuda.is_current_stream_capturing()
):
# Use overlap only in FULL graphs; eager warmup initializes Mega mHC.
mhc_stream = None
mhc_pre = (
partial(mhc_pre_delayed_overlap, stream=mhc_stream)
if mhc_stream is not None
else mhc_pre_delayed_tilelang
)
# The reference collapses each sublayer's input with the *previous*
# sublayer's pre-mix: attention uses the pre-mix carried in (identity
# for the first layer), the FFN uses this layer's attention pre-mix.
@@ -360,7 +432,7 @@ class DeepseekV4DecoderLayer(nn.Module):
# copies and the identity pre-mix selects copy 0.
assert self.hc_attn_fn_broadcast is not None
residual = x.unsqueeze(1).expand(-1, self.hc_mult, -1).contiguous()
post_mix, res_mix, x, attn_pre = mhc_pre_delayed_tilelang(
post_mix, res_mix, x, attn_pre = mhc_pre(
residual,
self.hc_attn_fn_broadcast,
self.hc_attn_scale,
@@ -376,7 +448,7 @@ class DeepseekV4DecoderLayer(nn.Module):
)
else:
residual = x
post_mix, res_mix, x, attn_pre = mhc_pre_delayed_tilelang(
post_mix, res_mix, x, attn_pre = mhc_pre(
residual,
self.hc_attn_fn,
self.hc_attn_scale,
@@ -395,6 +467,8 @@ class DeepseekV4DecoderLayer(nn.Module):
# and this block's pre, on the full hc stream, so the mix
# coefficients see the injected stream. The injection also keeps
# the post out of the pre-norm GEMM's fused prologue.
if self.fuse_mhc_all_reduce:
x = tensor_model_parallel_all_reduce(x)
previous_post = mhc_post_tilelang(x, residual, post_mix, res_mix)
if capture_previous_aux:
previous_aux = previous_post.mean(dim=1)
@@ -403,7 +477,7 @@ class DeepseekV4DecoderLayer(nn.Module):
engram_hashes[:, self.engram.layer_hash_index],
engram_mask,
)
post_mix, res_mix, x, attn_pre = mhc_pre_delayed_tilelang(
post_mix, res_mix, x, attn_pre = mhc_pre(
residual,
self.hc_attn_fn,
self.hc_attn_scale,
@@ -437,6 +511,8 @@ class DeepseekV4DecoderLayer(nn.Module):
norm_weight=self.attn_norm.weight,
norm_eps=self.attn_norm.variance_epsilon,
capture_aux=capture_previous_aux,
stream=mhc_stream,
reduce_results=self.fuse_mhc_all_reduce,
)
if capture_previous_aux:
previous_aux = aux
@@ -445,9 +521,13 @@ class DeepseekV4DecoderLayer(nn.Module):
x = sp_all_gather(x)[: positions.shape[0]]
x = self.attn(positions, x, None)
if self.use_sequence_parallel:
# With GEMM-RS bound, the attention output is already this rank's
# sequence-parallel shard (see DeepseekV4Attention._wo_b_proj).
if self.use_sequence_parallel and self.attn.gemm_rs is None:
x = sp_reduce_scatter(x)
if mhc_stream is not None:
torch.cuda.current_stream().wait_stream(mhc_stream)
residual, post_mix, res_mix, x, ffn_pre, _ = mhc_shifted_post_pre(
x,
residual,
@@ -464,8 +544,12 @@ class DeepseekV4DecoderLayer(nn.Module):
pre_mix=attn_pre,
norm_weight=self.ffn_norm.weight,
norm_eps=self.ffn_norm.variance_epsilon,
stream=mhc_stream,
reduce_results=self.fuse_mhc_all_reduce,
)
x = self.ffn(x, input_ids, mega_gate_metadata)
if mhc_stream is not None:
torch.cuda.current_stream().wait_stream(mhc_stream)
return x, residual, post_mix, res_mix, ffn_pre, previous_aux
@@ -497,6 +581,11 @@ class DeepseekV4Model(nn.Module, EagleModelMixin):
# (compressor kv_score, indexer.weights_proj). fused_wqa_wkv stays on
# the default stream.
aux_stream_list = [torch.cuda.Stream() for _ in range(3)]
# Keep mHC independent of the streams used inside attention.
mhc_stream = torch.cuda.Stream() if supports_mhc_overlap(vllm_config) else None
self.fuse_mhc_all_reduce = mhc_stream is not None and supports_mhc_all_reduce(
vllm_config
)
# Reserved topk indices buffer for all Indexer layers to reuse.
self.topk_indices_buffer = torch.empty(
@@ -531,6 +620,17 @@ class DeepseekV4Model(nn.Module, EagleModelMixin):
self.embed_tokens = PPMissingLayer()
self.engram_layout = EngramLayout.from_config(config)
engram_config = vllm_config.engram_config
if (
self.engram_layout is not None
and engram_config is not None
and engram_config.dp_shared_memory
):
engram_config.dp_shared_memory = can_share_engram_tables(self.engram_layout)
# GEMM-RS uses NCCL symmetric-memory multicast, which requires all TP
# ranks to belong to one NVLink domain. Collective: run before layers.
self.run_gemm_rs = maybe_init_gemm_rs(vllm_config, self.use_sequence_parallel)
self.start_layer, self.end_layer, self.layers = make_layers(
config.num_hidden_layers,
@@ -541,6 +641,9 @@ class DeepseekV4Model(nn.Module, EagleModelMixin):
aux_stream_list=aux_stream_list,
candidate_block_buffer=self.candidate_block_buffer,
engram_layout=self.engram_layout,
run_gemm_rs=self.run_gemm_rs,
mhc_stream=mhc_stream,
fuse_mhc_all_reduce=self.fuse_mhc_all_reduce,
),
prefix=f"{prefix}.layers",
)
@@ -750,6 +853,8 @@ class DeepseekV4Model(nn.Module, EagleModelMixin):
aux_hidden_by_layer[idx] = previous_aux
if layer is not None:
# The last layer has no successor to fold its post into.
if self.fuse_mhc_all_reduce:
hidden_states = tensor_model_parallel_all_reduce(hidden_states)
hidden_states = mhc_post_tilelang(
hidden_states, residual, post_mix, res_mix
)
+16 -70
View File
@@ -5,9 +5,6 @@ import functools
import torch
from vllm.model_executor.kernels.mhc.tilelang import (
mhc_fused_post_pre_delayed_tilelang,
)
from vllm.platforms import current_platform
from vllm.utils.deep_gemm import (
_import_deep_gemm,
@@ -31,6 +28,22 @@ def is_mega_mhc_supported(hidden_size: int, hc_mult: int) -> bool:
return deep_gemm is not None and callable(getattr(deep_gemm, "mega_mhc", None))
def can_use_mega_mhc(
x: torch.Tensor,
residual: torch.Tensor,
pre_mix: torch.Tensor | None,
norm_weight: torch.Tensor | None,
capture_aux: bool,
) -> bool:
return (
pre_mix is not None
and norm_weight is not None
and not capture_aux
and x.shape[0] <= 1 << 20
and is_mega_mhc_supported(x.shape[1], residual.shape[1])
)
def mhc_shifted_post_pre_deep_gemm(
x: torch.Tensor,
residual: torch.Tensor,
@@ -87,70 +100,3 @@ def mhc_shifted_post_pre_deep_gemm(
y_bf16,
new_prev_mix.squeeze(-1),
)
def mhc_shifted_post_pre(
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,
pre_mix: torch.Tensor | None = None,
norm_weight: torch.Tensor | None = None,
norm_eps: float = 1e-6,
capture_aux: bool = False,
) -> tuple[
torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor
]:
"""Use Mega-mHC for carried mixing, retaining TileLang for aux capture."""
if (
pre_mix is not None
and norm_weight is not None
and not capture_aux
and x.shape[0] <= 1 << 20
and is_mega_mhc_supported(x.shape[1], residual.shape[1])
):
outputs = mhc_shifted_post_pre_deep_gemm(
x,
residual,
pre_mix,
post_layer_mix,
comb_res_mix,
fn,
hc_scale,
hc_base,
rms_eps,
hc_pre_eps,
hc_post_mult_value,
hc_sinkhorn_eps,
sinkhorn_repeat,
norm_weight,
norm_eps,
)
return *outputs, x.new_empty(0, x.shape[1])
return mhc_fused_post_pre_delayed_tilelang(
x,
residual,
post_layer_mix,
comb_res_mix,
fn,
hc_scale,
hc_base,
rms_eps,
hc_pre_eps,
hc_sinkhorn_eps,
hc_post_mult_value,
sinkhorn_repeat,
pre_mix=pre_mix,
norm_weight=norm_weight,
norm_eps=norm_eps,
capture_aux=capture_aux,
)
+267
View File
@@ -0,0 +1,267 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Dispatch DSV4.1 mHC operations and overlap coefficient generation."""
from functools import partial
from typing import TYPE_CHECKING, cast
import torch
from vllm.config import VllmConfig
from vllm.distributed import get_tp_group
from vllm.model_executor.kernels.mhc.tilelang import (
mhc_fused_post_pre_delayed_tilelang,
mhc_post_tilelang,
)
from vllm.platforms import current_platform
from vllm.utils.deep_gemm import is_deep_gemm_supported
from .mega_mhc import (
can_use_mega_mhc,
mhc_shifted_post_pre_deep_gemm,
)
if TYPE_CHECKING:
from vllm.distributed.device_communicators.cuda_communicator import CudaCommunicator
# GB200 TP4/FlashInfer improves through 16 tokens; larger screens tie or regress.
MHC_OVERLAP_MAX_TOKENS = 16
def supports_mhc_overlap(vllm_config: VllmConfig) -> bool:
"""Check kernel requirements and safety of sharing the coefficient stream."""
config = vllm_config.model_config.hf_config
# DeepGEMM's prenorm kernel requires K % 64 == 0, N % 8 == 0, and N <= 32.
mix_size = config.hc_mult * (config.hc_mult + 2)
return (
current_platform.is_device_capability_family(100)
and is_deep_gemm_supported()
and config.hidden_size % 64 == 0
and 0 < mix_size <= 32
and mix_size % 8 == 0
and not vllm_config.parallel_config.use_ubatching
)
def supports_mhc_all_reduce(vllm_config: VllmConfig) -> bool:
parallel = vllm_config.parallel_config
config = vllm_config.model_config.hf_config
if (
parallel.tensor_parallel_size != 4
or parallel.enable_expert_parallel
or config.hidden_size != 5120
or config.hc_mult != 4
):
return False
comm = cast("CudaCommunicator", get_tp_group().device_communicator).ca_comm
return comm is not None and bool(comm.mnnvl_lamport_ag_multicast_ptr)
def mhc_pre_delayed_overlap(
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,
pre_mix: torch.Tensor | None = None,
x: torch.Tensor | None = None,
norm_weight: torch.Tensor | None = None,
norm_eps: float = 1e-6,
*,
stream: torch.cuda.Stream,
layer_input: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
"""Prepare the input on the caller stream and coefficients on another stream.
Returns post mix, residual mix, normalized input, and next pre-mix. Only the
input is ready on the caller stream; join stream before using coefficients.
The caller must retain the weights and coefficient outputs until the join.
"""
from vllm.model_executor.kernels.mhc.warmup import (
MHC_PRE_NORM_KERNEL,
compute_mhc_pre_num_splits,
)
from vllm.utils.deep_gemm import tf32_hc_prenorm_gemm
n, hc, hidden = residual.shape
assert residual.is_contiguous() and residual.dtype == torch.bfloat16
assert norm_weight is not None
if x is None:
x = residual.view(n, hc * hidden)
assert x.is_contiguous()
post = torch.empty((n, hc), device=residual.device, dtype=torch.float32)
comb = torch.empty((n, hc * hc), device=residual.device, dtype=torch.float32)
next_pre = torch.empty_like(post)
compute_input = layer_input is None
if layer_input is None:
layer_input = torch.empty(
(n, hidden), device=residual.device, dtype=torch.bfloat16
)
outputs = post.unsqueeze(-1), comb.view(n, hc, hc), layer_input, next_pre
if n == 0:
return outputs
splits = compute_mhc_pre_num_splits(x.shape[1], n)
mix = torch.empty(
(splits, n, hc * (hc + 2)), device=residual.device, dtype=torch.float32
)
sqr = torch.empty((splits, n), device=residual.device, dtype=torch.float32)
epilogue = partial(
MHC_PRE_NORM_KERNEL,
mix,
sqr,
hc_scale,
hc_base,
residual,
post,
comb,
layer_input,
norm_weight,
pre_mix if pre_mix is not None else post,
next_pre,
layer_input, # Unused aux output in split modes.
hidden_size=hidden,
rms_eps=rms_eps,
hc_pre_eps=hc_pre_eps,
hc_sinkhorn_eps=hc_sinkhorn_eps,
hc_post_mult_value=hc_post_mult_value,
sinkhorn_repeat=sinkhorn_repeat,
norm_eps=norm_eps,
hc_mult=hc,
use_pre_mix_in=pre_mix is not None,
save_pre_mix=True,
rms_numel=x.shape[1],
)
main = torch.cuda.current_stream()
# Prioritize input readiness for small batches before releasing statistics.
if compute_input and n <= 8:
epilogue(split_mode="input")
stream.wait_stream(main)
with torch.cuda.stream(stream):
tf32_hc_prenorm_gemm(x, fn, mix, sqr, splits)
epilogue(split_mode="stats")
for tensor in (x, mix, sqr):
tensor.record_stream(stream)
if compute_input and n > 8:
epilogue(split_mode="input")
return outputs
def mhc_shifted_post_pre(
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,
pre_mix: torch.Tensor | None = None,
norm_weight: torch.Tensor | None = None,
norm_eps: float = 1e-6,
capture_aux: bool = False,
*,
stream: torch.cuda.Stream | None = None,
reduce_results: bool = False,
) -> tuple[
torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor
]:
"""Dispatch shifted post/pre to overlap, Mega-mHC, or fused TileLang.
When stream is supplied, join it before consuming the returned coefficients.
"""
layer_input = None
if reduce_results:
tp = get_tp_group()
if stream is not None and 0 < x.shape[0] <= MHC_OVERLAP_MAX_TOKENS:
comm = cast("CudaCommunicator", tp.device_communicator).ca_comm
assert comm is not None and comm.mnnvl_lamport_epochs is not None
output = torch.empty_like(residual)
layer_input = torch.empty_like(x)
torch.ops._C_custom_ar.all_reduce_mhc(
x,
residual,
post_layer_mix,
comb_res_mix,
pre_mix,
norm_weight,
output,
layer_input,
comm.mnnvl_lamport_ag_local_ptr,
comm.mnnvl_lamport_ag_multicast_ptr,
comm.mnnvl_lamport_epochs[0],
comm.rank,
comm.mnnvl_buffer_size,
norm_eps,
)
residual = output
else:
x = tp.all_reduce(x)
if stream is not None:
if layer_input is None:
residual = mhc_post_tilelang(x, residual, post_layer_mix, comb_res_mix)
aux = residual.mean(dim=1) if capture_aux else x.new_empty(0, x.shape[1])
pre_outputs = mhc_pre_delayed_overlap(
residual,
fn,
hc_scale,
hc_base,
rms_eps,
hc_pre_eps,
hc_sinkhorn_eps,
hc_post_mult_value,
sinkhorn_repeat,
pre_mix=pre_mix,
norm_weight=norm_weight,
norm_eps=norm_eps,
stream=stream,
layer_input=layer_input,
)
return residual, *pre_outputs, aux
if can_use_mega_mhc(x, residual, pre_mix, norm_weight, capture_aux):
assert pre_mix is not None and norm_weight is not None
outputs = mhc_shifted_post_pre_deep_gemm(
x,
residual,
pre_mix,
post_layer_mix,
comb_res_mix,
fn,
hc_scale,
hc_base,
rms_eps,
hc_pre_eps,
hc_post_mult_value,
hc_sinkhorn_eps,
sinkhorn_repeat,
norm_weight,
norm_eps,
)
return *outputs, x.new_empty(0, x.shape[1])
return mhc_fused_post_pre_delayed_tilelang(
x,
residual,
post_layer_mix,
comb_res_mix,
fn,
hc_scale,
hc_base,
rms_eps,
hc_pre_eps,
hc_sinkhorn_eps,
hc_post_mult_value,
sinkhorn_repeat,
pre_mix=pre_mix,
norm_weight=norm_weight,
norm_eps=norm_eps,
capture_aux=capture_aux,
)
+1
View File
@@ -355,6 +355,7 @@ class Glm5NextDecoderLayer(nn.Module):
intermediate_size=config.intermediate_size,
hidden_act=config.hidden_act,
quant_config=quant_config,
is_sequence_parallel=self.is_sequence_parallel,
prefix=f"{prefix}.mlp",
swiglu_limit=config.swiglu_limit,
)
+14 -7
View File
@@ -14,20 +14,27 @@ The package is organized like `vllm.models.deepseek_v32`: this module is the
only public entry point and dispatches on the current platform, so registry
entries never reach into a platform subpackage.
NVIDIA and ROCm are supported. The port also drops the reference
implementation's HPC/TPCP fusion paths, which depend on infrastructure that
does not exist in this tree.
NVIDIA and ROCm are supported, the latter through `amd/`. The port also drops
the reference implementation's HPC/TPCP fusion paths, which depend on
infrastructure that does not exist in this tree.
"""
from typing import TYPE_CHECKING
from vllm.platforms import current_platform
if current_platform.is_xpu():
raise NotImplementedError("hy_v4 does not yet support XPU.")
else:
# The implementation is shared by CUDA and ROCm; platform-specific
# attention behavior is selected by the normal attention backend router.
# The NVIDIA branch is the static default that type-checkers see; the ROCm
# branch overrides it at runtime (kept type-compatible via type: ignore).
if TYPE_CHECKING or not current_platform.is_rocm():
from .nvidia.model import HYV4ForCausalLM
from .nvidia.mtp import HYV4MTP
else:
from .amd.model import HYV4ForCausalLM # type: ignore[assignment]
# The draft head has no ROCm-specific implementation yet.
from .nvidia.mtp import HYV4MTP # noqa: E402
__all__ = [
"HYV4ForCausalLM",
+2
View File
@@ -0,0 +1,2 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
+718
View File
@@ -0,0 +1,718 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Adapted from
# Copyright 2023 The vLLM team.
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
#
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
# and OPT implementations in this library. It has been modified from its
# original forms to accommodate minor architectural differences compared
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Inference-only HY V4 model compatible with HuggingFace weights (ROCm)."""
import typing
from collections.abc import Callable, Iterable, MutableSequence, Sequence
from itertools import islice
import regex as re
import torch
from torch import nn
from transformers import PretrainedConfig
from vllm.compilation.decorators import support_torch_compile
from vllm.config import CacheConfig, VllmConfig
from vllm.distributed import (
get_pp_group,
get_tensor_model_parallel_rank,
get_tensor_model_parallel_world_size,
)
from vllm.logger import init_logger
from vllm.model_executor.layers.fused_moe import fused_moe_make_expert_params_mapping
from vllm.model_executor.layers.layernorm import RMSNorm
from vllm.model_executor.layers.logits_processor import LogitsProcessor
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.deepseek_v2 import _try_load_fp8_indexer_wk
from vllm.model_executor.models.interfaces import SupportsLoRA, SupportsPP
from vllm.model_executor.models.utils import (
AutoWeightsLoader,
PPMissingLayer,
WeightsMapper,
get_pp_missing_layer_names,
is_pp_missing_parameter,
make_empty_intermediate_tensors_factory,
make_layers,
maybe_prefix,
)
from vllm.platforms import current_platform
from vllm.sequence import IntermediateTensors
from ..nvidia.attention import (
HYV4MLAAttention,
compute_skip_topk_layers,
is_skip_topk_indexer_weight,
)
from ..nvidia.hc import HYV4HCHeadLayer, HYV4HCLayer
from ..nvidia.moe import HYV4FeedForward, HYV4MoEFused
logger = init_logger(__name__)
def _normalize_hyv4_config(config: PretrainedConfig) -> PretrainedConfig:
"""Populate the aliases consumed by the shared MoE implementation."""
config.router_scaling_factor = config.routed_scaling_factor
config.num_experts = config.n_routed_experts
config.expert_hidden_dim = config.moe_intermediate_size
config.num_shared_experts = config.n_shared_experts
config.route_norm = config.norm_topk_prob
return config
class HYV4DecoderLayer(nn.Module):
"""One HY V4 decoder layer: MLA attention plus a dense or MoE MLP.
When``config.enable_ihc`` is set the layer runs on ``hc_mult`` residual
channels and each sub-block is wrapped by an `HYV4HCLayer` boundary;
otherwise it uses the standard single-stream residual.
"""
def __init__(
self,
config: PretrainedConfig,
vllm_config: VllmConfig,
cache_config: CacheConfig | None = None,
quant_config: QuantizationConfig | None = None,
prefix: str = "",
topk_indices_buffer: torch.Tensor | None = None,
) -> None:
super().__init__()
self.hidden_size = config.hidden_size
self.config = config
self.enable_ihc = getattr(config, "enable_ihc", False)
layer_idx = int(prefix.split(".")[-1])
self.layer_idx = layer_idx
max_position_embeddings = getattr(config, "max_position_embeddings", 8192)
self.self_attn = HYV4MLAAttention(
vllm_config=vllm_config,
config=config,
hidden_size=self.hidden_size,
num_heads=config.num_attention_heads,
qk_nope_head_dim=config.qk_nope_head_dim,
qk_rope_head_dim=config.qk_rope_head_dim,
v_head_dim=config.v_head_dim,
q_lora_rank=config.q_lora_rank,
kv_lora_rank=config.kv_lora_rank,
max_position_embeddings=max_position_embeddings,
cache_config=cache_config,
quant_config=quant_config,
prefix=f"{prefix}.self_attn",
layer_idx=layer_idx,
topk_indices_buffer=topk_indices_buffer,
)
self.input_layernorm = RMSNorm(config.hidden_size, config.rms_norm_eps)
if config.mlp_layer_types[layer_idx] == "dense":
self.mlp = HYV4FeedForward(
hidden_size=config.hidden_size,
intermediate_size=config.intermediate_size,
hidden_act=config.hidden_act,
quant_config=quant_config,
prefix=f"{prefix}.mlp",
)
self.block_type = "feedforward"
else:
self.mlp = HYV4MoEFused(
config=config, quant_config=quant_config, prefix=f"{prefix}.mlp"
)
self.block_type = "moe"
self.post_attention_layernorm = RMSNorm(config.hidden_size, config.rms_norm_eps)
self.hc_attn_layer = HYV4HCLayer(
config, layer_idx, prefix=f"{prefix}.hc_attn_layer"
)
self.hc_mlp_layer = HYV4HCLayer(
config, layer_idx, prefix=f"{prefix}.hc_mlp_layer"
)
def forward(
self,
positions: torch.Tensor,
hidden_states: torch.Tensor,
residual: torch.Tensor | None,
) -> tuple[torch.Tensor, torch.Tensor | None]:
if self.enable_ihc:
return self._forward_ihc(positions, hidden_states)
return self._forward_normal(positions, hidden_states, residual)
def _forward_normal(
self,
positions: torch.Tensor,
hidden_states: torch.Tensor,
residual: torch.Tensor | None,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Standard single-residual-stream forward (iHC disabled)."""
if residual is not None:
hidden_states = hidden_states + residual
residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
hidden_states = self.self_attn(
positions=positions,
hidden_states=hidden_states,
)
hidden_states = hidden_states + residual
residual = hidden_states
hidden_states = self.post_attention_layernorm(hidden_states)
hidden_states = self.mlp(hidden_states)
return hidden_states, residual
def _forward_ihc(
self,
positions: torch.Tensor,
hidden_states: torch.Tensor,
) -> tuple[torch.Tensor, None]:
"""IHC forward: each sub-block reduces and re-scatters the channels."""
hidden_states = self.hc_attn_layer.prepare_input(hidden_states)
hidden_states, post_gates, residual = self.hc_attn_layer.pre(hidden_states)
hidden_states = self.input_layernorm(hidden_states)
hidden_states = self.self_attn(
positions=positions,
hidden_states=hidden_states,
)
hidden_states = self.hc_attn_layer.post(hidden_states, residual, post_gates)
hidden_states = self.hc_mlp_layer.prepare_input(hidden_states)
hidden_states, post_gates, residual = self.hc_mlp_layer.pre(hidden_states)
hidden_states = self.post_attention_layernorm(hidden_states)
hidden_states = self.mlp(hidden_states)
hidden_states = self.hc_mlp_layer.post(hidden_states, residual, post_gates)
# Under iHC the residual is carried inside hidden_states.
return hidden_states, None
@support_torch_compile
class HYV4Model(nn.Module):
"""HY V4 backbone."""
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
super().__init__()
config = _normalize_hyv4_config(vllm_config.model_config.hf_config)
cache_config = vllm_config.cache_config
quant_config = vllm_config.quant_config
parallel_config = vllm_config.parallel_config
eplb_config = parallel_config.eplb_config
self.num_redundant_experts = eplb_config.num_redundant_experts
self.device = current_platform.device_type
self.vocab_size = config.vocab_size
self.is_sparse = hasattr(config, "index_topk")
if self.is_sparse:
self.topk_indices_buffer = torch.empty(
vllm_config.scheduler_config.max_num_batched_tokens,
config.index_topk,
dtype=torch.int32,
device=self.device,
)
else:
self.topk_indices_buffer = None
self.config = config
self.quant_config = quant_config
self.enable_ihc = getattr(config, "enable_ihc", False)
if get_pp_group().is_first_rank or (
self.config.tie_word_embeddings and get_pp_group().is_last_rank
):
self.embed_tokens = VocabParallelEmbedding(
config.vocab_size,
config.hidden_size,
)
else:
self.embed_tokens = PPMissingLayer()
self.start_layer, self.end_layer, self.layers = make_layers(
config.num_hidden_layers,
lambda prefix: HYV4DecoderLayer(
config=config,
vllm_config=vllm_config,
cache_config=cache_config,
quant_config=quant_config,
prefix=prefix,
topk_indices_buffer=self.topk_indices_buffer,
),
prefix=f"{prefix}.layers",
)
if get_pp_group().is_last_rank:
self.norm = RMSNorm(config.hidden_size, config.rms_norm_eps)
else:
self.norm = PPMissingLayer()
if self.enable_ihc:
# iHC head layer: merge the residual channels into one stream.
if get_pp_group().is_last_rank:
self.hc_head = HYV4HCHeadLayer(
config,
hidden_size=config.hidden_size,
hc_mult=config.hc_mult,
hc_eps=config.hc_eps,
prefix=f"{prefix}.hc_head",
)
else:
self.hc_head = PPMissingLayer()
self.make_empty_intermediate_tensors = (
make_empty_intermediate_tensors_factory(
["hidden_states"], config.hc_mult * config.hidden_size
)
)
else:
self.make_empty_intermediate_tensors = (
make_empty_intermediate_tensors_factory(
["hidden_states", "residual"], config.hidden_size
)
)
# MoE hyperparameters (consumed by EPLB).
self.expert_weights: MutableSequence[Sequence[torch.Tensor]] = []
self.num_expert_groups = 1
self.moe_layers: list[nn.Module] = []
example_layer: HYV4MoEFused | None = None
for layer in self.layers:
if isinstance(layer, PPMissingLayer):
continue
assert isinstance(layer, HYV4DecoderLayer)
if layer.block_type == "moe":
assert isinstance(layer.mlp, HYV4MoEFused)
example_layer = layer.mlp
self.moe_layers.append(layer.mlp.experts)
if example_layer is None:
self.num_moe_layers = 0
self.num_logical_experts = 0
self.num_physical_experts = 0
self.num_local_physical_experts = 0
self.num_routed_experts = 0
self.num_redundant_experts = 0
return
self.num_moe_layers = len(self.moe_layers)
self.num_logical_experts = example_layer.n_logical_experts
self.num_physical_experts = example_layer.n_physical_experts
self.num_local_physical_experts = example_layer.n_local_physical_experts
self.num_routed_experts = example_layer.n_routed_experts
self.num_redundant_experts = example_layer.n_redundant_experts
def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
return self.embed_tokens(input_ids)
def update_physical_experts_metadata(
self,
num_physical_experts: int,
num_local_physical_experts: int,
) -> None:
assert self.num_local_physical_experts == num_local_physical_experts
self.num_physical_experts = num_physical_experts
self.num_local_physical_experts = num_local_physical_experts
self.num_redundant_experts = num_physical_experts - self.num_logical_experts
for layer in self.layers:
if isinstance(layer, PPMissingLayer):
continue
if isinstance(layer.mlp, HYV4MoEFused):
moe = layer.mlp
moe.n_local_physical_experts = num_local_physical_experts
moe.n_physical_experts = num_physical_experts
moe.n_redundant_experts = self.num_redundant_experts
moe.experts.update_expert_map()
def get_expert_mapping(self) -> list[tuple[str, str, int, str]]:
# (param_name, weight_name, expert_id, shard_id) for weights, fp8
# weight scales and fp8 activation scales.
if not hasattr(self, "_cached_expert_params_mapping"):
self._cached_expert_params_mapping = fused_moe_make_expert_params_mapping(
self,
ckpt_gate_proj_name="gate_proj",
ckpt_down_proj_name="down_proj",
ckpt_up_proj_name="up_proj",
num_experts=self.config.num_experts,
num_redundant_experts=self.num_redundant_experts,
)
return self._cached_expert_params_mapping
def forward(
self,
input_ids: torch.Tensor,
positions: torch.Tensor,
intermediate_tensors: IntermediateTensors | None = 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)
residual = None
else:
assert intermediate_tensors is not None
hidden_states = intermediate_tensors["hidden_states"]
# In iHC mode the flattened [num_tokens, hc*h] tensor from the
# previous PP stage is reshaped back to 3D by the first layer's
# prepare_input, and residual is unused.
residual = None if self.enable_ihc else intermediate_tensors["residual"]
for layer in islice(self.layers, self.start_layer, self.end_layer):
hidden_states, residual = layer(positions, hidden_states, residual)
if not get_pp_group().is_last_rank:
if self.enable_ihc:
# hidden_states is [num_tokens, hc, h]; flatten the channel dim
# for PP transfer (matches the 2D receive buffer).
return IntermediateTensors({"hidden_states": hidden_states.flatten(1)})
return IntermediateTensors(
{"hidden_states": hidden_states, "residual": residual}
)
if self.enable_ihc:
hidden_states = self.hc_head(hidden_states)
else:
hidden_states = hidden_states + residual
return self.norm(hidden_states)
def load_fused_expert_weights(
self,
name: str,
params_dict: dict,
loaded_weight: torch.Tensor,
shard_id: str,
num_experts: int,
) -> bool:
param = params_dict[name]
weight_loader = typing.cast(Callable[..., bool], param.weight_loader)
loaded_local_expert = False
for expert_id in range(num_experts):
curr_expert_weight = loaded_weight[expert_id]
success = weight_loader(
param,
curr_expert_weight,
name,
shard_id,
expert_id,
return_success=True,
)
if success:
loaded_local_expert = True
return loaded_local_expert
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
# FP8 indexer wk dequant buffer (weight and scale arrive separately).
pending_wk_fp8: dict[str, dict[str, torch.Tensor]] = {}
pp_missing_layer_names = get_pp_missing_layer_names(self)
skip_topk_layers = compute_skip_topk_layers(self.config)
# Must not be cached on `self`: `process_weights_after_loading` swaps in
# kernel-specific expert weights via `replace_parameter`, and a cache
# outliving this call would pin the pre-shuffle storage (OOM on large
# MoE) and make a later reload target orphaned tensors.
params_dict = dict(self.named_parameters())
# Split per-expert mapping (V3 style): experts.0.gate_proj.weight
split_expert_params_mapping = self.get_expert_mapping()
loaded_params: set[str] = set()
# Sink weights are sharded like the q/k/v linears.
sink_tp_size = get_tensor_model_parallel_world_size()
sink_tp_rank = get_tensor_model_parallel_rank()
n_local_head = self.config.num_attention_heads // sink_tp_size
head_rank_start = n_local_head * sink_tp_rank
head_rank_end = n_local_head * (sink_tp_rank + 1)
base_layer = (
"base_layer." if any(".base_layer." in name for name in params_dict) else ""
)
# Fused expert mapping: experts.gate_up_proj (all experts in one tensor).
# The packed weights are owned by the RoutedExperts submodule, so the
# targets are experts.routed_experts.[base_layer.]w{13,2}_weight.
fused_expert_prefix = f".experts.routed_experts.{base_layer}"
fused_expert_params_mapping = [
(f"{fused_expert_prefix}w13_weight", ".experts.gate_up_proj", 0, "w1"),
(f"{fused_expert_prefix}w2_weight", ".experts.down_proj", 0, "w2"),
]
num_experts = getattr(self.config, "num_experts", 0)
def _should_skip_missing_param(param_name: str) -> bool:
# Sparse checkpoints may contain indexer weights for layers that
# fall back to dense MLA on unsupported GPUs.
return ".indexer." in param_name
def _is_split_expert_weight(weight_name: str) -> bool:
"""Whether this weight is in split (per-expert) format."""
# Split format: mlp.experts.<id>.gate_proj.weight
return bool(re.search(r"\.experts\.\d+\.", weight_name))
def _is_fused_expert_weight(weight_name: str) -> bool:
"""Whether this weight is in fused (all-experts-packed) format."""
return ".experts.gate_up_proj" in weight_name or (
".experts.down_proj" in weight_name
and not _is_split_expert_weight(weight_name)
)
for name, loaded_weight in weights:
if is_skip_topk_indexer_weight(name, skip_topk_layers):
continue
if _try_load_fp8_indexer_wk(
name,
loaded_weight,
pending_wk_fp8,
params_dict,
loaded_params,
pp_missing_layer_names,
):
continue
if self.config.tie_word_embeddings and "lm_head.weight" in name:
continue
# Names and stacked shard ids are normalized upstream by
# AutoWeightsLoader, through quant_config.get_cache_scale_mapper()
# and hf_to_vllm_mapper.
stacked_shard_id = getattr(loaded_weight, "shard_id", None)
if ".indexer.wk." in name:
name = name.replace(".indexer.wk.", ".indexer.wk_weights_proj.")
stacked_shard_id = 0
# Skip loading extra bias for GPTQ models.
if name.endswith(".bias") and name not in params_dict:
continue
# Determine per-weight whether this is fused or split format.
is_fused_expert = _is_fused_expert_weight(name)
expert_params_mapping = (
fused_expert_params_mapping
if is_fused_expert
else split_expert_params_mapping
)
is_expert_weight = False
loaded_expert_param_names: set[str] = set()
for mapping in expert_params_mapping:
param_name, weight_name, expert_id, shard_id = mapping
if weight_name not in name:
continue
# This is an expert weight and must not be attempted as any
# other kind of weight later on.
is_expert_weight = True
# Do not modify `name`: the loop may continue past this point.
name_mapped = name.replace(weight_name, param_name)
if is_pp_missing_parameter(name_mapped, self):
continue
if is_fused_expert:
if "experts.gate_up_proj" in name:
chunks = loaded_weight.chunk(2, dim=-2)
success_w1 = self.load_fused_expert_weights(
name_mapped, params_dict, chunks[0], "w1", num_experts
)
success_w3 = self.load_fused_expert_weights(
name_mapped, params_dict, chunks[1], "w3", num_experts
)
success = success_w1 and success_w3
else:
success = self.load_fused_expert_weights(
name_mapped,
params_dict,
loaded_weight,
shard_id,
num_experts,
)
if success:
name = name_mapped
break
else:
# Split per-expert format (V3 style).
if name_mapped not in params_dict:
if _should_skip_missing_param(name_mapped):
continue
logger.warning_once(
"Skipping unknown checkpoint weight: %s",
name_mapped,
)
continue
param = params_dict[name_mapped]
# Ask the weight loader whether it succeeded, otherwise we
# may skip experts that have other available replicas.
weight_loader: Callable[..., typing.Any] = param.weight_loader
success = weight_loader(
param,
loaded_weight,
name_mapped,
shard_id=shard_id,
expert_id=expert_id,
return_success=True,
)
if success:
if not is_fused_expert:
loaded_expert_param_names.add(name_mapped)
continue
name = name_mapped
break
else:
if loaded_expert_param_names:
loaded_params.update(loaded_expert_param_names)
continue
if "learnable_sink_param" 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]
with torch.no_grad():
params_dict[name][:n].copy_(narrow_weight)
else:
if is_expert_weight:
# An expert weight that is not mapped to this rank.
continue
if "gate.e_score_correction_bias" in name:
name = name.replace(
"gate.e_score_correction_bias", "expert_bias"
)
if "router.gate." in name:
name = name.replace("router.", "")
if "hc_fn" in name:
name = name.replace("hc_fn", "hc_fn.weight")
if "hc_head_fn" in name:
name = name.replace("hc_head_fn", "hc_head_fn.weight")
if is_pp_missing_parameter(name, self):
continue
if name not in params_dict:
if _should_skip_missing_param(name):
continue
logger.warning_once(
"Skipping unknown checkpoint weight: %s",
name,
)
continue
param = params_dict[name]
weight_loader = getattr(
param, "weight_loader", default_weight_loader
)
if stacked_shard_id is None:
weight_loader(param, loaded_weight)
else:
weight_loader(param, loaded_weight, stacked_shard_id)
loaded_params.add(name)
return loaded_params
class HYV4ForCausalLM(nn.Module, SupportsPP, SupportsLoRA):
hf_to_vllm_mapper = WeightsMapper(
orig_to_new_stacked={
".q_a_proj": (".fused_qkv_a_proj", 0),
".kv_a_proj_with_mqa": (".fused_qkv_a_proj", 1),
".mlp.gate_proj": (".mlp.gate_up_proj", 0),
".mlp.up_proj": (".mlp.gate_up_proj", 1),
".shared_experts.gate_proj": (".shared_experts.gate_up_proj", 0),
".shared_experts.up_proj": (".shared_experts.gate_up_proj", 1),
".indexer.weights_proj.": (".indexer.wk_weights_proj.", 1),
}
)
packed_modules_mapping = {
"gate_up_proj": ["gate_proj", "up_proj"],
# MLA runs both latent down-projections as one GEMM.
"fused_qkv_a_proj": ["q_a_proj", "kv_a_proj_with_mqa"],
# The indexer fuses wk and weights_proj into one GEMM.
"wk_weights_proj": ["wk", "weights_proj"],
}
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.quant_config = quant_config
if quant_config is not None:
quant_config.packed_modules_mapping = self.packed_modules_mapping
parallel_config = vllm_config.parallel_config
eplb_config = parallel_config.eplb_config
self.num_redundant_experts = eplb_config.num_redundant_experts
self.model = HYV4Model(
vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model")
)
if get_pp_group().is_last_rank:
# The head stays in the model dtype; ``enable_lm_head_fp32`` is
# surfaced as ``head_dtype`` on the config (see HYV4Config), which
# makes LogitsProcessor accumulate the projection straight into
# fp32 instead of materializing an fp32 copy of the weight.
self.lm_head = ParallelLMHead(
config.vocab_size,
config.hidden_size,
quant_config=quant_config,
prefix=maybe_prefix(prefix, "lm_head"),
)
# With tie_word_embeddings, embed_tokens is kept on the last rank
# (see HYV4Model.__init__) so the weight can be shared here.
if self.config.tie_word_embeddings:
self.lm_head.weight = self.model.embed_tokens.weight
else:
self.lm_head = PPMissingLayer()
self.logits_processor = LogitsProcessor(config.vocab_size)
self.make_empty_intermediate_tensors = (
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 forward(
self,
input_ids: torch.Tensor,
positions: torch.Tensor,
intermediate_tensors: IntermediateTensors | None = None,
inputs_embeds: torch.Tensor | None = None,
) -> torch.Tensor | IntermediateTensors:
return self.model(input_ids, positions, intermediate_tensors, inputs_embeds)
def compute_logits(
self,
hidden_states: torch.Tensor,
) -> torch.Tensor | None:
logits = self.logits_processor(self.lm_head, hidden_states)
if getattr(self.config, "soft_logits_capping", False):
soft_cap = self.config.soft_logits_capping_logits
logits = soft_cap * torch.nn.functional.tanh(logits / soft_cap)
return logits
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
# MTP layers are loaded by the MTP head, not by the target model. They
# appear as model.mtp_layers.<i>.* and as the layer ids past the backbone.
mtp_start = self.config.num_hidden_layers
drop_prefixes: dict[str, str | None] = {"model.mtp_layers.": None}
for i in range(getattr(self.config, "num_nextn_predict_layers", 0)):
drop_prefixes[f"model.layers.{mtp_start + i}."] = None
if self.config.tie_word_embeddings:
drop_prefixes["lm_head."] = None
drop_mapper = WeightsMapper(orig_to_new_prefix=drop_prefixes)
loader = AutoWeightsLoader(self)
return loader.load_weights(weights, mapper=self.hf_to_vllm_mapper | drop_mapper)
def get_expert_mapping(self) -> list[tuple[str, str, int, str]]:
return self.model.get_expert_mapping()
+2
View File
@@ -758,6 +758,8 @@ class HYV4MLAAttention(nn.Module):
"""
if self.indexer is not None and self.is_sparse and not self.skip_topk:
self.indexer(hidden_states, q_c, positions, self.indexer_rope_emb)
if self.is_sparse:
self.mla_attn.impl.record_logical_topk_ready() # type: ignore[attr-defined]
out.copy_(
self.mla_attn(
q,
+2 -3
View File
@@ -271,8 +271,7 @@ class KimiK3DeltaAttention(GatedDeltaNetAttention):
self,
hidden_states: torch.Tensor,
positions: torch.Tensor,
output: torch.Tensor,
) -> None:
) -> torch.Tensor:
num_tokens = hidden_states.size(0)
projected_qkvgfab = self.in_proj_qkvgfab(hidden_states)[0]
@@ -306,7 +305,7 @@ class KimiK3DeltaAttention(GatedDeltaNetAttention):
core_attn_out=core_attn_out,
)
core_attn_out = rearrange(core_attn_out, "1 n h d -> n (h d)")
output[:] = self.o_proj(core_attn_out)[0]
return self.o_proj(core_attn_out)[0]
@eager_break_during_capture
def _forward(
+25 -16
View File
@@ -456,9 +456,8 @@ class KimiMLAAttention(nn.Module):
self,
positions: torch.Tensor,
hidden_states: torch.Tensor,
output: torch.Tensor,
) -> None:
output[:] = self.mla_attn(positions, hidden_states)
) -> torch.Tensor:
return self.mla_attn(positions, hidden_states)
class KimiDecoderLayer(nn.Module):
@@ -582,25 +581,29 @@ class KimiDecoderLayer(nn.Module):
positions: torch.Tensor,
hidden_states: torch.Tensor,
) -> torch.Tensor:
attn_output = torch.empty_like(hidden_states)
self.self_attn(
return self.self_attn(
hidden_states=hidden_states,
positions=positions,
output=attn_output,
)
return attn_output
def forward(
self,
positions: torch.Tensor,
hidden_states: torch.Tensor,
residual: torch.Tensor | None,
prefix_delta: torch.Tensor | None = None,
**kwargs,
) -> tuple[torch.Tensor, torch.Tensor]:
) -> (
tuple[torch.Tensor, torch.Tensor]
| tuple[torch.Tensor, torch.Tensor, torch.Tensor]
):
if self.use_attn_residuals:
assert residual is not None
return self.forward_attn_residual(positions, hidden_states, residual)
return self.forward_attn_residual(
positions, hidden_states, residual, prefix_delta
)
assert prefix_delta is None
# Self Attention
if residual is None:
residual = hidden_states
@@ -620,7 +623,8 @@ class KimiDecoderLayer(nn.Module):
positions: torch.Tensor,
hidden_states: torch.Tensor,
block_residual: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
prefix_delta: torch.Tensor | None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
prefix_sum = hidden_states
hidden_states = _apply_attn_res(
prefix_sum,
@@ -628,6 +632,7 @@ class KimiDecoderLayer(nn.Module):
self.self_attention_res_proj,
self.self_attention_res_norm,
self.prev_valid_blocks,
delta=prefix_delta,
output_norm=self.input_layernorm,
block_write_idx=(self.block_write_idx if self.is_block_write_layer else -1),
)
@@ -657,8 +662,7 @@ class KimiDecoderLayer(nn.Module):
)
hidden_states = self.mlp(hidden_states)
prefix_sum = prefix_sum + hidden_states
return prefix_sum, block_residual
return prefix_sum, block_residual, hidden_states
class KimiLinearModel(nn.Module, EagleModelMixin):
@@ -813,24 +817,28 @@ class KimiLinearModel(nn.Module, EagleModelMixin):
if residual is not None:
block_residual[:, : residual.size(1), :].copy_(residual)
residual = block_residual
prefix_delta = None
for layer_idx, layer in enumerate(
self.layers[self.start_layer : self.end_layer],
start=self.start_layer,
):
hidden_states, residual = layer(
hidden_states, residual, prefix_delta = layer(
positions=positions,
hidden_states=hidden_states,
residual=residual,
prefix_delta=prefix_delta,
)
if (layer_idx + 1) in self.aux_hidden_state_layers:
# AMD attn-res layer already returns prefix_sum + MLP delta as
# hidden_states; the override drops the block bank in residual.
self._maybe_add_hidden_state(
aux_hidden_states, layer_idx + 1, hidden_states, residual
aux_hidden_states,
layer_idx + 1,
hidden_states + prefix_delta,
residual,
)
if not get_pp_group().is_last_rank:
hidden_states = hidden_states + prefix_delta
return IntermediateTensors(
{"hidden_states": hidden_states, "residual": residual}
)
@@ -841,6 +849,7 @@ class KimiLinearModel(nn.Module, EagleModelMixin):
self.output_attn_res_proj,
self.output_attn_res_norm,
attn_res_block_num,
delta=prefix_delta,
)
# NOTE: the final norm is applied in compute_logits instead of here, so
# the MTP draft model receives the pre-norm hidden states.
+19 -104
View File
@@ -21,6 +21,10 @@ from vllm.model_executor.layers.linear import (
RowParallelLinear,
)
from vllm.model_executor.layers.mamba.gdn.base import GatedDeltaNetAttention
from vllm.model_executor.layers.mamba.kda_checkpoint import (
FlashKDAPrefillCheckpointExporter,
kda_prefill_checkpoint_alignment,
)
from vllm.model_executor.layers.mamba.mamba_utils import (
MambaStateDtypeCalculator,
MambaStateShapeCalculator,
@@ -49,7 +53,6 @@ from vllm.models.kimi_k3.nvidia.kda_metadata import (
from vllm.platforms import current_platform
from vllm.third_party.flash_linear_attention.ops.kda import FusedRMSNormGated
from vllm.transformers_utils.configs.kimi_linear import KimiLinearConfig
from vllm.triton_utils import tl, triton
from vllm.utils.flashinfer import (
flashinfer_fused_kda_decode,
flashinfer_recurrent_kda,
@@ -57,7 +60,6 @@ from vllm.utils.flashinfer import (
has_flashinfer_recurrent_kda,
)
from vllm.v1.attention.backend import AttentionBackend
from vllm.v1.attention.backends.utils import NULL_BLOCK_ID
from vllm.v1.kv_cache_interface import MambaSpec
from vllm.v1.worker.workspace import current_workspace_manager
@@ -389,69 +391,6 @@ def _flashinfer_kda_prefill(
return output, initial_state
@triton.jit
def _store_cache_checkpoints_kernel(
x_ptr,
conv_state_ptr,
recurrent_checkpoint_ptr,
recurrent_state_ptr,
query_start_loc_ptr,
checkpoint_offsets_ptr,
checkpoint_state_indices_ptr,
x_stride_0: tl.constexpr,
x_stride_1: tl.constexpr,
state_stride_0: tl.constexpr,
state_stride_1: tl.constexpr,
state_stride_2: tl.constexpr,
checkpoint_stride_0: tl.constexpr,
recurrent_state_stride_0: tl.constexpr,
checkpoint_offset_stride: tl.constexpr,
STATE_LEN: tl.constexpr,
WIDTH: tl.constexpr,
RECURRENT_ROW_SIZE: tl.constexpr,
NULL_STATE_IDX: tl.constexpr,
BLOCK_SIZE: tl.constexpr,
):
# store checkpoints to cache
seq_idx = tl.program_id(0)
cols = tl.program_id(1) * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
state_idx = tl.load(checkpoint_state_indices_ptr + seq_idx).to(tl.int64)
checkpoint_offset = tl.load(
checkpoint_offsets_ptr + seq_idx * checkpoint_offset_stride
)
valid_checkpoint = (state_idx != NULL_STATE_IDX) & (checkpoint_offset > 0)
valid_conv = (
(cols < WIDTH * STATE_LEN) & valid_checkpoint & (checkpoint_offset >= STATE_LEN)
)
width_idx = cols // STATE_LEN
history_idx = cols % STATE_LEN
checkpoint_end = tl.load(query_start_loc_ptr + seq_idx) + checkpoint_offset
token_idx = checkpoint_end - STATE_LEN + history_idx
values = tl.load(
x_ptr + token_idx * x_stride_0 + width_idx * x_stride_1,
mask=valid_conv,
)
tl.store(
conv_state_ptr
+ state_idx * state_stride_0
+ width_idx * state_stride_1
+ history_idx * state_stride_2,
values,
mask=valid_conv,
)
valid_recurrent = (cols < RECURRENT_ROW_SIZE) & valid_checkpoint
recurrent = tl.load(
recurrent_checkpoint_ptr + seq_idx * checkpoint_stride_0 + cols,
mask=valid_recurrent,
)
tl.store(
recurrent_state_ptr + state_idx * recurrent_state_stride_0 + cols,
recurrent,
mask=valid_recurrent,
)
def resolve_kda_prefill_backend(
backend: str,
head_dim: int,
@@ -735,6 +674,7 @@ class KimiK3DeltaAttention(GatedDeltaNetAttention):
self._flashinfer_kda_output_spec: tuple[tuple[int, ...], torch.dtype] | None = (
None
)
self._checkpoint_exporter: FlashKDAPrefillCheckpointExporter | None = None
if self.kda_prefill_backend == "flashkda":
T = vllm_config.scheduler_config.max_num_batched_tokens
N = vllm_config.scheduler_config.max_num_seqs
@@ -748,6 +688,7 @@ class KimiK3DeltaAttention(GatedDeltaNetAttention):
((N, H, D, D), self.get_state_dtype()[1]),
((workspace_size,), torch.uint8),
)
self._checkpoint_exporter = FlashKDAPrefillCheckpointExporter()
elif self.kda_prefill_backend == "flashinfer":
T = vllm_config.scheduler_config.max_num_batched_tokens
H, D = self.local_num_heads, self.head_dim
@@ -783,7 +724,7 @@ class KimiK3DeltaAttention(GatedDeltaNetAttention):
)
self.gemm_rs_ar = None
if run_gemm_rs_ar:
from vllm.models.kimi_k3.nvidia.ops.cute_dsl.gemm_rs_ar import (
from vllm.model_executor.kernels.linear.cute_dsl.gemm_rs_ar import (
get_gemm_rs_ar,
)
@@ -800,12 +741,11 @@ class KimiK3DeltaAttention(GatedDeltaNetAttention):
def get_kv_cache_spec(self, vllm_config: VllmConfig) -> MambaSpec:
spec = super().get_kv_cache_spec(vllm_config)
assert isinstance(spec, MambaSpec)
alignment = kda_prefill_checkpoint_alignment(self.kda_prefill_backend)
return replace(
spec,
num_prefill_checkpoint_blocks=int(self.kda_prefill_backend == "flashkda"),
prefill_checkpoint_alignment=(
16 if self.kda_prefill_backend == "flashkda" else None
),
num_prefill_checkpoint_blocks=int(alignment is not None),
prefill_checkpoint_alignment=alignment,
)
def forward(
@@ -869,7 +809,7 @@ class KimiK3DeltaAttention(GatedDeltaNetAttention):
)
core_attn_out = rearrange(core_attn_out, "1 n h d -> n (h d)")
if self.gemm_rs_ar is not None and self.gemm_rs_ar.should_run(core_attn_out):
return self.gemm_rs_ar(core_attn_out, self.o_proj.weight)
return self.gemm_rs_ar.apply(core_attn_out, self.o_proj)
return self.o_proj(core_attn_out)[0]
@eager_break_during_capture
@@ -1173,39 +1113,14 @@ class KimiK3DeltaAttention(GatedDeltaNetAttention):
)
core_attn_out_non_spec = flashkda_out
last_recurrent_state = final_state
state_len = conv_state.shape[-1]
width = mixed_qkv_ns.shape[-1]
recurrent_row_size = checkpoint_state[0].numel()
block_size = 256
_store_cache_checkpoints_kernel[
(
checkpoint_offsets.numel(),
triton.cdiv(
max(width * state_len, recurrent_row_size),
block_size,
),
)
](
mixed_qkv_ns,
conv_state,
checkpoint_state,
recurrent_state,
non_spec_query_start_loc,
checkpoint_offsets,
checkpoint.state_indices,
mixed_qkv_ns.stride(0),
mixed_qkv_ns.stride(1),
conv_state.stride(0),
conv_state.stride(1),
conv_state.stride(2),
checkpoint_state.stride(0),
recurrent_state.stride(0),
checkpoint_offsets.stride(0),
state_len,
width,
recurrent_row_size,
NULL_BLOCK_ID,
block_size,
assert self._checkpoint_exporter is not None
self._checkpoint_exporter.export(
checkpoint,
raw_qkv=mixed_qkv_ns,
conv_state=conv_state,
recurrent_checkpoint=checkpoint_state,
recurrent_state=recurrent_state,
cu_seqlens=non_spec_query_start_loc,
)
else:
(
+19 -87
View File
@@ -18,9 +18,12 @@ from typing import TYPE_CHECKING
import torch
from vllm.config import VllmConfig
from vllm.model_executor.layers.mamba.checkpoint import (
MambaPrefillCheckpointBuilder,
MambaPrefillCheckpointMetadata,
)
from vllm.platforms import current_platform
from vllm.triton_utils import tl, triton
from vllm.utils.math_utils import cdiv
from vllm.utils.torch_utils import async_tensor_h2d
from vllm.v1.attention.backend import CommonAttentionMetadata
from vllm.v1.attention.backends.gdn_attn import (
@@ -37,11 +40,7 @@ from vllm.v1.attention.backends.utils import (
compute_causal_conv1d_metadata,
split_decodes_and_prefills,
)
from vllm.v1.kv_cache_interface import (
MambaSpec,
get_mamba_prefill_checkpoint_position,
is_mamba_prefill_checkpoint_valid,
)
from vllm.v1.kv_cache_interface import MambaSpec
if TYPE_CHECKING:
from vllm.models.kimi_k3.nvidia.ops.recoverssm import (
@@ -262,12 +261,6 @@ class KDARecoverSSMCommitMetadata:
align: KDARecoverSSMAlignMetadata | None
@dataclass
class KDACheckpointMetadata:
checkpoint_offsets: torch.Tensor
state_indices: torch.Tensor
@dataclass
class KimiK3KDAMetadata(GDNAttentionMetadata, RecoverSSMMetadata):
spec_token_start: int | None = None
@@ -278,7 +271,7 @@ class KimiK3KDAMetadata(GDNAttentionMetadata, RecoverSSMMetadata):
recoverssm_context: "KDARecoverSSMCommitContext | None" = field(
default=None, repr=False, compare=False
)
checkpoint: KDACheckpointMetadata | None = None
checkpoint: MambaPrefillCheckpointMetadata | None = None
def commit_recoverssm_state(
self, num_accepted_tokens: torch.Tensor
@@ -322,6 +315,9 @@ class KimiK3KDAMetadataBuilder(GDNAttentionMetadataBuilder):
device: torch.device,
) -> None:
super().__init__(kv_cache_spec, layer_names, vllm_config, device)
self.checkpoint_builder = MambaPrefillCheckpointBuilder(
vllm_config, kv_cache_spec
)
additional_config = vllm_config.additional_config
self.use_flashinfer_prefill = (
isinstance(additional_config, dict)
@@ -400,8 +396,10 @@ class KimiK3KDAMetadataBuilder(GDNAttentionMetadataBuilder):
if not self.use_spec_decode or num_decode_draft_tokens_cpu is None:
spec_sequence_masks_cpu = None
num_spec_decodes = 0
active_non_spec_mask_cpu = None
else:
spec_sequence_masks_cpu = num_decode_draft_tokens_cpu >= 0
active_non_spec_mask_cpu = None
if self.use_recoverssm:
assert m.is_prefilling is not None
assert m.is_prefilling.device.type == "cpu"
@@ -418,6 +416,7 @@ class KimiK3KDAMetadataBuilder(GDNAttentionMetadataBuilder):
):
spec_sequence_masks_cpu = None
num_spec_decodes = 0
active_non_spec_mask_cpu = None
else:
num_spec_decodes = spec_sequence_masks_cpu.sum().item()
if num_spec_decodes == 0:
@@ -624,80 +623,6 @@ class KimiK3KDAMetadataBuilder(GDNAttentionMetadataBuilder):
else:
has_initial_state = None
checkpoint = None
checkpoint_enabled = (
self.vllm_config.cache_config.mamba_cache_mode == "align"
and self.kv_cache_spec.num_prefill_checkpoint_blocks > 0
)
if num_prefills > 0 and checkpoint_enabled:
# prepare checkpoint metadata
assert m.seq_lens_cpu_upper_bound is not None
request_rows = list(range(m.num_reqs))
if spec_sequence_masks_cpu is not None:
# get non spec request rows
request_rows = active_non_spec_mask_cpu.nonzero().flatten().tolist()
all_query_lens = query_start_loc_cpu.diff().tolist()
query_lens = [all_query_lens[row] for row in request_rows]
seq_lens = m.seq_lens_cpu_upper_bound.tolist()
block_size = self.kv_cache_spec.block_size
hash_block_size = (
self.vllm_config.cache_config.prefix_match_unit or block_size
)
speculative_config = self.vllm_config.speculative_config
drop_eagle_block = (
speculative_config is not None
and speculative_config.use_eagle_block_drop()
)
checkpoint_splits = []
checkpoint_cols = []
for row, query_len in zip(request_rows, query_lens):
seq_len = seq_lens[row]
query_start = seq_len - query_len
checkpoint_position = get_mamba_prefill_checkpoint_position(
seq_len,
hash_block_size,
drop_eagle_block=drop_eagle_block,
)
offset = checkpoint_position - query_start
valid = is_mamba_prefill_checkpoint_valid(
query_start=query_start,
query_end=seq_len,
checkpoint_position=checkpoint_position,
hash_block_size=hash_block_size,
mamba_block_size=block_size,
checkpoint_alignment=(
self.kv_cache_spec.prefill_checkpoint_alignment
),
)
offset = offset if valid else 0
first_len = offset or query_len
checkpoint_splits.append((first_len, query_len - first_len))
checkpoint_cols.append(cdiv(seq_len, block_size) - 2 if valid else -1)
if any(tail for _, tail in checkpoint_splits):
checkpoint_offsets_tensor = async_tensor_h2d(
[first if tail else 0 for first, tail in checkpoint_splits],
dtype=torch.int32,
device=query_start_loc.device,
)
request_rows_tensor = async_tensor_h2d(
request_rows, dtype=torch.int64, device=query_start_loc.device
)
checkpoint_cols_tensor = async_tensor_h2d(
checkpoint_cols, dtype=torch.int64, device=query_start_loc.device
)
checkpoint_state_indices = m.block_table_tensor[
request_rows_tensor, checkpoint_cols_tensor
]
checkpoint_state_indices = torch.where(
checkpoint_cols_tensor >= 0,
checkpoint_state_indices,
NULL_BLOCK_ID,
)
checkpoint = KDACheckpointMetadata(
checkpoint_offsets_tensor,
checkpoint_state_indices,
)
# Prepare per-request tensors for cudagraph replay. num_actual_tokens
# may be token-padded, while state/query/acceptance metadata is indexed
# by request.
@@ -776,6 +701,13 @@ class KimiK3KDAMetadataBuilder(GDNAttentionMetadataBuilder):
flashinfer_prefill_query_start_loc.diff(), descending=True
).to(torch.int32)
checkpoint = None
if num_prefills > 0:
request_rows = list(range(m.num_reqs))
if active_non_spec_mask_cpu is not None:
request_rows = active_non_spec_mask_cpu.nonzero().flatten().tolist()
checkpoint = self.checkpoint_builder.build(m, request_rows)
return KimiK3KDAMetadata(
num_prefills=num_prefills,
num_prefill_tokens=num_prefill_tokens,
+2 -2
View File
@@ -301,7 +301,7 @@ class MultiHeadLatentAttention(nn.Module, AttentionLayerBase):
)
self.gemm_rs_ar = None
if run_gemm_rs_ar:
from vllm.models.kimi_k3.nvidia.ops.cute_dsl.gemm_rs_ar import (
from vllm.model_executor.kernels.linear.cute_dsl.gemm_rs_ar import (
get_gemm_rs_ar,
)
@@ -631,7 +631,7 @@ class MultiHeadLatentAttention(nn.Module, AttentionLayerBase):
attn_out = _gate_sigmoid_mul(attn_out, gate)
if self.gemm_rs_ar is not None and self.gemm_rs_ar.should_run(attn_out):
return self.gemm_rs_ar(attn_out, self.o_proj.weight)
return self.gemm_rs_ar.apply(attn_out, self.o_proj)
return self.o_proj(attn_out)[0]
+13 -55
View File
@@ -160,54 +160,23 @@ def maybe_init_gemm_rs_ar(vllm_config: VllmConfig, use_sequence_parallel: bool)
# its singleton to exactly one mode.
all_reduce = not use_sequence_parallel
mode = "GEMM-AR" if all_reduce else "GEMM-RS"
enabled = envs.VLLM_KIMI_K3_GEMM_AR if all_reduce else envs.VLLM_KIMI_K3_GEMM_RS
enabled = envs.VLLM_KIMI_K3_GEMM_AR if all_reduce else envs.VLLM_ENABLE_GEMM_RS
if not enabled:
return False
parallel_config = vllm_config.parallel_config
tp_size = parallel_config.tensor_parallel_size
if parallel_config.use_ubatching:
reason = "ubatching is enabled"
elif vllm_config.model_config.dtype != torch.bfloat16:
reason = "the model dtype is not BF16"
elif not current_platform.is_cuda():
reason = "the device is not CUDA"
elif not current_platform.is_device_capability_family(100):
reason = "the device is not SM100-family"
elif not 1 < tp_size <= 16:
reason = "TP size is not in the supported range 2-16"
elif 128 % tp_size != 0:
reason = "TP size does not divide 128"
else:
reason = None
if reason is not None:
logger.warning_once("%s is disabled because %s.", mode, reason)
return False
from vllm.models.kimi_k3.nvidia.ops.cute_dsl.gemm_rs_ar import init_gemm_rs_ar
# The kernel module pulls in cute_dsl, so import it only once the flag
# asks for it.
from vllm.model_executor.kernels.linear.cute_dsl.gemm_rs_ar import (
maybe_init_gemm_rs_ar as maybe_init_shared_gemm_rs_ar,
)
config = vllm_config.model_config.hf_text_config
try:
init_gemm_rs_ar(
max_M=vllm_config.scheduler_config.max_num_batched_tokens,
N=config.hidden_size,
all_reduce=all_reduce,
)
except RuntimeError as e:
logger.warning_once(
"%s is disabled because initialization failed: %s. This may mean "
"the TP ranks do not share one NVLink domain.",
mode,
e,
)
if not maybe_init_shared_gemm_rs_ar(
vllm_config, N=config.hidden_size, all_reduce=all_reduce
):
return False
if all_reduce:
logger.info_once(
"GEMM-AR is enabled. To disable it, set VLLM_KIMI_K3_GEMM_AR=0."
)
else:
logger.info_once("GEMM-RS is enabled.")
flag = "VLLM_KIMI_K3_GEMM_AR" if all_reduce else "VLLM_ENABLE_GEMM_RS"
logger.info_once("To disable %s, set %s=0.", mode, flag)
return True
@@ -276,7 +245,7 @@ class KimiMLP(nn.Module):
not use_sequence_parallel and reduce_results
)
if use_gemm_rs_ar and run_gemm_rs_ar:
from vllm.models.kimi_k3.nvidia.ops.cute_dsl.gemm_rs_ar import (
from vllm.model_executor.kernels.linear.cute_dsl.gemm_rs_ar import (
get_gemm_rs_ar,
)
@@ -309,7 +278,7 @@ class KimiMLP(nn.Module):
x = self.act_fn(gate_up)
if self.gemm_rs_ar is not None and self.gemm_rs_ar.should_run(x):
return self.gemm_rs_ar(x, self.down_proj.weight)
return self.gemm_rs_ar.apply(x, self.down_proj)
x, _ = self.down_proj(x)
if self.shard_sequence_parallel:
@@ -922,14 +891,12 @@ class KimiDecoderLayer(nn.Module):
aux_stream=aux_stream,
run_gemm_rs_ar=run_gemm_rs_ar,
)
self._self_attn_writes_output = False
else:
self.self_attn = KimiLinearGatedDeltaNetAttention(
config,
vllm_config,
prefix=f"{prefix}.self_attn",
)
self._self_attn_writes_output = True
else:
qk_nope_head_dim = config.qk_nope_head_dim
qk_rope_head_dim = config.qk_rope_head_dim
@@ -959,7 +926,6 @@ class KimiDecoderLayer(nn.Module):
aux_stream=aux_stream,
run_gemm_rs_ar=run_gemm_rs_ar,
)
self._self_attn_writes_output = False
if self.use_sequence_parallel:
self.self_attn.o_proj.reduce_results = False
@@ -1025,14 +991,6 @@ class KimiDecoderLayer(nn.Module):
positions: torch.Tensor,
hidden_states: torch.Tensor,
) -> torch.Tensor:
if self._self_attn_writes_output:
output = torch.empty_like(hidden_states)
self.self_attn(
hidden_states=hidden_states,
positions=positions,
output=output,
)
return output
return self.self_attn(
hidden_states=hidden_states,
positions=positions,
@@ -1,894 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""SM100 BF16 GEMM with fused tensor-parallel reduce-scatter/all-reduce."""
# Based on CUTLASS's Blackwell distributed GEMM-RS example at dcf215a.
# See https://github.com/NVIDIA/cutlass/issues/3117 for memory semantics.
from functools import cache
import cutlass
import torch
import torch.distributed._symmetric_memory as symm_mem
from cuda.bindings.driver import CUstream
from cutlass import BFloat16, Int32, Int64, Uint16, cute, utils
from cutlass._mlir import ir
from cutlass._mlir.dialects import llvm, nvvm, vector
from cutlass.cute.nvgpu import cpasync, tcgen05
from cutlass.cute.runtime import make_fake_stream, make_fake_tensor, make_ptr, nullptr
from cutlass.cutlass_dsl import dsl_user_op
from cutlass.utils import get_smem_capacity_in_bytes
from vllm.cute_utils import _tcgen05, mbarrier, simple_tma_copy, to_cta0_smem
from vllm.distributed import get_tp_group
from vllm.logger import init_logger
from vllm.model_executor.layers.linear import LinearBase, UnquantizedLinearMethod
logger = init_logger(__name__)
@dsl_user_op
def nanosleep(ns: int, *, loc=None, ip=None) -> None:
nvvm.nanosleep(Int32(ns).ir_value(loc=loc, ip=ip), loc=loc, ip=ip)
@dsl_user_op
def multimem_ld_reduce_16B(x: cute.Tensor, *, loc=None, ip=None) -> cute.Tensor:
# The vector instruction assumes x is contiguous and 16-byte aligned.
assert x.element_type == BFloat16
vec_type = ".v4.bf16x2"
ptr = x.iterator.toint(loc=loc, ip=ip).ir_value(loc=loc, ip=ip)
asm = (
"multimem.ld_reduce.relaxed.gpu.global.add.acc::f32"
f"{vec_type} {{$0, $1, $2, $3}}, [$4];"
)
struct = llvm.inline_asm(
llvm.StructType.get_literal([Int32.mlir_type] * 4),
[ptr],
asm,
"=r,=r,=r,=r,l",
has_side_effects=True,
loc=loc,
ip=ip,
)
vec = vector.from_elements(
ir.VectorType.get([4], Int32.mlir_type, loc=loc),
[
llvm.extractvalue(Int32.mlir_type, struct, [i], loc=loc, ip=ip)
for i in range(4)
],
loc=loc,
ip=ip,
)
ssa = cute.TensorSSA(vec, 4, Int32)
y = cute.make_rmem_tensor(4, Int32)
y.store(ssa)
return cute.recast_tensor(y, x.element_type)
@dsl_user_op
def multimem_st_16B(dst: cute.Tensor, value: cute.Tensor, *, loc=None, ip=None) -> None:
# The vector instruction assumes dst and value are contiguous BF16x8 vectors
# and dst is 16-byte aligned.
assert dst.element_type == BFloat16
assert value.element_type == BFloat16
ptr = dst.iterator.toint(loc=loc, ip=ip).ir_value(loc=loc, ip=ip)
regs = cute.recast_tensor(value, Int32, loc=loc, ip=ip)
llvm.inline_asm(
None,
[ptr] + [regs[i].ir_value(loc=loc, ip=ip) for i in range(4)],
"multimem.st.relaxed.sys.global.v4.f32 [$0], {$1, $2, $3, $4};",
"l,r,r,r,r",
has_side_effects=True,
loc=loc,
ip=ip,
)
class Sm100GemmRsArBF16:
def __init__(
self,
rank: int,
num_ranks: int,
BN: int = 128,
cta_group: int = 1,
all_reduce: bool = False,
) -> None:
self.rank = rank
self.num_ranks = num_ranks
BM, BK = 128, 64
self.cta_tile = (BM, BN, BK)
self.cta_group = cta_group
self.all_reduce = all_reduce
smem_bytes = get_smem_capacity_in_bytes()
self.stage_size = (BM + (BN // cta_group)) * BK * 2
self.num_stages = smem_bytes // self.stage_size
@cute.jit
def prepare_tma(
self, tensor: cute.Tensor, BM: cutlass.Constexpr, BK: cutlass.Constexpr
) -> cpasync.TmaInfo:
tma_group = (
tcgen05.CtaGroup.TWO if self.cta_group == 2 else tcgen05.CtaGroup.ONE
)
tma_op = cpasync.CopyBulkTensorTileG2SOp(cta_group=tma_group)
swizzle_128b = cute.make_swizzle(3, 4, 3)
layout = cute.make_layout(
(BM, BK, self.num_stages),
stride=(BK, 1, BM * BK),
)
layout = cute.make_composed_layout(swizzle_128b, 0, layout)
return cpasync.make_tiled_tma_atom(tma_op, tensor, layout, (BM, BK))
@cute.jit
def __call__(
self,
A: cute.Tensor,
B: cute.Tensor,
partial_uc: cute.Tensor,
partial_mc_ptr: cute.Pointer,
output: cute.Tensor,
flags_uc: cute.Tensor,
flags_mc_ptr: cute.Pointer,
peer_flag_ptr: cute.Pointer,
grid_size: Int32,
stream: CUstream,
) -> None:
N = B.shape[0]
BM, BN, BK = self.cta_tile
A_tma = self.prepare_tma(A, BM, BK)
B_tma = self.prepare_tma(B, BN // self.cta_group, BK)
padded_M = partial_uc.shape[0]
partial_mc = cute.make_tensor(
partial_mc_ptr,
cute.make_layout((padded_M, N), stride=(N, 1)),
)
peer_flags = cute.make_tensor(
peer_flag_ptr,
cute.make_layout(self.num_ranks),
)
grid = (grid_size, 1, 1)
block = (10 * 32, 1, 1)
cluster = (self.cta_group, 1, 1)
self.kernel(
A_tma,
B_tma,
partial_uc,
partial_mc,
output,
flags_uc.iterator,
flags_mc_ptr,
peer_flags,
).launch(grid=grid, block=block, cluster=cluster, stream=stream)
@cute.kernel
def kernel(
self,
A_tma: cpasync.TmaInfo,
B_tma: cpasync.TmaInfo,
partial_uc: cute.Tensor,
partial_mc: cute.Tensor,
output: cute.Tensor,
flags_uc_ptr: cute.Pointer,
flags_mc_ptr: cute.Pointer,
peer_flags: cute.Tensor,
) -> None:
tid, _, _ = cute.arch.thread_idx()
raw_bid, _, _ = cute.arch.block_idx()
num_bids, _, _ = cute.arch.grid_dim()
warp_id = cute.arch.make_warp_uniform(tid // 32)
BM, BN, BK = self.cta_tile
cta_group = self.cta_group
num_stages = self.num_stages
num_ranks = self.num_ranks
is_2cta = cta_group == 2
cta_rank = raw_bid % self.cta_group
num_tmem_stages = 512 // BN
smem = utils.SmemAllocator()
sA = smem.allocate_tensor(
BFloat16,
A_tma.smem_layout.outer,
byte_alignment=128,
swizzle=A_tma.smem_layout.inner,
)
sB = smem.allocate_tensor(
BFloat16,
B_tma.smem_layout.outer,
byte_alignment=128,
swizzle=B_tma.smem_layout.inner,
)
tma_full_mbar = smem.allocate_array(Int64, num_stages)
tma_empty_mbar = smem.allocate_array(Int64, num_stages)
tmem_full_mbar = smem.allocate_array(Int64, num_tmem_stages)
tmem_empty_mbar = smem.allocate_array(Int64, num_tmem_stages)
taddr = smem.allocate(Int32, 4)
# Named barriers
BAR_TMEM_ALLOC = 1
BAR_EPILOGUE = 2
BAR_COMM = 3
M, K = A_tma.tma_tensor.shape
N, _ = B_tma.tma_tensor.shape
local_M = (
partial_uc.shape[0] // num_ranks if self.all_reduce else output.shape[0]
)
grid_m = cute.ceil_div(M, BM)
# Keep 2-CTA clusters within a single N tile.
grid_m = cute.ceil_div(grid_m, cta_group) * cta_group
grid_n = cute.ceil_div(N, BN)
if warp_id == 0:
with cute.arch.elect_one():
for i in cutlass.range_constexpr(num_stages):
cute.arch.mbarrier_init(tma_full_mbar + i, cta_group)
cute.arch.mbarrier_init(tma_empty_mbar + i, 1)
for i in cutlass.range_constexpr(num_tmem_stages):
cute.arch.mbarrier_init(tmem_full_mbar + i, 1)
cute.arch.mbarrier_init(tmem_empty_mbar + i, 128 * cta_group)
cute.arch.mbarrier_init_fence()
elif warp_id == 1:
cpasync.prefetch_descriptor(A_tma.atom)
cpasync.prefetch_descriptor(B_tma.atom)
if cutlass.const_expr(is_2cta):
cute.arch.cluster_arrive_relaxed()
cute.arch.cluster_wait()
else:
cute.arch.sync_threads()
total_tiles = grid_m * grid_n
if warp_id == 9:
# TMA warp
tma_stage = 0
parity = 1
if cutlass.const_expr(is_2cta):
tma_full_mbar_ = to_cta0_smem(tma_full_mbar)
else:
tma_full_mbar_ = tma_full_mbar
# Select global-memory tiles.
# [(BM, BK), (M/BM, K/BK)]
gA_tiles = cute.zipped_divide(A_tma.tma_tensor, (BM, BK))
gB_tiles = cute.zipped_divide(B_tma.tma_tensor, (BN // cta_group, BK))
for bid in range(raw_bid, total_tiles, num_bids):
bid_m = bid % grid_m
bid_n = bid // grid_m
if cutlass.const_expr(cta_group == 2):
bid_n = bid_n * cta_group + cta_rank
for iter_k in cutlass.range(cute.ceil_div(K, BK), unroll=1):
mbar = tma_full_mbar_ + tma_stage
cute.arch.mbarrier_wait(tma_empty_mbar + tma_stage, parity)
with cute.arch.elect_one():
mbarrier.arrive_expect_tx(mbar, self.stage_size, "cluster")
simple_tma_copy(
A_tma.atom,
gA_tiles[None, (bid_m, iter_k)],
sA[None, None, tma_stage],
mbar,
)
simple_tma_copy(
B_tma.atom,
gB_tiles[None, (bid_n, iter_k)],
sB[None, None, tma_stage],
mbar,
)
tma_stage = (tma_stage + 1) % num_stages
if tma_stage == 0:
parity ^= 1
elif warp_id == 8:
# MMA warp
cute.arch.barrier(barrier_id=BAR_TMEM_ALLOC, number_of_threads=5 * 32)
if cta_rank == 0:
tma_stage = 0
tma_full_parity = 0
tmem_stage = 0
tmem_empty_parity = 1
MMA_M = BM * cta_group
MMA_N = BN
idesc = _tcgen05.make_bf16_idesc(MMA_M, MMA_N)
sdesc = _tcgen05.make_sdesc_128B_swizzle(0)
multicast_mask = Uint16((1 << self.cta_group) - 1)
for bid in range(raw_bid, total_tiles, num_bids):
cute.arch.mbarrier_wait(
tmem_empty_mbar + tmem_stage, tmem_empty_parity
)
_tcgen05.fence_after_thread_sync()
for iter_k in cutlass.range(cute.ceil_div(K, BK), unroll=1):
d_tmem = BN * tmem_stage
a_addr = sA[None, None, tma_stage].iterator.toint()
b_addr = sB[None, None, tma_stage].iterator.toint()
a_desc = sdesc | (a_addr >> 4)
b_desc = sdesc | (b_addr >> 4)
cute.arch.mbarrier_wait(
tma_full_mbar + tma_stage, tma_full_parity
)
_tcgen05.fence_after_thread_sync()
for mma_k in cutlass.range_constexpr(BK // 16):
enable_d = iter_k > 0 or mma_k > 0
_tcgen05.mma_f16(
d_tmem, a_desc, b_desc, idesc, enable_d, cta_group
)
a_desc += 32 >> 4
b_desc += 32 >> 4
_tcgen05.commit(
tma_empty_mbar + tma_stage, multicast_mask, cta_group
)
tma_stage = (tma_stage + 1) % num_stages
if tma_stage == 0:
tma_full_parity ^= 1
_tcgen05.commit(
tmem_full_mbar + tmem_stage, multicast_mask, cta_group
)
tmem_stage = (tmem_stage + 1) % num_tmem_stages
if tmem_stage == 0:
tmem_empty_parity ^= 1
elif warp_id >= 4:
# Communication warps
# Keep epilogue in warps 0-3 and communication in warps 4-7.
# Swapping the warpgroups can hang due to warp scheduling.
tid_ = tid % 128
# Offset in the [M, N] GEMM result.
rank_start = self.rank * local_M
rank_end = min(rank_start + local_M, M)
st_atom = cute.make_copy_atom(
cute.nvgpu.CopyUniversalOp(), BFloat16, num_bits_per_copy=128
)
# Each thread issues one BF16x8 multimem reduction per vector.
vec_width = 8
vec_cols = BN // vec_width
max_tile_rows = BM // num_ranks
vecs_per_tile = max_tile_rows * vec_cols
partial_vecs = cute.zipped_divide(partial_mc, (1, vec_width))
if cutlass.const_expr(not self.all_reduce):
output_vecs = cute.zipped_divide(output, (1, vec_width))
for tile_id in range(raw_bid, total_tiles, num_bids):
rs_bid_m = tile_id % grid_m
bid_n = tile_id // grid_m
local_row_start = rs_bid_m * local_M // grid_m
local_row_end = (rs_bid_m + 1) * local_M // grid_m
global_row_start = rank_start + local_row_start
global_row_end = min(rank_start + local_row_end, M)
if global_row_start < M:
# Map the current RS tile to the required GEMM tiles.
# Since an RS tile is smaller than a GEMM tile, each RS tile
# can overlap at most 2 GEMM tiles.
gemm_bid_m0 = global_row_start // BM
gemm_bid_m1 = max(global_row_end - 1, global_row_start) // BM
# Poll local L2 with relaxed GPU-scope loads. The following
# multimem reduction reads every rank's L2 directly, so no
# acquire fence or L1 invalidation is needed.
if tid_ == 0:
# Poll the 1st GEMM tile.
flag_ptr = flags_uc_ptr + bid_n * grid_m + gemm_bid_m0
arrivals = cute.arch.load(
flag_ptr, Int32, sem="relaxed", scope="gpu"
)
while arrivals < num_ranks:
nanosleep(64)
arrivals = cute.arch.load(
flag_ptr, Int32, sem="relaxed", scope="gpu"
)
elif tid_ == 32 and gemm_bid_m1 != gemm_bid_m0:
# Poll the 2nd GEMM tile with another warp if needed.
flag_ptr = flags_uc_ptr + bid_n * grid_m + gemm_bid_m1
arrivals = cute.arch.load(
flag_ptr, Int32, sem="relaxed", scope="gpu"
)
while arrivals < num_ranks:
nanosleep(64)
arrivals = cute.arch.load(
flag_ptr, Int32, sem="relaxed", scope="gpu"
)
cute.arch.barrier(barrier_id=BAR_COMM, number_of_threads=128)
# Issue multimem.ld_reduce before storing any result.
reduced_vecs = []
for vec_iter in cutlass.range_constexpr(vecs_per_tile // 128):
vec_idx = tid_ + vec_iter * 128
local_row = local_row_start + vec_idx // vec_cols
global_row = rank_start + local_row
col = bid_n * vec_cols + vec_idx % vec_cols
reduced_vec = cute.make_rmem_tensor(vec_width, BFloat16)
if local_row < local_row_end and global_row < M:
tmp = multimem_ld_reduce_16B(
partial_vecs[None, (global_row, col)]
)
reduced_vec.store(tmp.load())
reduced_vecs.append(reduced_vec)
for vec_iter in cutlass.range_constexpr(vecs_per_tile // 128):
vec_idx = tid_ + vec_iter * 128
local_row = local_row_start + vec_idx // vec_cols
global_row = rank_start + local_row
col = bid_n * vec_cols + vec_idx % vec_cols
if local_row < local_row_end and global_row < M:
if cutlass.const_expr(self.all_reduce):
# Broadcast the result to all ranks.
multimem_st_16B(
partial_vecs[None, (global_row, col)],
reduced_vecs[vec_iter],
)
else:
# Store the result to local L2.
cute.copy(
st_atom,
reduced_vecs[vec_iter],
output_vecs[None, (local_row, col)],
)
cute.arch.barrier(barrier_id=BAR_COMM, number_of_threads=128)
# Release each GEMM tile consumed by this RS tile. The last
# consumer resets its producer flag for the next launch.
def release_gemm_tile(
gemm_bid_m,
tile_M,
logical_M,
rank_start,
rank_end,
local_M,
grid_m,
tile_N,
flags,
num_ranks,
):
gemm_start = gemm_bid_m * tile_M
gemm_end = min(gemm_start + tile_M, logical_M)
local_start = max(gemm_start, rank_start) - rank_start
local_end = min(gemm_end, rank_end) - rank_start
# Compute the number of consumers to identify the last
# arrival, which resets the producer flag.
first_rs_tile = (
cute.ceil_div((local_start + 1) * grid_m, local_M) - 1
)
last_rs_tile = cute.ceil_div(local_end * grid_m, local_M) - 1
num_consumers = last_rs_tile - first_rs_tile + 1
flag_ptr = flags + tile_N * grid_m + gemm_bid_m
old_count = cute.arch.atomic_add(
flag_ptr, Int32(1), sem="relaxed", scope="gpu"
)
if old_count == num_ranks + num_consumers - 1:
cute.arch.store(
flag_ptr, Int32(0), sem="relaxed", scope="gpu"
)
if tid_ == 0:
# Arrive at the 1st GEMM tile.
release_gemm_tile(
gemm_bid_m0,
BM,
M,
rank_start,
rank_end,
local_M,
grid_m,
bid_n,
flags_uc_ptr,
num_ranks,
)
elif tid_ == 32 and gemm_bid_m1 != gemm_bid_m0:
# Arrive at the 2nd GEMM tile if necessary.
release_gemm_tile(
gemm_bid_m1,
BM,
M,
rank_start,
rank_end,
local_M,
grid_m,
bid_n,
flags_uc_ptr,
num_ranks,
)
# Exit barrier. GPU scope is sufficient for RS because the kernel
# writes local global memory and only needs to flush it to local L2.
# AR uses system scope to flush the multimem stores to remote L2.
cute.arch.barrier(barrier_id=BAR_COMM, number_of_threads=128)
if tid_ == 0:
exit_flag = total_tiles + raw_bid
scope = "sys" if self.all_reduce else "gpu"
utils.distributed.multimem_red_add1(
flags_mc_ptr + exit_flag, order="release", scope=scope
)
utils.distributed.spin_lock_atom_cas_acquire_wait(
flags_uc_ptr + exit_flag,
expected_val=num_ranks,
reset_val=0,
scope=scope,
)
else:
# Epilogue warps
warp_id_ = warp_id % 4
tid_ = tid % 128
peer_flag_bases = cute.make_rmem_tensor(num_ranks, Int64)
if tid_ == 0:
for rank in cutlass.range_constexpr(num_ranks):
peer_flag_bases[rank] = cute.arch.load(
(peer_flags.iterator + rank).llvm_ptr,
Int64,
)
if warp_id_ == 0:
_tcgen05.alloc(taddr, cta_group)
cute.arch.barrier(barrier_id=BAR_TMEM_ALLOC, number_of_threads=5 * 32)
WIDTH = cutlass.const_expr(16)
partial_vecs = cute.zipped_divide(partial_uc, (1, WIDTH))
bf16x16_atom = cute.make_copy_atom(
cute.nvgpu.CopyUniversalOp(),
BFloat16,
num_bits_per_copy=256,
l1c_evict_priority=cute.nvgpu.CacheEvictionPriority.NO_ALLOCATE,
)
tmem_stage = 0
parity = 0
if cutlass.const_expr(is_2cta):
tmem_empty_mbar_ = to_cta0_smem(tmem_empty_mbar)
else:
tmem_empty_mbar_ = tmem_empty_mbar
for bid in range(raw_bid, total_tiles, num_bids):
bid_m = bid % grid_m
bid_n = bid // grid_m
if warp_id_ == 0:
cute.arch.mbarrier_wait(tmem_full_mbar + tmem_stage, parity)
cute.arch.barrier(barrier_id=BAR_EPILOGUE, number_of_threads=128)
_tcgen05.fence_after_thread_sync()
for i in cutlass.range_constexpr(BN // WIDTH):
tcol = tmem_stage * BN + i * WIDTH
regs = _tcgen05.ld(warp_id_ * 32, tcol, "32x32b", WIDTH)
_tcgen05.wait_ld()
if cutlass.const_expr(i == BN // WIDTH - 1):
_tcgen05.fence_before_thread_sync()
mbarrier.arrive(tmem_empty_mbar_ + tmem_stage, "cluster")
tmp = cute.make_rmem_tensor(WIDTH, BFloat16)
tmp.store(regs.to(BFloat16))
global_row = bid_m * BM + tid_
if global_row < M:
coord = (global_row, bid_n * (BN // WIDTH) + i)
cute.copy(bf16x16_atom, tmp, partial_vecs[None, coord])
cute.arch.barrier(barrier_id=BAR_EPILOGUE, number_of_threads=128)
# Signal GEMM completion. GPU scope is sufficient because the
# partial output only needs to be flushed to local L2.
if tid_ == 0 and bid_m * BM < M:
gemm_start = bid_m * BM
gemm_end = min(gemm_start + BM, M)
first_owner = gemm_start // local_M
last_owner = (gemm_end - 1) // local_M
# signal to all consuming ranks (can be more than 1)
for rank in cutlass.range_constexpr(num_ranks):
if first_owner <= rank and rank <= last_owner:
ptr = cute.make_ptr(
Int32,
peer_flag_bases[rank],
cute.AddressSpace.gmem,
assumed_align=16,
)
ptr += bid_m + bid_n * grid_m
utils.distributed.red_add1(
ptr, order="release", scope="gpu"
)
tmem_stage = (tmem_stage + 1) % num_tmem_stages
if tmem_stage == 0:
parity ^= 1
if cutlass.const_expr(is_2cta):
cute.arch.cluster_arrive_relaxed()
cute.arch.cluster_wait()
else:
cute.arch.barrier(barrier_id=BAR_EPILOGUE, number_of_threads=128)
if warp_id_ == 0:
_tcgen05.dealloc(cta_group)
@cache
@staticmethod
def compile(
rank: int,
num_ranks: int,
BN: int,
cta_group: int,
all_reduce: bool = False,
):
M = cute.sym_int()
padded_M = cute.sym_int()
N = cute.sym_int()
K = cute.sym_int()
local_M = cute.sym_int()
num_flags = cute.sym_int()
A = make_fake_tensor(
BFloat16, (M, K), (cute.sym_int64(divisibility=8), 1), assumed_align=16
)
B = make_fake_tensor(
BFloat16, (N, K), (cute.sym_int64(divisibility=8), 1), assumed_align=16
)
partial = make_fake_tensor(
BFloat16,
(padded_M, N),
(cute.sym_int64(divisibility=16), 1),
assumed_align=32,
)
partial_mc_ptr = nullptr(BFloat16, cute.AddressSpace.gmem, assumed_align=32)
output = (
None
if all_reduce
else make_fake_tensor(
BFloat16,
(local_M, N),
(cute.sym_int64(divisibility=16), 1),
assumed_align=32,
)
)
flags = make_fake_tensor(Int32, (num_flags,), (1,), assumed_align=16)
flags_mc_ptr = nullptr(Int32, cute.AddressSpace.gmem, assumed_align=16)
peer_flag_ptr = nullptr(Int64, cute.AddressSpace.gmem, assumed_align=8)
stream = make_fake_stream(use_tvm_ffi_env_stream=True)
kernel = Sm100GemmRsArBF16(
rank, num_ranks, BN, cta_group, all_reduce=all_reduce
)
return cute.compile(
kernel,
A,
B,
partial,
partial_mc_ptr,
output,
flags,
flags_mc_ptr,
peer_flag_ptr,
128,
stream,
options="--enable-tvm-ffi",
)
class GemmRsAr:
"""Own the symmetric workspace for Kimi-K3 GEMM-RS/AR launches.
All TP ranks must belong to one NVLink domain for multimem instructions.
Each instance is bound to either RS or AR. A vLLM worker has one static
sequence-parallel topology, so the process-wide singleton only needs one
mode. Two independent mode-specific singletons would lift that restriction
but duplicate the large symmetric workspace. A future mixed-mode design
should instead use lightweight RS/AR frontends over one shared multicast
workspace; that is outside this integration's current scope.
"""
def __init__(self, *, max_M: int, N: int, all_reduce: bool = False) -> None:
tp_group = get_tp_group()
group = tp_group.device_group
rank = tp_group.rank_in_group
world_size = tp_group.world_size
device = torch.device("cuda", torch.accelerator.current_device_index())
assert 1 < world_size <= 16
assert 128 % world_size == 0
assert max_M >= 128 and N % 128 == 0
max_M = (max_M + world_size - 1) // world_size * world_size
self.rank = rank
self.world_size = world_size
self.max_M = max_M
self.N = N
self.device = device
self.all_reduce = all_reduce
self.partial = symm_mem.empty((max_M, N), dtype=torch.bfloat16, device=device)
self.partial_handle = symm_mem.rendezvous(self.partial, group)
if self.partial_handle.multicast_ptr == 0:
raise RuntimeError("GEMM-RS/AR requires NVLink multicast memory")
self.partial_mc_ptr = make_ptr(
BFloat16,
self.partial_handle.multicast_ptr,
cute.AddressSpace.gmem,
assumed_align=32,
)
grid_m = (max_M + 127) // 128
cta_group = 2 if max_M >= 1024 or grid_m % 2 == 0 else 1
grid_m = (grid_m + cta_group - 1) // cta_group * cta_group
self.num_sms = torch.cuda.get_device_properties(device).multi_processor_count
max_flags = grid_m * (N // 128) + self.num_sms
self.flags = symm_mem.empty(max_flags, dtype=torch.int32, device=device)
self.flags_handle = symm_mem.rendezvous(self.flags, group)
if self.flags_handle.multicast_ptr == 0:
raise RuntimeError("GEMM-RS/AR requires NVLink multicast memory")
self.flags.zero_()
self.flags_mc_ptr = make_ptr(
Int32,
self.flags_handle.multicast_ptr,
cute.AddressSpace.gmem,
assumed_align=16,
)
self.peer_flag_ptr = make_ptr(
Int64,
self.flags_handle.buffer_ptrs_dev,
cute.AddressSpace.gmem,
assumed_align=8,
)
torch.accelerator.synchronize(device)
tp_group.barrier()
def can_run(self, linear: LinearBase) -> bool:
# Validate projection-invariant requirements once during model init.
# only supports BF16 for now
if not isinstance(linear.quant_method, UnquantizedLinearMethod):
return False
w = linear.weight
if w.ndim != 2:
return False
K = w.shape[1]
return (
w.shape == (self.N, K)
and K % 64 == 0
and w.dtype == torch.bfloat16
and w.device == self.device
and w.is_contiguous()
)
def warn_incompatible_projection(self) -> None:
logger.warning_once(
"Some projections are incompatible with GEMM-RS/AR; using the "
"unfused path instead.",
scope="global",
)
def should_run(self, x: torch.Tensor) -> bool:
# Use the same threshold for RS and AR for now. Small-M shapes are
# supported but faster on the existing LL path.
return x.shape[0] >= 128
def __call__(self, x: torch.Tensor, w: torch.Tensor) -> torch.Tensor:
assert x.ndim == 2
M, K = x.shape
assert 0 < M <= self.max_M
assert w.shape == (self.N, K) and K % 64 == 0
assert w.dtype == torch.bfloat16
assert w.device == self.device
assert w.is_contiguous()
assert x.dtype == torch.bfloat16
assert x.device == self.device
assert x.is_contiguous()
N = w.shape[0]
padded_M = (M + self.world_size - 1) // self.world_size
padded_M *= self.world_size
local_M = padded_M // self.world_size
grid_m = (M + 127) // 128
# Avoid padding small odd grids; 2-CTA wins consistently for M >= 1024.
cta_group = 2 if M >= 1024 or grid_m % 2 == 0 else 1
grid_m = (grid_m + cta_group - 1) // cta_group * cta_group
BN = 256 if M * K >= 24 * 1024 * 1024 else 128
assert N % BN == 0
num_tiles = grid_m * (N // BN)
num_ctas = min(num_tiles, self.num_sms)
num_ctas = num_ctas // cta_group * cta_group
assert self.flags.numel() >= num_tiles + num_ctas
output = None
if not self.all_reduce:
output = torch.empty((local_M, N), dtype=torch.bfloat16, device=self.device)
compiled = Sm100GemmRsArBF16.compile(
self.rank,
self.world_size,
BN,
cta_group,
self.all_reduce,
)
compiled(
x,
w,
self.partial[:padded_M],
self.partial_mc_ptr,
output,
self.flags,
self.flags_mc_ptr,
self.peer_flag_ptr,
num_ctas,
)
if self.all_reduce:
# AttnRes may retain output past the next workspace reuse.
# A future kernel could overlap this copy using an extra warp or
# the communication warp.
return self.partial[:M].clone()
assert output is not None
return output
_gemm_rs_ar: GemmRsAr | None = None
def init_gemm_rs_ar(max_M: int, N: int, *, all_reduce: bool = False) -> None:
"""Collectively initialize the process-wide, mode-bound GEMM-RS/AR state."""
global _gemm_rs_ar
if _gemm_rs_ar is not None:
if _gemm_rs_ar.all_reduce != all_reduce:
current = "AR" if _gemm_rs_ar.all_reduce else "RS"
requested = "AR" if all_reduce else "RS"
raise RuntimeError(
f"GEMM-RS/AR is already initialized for {current}; "
f"a worker cannot reinitialize it for {requested}"
)
assert _gemm_rs_ar.max_M >= max_M and _gemm_rs_ar.N == N
return
_gemm_rs_ar = GemmRsAr(max_M=max_M, N=N, all_reduce=all_reduce)
def warmup_gemm_rs_ar() -> int:
"""Compile every reachable dispatch for the initialized GEMM-RS/AR mode."""
# Initialization can be disabled or fail when multicast is unavailable.
if _gemm_rs_ar is None:
return 0
# Keep these profiles in sync with the dispatch in GemmRsAr.__call__.
profiles = ((128, 1), (128, 2), (256, 2))
for BN, cta_group in profiles:
Sm100GemmRsArBF16.compile(
_gemm_rs_ar.rank,
_gemm_rs_ar.world_size,
BN,
cta_group,
_gemm_rs_ar.all_reduce,
)
return len(profiles)
def get_gemm_rs_ar() -> GemmRsAr:
assert _gemm_rs_ar is not None, "GEMM-RS/AR is not initialized"
return _gemm_rs_ar
+163 -81
View File
@@ -890,6 +890,30 @@ class MiniMaxM3SparseAttention(nn.Module, AttentionLayerBase):
self._ensure_aiter_sparse_pa_kv_cache()
return self.kv_cache_k, self.kv_cache_v
def _get_aiter_sparse_pa_slot_mapping(
self,
slot_mapping: torch.Tensor,
key_cache: torch.Tensor,
value_cache: torch.Tensor,
) -> torch.Tensor:
if value_cache.shape[0] == key_cache.shape[0]:
return slot_mapping
attn_metadata = get_forward_context().attn_metadata
page16_slot_mapping = None
if isinstance(attn_metadata, dict):
main_md = attn_metadata[self.layer_name]
assert isinstance(main_md, MiniMaxM3SparseMetadata)
page16_slot_mapping = main_md.page16_slot_mapping
if (
page16_slot_mapping is None
or page16_slot_mapping.shape != slot_mapping.shape
):
page16_slot_mapping = minimax_m3_rebase_slots_to_page16(
slot_mapping, self.kv_cache.shape[2]
)
return page16_slot_mapping
def _insert_aiter_sparse_pa_kv(
self,
k: torch.Tensor,
@@ -897,6 +921,8 @@ class MiniMaxM3SparseAttention(nn.Module, AttentionLayerBase):
index_k: torch.Tensor | None,
slot_mapping: torch.Tensor,
index_slot_mapping: torch.Tensor | None,
key_cache: torch.Tensor,
value_cache: torch.Tensor,
) -> None:
if self.kv_cache.numel() == 0:
return
@@ -906,22 +932,6 @@ class MiniMaxM3SparseAttention(nn.Module, AttentionLayerBase):
minimax_m3_insert_index_cache,
)
key_cache, value_cache = self.get_aiter_sparse_pa_kv_cache()
if value_cache.shape[0] != key_cache.shape[0]:
attn_metadata = get_forward_context().attn_metadata
page16_slot_mapping = None
if isinstance(attn_metadata, dict):
main_md = attn_metadata[self.layer_name]
assert isinstance(main_md, MiniMaxM3SparseMetadata)
page16_slot_mapping = main_md.page16_slot_mapping
if (
page16_slot_mapping is None
or page16_slot_mapping.shape != slot_mapping.shape
):
page16_slot_mapping = minimax_m3_rebase_slots_to_page16(
slot_mapping, self.kv_cache.shape[2]
)
slot_mapping = page16_slot_mapping
kv_cache_dtype = (
self.kv_cache_dtype
if is_quantized_kv_cache(self.kv_cache_dtype)
@@ -976,38 +986,78 @@ class MiniMaxM3SparseAttention(nn.Module, AttentionLayerBase):
main_slot_mapping = fwd_slot_mapping[self.layer_name]
q = qkv.new_empty((num_tokens, self.q_size))
key_cache = value_cache = page16_slot_mapping = None
k_scale = v_scale = None
use_fused_qknorm = False
if self.use_aiter_sparse_pa:
key_cache, value_cache = self.get_aiter_sparse_pa_kv_cache()
page16_slot_mapping = self._get_aiter_sparse_pa_slot_mapping(
main_slot_mapping, key_cache, value_cache
)
k_scale = getattr(self, "_k_scale", None)
v_scale = getattr(self, "_v_scale", None)
use_fused_qknorm = rocm_aiter_ops.fused_qknorm_idxrqknorm_enabled(
self.kv_cache_dtype, k_scale, v_scale
)
if self.skip_index_topk:
index_q = None
if self.use_aiter_sparse_pa:
ops.fused_minimax_m3_qknorm_rope_kv_insert(
qkv,
self.q_norm.weight,
self.k_norm.weight,
cos_sin_cache,
positions,
self.num_heads,
self.num_kv_heads,
rotary_dim,
eps,
num_index_heads=self.num_idx_heads,
q_out=q,
skip_index_branch=True,
)
k_start = self.q_size
v_start = k_start + self.kv_size
k = qkv[:, k_start:v_start].view(
num_tokens, self.num_kv_heads, self.head_dim
)
v = qkv[:, v_start : v_start + self.kv_size].view(
num_tokens, self.num_kv_heads, self.head_dim
)
self._insert_aiter_sparse_pa_kv(
k,
v,
None,
main_slot_mapping,
None,
)
assert key_cache is not None
assert value_cache is not None
assert page16_slot_mapping is not None
if use_fused_qknorm:
rocm_aiter_ops.fused_qknorm_idxrqknorm(
qkv,
self.q_norm.weight,
self.k_norm.weight,
cos_sin_cache,
positions,
self.num_heads,
self.num_kv_heads,
rotary_dim,
eps,
page16_slot_mapping,
key_cache,
value_cache,
q,
self.kv_cache_dtype,
k_scale,
v_scale,
num_index_heads=self.num_idx_heads,
skip_index_branch=True,
)
else:
ops.fused_minimax_m3_qknorm_rope_kv_insert(
qkv,
self.q_norm.weight,
self.k_norm.weight,
cos_sin_cache,
positions,
self.num_heads,
self.num_kv_heads,
rotary_dim,
eps,
num_index_heads=self.num_idx_heads,
q_out=q,
skip_index_branch=True,
)
k_start = self.q_size
v_start = k_start + self.kv_size
k = qkv[:, k_start:v_start].view(
num_tokens, self.num_kv_heads, self.head_dim
)
v = qkv[:, v_start : v_start + self.kv_size].view(
num_tokens, self.num_kv_heads, self.head_dim
)
self._insert_aiter_sparse_pa_kv(
k,
v,
None,
page16_slot_mapping,
None,
key_cache,
value_cache,
)
else:
ops.fused_minimax_m3_qknorm_rope_kv_insert(
qkv,
@@ -1037,42 +1087,74 @@ class MiniMaxM3SparseAttention(nn.Module, AttentionLayerBase):
dtype=self.indexer.index_cache.dtype,
)
if self.use_aiter_sparse_pa:
ops.fused_minimax_m3_qknorm_rope_kv_insert(
qkv,
self.q_norm.weight,
self.k_norm.weight,
cos_sin_cache,
positions,
self.num_heads,
self.num_kv_heads,
rotary_dim,
eps,
self.index_q_norm.weight,
self.index_k_norm.weight,
self.num_idx_heads,
q_out=q,
index_q_out=index_q,
kv_cache_dtype=self.kv_cache_dtype,
)
k_start = self.q_size
v_start = k_start + self.kv_size
index_k_start = v_start + self.kv_size + self.index_q_size
k = qkv[:, k_start:v_start].view(
num_tokens, self.num_kv_heads, self.head_dim
)
v = qkv[:, v_start : v_start + self.kv_size].view(
num_tokens, self.num_kv_heads, self.head_dim
)
index_k = qkv[
:, index_k_start : index_k_start + self.idx_head_dim
].view(num_tokens, self.idx_head_dim)
self._insert_aiter_sparse_pa_kv(
k,
v,
index_k,
main_slot_mapping,
index_slot_mapping,
)
assert key_cache is not None
assert value_cache is not None
assert page16_slot_mapping is not None
index_cache = self.indexer.index_cache.kv_cache
if use_fused_qknorm:
rocm_aiter_ops.fused_qknorm_idxrqknorm(
qkv,
self.q_norm.weight,
self.k_norm.weight,
cos_sin_cache,
positions,
self.num_heads,
self.num_kv_heads,
rotary_dim,
eps,
page16_slot_mapping,
key_cache,
value_cache,
q,
self.kv_cache_dtype,
k_scale,
v_scale,
self.index_q_norm.weight,
self.index_k_norm.weight,
self.num_idx_heads,
index_cache,
index_q,
index_slot_mapping,
)
else:
ops.fused_minimax_m3_qknorm_rope_kv_insert(
qkv,
self.q_norm.weight,
self.k_norm.weight,
cos_sin_cache,
positions,
self.num_heads,
self.num_kv_heads,
rotary_dim,
eps,
self.index_q_norm.weight,
self.index_k_norm.weight,
self.num_idx_heads,
q_out=q,
index_q_out=index_q,
kv_cache_dtype=self.kv_cache_dtype,
)
k_start = self.q_size
v_start = k_start + self.kv_size
index_k_start = v_start + self.kv_size + self.index_q_size
k = qkv[:, k_start:v_start].view(
num_tokens, self.num_kv_heads, self.head_dim
)
v = qkv[:, v_start : v_start + self.kv_size].view(
num_tokens, self.num_kv_heads, self.head_dim
)
index_k = qkv[
:, index_k_start : index_k_start + self.idx_head_dim
].view(num_tokens, self.idx_head_dim)
self._insert_aiter_sparse_pa_kv(
k,
v,
index_k,
page16_slot_mapping,
index_slot_mapping,
key_cache,
value_cache,
)
else:
ops.fused_minimax_m3_qknorm_rope_kv_insert(
qkv,