[Model] Support Qwen3.8-Flash-Next (#53896)
Signed-off-by: huanghaoyan.hhy <huanghaoyan.hhy@alibaba-inc.com> Signed-off-by: andyluo7 <andy.luo@amd.com> Signed-off-by: lishunyang12 <lishunyang03@gmail.com> Signed-off-by: Harry Huang <huanghaoyan.hhy@alibaba-inc.com> Signed-off-by: Thien Tran <gau.nernst@yahoo.com.sg> Signed-off-by: Isotr0py <Isotr0py@outlook.com> Signed-off-by: Lucas Wilkinson <lwilkins@redhat.com> Signed-off-by: Yifan Qiao <yifanqiao@inferact.ai> Signed-off-by: zjy0516 <riverclouds.zhu@qq.com> Co-authored-by: zjy0516 <riverclouds.zhu@qq.com> Co-authored-by: KungYork <firelikest@163.com> Co-authored-by: Thien Tran <gau.nernst@yahoo.com.sg> Co-authored-by: Yifan Qiao <yifanqiao@inferact.ai> Co-authored-by: andyluo7 <43718156+andyluo7@users.noreply.github.com> Co-authored-by: Isotr0py <mozf@inferact.ai> Co-authored-by: andyluo7 <andy.luo@amd.com> Co-authored-by: OpenAI Codex <noreply@openai.com> Co-authored-by: lishunyang12 <lishunyang03@gmail.com> Co-authored-by: Vadim Gimpelson <156319763+vadiklyutiy@users.noreply.github.com> Co-authored-by: Isotr0py <Isotr0py@outlook.com> Co-authored-by: Lucas Wilkinson <lwilkins@redhat.com> Co-authored-by: Claude Opus 5 <noreply@anthropic.com> Co-authored-by: OpenAI Codex <codex@openai.com>
This commit is contained in:
co-authored by
zjy0516
KungYork
Thien Tran
Yifan Qiao
andyluo7
Isotr0py
andyluo7
OpenAI Codex
lishunyang12
Vadim Gimpelson
Isotr0py
Lucas Wilkinson
Claude Opus 5
OpenAI Codex
parent
687db59744
commit
e126687a9a
@@ -0,0 +1,61 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Qwen4Exp model package."""
|
||||
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from .common.hyperconnection import (
|
||||
GatedResidual,
|
||||
GroupedGemmaRMSNorm,
|
||||
HyperConnectionBase,
|
||||
HyperConnectionConfig,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .nvidia.model import (
|
||||
Qwen4ExpForCausalLM,
|
||||
Qwen4ExpForConditionalGeneration,
|
||||
)
|
||||
from .nvidia.mtp import Qwen4ExpMTP
|
||||
|
||||
|
||||
def __getattr__(name: str) -> Any:
|
||||
if name in {
|
||||
"Qwen4ExpForCausalLM",
|
||||
"Qwen4ExpForConditionalGeneration",
|
||||
"Qwen4ExpMTP",
|
||||
}:
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
if current_platform.is_xpu() or current_platform.is_tpu():
|
||||
raise NotImplementedError("Qwen4Exp currently supports CUDA and ROCm only")
|
||||
if current_platform.is_rocm():
|
||||
from .amd.model import (
|
||||
Qwen4ExpForCausalLM,
|
||||
Qwen4ExpForConditionalGeneration,
|
||||
)
|
||||
from .amd.mtp import Qwen4ExpMTP
|
||||
else:
|
||||
from .nvidia.model import (
|
||||
Qwen4ExpForCausalLM,
|
||||
Qwen4ExpForConditionalGeneration,
|
||||
)
|
||||
from .nvidia.mtp import Qwen4ExpMTP
|
||||
|
||||
return {
|
||||
"Qwen4ExpForCausalLM": Qwen4ExpForCausalLM,
|
||||
"Qwen4ExpForConditionalGeneration": (Qwen4ExpForConditionalGeneration),
|
||||
"Qwen4ExpMTP": Qwen4ExpMTP,
|
||||
}[name]
|
||||
raise AttributeError(name)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"GatedResidual",
|
||||
"GroupedGemmaRMSNorm",
|
||||
"HyperConnectionBase",
|
||||
"HyperConnectionConfig",
|
||||
"Qwen4ExpForCausalLM",
|
||||
"Qwen4ExpForConditionalGeneration",
|
||||
"Qwen4ExpMTP",
|
||||
]
|
||||
@@ -0,0 +1,2 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
@@ -0,0 +1,205 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""HyperConnection (Gated Residual) utilities for the AMD model variant.
|
||||
|
||||
Implements the HyperConnection residual scheme proposed in
|
||||
"HyperConnections" (https://arxiv.org/abs/2409.19606). This AMD variant
|
||||
delays each HC combine to the following HC mix boundary. HC glue kernels,
|
||||
including fused combine+RMSNorm, live in ``ops/hc.py``; projections remain
|
||||
standard vLLM Linear modules.
|
||||
|
||||
Hidden states between layers have shape ``[..., HC*HS]`` with HS inner
|
||||
(HC outer, HS inner — checkpoint-native layout).
|
||||
|
||||
Typical usage inside a transformer decoder layer::
|
||||
|
||||
self.attn_hc = GatedResidual(hc_config)
|
||||
|
||||
hidden_states, block_input, injection = self.attn_hc.mix(hidden_states)
|
||||
attention_output = attention(block_input)
|
||||
hidden_states, block_input, injection = self.mlp_hc.combine_and_mix(
|
||||
hidden_states, attention_output, injection
|
||||
)
|
||||
"""
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from vllm.model_executor.layers.linear import (
|
||||
MergedColumnParallelLinear,
|
||||
ReplicatedLinear,
|
||||
)
|
||||
from vllm.model_executor.models.utils import maybe_prefix
|
||||
|
||||
from ..common.hyperconnection import (
|
||||
GroupedGemmaRMSNorm,
|
||||
HyperConnectionConfig,
|
||||
)
|
||||
from .ops.hc import (
|
||||
grouped_gemma_rmsnorm,
|
||||
hc_combine,
|
||||
hc_combine_norm,
|
||||
hc_gate_mix,
|
||||
hc_silu,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Gated-residual variant
|
||||
# ---------------------------------------------------------------------------
|
||||
class GatedResidual(nn.Module):
|
||||
"""Gated HyperConnection with learnable low-rank mixing and injection.
|
||||
|
||||
``combine_and_mix()`` runs the pre pipeline (grouped GemmaRMSNorm -> merged
|
||||
low-rank down+inject GEMM -> silu -> up GEMM -> sigmoid -> gated mean
|
||||
over the HC streams). When passed a pending block output and an injection,
|
||||
it fuses their residual combine with the RMSNorm. Final mixers use
|
||||
``use_combine=False`` and do not produce a new injection.
|
||||
|
||||
Weights: the norm owns the grouped GemmaRMSNorm affine; the projections
|
||||
are vLLM Linear modules (merged replicated linear for down+inject), so
|
||||
GEMM dispatch (e.g. the low-latency skinny GEMM) applies through the
|
||||
standard quant_method mechanism.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config: HyperConnectionConfig,
|
||||
use_combine: bool = True,
|
||||
prefix: str = "",
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.lora_rank = config.hc_lowrank
|
||||
self.hc_count = config.hc_count
|
||||
self.hidden_size = config.hidden_size
|
||||
self.use_combine = use_combine
|
||||
|
||||
norm_size = (
|
||||
self.hyper_hidden_size if config.hc_per_branch_norm else config.hidden_size
|
||||
)
|
||||
group_size = config.hidden_size if config.hc_per_branch_norm else None
|
||||
# Normalize each H-sized HC stream independently while retaining a
|
||||
# separate affine weight for every element of the HC*H layout.
|
||||
self.hc_norm = GroupedGemmaRMSNorm(
|
||||
norm_size,
|
||||
eps=config.rms_norm_eps,
|
||||
group_size=group_size,
|
||||
dtype=config.params_dtype,
|
||||
)
|
||||
|
||||
# -- vLLM Linear weights --------------------------------------------
|
||||
# The merged skinny-GEMM shape is physically padded to 16 rows for
|
||||
# alignment and efficient backend dispatch.
|
||||
self.pad_size = (-(self.lora_rank + self.hc_count)) % 16 if use_combine else 0
|
||||
if use_combine:
|
||||
self.input_mix_weight_down_block_inject = MergedColumnParallelLinear(
|
||||
self.hyper_hidden_size,
|
||||
[self.lora_rank, self.hc_count]
|
||||
+ ([self.pad_size] if self.pad_size else []),
|
||||
bias=False,
|
||||
params_dtype=config.params_dtype,
|
||||
quant_config=None,
|
||||
prefix=maybe_prefix(prefix, "input_mix_weight_down_block_inject"),
|
||||
return_bias=False,
|
||||
disable_tp=True,
|
||||
)
|
||||
else:
|
||||
self.input_mix_weight_down = ReplicatedLinear(
|
||||
self.hyper_hidden_size,
|
||||
self.lora_rank,
|
||||
bias=False,
|
||||
params_dtype=config.params_dtype,
|
||||
quant_config=None,
|
||||
prefix=maybe_prefix(prefix, "input_mix_weight_down"),
|
||||
return_bias=False,
|
||||
)
|
||||
self.input_mix_weight_up = ReplicatedLinear(
|
||||
self.lora_rank,
|
||||
self.hyper_hidden_size,
|
||||
bias=False,
|
||||
params_dtype=config.params_dtype,
|
||||
quant_config=None,
|
||||
prefix=maybe_prefix(prefix, "input_mix_weight_up"),
|
||||
return_bias=False,
|
||||
)
|
||||
|
||||
def mix(
|
||||
self, hidden_states: torch.Tensor
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]:
|
||||
xn = grouped_gemma_rmsnorm(
|
||||
hidden_states,
|
||||
self.hc_norm.weight,
|
||||
self.config.rms_norm_eps,
|
||||
self.hc_count,
|
||||
)
|
||||
|
||||
if self.use_combine:
|
||||
# produce injection logits for combine
|
||||
split_sizes = [self.lora_rank, self.hc_count, self.pad_size]
|
||||
down_and_injection = self.input_mix_weight_down_block_inject(xn)
|
||||
lora, injection, _ = down_and_injection.split(split_sizes, dim=-1)
|
||||
else:
|
||||
lora = self.input_mix_weight_down(xn)
|
||||
injection = None
|
||||
|
||||
lora = hc_silu(lora, self.hc_count)
|
||||
gate = self.input_mix_weight_up(lora) # [M, D]
|
||||
block_input = hc_gate_mix(xn, gate, self.hc_count)
|
||||
|
||||
return hidden_states, block_input, injection
|
||||
|
||||
def combine_and_mix(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
prev_block_output: torch.Tensor,
|
||||
prev_injection: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]:
|
||||
"""Consume a pending combine, then prepare the next block input.
|
||||
|
||||
``hidden_states`` is the multi-stream state from before the pending
|
||||
block's mix. Its combine with ``block_output`` is fused with this
|
||||
module's input RMSNorm.
|
||||
"""
|
||||
hidden_states, xn = hc_combine_norm(
|
||||
hidden_states,
|
||||
prev_block_output,
|
||||
prev_injection,
|
||||
self.hc_norm.weight,
|
||||
self.config.rms_norm_eps,
|
||||
self.hc_count,
|
||||
)
|
||||
|
||||
if self.use_combine:
|
||||
# produce injection logits for combine
|
||||
split_sizes = [self.lora_rank, self.hc_count, self.pad_size]
|
||||
down_and_injection = self.input_mix_weight_down_block_inject(xn)
|
||||
lora, injection, _ = down_and_injection.split(split_sizes, dim=-1)
|
||||
else:
|
||||
lora = self.input_mix_weight_down(xn)
|
||||
injection = None
|
||||
|
||||
lora = hc_silu(lora, self.hc_count)
|
||||
gate = self.input_mix_weight_up(lora) # [M, D]
|
||||
block_input = hc_gate_mix(xn, gate, self.hc_count)
|
||||
|
||||
return hidden_states, block_input, injection
|
||||
|
||||
def combine(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
block_output: torch.Tensor,
|
||||
injection: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
return hc_combine(hidden_states, block_output, injection, self.hc_count)
|
||||
|
||||
@property
|
||||
def hyper_hidden_size(self) -> int:
|
||||
return self.hc_count * self.hidden_size
|
||||
|
||||
|
||||
__all__ = [
|
||||
"GatedResidual",
|
||||
"GroupedGemmaRMSNorm",
|
||||
"HyperConnectionConfig",
|
||||
]
|
||||
@@ -0,0 +1,321 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Qwen4Exp weight-free QSA indexer."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import cast
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.forward_context import get_forward_context
|
||||
from vllm.model_executor.layers.layernorm import GemmaRMSNorm
|
||||
from vllm.model_executor.layers.linear import ReplicatedLinear
|
||||
from vllm.model_executor.layers.quantization import QuantizationConfig
|
||||
from vllm.model_executor.layers.rotary_embedding.mrope import triton_mrope
|
||||
from vllm.transformers_utils.configs.qwen4_exp import (
|
||||
Qwen4ExpTextConfig,
|
||||
)
|
||||
|
||||
from ..common.qsa_cache import (
|
||||
QSACompressedKeyCache,
|
||||
QSAForwardMetadata,
|
||||
QSAKeyStateCache,
|
||||
canonical_qsa_rope_positions,
|
||||
)
|
||||
|
||||
|
||||
def apply_qsa_rope(
|
||||
rotary_emb: nn.Module,
|
||||
positions: torch.Tensor,
|
||||
tensor: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
"""Apply the main attention's exact 1D/MRoPE composition to QSA heads."""
|
||||
|
||||
num_tokens, _, head_dim = tensor.shape
|
||||
rotary_dim = rotary_emb.rotary_dim
|
||||
cache = rotary_emb._match_cos_sin_cache_dtype(tensor) # noqa: SLF001
|
||||
cos_sin = cache[positions]
|
||||
cos, sin = cos_sin.chunk(2, dim=-1)
|
||||
if positions.ndim == 2:
|
||||
shape = tensor.shape
|
||||
tensor, _ = triton_mrope(
|
||||
tensor.reshape(num_tokens, -1),
|
||||
tensor.new_empty((num_tokens, head_dim)),
|
||||
cos,
|
||||
sin,
|
||||
rotary_emb.mrope_section,
|
||||
head_dim,
|
||||
rotary_dim,
|
||||
rotary_emb.mrope_interleaved,
|
||||
rotary_emb.is_neox_style,
|
||||
)
|
||||
return tensor.reshape(shape)
|
||||
|
||||
rotated = rotary_emb.apply_rotary_emb(
|
||||
tensor[..., :rotary_dim],
|
||||
cos,
|
||||
sin,
|
||||
)
|
||||
return torch.cat((rotated, tensor[..., rotary_dim:]), dim=-1)
|
||||
|
||||
|
||||
def apply_qsa_rmsnorm(
|
||||
norm: GemmaRMSNorm,
|
||||
tensor: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
"""Use vLLM's portable RMSNorm implementation on ROCm."""
|
||||
|
||||
return cast(torch.Tensor, norm(tensor))
|
||||
|
||||
|
||||
class QSAIndexer(nn.Module):
|
||||
"""Replicated Q/K projection plus paged, weight-free QSA selection.
|
||||
|
||||
``prefix`` must be the checkpoint's indexer prefix, normally
|
||||
``model.layers.N.self_attn.indexer``. Consequently the trainable names are
|
||||
``index_qk_proj``, ``q_layernorm`` and ``k_layernorm`` under that prefix.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
vllm_config: VllmConfig,
|
||||
config: Qwen4ExpTextConfig,
|
||||
layer_id: int,
|
||||
rotary_emb: nn.Module,
|
||||
quant_config: QuantizationConfig | None = None,
|
||||
prefix: str = "",
|
||||
) -> None:
|
||||
super().__init__()
|
||||
if vllm_config.cache_config is None:
|
||||
raise ValueError("QSA requires a paged KV cache")
|
||||
if vllm_config.model_config.dtype != torch.bfloat16:
|
||||
raise NotImplementedError("Qwen4Exp QSA currently requires BF16")
|
||||
|
||||
self.layer_id = int(layer_id)
|
||||
self.index_n_heads = int(config.indexer_n_heads)
|
||||
self.index_kv_heads = int(config.indexer_kv_heads)
|
||||
self.index_head_dim = int(config.indexer_head_dim)
|
||||
self.token_topk = int(config.indexer_budget)
|
||||
self.compress_ratio = int(config.indexer_compress_ratio)
|
||||
self.rotary_emb = rotary_emb
|
||||
self.prefix = prefix
|
||||
# MTP step 0 selects the target-aligned rows; later steps reuse them
|
||||
# while continuing to update the QSA side cache.
|
||||
self.skip_topk = False
|
||||
|
||||
self.index_qk_proj = ReplicatedLinear(
|
||||
int(config.hidden_size),
|
||||
(self.index_n_heads + self.index_kv_heads) * self.index_head_dim,
|
||||
bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.index_qk_proj" if prefix else "index_qk_proj",
|
||||
)
|
||||
self.q_layernorm = GemmaRMSNorm(
|
||||
self.index_head_dim,
|
||||
eps=float(getattr(config, "rms_norm_eps", 1e-6)),
|
||||
)
|
||||
self.k_layernorm = GemmaRMSNorm(
|
||||
self.index_head_dim,
|
||||
eps=float(getattr(config, "rms_norm_eps", 1e-6)),
|
||||
)
|
||||
|
||||
cache_config = vllm_config.cache_config
|
||||
cache_prefix = f"{prefix}." if prefix else ""
|
||||
self.raw_key_cache = QSAKeyStateCache(
|
||||
head_size=self.index_head_dim,
|
||||
dtype=torch.bfloat16,
|
||||
cache_rope_positions=vllm_config.model_config.uses_mrope,
|
||||
prefix=f"{cache_prefix}raw_key_cache",
|
||||
cache_config=cache_config,
|
||||
compress_ratio=self.compress_ratio,
|
||||
vllm_config=vllm_config,
|
||||
)
|
||||
self.compressed_key_cache = QSACompressedKeyCache(
|
||||
head_size=self.index_head_dim,
|
||||
dtype=torch.bfloat16,
|
||||
compress_ratio=self.compress_ratio,
|
||||
prefix=f"{cache_prefix}compressed_key_cache",
|
||||
cache_config=cache_config,
|
||||
vllm_config=vllm_config,
|
||||
)
|
||||
|
||||
@property
|
||||
def output_width(self) -> int:
|
||||
return self.token_topk + self.compress_ratio - 1
|
||||
|
||||
def project_qk(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Project replicated Q/K, normalize+rotate Q, and preserve raw K."""
|
||||
|
||||
qk, _ = self.index_qk_proj(hidden_states)
|
||||
q_raw, token_k = qk.split(
|
||||
(
|
||||
self.index_n_heads * self.index_head_dim,
|
||||
self.index_kv_heads * self.index_head_dim,
|
||||
),
|
||||
dim=-1,
|
||||
)
|
||||
q = q_raw.reshape(-1, self.index_n_heads, self.index_head_dim)
|
||||
q = apply_qsa_rmsnorm(
|
||||
self.q_layernorm,
|
||||
q.reshape(-1, self.index_head_dim),
|
||||
).reshape_as(q)
|
||||
q = apply_qsa_rope(self.rotary_emb, positions, q)
|
||||
return q, token_k.reshape(-1, 1, self.index_head_dim)
|
||||
|
||||
def normalize_compressed_keys(
|
||||
self,
|
||||
compressed_keys: torch.Tensor,
|
||||
first_rope_positions: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
"""Normalize pooled K and apply the first token's exact group position."""
|
||||
|
||||
keys = compressed_keys.reshape(-1, self.index_head_dim)
|
||||
keys = apply_qsa_rmsnorm(self.k_layernorm, keys).reshape(
|
||||
-1, 1, self.index_head_dim
|
||||
)
|
||||
if getattr(self.rotary_emb, "mrope_section", None):
|
||||
positions = first_rope_positions.transpose(0, 1)
|
||||
else:
|
||||
positions = first_rope_positions[:, 0]
|
||||
return apply_qsa_rope(self.rotary_emb, positions, keys)
|
||||
|
||||
def _metadata(
|
||||
self,
|
||||
) -> tuple[QSAForwardMetadata, QSAForwardMetadata] | None:
|
||||
metadata = get_forward_context().attn_metadata
|
||||
if isinstance(metadata, list):
|
||||
metadata = metadata[0]
|
||||
if not isinstance(metadata, dict):
|
||||
return None
|
||||
raw = cast(QSAForwardMetadata, metadata[self.raw_key_cache.prefix])
|
||||
compressed = cast(
|
||||
QSAForwardMetadata, metadata[self.compressed_key_cache.prefix]
|
||||
)
|
||||
if raw.num_actual_tokens != compressed.num_actual_tokens:
|
||||
raise RuntimeError("QSA side-cache metadata token counts disagree")
|
||||
if not raw.logical_positions.is_cuda and (
|
||||
not torch.equal(raw.logical_positions, compressed.logical_positions)
|
||||
):
|
||||
raise RuntimeError("QSA side-cache metadata positions disagree")
|
||||
return raw, compressed
|
||||
|
||||
def _update_and_compress(
|
||||
self,
|
||||
token_k: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
raw_metadata: QSAForwardMetadata,
|
||||
compressed_metadata: QSAForwardMetadata,
|
||||
) -> None:
|
||||
num_tokens = raw_metadata.num_actual_tokens
|
||||
raw_key_cache = self.raw_key_cache.key_cache
|
||||
rope_position_cache = self.raw_key_cache.rope_position_cache
|
||||
from .ops.qsa import qsa_compress_groups_with_ratio, qsa_store_cache_rows
|
||||
|
||||
if rope_position_cache is None:
|
||||
position_rows = raw_metadata.logical_positions.view(-1, 1, 1).expand(
|
||||
-1, 1, 3
|
||||
)
|
||||
else:
|
||||
position_rows = canonical_qsa_rope_positions(positions)[:num_tokens].to(
|
||||
device=raw_key_cache.device
|
||||
)
|
||||
pooled, first_positions = qsa_compress_groups_with_ratio(
|
||||
token_k[:num_tokens],
|
||||
position_rows,
|
||||
raw_key_cache,
|
||||
raw_metadata.block_table,
|
||||
raw_metadata.token_to_req,
|
||||
raw_metadata.query_start_loc,
|
||||
raw_metadata.logical_positions,
|
||||
compressed_metadata.slot_mapping,
|
||||
self.compress_ratio,
|
||||
rope_position_cache,
|
||||
)
|
||||
normalized = self.normalize_compressed_keys(pooled, first_positions)
|
||||
qsa_store_cache_rows(
|
||||
self.compressed_key_cache.kv_cache,
|
||||
compressed_metadata.slot_mapping,
|
||||
normalized,
|
||||
)
|
||||
qsa_store_cache_rows(
|
||||
raw_key_cache,
|
||||
raw_metadata.slot_mapping,
|
||||
token_k[:num_tokens],
|
||||
)
|
||||
if rope_position_cache is not None:
|
||||
qsa_store_cache_rows(
|
||||
rope_position_cache,
|
||||
raw_metadata.slot_mapping,
|
||||
position_rows,
|
||||
)
|
||||
|
||||
def _select(
|
||||
self,
|
||||
q: torch.Tensor,
|
||||
metadata: QSAForwardMetadata,
|
||||
out: torch.Tensor | None,
|
||||
) -> torch.Tensor:
|
||||
from .ops.qsa import qsa_select_paged_tokens
|
||||
|
||||
return qsa_select_paged_tokens(
|
||||
q,
|
||||
self.compressed_key_cache.kv_cache,
|
||||
metadata.block_table,
|
||||
metadata.token_to_req,
|
||||
metadata.logical_positions,
|
||||
metadata.seq_lens,
|
||||
self.token_topk,
|
||||
self.compress_ratio,
|
||||
out,
|
||||
)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
out: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Return fixed-width request-relative token indices padded with ``-1``."""
|
||||
|
||||
metadata = self._metadata()
|
||||
if metadata is None:
|
||||
# Preserve step-0 indices when later MTP steps reuse the buffer.
|
||||
if self.skip_topk and out is not None:
|
||||
return out
|
||||
result = torch.full(
|
||||
(hidden_states.shape[0], self.output_width),
|
||||
-1,
|
||||
dtype=torch.int32,
|
||||
device=hidden_states.device,
|
||||
)
|
||||
if out is not None:
|
||||
out.copy_(result)
|
||||
return out
|
||||
return result
|
||||
raw_metadata, compressed_metadata = metadata
|
||||
num_tokens = raw_metadata.num_actual_tokens
|
||||
q, token_k = self.project_qk(
|
||||
hidden_states[:num_tokens], positions[..., :num_tokens]
|
||||
)
|
||||
self._update_and_compress(
|
||||
token_k,
|
||||
positions[..., :num_tokens],
|
||||
raw_metadata,
|
||||
compressed_metadata,
|
||||
)
|
||||
if self.skip_topk:
|
||||
if out is None:
|
||||
raise RuntimeError("QSA top-k reuse requires an output buffer")
|
||||
return out
|
||||
return self._select(q, compressed_metadata, out)
|
||||
|
||||
|
||||
__all__ = ["QSAIndexer", "apply_qsa_rope"]
|
||||
@@ -0,0 +1,15 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Qwen4Exp low-latency GEMM hook for AMD ROCm."""
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
|
||||
def enable_qwen4_exp_low_latency_gemm(
|
||||
module: nn.Module,
|
||||
dtype: torch.dtype,
|
||||
) -> None:
|
||||
"""Keep the standard vLLM linear methods on AMD ROCm."""
|
||||
|
||||
del module, dtype
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,143 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Model-runner state for Qwen4Exp PLE inputs."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.v1.worker.gpu.input_batch import InputBatch
|
||||
from vllm.v1.worker.gpu.mm.encoder_cache import EncoderCache
|
||||
from vllm.v1.worker.gpu.model_states.mamba_hybrid import MambaHybridModelState
|
||||
from vllm.v1.worker.gpu.states import RequestState
|
||||
|
||||
|
||||
class Qwen4ExpModelState(MambaHybridModelState):
|
||||
"""Add rollback-safe PLE n-gram context to the model inputs."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vllm_config: VllmConfig,
|
||||
model: nn.Module,
|
||||
encoder_cache: EncoderCache | None,
|
||||
device: torch.device,
|
||||
) -> None:
|
||||
super().__init__(vllm_config, model, encoder_cache, device)
|
||||
config = self.model_config.hf_text_config
|
||||
self.uses_ngram_embedding = bool(config.ple_layer_ids)
|
||||
if not self.uses_ngram_embedding:
|
||||
self.ngram_context_len = 0
|
||||
self.ngram_eos_token_id = 0
|
||||
return
|
||||
|
||||
if vllm_config.parallel_config.pipeline_parallel_size > 1:
|
||||
raise RuntimeError(
|
||||
"N-gram PLE embedding currently requires "
|
||||
"pipeline_parallel_size=1 because non-first pipeline ranks do "
|
||||
"not receive the raw input_ids required by PLE. Please run "
|
||||
"with PP=1."
|
||||
)
|
||||
|
||||
self.ngram_context_len = int(config.ngram_size) - 1
|
||||
if self.ngram_context_len <= 0:
|
||||
raise ValueError("N-gram embedding requires context length >= 1.")
|
||||
self.ngram_eos_token_id = int(config.eos_token_id)
|
||||
self.ngram_context = torch.full(
|
||||
(self.max_num_reqs, self.ngram_context_len),
|
||||
self.ngram_eos_token_id,
|
||||
dtype=torch.int32,
|
||||
device=self.device,
|
||||
)
|
||||
self.ngram_context_offsets = torch.arange(
|
||||
-self.ngram_context_len,
|
||||
0,
|
||||
dtype=torch.int64,
|
||||
device=self.device,
|
||||
)
|
||||
self.ple_query_start_loc = torch.zeros(
|
||||
self.max_num_reqs + 1,
|
||||
dtype=torch.int32,
|
||||
device=self.device,
|
||||
)
|
||||
|
||||
def _prepare_ngram_context(
|
||||
self,
|
||||
input_batch: InputBatch,
|
||||
req_states: RequestState,
|
||||
) -> torch.Tensor:
|
||||
num_reqs = input_batch.num_reqs
|
||||
num_reqs_padded = input_batch.num_reqs_after_padding
|
||||
context = self.ngram_context[:num_reqs_padded]
|
||||
context.fill_(self.ngram_eos_token_id)
|
||||
if num_reqs == 0:
|
||||
return context
|
||||
|
||||
request_indices = input_batch.idx_mapping[:num_reqs].long()
|
||||
context_end = req_states.num_computed_tokens.gpu[request_indices].long()
|
||||
token_indices = context_end.unsqueeze(1) + self.ngram_context_offsets
|
||||
valid_tokens = token_indices >= 0
|
||||
token_indices.clamp_min_(0)
|
||||
context_tokens = req_states.all_token_ids.gpu[
|
||||
request_indices.unsqueeze(1), token_indices
|
||||
]
|
||||
context[:num_reqs].copy_(
|
||||
torch.where(
|
||||
valid_tokens,
|
||||
context_tokens,
|
||||
context_tokens.new_full((), self.ngram_eos_token_id),
|
||||
)
|
||||
)
|
||||
return context
|
||||
|
||||
def prepare_inputs(
|
||||
self,
|
||||
input_batch: InputBatch,
|
||||
req_states: RequestState,
|
||||
) -> dict[str, Any]:
|
||||
model_inputs = super().prepare_inputs(input_batch, req_states)
|
||||
if not self.uses_ngram_embedding:
|
||||
return model_inputs
|
||||
|
||||
num_reqs_padded = input_batch.num_reqs_after_padding
|
||||
query_start_loc = self.ple_query_start_loc[: num_reqs_padded + 1]
|
||||
query_start_loc.copy_(input_batch.query_start_loc[: num_reqs_padded + 1])
|
||||
model_inputs.update(
|
||||
query_start_loc=query_start_loc,
|
||||
ngram_context=self._prepare_ngram_context(input_batch, req_states),
|
||||
)
|
||||
return model_inputs
|
||||
|
||||
def prepare_dummy_inputs(
|
||||
self,
|
||||
num_reqs: int,
|
||||
num_tokens: int,
|
||||
) -> dict[str, Any]:
|
||||
model_inputs = super().prepare_dummy_inputs(num_reqs, num_tokens)
|
||||
if not self.uses_ngram_embedding:
|
||||
return model_inputs
|
||||
|
||||
query_start_loc = self.ple_query_start_loc[: num_reqs + 1]
|
||||
query_start_loc[0] = 0
|
||||
tokens_per_req, num_extra_tokens = divmod(num_tokens, num_reqs)
|
||||
query_lens = torch.full(
|
||||
(num_reqs,),
|
||||
tokens_per_req,
|
||||
dtype=query_start_loc.dtype,
|
||||
device=query_start_loc.device,
|
||||
)
|
||||
if num_extra_tokens > 0:
|
||||
query_lens[-num_extra_tokens:] += 1
|
||||
torch.cumsum(query_lens, dim=0, out=query_start_loc[1:])
|
||||
|
||||
ngram_context = self.ngram_context[:num_reqs]
|
||||
ngram_context.fill_(self.ngram_eos_token_id)
|
||||
model_inputs.update(
|
||||
query_start_loc=query_start_loc,
|
||||
ngram_context=ngram_context,
|
||||
)
|
||||
return model_inputs
|
||||
|
||||
|
||||
__all__ = ["Qwen4ExpModelState"]
|
||||
@@ -0,0 +1,462 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Inference-only Qwen4Exp MTP (Multi-Token Predictor) model.
|
||||
|
||||
The MTP draft model reuses the Qwen4Exp backbone (PLE/HC/MoE) but:
|
||||
- drops all multi-modal handling (text-only),
|
||||
- forces PLE off while keeping the main model's HC stream count,
|
||||
- fuses the backbone hidden and the new-token embedding via
|
||||
``residual_linear_shared`` (fc_embedding + shared fc_hidden) instead of
|
||||
the ``Linear(2H, H)`` + repeat used by other MTP variants,
|
||||
- emits TWO hidden streams per step (scheme A): a single stream [T, H]
|
||||
(final-mixer collapsed, fed to the LM head) and a pre-final-mixer
|
||||
multi stream [T, hc_count*H] (fed to the next draft step).
|
||||
"""
|
||||
|
||||
from collections.abc import Iterable
|
||||
|
||||
import regex as re
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from vllm.compilation.decorators import support_torch_compile
|
||||
from vllm.config import VllmConfig, replace, set_current_vllm_config
|
||||
from vllm.distributed import get_pp_group
|
||||
from vllm.model_executor.layers.fused_moe.utils import (
|
||||
is_model_fused_shared_expert_compatible,
|
||||
)
|
||||
from vllm.model_executor.layers.layernorm import GemmaRMSNorm
|
||||
from vllm.model_executor.layers.linear import ColumnParallelLinear
|
||||
from vllm.model_executor.layers.logits_processor import LogitsProcessor
|
||||
from vllm.model_executor.layers.vocab_parallel_embedding import (
|
||||
ParallelLMHead,
|
||||
VocabParallelEmbedding,
|
||||
)
|
||||
from vllm.model_executor.model_loader.utils import configure_quant_config
|
||||
from vllm.model_executor.models.interfaces import SupportsPP
|
||||
from vllm.model_executor.models.qwen3_5 import Qwen3_5Model
|
||||
from vllm.model_executor.models.utils import (
|
||||
AutoWeightsLoader,
|
||||
PPMissingLayer,
|
||||
WeightsMapper,
|
||||
get_draft_quant_config,
|
||||
make_empty_intermediate_tensors_factory,
|
||||
maybe_fuse_shared_experts,
|
||||
maybe_prefix,
|
||||
)
|
||||
from vllm.sequence import IntermediateTensors
|
||||
from vllm.transformers_utils.configs.qwen4_exp import (
|
||||
Qwen4ExpTextConfig,
|
||||
)
|
||||
|
||||
from .hyperconnection import GatedResidual, HyperConnectionConfig
|
||||
from .low_latency_gemm import enable_qwen4_exp_low_latency_gemm
|
||||
from .model import (
|
||||
_HC_WEIGHTS_MAPPER,
|
||||
_QWEN4_EXP_IGNORED_MISSING_SUFFIXES,
|
||||
Qwen4ExpDecoderLayer,
|
||||
Qwen4ExpMixtureOfExperts,
|
||||
Qwen4ExpSparseMoeBlock,
|
||||
)
|
||||
|
||||
|
||||
def _remap_ignored_layers(
|
||||
ignored_layers: list[str],
|
||||
mtp_start_layer_idx: int,
|
||||
) -> list[str]:
|
||||
remapped: list[str] = []
|
||||
for name in ignored_layers:
|
||||
if name.startswith("mtp."):
|
||||
new_name = re.sub(
|
||||
r"(?<=\.layers\.)\d+",
|
||||
lambda m: str(mtp_start_layer_idx + int(m.group(0))),
|
||||
name,
|
||||
)
|
||||
remapped.append(new_name)
|
||||
else:
|
||||
remapped.append(name)
|
||||
return remapped
|
||||
|
||||
|
||||
def _remap_mtp_weight_name(name: str) -> str | None:
|
||||
"""Map Qwen4Exp checkpoint paths into the standalone draft model."""
|
||||
|
||||
for checkpoint_prefix in (
|
||||
"model.language_model.",
|
||||
"language_model.",
|
||||
):
|
||||
if name.startswith(checkpoint_prefix):
|
||||
name = name.removeprefix(checkpoint_prefix)
|
||||
break
|
||||
|
||||
if name.startswith("embed_tokens."):
|
||||
name = f"model.{name}"
|
||||
if name.startswith("model.mtp."):
|
||||
name = name.removeprefix("model.")
|
||||
if name.startswith("mtp.shared_head.head."):
|
||||
return name.replace("mtp.shared_head.head.", "lm_head.", 1)
|
||||
if name.startswith("model.shared_head.head."):
|
||||
return name.replace("model.shared_head.head.", "lm_head.", 1)
|
||||
if name.startswith("shared_head.head."):
|
||||
return name.replace("shared_head.head.", "lm_head.", 1)
|
||||
if name.startswith("model.lm_head."):
|
||||
return name.removeprefix("model.")
|
||||
if name.startswith("mtp."):
|
||||
return name.replace("mtp.", "model.", 1)
|
||||
if name.startswith("model.embed_tokens.") or name.startswith("lm_head."):
|
||||
return name
|
||||
return None
|
||||
|
||||
|
||||
def _make_draft_vllm_config(
|
||||
vllm_config: VllmConfig,
|
||||
mtp_start_layer_idx: int,
|
||||
) -> VllmConfig:
|
||||
"""Ensure that the draft model config is set in the vLLM config."""
|
||||
speculative_config = vllm_config.speculative_config
|
||||
if speculative_config is None or speculative_config.draft_model_config is None:
|
||||
raise ValueError("speculative_config.draft_model_config must be set")
|
||||
|
||||
draft_quant_config = get_draft_quant_config(vllm_config)
|
||||
|
||||
# inject packed and ignored modules to the quantization config of draft model
|
||||
if draft_quant_config is not None:
|
||||
configure_quant_config(draft_quant_config, Qwen4ExpMTP)
|
||||
ignored_layers = getattr(draft_quant_config, "ignored_layers", None)
|
||||
if ignored_layers:
|
||||
setattr( # noqa: B010
|
||||
draft_quant_config,
|
||||
"ignored_layers",
|
||||
_remap_ignored_layers(ignored_layers, mtp_start_layer_idx),
|
||||
)
|
||||
exclude_modules = getattr(draft_quant_config, "exclude_modules", None)
|
||||
if exclude_modules:
|
||||
setattr( # noqa: B010
|
||||
draft_quant_config,
|
||||
"exclude_modules",
|
||||
_remap_ignored_layers(exclude_modules, mtp_start_layer_idx),
|
||||
)
|
||||
|
||||
draft_vllm_config = replace(
|
||||
vllm_config,
|
||||
model_config=speculative_config.draft_model_config,
|
||||
)
|
||||
# VllmConfig post-init derives the target quant config, so restore the
|
||||
# independently resolved draft quant config after replacement.
|
||||
draft_vllm_config.quant_config = draft_quant_config
|
||||
return draft_vllm_config
|
||||
|
||||
|
||||
@support_torch_compile(
|
||||
dynamic_arg_dims={
|
||||
"input_ids": 0,
|
||||
"positions": -1,
|
||||
"intermediate_tensors": 0,
|
||||
"inputs_embeds": 0,
|
||||
"hidden_states": 0,
|
||||
}
|
||||
)
|
||||
class Qwen4ExpMultiTokenPredictor(nn.Module):
|
||||
hf_to_vllm_mapper = Qwen3_5Model.hf_to_vllm_mapper | _HC_WEIGHTS_MAPPER
|
||||
|
||||
def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None:
|
||||
super().__init__()
|
||||
|
||||
model_config = vllm_config.model_config
|
||||
config: Qwen4ExpTextConfig = model_config.hf_text_config
|
||||
|
||||
self.config = config
|
||||
self.vocab_size = config.vocab_size
|
||||
|
||||
self.mtp_start_layer_idx = config.num_hidden_layers
|
||||
self.num_mtp_layers = getattr(config, "mtp_num_hidden_layers", 1)
|
||||
|
||||
self.hidden_size = config.hidden_size
|
||||
self.hc_count = config.hc_count
|
||||
|
||||
self.embed_tokens = VocabParallelEmbedding(self.vocab_size, self.hidden_size)
|
||||
draft_vllm_config = _make_draft_vllm_config(
|
||||
vllm_config,
|
||||
self.mtp_start_layer_idx,
|
||||
)
|
||||
with set_current_vllm_config(draft_vllm_config, prefix=prefix):
|
||||
# residual_linear_shared fusion: fc_embedding projects the token
|
||||
# embedding, fc_hidden (shared across HC branches) projects the
|
||||
# backbone hidden; the embedding is added as a residual to every
|
||||
# branch (see mtp_residual_linear_shared.md).
|
||||
self.fc_embedding = ColumnParallelLinear(
|
||||
self.hidden_size,
|
||||
self.hidden_size,
|
||||
gather_output=True,
|
||||
bias=False,
|
||||
return_bias=False,
|
||||
quant_config=draft_vllm_config.quant_config,
|
||||
prefix=f"{prefix}.fc_embedding",
|
||||
)
|
||||
self.fc_hidden = ColumnParallelLinear(
|
||||
self.hidden_size,
|
||||
self.hidden_size,
|
||||
gather_output=True,
|
||||
bias=False,
|
||||
return_bias=False,
|
||||
quant_config=draft_vllm_config.quant_config,
|
||||
prefix=f"{prefix}.fc_hidden",
|
||||
)
|
||||
self.layers = nn.ModuleList(
|
||||
Qwen4ExpDecoderLayer(
|
||||
draft_vllm_config,
|
||||
layer_type="full_attention",
|
||||
prefix=f"{prefix}.layers.{self.mtp_start_layer_idx + idx}",
|
||||
)
|
||||
for idx in range(self.num_mtp_layers)
|
||||
)
|
||||
self.is_fused_shared_expert_enabled = is_model_fused_shared_expert_compatible(
|
||||
self.layers,
|
||||
Qwen4ExpSparseMoeBlock,
|
||||
"mlp",
|
||||
)
|
||||
|
||||
self.pre_fc_norm_embedding = GemmaRMSNorm(
|
||||
self.hidden_size, eps=config.rms_norm_eps
|
||||
)
|
||||
self.pre_fc_norm_hidden = GemmaRMSNorm(
|
||||
self.hidden_size * self.hc_count, eps=config.rms_norm_eps
|
||||
)
|
||||
# HC final mixer collapses the multi stream into [T, H] for the LM head.
|
||||
hc_config = HyperConnectionConfig(
|
||||
hc_count=config.hc_count,
|
||||
hidden_size=config.hidden_size,
|
||||
params_dtype=torch.bfloat16,
|
||||
hc_lowrank=config.hc_lowrank,
|
||||
rms_norm_eps=config.rms_norm_eps,
|
||||
hc_per_branch_norm=True,
|
||||
)
|
||||
self.hyper_connection_mixer = GatedResidual(
|
||||
hc_config,
|
||||
use_combine=False,
|
||||
prefix=maybe_prefix(prefix, "hyper_connection_mixer"),
|
||||
)
|
||||
self.make_empty_intermediate_tensors = make_empty_intermediate_tensors_factory(
|
||||
["hidden_states"], self.hidden_size * self.hc_count
|
||||
)
|
||||
|
||||
def _iter_qsa_attentions(self):
|
||||
"""Yield MTP attention modules that own a QSA indexer."""
|
||||
|
||||
for layer in self.layers:
|
||||
attention = getattr(layer, "self_attn", None)
|
||||
if (
|
||||
attention is not None
|
||||
and getattr(attention, "indexer", None) is not None
|
||||
):
|
||||
yield attention
|
||||
|
||||
def set_skip_topk(self, skip: bool) -> None:
|
||||
"""Select on MTP step 0 and reuse its QSA indices on later steps."""
|
||||
|
||||
for attention in self._iter_qsa_attentions():
|
||||
attention.indexer.skip_topk = skip
|
||||
|
||||
def compact_topk_indices(self, row_indices: torch.Tensor) -> None:
|
||||
"""Keep each request's target-aligned step-0 sparse-index row."""
|
||||
|
||||
num_rows = row_indices.numel()
|
||||
for attention in self._iter_qsa_attentions():
|
||||
buffer = attention.topk_indices_buffer
|
||||
selected = buffer.index_select(0, row_indices)
|
||||
buffer[:num_rows].copy_(selected)
|
||||
|
||||
def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
|
||||
return self.embed_tokens(input_ids)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.Tensor | None,
|
||||
positions: torch.Tensor,
|
||||
hidden_states: torch.Tensor | None = None,
|
||||
intermediate_tensors: IntermediateTensors | None = None,
|
||||
inputs_embeds: torch.Tensor | None = None,
|
||||
spec_step_idx: int = 0,
|
||||
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor] | IntermediateTensors:
|
||||
hc_count = self.hc_count
|
||||
hidden_size = self.hidden_size
|
||||
|
||||
if get_pp_group().is_first_rank:
|
||||
assert hidden_states is not None
|
||||
if inputs_embeds is None:
|
||||
assert input_ids is not None
|
||||
inputs_embeds = self.embed_input_ids(input_ids)
|
||||
# Embedding branch: pre-norm -> fc_embedding -> [T, H].
|
||||
inputs_embeds = self.pre_fc_norm_embedding(inputs_embeds)
|
||||
inputs_embeds = self.fc_embedding(inputs_embeds)
|
||||
|
||||
# Backbone hidden is multi-stream [T, hc_count*H] (scheme A:
|
||||
# the main model truly emits the pre-final-mixer multi stream
|
||||
# on the first step; subsequent steps reuse the prior draft
|
||||
# step's multi stream).
|
||||
num_tokens = hidden_states.shape[0]
|
||||
hidden_states = hidden_states.view(num_tokens, hc_count, hidden_size)
|
||||
hidden_states = self.pre_fc_norm_hidden(hidden_states.flatten(-2)).view(
|
||||
num_tokens, hc_count, hidden_size
|
||||
)
|
||||
hidden_states = self.fc_hidden(hidden_states)
|
||||
# Add the embedding residual to every branch, then fold back
|
||||
# to [T, hc_count*H] (HC outer, HS inner) for the HC decoder.
|
||||
hidden_states = inputs_embeds.unsqueeze(-2) + hidden_states
|
||||
hidden_states = hidden_states.flatten(-2)
|
||||
else:
|
||||
assert intermediate_tensors is not None
|
||||
hidden_states = intermediate_tensors["hidden_states"]
|
||||
|
||||
current_step_idx = spec_step_idx % self.num_mtp_layers
|
||||
layer = self.layers[current_step_idx]
|
||||
hidden_states, block_output, injection = layer(
|
||||
hidden_states=hidden_states,
|
||||
prev_block_output=None,
|
||||
prev_injection=None,
|
||||
positions=positions,
|
||||
input_ids=None,
|
||||
query_start_loc=None,
|
||||
ngram_context=None,
|
||||
)
|
||||
if not get_pp_group().is_last_rank:
|
||||
# As in the target model, PP carries a materialized tensor rather
|
||||
# than the delayed hidden/output/injection tuple.
|
||||
hidden_states = layer.mlp_hyper_connection.combine(
|
||||
hidden_states, block_output, injection
|
||||
)
|
||||
return IntermediateTensors({"hidden_states": hidden_states})
|
||||
|
||||
# Last PP rank finalize. Keep both:
|
||||
# (A) sample_hidden_states [T, H] -> single stream for the LM head
|
||||
# (B) multi_hidden [T, hc_count*H] -> pre-final-mixer multi stream
|
||||
# for the next draft step (zero extra compute, just kept).
|
||||
multi_hidden, sample_hidden_states, _ = (
|
||||
self.hyper_connection_mixer.combine_and_mix(
|
||||
hidden_states, block_output, injection
|
||||
)
|
||||
)
|
||||
return sample_hidden_states, multi_hidden
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
weights = maybe_fuse_shared_experts(
|
||||
weights,
|
||||
enabled=self.is_fused_shared_expert_enabled,
|
||||
n_routed_experts=getattr(self.config, "num_experts", 0) or 0,
|
||||
n_shared_experts=1,
|
||||
ckpt_prefix="mlp.shared_expert",
|
||||
)
|
||||
mapper = self.hf_to_vllm_mapper | WeightsMapper(
|
||||
orig_to_new_substr={"hyper_connection_mixer.block_inject_weight": None}
|
||||
)
|
||||
loader = AutoWeightsLoader(
|
||||
self,
|
||||
ignore_unexpected_suffixes=_QWEN4_EXP_IGNORED_MISSING_SUFFIXES.copy(),
|
||||
)
|
||||
return loader.load_weights(weights, mapper=mapper)
|
||||
|
||||
|
||||
@support_torch_compile(
|
||||
dynamic_arg_dims={
|
||||
"input_ids": 0,
|
||||
"positions": -1,
|
||||
"intermediate_tensors": 0,
|
||||
"inputs_embeds": 0,
|
||||
"hidden_states": 0,
|
||||
}
|
||||
)
|
||||
class Qwen4ExpMTP(nn.Module, SupportsPP, Qwen4ExpMixtureOfExperts):
|
||||
packed_modules_mapping = {
|
||||
"qkv_proj": ["q_proj", "k_proj", "v_proj"],
|
||||
"gate_up_proj": ["gate_proj", "up_proj"],
|
||||
"in_proj_qkvz": ["in_proj_qkv", "in_proj_z"],
|
||||
"in_proj_ba": ["in_proj_b", "in_proj_a"],
|
||||
"input_mix_weight_down_block_inject": [
|
||||
"input_mix_weight_down",
|
||||
"block_inject_weight",
|
||||
"_input_mix_padding",
|
||||
],
|
||||
}
|
||||
|
||||
def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None:
|
||||
config: Qwen4ExpTextConfig = vllm_config.model_config.hf_text_config
|
||||
self.vllm_config = vllm_config
|
||||
cache_config = vllm_config.cache_config
|
||||
if cache_config.mamba_cache_mode == "all":
|
||||
raise NotImplementedError(
|
||||
"Qwen4ExpMTP currently does not support 'all' prefix caching, "
|
||||
"please use '--mamba-cache-mode=align' instead"
|
||||
)
|
||||
|
||||
self.quant_config = vllm_config.quant_config
|
||||
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.model = Qwen4ExpMultiTokenPredictor(
|
||||
vllm_config=vllm_config,
|
||||
prefix=maybe_prefix(prefix, "mtp"),
|
||||
)
|
||||
|
||||
if get_pp_group().is_last_rank:
|
||||
if config.tie_word_embeddings:
|
||||
self.lm_head = self.model.embed_tokens
|
||||
else:
|
||||
self.lm_head = ParallelLMHead(
|
||||
config.vocab_size,
|
||||
config.hidden_size,
|
||||
prefix=maybe_prefix(prefix, "lm_head"),
|
||||
)
|
||||
else:
|
||||
self.lm_head = PPMissingLayer()
|
||||
|
||||
self.logits_processor = LogitsProcessor(config.vocab_size)
|
||||
self.make_empty_intermediate_tensors = (
|
||||
self.model.make_empty_intermediate_tensors
|
||||
)
|
||||
self.set_moe_parameters(self.model.layers)
|
||||
enable_qwen4_exp_low_latency_gemm(self, vllm_config.model_config.dtype)
|
||||
|
||||
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 | None,
|
||||
positions: torch.Tensor,
|
||||
hidden_states: torch.Tensor | None = None,
|
||||
intermediate_tensors: IntermediateTensors | None = None,
|
||||
inputs_embeds: torch.Tensor | None = None,
|
||||
spec_step_idx: int = 0,
|
||||
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor] | IntermediateTensors:
|
||||
return self.model(
|
||||
input_ids,
|
||||
positions,
|
||||
hidden_states,
|
||||
intermediate_tensors,
|
||||
inputs_embeds,
|
||||
spec_step_idx=spec_step_idx,
|
||||
)
|
||||
|
||||
def compute_logits(
|
||||
self, hidden_states: torch.Tensor, spec_step_idx: int = 0
|
||||
) -> torch.Tensor | None:
|
||||
return self.logits_processor(self.lm_head, hidden_states)
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
def remap_weight_names():
|
||||
for name, weight in weights:
|
||||
remapped_name = _remap_mtp_weight_name(name)
|
||||
if remapped_name is not None:
|
||||
yield remapped_name, weight
|
||||
|
||||
mapper = WeightsMapper(
|
||||
orig_to_new_substr={"hyper_connection_mixer.block_inject_weight": None}
|
||||
)
|
||||
loader = AutoWeightsLoader(
|
||||
self,
|
||||
ignore_unexpected_suffixes=_QWEN4_EXP_IGNORED_MISSING_SUFFIXES.copy(),
|
||||
)
|
||||
return loader.load_weights(remap_weight_names(), mapper=mapper)
|
||||
|
||||
|
||||
__all__ = ["Qwen4ExpMTP", "Qwen4ExpMultiTokenPredictor"]
|
||||
@@ -0,0 +1,3 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""AMD ROCm Qwen4Exp kernels; import leaf modules directly."""
|
||||
@@ -0,0 +1,487 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""AMD ROCm HyperConnection kernels for Qwen4Exp."""
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import tl, triton
|
||||
from vllm.utils.torch_utils import direct_register_custom_op
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _grouped_gemma_rmsnorm_kernel(
|
||||
x_ptr,
|
||||
w_ptr,
|
||||
y_ptr,
|
||||
stride_x,
|
||||
stride_y,
|
||||
DIM: tl.constexpr,
|
||||
NUM_GROUPS: tl.constexpr,
|
||||
W_SHARED: tl.constexpr,
|
||||
EPS: tl.constexpr,
|
||||
launch_pdl: tl.constexpr,
|
||||
) -> None:
|
||||
GROUP_DIM: tl.constexpr = DIM // NUM_GROUPS
|
||||
BLOCK_SIZE: tl.constexpr = triton.next_power_of_2(GROUP_DIM)
|
||||
|
||||
pid = tl.program_id(0)
|
||||
group_id = pid % NUM_GROUPS
|
||||
row = pid // NUM_GROUPS
|
||||
|
||||
offs_g = tl.arange(0, BLOCK_SIZE)
|
||||
offsets = group_id * GROUP_DIM + offs_g
|
||||
mask = offs_g < GROUP_DIM
|
||||
# A [GROUP_DIM] affine is shared; a [DIM] affine follows the grouped
|
||||
# checkpoint layout.
|
||||
w_offs = offs_g if W_SHARED else offsets
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_wait()
|
||||
|
||||
x = tl.load(x_ptr + row * stride_x + offsets, mask, other=0.0).to(tl.float32)
|
||||
w = tl.load(w_ptr + w_offs, mask, other=0.0)
|
||||
|
||||
rrms = tl.rsqrt(tl.sum(x * x) / GROUP_DIM + EPS)
|
||||
# Gemma's (1 + w) affine is written this way to lower to an FMA.
|
||||
y = x * rrms
|
||||
y += y * w.to(tl.float32)
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_launch_dependents()
|
||||
tl.store(y_ptr + row * stride_y + offsets, y, mask)
|
||||
|
||||
|
||||
def _grouped_gemma_rmsnorm(
|
||||
x: torch.Tensor, weight: torch.Tensor, eps: float, num_groups: int
|
||||
) -> torch.Tensor:
|
||||
N, DIM = x.shape
|
||||
assert x.stride(1) == 1, "grouped Gemma RMSNorm requires unit inner stride"
|
||||
assert weight.is_contiguous(), "grouped Gemma RMSNorm weight must be contiguous"
|
||||
assert DIM % num_groups == 0
|
||||
group_dim = DIM // num_groups
|
||||
assert weight.numel() in (group_dim, DIM)
|
||||
|
||||
y = x.new_empty(x.shape)
|
||||
_grouped_gemma_rmsnorm_kernel[(N * num_groups,)](
|
||||
x,
|
||||
weight,
|
||||
y,
|
||||
x.stride(0),
|
||||
y.stride(0),
|
||||
DIM,
|
||||
num_groups,
|
||||
W_SHARED=weight.numel() == group_dim,
|
||||
EPS=eps,
|
||||
launch_pdl=current_platform.is_arch_support_pdl(),
|
||||
)
|
||||
return y
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _hc_silu_kernel(
|
||||
x_ptr,
|
||||
y_ptr,
|
||||
stride_x,
|
||||
stride_y,
|
||||
DIM: tl.constexpr,
|
||||
HC: tl.constexpr,
|
||||
launch_pdl: tl.constexpr,
|
||||
) -> None:
|
||||
BLOCK_SIZE: tl.constexpr = triton.next_power_of_2(DIM)
|
||||
|
||||
row = tl.program_id(0)
|
||||
offs = tl.arange(0, BLOCK_SIZE)
|
||||
mask = offs < DIM
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_wait()
|
||||
|
||||
x = tl.load(x_ptr + row * stride_x + offs, mask).to(tl.float32) / HC
|
||||
y = x * tl.sigmoid(x)
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_launch_dependents()
|
||||
tl.store(y_ptr + row * stride_y + offs, y, mask)
|
||||
|
||||
|
||||
def _hc_silu(x: torch.Tensor, hc_count: int) -> torch.Tensor:
|
||||
num_tokens, DIM = x.shape
|
||||
assert x.stride(1) == 1
|
||||
|
||||
output = x.new_empty(x.shape)
|
||||
_hc_silu_kernel[(num_tokens,)](
|
||||
x,
|
||||
output,
|
||||
x.stride(0),
|
||||
output.stride(0),
|
||||
DIM=DIM,
|
||||
HC=hc_count,
|
||||
launch_pdl=current_platform.is_arch_support_pdl(),
|
||||
)
|
||||
return output
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _hc_gate_mix_kernel(
|
||||
x_ptr,
|
||||
g_ptr,
|
||||
y_ptr,
|
||||
stride_x,
|
||||
stride_g,
|
||||
stride_y,
|
||||
DIM: tl.constexpr,
|
||||
HC: tl.constexpr,
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
launch_pdl: tl.constexpr,
|
||||
) -> None:
|
||||
HC_DIM: tl.constexpr = DIM // HC
|
||||
|
||||
row = tl.program_id(0)
|
||||
tile_id = tl.program_id(1)
|
||||
offs_inner = tile_id * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
|
||||
mask = offs_inner < HC_DIM
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_wait()
|
||||
|
||||
# The constexpr loop is unrolled and keeps one stream live at a time.
|
||||
# Materializing [HC, BLOCK_SIZE] more than doubles latency at large M.
|
||||
acc = tl.zeros([BLOCK_SIZE], dtype=tl.float32)
|
||||
for stream in tl.static_range(HC):
|
||||
offsets = stream * HC_DIM + offs_inner
|
||||
g = tl.load(g_ptr + row * stride_g + offsets, mask, other=0.0)
|
||||
x = tl.load(x_ptr + row * stride_x + offsets, mask, other=0.0)
|
||||
acc += tl.sigmoid(g.to(tl.float32)) * x.to(tl.float32)
|
||||
acc /= HC
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_launch_dependents()
|
||||
tl.store(y_ptr + row * stride_y + offs_inner, acc, mask)
|
||||
|
||||
|
||||
def _hc_gate_mix(x: torch.Tensor, gate: torch.Tensor, hc_count: int) -> torch.Tensor:
|
||||
N, DIM = gate.shape
|
||||
assert x.shape == gate.shape
|
||||
assert DIM % hc_count == 0
|
||||
assert x.stride(1) == 1
|
||||
assert gate.stride(1) == 1
|
||||
|
||||
HC_DIM = DIM // hc_count
|
||||
out = x.new_empty(N, HC_DIM)
|
||||
BLOCK_SIZE = 512
|
||||
_hc_gate_mix_kernel[(N, triton.cdiv(HC_DIM, BLOCK_SIZE))](
|
||||
x,
|
||||
gate,
|
||||
out,
|
||||
x.stride(0),
|
||||
gate.stride(0),
|
||||
out.stride(0),
|
||||
DIM,
|
||||
hc_count,
|
||||
BLOCK_SIZE,
|
||||
launch_pdl=current_platform.is_arch_support_pdl(),
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _hc_combine_kernel(
|
||||
block_ptr,
|
||||
res_ptr,
|
||||
inj_ptr,
|
||||
out_ptr,
|
||||
stride_block,
|
||||
stride_res,
|
||||
stride_inj,
|
||||
stride_out,
|
||||
HC_DIM: tl.constexpr,
|
||||
HC: tl.constexpr,
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
launch_pdl: tl.constexpr,
|
||||
) -> None:
|
||||
HC_PAD: tl.constexpr = triton.next_power_of_2(HC)
|
||||
|
||||
row = tl.program_id(0)
|
||||
tile_id = tl.program_id(1)
|
||||
|
||||
offs_inner = tile_id * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
|
||||
mask_inner = offs_inner < HC_DIM
|
||||
offs_hc = tl.arange(0, HC_PAD)
|
||||
mask_hc = offs_hc < HC
|
||||
offs = offs_hc[:, None] * HC_DIM + offs_inner[None, :]
|
||||
mask = mask_hc[:, None] & mask_inner[None, :]
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_wait()
|
||||
|
||||
inj = tl.load(inj_ptr + row * stride_inj + offs_hc, mask_hc, other=0.0)
|
||||
block = tl.load(block_ptr + row * stride_block + offs_inner, mask_inner, other=0.0)
|
||||
res = tl.load(res_ptr + row * stride_res + offs, mask, other=0.0)
|
||||
|
||||
# Keeping HC as a broadcast dimension is faster here than four separate
|
||||
# residual load/store sequences.
|
||||
inj = 2.0 * tl.sigmoid(inj.to(tl.float32) / HC)
|
||||
out = res.to(tl.float32) + block.to(tl.float32)[None, :] * inj[:, None]
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_launch_dependents()
|
||||
tl.store(out_ptr + row * stride_out + offs, out, mask=mask)
|
||||
|
||||
|
||||
def _hc_combine(
|
||||
residual: torch.Tensor,
|
||||
block_output: torch.Tensor,
|
||||
injection_logits: torch.Tensor,
|
||||
hc_count: int,
|
||||
) -> torch.Tensor:
|
||||
N, DIM = residual.shape
|
||||
assert DIM % hc_count == 0
|
||||
hc_dim = DIM // hc_count
|
||||
assert block_output.shape == (N, hc_dim)
|
||||
assert injection_logits.shape == (N, hc_count)
|
||||
assert residual.stride(1) == 1
|
||||
assert block_output.stride(1) == 1
|
||||
assert injection_logits.stride(1) == 1
|
||||
|
||||
out = residual.new_empty(residual.shape)
|
||||
BLOCK_SIZE = 512
|
||||
_hc_combine_kernel[(N, triton.cdiv(hc_dim, BLOCK_SIZE))](
|
||||
block_output,
|
||||
residual,
|
||||
injection_logits,
|
||||
out,
|
||||
block_output.stride(0),
|
||||
residual.stride(0),
|
||||
injection_logits.stride(0),
|
||||
out.stride(0),
|
||||
hc_dim,
|
||||
hc_count,
|
||||
BLOCK_SIZE,
|
||||
launch_pdl=current_platform.is_arch_support_pdl(),
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _hc_combine_norm_kernel(
|
||||
block_ptr,
|
||||
res_ptr,
|
||||
inj_ptr,
|
||||
w_ptr,
|
||||
out_ptr,
|
||||
y_ptr,
|
||||
stride_block,
|
||||
stride_res,
|
||||
stride_inj,
|
||||
stride_out,
|
||||
stride_y,
|
||||
HC_DIM: tl.constexpr,
|
||||
HC: tl.constexpr,
|
||||
W_SHARED: tl.constexpr,
|
||||
EPS: tl.constexpr,
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
launch_pdl: tl.constexpr,
|
||||
) -> None:
|
||||
HC_PAD: tl.constexpr = triton.next_power_of_2(HC)
|
||||
NUM_TILES: tl.constexpr = triton.cdiv(HC_DIM, BLOCK_SIZE)
|
||||
NUM_TILES_PAD: tl.constexpr = triton.next_power_of_2(NUM_TILES)
|
||||
|
||||
row = tl.program_id(0)
|
||||
stream = tl.program_id(1)
|
||||
offs_hc = tl.arange(0, HC_PAD)
|
||||
mask_hc = offs_hc < HC
|
||||
tile_ids = tl.arange(0, NUM_TILES_PAD)
|
||||
offs_inner = tile_ids[:, None] * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)[None, :]
|
||||
mask_inner = offs_inner < HC_DIM
|
||||
offs = stream * HC_DIM + offs_inner
|
||||
# Shared norm weights repeat across streams; per-branch weights use the
|
||||
# same flattened HC layout as the residual.
|
||||
w_offs = offs_inner if W_SHARED else offs
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_wait()
|
||||
|
||||
# Start the uncached residual load first, then issue the other combine
|
||||
# loads before consuming any of them.
|
||||
res = tl.load(res_ptr + row * stride_res + offs, mask_inner, other=0.0)
|
||||
inj = tl.load(inj_ptr + row * stride_inj + offs_hc, mask_hc, other=0.0)
|
||||
block = tl.load(block_ptr + row * stride_block + offs_inner, mask_inner, other=0.0)
|
||||
inj = 2.0 * tl.sigmoid(inj.to(tl.float32) / HC)
|
||||
inj = tl.sum(tl.where(offs_hc == stream, inj, 0.0))
|
||||
# Round the materialized combine result before normalization. This matches
|
||||
# the unfused combine -> RMSNorm boundary.
|
||||
out = (res.to(tl.float32) + block.to(tl.float32) * inj).to(out_ptr.dtype.element_ty)
|
||||
tl.store(out_ptr + row * stride_out + offs, out, mask=mask_inner)
|
||||
|
||||
out = out.to(tl.float32)
|
||||
# Keep the two-axis reduction: flattening the padded tile is ~40% slower
|
||||
# at decode sizes.
|
||||
sum_sq = tl.sum(tl.sum(out * out, axis=1), axis=0)
|
||||
rrms = tl.rsqrt(sum_sq / HC_DIM + EPS)
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_launch_dependents()
|
||||
|
||||
# Loading the weight earlier helps decode but keeps the tile live across
|
||||
# the reduction and regresses larger batches, so defer it to the norm.
|
||||
w = tl.load(w_ptr + w_offs, mask_inner, other=0.0)
|
||||
y = out * rrms
|
||||
y += y * w.to(tl.float32)
|
||||
tl.store(y_ptr + row * stride_y + offs, y, mask_inner)
|
||||
|
||||
|
||||
def _hc_combine_norm(
|
||||
residual: torch.Tensor,
|
||||
block_output: torch.Tensor,
|
||||
injection_logits: torch.Tensor,
|
||||
norm_weight: torch.Tensor,
|
||||
eps: float,
|
||||
hc_count: int,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
N, DIM = residual.shape
|
||||
assert DIM % hc_count == 0
|
||||
hc_dim = DIM // hc_count
|
||||
assert block_output.shape == (N, hc_dim)
|
||||
assert injection_logits.shape == (N, hc_count)
|
||||
assert residual.stride(1) == 1
|
||||
assert block_output.stride(1) == 1
|
||||
assert injection_logits.stride(1) == 1
|
||||
assert norm_weight.is_contiguous()
|
||||
assert norm_weight.numel() in (hc_dim, DIM)
|
||||
|
||||
out = residual.new_empty(residual.shape)
|
||||
y = residual.new_empty(residual.shape)
|
||||
BLOCK_SIZE = 512
|
||||
_hc_combine_norm_kernel[(N, hc_count)](
|
||||
block_output,
|
||||
residual,
|
||||
injection_logits,
|
||||
norm_weight,
|
||||
out,
|
||||
y,
|
||||
block_output.stride(0),
|
||||
residual.stride(0),
|
||||
injection_logits.stride(0),
|
||||
out.stride(0),
|
||||
y.stride(0),
|
||||
hc_dim,
|
||||
hc_count,
|
||||
W_SHARED=norm_weight.numel() == hc_dim,
|
||||
EPS=eps,
|
||||
BLOCK_SIZE=BLOCK_SIZE,
|
||||
launch_pdl=current_platform.is_arch_support_pdl(),
|
||||
)
|
||||
return out, y
|
||||
|
||||
|
||||
def _same_shape_fake(x: torch.Tensor, *args) -> torch.Tensor:
|
||||
return x.new_empty(x.shape)
|
||||
|
||||
|
||||
def _hc_gate_mix_fake(
|
||||
x: torch.Tensor, gate: torch.Tensor, hc_count: int
|
||||
) -> torch.Tensor:
|
||||
del gate
|
||||
return x.new_empty((x.shape[0], x.shape[1] // hc_count))
|
||||
|
||||
|
||||
def _hc_combine_fake(
|
||||
residual: torch.Tensor,
|
||||
block_output: torch.Tensor,
|
||||
injection_logits: torch.Tensor,
|
||||
hc_count: int,
|
||||
) -> torch.Tensor:
|
||||
del block_output, injection_logits, hc_count
|
||||
return residual.new_empty(residual.shape)
|
||||
|
||||
|
||||
def _hc_combine_norm_fake(
|
||||
residual: torch.Tensor,
|
||||
block_output: torch.Tensor,
|
||||
injection_logits: torch.Tensor,
|
||||
norm_weight: torch.Tensor,
|
||||
eps: float,
|
||||
hc_count: int,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
del block_output, injection_logits, norm_weight, eps, hc_count
|
||||
return residual.new_empty(residual.shape), residual.new_empty(residual.shape)
|
||||
|
||||
|
||||
direct_register_custom_op(
|
||||
op_name="qwen4_exp_grouped_gemma_rmsnorm",
|
||||
op_func=_grouped_gemma_rmsnorm,
|
||||
fake_impl=_same_shape_fake,
|
||||
)
|
||||
direct_register_custom_op(
|
||||
op_name="qwen4_exp_hc_silu",
|
||||
op_func=_hc_silu,
|
||||
fake_impl=_same_shape_fake,
|
||||
)
|
||||
direct_register_custom_op(
|
||||
op_name="qwen4_exp_hc_gate_mix",
|
||||
op_func=_hc_gate_mix,
|
||||
fake_impl=_hc_gate_mix_fake,
|
||||
)
|
||||
direct_register_custom_op(
|
||||
op_name="qwen4_exp_hc_combine",
|
||||
op_func=_hc_combine,
|
||||
fake_impl=_hc_combine_fake,
|
||||
)
|
||||
direct_register_custom_op(
|
||||
op_name="qwen4_exp_hc_combine_norm",
|
||||
op_func=_hc_combine_norm,
|
||||
fake_impl=_hc_combine_norm_fake,
|
||||
)
|
||||
|
||||
|
||||
def grouped_gemma_rmsnorm(
|
||||
x: torch.Tensor, weight: torch.Tensor, eps: float, num_groups: int
|
||||
) -> torch.Tensor:
|
||||
return torch.ops.vllm.qwen4_exp_grouped_gemma_rmsnorm(x, weight, eps, num_groups)
|
||||
|
||||
|
||||
def hc_silu(x: torch.Tensor, hc_count: int) -> torch.Tensor:
|
||||
return torch.ops.vllm.qwen4_exp_hc_silu(x, hc_count)
|
||||
|
||||
|
||||
def hc_gate_mix(x: torch.Tensor, gate: torch.Tensor, hc_count: int) -> torch.Tensor:
|
||||
return torch.ops.vllm.qwen4_exp_hc_gate_mix(x, gate, hc_count)
|
||||
|
||||
|
||||
def hc_combine(
|
||||
residual: torch.Tensor,
|
||||
block_output: torch.Tensor,
|
||||
injection_logits: torch.Tensor,
|
||||
hc_count: int,
|
||||
) -> torch.Tensor:
|
||||
return torch.ops.vllm.qwen4_exp_hc_combine(
|
||||
residual, block_output, injection_logits, hc_count
|
||||
)
|
||||
|
||||
|
||||
def hc_combine_norm(
|
||||
residual: torch.Tensor,
|
||||
block_output: torch.Tensor,
|
||||
injection_logits: torch.Tensor,
|
||||
norm_weight: torch.Tensor,
|
||||
eps: float,
|
||||
hc_count: int,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
return torch.ops.vllm.qwen4_exp_hc_combine_norm(
|
||||
residual,
|
||||
block_output,
|
||||
injection_logits,
|
||||
norm_weight,
|
||||
eps,
|
||||
hc_count,
|
||||
)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"grouped_gemma_rmsnorm",
|
||||
"hc_combine",
|
||||
"hc_combine_norm",
|
||||
"hc_gate_mix",
|
||||
"hc_silu",
|
||||
]
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,474 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""AMD ROCm QSA owner with Triton kernels."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import ClassVar, cast
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.config.cache import CacheDType
|
||||
from vllm.distributed import get_tensor_model_parallel_world_size
|
||||
from vllm.forward_context import get_forward_context
|
||||
from vllm.model_executor.layers.attention.attention import (
|
||||
set_default_quant_scales,
|
||||
)
|
||||
from vllm.model_executor.layers.attention_layer_base import AttentionLayerBase
|
||||
from vllm.model_executor.layers.layernorm import GemmaRMSNorm
|
||||
from vllm.model_executor.layers.linear import QKVParallelLinear, RowParallelLinear
|
||||
from vllm.model_executor.layers.quantization import QuantizationConfig
|
||||
from vllm.model_executor.layers.rotary_embedding import get_rope
|
||||
from vllm.model_executor.models.qwen3_next import Qwen3NextAttention
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.transformers_utils.configs.qwen4_exp import (
|
||||
Qwen4ExpTextConfig,
|
||||
)
|
||||
from vllm.utils.torch_utils import (
|
||||
LayerNameType,
|
||||
_encode_layer_name,
|
||||
_resolve_layer_name,
|
||||
canonicalize_singleton_dim_strides,
|
||||
direct_register_custom_op,
|
||||
kv_cache_dtype_str_to_dtype,
|
||||
)
|
||||
from vllm.v1.attention.backend import (
|
||||
AttentionBackend,
|
||||
AttentionCGSupport,
|
||||
AttentionType,
|
||||
MultipleOf,
|
||||
)
|
||||
from vllm.v1.attention.backends.fa_utils import is_flash_attn_varlen_func_available
|
||||
from vllm.v1.attention.backends.flash_attn import (
|
||||
FlashAttentionBackend,
|
||||
FlashAttentionImpl,
|
||||
FlashAttentionMetadata,
|
||||
FlashAttentionMetadataBuilder,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
FullAttentionSpec,
|
||||
KVCacheSpec,
|
||||
get_kv_quant_mode,
|
||||
)
|
||||
|
||||
from ..common.qsa_cache import QSAForwardMetadata
|
||||
from . import model
|
||||
from .indexer_qsa import QSAIndexer
|
||||
|
||||
|
||||
class Qwen4ExpQSAMetadataBuilder(FlashAttentionMetadataBuilder):
|
||||
"""Flash metadata supporting uniform decode and target-verify graphs."""
|
||||
|
||||
_cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.UNIFORM_BATCH
|
||||
|
||||
|
||||
class Qwen4ExpQSAFlashAttentionBackend(FlashAttentionBackend):
|
||||
"""FullAttentionSpec backend used by the merged QSA owner."""
|
||||
|
||||
supported_dtypes: ClassVar[list[torch.dtype]] = [torch.bfloat16]
|
||||
supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = ["auto", "bfloat16"]
|
||||
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
return "QWEN4_EXP_QSA_TRITON"
|
||||
|
||||
@staticmethod
|
||||
def get_supported_kernel_block_sizes() -> list[int | MultipleOf]:
|
||||
# QSA consumes manager pages directly and does not use FA4 paged attention.
|
||||
return [MultipleOf(16)]
|
||||
|
||||
@staticmethod
|
||||
def get_impl_cls() -> type[Qwen4ExpQSAFlashAttentionImpl]:
|
||||
return Qwen4ExpQSAFlashAttentionImpl
|
||||
|
||||
@staticmethod
|
||||
def get_builder_cls() -> type[Qwen4ExpQSAMetadataBuilder]:
|
||||
return Qwen4ExpQSAMetadataBuilder
|
||||
|
||||
@classmethod
|
||||
def is_sparse(cls) -> bool:
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def supports_kv_connector(cls) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
class Qwen4ExpQSAFlashAttentionImpl(FlashAttentionImpl):
|
||||
"""Run paged sparse GQA with the QSA Triton kernel."""
|
||||
|
||||
supports_dcp: bool = False
|
||||
supports_pcp: bool = False
|
||||
|
||||
def __init__(self, *args, **kwargs) -> None:
|
||||
super().__init__(*args, **kwargs)
|
||||
if not is_flash_attn_varlen_func_available():
|
||||
raise NotImplementedError("Qwen4Exp QSA requires FlashAttention")
|
||||
if self.dcp_world_size != 1:
|
||||
raise NotImplementedError(
|
||||
"Qwen4Exp QSA does not support decode context parallelism"
|
||||
)
|
||||
if self.kv_cache_dtype not in ("auto", "bfloat16"):
|
||||
raise NotImplementedError("Qwen4Exp QSA requires a BF16 main KV cache")
|
||||
self.supports_quant_query_input = False
|
||||
|
||||
def forward_qsa(
|
||||
self,
|
||||
layer: torch.nn.Module,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
kv_cache: torch.Tensor,
|
||||
attn_metadata: FlashAttentionMetadata,
|
||||
output: torch.Tensor,
|
||||
token_to_req: torch.Tensor,
|
||||
output_scale: torch.Tensor | None = None,
|
||||
output_block_scale: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
del key, value
|
||||
if output_scale is not None or output_block_scale is not None:
|
||||
raise NotImplementedError("QSA does not support fused output quantization")
|
||||
if self.alibi_slopes is not None or self.sinks is not None:
|
||||
raise NotImplementedError("QSA does not support ALiBi or attention sinks")
|
||||
if self.sliding_window != (-1, -1):
|
||||
raise NotImplementedError("QSA does not support sliding-window attention")
|
||||
|
||||
num_tokens = attn_metadata.num_actual_tokens
|
||||
output.zero_()
|
||||
if num_tokens == 0:
|
||||
return output
|
||||
|
||||
topk_buffer = getattr(layer, "topk_indices_buffer", None)
|
||||
if topk_buffer is None:
|
||||
raise RuntimeError("QSA owner did not provide its top-k buffer")
|
||||
logical_indices = topk_buffer[:num_tokens]
|
||||
token_to_req = token_to_req[:num_tokens]
|
||||
key_cache, value_cache = kv_cache.transpose(1, 2).split(self.head_size, dim=-1)
|
||||
key_cache = canonicalize_singleton_dim_strides(key_cache)
|
||||
value_cache = canonicalize_singleton_dim_strides(value_cache)
|
||||
if key_cache.dtype != torch.bfloat16 or query.dtype != torch.bfloat16:
|
||||
raise NotImplementedError("Qwen4Exp QSA requires BF16 Q/K/V")
|
||||
|
||||
from .ops.qsa import qsa_sparse_paged_attention
|
||||
|
||||
qsa_sparse_paged_attention(
|
||||
query[:num_tokens],
|
||||
key_cache,
|
||||
value_cache,
|
||||
logical_indices,
|
||||
attn_metadata.block_table,
|
||||
token_to_req,
|
||||
output[:num_tokens],
|
||||
)
|
||||
return output
|
||||
|
||||
|
||||
class Qwen4ExpQSAAttention(Qwen3NextAttention, AttentionLayerBase):
|
||||
"""Merged Qwen full-attention owner with a QSA index side branch."""
|
||||
|
||||
supports_dcp = False
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
vllm_config: VllmConfig,
|
||||
config: Qwen4ExpTextConfig,
|
||||
layer_id: int,
|
||||
quant_config: QuantizationConfig | None = None,
|
||||
reduce_results: bool = True,
|
||||
prefix: str = "",
|
||||
) -> None:
|
||||
nn.Module.__init__(self)
|
||||
cache_config = vllm_config.cache_config
|
||||
model_config = vllm_config.model_config
|
||||
if cache_config is None:
|
||||
raise ValueError("Qwen4Exp QSA requires a paged KV cache")
|
||||
if model_config.dtype != torch.bfloat16:
|
||||
raise NotImplementedError("Qwen4Exp QSA currently requires BF16")
|
||||
if cache_config.cache_dtype not in ("auto", "bfloat16"):
|
||||
raise NotImplementedError("Qwen4Exp QSA requires a BF16 main KV cache")
|
||||
if getattr(quant_config, "kv_cache_scheme", None) is not None:
|
||||
raise NotImplementedError("Qwen4Exp QSA does not support KV quantization")
|
||||
parallel_config = vllm_config.parallel_config
|
||||
if (
|
||||
parallel_config.prefill_context_parallel_size > 1
|
||||
or parallel_config.decode_context_parallel_size > 1
|
||||
):
|
||||
raise NotImplementedError(
|
||||
"Qwen4Exp QSA does not support context parallelism"
|
||||
)
|
||||
if not getattr(config, "is_causal", True):
|
||||
raise NotImplementedError("Qwen4Exp QSA requires causal decoder attention")
|
||||
|
||||
self.config = config
|
||||
self.hidden_size = int(config.hidden_size)
|
||||
tp_size = get_tensor_model_parallel_world_size()
|
||||
self.total_num_heads = int(config.num_attention_heads)
|
||||
if self.total_num_heads % tp_size:
|
||||
raise ValueError("QSA attention heads must be divisible by TP size")
|
||||
self.num_heads = self.total_num_heads // tp_size
|
||||
self.total_num_kv_heads = int(config.num_key_value_heads)
|
||||
if self.total_num_kv_heads >= tp_size:
|
||||
if self.total_num_kv_heads % tp_size:
|
||||
raise ValueError("QSA KV heads must be divisible by TP size")
|
||||
elif tp_size % self.total_num_kv_heads:
|
||||
raise ValueError("TP size must be divisible by replicated QSA KV heads")
|
||||
self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size)
|
||||
self.head_dim = int(config.head_dim or self.hidden_size // self.num_heads)
|
||||
self.q_size = self.num_heads * self.head_dim
|
||||
self.kv_size = self.num_kv_heads * self.head_dim
|
||||
self.scaling = self.head_dim**-0.5
|
||||
self.dual_chunk_attention_config = getattr(
|
||||
config, "dual_chunk_attention_config", None
|
||||
)
|
||||
if self.dual_chunk_attention_config is not None:
|
||||
raise NotImplementedError("Qwen4Exp QSA does not support dual-chunk RoPE")
|
||||
# Qwen4Exp full-attention checkpoints always pack a sigmoid output
|
||||
# gate next to Q, even when an inherited config default says otherwise.
|
||||
self.attn_output_gate = True
|
||||
|
||||
self.qkv_proj = QKVParallelLinear(
|
||||
self.hidden_size,
|
||||
self.head_dim,
|
||||
self.total_num_heads * (1 + self.attn_output_gate),
|
||||
self.total_num_kv_heads,
|
||||
bias=False,
|
||||
quant_config=model.without_modelopt_fp4(quant_config),
|
||||
prefix=f"{prefix}.qkv_proj",
|
||||
)
|
||||
self.o_proj = RowParallelLinear(
|
||||
self.total_num_heads * self.head_dim,
|
||||
self.hidden_size,
|
||||
bias=False,
|
||||
reduce_results=reduce_results,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.o_proj",
|
||||
)
|
||||
self.rotary_emb = get_rope(
|
||||
head_size=self.head_dim,
|
||||
max_position=config.max_position_embeddings,
|
||||
rope_parameters=config.rope_parameters,
|
||||
)
|
||||
self.q_norm = GemmaRMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
||||
self.k_norm = GemmaRMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
||||
|
||||
mm_config = model_config.multimodal_config
|
||||
text_only = mm_config is None or mm_config.language_model_only
|
||||
self.use_fused_qk_norm_rope_gate = (
|
||||
self.attn_output_gate
|
||||
and getattr(self.rotary_emb, "is_neox_style", False)
|
||||
and current_platform.is_cuda()
|
||||
and text_only
|
||||
)
|
||||
|
||||
self.layer_name = f"{prefix}.attn"
|
||||
self.attn_type = AttentionType.DECODER
|
||||
self.kv_cache_dtype = cache_config.cache_dtype
|
||||
self.kv_cache_torch_dtype = kv_cache_dtype_str_to_dtype(
|
||||
self.kv_cache_dtype, model_config
|
||||
)
|
||||
if self.kv_cache_torch_dtype != torch.bfloat16:
|
||||
raise NotImplementedError("Qwen4Exp QSA requires BF16 cache storage")
|
||||
self.kv_sharing_target_layer_name = None
|
||||
self.kv_cache = torch.tensor([])
|
||||
set_default_quant_scales(self, register_buffer=True)
|
||||
|
||||
self.attn_backend = Qwen4ExpQSAFlashAttentionBackend
|
||||
self.impl = Qwen4ExpQSAFlashAttentionImpl(
|
||||
self.num_heads,
|
||||
self.head_dim,
|
||||
self.scaling,
|
||||
self.num_kv_heads,
|
||||
None,
|
||||
None,
|
||||
self.kv_cache_dtype,
|
||||
None,
|
||||
AttentionType.DECODER,
|
||||
None,
|
||||
)
|
||||
self.indexer = QSAIndexer(
|
||||
vllm_config=vllm_config,
|
||||
config=config,
|
||||
layer_id=layer_id,
|
||||
rotary_emb=self.rotary_emb,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.indexer",
|
||||
)
|
||||
max_tokens = vllm_config.scheduler_config.max_num_batched_tokens
|
||||
self.register_buffer(
|
||||
"topk_indices_buffer",
|
||||
torch.empty(
|
||||
max_tokens,
|
||||
self.indexer.output_width,
|
||||
dtype=torch.int32,
|
||||
),
|
||||
persistent=False,
|
||||
)
|
||||
|
||||
static_context = vllm_config.compilation_config.static_forward_context
|
||||
if self.layer_name in static_context:
|
||||
raise ValueError(f"Duplicate layer name: {self.layer_name}")
|
||||
static_context[self.layer_name] = self
|
||||
|
||||
def get_attn_backend(self) -> type[AttentionBackend]:
|
||||
return self.attn_backend
|
||||
|
||||
def get_kv_cache_spec(self, vllm_config: VllmConfig) -> KVCacheSpec:
|
||||
return FullAttentionSpec(
|
||||
block_size=vllm_config.cache_config.block_size,
|
||||
num_kv_heads=self.num_kv_heads,
|
||||
head_size=self.head_dim,
|
||||
head_size_v=self.head_dim,
|
||||
dtype=self.kv_cache_torch_dtype,
|
||||
kv_quant_mode=get_kv_quant_mode(self.kv_cache_dtype),
|
||||
)
|
||||
|
||||
def _run_qsa(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
output: torch.Tensor,
|
||||
) -> None:
|
||||
metadata = get_forward_context().attn_metadata
|
||||
if isinstance(metadata, list):
|
||||
metadata = metadata[0]
|
||||
if not isinstance(metadata, dict):
|
||||
output.zero_()
|
||||
return
|
||||
main_metadata = cast(FlashAttentionMetadata, metadata[self.layer_name])
|
||||
if self.kv_cache.numel() == 0:
|
||||
raise RuntimeError("QSA main K/V cache is not bound")
|
||||
|
||||
num_tokens = main_metadata.num_actual_tokens
|
||||
side_metadata = cast(
|
||||
QSAForwardMetadata,
|
||||
metadata[self.indexer.raw_key_cache.prefix],
|
||||
)
|
||||
if side_metadata.num_actual_tokens != num_tokens:
|
||||
raise RuntimeError("QSA main and side metadata token counts disagree")
|
||||
selected = self.indexer(
|
||||
hidden_states,
|
||||
positions,
|
||||
self.topk_indices_buffer[:num_tokens],
|
||||
)
|
||||
if selected.shape != (
|
||||
num_tokens,
|
||||
self.indexer.output_width,
|
||||
):
|
||||
raise RuntimeError("QSA indexer returned an invalid selection shape")
|
||||
impl = cast(Qwen4ExpQSAFlashAttentionImpl, self.impl)
|
||||
impl.do_kv_cache_update(
|
||||
self,
|
||||
key,
|
||||
value,
|
||||
self.kv_cache,
|
||||
main_metadata.slot_mapping,
|
||||
)
|
||||
impl.forward_qsa(
|
||||
self,
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
self.kv_cache,
|
||||
main_metadata,
|
||||
output,
|
||||
token_to_req=side_metadata.token_to_req,
|
||||
)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
positions: torch.Tensor,
|
||||
hidden_states: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
qkv, _ = self.qkv_proj(hidden_states)
|
||||
q, k, v, gate = self._project_qkv_gate(qkv, positions)
|
||||
num_tokens = hidden_states.shape[0]
|
||||
query = q.view(num_tokens, self.num_heads, self.head_dim)
|
||||
key = k.view(num_tokens, self.num_kv_heads, self.head_dim)
|
||||
value = v.view(num_tokens, self.num_kv_heads, self.head_dim)
|
||||
attn_output = torch.empty_like(query)
|
||||
encoded_layer_name = _encode_layer_name(self.layer_name)
|
||||
if current_platform.opaque_attention_op():
|
||||
torch.ops.vllm.qwen4_exp_qsa_with_output(
|
||||
hidden_states,
|
||||
positions,
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
attn_output,
|
||||
encoded_layer_name,
|
||||
)
|
||||
else:
|
||||
qwen4_exp_qsa_with_output(
|
||||
hidden_states,
|
||||
positions,
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
attn_output,
|
||||
encoded_layer_name,
|
||||
)
|
||||
flat_output = attn_output.view(num_tokens, -1)
|
||||
if gate is not None:
|
||||
flat_output = flat_output * torch.sigmoid(gate)
|
||||
output, _ = self.o_proj(flat_output)
|
||||
return output
|
||||
|
||||
|
||||
def qwen4_exp_qsa_with_output(
|
||||
hidden_states: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
output: torch.Tensor,
|
||||
layer_name: LayerNameType,
|
||||
) -> None:
|
||||
"""Run the complete QSA state/update/attend transaction."""
|
||||
|
||||
layer_name = _resolve_layer_name(layer_name)
|
||||
layer = get_forward_context().no_compile_layers[layer_name]
|
||||
if not isinstance(layer, Qwen4ExpQSAAttention):
|
||||
raise TypeError(f"{layer_name} is not a Qwen4Exp QSA owner")
|
||||
layer._run_qsa(
|
||||
hidden_states,
|
||||
positions,
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
output,
|
||||
)
|
||||
|
||||
|
||||
def qwen4_exp_qsa_with_output_fake(
|
||||
hidden_states: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
output: torch.Tensor,
|
||||
layer_name: LayerNameType,
|
||||
) -> None:
|
||||
del hidden_states, positions, query, key, value, output, layer_name
|
||||
|
||||
|
||||
direct_register_custom_op(
|
||||
op_name="qwen4_exp_qsa_with_output",
|
||||
op_func=qwen4_exp_qsa_with_output,
|
||||
mutates_args=["output"],
|
||||
fake_impl=qwen4_exp_qsa_with_output_fake,
|
||||
)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"QSAIndexer",
|
||||
"Qwen4ExpQSAAttention",
|
||||
"Qwen4ExpQSAFlashAttentionBackend",
|
||||
"Qwen4ExpQSAFlashAttentionImpl",
|
||||
"qwen4_exp_qsa_with_output",
|
||||
]
|
||||
@@ -0,0 +1,17 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Common Qwen4Exp model components."""
|
||||
|
||||
from .hyperconnection import (
|
||||
GatedResidual,
|
||||
GroupedGemmaRMSNorm,
|
||||
HyperConnectionBase,
|
||||
HyperConnectionConfig,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"GatedResidual",
|
||||
"GroupedGemmaRMSNorm",
|
||||
"HyperConnectionBase",
|
||||
"HyperConnectionConfig",
|
||||
]
|
||||
@@ -0,0 +1,250 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""HyperConnection (Gated Residual) utilities.
|
||||
|
||||
Implements the HyperConnection residual scheme proposed in
|
||||
"HyperConnections" (https://arxiv.org/abs/2409.19606).
|
||||
|
||||
The two concrete variants are:
|
||||
- ``HyperConnectionBase`` - simple average pooling across hc_count parallel
|
||||
streams (equivalent to hyperconnection_average).
|
||||
- ``GatedResidual`` - learnable low-rank gated mixing and injection
|
||||
(gated_residual).
|
||||
|
||||
Hidden states between layers have shape ``[..., HC*HS]`` with HS inner
|
||||
(HC outer, HS inner — checkpoint-native layout). The local torch
|
||||
implementation consumes the hyper input viewed as ``[..., HC, HS]``.
|
||||
|
||||
Typical usage inside a transformer decoder layer::
|
||||
|
||||
self.attn_hc = GatedResidual(hc_config, role="attn")
|
||||
self.mlp_hc = GatedResidual(hc_config, role="mlp")
|
||||
|
||||
hidden_states, residual = self.attn_hc.mix(hidden_states)
|
||||
hidden_states = attention(hidden_states)
|
||||
hidden_states = self.attn_hc.combine(hidden_states, residual)
|
||||
|
||||
hidden_states, residual = self.mlp_hc.mix(hidden_states)
|
||||
hidden_states = mlp(hidden_states)
|
||||
hidden_states = self.mlp_hc.combine(hidden_states, residual)
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch import nn
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Config
|
||||
# ---------------------------------------------------------------------------
|
||||
@dataclass
|
||||
class HyperConnectionConfig:
|
||||
"""Configuration shared by all HyperConnection variants."""
|
||||
|
||||
hc_count: int = 4
|
||||
hidden_size: int = 64
|
||||
params_dtype: torch.dtype = torch.bfloat16
|
||||
mtp_hc: bool = False
|
||||
hc_lowrank: int = 16
|
||||
rms_norm_eps: float = 1e-6
|
||||
hc_per_branch_norm: bool = False
|
||||
|
||||
|
||||
class GroupedGemmaRMSNorm(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
hidden_size: int,
|
||||
eps: float,
|
||||
group_size: int | None,
|
||||
dtype: torch.dtype | None,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
if group_size is not None and hidden_size % group_size:
|
||||
raise ValueError(
|
||||
f"hidden_size ({hidden_size}) must be divisible by "
|
||||
f"group_size ({group_size})"
|
||||
)
|
||||
self.variance_epsilon = eps
|
||||
self.group_size = group_size
|
||||
self.weight = nn.Parameter(torch.zeros(hidden_size, dtype=dtype))
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
input_dtype = hidden_states.dtype
|
||||
hidden_states = hidden_states.float()
|
||||
if self.group_size is None:
|
||||
variance = hidden_states.square().mean(dim=-1, keepdim=True)
|
||||
normalized = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
||||
else:
|
||||
grouped = hidden_states.unflatten(
|
||||
-1, (hidden_states.shape[-1] // self.group_size, self.group_size)
|
||||
)
|
||||
variance = grouped.square().mean(dim=-1, keepdim=True)
|
||||
normalized = (
|
||||
grouped * torch.rsqrt(variance + self.variance_epsilon)
|
||||
).flatten(-2)
|
||||
return (normalized * (1.0 + self.weight.float())).to(input_dtype)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Average-pooling variant
|
||||
# ---------------------------------------------------------------------------
|
||||
class HyperConnectionBase(nn.Module):
|
||||
"""Average-pooling HyperConnection (``hyperconnection_average``).
|
||||
|
||||
Splits the incoming ``[..., HC*HS]`` tensor (HC outer, HS inner) into
|
||||
``HC`` parallel streams, averages them for the block input, and
|
||||
broadcasts the block output back to every stream.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config: HyperConnectionConfig,
|
||||
layer_idx: int | None = None,
|
||||
role: str | None = None,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.hc_count = config.hc_count
|
||||
self.hidden_size = config.hidden_size
|
||||
self.layer_idx = layer_idx
|
||||
self.role = role
|
||||
|
||||
@property
|
||||
def hyper_hidden_size(self) -> int:
|
||||
return self.hc_count * self.hidden_size
|
||||
|
||||
def mix(self, hyper_input: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Average the HC streams into a single block input."""
|
||||
assert hyper_input.shape[-1] == self.hc_count * self.hidden_size
|
||||
# [*, HC, HS] — mean over HC (dim=-2).
|
||||
unflat = hyper_input.unflatten(-1, (self.hc_count, self.hidden_size))
|
||||
mixed_input = unflat.mean(dim=-2)
|
||||
return mixed_input, hyper_input
|
||||
|
||||
def combine(
|
||||
self, block_output: torch.Tensor, residual: torch.Tensor
|
||||
) -> torch.Tensor:
|
||||
"""Broadcast the block output back to every stream."""
|
||||
assert residual.shape[-1] == self.hc_count * self.hidden_size
|
||||
assert block_output.shape[-1] == self.hidden_size
|
||||
residual_reshaped = residual.unflatten(-1, (self.hc_count, self.hidden_size))
|
||||
combined = residual_reshaped + block_output.unsqueeze(-2)
|
||||
return combined.flatten(-2)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Gated-residual variant
|
||||
# ---------------------------------------------------------------------------
|
||||
class GatedResidual(HyperConnectionBase):
|
||||
"""Gated HyperConnection with learnable low-rank mixing and injection.
|
||||
|
||||
``mix()`` applies GemmaRMSNorm per HC stream and projects through a
|
||||
low-rank sigmoid gate to produce a single block input. ``combine()``
|
||||
injects the block output back into each stream through a learned
|
||||
per-stream injection weight.
|
||||
|
||||
This implementation uses only PyTorch operators. Tensor-parallel
|
||||
collectives are supplied by its caller.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config: HyperConnectionConfig,
|
||||
layer_idx: int | None = None,
|
||||
role: str | None = None,
|
||||
use_mix: bool = True,
|
||||
use_combine: bool = True,
|
||||
) -> None:
|
||||
super().__init__(config, layer_idx, role)
|
||||
norm_size = (
|
||||
self.hyper_hidden_size if config.hc_per_branch_norm else config.hidden_size
|
||||
)
|
||||
group_size = config.hidden_size if config.hc_per_branch_norm else None
|
||||
# Normalize each H-sized HC stream independently while retaining a
|
||||
# separate affine weight for every element of the HC*H layout.
|
||||
self.hc_norm = GroupedGemmaRMSNorm(
|
||||
norm_size,
|
||||
eps=config.rms_norm_eps,
|
||||
group_size=group_size,
|
||||
dtype=config.params_dtype,
|
||||
)
|
||||
|
||||
# -- raw Linear weights (checkpoint-compatible) ----------------------
|
||||
if use_mix:
|
||||
self.input_mix_weight_down = nn.Linear(
|
||||
self.hyper_hidden_size,
|
||||
config.hc_lowrank,
|
||||
bias=False,
|
||||
dtype=config.params_dtype,
|
||||
)
|
||||
self.input_mix_weight_up = nn.Linear(
|
||||
config.hc_lowrank,
|
||||
self.hyper_hidden_size,
|
||||
bias=False,
|
||||
dtype=config.params_dtype,
|
||||
)
|
||||
if use_combine:
|
||||
self.block_inject_weight = nn.Linear(
|
||||
self.hyper_hidden_size,
|
||||
self.hc_count,
|
||||
bias=False,
|
||||
dtype=config.params_dtype,
|
||||
)
|
||||
|
||||
def _normalize(self, hyper_input: torch.Tensor) -> torch.Tensor:
|
||||
if self.config.hc_per_branch_norm:
|
||||
return self.hc_norm(hyper_input)
|
||||
return self.hc_norm(
|
||||
hyper_input.unflatten(-1, (self.hc_count, self.hidden_size))
|
||||
).flatten(-2)
|
||||
|
||||
def mix(
|
||||
self, hyper_input: torch.Tensor
|
||||
) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor]]:
|
||||
"""Mix: RMSNorm -> low-rank gate -> gated mean."""
|
||||
assert hyper_input.shape[-1] == self.hc_count * self.hidden_size
|
||||
if not hasattr(self, "input_mix_weight_down"):
|
||||
raise RuntimeError("mix was disabled for this hyper-connection")
|
||||
hyper_input_normed = self._normalize(hyper_input)
|
||||
# Gate — original mix order: linear+silu then linear+sigmoid.
|
||||
gate = F.silu(
|
||||
F.linear(hyper_input_normed, self.input_mix_weight_down.weight)
|
||||
/ self.hc_count
|
||||
)
|
||||
gate = torch.sigmoid(F.linear(gate, self.input_mix_weight_up.weight)).unflatten(
|
||||
-1, (self.hc_count, self.hidden_size)
|
||||
)
|
||||
mixed_input = (
|
||||
gate * hyper_input_normed.unflatten(-1, (self.hc_count, self.hidden_size))
|
||||
).mean(dim=-2)
|
||||
return mixed_input.to(hyper_input.dtype), (hyper_input, hyper_input_normed)
|
||||
|
||||
def combine(
|
||||
self,
|
||||
block_output: torch.Tensor,
|
||||
residuals: tuple[torch.Tensor, torch.Tensor],
|
||||
) -> torch.Tensor:
|
||||
if not hasattr(self, "block_inject_weight"):
|
||||
raise RuntimeError("combine was disabled for this hyper-connection")
|
||||
hyper_input, hyper_input_normed = residuals
|
||||
assert hyper_input.shape[-1] == self.hc_count * self.hidden_size
|
||||
assert block_output.shape[-1] == self.hidden_size
|
||||
residual = hyper_input.unflatten(-1, (self.hc_count, self.hidden_size))
|
||||
# The paired mix keeps its normalized hyper input so combine uses the
|
||||
# same HC module's injection weight.
|
||||
injection_weight = 2.0 * torch.sigmoid(
|
||||
F.linear(hyper_input_normed, self.block_inject_weight.weight)
|
||||
/ self.hc_count
|
||||
)
|
||||
output = residual + block_output.unsqueeze(-2) * injection_weight.unsqueeze(-1)
|
||||
return output.flatten(-2).to(hyper_input.dtype)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"GatedResidual",
|
||||
"GroupedGemmaRMSNorm",
|
||||
"HyperConnectionBase",
|
||||
"HyperConnectionConfig",
|
||||
]
|
||||
@@ -0,0 +1,100 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Common Qwen4Exp PLE helpers."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.model_executor.layers.vocab_parallel_embedding import (
|
||||
VocabParallelEmbedding,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PLEShardOverlap:
|
||||
"""Source and destination slices for one checkpoint embedding shard."""
|
||||
|
||||
source_start: int
|
||||
destination_start: int
|
||||
row_count: int
|
||||
|
||||
|
||||
def compute_ple_shard_overlap(
|
||||
*,
|
||||
checkpoint_start: int,
|
||||
checkpoint_rows: int,
|
||||
tp_start: int,
|
||||
tp_end: int,
|
||||
) -> PLEShardOverlap | None:
|
||||
"""Compute the overlap of a checkpoint shard and one TP vocabulary range."""
|
||||
|
||||
if checkpoint_start < 0 or checkpoint_rows < 0:
|
||||
raise ValueError("checkpoint shard bounds must be non-negative")
|
||||
if tp_start < 0 or tp_end < tp_start:
|
||||
raise ValueError("invalid TP vocabulary range")
|
||||
checkpoint_end = checkpoint_start + checkpoint_rows
|
||||
overlap_start = max(checkpoint_start, tp_start)
|
||||
overlap_end = min(checkpoint_end, tp_end)
|
||||
if overlap_start >= overlap_end:
|
||||
return None
|
||||
return PLEShardOverlap(
|
||||
source_start=overlap_start - checkpoint_start,
|
||||
destination_start=overlap_start - tp_start,
|
||||
row_count=overlap_end - overlap_start,
|
||||
)
|
||||
|
||||
|
||||
def copy_ple_embedding_shard_(
|
||||
destination: torch.Tensor,
|
||||
loaded_weight: torch.Tensor,
|
||||
*,
|
||||
checkpoint_start: int,
|
||||
tp_start: int,
|
||||
tp_end: int,
|
||||
) -> int:
|
||||
"""Copy the overlapping rows of a PLE checkpoint shard into a TP table."""
|
||||
|
||||
if destination.ndim == 0 or loaded_weight.ndim != destination.ndim:
|
||||
raise ValueError("destination and loaded weight must have matching ranks")
|
||||
if destination.shape[1:] != loaded_weight.shape[1:]:
|
||||
raise ValueError(
|
||||
"embedding shard dimensions do not match: "
|
||||
f"{tuple(destination.shape[1:])} != {tuple(loaded_weight.shape[1:])}"
|
||||
)
|
||||
if destination.shape[0] < tp_end - tp_start:
|
||||
raise ValueError("destination does not cover the requested TP range")
|
||||
overlap = compute_ple_shard_overlap(
|
||||
checkpoint_start=checkpoint_start,
|
||||
checkpoint_rows=loaded_weight.shape[0],
|
||||
tp_start=tp_start,
|
||||
tp_end=tp_end,
|
||||
)
|
||||
if overlap is None:
|
||||
return 0
|
||||
source = loaded_weight.narrow(0, overlap.source_start, overlap.row_count)
|
||||
target = destination.narrow(0, overlap.destination_start, overlap.row_count)
|
||||
with torch.no_grad():
|
||||
target.copy_(source.to(device=target.device, dtype=target.dtype))
|
||||
return overlap.row_count
|
||||
|
||||
|
||||
class PLEVocabParallelEmbedding(VocabParallelEmbedding):
|
||||
"""Vocab-parallel embedding that accepts checkpoint row shards."""
|
||||
|
||||
def weight_loader(
|
||||
self,
|
||||
param: torch.Tensor,
|
||||
loaded_weight: torch.Tensor,
|
||||
checkpoint_start: int | None = None,
|
||||
) -> None:
|
||||
if checkpoint_start is None:
|
||||
super().weight_loader(param, loaded_weight)
|
||||
return
|
||||
copy_ple_embedding_shard_(
|
||||
param,
|
||||
loaded_weight,
|
||||
checkpoint_start=checkpoint_start,
|
||||
tp_start=self.shard_indices.org_vocab_start_index,
|
||||
tp_end=self.shard_indices.org_vocab_end_index,
|
||||
)
|
||||
@@ -0,0 +1,807 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Paged side-cache ownership and metadata for Qwen4Exp QSA.
|
||||
|
||||
Each QSA layer keeps a fixed circular buffer of raw index keys (the
|
||||
compressor state) and one compressed key. MRoPE models pack exact three-axis
|
||||
positions beside the raw keys; text models derive group positions from
|
||||
logical positions. The compressor state uses one block per request, while
|
||||
the compressed owner uses ``MLAAttentionSpec.tokens_per_state`` so its block
|
||||
table follows the main KV-cache lifecycle. Their physical tensor storage is
|
||||
shared by the generic cache-layout planner.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from dataclasses import dataclass
|
||||
from functools import cache
|
||||
from typing import ClassVar
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from vllm.config import CacheConfig, VllmConfig
|
||||
from vllm.config.cache import CacheDType
|
||||
from vllm.model_executor.layers.attention_layer_base import AttentionLayerBase
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import HAS_TRITON, tl, triton
|
||||
from vllm.utils.math_utils import cdiv
|
||||
from vllm.v1.attention.backend import (
|
||||
AttentionBackend,
|
||||
AttentionCGSupport,
|
||||
AttentionMetadata,
|
||||
AttentionMetadataBuilder,
|
||||
CommonAttentionMetadata,
|
||||
)
|
||||
from vllm.v1.attention.backends.utils import PAD_SLOT_ID
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
AttentionSpec,
|
||||
CircularBufferSpec,
|
||||
KVCacheLayout,
|
||||
KVCacheSpec,
|
||||
MLAAttentionSpec,
|
||||
)
|
||||
|
||||
|
||||
def canonical_qsa_rope_positions(positions: torch.Tensor) -> torch.Tensor:
|
||||
"""Return exact per-token positions as ``[tokens, 1, 3]`` int64 rows."""
|
||||
|
||||
if positions.ndim == 1:
|
||||
positions = positions.unsqueeze(0).expand(3, -1)
|
||||
elif positions.ndim != 2 or positions.shape[0] not in (1, 3):
|
||||
raise ValueError("QSA RoPE positions must be [tokens] or [1|3, tokens]")
|
||||
if positions.shape[0] == 1:
|
||||
positions = positions.expand(3, -1)
|
||||
return positions.transpose(0, 1).unsqueeze(1).to(torch.int64)
|
||||
|
||||
|
||||
def _logical_positions(
|
||||
query_start_loc: torch.Tensor,
|
||||
seq_lens: torch.Tensor,
|
||||
token_to_req: torch.Tensor,
|
||||
num_tokens: int,
|
||||
) -> torch.Tensor:
|
||||
if num_tokens == 0:
|
||||
return seq_lens.new_empty((0,), dtype=torch.int64)
|
||||
arange = torch.arange(num_tokens, device=query_start_loc.device)
|
||||
requests = token_to_req[:num_tokens].long()
|
||||
query_lens = torch.diff(query_start_loc)
|
||||
within_query = arange - query_start_loc.index_select(0, requests)
|
||||
return (
|
||||
seq_lens.index_select(0, requests).long()
|
||||
- query_lens.index_select(0, requests).long()
|
||||
+ within_query.long()
|
||||
)
|
||||
|
||||
|
||||
def _logical_to_physical_qsa_slots(
|
||||
block_table: torch.Tensor,
|
||||
request_indices: torch.Tensor,
|
||||
logical_positions: torch.Tensor,
|
||||
block_size: int,
|
||||
) -> torch.Tensor:
|
||||
if block_size <= 0:
|
||||
raise ValueError("QSA cache block size must be positive")
|
||||
if block_table.ndim != 2:
|
||||
raise ValueError("QSA block table must be two-dimensional")
|
||||
if request_indices.shape != logical_positions.shape:
|
||||
request_indices = torch.broadcast_to(request_indices, logical_positions.shape)
|
||||
|
||||
requests = request_indices.to(device=block_table.device, dtype=torch.long)
|
||||
positions = logical_positions.to(device=block_table.device, dtype=torch.long)
|
||||
valid = (requests >= 0) & (requests < block_table.shape[0]) & (positions >= 0)
|
||||
logical_blocks = torch.div(
|
||||
positions.clamp_min(0), block_size, rounding_mode="floor"
|
||||
)
|
||||
valid &= logical_blocks < block_table.shape[1]
|
||||
safe_requests = requests.clamp(0, max(block_table.shape[0] - 1, 0))
|
||||
safe_blocks = logical_blocks.clamp(0, max(block_table.shape[1] - 1, 0))
|
||||
if not all(block_table.shape):
|
||||
return torch.full_like(positions, PAD_SLOT_ID)
|
||||
physical_blocks = block_table[safe_requests, safe_blocks].long()
|
||||
valid &= physical_blocks >= 0
|
||||
slots = physical_blocks * block_size + positions.remainder(block_size)
|
||||
return torch.where(valid, slots, PAD_SLOT_ID)
|
||||
|
||||
|
||||
def circular_qsa_slot_mapping(
|
||||
block_table: torch.Tensor,
|
||||
token_to_req: torch.Tensor,
|
||||
logical_positions: torch.Tensor,
|
||||
compressor_state_size: int,
|
||||
query_start_loc: torch.Tensor | None = None,
|
||||
out: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Map each request to its fixed physical block as a circular token ring."""
|
||||
|
||||
if compressor_state_size <= 0:
|
||||
raise ValueError("QSA circular buffer size must be positive")
|
||||
if block_table.ndim != 2:
|
||||
raise ValueError("QSA block table must be two-dimensional")
|
||||
|
||||
requests = token_to_req.to(device=block_table.device, dtype=torch.long)
|
||||
positions = logical_positions.to(device=block_table.device, dtype=torch.long)
|
||||
if not all(block_table.shape):
|
||||
slots = torch.full_like(positions, PAD_SLOT_ID)
|
||||
else:
|
||||
valid = (requests >= 0) & (requests < block_table.shape[0]) & (positions >= 0)
|
||||
safe_requests = requests.clamp(0, block_table.shape[0] - 1)
|
||||
physical_blocks = block_table[safe_requests, 0].long()
|
||||
valid &= physical_blocks >= 0
|
||||
slots = physical_blocks * compressor_state_size + positions.remainder(
|
||||
compressor_state_size
|
||||
)
|
||||
slots = torch.where(valid, slots, PAD_SLOT_ID)
|
||||
|
||||
if query_start_loc is not None:
|
||||
if query_start_loc.ndim != 1 or query_start_loc.shape[0] < 2:
|
||||
raise ValueError("QSA query starts must contain a terminal offset")
|
||||
query_start_loc = query_start_loc.to(block_table.device)
|
||||
num_requests = query_start_loc.shape[0] - 1
|
||||
safe_requests = requests.clamp(0, num_requests - 1)
|
||||
request_ends = query_start_loc.index_select(0, safe_requests + 1)
|
||||
rows = torch.arange(slots.numel(), device=slots.device)
|
||||
keep = (
|
||||
(requests >= 0)
|
||||
& (requests < num_requests)
|
||||
& (rows + compressor_state_size >= request_ends)
|
||||
)
|
||||
slots = torch.where(keep, slots, PAD_SLOT_ID)
|
||||
|
||||
slots = slots.to(torch.int64)
|
||||
if out is not None:
|
||||
out.fill_(PAD_SLOT_ID)
|
||||
out[: slots.numel()].copy_(slots)
|
||||
return out[: slots.numel()]
|
||||
return slots
|
||||
|
||||
|
||||
def compressed_qsa_slot_mapping(
|
||||
block_table: torch.Tensor,
|
||||
token_to_req: torch.Tensor,
|
||||
logical_positions: torch.Tensor,
|
||||
storage_block_size: int,
|
||||
compress_ratio: int,
|
||||
out: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Build boundary-only slots for an ``MLAAttentionSpec`` QSA cache."""
|
||||
|
||||
if storage_block_size <= 0 or compress_ratio <= 0:
|
||||
raise ValueError("QSA block size and compression ratio must be positive")
|
||||
compressed_positions = torch.div(
|
||||
logical_positions.clamp_min(0), compress_ratio, rounding_mode="floor"
|
||||
)
|
||||
slots = _logical_to_physical_qsa_slots(
|
||||
block_table,
|
||||
token_to_req,
|
||||
compressed_positions,
|
||||
storage_block_size,
|
||||
)
|
||||
valid = (logical_positions >= 0) & (
|
||||
(logical_positions + 1).remainder(compress_ratio) == 0
|
||||
)
|
||||
slots = torch.where(valid, slots, PAD_SLOT_ID).to(torch.int64)
|
||||
if out is not None:
|
||||
out.fill_(PAD_SLOT_ID)
|
||||
out[: slots.numel()].copy_(slots)
|
||||
return out[: slots.numel()]
|
||||
return slots
|
||||
|
||||
|
||||
@cache
|
||||
def _metadata_launch_pdl() -> bool:
|
||||
return current_platform.is_arch_support_pdl()
|
||||
|
||||
|
||||
@triton.jit(
|
||||
do_not_specialize=[
|
||||
"num_reqs",
|
||||
"num_mapped_tokens",
|
||||
"num_tokens",
|
||||
"max_num_work",
|
||||
"num_search_steps",
|
||||
"work_search_steps",
|
||||
]
|
||||
)
|
||||
def _build_qsa_metadata_kernel(
|
||||
query_start_loc_ptr,
|
||||
seq_lens_ptr,
|
||||
common_slot_mapping_ptr,
|
||||
block_table_ptr,
|
||||
token_to_req_ptr,
|
||||
logical_positions_ptr,
|
||||
slot_mapping_ptr,
|
||||
k_work_metadata_ptr,
|
||||
block_table_stride_0: tl.constexpr,
|
||||
block_table_stride_1: tl.constexpr,
|
||||
num_reqs,
|
||||
num_mapped_tokens,
|
||||
num_tokens,
|
||||
max_num_work,
|
||||
num_search_steps,
|
||||
work_search_steps,
|
||||
storage_block_size: tl.constexpr,
|
||||
compress_ratio: tl.constexpr,
|
||||
circular_buffer_size: tl.constexpr,
|
||||
num_block_table_columns: tl.constexpr,
|
||||
launch_pdl: tl.constexpr,
|
||||
TOKEN_BLOCK_SIZE: tl.constexpr,
|
||||
REQUEST_SCAN_SIZE: tl.constexpr,
|
||||
WORK_BLOCK_SIZE: tl.constexpr,
|
||||
):
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_wait()
|
||||
|
||||
pid = tl.program_id(0)
|
||||
token_idx = pid * TOKEN_BLOCK_SIZE + tl.arange(0, TOKEN_BLOCK_SIZE)
|
||||
store_mask = token_idx < num_tokens
|
||||
mapped = token_idx < num_mapped_tokens
|
||||
search_token_idx = tl.minimum(token_idx, num_mapped_tokens - 1)
|
||||
request_idx = tl.zeros((TOKEN_BLOCK_SIZE,), tl.int32)
|
||||
# Find the last query start at or before each token. The dynamic loop avoids
|
||||
# compiling a kernel variant for every ceil(log2(num_reqs)).
|
||||
for step in tl.range(0, num_search_steps):
|
||||
candidate = request_idx + (1 << (num_search_steps - step - 1))
|
||||
valid_candidate = candidate < num_reqs
|
||||
candidate_start = tl.load(
|
||||
query_start_loc_ptr + candidate,
|
||||
mask=valid_candidate,
|
||||
other=num_mapped_tokens + 1,
|
||||
)
|
||||
advance = valid_candidate & (candidate_start <= search_token_idx)
|
||||
request_idx = tl.where(advance, candidate, request_idx)
|
||||
query_start = tl.load(query_start_loc_ptr + request_idx, mask=mapped, other=0)
|
||||
query_end = tl.load(query_start_loc_ptr + request_idx + 1, mask=mapped, other=0)
|
||||
seq_len = tl.load(seq_lens_ptr + request_idx, mask=mapped, other=0)
|
||||
logical_position = seq_len - (query_end - query_start) + token_idx - query_start
|
||||
logical_position = tl.where(mapped, logical_position, -1)
|
||||
tl.store(
|
||||
token_to_req_ptr + token_idx,
|
||||
tl.where(mapped, request_idx, 0),
|
||||
mask=store_mask,
|
||||
)
|
||||
tl.store(
|
||||
logical_positions_ptr + token_idx,
|
||||
logical_position,
|
||||
mask=store_mask,
|
||||
)
|
||||
|
||||
# circular_buffer_size is constexpr, so each builder instance compiles out
|
||||
# the other QSA cache owner's slot-mapping rule.
|
||||
if circular_buffer_size > 0:
|
||||
valid = (
|
||||
mapped
|
||||
& (logical_position >= 0)
|
||||
& (token_idx + circular_buffer_size >= query_end)
|
||||
& (num_block_table_columns > 0)
|
||||
)
|
||||
physical_block = tl.load(
|
||||
block_table_ptr + request_idx * block_table_stride_0,
|
||||
mask=valid,
|
||||
other=-1,
|
||||
)
|
||||
valid &= physical_block >= 0
|
||||
slot = physical_block * circular_buffer_size + (
|
||||
logical_position % circular_buffer_size
|
||||
)
|
||||
elif compress_ratio != 1:
|
||||
compressed_position = tl.maximum(logical_position, 0) // compress_ratio
|
||||
logical_block = compressed_position // storage_block_size
|
||||
valid = (
|
||||
mapped
|
||||
& (logical_position >= 0)
|
||||
& ((logical_position + 1) % compress_ratio == 0)
|
||||
& (logical_block < num_block_table_columns)
|
||||
)
|
||||
physical_block = tl.load(
|
||||
block_table_ptr
|
||||
+ request_idx * block_table_stride_0
|
||||
+ logical_block * block_table_stride_1,
|
||||
mask=valid,
|
||||
other=-1,
|
||||
)
|
||||
valid &= physical_block >= 0
|
||||
valid &= (
|
||||
tl.load(common_slot_mapping_ptr + token_idx, mask=mapped, other=-1) >= 0
|
||||
)
|
||||
slot = physical_block * storage_block_size + (
|
||||
compressed_position % storage_block_size
|
||||
)
|
||||
if (circular_buffer_size > 0) or (compress_ratio != 1):
|
||||
tl.store(
|
||||
slot_mapping_ptr + token_idx,
|
||||
tl.where(valid, slot, -1),
|
||||
mask=store_mask,
|
||||
)
|
||||
work_tile_start = pid * WORK_BLOCK_SIZE
|
||||
has_work_tile = work_tile_start < max_num_work
|
||||
if k_work_metadata_ptr is not None and has_work_tile:
|
||||
# Every work CTA builds the request prefix in registers. Recomputing this
|
||||
# small vector lets CTAs write disjoint work tiles without a grid barrier.
|
||||
requests = tl.arange(0, REQUEST_SCAN_SIZE)
|
||||
valid_request = requests < num_reqs
|
||||
request_query_start = tl.load(
|
||||
query_start_loc_ptr + requests, mask=valid_request, other=0
|
||||
)
|
||||
request_query_end = tl.load(
|
||||
query_start_loc_ptr + requests + 1, mask=valid_request, other=0
|
||||
)
|
||||
request_seq_len = tl.load(seq_lens_ptr + requests, mask=valid_request, other=0)
|
||||
request_query_len = request_query_end - request_query_start
|
||||
chunk_start = request_seq_len - request_query_len
|
||||
num_groups = request_seq_len // compress_ratio - chunk_start // compress_ratio
|
||||
# Nonempty requests need one item even without a completed compression
|
||||
# group because work item zero also commits the current raw-K suffix.
|
||||
work_counts = tl.where(request_query_len > 0, tl.maximum(num_groups, 1), 0)
|
||||
work_ends = tl.cumsum(tl.where(valid_request, work_counts, 0), axis=0)
|
||||
total_work = tl.sum(tl.where(valid_request, work_counts, 0), axis=0)
|
||||
work_offsets = tl.arange(0, WORK_BLOCK_SIZE)
|
||||
work = work_tile_start + work_offsets
|
||||
in_bounds = work < max_num_work
|
||||
active = in_bounds & (work < total_work)
|
||||
request = tl.zeros((WORK_BLOCK_SIZE,), dtype=tl.int32)
|
||||
# Request zero starts at zero for every active work item. Descending
|
||||
# steps find the last request starting at or before this item.
|
||||
for step_idx in tl.range(0, work_search_steps):
|
||||
step = 1 << (work_search_steps - step_idx - 1)
|
||||
candidate = request + step
|
||||
valid_candidate = candidate < num_reqs
|
||||
candidate_start = tl.gather(work_ends, candidate - 1, 0)
|
||||
advance = active & valid_candidate & (candidate_start <= work)
|
||||
request = tl.where(advance, candidate, request)
|
||||
|
||||
if launch_pdl:
|
||||
# Let the dependent grid start launch setup while these CTAs finish
|
||||
# stores; its gdc_wait still orders access to the completed metadata.
|
||||
tl.extra.cuda.gdc_launch_dependents()
|
||||
|
||||
owner_work_start = tl.gather(work_ends, tl.maximum(request - 1, 0), 0)
|
||||
owner_work_start = tl.where(request == 0, 0, owner_work_start)
|
||||
work_in_request = work - owner_work_start
|
||||
tl.store(
|
||||
k_work_metadata_ptr + work * 2,
|
||||
tl.where(active, request, -1),
|
||||
mask=in_bounds,
|
||||
)
|
||||
tl.store(
|
||||
k_work_metadata_ptr + work * 2 + 1,
|
||||
tl.where(active, work_in_request, -1),
|
||||
mask=in_bounds,
|
||||
)
|
||||
|
||||
else:
|
||||
if launch_pdl:
|
||||
# A dependent grid launches only after every CTA has signaled.
|
||||
tl.extra.cuda.gdc_launch_dependents()
|
||||
|
||||
|
||||
def build_qsa_metadata_triton(
|
||||
common_attn_metadata: CommonAttentionMetadata,
|
||||
token_to_req_buffer: torch.Tensor,
|
||||
logical_positions_buffer: torch.Tensor,
|
||||
slot_mapping_buffer: torch.Tensor,
|
||||
*,
|
||||
storage_block_size: int,
|
||||
compress_ratio: int,
|
||||
circular_buffer_size: int = 0,
|
||||
k_work_metadata_buffer: torch.Tensor | None = None,
|
||||
request_capacity: int | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
"""Build QSA side-cache and optional pre-indexer work metadata."""
|
||||
num_tokens = common_attn_metadata.num_actual_tokens
|
||||
num_mapped_tokens = int(common_attn_metadata.query_start_loc_cpu[-1])
|
||||
token_to_req = token_to_req_buffer[:num_tokens]
|
||||
logical_positions = logical_positions_buffer[:num_tokens]
|
||||
slot_mapping = slot_mapping_buffer[:num_tokens]
|
||||
num_reqs = common_attn_metadata.query_start_loc.shape[0] - 1
|
||||
assert num_reqs > 0
|
||||
|
||||
if k_work_metadata_buffer is not None:
|
||||
if request_capacity is None:
|
||||
request_capacity = num_reqs
|
||||
assert request_capacity >= num_reqs
|
||||
# Pad for tl.arange while keeping the scan width stable across live batches.
|
||||
request_scan_size = 1 << int(math.ceil(math.log2(request_capacity)))
|
||||
max_num_work = k_work_metadata_buffer.shape[0]
|
||||
else:
|
||||
request_scan_size = 1
|
||||
max_num_work = 0
|
||||
|
||||
if num_tokens == 0 and k_work_metadata_buffer is None:
|
||||
return token_to_req, logical_positions, slot_mapping
|
||||
|
||||
block_table = common_attn_metadata.block_table_tensor
|
||||
num_search_steps = int(math.ceil(math.log2(num_reqs)))
|
||||
work_search_steps = int(math.ceil(math.log2(num_reqs)))
|
||||
# The same grid covers token tiles and, for the compressed cache, work tiles.
|
||||
num_token_blocks = cdiv(num_tokens, 128)
|
||||
num_work_blocks = (
|
||||
cdiv(max_num_work, 256) if k_work_metadata_buffer is not None else 0
|
||||
)
|
||||
_build_qsa_metadata_kernel[(max(num_token_blocks, num_work_blocks, 1),)](
|
||||
common_attn_metadata.query_start_loc,
|
||||
common_attn_metadata.seq_lens,
|
||||
common_attn_metadata.slot_mapping,
|
||||
block_table,
|
||||
token_to_req,
|
||||
logical_positions,
|
||||
slot_mapping,
|
||||
k_work_metadata_buffer,
|
||||
block_table.stride(0),
|
||||
block_table.stride(1),
|
||||
num_reqs,
|
||||
num_mapped_tokens,
|
||||
num_tokens,
|
||||
max_num_work,
|
||||
num_search_steps,
|
||||
work_search_steps,
|
||||
storage_block_size,
|
||||
compress_ratio,
|
||||
circular_buffer_size,
|
||||
block_table.shape[1],
|
||||
launch_pdl=_metadata_launch_pdl(),
|
||||
TOKEN_BLOCK_SIZE=128,
|
||||
REQUEST_SCAN_SIZE=request_scan_size,
|
||||
WORK_BLOCK_SIZE=256,
|
||||
num_warps=4,
|
||||
)
|
||||
if circular_buffer_size == 0 and compress_ratio == 1:
|
||||
slot_mapping = common_attn_metadata.slot_mapping[:num_tokens]
|
||||
return token_to_req, logical_positions, slot_mapping
|
||||
|
||||
|
||||
def _build_qsa_metadata_torch(
|
||||
common_attn_metadata: CommonAttentionMetadata,
|
||||
token_to_req_buffer: torch.Tensor,
|
||||
logical_positions_buffer: torch.Tensor,
|
||||
slot_mapping_buffer: torch.Tensor,
|
||||
*,
|
||||
storage_block_size: int,
|
||||
compress_ratio: int,
|
||||
circular_buffer_size: int = 0,
|
||||
k_work_metadata_buffer: torch.Tensor | None = None,
|
||||
request_capacity: int | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
del request_capacity
|
||||
num_tokens = common_attn_metadata.num_actual_tokens
|
||||
num_mapped_tokens = int(common_attn_metadata.query_start_loc_cpu[-1])
|
||||
logical_positions = logical_positions_buffer[:num_tokens]
|
||||
|
||||
token_to_req = common_attn_metadata.token_to_req_indices(token_to_req_buffer)[
|
||||
:num_tokens
|
||||
]
|
||||
logical_positions[:num_mapped_tokens].copy_(
|
||||
_logical_positions(
|
||||
common_attn_metadata.query_start_loc,
|
||||
common_attn_metadata.seq_lens,
|
||||
token_to_req[:num_mapped_tokens],
|
||||
num_mapped_tokens,
|
||||
)
|
||||
)
|
||||
if num_mapped_tokens < num_tokens:
|
||||
logical_positions[num_mapped_tokens:].fill_(-1)
|
||||
if circular_buffer_size > 0:
|
||||
slot_mapping = circular_qsa_slot_mapping(
|
||||
common_attn_metadata.block_table_tensor,
|
||||
token_to_req,
|
||||
logical_positions,
|
||||
circular_buffer_size,
|
||||
query_start_loc=common_attn_metadata.query_start_loc,
|
||||
out=slot_mapping_buffer,
|
||||
)
|
||||
elif compress_ratio == 1:
|
||||
slot_mapping = common_attn_metadata.slot_mapping[:num_tokens]
|
||||
else:
|
||||
slot_mapping = compressed_qsa_slot_mapping(
|
||||
common_attn_metadata.block_table_tensor,
|
||||
token_to_req,
|
||||
logical_positions,
|
||||
storage_block_size,
|
||||
compress_ratio,
|
||||
slot_mapping_buffer,
|
||||
)
|
||||
slot_mapping.masked_fill_(
|
||||
common_attn_metadata.slot_mapping[:num_tokens] < 0, -1
|
||||
)
|
||||
if k_work_metadata_buffer is not None:
|
||||
query_lens = (
|
||||
common_attn_metadata.query_start_loc[1:]
|
||||
- common_attn_metadata.query_start_loc[:-1]
|
||||
)
|
||||
chunk_starts = common_attn_metadata.seq_lens - query_lens
|
||||
num_work_per_request = (
|
||||
common_attn_metadata.seq_lens // compress_ratio
|
||||
- chunk_starts // compress_ratio
|
||||
)
|
||||
num_work_per_request = torch.where(
|
||||
query_lens > 0, num_work_per_request.clamp_min(1), 0
|
||||
)
|
||||
k_start_loc = torch.empty(
|
||||
query_lens.shape[0] + 1,
|
||||
dtype=torch.int32,
|
||||
device=query_lens.device,
|
||||
)
|
||||
k_start_loc[0] = 0
|
||||
torch.cumsum(num_work_per_request, 0, out=k_start_loc[1:])
|
||||
work = torch.arange(
|
||||
k_work_metadata_buffer.shape[0],
|
||||
device=k_work_metadata_buffer.device,
|
||||
)
|
||||
requests = torch.searchsorted(k_start_loc[1:], work, right=True)
|
||||
active = work < k_start_loc[-1]
|
||||
work_in_request = (
|
||||
work - k_start_loc[requests.clamp_max(query_lens.shape[0] - 1)]
|
||||
)
|
||||
k_work_metadata_buffer[:, 0].copy_(
|
||||
torch.where(active, requests, -1).to(torch.int32)
|
||||
)
|
||||
k_work_metadata_buffer[:, 1].copy_(
|
||||
torch.where(active, work_in_request, -1).to(torch.int32)
|
||||
)
|
||||
return token_to_req, logical_positions, slot_mapping
|
||||
|
||||
|
||||
# Resolve the fallback outside the per-step metadata hot path.
|
||||
build_qsa_metadata = (
|
||||
build_qsa_metadata_triton if HAS_TRITON else _build_qsa_metadata_torch
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class QSAForwardMetadata(AttentionMetadata):
|
||||
"""Common per-forward metadata for one QSA side cache."""
|
||||
|
||||
block_table: torch.Tensor
|
||||
slot_mapping: torch.Tensor
|
||||
seq_lens: torch.Tensor
|
||||
query_start_loc: torch.Tensor
|
||||
token_to_req: torch.Tensor
|
||||
logical_positions: torch.Tensor
|
||||
k_work_metadata: torch.Tensor
|
||||
num_actual_tokens: int
|
||||
storage_block_size: int
|
||||
compress_ratio: int
|
||||
|
||||
|
||||
class QSAMetadataBuilder(AttentionMetadataBuilder[QSAForwardMetadata]):
|
||||
"""Build QSA metadata from vLLM's cache-group-specific common metadata."""
|
||||
|
||||
_cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.UNIFORM_BATCH
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
kv_cache_spec: AttentionSpec,
|
||||
layer_names: list[str],
|
||||
vllm_config: VllmConfig,
|
||||
device: torch.device,
|
||||
) -> None:
|
||||
super().__init__(kv_cache_spec, layer_names, vllm_config, device)
|
||||
self.is_circular_buffer = isinstance(kv_cache_spec, CircularBufferSpec)
|
||||
if isinstance(kv_cache_spec, MLAAttentionSpec):
|
||||
compress_ratio = kv_cache_spec.tokens_per_state
|
||||
assert isinstance(compress_ratio, int), (
|
||||
"QSA compression requires an integer tokens_per_state"
|
||||
)
|
||||
self.compress_ratio = compress_ratio
|
||||
else:
|
||||
self.compress_ratio = 1
|
||||
self.storage_block_size = kv_cache_spec.num_states
|
||||
max_tokens = vllm_config.scheduler_config.max_num_batched_tokens
|
||||
self.token_to_req_buffer = torch.empty(
|
||||
max_tokens, dtype=torch.int32, device=device
|
||||
)
|
||||
self.slot_mapping_buffer = torch.empty(
|
||||
max_tokens, dtype=torch.int64, device=device
|
||||
)
|
||||
self.logical_positions_buffer = torch.empty(
|
||||
max_tokens, dtype=torch.int64, device=device
|
||||
)
|
||||
max_requests = vllm_config.scheduler_config.max_num_seqs
|
||||
self.request_capacity = max_requests
|
||||
if not self.is_circular_buffer and self.compress_ratio != 1:
|
||||
max_k_work = (
|
||||
max_tokens + (self.compress_ratio - 1) * max_requests
|
||||
) // self.compress_ratio
|
||||
self.k_work_metadata_buffer = torch.empty(
|
||||
max_k_work, 2, dtype=torch.int32, device=device
|
||||
)
|
||||
else:
|
||||
self.k_work_metadata_buffer = torch.empty(
|
||||
0, 2, dtype=torch.int32, device=device
|
||||
)
|
||||
|
||||
def build(
|
||||
self,
|
||||
common_prefix_len: int,
|
||||
common_attn_metadata: CommonAttentionMetadata,
|
||||
fast_build: bool = False,
|
||||
) -> QSAForwardMetadata:
|
||||
del common_prefix_len, fast_build
|
||||
num_tokens = common_attn_metadata.num_actual_tokens
|
||||
build_k_work = not self.is_circular_buffer and self.compress_ratio != 1
|
||||
k_work_metadata = self.k_work_metadata_buffer
|
||||
request_capacity = None
|
||||
if build_k_work:
|
||||
num_requests = common_attn_metadata.query_start_loc.shape[0] - 1
|
||||
request_capacity = self.request_capacity
|
||||
max_num_work = (
|
||||
num_tokens + (self.compress_ratio - 1) * num_requests
|
||||
) // self.compress_ratio
|
||||
k_work_metadata = self.k_work_metadata_buffer[:max_num_work]
|
||||
token_to_req, logical_positions, slot_mapping = build_qsa_metadata(
|
||||
common_attn_metadata,
|
||||
self.token_to_req_buffer,
|
||||
self.logical_positions_buffer,
|
||||
self.slot_mapping_buffer,
|
||||
storage_block_size=self.storage_block_size,
|
||||
compress_ratio=self.compress_ratio,
|
||||
circular_buffer_size=(
|
||||
self.kv_cache_spec.block_size if self.is_circular_buffer else 0
|
||||
),
|
||||
k_work_metadata_buffer=k_work_metadata if build_k_work else None,
|
||||
request_capacity=request_capacity,
|
||||
)
|
||||
return QSAForwardMetadata(
|
||||
block_table=common_attn_metadata.block_table_tensor,
|
||||
slot_mapping=slot_mapping,
|
||||
seq_lens=common_attn_metadata.seq_lens,
|
||||
query_start_loc=common_attn_metadata.query_start_loc,
|
||||
token_to_req=token_to_req,
|
||||
logical_positions=logical_positions,
|
||||
k_work_metadata=k_work_metadata,
|
||||
num_actual_tokens=num_tokens,
|
||||
storage_block_size=self.storage_block_size,
|
||||
compress_ratio=self.compress_ratio,
|
||||
)
|
||||
|
||||
|
||||
class QSAStateBackend(AttentionBackend):
|
||||
"""Key-only dummy backend for out-of-band BF16 QSA side-cache operations."""
|
||||
|
||||
supported_dtypes: ClassVar[list[torch.dtype]] = [torch.bfloat16]
|
||||
supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = ["auto", "bfloat16"]
|
||||
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
return "QWEN4_EXP_EXP_QSA_STATE"
|
||||
|
||||
@staticmethod
|
||||
def get_impl_cls():
|
||||
raise NotImplementedError(
|
||||
"QSA state caches run out-of-band and have no attention impl"
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def get_builder_cls() -> type[QSAMetadataBuilder]:
|
||||
return QSAMetadataBuilder
|
||||
|
||||
@classmethod
|
||||
def supported_kv_cache_layouts(cls) -> tuple[KVCacheLayout, ...]:
|
||||
# QSA pages are packed beside the main KV pages within each block.
|
||||
return (KVCacheLayout.BLNHC, KVCacheLayout.BLHNC)
|
||||
|
||||
|
||||
class _QSAStateCache(nn.Module, AttentionLayerBase):
|
||||
supports_dcp = False
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
head_size: int,
|
||||
dtype: torch.dtype,
|
||||
cache_config: CacheConfig,
|
||||
prefix: str,
|
||||
vllm_config: VllmConfig,
|
||||
compress_ratio: int = 1,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
if head_size <= 0:
|
||||
raise ValueError("QSA cache head size must be positive")
|
||||
if compress_ratio <= 0:
|
||||
raise ValueError("QSA compression ratio must be positive")
|
||||
if cache_config.block_size % compress_ratio:
|
||||
raise ValueError(
|
||||
"QSA cache block size must be divisible by the compression ratio"
|
||||
)
|
||||
self.head_size = head_size
|
||||
self.dtype = dtype
|
||||
self.cache_config = cache_config
|
||||
self.prefix = prefix
|
||||
self.compress_ratio = compress_ratio
|
||||
self.kv_cache = torch.tensor([])
|
||||
|
||||
static_context = vllm_config.compilation_config.static_forward_context
|
||||
if prefix in static_context:
|
||||
raise ValueError(f"Duplicate layer name: {prefix}")
|
||||
static_context[prefix] = self
|
||||
|
||||
def forward(self) -> None: ...
|
||||
|
||||
def bind_kv_cache(self, kv_cache: torch.Tensor) -> None:
|
||||
"""Adapt the unified [B, H, N, C] view to QSA's [B, N, H, C]."""
|
||||
if kv_cache.ndim != 4 or kv_cache.shape[1] != 1:
|
||||
raise ValueError("QSA state cache must be [blocks, 1, states, width]")
|
||||
if kv_cache.dtype != torch.bfloat16 or kv_cache.shape[3] != self.head_size:
|
||||
raise ValueError("QSA state cache does not match its packed BF16 spec")
|
||||
super().bind_kv_cache(kv_cache.transpose(1, 2))
|
||||
|
||||
def get_attn_backend(self) -> type[AttentionBackend]:
|
||||
return QSAStateBackend
|
||||
|
||||
|
||||
class QSAKeyStateCache(_QSAStateCache):
|
||||
"""Raw BF16 key, optionally followed by exact int64 MRoPE positions."""
|
||||
|
||||
_BF16_PER_INT64 = 4
|
||||
_NUM_ROPE_AXES = 3
|
||||
|
||||
def __init__(self, *, cache_rope_positions: bool = False, **kwargs) -> None:
|
||||
key_head_size = int(kwargs.pop("head_size"))
|
||||
self.key_head_size = key_head_size
|
||||
self.cache_rope_positions = bool(cache_rope_positions)
|
||||
self.rope_position_offset = (
|
||||
(key_head_size + self._BF16_PER_INT64 - 1) // self._BF16_PER_INT64
|
||||
) * self._BF16_PER_INT64
|
||||
storage_head_size = key_head_size
|
||||
if self.cache_rope_positions:
|
||||
storage_head_size = self.rope_position_offset + (
|
||||
self._NUM_ROPE_AXES * self._BF16_PER_INT64
|
||||
)
|
||||
super().__init__(head_size=storage_head_size, **kwargs)
|
||||
|
||||
def bind_kv_cache(self, kv_cache: torch.Tensor) -> None:
|
||||
super().bind_kv_cache(kv_cache)
|
||||
qsa_cache = self.kv_cache
|
||||
self.key_cache = qsa_cache[..., : self.key_head_size]
|
||||
if self.cache_rope_positions:
|
||||
position_tail = qsa_cache[..., self.rope_position_offset :]
|
||||
self.rope_position_cache = position_tail.view(torch.int64)
|
||||
else:
|
||||
self.rope_position_cache = None
|
||||
|
||||
def get_kv_cache_spec(self, vllm_config: VllmConfig) -> KVCacheSpec:
|
||||
# Hold the open group's committed keys plus every row a speculative
|
||||
# step stores before acceptance is known, rounded up to whole groups so
|
||||
# the ring divides the attention block size (it joins the LCM that sets
|
||||
# the scheduler block size). Anything narrower lets a rejected draft row
|
||||
# overwrite a committed key the next step needs to close the group.
|
||||
span = self.compress_ratio + vllm_config.num_speculative_tokens
|
||||
capacity = self.compress_ratio * cdiv(span, self.compress_ratio)
|
||||
assert self.cache_config.block_size % capacity == 0, (
|
||||
f"QSA ring capacity {capacity} must divide the attention block "
|
||||
f"size {self.cache_config.block_size}"
|
||||
)
|
||||
return CircularBufferSpec(
|
||||
block_size=capacity,
|
||||
num_kv_heads=1,
|
||||
head_size=self.head_size,
|
||||
head_size_v=0,
|
||||
dtype=self.dtype,
|
||||
)
|
||||
|
||||
|
||||
class QSACompressedKeyCache(_QSAStateCache):
|
||||
"""Normalized, group-first-RoPE BF16 key at one row per complete group."""
|
||||
|
||||
def get_kv_cache_spec(self, vllm_config: VllmConfig) -> KVCacheSpec:
|
||||
del vllm_config
|
||||
return MLAAttentionSpec(
|
||||
block_size=self.cache_config.block_size,
|
||||
num_kv_heads=1,
|
||||
head_size=self.head_size,
|
||||
dtype=self.dtype,
|
||||
tokens_per_state=self.compress_ratio,
|
||||
)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"QSACompressedKeyCache",
|
||||
"QSAForwardMetadata",
|
||||
"QSAKeyStateCache",
|
||||
"QSAMetadataBuilder",
|
||||
"QSAStateBackend",
|
||||
"canonical_qsa_rope_positions",
|
||||
"circular_qsa_slot_mapping",
|
||||
"compressed_qsa_slot_mapping",
|
||||
]
|
||||
@@ -0,0 +1,252 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Qwen4Exp model configuration."""
|
||||
|
||||
from typing import Any, ClassVar, cast
|
||||
|
||||
from transformers import PretrainedConfig
|
||||
from transformers.models.qwen3_vl.configuration_qwen3_vl import (
|
||||
Qwen3VLVisionConfig,
|
||||
)
|
||||
|
||||
from vllm.transformers_utils.configs.qwen3_next import Qwen3NextConfig
|
||||
|
||||
_QSA_CONFIG_FIELDS = (
|
||||
"indexer_n_heads",
|
||||
"indexer_kv_heads",
|
||||
"indexer_head_dim",
|
||||
"indexer_budget",
|
||||
"indexer_compress_ratio",
|
||||
)
|
||||
|
||||
|
||||
class Qwen4ExpVisionConfig(Qwen3VLVisionConfig):
|
||||
model_type = "qwen4_exp"
|
||||
base_config_key = "vision_config"
|
||||
|
||||
|
||||
class Qwen4ExpTextConfig(Qwen3NextConfig):
|
||||
model_type = "qwen4_exp_text"
|
||||
base_config_key = "text_config"
|
||||
keys_to_ignore_at_inference = ["past_key_values"]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
hc_count: int = 4,
|
||||
hc_lowrank: int = 320,
|
||||
ple_layer_ids: list[int] | None = None,
|
||||
ple_embed_dim: int | None = None,
|
||||
ple_conv_kernel_size: int = 4,
|
||||
ngram_size: int = 3,
|
||||
heads_per_ngram: int = 8,
|
||||
ngram_vocab_size_base: int = 20_000_000,
|
||||
make_ngram_vocab_size_divisible_by: int = 128,
|
||||
output_gate_type: str = "sigmoid",
|
||||
rope_parameters: dict[str, Any] | None = None,
|
||||
layer_types: list[str] | None = None,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
if hc_count <= 1:
|
||||
raise ValueError(f"Qwen4Exp requires hc_count > 1, got {hc_count}.")
|
||||
|
||||
if rope_parameters is not None:
|
||||
if kwargs.get("rope_scaling") is None:
|
||||
kwargs["rope_scaling"] = rope_parameters
|
||||
if kwargs.get("rope_theta") is None and "rope_theta" in rope_parameters:
|
||||
kwargs["rope_theta"] = rope_parameters["rope_theta"]
|
||||
if (
|
||||
kwargs.get("partial_rotary_factor") is None
|
||||
and "partial_rotary_factor" in rope_parameters
|
||||
):
|
||||
kwargs["partial_rotary_factor"] = rope_parameters[
|
||||
"partial_rotary_factor"
|
||||
]
|
||||
|
||||
rope_scaling = kwargs.get("rope_scaling")
|
||||
rope_theta = kwargs.get("rope_theta", 10_000.0)
|
||||
super().__init__(layer_types=layer_types, **kwargs)
|
||||
|
||||
normalized_rope_parameters = self.rope_parameters
|
||||
self.rope_scaling = (
|
||||
rope_scaling or rope_parameters or normalized_rope_parameters
|
||||
)
|
||||
self.rope_parameters = rope_parameters or normalized_rope_parameters
|
||||
self.rope_theta = rope_theta
|
||||
|
||||
self.hc_count = hc_count
|
||||
self.hc_lowrank = hc_lowrank
|
||||
self.ple_layer_ids = ple_layer_ids or []
|
||||
self.ple_embed_dim = (
|
||||
self.hidden_size if ple_embed_dim is None else ple_embed_dim
|
||||
)
|
||||
self.ple_conv_kernel_size = ple_conv_kernel_size
|
||||
self.ngram_size = ngram_size
|
||||
self.heads_per_ngram = heads_per_ngram
|
||||
self.ngram_vocab_size_base = ngram_vocab_size_base
|
||||
self.make_ngram_vocab_size_divisible_by = make_ngram_vocab_size_divisible_by
|
||||
self.output_gate_type = output_gate_type
|
||||
|
||||
self._validate_ple_config()
|
||||
self._validate_ple_layer_ids()
|
||||
self._validate_qsa_config()
|
||||
|
||||
def _validate_ple_config(self) -> None:
|
||||
if self.hc_lowrank <= 0:
|
||||
raise ValueError(f"hc_lowrank must be positive, got {self.hc_lowrank}")
|
||||
if self.ngram_size < 2:
|
||||
raise ValueError(f"ngram_size must be >= 2, got {self.ngram_size}")
|
||||
if self.heads_per_ngram <= 0:
|
||||
raise ValueError(
|
||||
f"heads_per_ngram must be positive, got {self.heads_per_ngram}"
|
||||
)
|
||||
if self.ple_embed_dim <= 0:
|
||||
raise ValueError(
|
||||
f"ple_embed_dim must be positive, got {self.ple_embed_dim}"
|
||||
)
|
||||
ngram_heads = (self.ngram_size - 1) * self.heads_per_ngram
|
||||
if self.ple_embed_dim % ngram_heads:
|
||||
raise ValueError(
|
||||
"ple_embed_dim must be divisible by total ngram heads: "
|
||||
f"{self.ple_embed_dim} % {ngram_heads} != 0"
|
||||
)
|
||||
if self.ple_conv_kernel_size <= 0:
|
||||
raise ValueError(
|
||||
"ple_conv_kernel_size must be positive, got "
|
||||
f"{self.ple_conv_kernel_size}"
|
||||
)
|
||||
if self.ngram_vocab_size_base <= 0:
|
||||
raise ValueError("ngram_vocab_size_base must be positive")
|
||||
if self.make_ngram_vocab_size_divisible_by <= 0:
|
||||
raise ValueError("make_ngram_vocab_size_divisible_by must be positive")
|
||||
|
||||
def _validate_ple_layer_ids(self) -> None:
|
||||
invalid = [
|
||||
layer_id
|
||||
for layer_id in self.ple_layer_ids
|
||||
if not 1 <= int(layer_id) <= self.num_hidden_layers
|
||||
]
|
||||
if invalid:
|
||||
raise ValueError(
|
||||
"ple_layer_ids are 1-based and must refer to an existing layer; "
|
||||
f"got {invalid} for {self.num_hidden_layers} layers"
|
||||
)
|
||||
|
||||
def _validate_qsa_config(self) -> None:
|
||||
configured = {name: getattr(self, name, None) for name in _QSA_CONFIG_FIELDS}
|
||||
if all(value is None for value in configured.values()):
|
||||
return
|
||||
|
||||
missing = [name for name, value in configured.items() if value is None]
|
||||
if missing:
|
||||
raise ValueError(f"QSA config is missing required fields: {missing}")
|
||||
|
||||
values = {name: int(cast(int, value)) for name, value in configured.items()}
|
||||
if any(value <= 0 for value in values.values()):
|
||||
raise ValueError(f"QSA config values must be positive: {values}")
|
||||
if values["indexer_kv_heads"] != 1:
|
||||
raise ValueError("the QSA MQA operators require indexer_kv_heads=1")
|
||||
if values["indexer_budget"] % values["indexer_compress_ratio"] != 0:
|
||||
raise ValueError(
|
||||
"indexer_budget must be divisible by indexer_compress_ratio"
|
||||
)
|
||||
block_topk = values["indexer_budget"] // values["indexer_compress_ratio"]
|
||||
if block_topk not in (512, 2048):
|
||||
raise ValueError(
|
||||
"QSA requires indexer_budget / indexer_compress_ratio "
|
||||
f"to be 512 or 2048, got {block_topk}"
|
||||
)
|
||||
rotary_dim = int(self.head_dim * self.partial_rotary_factor)
|
||||
if rotary_dim > values["indexer_head_dim"]:
|
||||
raise ValueError(
|
||||
"QSA indexer_head_dim must cover the attention rotary "
|
||||
f"dimension, got {values['indexer_head_dim']} < {rotary_dim}"
|
||||
)
|
||||
|
||||
@property
|
||||
def layers_block_type(self) -> list[str]:
|
||||
return [
|
||||
"attention" if layer_type == "full_attention" else layer_type
|
||||
for layer_type in self.layer_types
|
||||
]
|
||||
|
||||
@property
|
||||
def short_conv_layer_ids(self) -> list[int]:
|
||||
if not self.ple_layer_ids:
|
||||
return []
|
||||
return sorted({int(layer_id) - 1 for layer_id in self.ple_layer_ids})
|
||||
|
||||
@property
|
||||
def short_conv_state_shape(self) -> tuple[int, int] | None:
|
||||
if not self.short_conv_layer_ids:
|
||||
return None
|
||||
ple_state_len = (self.ple_conv_kernel_size - 1) * self.ngram_size
|
||||
ple_channels = self.hidden_size * self.hc_count
|
||||
return ple_channels, ple_state_len
|
||||
|
||||
@property
|
||||
def ngram_context_len(self) -> int:
|
||||
if not self.ple_layer_ids:
|
||||
return 0
|
||||
return max(int(self.ngram_size) - 1, 0)
|
||||
|
||||
|
||||
class Qwen4ExpConfig(PretrainedConfig):
|
||||
model_type = "qwen4_exp"
|
||||
sub_configs: ClassVar[dict[str, type[PretrainedConfig]]] = {
|
||||
"vision_config": Qwen4ExpVisionConfig,
|
||||
"text_config": Qwen4ExpTextConfig,
|
||||
}
|
||||
keys_to_ignore_at_inference = ["past_key_values"]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
text_config: Qwen4ExpTextConfig | dict[str, Any] | None = None,
|
||||
vision_config: Qwen4ExpVisionConfig | dict[str, Any] | None = None,
|
||||
image_token_id: int = 248056,
|
||||
video_token_id: int = 248057,
|
||||
vision_start_token_id: int = 248053,
|
||||
vision_end_token_id: int = 248054,
|
||||
tie_word_embeddings: bool = False,
|
||||
rope_parameters: dict[str, Any] | None = None,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
if text_config is not None:
|
||||
kwargs.pop("split_ngram_parts", None)
|
||||
|
||||
text_kwargs = (
|
||||
dict(kwargs)
|
||||
if text_config is None
|
||||
and "hidden_size" in kwargs
|
||||
and "num_hidden_layers" in kwargs
|
||||
else {}
|
||||
)
|
||||
|
||||
if isinstance(vision_config, dict):
|
||||
self.vision_config = self.sub_configs["vision_config"](**vision_config)
|
||||
elif vision_config is None:
|
||||
self.vision_config = self.sub_configs["vision_config"]()
|
||||
else:
|
||||
self.vision_config = vision_config
|
||||
|
||||
if isinstance(text_config, dict):
|
||||
self.text_config = self.sub_configs["text_config"](**text_config)
|
||||
elif text_config is None:
|
||||
self.text_config = self.sub_configs["text_config"](**text_kwargs)
|
||||
else:
|
||||
self.text_config = text_config
|
||||
|
||||
self.image_token_id = image_token_id
|
||||
self.video_token_id = video_token_id
|
||||
self.vision_start_token_id = vision_start_token_id
|
||||
self.vision_end_token_id = vision_end_token_id
|
||||
self.rope_parameters = rope_parameters or getattr(
|
||||
self.text_config, "rope_parameters", {}
|
||||
)
|
||||
super().__init__(**kwargs, tie_word_embeddings=tie_word_embeddings)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"Qwen4ExpConfig",
|
||||
"Qwen4ExpTextConfig",
|
||||
"Qwen4ExpVisionConfig",
|
||||
]
|
||||
@@ -0,0 +1,2 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
@@ -0,0 +1,205 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""HyperConnection (Gated Residual) utilities — NVIDIA model variant.
|
||||
|
||||
Implements the HyperConnection residual scheme proposed in
|
||||
"HyperConnections" (https://arxiv.org/abs/2409.19606). This NVIDIA variant
|
||||
delays each HC combine to the following HC mix boundary. HC glue kernels,
|
||||
including fused combine+RMSNorm, live in ``ops/hc.py``; projections remain
|
||||
standard vLLM Linear modules.
|
||||
|
||||
Hidden states between layers have shape ``[..., HC*HS]`` with HS inner
|
||||
(HC outer, HS inner — checkpoint-native layout).
|
||||
|
||||
Typical usage inside a transformer decoder layer::
|
||||
|
||||
self.attn_hc = GatedResidual(hc_config)
|
||||
|
||||
hidden_states, block_input, injection = self.attn_hc.mix(hidden_states)
|
||||
attention_output = attention(block_input)
|
||||
hidden_states, block_input, injection = self.mlp_hc.combine_and_mix(
|
||||
hidden_states, attention_output, injection
|
||||
)
|
||||
"""
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from vllm.model_executor.layers.linear import (
|
||||
MergedColumnParallelLinear,
|
||||
ReplicatedLinear,
|
||||
)
|
||||
from vllm.model_executor.models.utils import maybe_prefix
|
||||
|
||||
from ..common.hyperconnection import (
|
||||
GroupedGemmaRMSNorm,
|
||||
HyperConnectionConfig,
|
||||
)
|
||||
from .ops.hc import (
|
||||
grouped_gemma_rmsnorm,
|
||||
hc_combine,
|
||||
hc_combine_norm,
|
||||
hc_gate_mix,
|
||||
hc_silu,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Gated-residual variant
|
||||
# ---------------------------------------------------------------------------
|
||||
class GatedResidual(nn.Module):
|
||||
"""Gated HyperConnection with learnable low-rank mixing and injection.
|
||||
|
||||
``combine_and_mix()`` runs the pre pipeline (grouped GemmaRMSNorm -> merged
|
||||
low-rank down+inject GEMM -> silu -> up GEMM -> sigmoid -> gated mean
|
||||
over the HC streams). When passed a pending block output and an injection,
|
||||
it fuses their residual combine with the RMSNorm. Final mixers use
|
||||
``use_combine=False`` and do not produce a new injection.
|
||||
|
||||
Weights: the norm owns the grouped GemmaRMSNorm affine; the projections
|
||||
are vLLM Linear modules (merged replicated linear for down+inject), so
|
||||
GEMM dispatch (e.g. the low-latency skinny GEMM) applies through the
|
||||
standard quant_method mechanism.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config: HyperConnectionConfig,
|
||||
use_combine: bool = True,
|
||||
prefix: str = "",
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.lora_rank = config.hc_lowrank
|
||||
self.hc_count = config.hc_count
|
||||
self.hidden_size = config.hidden_size
|
||||
self.use_combine = use_combine
|
||||
|
||||
norm_size = (
|
||||
self.hyper_hidden_size if config.hc_per_branch_norm else config.hidden_size
|
||||
)
|
||||
group_size = config.hidden_size if config.hc_per_branch_norm else None
|
||||
# Normalize each H-sized HC stream independently while retaining a
|
||||
# separate affine weight for every element of the HC*H layout.
|
||||
self.hc_norm = GroupedGemmaRMSNorm(
|
||||
norm_size,
|
||||
eps=config.rms_norm_eps,
|
||||
group_size=group_size,
|
||||
dtype=config.params_dtype,
|
||||
)
|
||||
|
||||
# -- vLLM Linear weights --------------------------------------------
|
||||
# The merged skinny-GEMM shape is physically padded to 16 rows to ensure
|
||||
# good alignment and performant implementation chosen by CuBLAS heuristics.
|
||||
self.pad_size = (-(self.lora_rank + self.hc_count)) % 16 if use_combine else 0
|
||||
if use_combine:
|
||||
self.input_mix_weight_down_block_inject = MergedColumnParallelLinear(
|
||||
self.hyper_hidden_size,
|
||||
[self.lora_rank, self.hc_count]
|
||||
+ ([self.pad_size] if self.pad_size else []),
|
||||
bias=False,
|
||||
params_dtype=config.params_dtype,
|
||||
quant_config=None,
|
||||
prefix=maybe_prefix(prefix, "input_mix_weight_down_block_inject"),
|
||||
return_bias=False,
|
||||
disable_tp=True,
|
||||
)
|
||||
else:
|
||||
self.input_mix_weight_down = ReplicatedLinear(
|
||||
self.hyper_hidden_size,
|
||||
self.lora_rank,
|
||||
bias=False,
|
||||
params_dtype=config.params_dtype,
|
||||
quant_config=None,
|
||||
prefix=maybe_prefix(prefix, "input_mix_weight_down"),
|
||||
return_bias=False,
|
||||
)
|
||||
self.input_mix_weight_up = ReplicatedLinear(
|
||||
self.lora_rank,
|
||||
self.hyper_hidden_size,
|
||||
bias=False,
|
||||
params_dtype=config.params_dtype,
|
||||
quant_config=None,
|
||||
prefix=maybe_prefix(prefix, "input_mix_weight_up"),
|
||||
return_bias=False,
|
||||
)
|
||||
|
||||
def mix(
|
||||
self, hidden_states: torch.Tensor
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]:
|
||||
xn = grouped_gemma_rmsnorm(
|
||||
hidden_states,
|
||||
self.hc_norm.weight,
|
||||
self.config.rms_norm_eps,
|
||||
self.hc_count,
|
||||
)
|
||||
|
||||
if self.use_combine:
|
||||
# produce injection logits for combine
|
||||
split_sizes = [self.lora_rank, self.hc_count, self.pad_size]
|
||||
down_and_injection = self.input_mix_weight_down_block_inject(xn)
|
||||
lora, injection, _ = down_and_injection.split(split_sizes, dim=-1)
|
||||
else:
|
||||
lora = self.input_mix_weight_down(xn)
|
||||
injection = None
|
||||
|
||||
lora = hc_silu(lora, self.hc_count)
|
||||
gate = self.input_mix_weight_up(lora) # [M, D]
|
||||
block_input = hc_gate_mix(xn, gate, self.hc_count)
|
||||
|
||||
return hidden_states, block_input, injection
|
||||
|
||||
def combine_and_mix(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
prev_block_output: torch.Tensor,
|
||||
prev_injection: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]:
|
||||
"""Consume a pending combine, then prepare the next block input.
|
||||
|
||||
``hidden_states`` is the multi-stream state from before the pending
|
||||
block's mix. Its combine with ``block_output`` is fused with this
|
||||
module's input RMSNorm.
|
||||
"""
|
||||
hidden_states, xn = hc_combine_norm(
|
||||
hidden_states,
|
||||
prev_block_output,
|
||||
prev_injection,
|
||||
self.hc_norm.weight,
|
||||
self.config.rms_norm_eps,
|
||||
self.hc_count,
|
||||
)
|
||||
|
||||
if self.use_combine:
|
||||
# produce injection logits for combine
|
||||
split_sizes = [self.lora_rank, self.hc_count, self.pad_size]
|
||||
down_and_injection = self.input_mix_weight_down_block_inject(xn)
|
||||
lora, injection, _ = down_and_injection.split(split_sizes, dim=-1)
|
||||
else:
|
||||
lora = self.input_mix_weight_down(xn)
|
||||
injection = None
|
||||
|
||||
lora = hc_silu(lora, self.hc_count)
|
||||
gate = self.input_mix_weight_up(lora) # [M, D]
|
||||
block_input = hc_gate_mix(xn, gate, self.hc_count)
|
||||
|
||||
return hidden_states, block_input, injection
|
||||
|
||||
def combine(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
block_output: torch.Tensor,
|
||||
injection: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
return hc_combine(hidden_states, block_output, injection, self.hc_count)
|
||||
|
||||
@property
|
||||
def hyper_hidden_size(self) -> int:
|
||||
return self.hc_count * self.hidden_size
|
||||
|
||||
|
||||
__all__ = [
|
||||
"GatedResidual",
|
||||
"GroupedGemmaRMSNorm",
|
||||
"HyperConnectionConfig",
|
||||
]
|
||||
@@ -0,0 +1,356 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Qwen4Exp weight-free QSA indexer."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import cast
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.forward_context import get_forward_context
|
||||
from vllm.model_executor.layers.layernorm import GemmaRMSNorm
|
||||
from vllm.model_executor.layers.linear import ReplicatedLinear
|
||||
from vllm.model_executor.layers.quantization import QuantizationConfig
|
||||
from vllm.model_executor.layers.rotary_embedding.mrope import triton_mrope
|
||||
from vllm.transformers_utils.configs.qwen4_exp import (
|
||||
Qwen4ExpTextConfig,
|
||||
)
|
||||
|
||||
from ..common.qsa_cache import (
|
||||
QSACompressedKeyCache,
|
||||
QSAForwardMetadata,
|
||||
QSAKeyStateCache,
|
||||
canonical_qsa_rope_positions,
|
||||
)
|
||||
from .ops.qsa_pre_indexer import qsa_pre_indexer
|
||||
|
||||
|
||||
def apply_qsa_rope(
|
||||
rotary_emb: nn.Module,
|
||||
positions: torch.Tensor,
|
||||
tensor: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
"""Apply the main attention's exact 1D/MRoPE composition to QSA heads."""
|
||||
|
||||
num_tokens, _, head_dim = tensor.shape
|
||||
rotary_dim = rotary_emb.rotary_dim
|
||||
cache = rotary_emb._match_cos_sin_cache_dtype(tensor) # noqa: SLF001
|
||||
cos_sin = cache[positions]
|
||||
cos, sin = cos_sin.chunk(2, dim=-1)
|
||||
if positions.ndim == 2:
|
||||
shape = tensor.shape
|
||||
tensor, _ = triton_mrope(
|
||||
tensor.reshape(num_tokens, -1),
|
||||
tensor.new_empty((num_tokens, head_dim)),
|
||||
cos,
|
||||
sin,
|
||||
rotary_emb.mrope_section,
|
||||
head_dim,
|
||||
rotary_dim,
|
||||
rotary_emb.mrope_interleaved,
|
||||
rotary_emb.is_neox_style,
|
||||
)
|
||||
return tensor.reshape(shape)
|
||||
|
||||
rotated = rotary_emb.apply_rotary_emb.forward_cuda(
|
||||
tensor[..., :rotary_dim],
|
||||
cos,
|
||||
sin,
|
||||
)
|
||||
return torch.cat((rotated, tensor[..., rotary_dim:]), dim=-1)
|
||||
|
||||
|
||||
def _supports_fused_pre_indexer(
|
||||
rotary_emb: nn.Module,
|
||||
head_dim: int,
|
||||
num_kv_heads: int,
|
||||
compress_ratio: int,
|
||||
) -> bool:
|
||||
rotary_dim = int(rotary_emb.rotary_dim)
|
||||
mrope_section = getattr(rotary_emb, "mrope_section", None)
|
||||
return (
|
||||
bool(getattr(rotary_emb, "is_neox_style", False))
|
||||
and (
|
||||
not mrope_section
|
||||
or (
|
||||
len(mrope_section) == 3
|
||||
and sum(mrope_section) == rotary_dim // 2
|
||||
and bool(getattr(rotary_emb, "mrope_interleaved", False))
|
||||
)
|
||||
)
|
||||
and head_dim == 128
|
||||
and rotary_dim == 64
|
||||
and num_kv_heads == 1
|
||||
and compress_ratio > 1
|
||||
and compress_ratio & (compress_ratio - 1) == 0
|
||||
)
|
||||
|
||||
|
||||
class QSAIndexer(nn.Module):
|
||||
"""Replicated Q/K projection plus paged, weight-free QSA selection.
|
||||
|
||||
``prefix`` must be the checkpoint's indexer prefix, normally
|
||||
``model.layers.N.self_attn.indexer``. Consequently the trainable names are
|
||||
``index_qk_proj``, ``q_layernorm`` and ``k_layernorm`` under that prefix.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
vllm_config: VllmConfig,
|
||||
config: Qwen4ExpTextConfig,
|
||||
layer_id: int,
|
||||
rotary_emb: nn.Module,
|
||||
quant_config: QuantizationConfig | None = None,
|
||||
prefix: str = "",
|
||||
) -> None:
|
||||
super().__init__()
|
||||
if vllm_config.cache_config is None:
|
||||
raise ValueError("QSA requires a paged KV cache")
|
||||
if vllm_config.model_config.dtype != torch.bfloat16:
|
||||
raise NotImplementedError("Qwen4Exp QSA currently requires BF16")
|
||||
|
||||
self.layer_id = int(layer_id)
|
||||
self.index_n_heads = int(config.indexer_n_heads)
|
||||
self.index_kv_heads = int(config.indexer_kv_heads)
|
||||
self.index_head_dim = int(config.indexer_head_dim)
|
||||
self.token_topk = int(config.indexer_budget)
|
||||
self.compress_ratio = int(config.indexer_compress_ratio)
|
||||
self.rotary_emb = rotary_emb
|
||||
self.use_fused_pre_indexer = _supports_fused_pre_indexer(
|
||||
rotary_emb,
|
||||
self.index_head_dim,
|
||||
self.index_kv_heads,
|
||||
self.compress_ratio,
|
||||
)
|
||||
self.prefix = prefix
|
||||
# MTP step 0 selects the target-aligned rows; later steps reuse them
|
||||
# while continuing to update the QSA side cache.
|
||||
self.skip_topk = False
|
||||
|
||||
self.index_qk_proj = ReplicatedLinear(
|
||||
int(config.hidden_size),
|
||||
(self.index_n_heads + self.index_kv_heads) * self.index_head_dim,
|
||||
bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.index_qk_proj" if prefix else "index_qk_proj",
|
||||
)
|
||||
self.q_layernorm = GemmaRMSNorm(
|
||||
self.index_head_dim,
|
||||
eps=float(getattr(config, "rms_norm_eps", 1e-6)),
|
||||
)
|
||||
self.k_layernorm = GemmaRMSNorm(
|
||||
self.index_head_dim,
|
||||
eps=float(getattr(config, "rms_norm_eps", 1e-6)),
|
||||
)
|
||||
|
||||
cache_config = vllm_config.cache_config
|
||||
cache_prefix = f"{prefix}." if prefix else ""
|
||||
self.raw_key_cache = QSAKeyStateCache(
|
||||
head_size=self.index_head_dim,
|
||||
dtype=torch.bfloat16,
|
||||
cache_rope_positions=vllm_config.model_config.uses_mrope,
|
||||
prefix=f"{cache_prefix}raw_key_cache",
|
||||
cache_config=cache_config,
|
||||
compress_ratio=self.compress_ratio,
|
||||
vllm_config=vllm_config,
|
||||
)
|
||||
self.compressed_key_cache = QSACompressedKeyCache(
|
||||
head_size=self.index_head_dim,
|
||||
dtype=torch.bfloat16,
|
||||
compress_ratio=self.compress_ratio,
|
||||
prefix=f"{cache_prefix}compressed_key_cache",
|
||||
cache_config=cache_config,
|
||||
vllm_config=vllm_config,
|
||||
)
|
||||
|
||||
@property
|
||||
def output_width(self) -> int:
|
||||
return self.token_topk + self.compress_ratio - 1
|
||||
|
||||
def _metadata(
|
||||
self,
|
||||
) -> tuple[QSAForwardMetadata, QSAForwardMetadata] | None:
|
||||
metadata = get_forward_context().attn_metadata
|
||||
if isinstance(metadata, list):
|
||||
metadata = metadata[0]
|
||||
if not isinstance(metadata, dict):
|
||||
return None
|
||||
raw = cast(QSAForwardMetadata, metadata[self.raw_key_cache.prefix])
|
||||
compressed = cast(
|
||||
QSAForwardMetadata, metadata[self.compressed_key_cache.prefix]
|
||||
)
|
||||
if raw.num_actual_tokens != compressed.num_actual_tokens:
|
||||
raise RuntimeError("QSA side-cache metadata token counts disagree")
|
||||
if not raw.logical_positions.is_cuda and (
|
||||
not torch.equal(raw.logical_positions, compressed.logical_positions)
|
||||
):
|
||||
raise RuntimeError("QSA side-cache metadata positions disagree")
|
||||
return raw, compressed
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
out: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Return fixed-width request-relative token indices padded with ``-1``."""
|
||||
|
||||
metadata = self._metadata()
|
||||
if metadata is None:
|
||||
# Preserve step-0 indices when later MTP steps reuse the buffer.
|
||||
if self.skip_topk and out is not None:
|
||||
return out
|
||||
result = torch.full(
|
||||
(hidden_states.shape[0], self.output_width),
|
||||
-1,
|
||||
dtype=torch.int32,
|
||||
device=hidden_states.device,
|
||||
)
|
||||
if out is not None:
|
||||
out.copy_(result)
|
||||
return out
|
||||
return result
|
||||
|
||||
from .ops.qsa import (
|
||||
qsa_compress_groups_with_ratio,
|
||||
qsa_select_paged_tokens,
|
||||
qsa_store_cache_rows,
|
||||
)
|
||||
|
||||
raw_metadata, compressed_metadata = metadata
|
||||
num_tokens = raw_metadata.num_actual_tokens
|
||||
hidden_states = hidden_states[:num_tokens]
|
||||
positions = positions[..., :num_tokens]
|
||||
|
||||
# Q/K projection
|
||||
projected_qk, _ = self.index_qk_proj(hidden_states)
|
||||
projected_q, raw_keys = projected_qk.split(
|
||||
(
|
||||
self.index_n_heads * self.index_head_dim,
|
||||
self.index_kv_heads * self.index_head_dim,
|
||||
),
|
||||
dim=-1,
|
||||
)
|
||||
raw_key_state_cache = self.raw_key_cache
|
||||
compressed_key_cache = self.compressed_key_cache.kv_cache
|
||||
|
||||
if self.use_fused_pre_indexer:
|
||||
q = projected_q.new_empty(
|
||||
num_tokens,
|
||||
self.index_n_heads,
|
||||
self.index_head_dim,
|
||||
)
|
||||
qsa_pre_indexer(
|
||||
projected_q,
|
||||
raw_keys,
|
||||
positions,
|
||||
self.rotary_emb.cos_sin_cache,
|
||||
self.q_layernorm.weight,
|
||||
self.k_layernorm.weight,
|
||||
self.q_layernorm.variance_epsilon,
|
||||
q,
|
||||
raw_key_state_cache.kv_cache,
|
||||
raw_metadata.slot_mapping,
|
||||
raw_metadata.block_table,
|
||||
raw_metadata.query_start_loc,
|
||||
raw_metadata.logical_positions,
|
||||
compressed_key_cache,
|
||||
compressed_metadata.slot_mapping,
|
||||
compressed_metadata.k_work_metadata,
|
||||
compress_ratio=self.compress_ratio,
|
||||
mrope_section=getattr(self.rotary_emb, "mrope_section", None),
|
||||
rope_pos_offset=(
|
||||
raw_key_state_cache.rope_position_offset
|
||||
if raw_key_state_cache.rope_position_cache is not None
|
||||
else None
|
||||
),
|
||||
)
|
||||
else:
|
||||
# Unfused reference path
|
||||
from flashinfer.norm import gemma_rmsnorm
|
||||
|
||||
q = projected_q.reshape(-1, self.index_n_heads, self.index_head_dim)
|
||||
q = gemma_rmsnorm(
|
||||
q.reshape(-1, self.index_head_dim),
|
||||
self.q_layernorm.weight,
|
||||
self.q_layernorm.variance_epsilon,
|
||||
).reshape_as(q)
|
||||
q = apply_qsa_rope(self.rotary_emb, positions, q)
|
||||
|
||||
raw_key_cache = raw_key_state_cache.key_cache
|
||||
rope_position_cache = raw_key_state_cache.rope_position_cache
|
||||
if rope_position_cache is None:
|
||||
position_rows = raw_metadata.logical_positions.view(-1, 1, 1).expand(
|
||||
-1, 1, 3
|
||||
)
|
||||
else:
|
||||
position_rows = canonical_qsa_rope_positions(positions).to(
|
||||
device=raw_key_cache.device
|
||||
)
|
||||
pooled, first_positions = qsa_compress_groups_with_ratio(
|
||||
raw_keys.reshape(-1, 1, self.index_head_dim),
|
||||
position_rows,
|
||||
raw_key_cache,
|
||||
raw_metadata.block_table,
|
||||
raw_metadata.token_to_req,
|
||||
raw_metadata.query_start_loc,
|
||||
raw_metadata.logical_positions,
|
||||
compressed_metadata.slot_mapping,
|
||||
self.compress_ratio,
|
||||
rope_position_cache,
|
||||
)
|
||||
compressed_keys = gemma_rmsnorm(
|
||||
pooled.reshape(-1, self.index_head_dim),
|
||||
self.k_layernorm.weight,
|
||||
self.k_layernorm.variance_epsilon,
|
||||
).reshape(-1, 1, self.index_head_dim)
|
||||
if getattr(self.rotary_emb, "mrope_section", None):
|
||||
first_positions = first_positions.transpose(0, 1)
|
||||
else:
|
||||
first_positions = first_positions[:, 0]
|
||||
compressed_keys = apply_qsa_rope(
|
||||
self.rotary_emb,
|
||||
first_positions,
|
||||
compressed_keys,
|
||||
)
|
||||
qsa_store_cache_rows(
|
||||
compressed_key_cache,
|
||||
compressed_metadata.slot_mapping,
|
||||
compressed_keys,
|
||||
)
|
||||
qsa_store_cache_rows(
|
||||
raw_key_cache,
|
||||
raw_metadata.slot_mapping,
|
||||
raw_keys,
|
||||
)
|
||||
if rope_position_cache is not None:
|
||||
qsa_store_cache_rows(
|
||||
rope_position_cache,
|
||||
raw_metadata.slot_mapping,
|
||||
position_rows,
|
||||
)
|
||||
|
||||
if self.skip_topk:
|
||||
if out is None:
|
||||
raise RuntimeError("QSA top-k reuse requires an output buffer")
|
||||
return out
|
||||
|
||||
# Score compressed keys, select blocks, then expand them to token indices.
|
||||
return qsa_select_paged_tokens(
|
||||
q,
|
||||
compressed_key_cache,
|
||||
compressed_metadata.block_table,
|
||||
compressed_metadata.token_to_req,
|
||||
compressed_metadata.logical_positions,
|
||||
compressed_metadata.seq_lens,
|
||||
self.token_topk,
|
||||
self.compress_ratio,
|
||||
out,
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["QSAIndexer", "apply_qsa_rope"]
|
||||
@@ -0,0 +1,185 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Qwen4Exp decode GEMM selection on Blackwell.
|
||||
|
||||
Dispatch follows Kimi-K3 and uses the local ``(N, K)`` shape and token count.
|
||||
Plans contain measured CUDA graph capture sizes; other token counts use the
|
||||
standard linear implementation.
|
||||
"""
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm.model_executor.kernels.linear.cute_dsl.skinny_gemm import (
|
||||
SkinnyGemmConfig,
|
||||
shape_dynamic_skinny_gemm,
|
||||
)
|
||||
from vllm.model_executor.layers.linear import LinearBase, UnquantizedLinearMethod
|
||||
from vllm.model_executor.layers.vocab_parallel_embedding import (
|
||||
ParallelLMHead,
|
||||
UnquantizedEmbeddingMethod,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.torch_utils import direct_register_custom_op
|
||||
|
||||
QWEN4_EXP_GEMM_PLANS: dict[tuple[int, int], dict[int, SkinnyGemmConfig]] = {
|
||||
# GDN fused QKVZ projection, TP=4.
|
||||
(4096, 2560): {
|
||||
1: SkinnyGemmConfig(1, 64, 4, k_unroll=4),
|
||||
2: SkinnyGemmConfig(2, 64, 4, k_unroll=4),
|
||||
},
|
||||
# GDN and QSA output projections, TP=4.
|
||||
(2560, 1536): {
|
||||
1: SkinnyGemmConfig(1, 128, 2, k_unroll=2, vector_width=4),
|
||||
2: SkinnyGemmConfig(2, 128, 2, k_unroll=2, vector_width=4),
|
||||
4: SkinnyGemmConfig(4, 64, 2, k_unroll=2),
|
||||
},
|
||||
# GDN fused B/A projection, TP=4.
|
||||
(24, 2560): {
|
||||
1: SkinnyGemmConfig(1, 128, 2, k_unroll=4, vector_width=4),
|
||||
2: SkinnyGemmConfig(2, 128, 2, k_unroll=4, vector_width=4),
|
||||
4: SkinnyGemmConfig(4, 128, 2, k_unroll=4, vector_width=4),
|
||||
8: SkinnyGemmConfig(8, 128, 1, k_unroll=4, vector_width=4),
|
||||
16: SkinnyGemmConfig(16, 128, 1, k_unroll=4, vector_width=4),
|
||||
},
|
||||
# QSA fused QKV/gate projection, TP=4.
|
||||
(3584, 2560): {
|
||||
1: SkinnyGemmConfig(1, 128, 4, k_unroll=4, vector_width=4),
|
||||
2: SkinnyGemmConfig(2, 64, 2, k_unroll=2),
|
||||
4: SkinnyGemmConfig(4, 64, 2, k_unroll=2),
|
||||
},
|
||||
# QSA indexer Q/K projection, replicated in a TP=4 deployment.
|
||||
(640, 2560): {
|
||||
1: SkinnyGemmConfig(1, 128, 1, k_unroll=4, vector_width=4),
|
||||
2: SkinnyGemmConfig(2, 128, 1, k_unroll=4, vector_width=4),
|
||||
4: SkinnyGemmConfig(4, 128, 1, k_unroll=4, vector_width=4),
|
||||
8: SkinnyGemmConfig(8, 128, 1, k_unroll=4, vector_width=4),
|
||||
},
|
||||
# Shared-expert fused gate/up projection, TP=4.
|
||||
(320, 2560): {
|
||||
1: SkinnyGemmConfig(1, 128, 2, k_unroll=4, vector_width=4),
|
||||
2: SkinnyGemmConfig(2, 128, 2, k_unroll=4, vector_width=4),
|
||||
4: SkinnyGemmConfig(4, 128, 2, k_unroll=4, vector_width=4),
|
||||
8: SkinnyGemmConfig(8, 64, 1, k_unroll=4),
|
||||
16: SkinnyGemmConfig(16, 128, 2, k_unroll=4, vector_width=4),
|
||||
},
|
||||
# LM head, TP=4.
|
||||
(62080, 2560): {
|
||||
1: SkinnyGemmConfig(1, 64, 4, k_unroll=2),
|
||||
2: SkinnyGemmConfig(2, 32, 4, k_unroll=2),
|
||||
},
|
||||
# HC merged down/injection projection, replicated in a TP=4 deployment.
|
||||
(336, 10240): {
|
||||
1: SkinnyGemmConfig(1, 128, 1, static_k=10240),
|
||||
2: SkinnyGemmConfig(2, 128, 1, static_k=10240),
|
||||
4: SkinnyGemmConfig(4, 128, 2, static_k=10240),
|
||||
8: SkinnyGemmConfig(8, 128, 1, k_unroll=4),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _is_sm103() -> bool:
|
||||
return current_platform.is_device_capability((10, 3))
|
||||
|
||||
|
||||
def _is_packed_row_major(tensor: torch.Tensor) -> bool:
|
||||
return tensor.dim() == 2 and tensor.stride() == (tensor.shape[1], 1)
|
||||
|
||||
|
||||
def _runtime_ok(x: torch.Tensor, weight: torch.Tensor) -> bool:
|
||||
return (
|
||||
not envs.VLLM_BATCH_INVARIANT
|
||||
and _is_packed_row_major(x)
|
||||
and _is_packed_row_major(weight)
|
||||
and x.dtype == torch.bfloat16
|
||||
and weight.dtype == torch.bfloat16
|
||||
and x.is_cuda
|
||||
and weight.is_cuda
|
||||
and x.device == weight.device
|
||||
and x.shape[1] == weight.shape[1]
|
||||
)
|
||||
|
||||
|
||||
class _Qwen4ExpLowLatencyApply:
|
||||
def apply(
|
||||
self,
|
||||
layer: nn.Module,
|
||||
x: torch.Tensor,
|
||||
bias: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
if bias is None and not envs.VLLM_BATCH_INVARIANT:
|
||||
return torch.ops.vllm.qwen4_exp_low_latency_gemm(x, layer.weight)
|
||||
return super().apply(layer, x, bias) # type: ignore[misc]
|
||||
|
||||
|
||||
class Qwen4ExpLowLatencyLinearMethod(_Qwen4ExpLowLatencyApply, UnquantizedLinearMethod):
|
||||
pass
|
||||
|
||||
|
||||
class Qwen4ExpLowLatencyEmbeddingMethod(
|
||||
_Qwen4ExpLowLatencyApply, UnquantizedEmbeddingMethod
|
||||
):
|
||||
pass
|
||||
|
||||
|
||||
def _qwen4_exp_low_latency_gemm(x: torch.Tensor, weight: torch.Tensor) -> torch.Tensor:
|
||||
plan = QWEN4_EXP_GEMM_PLANS.get((weight.shape[0], weight.shape[1]))
|
||||
config = None if plan is None else plan.get(x.shape[0])
|
||||
if (
|
||||
config is not None
|
||||
and _runtime_ok(x, weight)
|
||||
and shape_dynamic_skinny_gemm.is_available()
|
||||
):
|
||||
return shape_dynamic_skinny_gemm(x, weight, config)
|
||||
return torch.nn.functional.linear(x, weight)
|
||||
|
||||
|
||||
def _qwen4_exp_low_latency_gemm_fake(
|
||||
x: torch.Tensor, weight: torch.Tensor
|
||||
) -> torch.Tensor:
|
||||
return x.new_empty((*x.shape[:-1], weight.shape[0]))
|
||||
|
||||
|
||||
direct_register_custom_op(
|
||||
op_name="qwen4_exp_low_latency_gemm",
|
||||
op_func=_qwen4_exp_low_latency_gemm,
|
||||
fake_impl=_qwen4_exp_low_latency_gemm_fake,
|
||||
)
|
||||
|
||||
|
||||
def enable_qwen4_exp_low_latency_gemm(
|
||||
module: nn.Module,
|
||||
dtype: torch.dtype,
|
||||
) -> None:
|
||||
if dtype != torch.bfloat16 or not _is_sm103():
|
||||
return
|
||||
if not shape_dynamic_skinny_gemm.is_available():
|
||||
return
|
||||
|
||||
warmup_configs: set[SkinnyGemmConfig] = set()
|
||||
for child in module.modules():
|
||||
is_linear = (
|
||||
isinstance(child, LinearBase)
|
||||
and type(child.quant_method) is UnquantizedLinearMethod
|
||||
)
|
||||
is_head = (
|
||||
isinstance(child, ParallelLMHead)
|
||||
and type(child.quant_method) is UnquantizedEmbeddingMethod
|
||||
)
|
||||
if not (is_linear or is_head):
|
||||
continue
|
||||
weight = getattr(child, "weight", None)
|
||||
if weight is None or weight.dim() != 2:
|
||||
continue
|
||||
plan = QWEN4_EXP_GEMM_PLANS.get((weight.shape[0], weight.shape[1]))
|
||||
if plan is None:
|
||||
continue
|
||||
if is_linear:
|
||||
child.quant_method = Qwen4ExpLowLatencyLinearMethod()
|
||||
else:
|
||||
child.quant_method = Qwen4ExpLowLatencyEmbeddingMethod()
|
||||
warmup_configs.update(plan.values())
|
||||
|
||||
if warmup_configs:
|
||||
shape_dynamic_skinny_gemm.request_warmup_configs(dtype, warmup_configs)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,143 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Model-runner state for Qwen4Exp PLE inputs."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.v1.worker.gpu.input_batch import InputBatch
|
||||
from vllm.v1.worker.gpu.mm.encoder_cache import EncoderCache
|
||||
from vllm.v1.worker.gpu.model_states.mamba_hybrid import MambaHybridModelState
|
||||
from vllm.v1.worker.gpu.states import RequestState
|
||||
|
||||
|
||||
class Qwen4ExpModelState(MambaHybridModelState):
|
||||
"""Add rollback-safe PLE n-gram context to the model inputs."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vllm_config: VllmConfig,
|
||||
model: nn.Module,
|
||||
encoder_cache: EncoderCache | None,
|
||||
device: torch.device,
|
||||
) -> None:
|
||||
super().__init__(vllm_config, model, encoder_cache, device)
|
||||
config = self.model_config.hf_text_config
|
||||
self.uses_ngram_embedding = bool(config.ple_layer_ids)
|
||||
if not self.uses_ngram_embedding:
|
||||
self.ngram_context_len = 0
|
||||
self.ngram_eos_token_id = 0
|
||||
return
|
||||
|
||||
if vllm_config.parallel_config.pipeline_parallel_size > 1:
|
||||
raise RuntimeError(
|
||||
"N-gram PLE embedding currently requires "
|
||||
"pipeline_parallel_size=1 because non-first pipeline ranks do "
|
||||
"not receive the raw input_ids required by PLE. Please run "
|
||||
"with PP=1."
|
||||
)
|
||||
|
||||
self.ngram_context_len = int(config.ngram_size) - 1
|
||||
if self.ngram_context_len <= 0:
|
||||
raise ValueError("N-gram embedding requires context length >= 1.")
|
||||
self.ngram_eos_token_id = int(config.eos_token_id)
|
||||
self.ngram_context = torch.full(
|
||||
(self.max_num_reqs, self.ngram_context_len),
|
||||
self.ngram_eos_token_id,
|
||||
dtype=torch.int32,
|
||||
device=self.device,
|
||||
)
|
||||
self.ngram_context_offsets = torch.arange(
|
||||
-self.ngram_context_len,
|
||||
0,
|
||||
dtype=torch.int64,
|
||||
device=self.device,
|
||||
)
|
||||
self.ple_query_start_loc = torch.zeros(
|
||||
self.max_num_reqs + 1,
|
||||
dtype=torch.int32,
|
||||
device=self.device,
|
||||
)
|
||||
|
||||
def _prepare_ngram_context(
|
||||
self,
|
||||
input_batch: InputBatch,
|
||||
req_states: RequestState,
|
||||
) -> torch.Tensor:
|
||||
num_reqs = input_batch.num_reqs
|
||||
num_reqs_padded = input_batch.num_reqs_after_padding
|
||||
context = self.ngram_context[:num_reqs_padded]
|
||||
context.fill_(self.ngram_eos_token_id)
|
||||
if num_reqs == 0:
|
||||
return context
|
||||
|
||||
request_indices = input_batch.idx_mapping[:num_reqs].long()
|
||||
context_end = req_states.num_computed_tokens.gpu[request_indices].long()
|
||||
token_indices = context_end.unsqueeze(1) + self.ngram_context_offsets
|
||||
valid_tokens = token_indices >= 0
|
||||
token_indices.clamp_min_(0)
|
||||
context_tokens = req_states.all_token_ids.gpu[
|
||||
request_indices.unsqueeze(1), token_indices
|
||||
]
|
||||
context[:num_reqs].copy_(
|
||||
torch.where(
|
||||
valid_tokens,
|
||||
context_tokens,
|
||||
context_tokens.new_full((), self.ngram_eos_token_id),
|
||||
)
|
||||
)
|
||||
return context
|
||||
|
||||
def prepare_inputs(
|
||||
self,
|
||||
input_batch: InputBatch,
|
||||
req_states: RequestState,
|
||||
) -> dict[str, Any]:
|
||||
model_inputs = super().prepare_inputs(input_batch, req_states)
|
||||
if not self.uses_ngram_embedding:
|
||||
return model_inputs
|
||||
|
||||
num_reqs_padded = input_batch.num_reqs_after_padding
|
||||
query_start_loc = self.ple_query_start_loc[: num_reqs_padded + 1]
|
||||
query_start_loc.copy_(input_batch.query_start_loc[: num_reqs_padded + 1])
|
||||
model_inputs.update(
|
||||
query_start_loc=query_start_loc,
|
||||
ngram_context=self._prepare_ngram_context(input_batch, req_states),
|
||||
)
|
||||
return model_inputs
|
||||
|
||||
def prepare_dummy_inputs(
|
||||
self,
|
||||
num_reqs: int,
|
||||
num_tokens: int,
|
||||
) -> dict[str, Any]:
|
||||
model_inputs = super().prepare_dummy_inputs(num_reqs, num_tokens)
|
||||
if not self.uses_ngram_embedding:
|
||||
return model_inputs
|
||||
|
||||
query_start_loc = self.ple_query_start_loc[: num_reqs + 1]
|
||||
query_start_loc[0] = 0
|
||||
tokens_per_req, num_extra_tokens = divmod(num_tokens, num_reqs)
|
||||
query_lens = torch.full(
|
||||
(num_reqs,),
|
||||
tokens_per_req,
|
||||
dtype=query_start_loc.dtype,
|
||||
device=query_start_loc.device,
|
||||
)
|
||||
if num_extra_tokens > 0:
|
||||
query_lens[-num_extra_tokens:] += 1
|
||||
torch.cumsum(query_lens, dim=0, out=query_start_loc[1:])
|
||||
|
||||
ngram_context = self.ngram_context[:num_reqs]
|
||||
ngram_context.fill_(self.ngram_eos_token_id)
|
||||
model_inputs.update(
|
||||
query_start_loc=query_start_loc,
|
||||
ngram_context=ngram_context,
|
||||
)
|
||||
return model_inputs
|
||||
|
||||
|
||||
__all__ = ["Qwen4ExpModelState"]
|
||||
@@ -0,0 +1,462 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Inference-only Qwen4Exp MTP (Multi-Token Predictor) model.
|
||||
|
||||
The MTP draft model reuses the Qwen4Exp backbone (PLE/HC/MoE) but:
|
||||
- drops all multi-modal handling (text-only),
|
||||
- forces PLE off while keeping the main model's HC stream count,
|
||||
- fuses the backbone hidden and the new-token embedding via
|
||||
``residual_linear_shared`` (fc_embedding + shared fc_hidden) instead of
|
||||
the ``Linear(2H, H)`` + repeat used by other MTP variants,
|
||||
- emits TWO hidden streams per step (scheme A): a single stream [T, H]
|
||||
(final-mixer collapsed, fed to the LM head) and a pre-final-mixer
|
||||
multi stream [T, hc_count*H] (fed to the next draft step).
|
||||
"""
|
||||
|
||||
from collections.abc import Iterable
|
||||
|
||||
import regex as re
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from vllm.compilation.decorators import support_torch_compile
|
||||
from vllm.config import VllmConfig, replace, set_current_vllm_config
|
||||
from vllm.distributed import get_pp_group
|
||||
from vllm.model_executor.layers.fused_moe.utils import (
|
||||
is_model_fused_shared_expert_compatible,
|
||||
)
|
||||
from vllm.model_executor.layers.layernorm import GemmaRMSNorm
|
||||
from vllm.model_executor.layers.linear import ColumnParallelLinear
|
||||
from vllm.model_executor.layers.logits_processor import LogitsProcessor
|
||||
from vllm.model_executor.layers.vocab_parallel_embedding import (
|
||||
ParallelLMHead,
|
||||
VocabParallelEmbedding,
|
||||
)
|
||||
from vllm.model_executor.model_loader.utils import configure_quant_config
|
||||
from vllm.model_executor.models.interfaces import SupportsPP
|
||||
from vllm.model_executor.models.qwen3_5 import Qwen3_5Model
|
||||
from vllm.model_executor.models.utils import (
|
||||
AutoWeightsLoader,
|
||||
PPMissingLayer,
|
||||
WeightsMapper,
|
||||
get_draft_quant_config,
|
||||
make_empty_intermediate_tensors_factory,
|
||||
maybe_fuse_shared_experts,
|
||||
maybe_prefix,
|
||||
)
|
||||
from vllm.sequence import IntermediateTensors
|
||||
from vllm.transformers_utils.configs.qwen4_exp import (
|
||||
Qwen4ExpTextConfig,
|
||||
)
|
||||
|
||||
from .hyperconnection import GatedResidual, HyperConnectionConfig
|
||||
from .low_latency_gemm import enable_qwen4_exp_low_latency_gemm
|
||||
from .model import (
|
||||
_HC_WEIGHTS_MAPPER,
|
||||
_QWEN4_EXP_IGNORED_MISSING_SUFFIXES,
|
||||
Qwen4ExpDecoderLayer,
|
||||
Qwen4ExpMixtureOfExperts,
|
||||
Qwen4ExpSparseMoeBlock,
|
||||
)
|
||||
|
||||
|
||||
def _remap_ignored_layers(
|
||||
ignored_layers: list[str],
|
||||
mtp_start_layer_idx: int,
|
||||
) -> list[str]:
|
||||
remapped: list[str] = []
|
||||
for name in ignored_layers:
|
||||
if name.startswith("mtp."):
|
||||
new_name = re.sub(
|
||||
r"(?<=\.layers\.)\d+",
|
||||
lambda m: str(mtp_start_layer_idx + int(m.group(0))),
|
||||
name,
|
||||
)
|
||||
remapped.append(new_name)
|
||||
else:
|
||||
remapped.append(name)
|
||||
return remapped
|
||||
|
||||
|
||||
def _remap_mtp_weight_name(name: str) -> str | None:
|
||||
"""Map Qwen4Exp checkpoint paths into the standalone draft model."""
|
||||
|
||||
for checkpoint_prefix in (
|
||||
"model.language_model.",
|
||||
"language_model.",
|
||||
):
|
||||
if name.startswith(checkpoint_prefix):
|
||||
name = name.removeprefix(checkpoint_prefix)
|
||||
break
|
||||
|
||||
if name.startswith("embed_tokens."):
|
||||
name = f"model.{name}"
|
||||
if name.startswith("model.mtp."):
|
||||
name = name.removeprefix("model.")
|
||||
if name.startswith("mtp.shared_head.head."):
|
||||
return name.replace("mtp.shared_head.head.", "lm_head.", 1)
|
||||
if name.startswith("model.shared_head.head."):
|
||||
return name.replace("model.shared_head.head.", "lm_head.", 1)
|
||||
if name.startswith("shared_head.head."):
|
||||
return name.replace("shared_head.head.", "lm_head.", 1)
|
||||
if name.startswith("model.lm_head."):
|
||||
return name.removeprefix("model.")
|
||||
if name.startswith("mtp."):
|
||||
return name.replace("mtp.", "model.", 1)
|
||||
if name.startswith("model.embed_tokens.") or name.startswith("lm_head."):
|
||||
return name
|
||||
return None
|
||||
|
||||
|
||||
def _make_draft_vllm_config(
|
||||
vllm_config: VllmConfig,
|
||||
mtp_start_layer_idx: int,
|
||||
) -> VllmConfig:
|
||||
"""Ensure that the draft model config is set in the vLLM config."""
|
||||
speculative_config = vllm_config.speculative_config
|
||||
if speculative_config is None or speculative_config.draft_model_config is None:
|
||||
raise ValueError("speculative_config.draft_model_config must be set")
|
||||
|
||||
draft_quant_config = get_draft_quant_config(vllm_config)
|
||||
|
||||
# inject packed and ignored modules to the quantization config of draft model
|
||||
if draft_quant_config is not None:
|
||||
configure_quant_config(draft_quant_config, Qwen4ExpMTP)
|
||||
ignored_layers = getattr(draft_quant_config, "ignored_layers", None)
|
||||
if ignored_layers:
|
||||
setattr( # noqa: B010
|
||||
draft_quant_config,
|
||||
"ignored_layers",
|
||||
_remap_ignored_layers(ignored_layers, mtp_start_layer_idx),
|
||||
)
|
||||
exclude_modules = getattr(draft_quant_config, "exclude_modules", None)
|
||||
if exclude_modules:
|
||||
setattr( # noqa: B010
|
||||
draft_quant_config,
|
||||
"exclude_modules",
|
||||
_remap_ignored_layers(exclude_modules, mtp_start_layer_idx),
|
||||
)
|
||||
|
||||
draft_vllm_config = replace(
|
||||
vllm_config,
|
||||
model_config=speculative_config.draft_model_config,
|
||||
)
|
||||
# VllmConfig post-init derives the target quant config, so restore the
|
||||
# independently resolved draft quant config after replacement.
|
||||
draft_vllm_config.quant_config = draft_quant_config
|
||||
return draft_vllm_config
|
||||
|
||||
|
||||
@support_torch_compile(
|
||||
dynamic_arg_dims={
|
||||
"input_ids": 0,
|
||||
"positions": -1,
|
||||
"intermediate_tensors": 0,
|
||||
"inputs_embeds": 0,
|
||||
"hidden_states": 0,
|
||||
}
|
||||
)
|
||||
class Qwen4ExpMultiTokenPredictor(nn.Module):
|
||||
hf_to_vllm_mapper = Qwen3_5Model.hf_to_vllm_mapper | _HC_WEIGHTS_MAPPER
|
||||
|
||||
def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None:
|
||||
super().__init__()
|
||||
|
||||
model_config = vllm_config.model_config
|
||||
config: Qwen4ExpTextConfig = model_config.hf_text_config
|
||||
|
||||
self.config = config
|
||||
self.vocab_size = config.vocab_size
|
||||
|
||||
self.mtp_start_layer_idx = config.num_hidden_layers
|
||||
self.num_mtp_layers = getattr(config, "mtp_num_hidden_layers", 1)
|
||||
|
||||
self.hidden_size = config.hidden_size
|
||||
self.hc_count = config.hc_count
|
||||
|
||||
self.embed_tokens = VocabParallelEmbedding(self.vocab_size, self.hidden_size)
|
||||
draft_vllm_config = _make_draft_vllm_config(
|
||||
vllm_config,
|
||||
self.mtp_start_layer_idx,
|
||||
)
|
||||
with set_current_vllm_config(draft_vllm_config, prefix=prefix):
|
||||
# residual_linear_shared fusion: fc_embedding projects the token
|
||||
# embedding, fc_hidden (shared across HC branches) projects the
|
||||
# backbone hidden; the embedding is added as a residual to every
|
||||
# branch (see mtp_residual_linear_shared.md).
|
||||
self.fc_embedding = ColumnParallelLinear(
|
||||
self.hidden_size,
|
||||
self.hidden_size,
|
||||
gather_output=True,
|
||||
bias=False,
|
||||
return_bias=False,
|
||||
quant_config=draft_vllm_config.quant_config,
|
||||
prefix=f"{prefix}.fc_embedding",
|
||||
)
|
||||
self.fc_hidden = ColumnParallelLinear(
|
||||
self.hidden_size,
|
||||
self.hidden_size,
|
||||
gather_output=True,
|
||||
bias=False,
|
||||
return_bias=False,
|
||||
quant_config=draft_vllm_config.quant_config,
|
||||
prefix=f"{prefix}.fc_hidden",
|
||||
)
|
||||
self.layers = nn.ModuleList(
|
||||
Qwen4ExpDecoderLayer(
|
||||
draft_vllm_config,
|
||||
layer_type="full_attention",
|
||||
prefix=f"{prefix}.layers.{self.mtp_start_layer_idx + idx}",
|
||||
)
|
||||
for idx in range(self.num_mtp_layers)
|
||||
)
|
||||
self.is_fused_shared_expert_enabled = is_model_fused_shared_expert_compatible(
|
||||
self.layers,
|
||||
Qwen4ExpSparseMoeBlock,
|
||||
"mlp",
|
||||
)
|
||||
|
||||
self.pre_fc_norm_embedding = GemmaRMSNorm(
|
||||
self.hidden_size, eps=config.rms_norm_eps
|
||||
)
|
||||
self.pre_fc_norm_hidden = GemmaRMSNorm(
|
||||
self.hidden_size * self.hc_count, eps=config.rms_norm_eps
|
||||
)
|
||||
# HC final mixer collapses the multi stream into [T, H] for the LM head.
|
||||
hc_config = HyperConnectionConfig(
|
||||
hc_count=config.hc_count,
|
||||
hidden_size=config.hidden_size,
|
||||
params_dtype=torch.bfloat16,
|
||||
hc_lowrank=config.hc_lowrank,
|
||||
rms_norm_eps=config.rms_norm_eps,
|
||||
hc_per_branch_norm=True,
|
||||
)
|
||||
self.hyper_connection_mixer = GatedResidual(
|
||||
hc_config,
|
||||
use_combine=False,
|
||||
prefix=maybe_prefix(prefix, "hyper_connection_mixer"),
|
||||
)
|
||||
self.make_empty_intermediate_tensors = make_empty_intermediate_tensors_factory(
|
||||
["hidden_states"], self.hidden_size * self.hc_count
|
||||
)
|
||||
|
||||
def _iter_qsa_attentions(self):
|
||||
"""Yield MTP attention modules that own a QSA indexer."""
|
||||
|
||||
for layer in self.layers:
|
||||
attention = getattr(layer, "self_attn", None)
|
||||
if (
|
||||
attention is not None
|
||||
and getattr(attention, "indexer", None) is not None
|
||||
):
|
||||
yield attention
|
||||
|
||||
def set_skip_topk(self, skip: bool) -> None:
|
||||
"""Select on MTP step 0 and reuse its QSA indices on later steps."""
|
||||
|
||||
for attention in self._iter_qsa_attentions():
|
||||
attention.indexer.skip_topk = skip
|
||||
|
||||
def compact_topk_indices(self, row_indices: torch.Tensor) -> None:
|
||||
"""Keep each request's target-aligned step-0 sparse-index row."""
|
||||
|
||||
num_rows = row_indices.numel()
|
||||
for attention in self._iter_qsa_attentions():
|
||||
buffer = attention.topk_indices_buffer
|
||||
selected = buffer.index_select(0, row_indices)
|
||||
buffer[:num_rows].copy_(selected)
|
||||
|
||||
def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
|
||||
return self.embed_tokens(input_ids)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.Tensor | None,
|
||||
positions: torch.Tensor,
|
||||
hidden_states: torch.Tensor | None = None,
|
||||
intermediate_tensors: IntermediateTensors | None = None,
|
||||
inputs_embeds: torch.Tensor | None = None,
|
||||
spec_step_idx: int = 0,
|
||||
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor] | IntermediateTensors:
|
||||
hc_count = self.hc_count
|
||||
hidden_size = self.hidden_size
|
||||
|
||||
if get_pp_group().is_first_rank:
|
||||
assert hidden_states is not None
|
||||
if inputs_embeds is None:
|
||||
assert input_ids is not None
|
||||
inputs_embeds = self.embed_input_ids(input_ids)
|
||||
# Embedding branch: pre-norm -> fc_embedding -> [T, H].
|
||||
inputs_embeds = self.pre_fc_norm_embedding(inputs_embeds)
|
||||
inputs_embeds = self.fc_embedding(inputs_embeds)
|
||||
|
||||
# Backbone hidden is multi-stream [T, hc_count*H] (scheme A:
|
||||
# the main model truly emits the pre-final-mixer multi stream
|
||||
# on the first step; subsequent steps reuse the prior draft
|
||||
# step's multi stream).
|
||||
num_tokens = hidden_states.shape[0]
|
||||
hidden_states = hidden_states.view(num_tokens, hc_count, hidden_size)
|
||||
hidden_states = self.pre_fc_norm_hidden(hidden_states.flatten(-2)).view(
|
||||
num_tokens, hc_count, hidden_size
|
||||
)
|
||||
hidden_states = self.fc_hidden(hidden_states)
|
||||
# Add the embedding residual to every branch, then fold back
|
||||
# to [T, hc_count*H] (HC outer, HS inner) for the HC decoder.
|
||||
hidden_states = inputs_embeds.unsqueeze(-2) + hidden_states
|
||||
hidden_states = hidden_states.flatten(-2)
|
||||
else:
|
||||
assert intermediate_tensors is not None
|
||||
hidden_states = intermediate_tensors["hidden_states"]
|
||||
|
||||
current_step_idx = spec_step_idx % self.num_mtp_layers
|
||||
layer = self.layers[current_step_idx]
|
||||
hidden_states, block_output, injection = layer(
|
||||
hidden_states=hidden_states,
|
||||
prev_block_output=None,
|
||||
prev_injection=None,
|
||||
positions=positions,
|
||||
input_ids=None,
|
||||
query_start_loc=None,
|
||||
ngram_context=None,
|
||||
)
|
||||
if not get_pp_group().is_last_rank:
|
||||
# As in the target model, PP carries a materialized tensor rather
|
||||
# than the delayed hidden/output/injection tuple.
|
||||
hidden_states = layer.mlp_hyper_connection.combine(
|
||||
hidden_states, block_output, injection
|
||||
)
|
||||
return IntermediateTensors({"hidden_states": hidden_states})
|
||||
|
||||
# Last PP rank finalize. Keep both:
|
||||
# (A) sample_hidden_states [T, H] -> single stream for the LM head
|
||||
# (B) multi_hidden [T, hc_count*H] -> pre-final-mixer multi stream
|
||||
# for the next draft step (zero extra compute, just kept).
|
||||
multi_hidden, sample_hidden_states, _ = (
|
||||
self.hyper_connection_mixer.combine_and_mix(
|
||||
hidden_states, block_output, injection
|
||||
)
|
||||
)
|
||||
return sample_hidden_states, multi_hidden
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
weights = maybe_fuse_shared_experts(
|
||||
weights,
|
||||
enabled=self.is_fused_shared_expert_enabled,
|
||||
n_routed_experts=getattr(self.config, "num_experts", 0) or 0,
|
||||
n_shared_experts=1,
|
||||
ckpt_prefix="mlp.shared_expert",
|
||||
)
|
||||
mapper = self.hf_to_vllm_mapper | WeightsMapper(
|
||||
orig_to_new_substr={"hyper_connection_mixer.block_inject_weight": None}
|
||||
)
|
||||
loader = AutoWeightsLoader(
|
||||
self,
|
||||
ignore_unexpected_suffixes=_QWEN4_EXP_IGNORED_MISSING_SUFFIXES.copy(),
|
||||
)
|
||||
return loader.load_weights(weights, mapper=mapper)
|
||||
|
||||
|
||||
@support_torch_compile(
|
||||
dynamic_arg_dims={
|
||||
"input_ids": 0,
|
||||
"positions": -1,
|
||||
"intermediate_tensors": 0,
|
||||
"inputs_embeds": 0,
|
||||
"hidden_states": 0,
|
||||
}
|
||||
)
|
||||
class Qwen4ExpMTP(nn.Module, SupportsPP, Qwen4ExpMixtureOfExperts):
|
||||
packed_modules_mapping = {
|
||||
"qkv_proj": ["q_proj", "k_proj", "v_proj"],
|
||||
"gate_up_proj": ["gate_proj", "up_proj"],
|
||||
"in_proj_qkvz": ["in_proj_qkv", "in_proj_z"],
|
||||
"in_proj_ba": ["in_proj_b", "in_proj_a"],
|
||||
"input_mix_weight_down_block_inject": [
|
||||
"input_mix_weight_down",
|
||||
"block_inject_weight",
|
||||
"_input_mix_padding",
|
||||
],
|
||||
}
|
||||
|
||||
def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None:
|
||||
config: Qwen4ExpTextConfig = vllm_config.model_config.hf_text_config
|
||||
self.vllm_config = vllm_config
|
||||
cache_config = vllm_config.cache_config
|
||||
if cache_config.mamba_cache_mode == "all":
|
||||
raise NotImplementedError(
|
||||
"Qwen4ExpMTP currently does not support 'all' prefix caching, "
|
||||
"please use '--mamba-cache-mode=align' instead"
|
||||
)
|
||||
|
||||
self.quant_config = vllm_config.quant_config
|
||||
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.model = Qwen4ExpMultiTokenPredictor(
|
||||
vllm_config=vllm_config,
|
||||
prefix=maybe_prefix(prefix, "mtp"),
|
||||
)
|
||||
|
||||
if get_pp_group().is_last_rank:
|
||||
if config.tie_word_embeddings:
|
||||
self.lm_head = self.model.embed_tokens
|
||||
else:
|
||||
self.lm_head = ParallelLMHead(
|
||||
config.vocab_size,
|
||||
config.hidden_size,
|
||||
prefix=maybe_prefix(prefix, "lm_head"),
|
||||
)
|
||||
else:
|
||||
self.lm_head = PPMissingLayer()
|
||||
|
||||
self.logits_processor = LogitsProcessor(config.vocab_size)
|
||||
self.make_empty_intermediate_tensors = (
|
||||
self.model.make_empty_intermediate_tensors
|
||||
)
|
||||
self.set_moe_parameters(self.model.layers)
|
||||
enable_qwen4_exp_low_latency_gemm(self, vllm_config.model_config.dtype)
|
||||
|
||||
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 | None,
|
||||
positions: torch.Tensor,
|
||||
hidden_states: torch.Tensor | None = None,
|
||||
intermediate_tensors: IntermediateTensors | None = None,
|
||||
inputs_embeds: torch.Tensor | None = None,
|
||||
spec_step_idx: int = 0,
|
||||
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor] | IntermediateTensors:
|
||||
return self.model(
|
||||
input_ids,
|
||||
positions,
|
||||
hidden_states,
|
||||
intermediate_tensors,
|
||||
inputs_embeds,
|
||||
spec_step_idx=spec_step_idx,
|
||||
)
|
||||
|
||||
def compute_logits(
|
||||
self, hidden_states: torch.Tensor, spec_step_idx: int = 0
|
||||
) -> torch.Tensor | None:
|
||||
return self.logits_processor(self.lm_head, hidden_states)
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
def remap_weight_names():
|
||||
for name, weight in weights:
|
||||
remapped_name = _remap_mtp_weight_name(name)
|
||||
if remapped_name is not None:
|
||||
yield remapped_name, weight
|
||||
|
||||
mapper = WeightsMapper(
|
||||
orig_to_new_substr={"hyper_connection_mixer.block_inject_weight": None}
|
||||
)
|
||||
loader = AutoWeightsLoader(
|
||||
self,
|
||||
ignore_unexpected_suffixes=_QWEN4_EXP_IGNORED_MISSING_SUFFIXES.copy(),
|
||||
)
|
||||
return loader.load_weights(remap_weight_names(), mapper=mapper)
|
||||
|
||||
|
||||
__all__ = ["Qwen4ExpMTP", "Qwen4ExpMultiTokenPredictor"]
|
||||
@@ -0,0 +1,3 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""NVIDIA-only Qwen4Exp kernels; import leaf modules directly."""
|
||||
@@ -0,0 +1,487 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""NVIDIA HyperConnection kernels for Qwen4Exp."""
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import tl, triton
|
||||
from vllm.utils.torch_utils import direct_register_custom_op
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _grouped_gemma_rmsnorm_kernel(
|
||||
x_ptr,
|
||||
w_ptr,
|
||||
y_ptr,
|
||||
stride_x,
|
||||
stride_y,
|
||||
DIM: tl.constexpr,
|
||||
NUM_GROUPS: tl.constexpr,
|
||||
W_SHARED: tl.constexpr,
|
||||
EPS: tl.constexpr,
|
||||
launch_pdl: tl.constexpr,
|
||||
) -> None:
|
||||
GROUP_DIM: tl.constexpr = DIM // NUM_GROUPS
|
||||
BLOCK_SIZE: tl.constexpr = triton.next_power_of_2(GROUP_DIM)
|
||||
|
||||
pid = tl.program_id(0)
|
||||
group_id = pid % NUM_GROUPS
|
||||
row = pid // NUM_GROUPS
|
||||
|
||||
offs_g = tl.arange(0, BLOCK_SIZE)
|
||||
offsets = group_id * GROUP_DIM + offs_g
|
||||
mask = offs_g < GROUP_DIM
|
||||
# A [GROUP_DIM] affine is shared; a [DIM] affine follows the grouped
|
||||
# checkpoint layout.
|
||||
w_offs = offs_g if W_SHARED else offsets
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_wait()
|
||||
|
||||
x = tl.load(x_ptr + row * stride_x + offsets, mask, other=0.0).to(tl.float32)
|
||||
w = tl.load(w_ptr + w_offs, mask, other=0.0)
|
||||
|
||||
rrms = tl.rsqrt(tl.sum(x * x) / GROUP_DIM + EPS)
|
||||
# Gemma's (1 + w) affine is written this way to lower to an FMA.
|
||||
y = x * rrms
|
||||
y += y * w.to(tl.float32)
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_launch_dependents()
|
||||
tl.store(y_ptr + row * stride_y + offsets, y, mask)
|
||||
|
||||
|
||||
def _grouped_gemma_rmsnorm(
|
||||
x: torch.Tensor, weight: torch.Tensor, eps: float, num_groups: int
|
||||
) -> torch.Tensor:
|
||||
N, DIM = x.shape
|
||||
assert x.stride(1) == 1, "grouped Gemma RMSNorm requires unit inner stride"
|
||||
assert weight.is_contiguous(), "grouped Gemma RMSNorm weight must be contiguous"
|
||||
assert DIM % num_groups == 0
|
||||
group_dim = DIM // num_groups
|
||||
assert weight.numel() in (group_dim, DIM)
|
||||
|
||||
y = x.new_empty(x.shape)
|
||||
_grouped_gemma_rmsnorm_kernel[(N * num_groups,)](
|
||||
x,
|
||||
weight,
|
||||
y,
|
||||
x.stride(0),
|
||||
y.stride(0),
|
||||
DIM,
|
||||
num_groups,
|
||||
W_SHARED=weight.numel() == group_dim,
|
||||
EPS=eps,
|
||||
launch_pdl=current_platform.is_arch_support_pdl(),
|
||||
)
|
||||
return y
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _hc_silu_kernel(
|
||||
x_ptr,
|
||||
y_ptr,
|
||||
stride_x,
|
||||
stride_y,
|
||||
DIM: tl.constexpr,
|
||||
HC: tl.constexpr,
|
||||
launch_pdl: tl.constexpr,
|
||||
) -> None:
|
||||
BLOCK_SIZE: tl.constexpr = triton.next_power_of_2(DIM)
|
||||
|
||||
row = tl.program_id(0)
|
||||
offs = tl.arange(0, BLOCK_SIZE)
|
||||
mask = offs < DIM
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_wait()
|
||||
|
||||
x = tl.load(x_ptr + row * stride_x + offs, mask).to(tl.float32) / HC
|
||||
y = x * tl.sigmoid(x)
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_launch_dependents()
|
||||
tl.store(y_ptr + row * stride_y + offs, y, mask)
|
||||
|
||||
|
||||
def _hc_silu(x: torch.Tensor, hc_count: int) -> torch.Tensor:
|
||||
num_tokens, DIM = x.shape
|
||||
assert x.stride(1) == 1
|
||||
|
||||
output = x.new_empty(x.shape)
|
||||
_hc_silu_kernel[(num_tokens,)](
|
||||
x,
|
||||
output,
|
||||
x.stride(0),
|
||||
output.stride(0),
|
||||
DIM=DIM,
|
||||
HC=hc_count,
|
||||
launch_pdl=current_platform.is_arch_support_pdl(),
|
||||
)
|
||||
return output
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _hc_gate_mix_kernel(
|
||||
x_ptr,
|
||||
g_ptr,
|
||||
y_ptr,
|
||||
stride_x,
|
||||
stride_g,
|
||||
stride_y,
|
||||
DIM: tl.constexpr,
|
||||
HC: tl.constexpr,
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
launch_pdl: tl.constexpr,
|
||||
) -> None:
|
||||
HC_DIM: tl.constexpr = DIM // HC
|
||||
|
||||
row = tl.program_id(0)
|
||||
tile_id = tl.program_id(1)
|
||||
offs_inner = tile_id * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
|
||||
mask = offs_inner < HC_DIM
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_wait()
|
||||
|
||||
# The constexpr loop is unrolled and keeps one stream live at a time.
|
||||
# Materializing [HC, BLOCK_SIZE] more than doubles latency at large M.
|
||||
acc = tl.zeros([BLOCK_SIZE], dtype=tl.float32)
|
||||
for stream in tl.static_range(HC):
|
||||
offsets = stream * HC_DIM + offs_inner
|
||||
g = tl.load(g_ptr + row * stride_g + offsets, mask, other=0.0)
|
||||
x = tl.load(x_ptr + row * stride_x + offsets, mask, other=0.0)
|
||||
acc += tl.sigmoid(g.to(tl.float32)) * x.to(tl.float32)
|
||||
acc /= HC
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_launch_dependents()
|
||||
tl.store(y_ptr + row * stride_y + offs_inner, acc, mask)
|
||||
|
||||
|
||||
def _hc_gate_mix(x: torch.Tensor, gate: torch.Tensor, hc_count: int) -> torch.Tensor:
|
||||
N, DIM = gate.shape
|
||||
assert x.shape == gate.shape
|
||||
assert DIM % hc_count == 0
|
||||
assert x.stride(1) == 1
|
||||
assert gate.stride(1) == 1
|
||||
|
||||
HC_DIM = DIM // hc_count
|
||||
out = x.new_empty(N, HC_DIM)
|
||||
BLOCK_SIZE = 512
|
||||
_hc_gate_mix_kernel[(N, triton.cdiv(HC_DIM, BLOCK_SIZE))](
|
||||
x,
|
||||
gate,
|
||||
out,
|
||||
x.stride(0),
|
||||
gate.stride(0),
|
||||
out.stride(0),
|
||||
DIM,
|
||||
hc_count,
|
||||
BLOCK_SIZE,
|
||||
launch_pdl=current_platform.is_arch_support_pdl(),
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _hc_combine_kernel(
|
||||
block_ptr,
|
||||
res_ptr,
|
||||
inj_ptr,
|
||||
out_ptr,
|
||||
stride_block,
|
||||
stride_res,
|
||||
stride_inj,
|
||||
stride_out,
|
||||
HC_DIM: tl.constexpr,
|
||||
HC: tl.constexpr,
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
launch_pdl: tl.constexpr,
|
||||
) -> None:
|
||||
HC_PAD: tl.constexpr = triton.next_power_of_2(HC)
|
||||
|
||||
row = tl.program_id(0)
|
||||
tile_id = tl.program_id(1)
|
||||
|
||||
offs_inner = tile_id * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
|
||||
mask_inner = offs_inner < HC_DIM
|
||||
offs_hc = tl.arange(0, HC_PAD)
|
||||
mask_hc = offs_hc < HC
|
||||
offs = offs_hc[:, None] * HC_DIM + offs_inner[None, :]
|
||||
mask = mask_hc[:, None] & mask_inner[None, :]
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_wait()
|
||||
|
||||
inj = tl.load(inj_ptr + row * stride_inj + offs_hc, mask_hc, other=0.0)
|
||||
block = tl.load(block_ptr + row * stride_block + offs_inner, mask_inner, other=0.0)
|
||||
res = tl.load(res_ptr + row * stride_res + offs, mask, other=0.0)
|
||||
|
||||
# Keeping HC as a broadcast dimension is faster here than four separate
|
||||
# residual load/store sequences.
|
||||
inj = 2.0 * tl.sigmoid(inj.to(tl.float32) / HC)
|
||||
out = res.to(tl.float32) + block.to(tl.float32)[None, :] * inj[:, None]
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_launch_dependents()
|
||||
tl.store(out_ptr + row * stride_out + offs, out, mask=mask)
|
||||
|
||||
|
||||
def _hc_combine(
|
||||
residual: torch.Tensor,
|
||||
block_output: torch.Tensor,
|
||||
injection_logits: torch.Tensor,
|
||||
hc_count: int,
|
||||
) -> torch.Tensor:
|
||||
N, DIM = residual.shape
|
||||
assert DIM % hc_count == 0
|
||||
hc_dim = DIM // hc_count
|
||||
assert block_output.shape == (N, hc_dim)
|
||||
assert injection_logits.shape == (N, hc_count)
|
||||
assert residual.stride(1) == 1
|
||||
assert block_output.stride(1) == 1
|
||||
assert injection_logits.stride(1) == 1
|
||||
|
||||
out = residual.new_empty(residual.shape)
|
||||
BLOCK_SIZE = 512
|
||||
_hc_combine_kernel[(N, triton.cdiv(hc_dim, BLOCK_SIZE))](
|
||||
block_output,
|
||||
residual,
|
||||
injection_logits,
|
||||
out,
|
||||
block_output.stride(0),
|
||||
residual.stride(0),
|
||||
injection_logits.stride(0),
|
||||
out.stride(0),
|
||||
hc_dim,
|
||||
hc_count,
|
||||
BLOCK_SIZE,
|
||||
launch_pdl=current_platform.is_arch_support_pdl(),
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _hc_combine_norm_kernel(
|
||||
block_ptr,
|
||||
res_ptr,
|
||||
inj_ptr,
|
||||
w_ptr,
|
||||
out_ptr,
|
||||
y_ptr,
|
||||
stride_block,
|
||||
stride_res,
|
||||
stride_inj,
|
||||
stride_out,
|
||||
stride_y,
|
||||
HC_DIM: tl.constexpr,
|
||||
HC: tl.constexpr,
|
||||
W_SHARED: tl.constexpr,
|
||||
EPS: tl.constexpr,
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
launch_pdl: tl.constexpr,
|
||||
) -> None:
|
||||
HC_PAD: tl.constexpr = triton.next_power_of_2(HC)
|
||||
NUM_TILES: tl.constexpr = triton.cdiv(HC_DIM, BLOCK_SIZE)
|
||||
NUM_TILES_PAD: tl.constexpr = triton.next_power_of_2(NUM_TILES)
|
||||
|
||||
row = tl.program_id(0)
|
||||
stream = tl.program_id(1)
|
||||
offs_hc = tl.arange(0, HC_PAD)
|
||||
mask_hc = offs_hc < HC
|
||||
tile_ids = tl.arange(0, NUM_TILES_PAD)
|
||||
offs_inner = tile_ids[:, None] * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)[None, :]
|
||||
mask_inner = offs_inner < HC_DIM
|
||||
offs = stream * HC_DIM + offs_inner
|
||||
# Shared norm weights repeat across streams; per-branch weights use the
|
||||
# same flattened HC layout as the residual.
|
||||
w_offs = offs_inner if W_SHARED else offs
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_wait()
|
||||
|
||||
# Start the uncached residual load first, then issue the other combine
|
||||
# loads before consuming any of them.
|
||||
res = tl.load(res_ptr + row * stride_res + offs, mask_inner, other=0.0)
|
||||
inj = tl.load(inj_ptr + row * stride_inj + offs_hc, mask_hc, other=0.0)
|
||||
block = tl.load(block_ptr + row * stride_block + offs_inner, mask_inner, other=0.0)
|
||||
inj = 2.0 * tl.sigmoid(inj.to(tl.float32) / HC)
|
||||
inj = tl.sum(tl.where(offs_hc == stream, inj, 0.0))
|
||||
# Round the materialized combine result before normalization. This matches
|
||||
# the unfused combine -> RMSNorm boundary.
|
||||
out = (res.to(tl.float32) + block.to(tl.float32) * inj).to(out_ptr.dtype.element_ty)
|
||||
tl.store(out_ptr + row * stride_out + offs, out, mask=mask_inner)
|
||||
|
||||
out = out.to(tl.float32)
|
||||
# Keep the two-axis reduction: flattening the padded tile is ~40% slower
|
||||
# at decode sizes.
|
||||
sum_sq = tl.sum(tl.sum(out * out, axis=1), axis=0)
|
||||
rrms = tl.rsqrt(sum_sq / HC_DIM + EPS)
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_launch_dependents()
|
||||
|
||||
# Loading the weight earlier helps decode but keeps the tile live across
|
||||
# the reduction and regresses larger batches, so defer it to the norm.
|
||||
w = tl.load(w_ptr + w_offs, mask_inner, other=0.0)
|
||||
y = out * rrms
|
||||
y += y * w.to(tl.float32)
|
||||
tl.store(y_ptr + row * stride_y + offs, y, mask_inner)
|
||||
|
||||
|
||||
def _hc_combine_norm(
|
||||
residual: torch.Tensor,
|
||||
block_output: torch.Tensor,
|
||||
injection_logits: torch.Tensor,
|
||||
norm_weight: torch.Tensor,
|
||||
eps: float,
|
||||
hc_count: int,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
N, DIM = residual.shape
|
||||
assert DIM % hc_count == 0
|
||||
hc_dim = DIM // hc_count
|
||||
assert block_output.shape == (N, hc_dim)
|
||||
assert injection_logits.shape == (N, hc_count)
|
||||
assert residual.stride(1) == 1
|
||||
assert block_output.stride(1) == 1
|
||||
assert injection_logits.stride(1) == 1
|
||||
assert norm_weight.is_contiguous()
|
||||
assert norm_weight.numel() in (hc_dim, DIM)
|
||||
|
||||
out = residual.new_empty(residual.shape)
|
||||
y = residual.new_empty(residual.shape)
|
||||
BLOCK_SIZE = 512
|
||||
_hc_combine_norm_kernel[(N, hc_count)](
|
||||
block_output,
|
||||
residual,
|
||||
injection_logits,
|
||||
norm_weight,
|
||||
out,
|
||||
y,
|
||||
block_output.stride(0),
|
||||
residual.stride(0),
|
||||
injection_logits.stride(0),
|
||||
out.stride(0),
|
||||
y.stride(0),
|
||||
hc_dim,
|
||||
hc_count,
|
||||
W_SHARED=norm_weight.numel() == hc_dim,
|
||||
EPS=eps,
|
||||
BLOCK_SIZE=BLOCK_SIZE,
|
||||
launch_pdl=current_platform.is_arch_support_pdl(),
|
||||
)
|
||||
return out, y
|
||||
|
||||
|
||||
def _same_shape_fake(x: torch.Tensor, *args) -> torch.Tensor:
|
||||
return x.new_empty(x.shape)
|
||||
|
||||
|
||||
def _hc_gate_mix_fake(
|
||||
x: torch.Tensor, gate: torch.Tensor, hc_count: int
|
||||
) -> torch.Tensor:
|
||||
del gate
|
||||
return x.new_empty((x.shape[0], x.shape[1] // hc_count))
|
||||
|
||||
|
||||
def _hc_combine_fake(
|
||||
residual: torch.Tensor,
|
||||
block_output: torch.Tensor,
|
||||
injection_logits: torch.Tensor,
|
||||
hc_count: int,
|
||||
) -> torch.Tensor:
|
||||
del block_output, injection_logits, hc_count
|
||||
return residual.new_empty(residual.shape)
|
||||
|
||||
|
||||
def _hc_combine_norm_fake(
|
||||
residual: torch.Tensor,
|
||||
block_output: torch.Tensor,
|
||||
injection_logits: torch.Tensor,
|
||||
norm_weight: torch.Tensor,
|
||||
eps: float,
|
||||
hc_count: int,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
del block_output, injection_logits, norm_weight, eps, hc_count
|
||||
return residual.new_empty(residual.shape), residual.new_empty(residual.shape)
|
||||
|
||||
|
||||
direct_register_custom_op(
|
||||
op_name="qwen4_exp_grouped_gemma_rmsnorm",
|
||||
op_func=_grouped_gemma_rmsnorm,
|
||||
fake_impl=_same_shape_fake,
|
||||
)
|
||||
direct_register_custom_op(
|
||||
op_name="qwen4_exp_hc_silu",
|
||||
op_func=_hc_silu,
|
||||
fake_impl=_same_shape_fake,
|
||||
)
|
||||
direct_register_custom_op(
|
||||
op_name="qwen4_exp_hc_gate_mix",
|
||||
op_func=_hc_gate_mix,
|
||||
fake_impl=_hc_gate_mix_fake,
|
||||
)
|
||||
direct_register_custom_op(
|
||||
op_name="qwen4_exp_hc_combine",
|
||||
op_func=_hc_combine,
|
||||
fake_impl=_hc_combine_fake,
|
||||
)
|
||||
direct_register_custom_op(
|
||||
op_name="qwen4_exp_hc_combine_norm",
|
||||
op_func=_hc_combine_norm,
|
||||
fake_impl=_hc_combine_norm_fake,
|
||||
)
|
||||
|
||||
|
||||
def grouped_gemma_rmsnorm(
|
||||
x: torch.Tensor, weight: torch.Tensor, eps: float, num_groups: int
|
||||
) -> torch.Tensor:
|
||||
return torch.ops.vllm.qwen4_exp_grouped_gemma_rmsnorm(x, weight, eps, num_groups)
|
||||
|
||||
|
||||
def hc_silu(x: torch.Tensor, hc_count: int) -> torch.Tensor:
|
||||
return torch.ops.vllm.qwen4_exp_hc_silu(x, hc_count)
|
||||
|
||||
|
||||
def hc_gate_mix(x: torch.Tensor, gate: torch.Tensor, hc_count: int) -> torch.Tensor:
|
||||
return torch.ops.vllm.qwen4_exp_hc_gate_mix(x, gate, hc_count)
|
||||
|
||||
|
||||
def hc_combine(
|
||||
residual: torch.Tensor,
|
||||
block_output: torch.Tensor,
|
||||
injection_logits: torch.Tensor,
|
||||
hc_count: int,
|
||||
) -> torch.Tensor:
|
||||
return torch.ops.vllm.qwen4_exp_hc_combine(
|
||||
residual, block_output, injection_logits, hc_count
|
||||
)
|
||||
|
||||
|
||||
def hc_combine_norm(
|
||||
residual: torch.Tensor,
|
||||
block_output: torch.Tensor,
|
||||
injection_logits: torch.Tensor,
|
||||
norm_weight: torch.Tensor,
|
||||
eps: float,
|
||||
hc_count: int,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
return torch.ops.vllm.qwen4_exp_hc_combine_norm(
|
||||
residual,
|
||||
block_output,
|
||||
injection_logits,
|
||||
norm_weight,
|
||||
eps,
|
||||
hc_count,
|
||||
)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"grouped_gemma_rmsnorm",
|
||||
"hc_combine",
|
||||
"hc_combine_norm",
|
||||
"hc_gate_mix",
|
||||
"hc_silu",
|
||||
]
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,508 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Fused QSA pre-indexer kernel for Qwen4Exp."""
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.triton_utils import tl, triton
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _norm_rope(
|
||||
x,
|
||||
pos_t,
|
||||
pos_h,
|
||||
pos_w,
|
||||
cos_sin_ptr,
|
||||
cos_sin_stride,
|
||||
norm_weight_ptr,
|
||||
eps,
|
||||
IS_MROPE: tl.constexpr,
|
||||
MROPE_H: tl.constexpr,
|
||||
MROPE_W: tl.constexpr,
|
||||
):
|
||||
"""Apply Gemma RMSNorm and selected-axis NeoX RoPE to register rows."""
|
||||
TILE_T: tl.constexpr = x.shape[0]
|
||||
TILE_H: tl.constexpr = x.shape[1]
|
||||
D: tl.constexpr = x.shape[2]
|
||||
ROWS: tl.constexpr = TILE_T * TILE_H
|
||||
HALF: tl.constexpr = D // 2
|
||||
QUARTER: tl.constexpr = D // 4
|
||||
pairs = tl.arange(0, QUARTER)
|
||||
if IS_MROPE:
|
||||
# Qwen interleaves temporal, height, and width rotary pairs. Each axis
|
||||
# still indexes the same position-major cos/sin table.
|
||||
h_mask = ((pairs % 3) == 1) & (pairs <= 3 * MROPE_H)
|
||||
w_mask = ((pairs % 3) == 2) & (pairs <= 3 * MROPE_W)
|
||||
t_mask = ~(h_mask | w_mask)
|
||||
base = cos_sin_ptr + pairs[None, :]
|
||||
pos_rows = (pos_t, pos_h, pos_w)
|
||||
axis_masks = (t_mask, h_mask, w_mask)
|
||||
cos = tl.zeros((TILE_T, QUARTER), dtype=cos_sin_ptr.dtype.element_ty)
|
||||
sin = tl.zeros((TILE_T, QUARTER), dtype=cos_sin_ptr.dtype.element_ty)
|
||||
for axis in tl.static_range(3):
|
||||
cos += tl.load(
|
||||
base + pos_rows[axis][:, None] * cos_sin_stride,
|
||||
mask=axis_masks[axis][None, :],
|
||||
other=0,
|
||||
)
|
||||
sin += tl.load(
|
||||
base + pos_rows[axis][:, None] * cos_sin_stride + QUARTER,
|
||||
mask=axis_masks[axis][None, :],
|
||||
other=0,
|
||||
)
|
||||
else:
|
||||
cos = tl.load(cos_sin_ptr + pos_t[:, None] * cos_sin_stride + pairs[None, :])
|
||||
sin = tl.load(
|
||||
cos_sin_ptr + pos_t[:, None] * cos_sin_stride + QUARTER + pairs[None, :]
|
||||
)
|
||||
|
||||
cos = tl.reshape(
|
||||
tl.broadcast_to(cos[:, None, :], (TILE_T, TILE_H, QUARTER)),
|
||||
(ROWS, QUARTER),
|
||||
)
|
||||
sin = tl.reshape(
|
||||
tl.broadcast_to(sin[:, None, :], (TILE_T, TILE_H, QUARTER)),
|
||||
(ROWS, QUARTER),
|
||||
)
|
||||
x = tl.reshape(x, (ROWS, D)).to(tl.float32)
|
||||
weight = tl.load(norm_weight_ptr + tl.arange(0, D)).to(tl.float32) + 1.0
|
||||
rrms = tl.rsqrt(tl.sum(x * x, axis=1) / D + eps)
|
||||
y = (x * rrms[:, None] * weight[None, :]).to(cos.dtype)
|
||||
rotated, passthrough = tl.split(
|
||||
tl.permute(tl.reshape(y, (ROWS, 2, HALF)), (0, 2, 1))
|
||||
)
|
||||
r0, r1 = tl.split(tl.permute(tl.reshape(rotated, (ROWS, 2, QUARTER)), (0, 2, 1)))
|
||||
out0 = r0 * cos - r1 * sin
|
||||
out1 = r1 * cos + r0 * sin
|
||||
rotated = tl.reshape(tl.permute(tl.join(out0, out1), (0, 2, 1)), (ROWS, HALF))
|
||||
result = tl.reshape(tl.permute(tl.join(rotated, passthrough), (0, 2, 1)), (ROWS, D))
|
||||
return tl.reshape(result, (TILE_T, TILE_H, D))
|
||||
|
||||
|
||||
@triton.jit(
|
||||
do_not_specialize=[
|
||||
"num_tokens",
|
||||
"num_state_blocks",
|
||||
"num_compressed_blocks",
|
||||
"num_k_work",
|
||||
]
|
||||
)
|
||||
def _qsa_pre_indexer_kernel(
|
||||
q_ptr,
|
||||
q_stride_token,
|
||||
k_ptr,
|
||||
k_stride_token,
|
||||
pos_ptr,
|
||||
pos_stride_axis,
|
||||
pos_stride_token,
|
||||
cos_sin_ptr,
|
||||
q_norm_weight_ptr,
|
||||
k_norm_weight_ptr,
|
||||
eps,
|
||||
q_out_ptr,
|
||||
q_out_stride_token,
|
||||
q_out_stride_head,
|
||||
state_cache_ptr,
|
||||
state_cache_stride_block,
|
||||
state_cache_stride_token,
|
||||
state_slots_ptr,
|
||||
state_table_ptr,
|
||||
state_table_stride_req,
|
||||
query_start_loc_ptr,
|
||||
logical_positions_ptr,
|
||||
compressed_slots_ptr,
|
||||
k_work_metadata_ptr,
|
||||
compressed_cache_ptr,
|
||||
compressed_cache_stride_block,
|
||||
compressed_cache_stride_token,
|
||||
num_tokens,
|
||||
num_state_blocks,
|
||||
num_compressed_blocks,
|
||||
num_k_work,
|
||||
HQ: tl.constexpr,
|
||||
D: tl.constexpr,
|
||||
TILE_T_Q: tl.constexpr,
|
||||
TILE_H_Q: tl.constexpr,
|
||||
COMPRESS_RATIO: tl.constexpr,
|
||||
STATE_SIZE: tl.constexpr,
|
||||
COMP_PAGE_SIZE: tl.constexpr,
|
||||
IS_2D_POSITIONS: tl.constexpr,
|
||||
IS_K_MROPE: tl.constexpr,
|
||||
CACHE_HAS_ROPE_POS: tl.constexpr,
|
||||
MROPE_H: tl.constexpr,
|
||||
MROPE_W: tl.constexpr,
|
||||
):
|
||||
pid = tl.program_id(0)
|
||||
# K work occupies the first programs; the remaining programs tile Q. This
|
||||
# keeps both paths in one launch while leaving their register shapes
|
||||
# independent.
|
||||
if pid >= num_k_work:
|
||||
q_pid = pid - num_k_work
|
||||
num_head_tiles: tl.constexpr = tl.cdiv(HQ, TILE_H_Q)
|
||||
token_tile = q_pid // num_head_tiles
|
||||
head_tile = q_pid % num_head_tiles
|
||||
tokens = token_tile * TILE_T_Q + tl.arange(0, TILE_T_Q)
|
||||
heads = head_tile * TILE_H_Q + tl.arange(0, TILE_H_Q)
|
||||
valid_tokens = tokens < num_tokens
|
||||
valid_heads = heads < HQ
|
||||
dims = tl.arange(0, D)
|
||||
mask = valid_tokens[:, None, None] & valid_heads[None, :, None]
|
||||
x = tl.load(
|
||||
q_ptr
|
||||
+ tokens[:, None, None] * q_stride_token
|
||||
+ heads[None, :, None] * D
|
||||
+ dims[None, None, :],
|
||||
mask=mask,
|
||||
other=0.0,
|
||||
)
|
||||
pos_t = tl.load(pos_ptr + tokens * pos_stride_token, mask=valid_tokens, other=0)
|
||||
if IS_2D_POSITIONS:
|
||||
pos_h = tl.load(
|
||||
pos_ptr + pos_stride_axis + tokens * pos_stride_token,
|
||||
mask=valid_tokens,
|
||||
other=0,
|
||||
)
|
||||
pos_w = tl.load(
|
||||
pos_ptr + 2 * pos_stride_axis + tokens * pos_stride_token,
|
||||
mask=valid_tokens,
|
||||
other=0,
|
||||
)
|
||||
else:
|
||||
pos_h = pos_t
|
||||
pos_w = pos_t
|
||||
y = _norm_rope(
|
||||
x,
|
||||
pos_t,
|
||||
pos_h,
|
||||
pos_w,
|
||||
cos_sin_ptr,
|
||||
D // 2,
|
||||
q_norm_weight_ptr,
|
||||
eps,
|
||||
IS_2D_POSITIONS,
|
||||
MROPE_H,
|
||||
MROPE_W,
|
||||
)
|
||||
tl.store(
|
||||
q_out_ptr
|
||||
+ tokens[:, None, None] * q_out_stride_token
|
||||
+ heads[None, :, None] * q_out_stride_head
|
||||
+ dims[None, None, :],
|
||||
y,
|
||||
mask=mask,
|
||||
)
|
||||
|
||||
if pid < num_k_work:
|
||||
# One work item owns one completed compression group. Work item zero
|
||||
# additionally commits the request's current raw-K suffix below.
|
||||
work_metadata = tl.load(k_work_metadata_ptr + pid * 2 + tl.arange(0, 2))
|
||||
request, work_in_request = tl.split(work_metadata)
|
||||
if request < 0:
|
||||
return
|
||||
|
||||
query_start = tl.load(query_start_loc_ptr + request)
|
||||
query_end = tl.load(query_start_loc_ptr + request + 1)
|
||||
query_len = query_end - query_start
|
||||
chunk_end = tl.load(logical_positions_ptr + query_end - 1)
|
||||
chunk_start = chunk_end - query_len + 1
|
||||
num_groups = (chunk_end + 1) // COMPRESS_RATIO - chunk_start // COMPRESS_RATIO
|
||||
dims = tl.arange(0, D)
|
||||
|
||||
if work_in_request < num_groups:
|
||||
first_boundary = (
|
||||
(chunk_start + COMPRESS_RATIO) // COMPRESS_RATIO
|
||||
) * COMPRESS_RATIO - 1
|
||||
end_position = first_boundary + work_in_request * COMPRESS_RATIO
|
||||
boundary_token = query_start + end_position - chunk_start
|
||||
valid_token = (
|
||||
(boundary_token >= query_start)
|
||||
& (boundary_token < query_end)
|
||||
& (boundary_token < num_tokens)
|
||||
)
|
||||
compressed_slot = tl.load(
|
||||
compressed_slots_ptr + boundary_token,
|
||||
mask=valid_token,
|
||||
other=-1,
|
||||
)
|
||||
valid = (
|
||||
valid_token
|
||||
& (compressed_slot >= 0)
|
||||
& (compressed_slot < num_compressed_blocks * COMP_PAGE_SIZE)
|
||||
)
|
||||
state_block = tl.load(state_table_ptr + request * state_table_stride_req)
|
||||
state_block_valid = (state_block >= 0) & (state_block < num_state_blocks)
|
||||
safe_state_block = tl.maximum(state_block, 0).to(tl.int64)
|
||||
group_offsets = tl.arange(0, COMPRESS_RATIO)
|
||||
source_positions = end_position - (COMPRESS_RATIO - 1) + group_offsets
|
||||
source_in_chunk = source_positions >= chunk_start
|
||||
source_tokens = query_start + source_positions - chunk_start
|
||||
source_tokens_valid = (
|
||||
(source_tokens >= query_start)
|
||||
& (source_tokens < query_end)
|
||||
& (source_tokens < num_tokens)
|
||||
)
|
||||
current_base = (
|
||||
k_ptr + tl.maximum(source_tokens, 0)[:, None] * k_stride_token
|
||||
)
|
||||
cached_base = (
|
||||
state_cache_ptr
|
||||
+ safe_state_block * state_cache_stride_block
|
||||
+ (source_positions % STATE_SIZE)[:, None] * state_cache_stride_token
|
||||
)
|
||||
# Only the first completed group can cross the chunk boundary. Select
|
||||
# historical rows from the ring without issuing two masked loads.
|
||||
source_base = tl.where(source_in_chunk[:, None], current_base, cached_base)
|
||||
# Pointer selection obscures alignment from Triton's analysis.
|
||||
source_base = tl.multiple_of(source_base, (8, 8))
|
||||
source_valid = tl.where(
|
||||
source_in_chunk, source_tokens_valid, state_block_valid
|
||||
)
|
||||
source = tl.load(
|
||||
source_base + dims[None, :],
|
||||
mask=valid & source_valid[:, None],
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
# Match the unfused path's BF16 pooled tensor before RMSNorm.
|
||||
pooled = (
|
||||
(tl.sum(source, axis=0) / COMPRESS_RATIO).to(tl.bfloat16).to(tl.float32)
|
||||
)
|
||||
|
||||
first_position = end_position - (COMPRESS_RATIO - 1)
|
||||
if CACHE_HAS_ROPE_POS:
|
||||
# RoPE uses the first token in the pooled group. Its exact MRoPE
|
||||
# coordinates may live in this chunk or the raw-state ring.
|
||||
first_in_chunk = first_position >= chunk_start
|
||||
first_token = query_start + first_position - chunk_start
|
||||
first_token_valid = (
|
||||
(first_token >= query_start)
|
||||
& (first_token < query_end)
|
||||
& (first_token < num_tokens)
|
||||
)
|
||||
safe_first_token = tl.maximum(first_token, 0)
|
||||
load_current_position = first_in_chunk & first_token_valid
|
||||
first_pos_t = tl.load(
|
||||
pos_ptr + safe_first_token * pos_stride_token,
|
||||
mask=load_current_position,
|
||||
other=0,
|
||||
)
|
||||
if IS_2D_POSITIONS:
|
||||
first_pos_h = tl.load(
|
||||
pos_ptr + pos_stride_axis + safe_first_token * pos_stride_token,
|
||||
mask=load_current_position,
|
||||
other=0,
|
||||
)
|
||||
first_pos_w = tl.load(
|
||||
pos_ptr
|
||||
+ 2 * pos_stride_axis
|
||||
+ safe_first_token * pos_stride_token,
|
||||
mask=load_current_position,
|
||||
other=0,
|
||||
)
|
||||
else:
|
||||
first_pos_h = first_pos_t
|
||||
first_pos_w = first_pos_t
|
||||
tail = (
|
||||
state_cache_ptr
|
||||
+ safe_state_block * state_cache_stride_block
|
||||
+ (first_position % STATE_SIZE) * state_cache_stride_token
|
||||
+ D
|
||||
).to(tl.pointer_type(tl.int64))
|
||||
load_cached_position = ~first_in_chunk & state_block_valid
|
||||
cached_pos_t = tl.load(tail, mask=load_cached_position, other=0)
|
||||
cached_pos_h = tl.load(tail + 1, mask=load_cached_position, other=0)
|
||||
cached_pos_w = tl.load(tail + 2, mask=load_cached_position, other=0)
|
||||
pos_t = tl.where(first_in_chunk, first_pos_t.to(tl.int64), cached_pos_t)
|
||||
pos_h = tl.where(first_in_chunk, first_pos_h.to(tl.int64), cached_pos_h)
|
||||
pos_w = tl.where(first_in_chunk, first_pos_w.to(tl.int64), cached_pos_w)
|
||||
else:
|
||||
pos_t = first_position
|
||||
pos_h = first_position
|
||||
pos_w = first_position
|
||||
y = _norm_rope(
|
||||
tl.reshape(pooled, (1, 1, D)),
|
||||
pos_t + tl.arange(0, 1),
|
||||
pos_h + tl.arange(0, 1),
|
||||
pos_w + tl.arange(0, 1),
|
||||
cos_sin_ptr,
|
||||
D // 2,
|
||||
k_norm_weight_ptr,
|
||||
eps,
|
||||
IS_K_MROPE,
|
||||
MROPE_H,
|
||||
MROPE_W,
|
||||
)
|
||||
compressed_block = (compressed_slot // COMP_PAGE_SIZE).to(tl.int64)
|
||||
compressed_row = compressed_slot % COMP_PAGE_SIZE
|
||||
tl.store(
|
||||
compressed_cache_ptr
|
||||
+ compressed_block * compressed_cache_stride_block
|
||||
+ compressed_row * compressed_cache_stride_token
|
||||
+ dims,
|
||||
tl.reshape(y, (D,)),
|
||||
mask=valid,
|
||||
)
|
||||
|
||||
if work_in_request == 0:
|
||||
# This CTA may have just read historical rows from the circular buffer.
|
||||
# Keep every lane past those loads before overwriting the same ring.
|
||||
tl.debug_barrier()
|
||||
# One CTA per request commits only the suffix retained by the ring.
|
||||
num_state_rows = tl.minimum(query_len, STATE_SIZE)
|
||||
for state_offset in tl.range(0, num_state_rows):
|
||||
token = query_end - num_state_rows + state_offset
|
||||
valid_token = (
|
||||
(token >= query_start) & (token < query_end) & (token < num_tokens)
|
||||
)
|
||||
slot = tl.load(state_slots_ptr + token, mask=valid_token, other=-1)
|
||||
valid_slot = (
|
||||
valid_token & (slot >= 0) & (slot < num_state_blocks * STATE_SIZE)
|
||||
)
|
||||
safe_slot = tl.maximum(slot, 0)
|
||||
state_row = (
|
||||
state_cache_ptr
|
||||
+ (safe_slot // STATE_SIZE).to(tl.int64) * state_cache_stride_block
|
||||
+ (safe_slot % STATE_SIZE) * state_cache_stride_token
|
||||
)
|
||||
k = tl.load(
|
||||
k_ptr + tl.maximum(token, 0) * k_stride_token + dims,
|
||||
mask=valid_slot,
|
||||
other=0.0,
|
||||
)
|
||||
tl.store(state_row + dims, k, mask=valid_slot)
|
||||
if CACHE_HAS_ROPE_POS:
|
||||
pos_t = tl.load(
|
||||
pos_ptr + tl.maximum(token, 0) * pos_stride_token,
|
||||
mask=valid_slot,
|
||||
other=0,
|
||||
)
|
||||
if IS_2D_POSITIONS:
|
||||
pos_h = tl.load(
|
||||
pos_ptr
|
||||
+ pos_stride_axis
|
||||
+ tl.maximum(token, 0) * pos_stride_token,
|
||||
mask=valid_slot,
|
||||
other=0,
|
||||
)
|
||||
pos_w = tl.load(
|
||||
pos_ptr
|
||||
+ 2 * pos_stride_axis
|
||||
+ tl.maximum(token, 0) * pos_stride_token,
|
||||
mask=valid_slot,
|
||||
other=0,
|
||||
)
|
||||
else:
|
||||
pos_h = pos_t
|
||||
pos_w = pos_t
|
||||
tail = (state_row + D).to(tl.pointer_type(tl.int64))
|
||||
tl.store(tail, pos_t.to(tl.int64), mask=valid_slot)
|
||||
tl.store(tail + 1, pos_h.to(tl.int64), mask=valid_slot)
|
||||
tl.store(tail + 2, pos_w.to(tl.int64), mask=valid_slot)
|
||||
|
||||
|
||||
def qsa_pre_indexer(
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
cos_sin_cache: torch.Tensor,
|
||||
q_norm_weight: torch.Tensor,
|
||||
k_norm_weight: torch.Tensor,
|
||||
eps: float,
|
||||
q_out: torch.Tensor,
|
||||
state_cache: torch.Tensor,
|
||||
state_slots: torch.Tensor,
|
||||
state_block_table: torch.Tensor,
|
||||
query_start_loc: torch.Tensor,
|
||||
logical_positions: torch.Tensor,
|
||||
compressed_cache: torch.Tensor,
|
||||
compressed_slots: torch.Tensor,
|
||||
k_work_metadata: torch.Tensor,
|
||||
*,
|
||||
compress_ratio: int,
|
||||
mrope_section: tuple[int, int, int] | None,
|
||||
rope_pos_offset: int | None,
|
||||
) -> None:
|
||||
"""Normalize Q, compress K, then update the circular raw state."""
|
||||
num_tokens = q.shape[0]
|
||||
if num_tokens == 0:
|
||||
return
|
||||
num_q_heads, head_dim = q_out.shape[1:]
|
||||
assert cos_sin_cache.shape[-1] * 2 == head_dim
|
||||
assert q.shape == (num_tokens, num_q_heads * head_dim)
|
||||
assert k.shape == (num_tokens, head_dim)
|
||||
assert q.stride(-1) == 1
|
||||
assert k.stride(-1) == 1
|
||||
assert q_out.stride(-1) == 1
|
||||
assert cos_sin_cache.is_contiguous()
|
||||
assert state_cache.stride(-1) == 1
|
||||
assert compressed_cache.stride(-1) == 1
|
||||
assert k_work_metadata.ndim == 2 and k_work_metadata.shape[1] == 2
|
||||
is_2d_positions = positions.ndim == 2
|
||||
is_k_mrope = bool(mrope_section)
|
||||
cache_has_rope_pos = rope_pos_offset is not None
|
||||
assert rope_pos_offset is None or rope_pos_offset == head_dim
|
||||
if is_2d_positions:
|
||||
assert positions.shape == (3, num_tokens)
|
||||
assert is_k_mrope
|
||||
pos_stride_axis, pos_stride_token = positions.stride()
|
||||
else:
|
||||
assert positions.shape == (num_tokens,)
|
||||
pos_stride_axis, pos_stride_token = 0, positions.stride(0)
|
||||
section = mrope_section if mrope_section is not None else (0, 0, 0)
|
||||
assert len(section) == 3
|
||||
|
||||
if num_tokens <= 4096:
|
||||
TILE_T_Q, TILE_H_Q = 2, 2
|
||||
else:
|
||||
TILE_T_Q, TILE_H_Q = 2, 4
|
||||
num_k_work = k_work_metadata.shape[0]
|
||||
num_q_work = triton.cdiv(num_tokens, TILE_T_Q) * triton.cdiv(num_q_heads, TILE_H_Q)
|
||||
_qsa_pre_indexer_kernel[(num_k_work + num_q_work,)](
|
||||
q,
|
||||
q.stride(0),
|
||||
k,
|
||||
k.stride(0),
|
||||
positions,
|
||||
pos_stride_axis,
|
||||
pos_stride_token,
|
||||
cos_sin_cache,
|
||||
q_norm_weight,
|
||||
k_norm_weight,
|
||||
eps,
|
||||
q_out,
|
||||
q_out.stride(0),
|
||||
q_out.stride(1),
|
||||
state_cache,
|
||||
state_cache.stride(0),
|
||||
state_cache.stride(1),
|
||||
state_slots,
|
||||
state_block_table,
|
||||
state_block_table.stride(0),
|
||||
query_start_loc,
|
||||
logical_positions,
|
||||
compressed_slots,
|
||||
k_work_metadata,
|
||||
compressed_cache,
|
||||
compressed_cache.stride(0),
|
||||
compressed_cache.stride(1),
|
||||
num_tokens,
|
||||
state_cache.shape[0],
|
||||
compressed_cache.shape[0],
|
||||
num_k_work,
|
||||
HQ=num_q_heads,
|
||||
D=head_dim,
|
||||
TILE_T_Q=TILE_T_Q,
|
||||
TILE_H_Q=TILE_H_Q,
|
||||
COMPRESS_RATIO=compress_ratio,
|
||||
STATE_SIZE=state_cache.shape[1],
|
||||
COMP_PAGE_SIZE=compressed_cache.shape[1],
|
||||
IS_2D_POSITIONS=is_2d_positions,
|
||||
IS_K_MROPE=is_k_mrope,
|
||||
CACHE_HAS_ROPE_POS=cache_has_rope_pos,
|
||||
MROPE_H=section[1],
|
||||
MROPE_W=section[2],
|
||||
num_warps=1,
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["qsa_pre_indexer"]
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,487 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""NVIDIA QSA owner with Triton kernels."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import ClassVar, cast
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.config.cache import CacheDType
|
||||
from vllm.distributed import get_tensor_model_parallel_world_size
|
||||
from vllm.forward_context import get_forward_context
|
||||
from vllm.model_executor.layers.attention.attention import (
|
||||
set_default_quant_scales,
|
||||
)
|
||||
from vllm.model_executor.layers.attention_layer_base import AttentionLayerBase
|
||||
from vllm.model_executor.layers.layernorm import GemmaRMSNorm
|
||||
from vllm.model_executor.layers.linear import QKVParallelLinear, RowParallelLinear
|
||||
from vllm.model_executor.layers.quantization import QuantizationConfig
|
||||
from vllm.model_executor.layers.rotary_embedding import MRotaryEmbedding, get_rope
|
||||
from vllm.model_executor.models.qwen3_next import Qwen3NextAttention
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.transformers_utils.configs.qwen4_exp import (
|
||||
Qwen4ExpTextConfig,
|
||||
)
|
||||
from vllm.utils.torch_utils import (
|
||||
LayerNameType,
|
||||
_encode_layer_name,
|
||||
_resolve_layer_name,
|
||||
canonicalize_singleton_dim_strides,
|
||||
direct_register_custom_op,
|
||||
kv_cache_dtype_str_to_dtype,
|
||||
)
|
||||
from vllm.v1.attention.backend import (
|
||||
AttentionBackend,
|
||||
AttentionCGSupport,
|
||||
AttentionType,
|
||||
MultipleOf,
|
||||
)
|
||||
from vllm.v1.attention.backends.fa_utils import is_flash_attn_varlen_func_available
|
||||
from vllm.v1.attention.backends.flash_attn import (
|
||||
FlashAttentionBackend,
|
||||
FlashAttentionImpl,
|
||||
FlashAttentionMetadata,
|
||||
FlashAttentionMetadataBuilder,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
FullAttentionSpec,
|
||||
KVCacheSpec,
|
||||
get_kv_quant_mode,
|
||||
)
|
||||
|
||||
from ..common.qsa_cache import QSAForwardMetadata
|
||||
from . import model
|
||||
from .indexer_qsa import QSAIndexer
|
||||
|
||||
|
||||
class Qwen4ExpQSAMetadataBuilder(FlashAttentionMetadataBuilder):
|
||||
"""Flash metadata supporting uniform decode and target-verify graphs."""
|
||||
|
||||
_cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.UNIFORM_BATCH
|
||||
|
||||
|
||||
class Qwen4ExpQSAFlashAttentionBackend(FlashAttentionBackend):
|
||||
"""FullAttentionSpec backend used by the merged QSA owner."""
|
||||
|
||||
supported_dtypes: ClassVar[list[torch.dtype]] = [torch.bfloat16]
|
||||
supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = ["auto", "bfloat16"]
|
||||
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
return "QWEN4_EXP_QSA_TRITON"
|
||||
|
||||
@staticmethod
|
||||
def get_supported_kernel_block_sizes() -> list[int | MultipleOf]:
|
||||
# QSA consumes manager pages directly and does not use FA4 paged attention.
|
||||
return [MultipleOf(16)]
|
||||
|
||||
@staticmethod
|
||||
def get_impl_cls() -> type[Qwen4ExpQSAFlashAttentionImpl]:
|
||||
return Qwen4ExpQSAFlashAttentionImpl
|
||||
|
||||
@staticmethod
|
||||
def get_builder_cls() -> type[Qwen4ExpQSAMetadataBuilder]:
|
||||
return Qwen4ExpQSAMetadataBuilder
|
||||
|
||||
@classmethod
|
||||
def is_sparse(cls) -> bool:
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def supports_kv_connector(cls) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
class Qwen4ExpQSAFlashAttentionImpl(FlashAttentionImpl):
|
||||
"""Run paged sparse GQA with the QSA Triton kernel."""
|
||||
|
||||
supports_dcp: bool = False
|
||||
supports_pcp: bool = False
|
||||
|
||||
def __init__(self, *args, **kwargs) -> None:
|
||||
super().__init__(*args, **kwargs)
|
||||
if not is_flash_attn_varlen_func_available():
|
||||
raise NotImplementedError("Qwen4Exp QSA requires FlashAttention")
|
||||
if self.dcp_world_size != 1:
|
||||
raise NotImplementedError(
|
||||
"Qwen4Exp QSA does not support decode context parallelism"
|
||||
)
|
||||
if self.kv_cache_dtype not in ("auto", "bfloat16"):
|
||||
raise NotImplementedError("Qwen4Exp QSA requires a BF16 main KV cache")
|
||||
self.supports_quant_query_input = False
|
||||
|
||||
def forward_qsa(
|
||||
self,
|
||||
layer: torch.nn.Module,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
kv_cache: torch.Tensor,
|
||||
attn_metadata: FlashAttentionMetadata,
|
||||
output: torch.Tensor,
|
||||
token_to_req: torch.Tensor,
|
||||
output_scale: torch.Tensor | None = None,
|
||||
output_block_scale: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
del key, value
|
||||
if output_scale is not None or output_block_scale is not None:
|
||||
raise NotImplementedError("QSA does not support fused output quantization")
|
||||
if self.alibi_slopes is not None or self.sinks is not None:
|
||||
raise NotImplementedError("QSA does not support ALiBi or attention sinks")
|
||||
if self.sliding_window != (-1, -1):
|
||||
raise NotImplementedError("QSA does not support sliding-window attention")
|
||||
|
||||
num_tokens = attn_metadata.num_actual_tokens
|
||||
output.zero_()
|
||||
if num_tokens == 0:
|
||||
return output
|
||||
|
||||
topk_buffer = getattr(layer, "topk_indices_buffer", None)
|
||||
if topk_buffer is None:
|
||||
raise RuntimeError("QSA owner did not provide its top-k buffer")
|
||||
logical_indices = topk_buffer[:num_tokens]
|
||||
token_to_req = token_to_req[:num_tokens]
|
||||
key_cache, value_cache = kv_cache.transpose(1, 2).split(self.head_size, dim=-1)
|
||||
key_cache = canonicalize_singleton_dim_strides(key_cache)
|
||||
value_cache = canonicalize_singleton_dim_strides(value_cache)
|
||||
if key_cache.dtype != torch.bfloat16 or query.dtype != torch.bfloat16:
|
||||
raise NotImplementedError("Qwen4Exp QSA requires BF16 Q/K/V")
|
||||
|
||||
from .ops.qsa import qsa_sparse_paged_attention
|
||||
|
||||
qsa_sparse_paged_attention(
|
||||
query[:num_tokens],
|
||||
key_cache,
|
||||
value_cache,
|
||||
logical_indices,
|
||||
attn_metadata.block_table,
|
||||
token_to_req,
|
||||
output[:num_tokens],
|
||||
)
|
||||
return output
|
||||
|
||||
|
||||
class Qwen4ExpQSAAttention(Qwen3NextAttention, AttentionLayerBase):
|
||||
"""Merged Qwen full-attention owner with a QSA index side branch."""
|
||||
|
||||
supports_dcp = False
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
vllm_config: VllmConfig,
|
||||
config: Qwen4ExpTextConfig,
|
||||
layer_id: int,
|
||||
quant_config: QuantizationConfig | None = None,
|
||||
reduce_results: bool = True,
|
||||
prefix: str = "",
|
||||
) -> None:
|
||||
nn.Module.__init__(self)
|
||||
cache_config = vllm_config.cache_config
|
||||
model_config = vllm_config.model_config
|
||||
if cache_config is None:
|
||||
raise ValueError("Qwen4Exp QSA requires a paged KV cache")
|
||||
if model_config.dtype != torch.bfloat16:
|
||||
raise NotImplementedError("Qwen4Exp QSA currently requires BF16")
|
||||
if cache_config.cache_dtype not in ("auto", "bfloat16"):
|
||||
raise NotImplementedError("Qwen4Exp QSA requires a BF16 main KV cache")
|
||||
if getattr(quant_config, "kv_cache_scheme", None) is not None:
|
||||
raise NotImplementedError("Qwen4Exp QSA does not support KV quantization")
|
||||
parallel_config = vllm_config.parallel_config
|
||||
if (
|
||||
parallel_config.prefill_context_parallel_size > 1
|
||||
or parallel_config.decode_context_parallel_size > 1
|
||||
):
|
||||
raise NotImplementedError(
|
||||
"Qwen4Exp QSA does not support context parallelism"
|
||||
)
|
||||
if not getattr(config, "is_causal", True):
|
||||
raise NotImplementedError("Qwen4Exp QSA requires causal decoder attention")
|
||||
|
||||
self.config = config
|
||||
self.hidden_size = int(config.hidden_size)
|
||||
tp_size = get_tensor_model_parallel_world_size()
|
||||
self.total_num_heads = int(config.num_attention_heads)
|
||||
if self.total_num_heads % tp_size:
|
||||
raise ValueError("QSA attention heads must be divisible by TP size")
|
||||
self.num_heads = self.total_num_heads // tp_size
|
||||
self.total_num_kv_heads = int(config.num_key_value_heads)
|
||||
if self.total_num_kv_heads >= tp_size:
|
||||
if self.total_num_kv_heads % tp_size:
|
||||
raise ValueError("QSA KV heads must be divisible by TP size")
|
||||
elif tp_size % self.total_num_kv_heads:
|
||||
raise ValueError("TP size must be divisible by replicated QSA KV heads")
|
||||
self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size)
|
||||
self.head_dim = int(config.head_dim or self.hidden_size // self.num_heads)
|
||||
self.q_size = self.num_heads * self.head_dim
|
||||
self.kv_size = self.num_kv_heads * self.head_dim
|
||||
self.scaling = self.head_dim**-0.5
|
||||
self.dual_chunk_attention_config = getattr(
|
||||
config, "dual_chunk_attention_config", None
|
||||
)
|
||||
if self.dual_chunk_attention_config is not None:
|
||||
raise NotImplementedError("Qwen4Exp QSA does not support dual-chunk RoPE")
|
||||
# Qwen4Exp full-attention checkpoints always pack a sigmoid output
|
||||
# gate next to Q, even when an inherited config default says otherwise.
|
||||
self.attn_output_gate = True
|
||||
|
||||
self.qkv_proj = QKVParallelLinear(
|
||||
self.hidden_size,
|
||||
self.head_dim,
|
||||
self.total_num_heads * (1 + self.attn_output_gate),
|
||||
self.total_num_kv_heads,
|
||||
bias=False,
|
||||
quant_config=model.without_modelopt_fp4(quant_config),
|
||||
prefix=f"{prefix}.qkv_proj",
|
||||
)
|
||||
self.o_proj = RowParallelLinear(
|
||||
self.total_num_heads * self.head_dim,
|
||||
self.hidden_size,
|
||||
bias=False,
|
||||
reduce_results=reduce_results,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.o_proj",
|
||||
)
|
||||
self.rotary_emb = get_rope(
|
||||
head_size=self.head_dim,
|
||||
max_position=config.max_position_embeddings,
|
||||
rope_parameters=config.rope_parameters,
|
||||
)
|
||||
self.q_norm = GemmaRMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
||||
self.k_norm = GemmaRMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
||||
|
||||
mm_config = model_config.multimodal_config
|
||||
text_only = mm_config is None or mm_config.language_model_only
|
||||
mrope_section = getattr(self.rotary_emb, "mrope_section", None)
|
||||
supports_mrope = bool(
|
||||
type(self.rotary_emb) is MRotaryEmbedding
|
||||
and mrope_section
|
||||
and len(mrope_section) == 3
|
||||
and sum(mrope_section) == self.rotary_emb.rotary_dim // 2
|
||||
and getattr(self.rotary_emb, "mrope_interleaved", False)
|
||||
)
|
||||
supports_dtype = getattr(self.rotary_emb, "dtype", None) in (
|
||||
torch.float16,
|
||||
torch.bfloat16,
|
||||
)
|
||||
self.use_fused_qk_norm_rope_gate = (
|
||||
self.attn_output_gate
|
||||
and getattr(self.rotary_emb, "is_neox_style", False)
|
||||
and current_platform.is_cuda()
|
||||
and supports_dtype
|
||||
and (text_only or supports_mrope)
|
||||
)
|
||||
|
||||
self.layer_name = f"{prefix}.attn"
|
||||
self.attn_type = AttentionType.DECODER
|
||||
self.kv_cache_dtype = cache_config.cache_dtype
|
||||
self.kv_cache_torch_dtype = kv_cache_dtype_str_to_dtype(
|
||||
self.kv_cache_dtype, model_config
|
||||
)
|
||||
if self.kv_cache_torch_dtype != torch.bfloat16:
|
||||
raise NotImplementedError("Qwen4Exp QSA requires BF16 cache storage")
|
||||
self.kv_sharing_target_layer_name = None
|
||||
self.kv_cache = torch.tensor([])
|
||||
set_default_quant_scales(self, register_buffer=True)
|
||||
|
||||
self.attn_backend = Qwen4ExpQSAFlashAttentionBackend
|
||||
self.impl = Qwen4ExpQSAFlashAttentionImpl(
|
||||
self.num_heads,
|
||||
self.head_dim,
|
||||
self.scaling,
|
||||
self.num_kv_heads,
|
||||
None,
|
||||
None,
|
||||
self.kv_cache_dtype,
|
||||
None,
|
||||
AttentionType.DECODER,
|
||||
None,
|
||||
)
|
||||
self.indexer = QSAIndexer(
|
||||
vllm_config=vllm_config,
|
||||
config=config,
|
||||
layer_id=layer_id,
|
||||
rotary_emb=self.rotary_emb,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.indexer",
|
||||
)
|
||||
max_tokens = vllm_config.scheduler_config.max_num_batched_tokens
|
||||
self.register_buffer(
|
||||
"topk_indices_buffer",
|
||||
torch.empty(
|
||||
max_tokens,
|
||||
self.indexer.output_width,
|
||||
dtype=torch.int32,
|
||||
),
|
||||
persistent=False,
|
||||
)
|
||||
|
||||
static_context = vllm_config.compilation_config.static_forward_context
|
||||
if self.layer_name in static_context:
|
||||
raise ValueError(f"Duplicate layer name: {self.layer_name}")
|
||||
static_context[self.layer_name] = self
|
||||
|
||||
def get_attn_backend(self) -> type[AttentionBackend]:
|
||||
return self.attn_backend
|
||||
|
||||
def get_kv_cache_spec(self, vllm_config: VllmConfig) -> KVCacheSpec:
|
||||
return FullAttentionSpec(
|
||||
block_size=vllm_config.cache_config.block_size,
|
||||
num_kv_heads=self.num_kv_heads,
|
||||
head_size=self.head_dim,
|
||||
head_size_v=self.head_dim,
|
||||
dtype=self.kv_cache_torch_dtype,
|
||||
kv_quant_mode=get_kv_quant_mode(self.kv_cache_dtype),
|
||||
)
|
||||
|
||||
def _run_qsa(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
output: torch.Tensor,
|
||||
) -> None:
|
||||
metadata = get_forward_context().attn_metadata
|
||||
if isinstance(metadata, list):
|
||||
metadata = metadata[0]
|
||||
if not isinstance(metadata, dict):
|
||||
output.zero_()
|
||||
return
|
||||
main_metadata = cast(FlashAttentionMetadata, metadata[self.layer_name])
|
||||
if self.kv_cache.numel() == 0:
|
||||
raise RuntimeError("QSA main K/V cache is not bound")
|
||||
|
||||
num_tokens = main_metadata.num_actual_tokens
|
||||
side_metadata = cast(
|
||||
QSAForwardMetadata,
|
||||
metadata[self.indexer.raw_key_cache.prefix],
|
||||
)
|
||||
if side_metadata.num_actual_tokens != num_tokens:
|
||||
raise RuntimeError("QSA main and side metadata token counts disagree")
|
||||
selected = self.indexer(
|
||||
hidden_states,
|
||||
positions,
|
||||
self.topk_indices_buffer[:num_tokens],
|
||||
)
|
||||
if selected.shape != (
|
||||
num_tokens,
|
||||
self.indexer.output_width,
|
||||
):
|
||||
raise RuntimeError("QSA indexer returned an invalid selection shape")
|
||||
impl = cast(Qwen4ExpQSAFlashAttentionImpl, self.impl)
|
||||
impl.do_kv_cache_update(
|
||||
self,
|
||||
key,
|
||||
value,
|
||||
self.kv_cache,
|
||||
main_metadata.slot_mapping,
|
||||
)
|
||||
impl.forward_qsa(
|
||||
self,
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
self.kv_cache,
|
||||
main_metadata,
|
||||
output,
|
||||
token_to_req=side_metadata.token_to_req,
|
||||
)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
positions: torch.Tensor,
|
||||
hidden_states: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
qkv, _ = self.qkv_proj(hidden_states)
|
||||
q, k, v, gate = self._project_qkv_gate(qkv, positions)
|
||||
num_tokens = hidden_states.shape[0]
|
||||
query = q.view(num_tokens, self.num_heads, self.head_dim)
|
||||
key = k.view(num_tokens, self.num_kv_heads, self.head_dim)
|
||||
value = v.view(num_tokens, self.num_kv_heads, self.head_dim)
|
||||
attn_output = torch.empty_like(query)
|
||||
encoded_layer_name = _encode_layer_name(self.layer_name)
|
||||
if current_platform.opaque_attention_op():
|
||||
torch.ops.vllm.qwen4_exp_qsa_with_output(
|
||||
hidden_states,
|
||||
positions,
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
attn_output,
|
||||
encoded_layer_name,
|
||||
)
|
||||
else:
|
||||
qwen4_exp_qsa_with_output(
|
||||
hidden_states,
|
||||
positions,
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
attn_output,
|
||||
encoded_layer_name,
|
||||
)
|
||||
flat_output = attn_output.view(num_tokens, -1)
|
||||
if gate is not None:
|
||||
flat_output = flat_output * torch.sigmoid(gate)
|
||||
output, _ = self.o_proj(flat_output)
|
||||
return output
|
||||
|
||||
|
||||
def qwen4_exp_qsa_with_output(
|
||||
hidden_states: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
output: torch.Tensor,
|
||||
layer_name: LayerNameType,
|
||||
) -> None:
|
||||
"""Run the complete QSA state/update/attend transaction."""
|
||||
|
||||
layer_name = _resolve_layer_name(layer_name)
|
||||
layer = get_forward_context().no_compile_layers[layer_name]
|
||||
if not isinstance(layer, Qwen4ExpQSAAttention):
|
||||
raise TypeError(f"{layer_name} is not a Qwen4Exp QSA owner")
|
||||
layer._run_qsa(
|
||||
hidden_states,
|
||||
positions,
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
output,
|
||||
)
|
||||
|
||||
|
||||
def qwen4_exp_qsa_with_output_fake(
|
||||
hidden_states: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
output: torch.Tensor,
|
||||
layer_name: LayerNameType,
|
||||
) -> None:
|
||||
del hidden_states, positions, query, key, value, output, layer_name
|
||||
|
||||
|
||||
direct_register_custom_op(
|
||||
op_name="qwen4_exp_qsa_with_output",
|
||||
op_func=qwen4_exp_qsa_with_output,
|
||||
mutates_args=["output"],
|
||||
fake_impl=qwen4_exp_qsa_with_output_fake,
|
||||
)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"QSAIndexer",
|
||||
"Qwen4ExpQSAAttention",
|
||||
"Qwen4ExpQSAFlashAttentionBackend",
|
||||
"Qwen4ExpQSAFlashAttentionImpl",
|
||||
"qwen4_exp_qsa_with_output",
|
||||
]
|
||||
Reference in New Issue
Block a user