Merge remote-tracking branch 'origin/main' into sync/lesj/qwen4exp-bugfixes
Signed-off-by: lesj0610 <lesj0610@users.noreply.github.com>
This commit is contained in:
@@ -0,0 +1,469 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""DeepGEMM sparse MQA-logits path for the DeepSeek V4.1 two-level indexer.
|
||||
|
||||
The candidate-source indexer publishes the top candidate blocks (in units of
|
||||
``candidate_block_size`` compressed positions). Instead of scoring every KV
|
||||
position and masking the dense logits down to those blocks, this path scores
|
||||
only the candidate tokens with DeepGEMM's sparse MQA logits kernels
|
||||
(``fp8_fp4_(paged_)sparse_mqa_logits``, DeepGEMM >= 2.8, SM100 only), runs
|
||||
DeepSelect's top-k directly on the bf16 logits they produce, and remaps the
|
||||
selected columns back to request-local positions.
|
||||
|
||||
Only the MXFP4 indexer cache is supported: the kernels require UE8M0-packed
|
||||
(granularity-32) Q/KV scales, which is exactly the MXFP4 cache layout. The
|
||||
FP8 indexer cache stores one fp32 scale per quant block instead.
|
||||
|
||||
The functions here take caller-owned output buffers (``sparse_indices``,
|
||||
``end``, ``col_indices``) so the hot path allocates nothing; the indexer
|
||||
metadata builder owns them.
|
||||
"""
|
||||
|
||||
import importlib.util
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.model_executor.layers.indexer_topk import (
|
||||
deep_select_topk,
|
||||
get_deep_select_stride_requirement,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import tl, triton
|
||||
from vllm.utils.deep_gemm import (
|
||||
fp8_fp4_paged_sparse_mqa_logits,
|
||||
fp8_fp4_sparse_mqa_logits,
|
||||
get_paged_sparse_mqa_logits_metadata,
|
||||
get_sparse_mqa_logits_metadata,
|
||||
)
|
||||
|
||||
# Sparse-block sizes (in tokens) supported by the DeepGEMM kernels.
|
||||
SPARSE_BLOCK_KV_CHOICES = (16, 8)
|
||||
|
||||
|
||||
def has_deep_select() -> bool:
|
||||
"""Whether the DeepSelect top-k extension is built and this GPU runs it."""
|
||||
return (
|
||||
importlib.util.find_spec("vllm._deepselect_C") is not None
|
||||
and current_platform.is_cuda()
|
||||
and current_platform.is_device_capability_family(100)
|
||||
)
|
||||
|
||||
|
||||
def check_deep_select_layout(num_sparse_cols: int, topk_tokens: int) -> None:
|
||||
"""Raise unless DeepSelect accepts the sparse logits layout.
|
||||
|
||||
The sparse kernels return contiguous bf16 ``[rows, num_sparse_cols]``
|
||||
logits and the top-k writes int32 ``[rows, topk_tokens]`` indices;
|
||||
DeepSelect needs both row strides aligned (1024B / 32B on SM100).
|
||||
"""
|
||||
in_align, out_align = get_deep_select_stride_requirement()
|
||||
logits_row_bytes = num_sparse_cols * torch.bfloat16.itemsize
|
||||
if num_sparse_cols >= 2**23 or logits_row_bytes % in_align != 0:
|
||||
raise ValueError(
|
||||
f"DeepSelect needs the sparse logits row ({num_sparse_cols} bf16 "
|
||||
f"columns, {logits_row_bytes} B) to be {in_align}B-aligned."
|
||||
)
|
||||
if topk_tokens > 4096 or (topk_tokens * torch.int32.itemsize) % out_align != 0:
|
||||
raise ValueError(
|
||||
f"DeepSelect needs topk <= 4096 with a {out_align}B-aligned int32 "
|
||||
f"output row, got topk={topk_tokens}."
|
||||
)
|
||||
|
||||
|
||||
_INT32_BIG = tl.constexpr(2**31 - 1)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _expand_candidates_kernel(
|
||||
cand_ptr,
|
||||
cand_stride,
|
||||
ks_ptr,
|
||||
ks_stride,
|
||||
ke_ptr,
|
||||
ke_stride,
|
||||
si_ptr,
|
||||
si_stride,
|
||||
end_ptr,
|
||||
end_stride,
|
||||
K: tl.constexpr,
|
||||
S: tl.constexpr,
|
||||
RATIO: tl.constexpr,
|
||||
SBK: tl.constexpr,
|
||||
):
|
||||
"""One program per row: expand + filter + sort candidate blocks.
|
||||
|
||||
Each row's valid sparse blocks come out sorted ascending (no dedup pass:
|
||||
production candidates are unique, and the kernel tolerates repeats),
|
||||
padded by repeating the last valid block — DeepGEMM's padding convention.
|
||||
``end`` counts valid sparse-token columns; valid columns form a prefix
|
||||
because block ids are sorted.
|
||||
"""
|
||||
row = tl.program_id(0)
|
||||
ks = tl.load(ks_ptr + row * ks_stride)
|
||||
ke = tl.load(ke_ptr + row * ke_stride)
|
||||
cols = tl.arange(0, K)
|
||||
cand = tl.load(cand_ptr + row * cand_stride + cols) # K is pow2, no mask
|
||||
if RATIO == 2:
|
||||
cand = tl.interleave(cand * RATIO, cand * RATIO + 1)
|
||||
|
||||
# Keep only blocks inside the row's KV range [0, ke - ks); the lower
|
||||
# bound is free since candidates are non-negative.
|
||||
kv_len = tl.maximum(ke - ks, 0)
|
||||
max_block = (kv_len + SBK - 1) // SBK
|
||||
valid = (cand >= 0) & (cand < max_block)
|
||||
vals = tl.where(valid, cand, _INT32_BIG)
|
||||
vals = tl.sort(vals)
|
||||
|
||||
# Anchor at the row's ks rounded down to a sparse-block boundary
|
||||
# (identity for the paged path, where ks == 0).
|
||||
base = ks // SBK
|
||||
si = tl.where(vals != _INT32_BIG, vals, 0) + base
|
||||
n_valid = tl.sum(valid.to(tl.int32))
|
||||
last_rel = tl.max(tl.where(valid, cand, -1))
|
||||
pad_val = tl.where(n_valid > 0, last_rel + base, base)
|
||||
tl.store(
|
||||
si_ptr + row * si_stride + tl.arange(0, S),
|
||||
tl.where(tl.arange(0, S) < n_valid, si, pad_val),
|
||||
)
|
||||
|
||||
# Valid sparse-token column count; only the last block can be partial.
|
||||
# Absolute start of the last block: (base + last_rel) * SBK + ks % SBK,
|
||||
# which is exactly last_rel * SBK + ks.
|
||||
last_start = last_rel * SBK + ks
|
||||
fill = tl.minimum(tl.maximum(ke - last_start, 1), SBK)
|
||||
end = tl.where(n_valid > 0, (n_valid - 1) * SBK + fill, 0)
|
||||
tl.store(end_ptr + row * end_stride, end)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _sparse_topk_remap_kernel(
|
||||
col_ptr,
|
||||
col_stride,
|
||||
si_ptr,
|
||||
si_stride,
|
||||
ks_ptr,
|
||||
ks_stride,
|
||||
out_ptr,
|
||||
out_stride,
|
||||
k,
|
||||
SBK: tl.constexpr,
|
||||
K_POW2: tl.constexpr,
|
||||
):
|
||||
"""Remap sparse top-k columns to request-local positions.
|
||||
|
||||
Column ``j * SBK + o`` scores the token at
|
||||
``(si[row, j] - ks // SBK) * SBK + o``; -1 columns stay -1.
|
||||
"""
|
||||
row = tl.program_id(0)
|
||||
ks_base = tl.load(ks_ptr + row * ks_stride) // SBK
|
||||
cols = tl.arange(0, K_POW2)
|
||||
c = tl.load(col_ptr + row * col_stride + cols, mask=cols < k, other=-1)
|
||||
valid = c >= 0
|
||||
cc = tl.where(valid, c, 0)
|
||||
blocks = tl.load(si_ptr + row * si_stride + cc // SBK)
|
||||
pos = (blocks - ks_base) * SBK + cc % SBK
|
||||
tl.store(out_ptr + row * out_stride + cols, tl.where(valid, pos, -1), mask=cols < k)
|
||||
|
||||
|
||||
def pick_sparse_block_kv(candidate_block_size: int) -> int:
|
||||
"""Largest sparse-block size (tokens) dividing the candidate block size."""
|
||||
for sbk in SPARSE_BLOCK_KV_CHOICES:
|
||||
if candidate_block_size % sbk == 0:
|
||||
return sbk
|
||||
raise ValueError(
|
||||
f"candidate_block_size={candidate_block_size} is not a multiple of "
|
||||
f"any supported sparse_block_kv {SPARSE_BLOCK_KV_CHOICES}."
|
||||
)
|
||||
|
||||
|
||||
def candidate_blocks_to_sparse_indices(
|
||||
candidate_blocks: torch.Tensor,
|
||||
row_ks: torch.Tensor,
|
||||
row_ke: torch.Tensor,
|
||||
candidate_block_size: int,
|
||||
sparse_block_kv: int,
|
||||
out: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Expand request-local candidate blocks into DeepGEMM sparse block ids.
|
||||
|
||||
Args:
|
||||
candidate_blocks: [rows, K] int32 request-local candidate block ids
|
||||
(-1 padded), in units of ``candidate_block_size`` positions. K
|
||||
must be a power of two (the in-kernel sort); rows may be strided.
|
||||
row_ks/row_ke: [rows] int32 per-row K range; bounds are in the same
|
||||
(packed-workspace) coordinates the sparse kernel iterates over.
|
||||
Pass zeros for the paged path, whose blocks are context-relative.
|
||||
candidate_block_size: Positions per candidate block.
|
||||
sparse_block_kv: Positions per sparse block (8 or 16).
|
||||
out: Optional ``(sparse_indices, end)`` buffers to write into,
|
||||
shaped [rows, K * ratio] and [rows], both int32.
|
||||
|
||||
Returns:
|
||||
sparse_indices: [rows, K * ratio] int32 block ids for DeepGEMM,
|
||||
sorted ascending per row with the valid prefix first (unique in
|
||||
production, where candidates are unique) and the remaining slots
|
||||
repeating the last valid block (the kernel's padding convention).
|
||||
With the unaligned-ks variant, block ``i`` starts at
|
||||
``i * sparse_block_kv + ks % sparse_block_kv``.
|
||||
end: [rows] int32 count of valid sparse-token columns; valid columns
|
||||
always form a prefix because the block ids are sorted.
|
||||
"""
|
||||
rows, num_candidates = candidate_blocks.shape
|
||||
ratio = candidate_block_size // sparse_block_kv
|
||||
assert ratio * sparse_block_kv == candidate_block_size and ratio in (1, 2), (
|
||||
candidate_block_size,
|
||||
sparse_block_kv,
|
||||
)
|
||||
assert num_candidates & (num_candidates - 1) == 0, num_candidates
|
||||
num_sparse = num_candidates * ratio
|
||||
if out is None:
|
||||
device = candidate_blocks.device
|
||||
out = (
|
||||
torch.empty(rows, num_sparse, dtype=torch.int32, device=device),
|
||||
torch.empty(rows, dtype=torch.int32, device=device),
|
||||
)
|
||||
sparse_indices, end = out
|
||||
assert sparse_indices.shape == (rows, num_sparse) and end.shape == (rows,)
|
||||
assert candidate_blocks.stride(1) == 1 and sparse_indices.stride(1) == 1
|
||||
for t in (candidate_blocks, row_ks, row_ke, sparse_indices, end):
|
||||
assert t.dtype == torch.int32, t.dtype
|
||||
|
||||
_expand_candidates_kernel[(rows,)](
|
||||
candidate_blocks,
|
||||
candidate_blocks.stride(0),
|
||||
row_ks,
|
||||
row_ks.stride(0),
|
||||
row_ke,
|
||||
row_ke.stride(0),
|
||||
sparse_indices,
|
||||
sparse_indices.stride(0),
|
||||
end,
|
||||
end.stride(0),
|
||||
K=num_candidates,
|
||||
S=num_sparse,
|
||||
RATIO=ratio,
|
||||
SBK=sparse_block_kv,
|
||||
num_warps=16,
|
||||
)
|
||||
return sparse_indices, end
|
||||
|
||||
|
||||
def sparse_topk_remap(
|
||||
logits: torch.Tensor,
|
||||
sparse_indices: torch.Tensor,
|
||||
end: torch.Tensor,
|
||||
row_ks: torch.Tensor,
|
||||
sparse_block_kv: int,
|
||||
topk_tokens: int,
|
||||
topk_indices: torch.Tensor,
|
||||
*,
|
||||
col_indices: torch.Tensor,
|
||||
) -> None:
|
||||
"""Row top-k over sparse logits, remapped to request-local positions.
|
||||
|
||||
Column ``j * sparse_block_kv + o`` of ``logits`` scores the token at
|
||||
request-local position
|
||||
``(sparse_indices[row, j] - ks // sparse_block_kv) * sparse_block_kv + o``.
|
||||
|
||||
DeepSelect consumes the bf16 logits as they come out of the sparse
|
||||
kernels; the valid columns form a prefix (block ids are sorted), so the
|
||||
per-row ``end`` bounds drive it directly. Slots beyond a row's valid
|
||||
count come back as -1.
|
||||
|
||||
Args:
|
||||
col_indices: [rows, topk_tokens] int32 scratch for the sparse-column
|
||||
top-k result (row stride 32B-aligned for DeepSelect).
|
||||
"""
|
||||
rows, width = logits.shape
|
||||
assert logits.dtype == torch.bfloat16 and width >= topk_tokens
|
||||
assert end.dtype == torch.int32 and end.shape == (rows,)
|
||||
cols = col_indices[:rows]
|
||||
deep_select_topk(logits, topk_tokens, end=end, output_idx=cols)
|
||||
_sparse_topk_remap_kernel[(rows,)](
|
||||
cols,
|
||||
cols.stride(0),
|
||||
sparse_indices,
|
||||
sparse_indices.stride(0),
|
||||
row_ks,
|
||||
row_ks.stride(0),
|
||||
topk_indices,
|
||||
topk_indices.stride(0),
|
||||
topk_tokens,
|
||||
SBK=sparse_block_kv,
|
||||
K_POW2=triton.next_power_of_2(topk_tokens),
|
||||
)
|
||||
|
||||
|
||||
def sparse_mqa_logits_prefill_chunk(
|
||||
q: torch.Tensor,
|
||||
q_scale: torch.Tensor,
|
||||
k_quant: torch.Tensor,
|
||||
k_scale: torch.Tensor,
|
||||
weights: torch.Tensor,
|
||||
cu_seqlen_ks: torch.Tensor,
|
||||
cu_seqlen_ke: torch.Tensor,
|
||||
candidate_blocks: torch.Tensor,
|
||||
candidate_block_size: int,
|
||||
sparse_block_kv: int,
|
||||
topk_tokens: int,
|
||||
topk_indices: torch.Tensor,
|
||||
*,
|
||||
sparse_indices: torch.Tensor,
|
||||
end: torch.Tensor,
|
||||
col_indices: torch.Tensor,
|
||||
kernel_metadata: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Sparse-MQA logits + top-k for one prefill chunk (packed KV workspace).
|
||||
|
||||
Args:
|
||||
q: [rows, H, D] packed Q values (MXFP4 viewed as int8).
|
||||
q_scale: [rows, H] int32 packed UE8M0 Q scales.
|
||||
k_quant: [total_kv, D] packed K workspace (MXFP4 viewed as int8).
|
||||
k_scale: [total_kv] int32 packed UE8M0 K scales.
|
||||
weights: [rows, H] bf16 per-head weights; the sparse kernels take
|
||||
bf16 and do not fold the Q scale in.
|
||||
cu_seqlen_ks/cu_seqlen_ke: [rows] int32 per-token K bounds in the
|
||||
packed workspace.
|
||||
candidate_blocks: [rows, K] int32 request-local candidate block ids.
|
||||
topk_indices: [rows, topk_tokens] output buffer.
|
||||
sparse_indices/end/col_indices: Caller-owned scratch, see
|
||||
`candidate_blocks_to_sparse_indices` and `sparse_topk_remap`.
|
||||
kernel_metadata: DeepGEMM schedule from a previous call with the same
|
||||
candidates and bounds (i.e. another indexer layer in the same
|
||||
step). When given, the candidate expansion is skipped and
|
||||
``sparse_indices``/``end`` are assumed to be up to date.
|
||||
|
||||
Returns:
|
||||
The DeepGEMM schedule metadata used, for reuse by later layers.
|
||||
"""
|
||||
assert weights.dtype == torch.bfloat16, weights.dtype
|
||||
if kernel_metadata is None:
|
||||
candidate_blocks_to_sparse_indices(
|
||||
candidate_blocks,
|
||||
cu_seqlen_ks,
|
||||
cu_seqlen_ke,
|
||||
candidate_block_size,
|
||||
sparse_block_kv,
|
||||
out=(sparse_indices, end),
|
||||
)
|
||||
kernel_metadata = get_sparse_mqa_logits_metadata(
|
||||
cu_seqlen_ks,
|
||||
cu_seqlen_ke,
|
||||
k_quant.shape[0],
|
||||
sparse_indices,
|
||||
q.dtype,
|
||||
sparse_block_kv,
|
||||
)
|
||||
logits = fp8_fp4_sparse_mqa_logits(
|
||||
(q, q_scale),
|
||||
(k_quant, k_scale),
|
||||
weights,
|
||||
kernel_metadata,
|
||||
sparse_indices.shape[1],
|
||||
sparse_block_kv,
|
||||
)
|
||||
sparse_topk_remap(
|
||||
logits,
|
||||
sparse_indices,
|
||||
end,
|
||||
cu_seqlen_ks,
|
||||
sparse_block_kv,
|
||||
topk_tokens,
|
||||
topk_indices,
|
||||
col_indices=col_indices,
|
||||
)
|
||||
return kernel_metadata
|
||||
|
||||
|
||||
def sparse_mqa_logits_paged_decode(
|
||||
q: torch.Tensor,
|
||||
q_scale: torch.Tensor,
|
||||
kv_cache: torch.Tensor,
|
||||
weights: torch.Tensor,
|
||||
context_lens: torch.Tensor,
|
||||
block_table: torch.Tensor,
|
||||
row_indices: torch.Tensor,
|
||||
candidate_blocks: torch.Tensor,
|
||||
candidate_block_size: int,
|
||||
sparse_block_kv: int,
|
||||
topk_tokens: int,
|
||||
topk_indices: torch.Tensor,
|
||||
*,
|
||||
row_ks: torch.Tensor,
|
||||
sparse_indices: torch.Tensor,
|
||||
end: torch.Tensor,
|
||||
col_indices: torch.Tensor,
|
||||
kernel_metadata: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Sparse-MQA logits + top-k for paged decode rows.
|
||||
|
||||
Every query is one row (spec-decode rows are flattened by the metadata
|
||||
builder), so ``block_table`` is already per row.
|
||||
|
||||
Args:
|
||||
q: [rows, 1, H, D] packed Q values (MXFP4 viewed as int8).
|
||||
q_scale: [rows, 1, H] int32 packed UE8M0 Q scales.
|
||||
kv_cache: 4D [num_pages, page_kv, 1, head_bytes] uint8 fused cache
|
||||
view; the page stride must be 512B-aligned.
|
||||
weights: [rows, H] bf16 per-head weights.
|
||||
context_lens: [rows] int32 per-row (compressed) context lengths.
|
||||
block_table: [rows, P] int32 per-row page table, ``stride(-1) == 1``.
|
||||
row_indices: [rows] int32 row -> request map (pairing only affects
|
||||
scheduling).
|
||||
candidate_blocks: [rows, K] int32 candidate block ids.
|
||||
topk_indices: [rows, topk_tokens] output buffer.
|
||||
row_ks: [rows] int32 zeros (paged blocks are context-relative).
|
||||
sparse_indices/end/col_indices: Caller-owned scratch.
|
||||
kernel_metadata: See `sparse_mqa_logits_prefill_chunk`.
|
||||
|
||||
Returns:
|
||||
The DeepGEMM schedule metadata used, for reuse by later layers.
|
||||
"""
|
||||
rows = q.shape[0]
|
||||
page_kv = kv_cache.shape[1]
|
||||
assert weights.dtype == torch.bfloat16, weights.dtype
|
||||
assert kv_cache.stride(0) % 512 == 0, (
|
||||
"paged cache page stride must be 512B-aligned: "
|
||||
f"shape={tuple(kv_cache.shape)} stride={kv_cache.stride()}"
|
||||
)
|
||||
assert page_kv % sparse_block_kv == 0, (page_kv, sparse_block_kv)
|
||||
assert block_table.shape[0] == rows and block_table.stride(-1) == 1
|
||||
assert context_lens.shape == (rows,) and context_lens.is_contiguous()
|
||||
|
||||
if kernel_metadata is None:
|
||||
candidate_blocks_to_sparse_indices(
|
||||
candidate_blocks,
|
||||
row_ks,
|
||||
context_lens,
|
||||
candidate_block_size,
|
||||
sparse_block_kv,
|
||||
out=(sparse_indices, end),
|
||||
)
|
||||
kernel_metadata = get_paged_sparse_mqa_logits_metadata(
|
||||
context_lens,
|
||||
block_table,
|
||||
row_indices,
|
||||
page_kv,
|
||||
sparse_indices,
|
||||
q.dtype,
|
||||
sparse_block_kv,
|
||||
)
|
||||
logits = fp8_fp4_paged_sparse_mqa_logits(
|
||||
(q, q_scale),
|
||||
kv_cache,
|
||||
weights,
|
||||
kernel_metadata,
|
||||
sparse_indices.shape[1],
|
||||
sparse_block_kv,
|
||||
)
|
||||
sparse_topk_remap(
|
||||
logits,
|
||||
sparse_indices,
|
||||
end,
|
||||
row_ks,
|
||||
sparse_block_kv,
|
||||
topk_tokens,
|
||||
topk_indices,
|
||||
col_indices=col_indices,
|
||||
)
|
||||
return kernel_metadata
|
||||
@@ -235,14 +235,19 @@ from vllm.platforms import PlatformEnum, current_platform
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def _get_linear_backend() -> str:
|
||||
def _get_linear_backend(*, quantization: str) -> str:
|
||||
"""Get the linear_backend setting from the current vllm config."""
|
||||
from vllm.config import get_current_vllm_config_or_none
|
||||
|
||||
config = get_current_vllm_config_or_none()
|
||||
if config is not None:
|
||||
return config.kernel_config.linear_backend
|
||||
return "auto"
|
||||
if (config := get_current_vllm_config_or_none()) is None:
|
||||
return "auto"
|
||||
overrides = config.kernel_config.linear_backend_per_quant
|
||||
if overrides is not None and (override := overrides.get(quantization)):
|
||||
logger.info_once(
|
||||
"Applied linear backend override for %r: %r", quantization, override
|
||||
)
|
||||
return override
|
||||
return config.kernel_config.linear_backend
|
||||
|
||||
|
||||
# Kernel classes covered by each --linear-backend value.
|
||||
@@ -370,6 +375,8 @@ def _filter_kernels_by_backend(
|
||||
def _resolve_backend_kernels(
|
||||
kernels: list[type],
|
||||
layer_desc: str,
|
||||
*,
|
||||
quantization: str,
|
||||
) -> list[type]:
|
||||
"""Apply --linear-backend filtering to one layer type's kernel list.
|
||||
|
||||
@@ -380,7 +387,7 @@ def _resolve_backend_kernels(
|
||||
layer types (e.g. NVFP4 MoE projections next to FP8 attention
|
||||
projections).
|
||||
"""
|
||||
linear_backend = _get_linear_backend()
|
||||
linear_backend = _get_linear_backend(quantization=quantization)
|
||||
if linear_backend == "auto":
|
||||
return kernels
|
||||
filtered = _filter_kernels_by_backend(linear_backend, kernels)
|
||||
@@ -625,6 +632,8 @@ def choose_scaled_mm_linear_kernel(
|
||||
possible_kernels: dict[PlatformEnum, list[type[_KernelT]]],
|
||||
compute_capability: int | None = None,
|
||||
force_kernel: type[_KernelT] | None = None,
|
||||
*,
|
||||
quantization: str,
|
||||
) -> type[_KernelT]:
|
||||
"""
|
||||
Choose a _KernelT that can implement the given config for the
|
||||
@@ -642,6 +651,7 @@ def choose_scaled_mm_linear_kernel(
|
||||
force_kernel (Optional[type[_KernelT]]): An Optional forced kernel to override
|
||||
the possible_kernels if it can be implemented. If None, it will only try the
|
||||
possible kernels.
|
||||
quantization: Quantization scheme used to select a backend override.
|
||||
|
||||
Raises:
|
||||
ValueError: If no kernel can implement the given config.
|
||||
@@ -668,7 +678,11 @@ def choose_scaled_mm_linear_kernel(
|
||||
platform_kernels = possible_kernels.get(current_platform._enum, [])
|
||||
|
||||
# Apply --linear-backend filtering when set.
|
||||
platform_kernels = _resolve_backend_kernels(platform_kernels, "scaled-mm")
|
||||
platform_kernels = _resolve_backend_kernels(
|
||||
platform_kernels,
|
||||
"scaled-mm",
|
||||
quantization=quantization,
|
||||
)
|
||||
|
||||
for kernel in platform_kernels:
|
||||
is_supported_and_can_implement, failure_reason = (
|
||||
@@ -705,6 +719,7 @@ def init_fp8_linear_kernel(
|
||||
kernel_type = choose_scaled_mm_linear_kernel(
|
||||
config=scaled_mm_linear_kernel_config,
|
||||
possible_kernels=_POSSIBLE_FP8_BLOCK_KERNELS, # type: ignore[misc]
|
||||
quantization="fp8_block_w8a8",
|
||||
force_kernel=force_kernel,
|
||||
)
|
||||
if module_name:
|
||||
@@ -736,6 +751,7 @@ def init_fp8_linear_kernel(
|
||||
kernel_type = choose_scaled_mm_linear_kernel(
|
||||
config=scaled_mm_linear_kernel_config,
|
||||
possible_kernels=_POSSIBLE_FP8_KERNELS, # type: ignore[arg-type]
|
||||
quantization="fp8_w8a8",
|
||||
force_kernel=force_kernel,
|
||||
)
|
||||
if module_name:
|
||||
@@ -772,6 +788,7 @@ def init_int8_linear_kernel(
|
||||
kernel_type = choose_scaled_mm_linear_kernel(
|
||||
config,
|
||||
_POSSIBLE_INT8_KERNELS,
|
||||
quantization="int8_w8a8",
|
||||
)
|
||||
|
||||
logger.info_once(
|
||||
@@ -824,7 +841,11 @@ def choose_mp_linear_kernel(
|
||||
platform_kernels = _POSSIBLE_KERNELS.get(current_platform._enum, [])
|
||||
|
||||
# Apply --linear-backend filtering when set.
|
||||
platform_kernels = _resolve_backend_kernels(platform_kernels, "mixed-precision")
|
||||
platform_kernels = _resolve_backend_kernels(
|
||||
platform_kernels,
|
||||
"mixed-precision",
|
||||
quantization="mixed_precision",
|
||||
)
|
||||
|
||||
failure_reasons = []
|
||||
for kernel in platform_kernels:
|
||||
@@ -875,7 +896,11 @@ def init_mxfp8_linear_kernel(*, bmm_batch_size: int | None = None) -> Mxfp8Linea
|
||||
possible = list(_POSSIBLE_MXFP8_KERNELS.get(platform, []))
|
||||
|
||||
# Apply --linear-backend filtering when set.
|
||||
possible = _resolve_backend_kernels(possible, "MXFP8")
|
||||
possible = _resolve_backend_kernels(
|
||||
possible,
|
||||
"MXFP8",
|
||||
quantization="mxfp8",
|
||||
)
|
||||
|
||||
failure_reasons = []
|
||||
for kernel_cls in possible:
|
||||
@@ -917,7 +942,11 @@ def init_mxfp4_linear_kernel(
|
||||
possible = list(_POSSIBLE_MXFP4_KERNELS.get(platform, []))
|
||||
|
||||
# Apply --linear-backend filtering when set.
|
||||
possible = _resolve_backend_kernels(possible, "MXFP4")
|
||||
possible = _resolve_backend_kernels(
|
||||
possible,
|
||||
"MXFP4",
|
||||
quantization="mxfp4",
|
||||
)
|
||||
|
||||
failure_reasons = []
|
||||
for kernel_cls in possible:
|
||||
@@ -957,7 +986,7 @@ def init_mxfp6_linear_kernel(
|
||||
activation_quant_key=activation_quant_key,
|
||||
)
|
||||
|
||||
linear_backend = _get_linear_backend()
|
||||
linear_backend = _get_linear_backend(quantization="mxfp6")
|
||||
|
||||
platform = current_platform._enum
|
||||
possible = list(_POSSIBLE_MXFP6_KERNELS.get(platform, []))
|
||||
@@ -1017,7 +1046,10 @@ def init_wfp8_a16_linear_kernel(
|
||||
)
|
||||
|
||||
kernel_type = choose_scaled_mm_linear_kernel(
|
||||
config, _POSSIBLE_WFP8A16_KERNELS, force_kernel=force_kernel
|
||||
config,
|
||||
_POSSIBLE_WFP8A16_KERNELS,
|
||||
quantization="w8a16_fp8",
|
||||
force_kernel=force_kernel,
|
||||
)
|
||||
|
||||
if module_name:
|
||||
@@ -1048,7 +1080,8 @@ def init_nvfp4_linear_kernel(use_a16: bool = False) -> NvFp4LinearKernel:
|
||||
# batch-invariant CUTLASS implementation when available, otherwise fall
|
||||
# back to emulation. It overrides --linear-backend.
|
||||
force_kernel: type[NvFp4LinearKernel] | None = None
|
||||
linear_backend = _get_linear_backend()
|
||||
quantization = "nvfp4_w4a16" if use_a16 else "nvfp4_w4a4"
|
||||
linear_backend = _get_linear_backend(quantization=quantization)
|
||||
if envs.VLLM_BATCH_INVARIANT:
|
||||
bi_supported, reason = CutlassNvFp4LinearKernel.is_supported()
|
||||
if bi_supported:
|
||||
@@ -1110,7 +1143,11 @@ def init_nvfp4_linear_kernel(use_a16: bool = False) -> NvFp4LinearKernel:
|
||||
possible = [kernel for kernel in possible if kernel in a16_kernels]
|
||||
|
||||
# Apply --linear-backend filtering when set.
|
||||
possible = _resolve_backend_kernels(possible, "NVFP4")
|
||||
possible = _resolve_backend_kernels(
|
||||
possible,
|
||||
"NVFP4",
|
||||
quantization=quantization,
|
||||
)
|
||||
|
||||
failure_reasons = []
|
||||
for kernel_cls in possible:
|
||||
|
||||
@@ -77,7 +77,7 @@ def _triton_w4a16_skinny_fmt_kernel(
|
||||
a_ptr, # [M, K] fp16/bf16 activations
|
||||
b_ptr, # [N, K//8] int32 packed (ExLlama shuffle, K is packed dim)
|
||||
scales_ptr, # [N, K//G] fp16/bf16 scales (skinny layout)
|
||||
zp_ptr, # [N, K//G] fp16/bf16 raw zero-points (when HAS_ZP=True)
|
||||
zp_ptr, # [N//8, K//G] int32 zero-points (when HAS_ZP=True)
|
||||
c_ptr, # [M, N] fp16/bf16 output
|
||||
# Dimensions
|
||||
M,
|
||||
@@ -103,8 +103,9 @@ def _triton_w4a16_skinny_fmt_kernel(
|
||||
| (val[1]<<16) | (val[3]<<20) | (val[5]<<24) | (val[7]<<28)
|
||||
|
||||
Scales are [N, K//G] (skinny layout, NOT transposed).
|
||||
When HAS_ZP=True, raw zero-points zp_raw are loaded from zp_ptr [N, K//G]
|
||||
and subtracted directly: (nibble - zp_raw) * scale.
|
||||
When HAS_ZP=True, zp_ptr holds [N//8, K//G] int32 with row n's raw
|
||||
zero-point at word[n//8] bits 4*(n%8), and dequant is
|
||||
(nibble - zp_raw) * scale.
|
||||
When HAS_ZP=False, only the constant ZP_BIAS is subtracted (symmetric).
|
||||
"""
|
||||
pid_m = tl.program_id(0)
|
||||
@@ -148,9 +149,10 @@ def _triton_w4a16_skinny_fmt_kernel(
|
||||
scales = tl.load(scale_ptrs, mask=scale_mask, other=1.0)
|
||||
|
||||
if HAS_ZP:
|
||||
zp_ptrs = zp_ptr + offs_n * num_groups + group_idx
|
||||
zp_raw = tl.load(zp_ptrs, mask=scale_mask, other=0.0)
|
||||
b_fp = (b.to(scales.dtype) - zp_raw[:, None]) * scales[:, None]
|
||||
zp_ptrs = zp_ptr + (offs_n // 8) * num_groups + group_idx
|
||||
zp_word = tl.load(zp_ptrs, mask=scale_mask, other=0)
|
||||
zp_raw = (zp_word >> (4 * (offs_n % 8))) & 0xF
|
||||
b_fp = (b - zp_raw[:, None]).to(scales.dtype) * scales[:, None]
|
||||
else:
|
||||
b_fp = (b - ZP_BIAS).to(scales.dtype) * scales[:, None]
|
||||
|
||||
@@ -192,7 +194,7 @@ def triton_w4a16_skinny_fmt_gemm(
|
||||
scales: torch.Tensor, # [N, K//G] fp16/bf16
|
||||
group_size: int,
|
||||
zp_bias: int = 8,
|
||||
zp: torch.Tensor | None = None, # [N, K//G] per-group zero-points
|
||||
zp: torch.Tensor | None = None, # [N//8, K//G] int32 zero-points
|
||||
) -> torch.Tensor:
|
||||
"""
|
||||
Fused W4A16 GEMM reading from skinny weight format [N, K//8].
|
||||
@@ -203,8 +205,8 @@ def triton_w4a16_skinny_fmt_gemm(
|
||||
scales: Per-group scales [N, K//G], same dtype as a.
|
||||
group_size: Quantization group size (resolved from -1 to K by caller).
|
||||
zp_bias: Constant zero bias (default 8 for unsigned int4).
|
||||
zp: Raw per-group zero-points [N, K//G] (asymmetric),
|
||||
stored as zp_raw in activation dtype. When provided,
|
||||
zp: Raw per-group zero-points [N//8, K//G] int32, row n at
|
||||
word[n//8] bits 4*(n%8) (asymmetric). When provided,
|
||||
dequant is (nibble - zp_raw) * scale.
|
||||
|
||||
Returns:
|
||||
@@ -225,8 +227,9 @@ def triton_w4a16_skinny_fmt_gemm(
|
||||
)
|
||||
if zp is not None:
|
||||
assert zp.is_contiguous(), "Zero-points must be contiguous"
|
||||
assert zp.shape == (N, num_groups), (
|
||||
f"zp shape mismatch: {zp.shape} vs ({N}, {num_groups})"
|
||||
assert N % 8 == 0, f"N must be divisible by 8 for packed zp, got {N}"
|
||||
assert zp.shape == (N // 8, num_groups), (
|
||||
f"zp shape mismatch: {zp.shape} vs ({N // 8}, {num_groups})"
|
||||
)
|
||||
has_zp = zp is not None
|
||||
|
||||
@@ -381,7 +384,10 @@ def _rdna_hybrid_w4a16_apply_impl(
|
||||
cu_count: int,
|
||||
group_size: int,
|
||||
) -> torch.Tensor:
|
||||
"""Dispatch between skinny GEMM and Triton based on batch size M."""
|
||||
"""Dispatch between skinny GEMM and Triton based on batch size M.
|
||||
|
||||
``w_zp`` is [N//8, K//G] int32 for asymmetric layers, None for symmetric.
|
||||
"""
|
||||
import vllm._custom_ops as ops
|
||||
|
||||
M = x_2d.shape[0]
|
||||
@@ -520,10 +526,7 @@ class RDNAHybridW4A16LinearKernel(MPLinearKernel):
|
||||
assert self.w_zp_name is not None
|
||||
w_zp_raw = getattr(layer, self.w_zp_name)
|
||||
permute_param_layout_(w_zp_raw, input_dim=1, output_dim=0, packed_dim=0)
|
||||
zp_unpacked = unpack_quantized_values_into_int32(
|
||||
w_zp_raw.data, c.weight_type, packed_dim=0
|
||||
)
|
||||
w_zp = zp_unpacked.to(c.act_type).contiguous()
|
||||
w_zp = w_zp_raw.data.contiguous()
|
||||
self._transform_param(layer, self.w_zp_name, lambda x: w_zp)
|
||||
|
||||
self._transform_param(layer, self.w_q_name, lambda x: w_q_skinny)
|
||||
|
||||
@@ -158,7 +158,7 @@ class AiterMxfp4LinearKernel(MxFp4LinearKernel):
|
||||
from vllm._aiter_ops import is_aiter_found_and_supported
|
||||
from vllm.model_executor.kernels.linear import _get_linear_backend
|
||||
|
||||
linear_backend = _get_linear_backend()
|
||||
linear_backend = _get_linear_backend(quantization="mxfp4")
|
||||
|
||||
if (
|
||||
current_platform.is_rocm()
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
|
||||
Consumes the FP8 E4M3 weights + E8M0 block scales directly (no dequant-to-BF16);
|
||||
activations are MXFP8-quantized per token. Uses the CDNA4 hardware microscaling
|
||||
matrix cores. Falls back (via the kernel selector) to the BF16
|
||||
``EmulationMxfp8LinearKernel`` on archs without native MX or for shapes with
|
||||
``K % 128 != 0``.
|
||||
matrix cores. ``dot_scaled`` tiles K by 128; a weight whose K is not a multiple
|
||||
of that is dequantized to BF16 once at load and served by a plain linear
|
||||
instead, since ``can_implement`` does not filter on K.
|
||||
"""
|
||||
|
||||
import torch
|
||||
@@ -194,6 +194,9 @@ def _select_cfg(M, N, K):
|
||||
return (128, 128, 256, 8, 2) if K % 256 == 0 else (128, 256, 128, 8, 3)
|
||||
|
||||
|
||||
_DOT_SCALED_K_ALIGN = 128
|
||||
|
||||
|
||||
class RocmDotScaledMxfp8LinearKernel(Mxfp8LinearKernel):
|
||||
"""Native CDNA4 (gfx950) MXFP8 linear via Triton ``tl.dot_scaled``."""
|
||||
|
||||
@@ -219,6 +222,8 @@ class RocmDotScaledMxfp8LinearKernel(Mxfp8LinearKernel):
|
||||
N, K = weight.shape
|
||||
scale_k = K // MXFP8_BLOCK_SIZE
|
||||
weight_scale = layer.weight_scale.data[:N, :scale_k].contiguous()
|
||||
if K % _DOT_SCALED_K_ALIGN != 0:
|
||||
weight = dequant_mxfp8_to_bf16(weight.contiguous(), weight_scale)
|
||||
layer.weight = Parameter(weight.contiguous(), requires_grad=False)
|
||||
layer.weight_scale = Parameter(weight_scale, requires_grad=False)
|
||||
|
||||
@@ -235,10 +240,13 @@ class RocmDotScaledMxfp8LinearKernel(Mxfp8LinearKernel):
|
||||
)
|
||||
out_shape = (*x.shape[:-1], layer.weight.shape[0])
|
||||
x2d = x.reshape(-1, x.shape[-1])
|
||||
if x2d.shape[-1] % 128 == 0:
|
||||
if layer.weight.element_size() >= 2:
|
||||
out = torch.nn.functional.linear(x2d, layer.weight.to(x.dtype))
|
||||
elif x2d.shape[-1] % _DOT_SCALED_K_ALIGN == 0:
|
||||
out = _mxfp8_dot_scaled_linear(x2d, layer.weight, layer.weight_scale)
|
||||
else:
|
||||
# dot_scaled tiling needs K % 128 == 0; dequantize fallback otherwise.
|
||||
# process_weights_after_loading dequantizes these weights once, so
|
||||
# this runs only if it did not; dot_scaled would be invalid here.
|
||||
w_bf16 = dequant_mxfp8_to_bf16(layer.weight, layer.weight_scale)
|
||||
out = torch.nn.functional.linear(x2d, w_bf16).to(x.dtype)
|
||||
out = out.reshape(out_shape)
|
||||
|
||||
@@ -261,6 +261,8 @@ class CPUFp8BlockScaledMMKernel(Fp8BlockScaledMMLinearKernel):
|
||||
return True, None
|
||||
|
||||
def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
|
||||
if getattr(layer, "_cpu_skip_gemm_dispatch", False):
|
||||
return
|
||||
# Skip the base class process (FP8 padding / fnuz normalization)
|
||||
# which is GPU-oriented. Instead, VNNI-prepack weights for AMX.
|
||||
params = self._get_layer_params(layer)
|
||||
|
||||
@@ -115,6 +115,10 @@ def mhc_pre_delayed_aiter(
|
||||
hc_post_mult_value: float,
|
||||
sinkhorn_repeat: int,
|
||||
pre_mix: torch.Tensor | None = None,
|
||||
sublayer_out: torch.Tensor | None = None,
|
||||
post_layer_mix: torch.Tensor | None = None,
|
||||
comb_res_mix: torch.Tensor | None = None,
|
||||
residual_out: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
"""mHC pre with the pre-mix carried in from the previous sublayer.
|
||||
|
||||
@@ -134,6 +138,13 @@ def mhc_pre_delayed_aiter(
|
||||
sinkhorn_repeat: number of sinkhorn iterations
|
||||
pre_mix: shape (..., hc_mult) from the previous sublayer, or None at
|
||||
model entry to select residual stream zero.
|
||||
sublayer_out: attention or FFN output, shape (..., hidden_size). When
|
||||
given with the two mixes below, the preceding post block is
|
||||
applied here so AITER can fold it into the pre projection.
|
||||
post_layer_mix: shape (..., hc_mult, 1), post gate for that block.
|
||||
comb_res_mix: shape (..., hc_mult, hc_mult), residual comb for it.
|
||||
residual_out: shape (..., hc_mult, hidden_size), written with the post
|
||||
block's new residual. Required exactly when the post is folded in.
|
||||
|
||||
Returns:
|
||||
post_mix: shape (..., hc_mult, 1), dtype torch.float32
|
||||
@@ -156,6 +167,10 @@ def mhc_pre_delayed_aiter(
|
||||
hc_post_mult_value,
|
||||
sinkhorn_repeat,
|
||||
pre_mix,
|
||||
sublayer_out,
|
||||
post_layer_mix,
|
||||
comb_res_mix,
|
||||
residual_out,
|
||||
)
|
||||
|
||||
|
||||
@@ -170,6 +185,10 @@ def _mhc_pre_delayed_aiter_fake(
|
||||
hc_post_mult_value: float,
|
||||
sinkhorn_repeat: int,
|
||||
pre_mix: torch.Tensor | None = None,
|
||||
sublayer_out: torch.Tensor | None = None,
|
||||
post_layer_mix: torch.Tensor | None = None,
|
||||
comb_res_mix: torch.Tensor | None = None,
|
||||
residual_out: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
hc_mult = residual.shape[-2]
|
||||
hidden_size = residual.shape[-1]
|
||||
@@ -313,7 +332,7 @@ direct_register_custom_op(
|
||||
direct_register_custom_op(
|
||||
op_name="mhc_pre_delayed_aiter",
|
||||
op_func=mhc_pre_delayed_aiter,
|
||||
mutates_args=[],
|
||||
mutates_args=["residual_out"],
|
||||
fake_impl=_mhc_pre_delayed_aiter_fake,
|
||||
)
|
||||
direct_register_custom_op(
|
||||
|
||||
@@ -194,6 +194,7 @@ def mhc_pre_delayed_tilelang(
|
||||
norm_weight,
|
||||
pre_mix if pre_mix is not None else post,
|
||||
next_pre_mix,
|
||||
layer_input,
|
||||
hidden_size=hidden_size,
|
||||
rms_eps=rms_eps,
|
||||
hc_pre_eps=hc_pre_eps,
|
||||
@@ -218,6 +219,7 @@ def mhc_pre_delayed_tilelang(
|
||||
layer_input,
|
||||
pre_mix if pre_mix is not None else post,
|
||||
next_pre_mix,
|
||||
layer_input,
|
||||
hidden_size,
|
||||
rms_eps,
|
||||
hc_pre_eps,
|
||||
@@ -263,6 +265,278 @@ def _mhc_pre_delayed_tilelang_fake(
|
||||
)
|
||||
|
||||
|
||||
def mhc_fused_post_pre_delayed_tilelang(
|
||||
x: torch.Tensor,
|
||||
residual: torch.Tensor,
|
||||
post_layer_mix: torch.Tensor,
|
||||
comb_res_mix: torch.Tensor,
|
||||
fn: torch.Tensor,
|
||||
hc_scale: torch.Tensor,
|
||||
hc_base: torch.Tensor,
|
||||
rms_eps: float,
|
||||
hc_pre_eps: float,
|
||||
hc_sinkhorn_eps: float,
|
||||
hc_post_mult_value: float,
|
||||
sinkhorn_repeat: int,
|
||||
pre_mix: torch.Tensor | None = None,
|
||||
norm_weight: torch.Tensor | None = None,
|
||||
norm_eps: float = 1e-6,
|
||||
capture_aux: bool = False,
|
||||
) -> tuple[
|
||||
torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor
|
||||
]:
|
||||
"""Run one mHC post block followed by the next delayed mHC pre block.
|
||||
|
||||
Within the fused kernel's token range the post mapping is folded into the
|
||||
pre-norm GEMM, so the updated residual streams feed the projection from
|
||||
registers instead of a second pass over global memory. Above it this runs
|
||||
the same post kernel and split-k GEMM as the unfused pair.
|
||||
|
||||
Args:
|
||||
x: BF16 sublayer output of shape (tokens, hidden_size).
|
||||
residual: BF16 residual streams of shape (tokens, hc_mult, hidden_size).
|
||||
post_layer_mix: FP32 post coefficients of shape (tokens, hc_mult, 1).
|
||||
comb_res_mix: FP32 residual coefficients, (tokens, hc_mult, hc_mult).
|
||||
fn: FP32 projection of shape (hc_mult * (hc_mult + 2), input_size).
|
||||
hc_scale: FP32 scales of shape (3,).
|
||||
hc_base: FP32 bias of shape (hc_mult * (hc_mult + 2),).
|
||||
rms_eps: RMS normalization epsilon.
|
||||
hc_pre_eps: Pre-mix epsilon.
|
||||
hc_sinkhorn_eps: Sinkhorn epsilon.
|
||||
hc_post_mult_value: Post-mix multiplier.
|
||||
sinkhorn_repeat: Number of Sinkhorn iterations.
|
||||
pre_mix: FP32 coefficients from the previous sublayer, or None to
|
||||
select residual stream zero.
|
||||
norm_weight: Optional BF16 RMSNorm weight for the collapsed input.
|
||||
norm_eps: RMSNorm epsilon for the collapsed input.
|
||||
capture_aux: Also return the mean over the post-mapped streams, which
|
||||
draft models consume as the target's hidden state. It is folded
|
||||
into the collapse, which already reads those streams.
|
||||
|
||||
Returns:
|
||||
The post-mapped residual streams, the post and residual coefficients,
|
||||
the optionally normalized BF16 layer input, the next FP32 pre-mix, and
|
||||
the BF16 stream mean (empty unless capture_aux), with shapes
|
||||
(tokens, hc_mult, hidden_size), (tokens, hc_mult, 1),
|
||||
(tokens, hc_mult, hc_mult), (tokens, hidden_size), (tokens, hc_mult),
|
||||
and (tokens, hidden_size).
|
||||
"""
|
||||
from vllm.model_executor.kernels.mhc.tilelang_kernels import (
|
||||
_HC_PRENORM_GEMM_TILELANG_KERNEL,
|
||||
_MHC_FUSED_TILELANG_KERNEL,
|
||||
_MHC_POST_TILELANG_KERNEL,
|
||||
mhc_fused_post_pre_split_config,
|
||||
mhc_pre_big_fuse_tilelang,
|
||||
)
|
||||
from vllm.model_executor.kernels.mhc.warmup import (
|
||||
MHC_PRE_NORM_KERNEL,
|
||||
compute_mhc_pre_num_splits,
|
||||
)
|
||||
from vllm.utils.deep_gemm import (
|
||||
is_deep_gemm_supported,
|
||||
tf32_hc_prenorm_gemm,
|
||||
)
|
||||
|
||||
assert residual.ndim == 3 and residual.dtype == torch.bfloat16
|
||||
assert residual.is_contiguous()
|
||||
num_tokens, hc_mult, hidden_size = residual.shape
|
||||
input_size = hc_mult * hidden_size
|
||||
mix_size = hc_mult * (hc_mult + 2)
|
||||
assert x.shape == (num_tokens, hidden_size) and x.dtype == torch.bfloat16
|
||||
assert x.is_contiguous()
|
||||
assert post_layer_mix.shape[:2] == (num_tokens, hc_mult)
|
||||
assert post_layer_mix.dtype == torch.float32 and post_layer_mix.is_contiguous()
|
||||
assert comb_res_mix.shape == (num_tokens, hc_mult, hc_mult)
|
||||
assert comb_res_mix.dtype == torch.float32 and comb_res_mix.is_contiguous()
|
||||
assert fn.shape == (mix_size, input_size) and fn.dtype == torch.float32
|
||||
assert hc_scale.shape == (3,) and hc_scale.dtype == torch.float32
|
||||
assert hc_base.shape == (mix_size,) and hc_base.dtype == torch.float32
|
||||
if pre_mix is not None:
|
||||
assert pre_mix.shape == (num_tokens, hc_mult)
|
||||
assert pre_mix.dtype == torch.float32 and pre_mix.is_contiguous()
|
||||
|
||||
next_pre_mix = torch.empty(
|
||||
num_tokens, hc_mult, dtype=torch.float32, device=residual.device
|
||||
)
|
||||
post = torch.empty_like(next_pre_mix)
|
||||
comb = torch.empty(
|
||||
num_tokens, hc_mult * hc_mult, dtype=torch.float32, device=residual.device
|
||||
)
|
||||
layer_input = torch.empty(
|
||||
num_tokens, hidden_size, dtype=torch.bfloat16, device=residual.device
|
||||
)
|
||||
aux = torch.empty(
|
||||
num_tokens if capture_aux else 0,
|
||||
hidden_size,
|
||||
dtype=torch.bfloat16,
|
||||
device=residual.device,
|
||||
)
|
||||
if num_tokens == 0:
|
||||
return (
|
||||
torch.empty_like(residual),
|
||||
post.unsqueeze(-1),
|
||||
comb.view(num_tokens, hc_mult, hc_mult),
|
||||
layer_input,
|
||||
next_pre_mix,
|
||||
aux,
|
||||
)
|
||||
|
||||
fused_config = mhc_fused_post_pre_split_config(num_tokens, hidden_size, hc_mult)
|
||||
if fused_config is not None:
|
||||
mixes, sqrsum, residual_cur = _MHC_FUSED_TILELANG_KERNEL(
|
||||
comb_res_mix,
|
||||
residual,
|
||||
post_layer_mix.view(num_tokens, hc_mult),
|
||||
x,
|
||||
fn.view(mix_size, hc_mult, hidden_size),
|
||||
hc_mult,
|
||||
hidden_size,
|
||||
mix_size,
|
||||
)
|
||||
else:
|
||||
residual_cur = torch.empty_like(residual)
|
||||
_MHC_POST_TILELANG_KERNEL(
|
||||
comb_res_mix,
|
||||
residual,
|
||||
post_layer_mix.view(num_tokens, hc_mult),
|
||||
x,
|
||||
residual_cur,
|
||||
hc_mult,
|
||||
hidden_size,
|
||||
)
|
||||
# The delayed epilogue is compiled per bucketed split count, so the
|
||||
# projection has to use the same bucket rather than the raw estimate.
|
||||
use_deep_gemm = is_deep_gemm_supported()
|
||||
n_splits = (
|
||||
compute_mhc_pre_num_splits(input_size, num_tokens) if use_deep_gemm else 1
|
||||
)
|
||||
mixes = torch.empty(
|
||||
n_splits, num_tokens, mix_size, dtype=torch.float32, device=residual.device
|
||||
)
|
||||
sqrsum = torch.empty(
|
||||
n_splits, num_tokens, dtype=torch.float32, device=residual.device
|
||||
)
|
||||
residual_cur_2d = residual_cur.view(num_tokens, input_size)
|
||||
if use_deep_gemm:
|
||||
tf32_hc_prenorm_gemm(residual_cur_2d, fn, mixes, sqrsum, n_splits)
|
||||
else:
|
||||
_HC_PRENORM_GEMM_TILELANG_KERNEL(
|
||||
residual_cur_2d,
|
||||
fn,
|
||||
mixes,
|
||||
sqrsum,
|
||||
input_size,
|
||||
1,
|
||||
)
|
||||
|
||||
outputs = (
|
||||
residual_cur,
|
||||
post.unsqueeze(-1),
|
||||
comb.view(num_tokens, hc_mult, hc_mult),
|
||||
layer_input,
|
||||
next_pre_mix,
|
||||
aux,
|
||||
)
|
||||
if norm_weight is not None:
|
||||
assert norm_weight.shape == (hidden_size,)
|
||||
assert norm_weight.dtype == torch.bfloat16 and norm_weight.is_contiguous()
|
||||
MHC_PRE_NORM_KERNEL(
|
||||
mixes,
|
||||
sqrsum,
|
||||
hc_scale,
|
||||
hc_base,
|
||||
residual_cur,
|
||||
post,
|
||||
comb,
|
||||
layer_input,
|
||||
norm_weight,
|
||||
pre_mix if pre_mix is not None else post,
|
||||
next_pre_mix,
|
||||
aux if capture_aux else layer_input,
|
||||
hidden_size=hidden_size,
|
||||
rms_eps=rms_eps,
|
||||
hc_pre_eps=hc_pre_eps,
|
||||
hc_sinkhorn_eps=hc_sinkhorn_eps,
|
||||
hc_post_mult_value=hc_post_mult_value,
|
||||
sinkhorn_repeat=sinkhorn_repeat,
|
||||
norm_eps=norm_eps,
|
||||
hc_mult=hc_mult,
|
||||
use_pre_mix_in=pre_mix is not None,
|
||||
save_pre_mix=True,
|
||||
rms_numel=input_size,
|
||||
write_aux=capture_aux,
|
||||
)
|
||||
return outputs
|
||||
mhc_pre_big_fuse_tilelang(
|
||||
mixes,
|
||||
sqrsum,
|
||||
hc_scale,
|
||||
hc_base,
|
||||
residual_cur,
|
||||
post,
|
||||
comb,
|
||||
layer_input,
|
||||
pre_mix if pre_mix is not None else post,
|
||||
next_pre_mix,
|
||||
aux if capture_aux else layer_input,
|
||||
hidden_size,
|
||||
rms_eps,
|
||||
hc_pre_eps,
|
||||
hc_sinkhorn_eps,
|
||||
hc_post_mult_value,
|
||||
sinkhorn_repeat,
|
||||
mixes.shape[0],
|
||||
hc_mult,
|
||||
use_pre_mix_in=pre_mix is not None,
|
||||
save_pre_mix=True,
|
||||
rms_numel=input_size,
|
||||
write_aux=capture_aux,
|
||||
)
|
||||
return outputs
|
||||
|
||||
|
||||
def _mhc_fused_post_pre_delayed_tilelang_fake(
|
||||
x: torch.Tensor,
|
||||
residual: torch.Tensor,
|
||||
post_layer_mix: torch.Tensor,
|
||||
comb_res_mix: torch.Tensor,
|
||||
fn: torch.Tensor,
|
||||
hc_scale: torch.Tensor,
|
||||
hc_base: torch.Tensor,
|
||||
rms_eps: float,
|
||||
hc_pre_eps: float,
|
||||
hc_sinkhorn_eps: float,
|
||||
hc_post_mult_value: float,
|
||||
sinkhorn_repeat: int,
|
||||
pre_mix: torch.Tensor | None = None,
|
||||
norm_weight: torch.Tensor | None = None,
|
||||
norm_eps: float = 1e-6,
|
||||
capture_aux: bool = False,
|
||||
) -> tuple[
|
||||
torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor
|
||||
]:
|
||||
num_tokens, hc_mult, hidden_size = residual.shape
|
||||
return (
|
||||
torch.empty_like(residual),
|
||||
torch.empty(
|
||||
num_tokens, hc_mult, 1, dtype=torch.float32, device=residual.device
|
||||
),
|
||||
torch.empty(
|
||||
num_tokens, hc_mult, hc_mult, dtype=torch.float32, device=residual.device
|
||||
),
|
||||
torch.empty(
|
||||
num_tokens, hidden_size, dtype=torch.bfloat16, device=residual.device
|
||||
),
|
||||
torch.empty(num_tokens, hc_mult, dtype=torch.float32, device=residual.device),
|
||||
torch.empty(
|
||||
num_tokens if capture_aux else 0,
|
||||
hidden_size,
|
||||
dtype=torch.bfloat16,
|
||||
device=residual.device,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def mhc_pre_tilelang(
|
||||
residual: torch.Tensor,
|
||||
fn: torch.Tensor,
|
||||
@@ -574,6 +848,7 @@ def mhc_fused_post_pre_tilelang(
|
||||
_MHC_FUSED_TILELANG_KERNEL,
|
||||
_MHC_POST_TILELANG_KERNEL,
|
||||
_MHC_PRE_BIG_FUSE_TILELANG_KERNEL,
|
||||
mhc_fused_post_pre_split_config,
|
||||
)
|
||||
|
||||
assert residual.dtype == torch.bfloat16
|
||||
@@ -614,7 +889,7 @@ def mhc_fused_post_pre_tilelang(
|
||||
post_layer_mix_flat = post_layer_mix.view(num_tokens, hc_mult)
|
||||
comb_res_mix_flat = comb_res_mix.view(num_tokens, hc_mult, hc_mult)
|
||||
|
||||
use_small_fma = num_tokens <= 16
|
||||
fused_config = mhc_fused_post_pre_split_config(num_tokens, hidden_size, hc_mult)
|
||||
|
||||
post_mix_cur = torch.empty(
|
||||
num_tokens,
|
||||
@@ -635,7 +910,7 @@ def mhc_fused_post_pre_tilelang(
|
||||
device=residual.device,
|
||||
)
|
||||
|
||||
if use_small_fma:
|
||||
if fused_config is not None:
|
||||
gemm_out_mul, gemm_out_sqrsum, residual_cur = _MHC_FUSED_TILELANG_KERNEL(
|
||||
comb_res_mix_flat,
|
||||
residual_flat,
|
||||
@@ -815,6 +1090,12 @@ direct_register_custom_op(
|
||||
mutates_args=[],
|
||||
fake_impl=_mhc_pre_delayed_tilelang_fake,
|
||||
)
|
||||
direct_register_custom_op(
|
||||
op_name="mhc_fused_post_pre_delayed_tilelang",
|
||||
op_func=mhc_fused_post_pre_delayed_tilelang,
|
||||
mutates_args=[],
|
||||
fake_impl=_mhc_fused_post_pre_delayed_tilelang_fake,
|
||||
)
|
||||
direct_register_custom_op(
|
||||
op_name="mhc_pre_tilelang",
|
||||
op_func=mhc_pre_tilelang,
|
||||
|
||||
@@ -37,8 +37,67 @@ def compute_num_split(block_k: int, k: int | None, grid_size: int) -> int:
|
||||
return split_k
|
||||
|
||||
|
||||
def _mhc_fused_n_splits(num_tokens: int, hidden_size: int) -> int:
|
||||
return 8 if num_tokens < 8 and hidden_size <= 4096 else 4
|
||||
# ``mhc_fused_tilelang`` splits the hidden size across a fixed thread block, so
|
||||
# every (tile_n, n_thr) pair is one more kernel to compile. Tuned on GB300
|
||||
# (hc_mult 4, hidden_size 5120 and 7168) against the separate post + split-k
|
||||
# GEMM it replaces; the bands are coarse because the loss against a per-shape
|
||||
# optimum is ~1-2%, while one fixed config gives up to 18% at the top of the
|
||||
# range.
|
||||
_FUSED_POST_PRE_N_THR = 128
|
||||
_FUSED_POST_PRE_MAX_TOKENS = 32
|
||||
|
||||
|
||||
def mhc_fused_post_pre_split_config(
|
||||
num_tokens: int, hidden_size: int, hc_mult: int
|
||||
) -> tuple[int, int, int] | None:
|
||||
"""Pick ``(tile_n, n_splits, n_thr)`` for the fused post + pre-norm GEMM.
|
||||
|
||||
Returns None when a separate post kernel followed by a split-k GEMM is the
|
||||
better choice, or when the hidden size does not divide evenly across the
|
||||
fused kernel's block. One source of truth for the dispatch decision, the
|
||||
compile key and the launch, which must agree.
|
||||
"""
|
||||
if num_tokens > _FUSED_POST_PRE_MAX_TOKENS:
|
||||
return None
|
||||
n_thr = _FUSED_POST_PRE_N_THR
|
||||
if hidden_size % n_thr:
|
||||
return None
|
||||
# The projection tiles supply the parallelism a small token count cannot,
|
||||
# so the tile grows with the batch: 1.3x at one token and 1.03x at 32
|
||||
# against a split-k GEMM given the split its own estimator computes.
|
||||
if num_tokens < 16:
|
||||
tile_n, n_splits = 2, 8
|
||||
else:
|
||||
tile_n, n_splits = 6, 8
|
||||
# The kernel drops projection tiles and k-slices it cannot fill evenly.
|
||||
mix_size = hc_mult * (hc_mult + 2)
|
||||
while tile_n > 1 and mix_size % tile_n:
|
||||
tile_n -= 1
|
||||
while n_splits > 1 and hidden_size % (n_splits * n_thr):
|
||||
n_splits //= 2
|
||||
return tile_n, n_splits, n_thr
|
||||
|
||||
|
||||
def require_fused_post_pre_config(
|
||||
num_tokens: int, hidden_size: int, hc_mult: int
|
||||
) -> tuple[int, int, int]:
|
||||
"""The config for a shape the caller has already committed to fusing."""
|
||||
config = mhc_fused_post_pre_split_config(num_tokens, hidden_size, hc_mult)
|
||||
if config is None:
|
||||
raise ValueError(
|
||||
"the fused mHC post + pre-norm GEMM does not cover num_tokens="
|
||||
f"{num_tokens} at hidden_size={hidden_size}"
|
||||
)
|
||||
return config
|
||||
|
||||
|
||||
def mhc_fused_post_pre_splits(hidden_size: int, hc_mult: int) -> tuple[int, ...]:
|
||||
"""Every split-k factor the fused post + pre-norm GEMM path can pick."""
|
||||
configs = (
|
||||
mhc_fused_post_pre_split_config(num_tokens, hidden_size, hc_mult)
|
||||
for num_tokens in range(1, _FUSED_POST_PRE_MAX_TOKENS + 1)
|
||||
)
|
||||
return tuple(sorted({config[1] for config in configs if config is not None}))
|
||||
|
||||
|
||||
@tilelang_jit
|
||||
@@ -53,6 +112,7 @@ def mhc_pre_big_fuse_tilelang(
|
||||
layer_input,
|
||||
pre_mix_in,
|
||||
pre_mix_out,
|
||||
aux_out,
|
||||
hidden_size: int,
|
||||
rms_eps: float,
|
||||
hc_pre_eps: float,
|
||||
@@ -64,6 +124,7 @@ def mhc_pre_big_fuse_tilelang(
|
||||
use_pre_mix_in: bool = False,
|
||||
save_pre_mix: bool = False,
|
||||
rms_numel: int = 0,
|
||||
write_aux: bool = False,
|
||||
):
|
||||
"""Fuse coefficient generation and residual collapse after the projection.
|
||||
|
||||
@@ -88,6 +149,7 @@ def mhc_pre_big_fuse_tilelang(
|
||||
|
||||
pre_mix_in: T.Tensor[[num_tokens, hc_mult], T.float32] # type: ignore[no-redef, valid-type]
|
||||
pre_mix_out: T.Tensor[[num_tokens, hc_mult], T.float32] # type: ignore[no-redef, valid-type]
|
||||
aux_out: T.Tensor[[num_tokens, hidden_size], T.bfloat16] # type: ignore[no-redef, valid-type]
|
||||
|
||||
with T.Kernel(num_tokens, threads=96) as i:
|
||||
if ENABLE_PDL:
|
||||
@@ -188,11 +250,24 @@ def mhc_pre_big_fuse_tilelang(
|
||||
|
||||
ol = T.alloc_fragment(hidden_block, T.float32)
|
||||
T.clear(ol)
|
||||
if write_aux:
|
||||
# Aux consumers (draft models) take the plain stream mean
|
||||
# of the same residual this collapse reads.
|
||||
aux = T.alloc_fragment(hidden_block, T.float32)
|
||||
T.clear(aux)
|
||||
|
||||
for i_hc in T.serial(hc_mult):
|
||||
pre = pre_mix_shared[i_hc]
|
||||
for i1_h in T.Parallel(hidden_block):
|
||||
ol[i1_h] += pre * xl[i_hc, i1_h]
|
||||
if write_aux:
|
||||
aux[i1_h] += xl[i_hc, i1_h]
|
||||
|
||||
if write_aux:
|
||||
for i1_h in T.Parallel(hidden_block):
|
||||
aux_out[i, i0_h * hidden_block + i1_h] = T.bfloat16(
|
||||
aux[i1_h] / hc_mult
|
||||
)
|
||||
|
||||
T.copy(ol, layer_input[i, i0_h * hidden_block])
|
||||
|
||||
@@ -216,6 +291,7 @@ def mhc_pre_big_fuse_with_norm_tilelang(
|
||||
norm_weight,
|
||||
pre_mix_in,
|
||||
pre_mix_out,
|
||||
aux_out,
|
||||
hidden_size: int,
|
||||
rms_eps: float,
|
||||
hc_pre_eps: float,
|
||||
@@ -229,6 +305,7 @@ def mhc_pre_big_fuse_with_norm_tilelang(
|
||||
use_pre_mix_in: bool = False,
|
||||
save_pre_mix: bool = False,
|
||||
rms_numel: int = 0,
|
||||
write_aux: bool = False,
|
||||
):
|
||||
num_tokens = T.dynamic("num_tokens")
|
||||
hc_mult3 = hc_mult * (2 + hc_mult)
|
||||
@@ -250,6 +327,7 @@ def mhc_pre_big_fuse_with_norm_tilelang(
|
||||
|
||||
pre_mix_in: T.Tensor[[num_tokens, hc_mult], T.float32] # type: ignore[no-redef, valid-type]
|
||||
pre_mix_out: T.Tensor[[num_tokens, hc_mult], T.float32] # type: ignore[no-redef, valid-type]
|
||||
aux_out: T.Tensor[[num_tokens, hidden_size], T.bfloat16] # type: ignore[no-redef, valid-type]
|
||||
|
||||
with T.Kernel(num_tokens, threads=96) as i:
|
||||
rms = T.alloc_fragment(1, T.float32)
|
||||
@@ -345,11 +423,24 @@ def mhc_pre_big_fuse_with_norm_tilelang(
|
||||
|
||||
ol = T.alloc_fragment(hidden_block, T.float32)
|
||||
T.clear(ol)
|
||||
if write_aux:
|
||||
# Aux consumers (draft models) take the plain stream mean
|
||||
# of the same residual this collapse reads.
|
||||
aux = T.alloc_fragment(hidden_block, T.float32)
|
||||
T.clear(aux)
|
||||
|
||||
for i_hc in T.serial(hc_mult):
|
||||
pre = pre_mix_shared[i_hc]
|
||||
for i1_h in T.Parallel(hidden_block):
|
||||
ol[i1_h] += pre * xl[i_hc, i1_h]
|
||||
if write_aux:
|
||||
aux[i1_h] += xl[i_hc, i1_h]
|
||||
|
||||
if write_aux:
|
||||
for i1_h in T.Parallel(hidden_block):
|
||||
aux_out[i, i0_h * hidden_block + i1_h] = T.bfloat16(
|
||||
aux[i1_h] / hc_mult
|
||||
)
|
||||
|
||||
if save_pre_mix:
|
||||
# Keep the BF16 boundary before the delayed input RMSNorm.
|
||||
@@ -1211,9 +1302,17 @@ class MhcPreBigFuseTileLangKernel(
|
||||
middle_args = (residual_out, *output_args, norm_weight)
|
||||
elif compile_key.use_norm_weight:
|
||||
assert norm_weight is not None
|
||||
middle_args = (*output_args, norm_weight, post_mix, post_mix)
|
||||
# layer_input stands in for the aux buffer on both epilogues: same
|
||||
# shape and dtype, and write_aux is off here so it is never written.
|
||||
middle_args = (
|
||||
*output_args,
|
||||
norm_weight,
|
||||
post_mix,
|
||||
post_mix,
|
||||
layer_input,
|
||||
)
|
||||
else:
|
||||
middle_args = (*output_args, post_mix, post_mix)
|
||||
middle_args = (*output_args, post_mix, post_mix, layer_input)
|
||||
norm_eps_args = (compile_key.norm_eps,) if compile_key.use_norm_weight else ()
|
||||
return (
|
||||
*common_args,
|
||||
@@ -1247,8 +1346,14 @@ class MhcPreBigFuseTileLangKernel(
|
||||
if use_pre_gemm_splits
|
||||
else n_splits
|
||||
)
|
||||
fused_n_splits = _mhc_fused_n_splits(num_tokens, hidden_size)
|
||||
actual_n_splits = fused_n_splits if use_fused_tilelang else pre_gemm_n_splits
|
||||
# The epilogue reduces over whatever the fused kernel split the GEMM
|
||||
# into, so both have to read the same config.
|
||||
fused_config = mhc_fused_post_pre_split_config(num_tokens, hidden_size, hc_mult)
|
||||
actual_n_splits = (
|
||||
fused_config[1]
|
||||
if use_fused_tilelang and fused_config is not None
|
||||
else pre_gemm_n_splits
|
||||
)
|
||||
actual_norm_eps = broadcast_norm_eps if is_broadcast else norm_eps
|
||||
actual_use_norm_weight = use_norm_weight or is_broadcast
|
||||
return self.CompileKey(
|
||||
@@ -1540,6 +1645,7 @@ class MhcFusedTileLangKernel(
|
||||
hc_mult: int
|
||||
n_splits: int
|
||||
tile_n: int
|
||||
n_thr: int
|
||||
|
||||
@staticmethod
|
||||
def kernel() -> Any:
|
||||
@@ -1552,14 +1658,15 @@ class MhcFusedTileLangKernel(
|
||||
hidden_size: int,
|
||||
hc_mult: int,
|
||||
) -> CompileKey:
|
||||
# TODO(gnovack): investigate autotuning these heuristics
|
||||
tile_n = 2 if num_tokens < 8 else 3
|
||||
n_splits = _mhc_fused_n_splits(num_tokens, hidden_size)
|
||||
# Subscripts rather than an unpack: the warmup tracer parses this body
|
||||
# and allows only plain assignments before the return.
|
||||
config = require_fused_post_pre_config(num_tokens, hidden_size, hc_mult)
|
||||
return self.CompileKey(
|
||||
hidden_size=hidden_size,
|
||||
hc_mult=hc_mult,
|
||||
n_splits=n_splits,
|
||||
tile_n=tile_n,
|
||||
n_splits=config[1],
|
||||
tile_n=config[0],
|
||||
n_thr=config[2],
|
||||
)
|
||||
|
||||
def get_warmup_keys(
|
||||
@@ -1574,11 +1681,11 @@ class MhcFusedTileLangKernel(
|
||||
num_tokens=WarmupIntRange(1, max_tokens + 1),
|
||||
hidden_size=hidden_size,
|
||||
hc_mult=hc_mult,
|
||||
_when=lambda *, num_tokens: num_tokens <= 16,
|
||||
_when=lambda *, num_tokens: num_tokens <= _FUSED_POST_PRE_MAX_TOKENS,
|
||||
)
|
||||
|
||||
def warmup_inputs(self, compile_key: CompileKey) -> dict[str, Any]:
|
||||
num_tokens = 1 if compile_key.tile_n == 2 else 8
|
||||
num_tokens = 1 if compile_key.tile_n == 2 else 16
|
||||
hidden_size = compile_key.hidden_size
|
||||
hc_mult = compile_key.hc_mult
|
||||
hc_mult3 = hc_mult * (2 + hc_mult)
|
||||
@@ -1617,8 +1724,9 @@ class MhcFusedTileLangKernel(
|
||||
hc_mult3: int,
|
||||
) -> TileLangLaunchSpec:
|
||||
num_tokens = residual_in.shape[0]
|
||||
tile_n = 2 if num_tokens < 8 else 3
|
||||
n_splits = _mhc_fused_n_splits(num_tokens, hidden_size)
|
||||
tile_n, n_splits, n_thr = require_fused_post_pre_config(
|
||||
num_tokens, hidden_size, hc_mult
|
||||
)
|
||||
yp_out = residual_in.new_empty(
|
||||
(n_splits, num_tokens, hc_mult3), dtype=torch.float32
|
||||
)
|
||||
@@ -1639,7 +1747,7 @@ class MhcFusedTileLangKernel(
|
||||
hidden_size,
|
||||
hc_mult3,
|
||||
),
|
||||
dict(tile_n=tile_n, split_k=n_splits),
|
||||
dict(n_thr=n_thr, tile_n=tile_n),
|
||||
(yp_out, rp_out, residual_out),
|
||||
)
|
||||
|
||||
|
||||
@@ -36,23 +36,33 @@ class MHCPreNormKernel(VllmJitKernel["MHCPreNormKernel.CompileKey"]):
|
||||
use_pre_mix_in: bool
|
||||
rms_numel: int
|
||||
save_pre_mix: bool = True
|
||||
write_aux: bool = False
|
||||
|
||||
kernel: Any = staticmethod(mhc_pre_big_fuse_with_norm_tilelang)
|
||||
|
||||
def dispatch(self, *, n_splits, **fields) -> CompileKey: # type: ignore[override]
|
||||
return self.CompileKey(n_splits=n_splits, **fields)
|
||||
|
||||
def get_warmup_keys(self, *, max_tokens: int, **fields) -> list[CompileKey]:
|
||||
# The split heuristic changes only at 64-token boundaries.
|
||||
splits = (
|
||||
sorted(
|
||||
def get_warmup_keys(
|
||||
self,
|
||||
*,
|
||||
max_tokens: int,
|
||||
extra_splits: Iterable[int] = (),
|
||||
**fields,
|
||||
) -> list[CompileKey]:
|
||||
# The split heuristic changes only at 64-token boundaries. Callers that
|
||||
# reach this kernel through another GEMM (the fused post + pre-norm
|
||||
# GEMM) pass the splits that GEMM picks in extra_splits.
|
||||
splits = sorted(
|
||||
set(extra_splits)
|
||||
| (
|
||||
{
|
||||
compute_mhc_pre_num_splits(fields["rms_numel"], num_tokens)
|
||||
for num_tokens in range(1, max_tokens + 1, 64)
|
||||
}
|
||||
if is_deep_gemm_supported()
|
||||
else {1}
|
||||
)
|
||||
if is_deep_gemm_supported()
|
||||
else [1]
|
||||
)
|
||||
return self._trace_dispatch(self.dispatch)(n_splits=splits, **fields)
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
from vllm import ir
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.custom_op import CustomOp
|
||||
from vllm.platforms import CpuArchEnum, current_platform
|
||||
@@ -332,24 +333,11 @@ class GeluAndMulSparse(CustomOp):
|
||||
raise ValueError("activation_sparsity is 0.0. Please use GeluAndMul.")
|
||||
target_sparsity_tensor = torch.tensor(activation_sparsity, dtype=torch.float32)
|
||||
normal_dist = torch.distributions.normal.Normal(0, 1)
|
||||
self.std_multiplier = normal_dist.icdf(target_sparsity_tensor)
|
||||
|
||||
def _gaussian_topk(self, x: torch.Tensor) -> torch.Tensor:
|
||||
"""Get % sparse percentile of the Gaussian distribution."""
|
||||
# NOTE(rob): for TP>1, we could all-gather to get the means/std.
|
||||
# But we do not do this because in expectation they are the same
|
||||
# and in practice the eval scores are good without gathering.
|
||||
mean = torch.mean(x, dim=-1, keepdim=True)
|
||||
std = torch.std(x, dim=-1, keepdim=True, unbiased=False)
|
||||
cutoff_x = mean + std * self.std_multiplier
|
||||
return nn.functional.relu(x - cutoff_x)
|
||||
self.std_multiplier = normal_dist.icdf(target_sparsity_tensor).item()
|
||||
|
||||
def forward_native(self, x: torch.Tensor) -> torch.Tensor:
|
||||
"""PyTorch-native implementation equivalent to forward()."""
|
||||
d = x.shape[-1] // 2
|
||||
out = self._gaussian_topk(x[..., :d])
|
||||
out = F.gelu(out, approximate=self.approximate)
|
||||
return out * x[..., d:]
|
||||
return ir.ops.gelu_and_mul_sparse(x, self.std_multiplier, self.approximate)
|
||||
|
||||
def forward_cuda(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return self.forward_native(x)
|
||||
|
||||
@@ -269,11 +269,11 @@ from vllm.utils.torch_utils import (
|
||||
LayerNameType,
|
||||
_encode_layer_name,
|
||||
_resolve_layer_name,
|
||||
async_tensor_h2d,
|
||||
direct_register_custom_op,
|
||||
get_dtype_size,
|
||||
is_quantized_kv_cache,
|
||||
kv_cache_dtype_str_to_dtype,
|
||||
np_to_pinned_tensor,
|
||||
)
|
||||
from vllm.v1.attention.backend import (
|
||||
AttentionBackend,
|
||||
@@ -1980,11 +1980,6 @@ def plan_mla_context_chunks(
|
||||
return plans
|
||||
|
||||
|
||||
def _flat_int32(values: list[int] | np.ndarray) -> torch.Tensor:
|
||||
"""Pinned int32 CPU tensor backing one concatenated per-chunk field."""
|
||||
return np_to_pinned_tensor(np.asarray(values, dtype=np.int32))
|
||||
|
||||
|
||||
def align_mla_chunked_context_workspace_size(
|
||||
vllm_config: VllmConfig,
|
||||
workspace_size: int,
|
||||
@@ -2161,24 +2156,28 @@ def build_mla_chunked_context_metadata(
|
||||
token_offset += num_tokens
|
||||
local_token_offset += num_local_tokens
|
||||
|
||||
seq_lens_cpu = _flat_int32(seq_lens_flat)
|
||||
starts_and_context_lens = _flat_int32(starts_flat + context_lens).to(
|
||||
device, non_blocking=True
|
||||
seq_lens_cpu = torch.tensor(
|
||||
seq_lens_flat, dtype=torch.int32, device="cpu", pin_memory=PIN_MEMORY
|
||||
)
|
||||
starts_and_context_lens = async_tensor_h2d(
|
||||
starts_flat + context_lens, device=device, dtype=torch.int32
|
||||
)
|
||||
starts = starts_and_context_lens[: len(starts_flat)]
|
||||
context_lens_gpu = starts_and_context_lens[len(starts_flat) :]
|
||||
cu_seq_lens = _flat_int32(cu_seq_lens_flat).to(device, non_blocking=True)
|
||||
cu_seqlens_q = _flat_int32(cu_seqlens_q_flat).to(device, non_blocking=True)
|
||||
token_to_seq = _flat_int32(np.concatenate(token_to_seq_parts)).to(
|
||||
device, non_blocking=True
|
||||
cu_seq_lens = async_tensor_h2d(cu_seq_lens_flat, device=device, dtype=torch.int32)
|
||||
cu_seqlens_q = async_tensor_h2d(cu_seqlens_q_flat, device=device, dtype=torch.int32)
|
||||
token_to_seq = async_tensor_h2d(
|
||||
np.concatenate(token_to_seq_parts), device=device, dtype=torch.int32
|
||||
)
|
||||
if use_dcp:
|
||||
padded_local_cu_seq_lens = _flat_int32(padded_local_cu_seq_lens_flat).to(
|
||||
device, non_blocking=True
|
||||
padded_local_cu_seq_lens = async_tensor_h2d(
|
||||
padded_local_cu_seq_lens_flat, device=device, dtype=torch.int32
|
||||
)
|
||||
padded_local_token_to_seq = async_tensor_h2d(
|
||||
np.concatenate(padded_local_token_to_seq_parts),
|
||||
device=device,
|
||||
dtype=torch.int32,
|
||||
)
|
||||
padded_local_token_to_seq = _flat_int32(
|
||||
np.concatenate(padded_local_token_to_seq_parts)
|
||||
).to(device, non_blocking=True)
|
||||
|
||||
chunks: list[MLACommonPrefillMetadata.ContextChunk] = []
|
||||
for index, (plan, layout) in enumerate(zip(plans, layouts)):
|
||||
@@ -2871,6 +2870,10 @@ class MLACommonBaseImpl(MLAAttentionImpl[A], Generic[A]):
|
||||
Returns:
|
||||
Tensor of shape [..., nope_dim + pe_dim]
|
||||
"""
|
||||
if k_pe.shape[-1] == 0:
|
||||
# NoPE MLA: nothing to append, so no copy either.
|
||||
return k_nope
|
||||
|
||||
k = torch.empty(
|
||||
(*k_nope.shape[:-1], k_nope.shape[-1] + k_pe.shape[-1]),
|
||||
dtype=k_nope.dtype,
|
||||
|
||||
@@ -111,6 +111,8 @@ def _is_masked_mha_available(
|
||||
if model_dims not in (
|
||||
(128, 512, 128, 64, 128),
|
||||
(64, 512, 192, 64, 256),
|
||||
# GLM-5.3-Flash: NoPE, qk_head_dim 256 == the (192, 64, 256) kernel.
|
||||
(64, 512, 256, 0, 256),
|
||||
):
|
||||
return False
|
||||
qk_head_dim = qk_nope_head_dim + qk_rope_head_dim
|
||||
|
||||
@@ -152,8 +152,6 @@ class StaticSinkAttention(Attention, CustomOp):
|
||||
attn_backend=attn_backend,
|
||||
**kwargs,
|
||||
)
|
||||
CustomOp.__init__(self)
|
||||
|
||||
self.sink_len = sink_len
|
||||
self.sink_populated = False
|
||||
self.sink_key = None
|
||||
|
||||
@@ -468,6 +468,7 @@ class CPUExpertsFp8(mk.FusedMoEExpertsModular):
|
||||
RoutingMethodType.Renormalize,
|
||||
RoutingMethodType.RenormalizeNaive,
|
||||
RoutingMethodType.DeepseekV4,
|
||||
RoutingMethodType.DeepSeekV3,
|
||||
]
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -385,14 +385,10 @@ def rocm_aiter_fused_experts(
|
||||
|
||||
gate_mode = ""
|
||||
if activation == MoEActivation.SITU:
|
||||
# a8w4 (VLLM_ROCM_USE_AITER_MOE_SITUV2_A8W4=1) uses the gate/up-
|
||||
# interleaved (_gui_) fp8 flydsl kernels; default a16w4 SiTU stays
|
||||
# separated.
|
||||
gate_mode = (
|
||||
GateMode.INTERLEAVE.value
|
||||
if rocm_aiter_ops.is_fused_moe_situv2_a8w4_enabled()
|
||||
else GateMode.SEPARATED.value
|
||||
)
|
||||
# SiTUv2 flydsl (VLLM_ROCM_USE_AITER_MOE_SITUV2=1) uses a4w4
|
||||
# fp4 activations with separated gate/up weights (AITER #4463);
|
||||
# default a16w4 SiTU also stays separated.
|
||||
gate_mode = GateMode.SEPARATED.value
|
||||
elif quant_config.use_mxfp4_w4a16:
|
||||
gate_mode = GateMode.INTERLEAVE.value
|
||||
elif activation_interleave is not None:
|
||||
|
||||
@@ -1572,12 +1572,6 @@ def convert_weight_to_mxfp4_moe_kernel_format(
|
||||
if w2_bias is not None:
|
||||
w2_bias = w2_bias.data.to(torch.float32)
|
||||
|
||||
import os
|
||||
|
||||
# TODO: Remove this once AITER is fixed
|
||||
# Necessary for AITER side from crashing
|
||||
os.environ["AITER_BF16_FP8_MOE_BOUND"] = "0"
|
||||
|
||||
if activation == MoEActivation.SITU:
|
||||
from aiter.utility.fp4_utils import e8m0_shuffle
|
||||
|
||||
@@ -1585,9 +1579,8 @@ def convert_weight_to_mxfp4_moe_kernel_format(
|
||||
|
||||
fp4_dtype = torch.float4_e2m1fn_x2
|
||||
e8m0_dtype = torch.float8_e8m0fnu
|
||||
# a8w4 uses gate/up-interleaved flydsl kernels;
|
||||
# default a16w4 keeps the separated layout.
|
||||
guinterleave = rocm_aiter_ops.is_fused_moe_situv2_a8w4_enabled()
|
||||
# SiTUv2 flydsl uses separated gate/up layout (a4w4).
|
||||
guinterleave = False
|
||||
w13 = rocm_aiter_ops.shuffle_weight_a16w4(
|
||||
w13_weight.data.view(fp4_dtype), 16, guinterleave
|
||||
)
|
||||
@@ -1606,6 +1599,14 @@ def convert_weight_to_mxfp4_moe_kernel_format(
|
||||
w2.is_shuffled = True
|
||||
return (w13, w2, w13_scale, w2_scale, w13_bias, w2_bias)
|
||||
|
||||
import os
|
||||
|
||||
# Interleaved a16w4 only (DeepSeekV4 etc.). AITER uses this bound to
|
||||
# pick bf16 vs fp8 activations when gate_mode is INTERLEAVE. SiTUv2
|
||||
# a4w4 is separated and selects q_dtype_a independently, so the bound
|
||||
# is unused on that path.
|
||||
os.environ["AITER_BF16_FP8_MOE_BOUND"] = "0"
|
||||
|
||||
from aiter.ops.shuffle import shuffle_scale as _shuf_s
|
||||
from aiter.ops.shuffle import shuffle_weight as _shuf_w
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@ from vllm.triton_utils import tl, triton
|
||||
from vllm.utils.math_utils import round_up
|
||||
from vllm.v1.worker.ubatching import (
|
||||
dbo_current_ubatch_id,
|
||||
dbo_enabled,
|
||||
)
|
||||
|
||||
|
||||
@@ -89,8 +90,10 @@ class DeepEPV2PrepareAndFinalize(mk.FusedMoEPrepareAndFinalizeModular):
|
||||
use cudagraphs anyway
|
||||
- Provides expert_tokens_meta for efficient batched expert kernels
|
||||
|
||||
Both modes use async_with_compute_stream=False (synchronous from
|
||||
caller's perspective). The ElasticBuffer handles comm internally.
|
||||
Dispatch always uses async_with_compute_stream=False. finalize_async
|
||||
issues the combine with async_with_compute_stream=True (except under
|
||||
DBO) so the modular kernel can overlap the shared-expert FFN with the
|
||||
combine a2a; the returned receiver joins via a device-side event wait.
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
@@ -465,15 +468,31 @@ class DeepEPV2PrepareAndFinalize(mk.FusedMoEPrepareAndFinalizeModular):
|
||||
f"got {fused_expert_output.dtype}"
|
||||
)
|
||||
|
||||
# DBO drives its own hook/receiver schedule; keep the combine
|
||||
# synchronous there (the receiver then only performs the copy).
|
||||
combine_async = do_async and not dbo_enabled()
|
||||
combined_x, _, event = self.buffer.combine(
|
||||
x=fused_expert_output,
|
||||
handle=handle,
|
||||
topk_weights=None,
|
||||
async_with_compute_stream=False,
|
||||
async_with_compute_stream=combine_async,
|
||||
allocate_on_comm_stream=combine_async,
|
||||
)
|
||||
|
||||
output.copy_(combined_x, non_blocking=True)
|
||||
return None
|
||||
if do_async:
|
||||
# The combine ran on DeepEP's comm stream; the modular kernel
|
||||
# issues the shared-expert FFN before calling the receiver, which
|
||||
# joins via a device-side cudaStreamWaitEvent (no host sync, so
|
||||
# this is safe inside a captured region).
|
||||
def _receiver():
|
||||
if event.event is not None:
|
||||
event.current_stream_wait()
|
||||
output.copy_(combined_x, non_blocking=True)
|
||||
|
||||
return _receiver
|
||||
else:
|
||||
output.copy_(combined_x, non_blocking=True)
|
||||
return None
|
||||
|
||||
def finalize_async(
|
||||
self,
|
||||
@@ -484,16 +503,17 @@ class DeepEPV2PrepareAndFinalize(mk.FusedMoEPrepareAndFinalizeModular):
|
||||
apply_router_weight_on_input: bool,
|
||||
weight_and_reduce_impl: mk.TopKWeightAndReduce,
|
||||
) -> Callable:
|
||||
self._finalize(
|
||||
receiver = self._finalize(
|
||||
output,
|
||||
fused_expert_output,
|
||||
topk_weights,
|
||||
topk_ids,
|
||||
apply_router_weight_on_input,
|
||||
weight_and_reduce_impl,
|
||||
False,
|
||||
True,
|
||||
)
|
||||
return lambda: None
|
||||
assert receiver is not None
|
||||
return receiver
|
||||
|
||||
def finalize(
|
||||
self,
|
||||
|
||||
@@ -457,9 +457,18 @@ class MoERunner(MoERunnerInterface):
|
||||
Latent MoE output transforms may contain non-linear ops, e.g. RMSNorm.
|
||||
TP partial routed outputs must be summed in latent space before such
|
||||
transforms are applied.
|
||||
|
||||
A transform that commutes with the TP sum is exempt: if
|
||||
``sum_r T(x_r) == T(sum_r x_r)``, applying the transform to the local
|
||||
partial output and letting the existing late all-reduce sum the
|
||||
combined result is equivalent, and costs one collective instead of two.
|
||||
Such a transform opts out by setting ``reduce_commutative = True``.
|
||||
The default is False, so transforms that do not declare themselves
|
||||
keep being reduced early.
|
||||
"""
|
||||
if (
|
||||
self.routed_output_transform is not None
|
||||
and not getattr(self.routed_output_transform, "reduce_commutative", False)
|
||||
and not self.moe_config.is_sequence_parallel
|
||||
and (self.moe_config.tp_size > 1 or self.moe_config.ep_size > 1)
|
||||
and not fused_output_is_reduced
|
||||
|
||||
@@ -5,21 +5,27 @@ Producer side of the QuantizedActivation contract for activation layers.
|
||||
|
||||
Given an activation module and the downstream linear it feeds, fuse the
|
||||
activation with that linear's input quantization into a single kernel when the
|
||||
linear advertises a consumable input_quant_key (see quant_activation.py).
|
||||
linear advertises a consumable input quantization key (see quant_activation.py).
|
||||
Falls back to the plain activation when nothing matches, so a model forward can
|
||||
always call maybe_fused_act_quant unconditionally.
|
||||
|
||||
This is the manual-fusion counterpart to ActivationQuantFusionPass: when fusion
|
||||
fires here the silu_and_mul pattern is already consumed, so the compiler pass
|
||||
finds nothing to rewrite and the two never double-fuse.
|
||||
fires here, the activation and quantization are already consumed, so a compiler
|
||||
pass cannot fuse the same boundary again.
|
||||
"""
|
||||
|
||||
from collections.abc import Callable
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.model_executor.layers.activation import SiluAndMul
|
||||
from vllm.model_executor.layers.fusion.quant_activation import QuantizedActivation
|
||||
from vllm.model_executor.layers.activation import ReLUSquaredActivation, SiluAndMul
|
||||
from vllm.model_executor.layers.fusion.quant_activation import (
|
||||
QuantizedActivation,
|
||||
get_input_quant_key,
|
||||
)
|
||||
from vllm.model_executor.layers.fusion.relu2_fp8_quant import (
|
||||
relu_squared_static_fp8_quant,
|
||||
)
|
||||
from vllm.model_executor.layers.linear import LinearBase
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import (
|
||||
QuantKey,
|
||||
@@ -139,12 +145,46 @@ def _silu_and_mul_nvfp4_dynamic(
|
||||
)
|
||||
|
||||
|
||||
# (activation module type, consumer input_quant_key) -> fused producer.
|
||||
# Mirrors ActivationQuantFusionPass.FUSED_OPS; add a row to migrate a scheme.
|
||||
# (activation module type, consumer input quantization key) -> fused producer.
|
||||
# Add a row for each supported manual producer.
|
||||
_FUSED_ACT_QUANT: dict[tuple[type, QuantKey], Callable] = {
|
||||
(SiluAndMul, kFp8StaticTensorSym): _silu_and_mul_fp8_static,
|
||||
}
|
||||
|
||||
|
||||
def _relu_squared_static_fp8_quant_supported(
|
||||
act_fn: torch.nn.Module,
|
||||
x: torch.Tensor,
|
||||
linear: LinearBase,
|
||||
) -> bool:
|
||||
"""Return whether the ReLU2 static-FP8 producer can consume this input."""
|
||||
scale = getattr(linear, "input_scale", None)
|
||||
return (
|
||||
isinstance(act_fn, ReLUSquaredActivation)
|
||||
and x.is_cuda
|
||||
and x.dtype == torch.bfloat16
|
||||
and x.is_contiguous()
|
||||
and isinstance(scale, torch.Tensor)
|
||||
and scale.dtype == torch.float32
|
||||
and scale.device == x.device
|
||||
and scale.numel() == 1
|
||||
)
|
||||
|
||||
|
||||
# Optional per-entry predicates preserve the unconditional fallback contract
|
||||
# for producers whose supported inputs are narrower than their registry key.
|
||||
_FUSED_ACT_QUANT_SUPPORT: dict[
|
||||
tuple[type, QuantKey], Callable[[torch.nn.Module, torch.Tensor, LinearBase], bool]
|
||||
] = {}
|
||||
|
||||
# This path is validated on SM90 and newer CUDA devices.
|
||||
if current_platform.is_cuda() and current_platform.has_device_capability(90):
|
||||
_RELU2_STATIC_FP8_KEY = (ReLUSquaredActivation, kFp8StaticTensorSym)
|
||||
_FUSED_ACT_QUANT[_RELU2_STATIC_FP8_KEY] = relu_squared_static_fp8_quant
|
||||
_FUSED_ACT_QUANT_SUPPORT[_RELU2_STATIC_FP8_KEY] = (
|
||||
_relu_squared_static_fp8_quant_supported
|
||||
)
|
||||
|
||||
# Add CUDA-specific entries for dynamic block quantization
|
||||
if current_platform.is_cuda_alike():
|
||||
_FUSED_ACT_QUANT[(SiluAndMul, kFp8Dynamic128Sym)] = _silu_and_mul_fp8_dynamic_128
|
||||
@@ -161,12 +201,14 @@ def maybe_fused_act_quant(
|
||||
) -> "torch.Tensor | QuantizedActivation":
|
||||
"""Apply act_fn, fusing the downstream linear's input quant when possible.
|
||||
|
||||
Returns a QuantizedActivation when a fused kernel matches
|
||||
(act_fn, linear.input_quant_key), else the plain activated tensor.
|
||||
Returns a QuantizedActivation when a fused kernel matches the activation and
|
||||
the consumer's effective input quantization key, else the plain activation.
|
||||
"""
|
||||
key = getattr(linear, "input_quant_key", None)
|
||||
key = get_input_quant_key(linear)
|
||||
if key is not None:
|
||||
producer = _FUSED_ACT_QUANT.get((type(act_fn), key))
|
||||
if producer is not None:
|
||||
registry_key = (type(act_fn), key)
|
||||
producer = _FUSED_ACT_QUANT.get(registry_key)
|
||||
support = _FUSED_ACT_QUANT_SUPPORT.get(registry_key)
|
||||
if producer is not None and (support is None or support(act_fn, x, linear)):
|
||||
return producer(x, linear)
|
||||
return act_fn(x)
|
||||
|
||||
@@ -5,7 +5,9 @@ A QuantizedActivation is a pre-quantized activation produced by a fused kernel
|
||||
and consumed directly by a linear layer, letting the layer skip its own input
|
||||
quantization. A linear advertises the key its kernel can consume via
|
||||
expose_input_quant_key; the kernel validates and reads the activation via
|
||||
as_quantized_activation.
|
||||
as_quantized_activation. Producers query the effective capability through
|
||||
get_input_quant_key, which hides the key when another consumer branch needs the
|
||||
original activation.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass, replace
|
||||
@@ -46,12 +48,11 @@ class QuantizedActivation:
|
||||
|
||||
|
||||
def expose_input_quant_key(layer: torch.nn.Module, kernel) -> None:
|
||||
"""Advertise the kernel's pre-quantized input key on the layer, if any.
|
||||
"""Store the kernel's pre-quantized input key on the layer, if any.
|
||||
|
||||
This is the bridge from a kernel's input_quant_key() to the
|
||||
layer.input_quant_key attribute that fusion call sites read. The attribute
|
||||
is left unset when the kernel quantizes its own input, so non-supporting
|
||||
backends never receive a QuantizedActivation.
|
||||
This is the bridge from a kernel's input_quant_key() to the layer capability
|
||||
that fusion call sites read through get_input_quant_key. The raw key is left
|
||||
unset when the kernel quantizes its own input.
|
||||
|
||||
TODO(mgoin): Producers also need the consumer's quantization scales (e.g.
|
||||
static input scale, global scale). Expose those here as well so producers
|
||||
@@ -59,7 +60,14 @@ def expose_input_quant_key(layer: torch.nn.Module, kernel) -> None:
|
||||
"""
|
||||
key = kernel.input_quant_key()
|
||||
if key is not None:
|
||||
layer.input_quant_key = key
|
||||
layer._input_quant_key = key
|
||||
|
||||
|
||||
def get_input_quant_key(layer: torch.nn.Module) -> QuantKey | None:
|
||||
"""Return the pre-quantized input key the complete layer can consume."""
|
||||
if getattr(layer, "requires_unquantized_input", False):
|
||||
return None
|
||||
return getattr(layer, "_input_quant_key", None)
|
||||
|
||||
|
||||
def as_quantized_activation(
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.model_executor.layers.fusion.quant_activation import QuantizedActivation
|
||||
from vllm.model_executor.layers.linear import LinearBase
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import (
|
||||
get_fp8_min_max,
|
||||
kFp8StaticTensorSym,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import tl, triton
|
||||
|
||||
_FP8_MIN, _FP8_MAX = get_fp8_min_max()
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _relu_squared_static_fp8_quant_kernel(
|
||||
x_ptr,
|
||||
scale_ptr,
|
||||
output_ptr,
|
||||
num_elements,
|
||||
FP8_MIN: tl.constexpr,
|
||||
FP8_MAX: tl.constexpr,
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
):
|
||||
offsets = tl.program_id(0) * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
|
||||
mask = offsets < num_elements
|
||||
x = tl.load(x_ptr + offsets, mask=mask, other=0.0).to(tl.float32)
|
||||
input_is_nan = x != x
|
||||
relu = tl.maximum(x, 0.0)
|
||||
# Preserve the standalone ReLU2 kernel's BF16 output boundary.
|
||||
activated = (relu * relu).to(tl.bfloat16).to(tl.float32)
|
||||
# Match O2's Inductor-compiled QuantFP8 reciprocal-then-multiply.
|
||||
quantized = activated * (1.0 / tl.load(scale_ptr))
|
||||
quantized = tl.maximum(tl.minimum(quantized, FP8_MAX), FP8_MIN)
|
||||
# Match the O2 native chain by preserving NaN through the FP8 conversion.
|
||||
quantized = tl.where(input_is_nan, x, quantized)
|
||||
tl.store(output_ptr + offsets, quantized, mask=mask)
|
||||
|
||||
|
||||
def relu_squared_static_fp8_quant(
|
||||
x: torch.Tensor, linear: LinearBase
|
||||
) -> QuantizedActivation:
|
||||
"""BF16 ReLU2 followed by static per-tensor FP8 quantization."""
|
||||
assert x.dtype == torch.bfloat16
|
||||
assert x.is_contiguous()
|
||||
scale = linear.input_scale
|
||||
assert scale.dtype == torch.float32
|
||||
assert x.device == scale.device
|
||||
assert scale.numel() == 1
|
||||
|
||||
output = torch.empty_like(x, dtype=current_platform.fp8_dtype())
|
||||
if x.numel() != 0:
|
||||
block_size = min(triton.next_power_of_2(x.shape[-1]), 2048)
|
||||
num_warps = min(max(block_size // 256, 1), 4)
|
||||
grid = lambda meta: (triton.cdiv(x.numel(), meta["BLOCK_SIZE"]),)
|
||||
_relu_squared_static_fp8_quant_kernel[grid](
|
||||
x,
|
||||
scale,
|
||||
output,
|
||||
x.numel(),
|
||||
FP8_MIN=_FP8_MIN,
|
||||
FP8_MAX=_FP8_MAX,
|
||||
BLOCK_SIZE=block_size,
|
||||
num_warps=num_warps,
|
||||
)
|
||||
|
||||
return QuantizedActivation(
|
||||
data=output,
|
||||
scale=scale,
|
||||
orig_dtype=x.dtype,
|
||||
orig_shape=x.shape,
|
||||
quant_key=kFp8StaticTensorSym,
|
||||
)
|
||||
@@ -20,9 +20,8 @@ Constraints:
|
||||
- x / residual must be bfloat16; hc_fn weights stay float32 (the checkpoint
|
||||
keeps them out of fp8 quantization via modules_to_not_convert)
|
||||
|
||||
The fused modules own no parameters: they hold references to the weights of the
|
||||
eager layer they replace, bound in ``process_weights_after_loading`` (invoked
|
||||
generically for every ``HpcModule`` by the model loader).
|
||||
The fused modules own no parameters: their forwards read the weights of the
|
||||
eager layer they replace directly via the captured owner reference.
|
||||
|
||||
NOTE: The reference implementation also offers a cross-layer post+pre fusion
|
||||
(``HpcIHCPostPre``) that folds one segment's post into the next segment's pre.
|
||||
@@ -147,41 +146,26 @@ class HpcIHCPre(HpcModule):
|
||||
object.__setattr__(self, "_fallback_op", fallback_op)
|
||||
# Same anti-cycle idiom for the fused RMSNorm owner (a sibling module).
|
||||
object.__setattr__(self, "_norm_owner", norm_owner)
|
||||
self.weight = None
|
||||
self.hc_scale = None
|
||||
self.hc_base = None
|
||||
self.rms_weight = None
|
||||
self.rms_eps = 0.0
|
||||
|
||||
@classmethod
|
||||
def support(cls, hc_mult: int, hidden_size: int) -> bool:
|
||||
return _ihc_supported(hc_mult, hidden_size)
|
||||
|
||||
def process_weights_after_loading(self, model=None):
|
||||
# hc_fn is a ReplicatedLinear whose weight is [2 * hc_mult, hc_mult * d].
|
||||
# It stays float32 -- the HPC kernel consumes fp32 weights directly, so
|
||||
# there is no conversion (and no precision loss) here.
|
||||
owner = self._fallback_op
|
||||
self.weight = owner.hc_fn.weight
|
||||
self.hc_scale = owner.hc_scale
|
||||
self.hc_base = owner.hc_base
|
||||
if self._norm_owner is not None:
|
||||
self.rms_weight = self._norm_owner.weight
|
||||
self.rms_eps = self._norm_owner.variance_epsilon
|
||||
|
||||
def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
import hpc
|
||||
|
||||
owner = self._fallback_op
|
||||
norm_owner = self._norm_owner
|
||||
return hpc.fuse_ihc_pre(
|
||||
x,
|
||||
self.weight,
|
||||
self.hc_scale,
|
||||
self.hc_base,
|
||||
owner.hc_fn.weight,
|
||||
owner.hc_scale,
|
||||
owner.hc_base,
|
||||
self.norm_eps,
|
||||
self.hc_eps,
|
||||
self.magnitude,
|
||||
self.rms_weight,
|
||||
self.rms_eps,
|
||||
norm_owner.weight if norm_owner is not None else None,
|
||||
norm_owner.variance_epsilon if norm_owner is not None else 0.0,
|
||||
)
|
||||
|
||||
|
||||
@@ -233,29 +217,20 @@ class HpcIHCHead(HpcModule):
|
||||
self.norm_eps = norm_eps
|
||||
# See HpcIHCPre: keep the owner out of the module tree.
|
||||
object.__setattr__(self, "_fallback_op", fallback_op)
|
||||
self.weight = None
|
||||
self.hc_scale = None
|
||||
self.hc_base = None
|
||||
|
||||
@classmethod
|
||||
def support(cls, hc_mult: int, hidden_size: int) -> bool:
|
||||
return _ihc_supported(hc_mult, hidden_size)
|
||||
|
||||
def process_weights_after_loading(self, model=None):
|
||||
# hc_head_fn weight is [hc_mult, hc_mult * d], float32.
|
||||
owner = self._fallback_op
|
||||
self.weight = owner.hc_head_fn.weight
|
||||
self.hc_scale = owner.hc_head_scale
|
||||
self.hc_base = owner.hc_head_base
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
import hpc
|
||||
|
||||
owner = self._fallback_op
|
||||
return hpc.fuse_ihc_head(
|
||||
x,
|
||||
self.weight,
|
||||
self.hc_scale,
|
||||
self.hc_base,
|
||||
owner.hc_head_fn.weight,
|
||||
owner.hc_head_scale,
|
||||
owner.hc_head_base,
|
||||
self.norm_eps,
|
||||
self.hc_eps,
|
||||
)
|
||||
|
||||
@@ -11,8 +11,5 @@ class HpcModule(nn.Module):
|
||||
def support(cls, *args, **kwargs):
|
||||
return True
|
||||
|
||||
def process_weights_after_loading(self, model):
|
||||
pass
|
||||
|
||||
def forward(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
@@ -90,13 +90,13 @@ class HpcRopeNorm(CustomOp, HpcModule):
|
||||
"""HPC fused RoPE + QK-Norm + KV-Cache-Write (+ optional FP8 Q quant).
|
||||
|
||||
Registered as a sub-module in model layers (e.g. HunYuanAttention).
|
||||
Norm weights are extracted from fallback norm modules via
|
||||
process_weights_after_loading() after all weights are loaded.
|
||||
The QK-Norm weights are read directly from the fallback norm modules
|
||||
(built in float32 when HPC is active), eliminating the derived copy.
|
||||
|
||||
forward() is dispatched by CustomOp framework:
|
||||
- In compiled mode: forward_cuda() calls torch.ops.vllm.hpc_rope_norm_forward
|
||||
as a splitting point — internal Python control flow is opaque
|
||||
to torch.compile and not captured by CUDA Graph.
|
||||
to torch.compile (its kernel launches can still be CUDA-graph captured).
|
||||
- In eager/native mode: forward_native() falls back to forward_cuda().
|
||||
"""
|
||||
|
||||
@@ -124,8 +124,6 @@ class HpcRopeNorm(CustomOp, HpcModule):
|
||||
self.num_kv_heads = num_kv_heads
|
||||
self.head_dim = head_dim
|
||||
|
||||
self.use_qk_norm = use_qk_norm
|
||||
|
||||
self.q_size = num_heads * head_dim
|
||||
self.kv_size = num_kv_heads * head_dim
|
||||
|
||||
@@ -139,31 +137,18 @@ class HpcRopeNorm(CustomOp, HpcModule):
|
||||
|
||||
self.head_per_group = num_heads // num_kv_heads
|
||||
|
||||
# Pre-allocate norm weight tensors as Parameters so they are tracked by
|
||||
# CuMemAllocator (for sleep/wake_up) and have stable addresses for CUDA
|
||||
# Graph replay. process_weights_after_loading() updates them inplace via
|
||||
# copy_() so refit does not invalidate captured graph tensor pointers.
|
||||
# Shape is [head_dim] to match the HPC kernel's q/k_norm_weight layout.
|
||||
if use_qk_norm and fallback_qnorm is not None:
|
||||
self.qnorm_weight: torch.nn.Parameter | None = torch.nn.Parameter(
|
||||
torch.empty(head_dim, dtype=torch.float32),
|
||||
requires_grad=False,
|
||||
)
|
||||
else:
|
||||
self.qnorm_weight = None
|
||||
if use_qk_norm and fallback_knorm is not None:
|
||||
self.knorm_weight: torch.nn.Parameter | None = torch.nn.Parameter(
|
||||
torch.empty(head_dim, dtype=torch.float32),
|
||||
requires_grad=False,
|
||||
)
|
||||
else:
|
||||
self.knorm_weight = None
|
||||
|
||||
self.use_fp8 = "fp8" in kv_cache_dtype
|
||||
# The RMSNorm/RoPE ordering is model dependent (e.g. HunYuan V3 applies
|
||||
# QK-Norm before RoPE -> NORM_THEN_ROPE), so it is supplied by the
|
||||
# caller. When QK-Norm is disabled the policy is forced to NONE.
|
||||
self.qk_norm_policy = qk_norm_policy if use_qk_norm else QkNormPolicy.NONE
|
||||
if self.qk_norm_policy != QkNormPolicy.NONE and (
|
||||
fallback_qnorm is None or fallback_knorm is None
|
||||
):
|
||||
raise ValueError(
|
||||
"QK-Norm is enabled but fallback_qnorm/fallback_knorm were not "
|
||||
"supplied; the fused kernel reads their weights directly."
|
||||
)
|
||||
|
||||
# Register layer_name + add self to the global instance registry so the
|
||||
# module-level custom op (hpc_rope_norm_forward) can route back here.
|
||||
@@ -215,20 +200,6 @@ class HpcRopeNorm(CustomOp, HpcModule):
|
||||
logger.info_once("enable hpc rope_norm")
|
||||
return True
|
||||
|
||||
def process_weights_after_loading(self, model: torch.nn.Module = None) -> None:
|
||||
"""Copy norm weights (float32) from fallback norm modules inplace.
|
||||
|
||||
Uses copy_() to preserve tensor addresses for CUDA Graph / refit
|
||||
compatibility. Called by the model's load_weights() after all weights
|
||||
are loaded (and generically from the model loader for DummyModelLoader
|
||||
/ sleep-wake_up reload paths).
|
||||
"""
|
||||
if self.use_qk_norm:
|
||||
if self.fallback_qnorm is not None and self.qnorm_weight is not None:
|
||||
self.qnorm_weight.data.copy_(self.fallback_qnorm.weight.data.float())
|
||||
if self.fallback_knorm is not None and self.knorm_weight is not None:
|
||||
self.knorm_weight.data.copy_(self.fallback_knorm.weight.data.float())
|
||||
|
||||
def register_layer_name(self, layer_name: str) -> None:
|
||||
"""Register layer_name and add self to the global registry.
|
||||
|
||||
@@ -430,12 +401,14 @@ class HpcRopeNorm(CustomOp, HpcModule):
|
||||
k_scale = attn_layer._k_scale.reshape(1)
|
||||
v_scale = attn_layer._v_scale.reshape(1)
|
||||
|
||||
q_norm_weight = (
|
||||
self.qnorm_weight if self.qk_norm_policy != QkNormPolicy.NONE else None
|
||||
)
|
||||
k_norm_weight = (
|
||||
self.knorm_weight if self.qk_norm_policy != QkNormPolicy.NONE else None
|
||||
)
|
||||
if self.qk_norm_policy != QkNormPolicy.NONE:
|
||||
assert self.fallback_qnorm is not None
|
||||
assert self.fallback_knorm is not None
|
||||
q_norm_weight = self.fallback_qnorm.weight
|
||||
k_norm_weight = self.fallback_knorm.weight
|
||||
else:
|
||||
q_norm_weight = None
|
||||
k_norm_weight = None
|
||||
|
||||
# --- Prefill ---
|
||||
if num_prefill_reqs > 0:
|
||||
|
||||
@@ -252,6 +252,8 @@ class LinearBase(PluggableLayer):
|
||||
disable_tp: If true, tensor parallelism will be disabled for this layer.
|
||||
"""
|
||||
|
||||
requires_unquantized_input = False
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
input_size: int,
|
||||
|
||||
@@ -8,7 +8,6 @@ auto-detected (Blackwell vs not) so call sites need not thread it through.
|
||||
"""
|
||||
|
||||
import functools
|
||||
from contextlib import contextmanager
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import triton
|
||||
@@ -26,20 +25,6 @@ def _is_blackwell() -> bool:
|
||||
_overrides: dict[str, tuple] = {}
|
||||
|
||||
|
||||
@contextmanager
|
||||
def override_replayssm_config(kernel: str, config: tuple):
|
||||
"""Pin ``kernel``'s launch config for the duration of the context."""
|
||||
prev = _overrides.get(kernel)
|
||||
_overrides[kernel] = config
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
if prev is None:
|
||||
_overrides.pop(kernel, None)
|
||||
else:
|
||||
_overrides[kernel] = prev
|
||||
|
||||
|
||||
def _dstate_tile(dstate: int, tile: int) -> int:
|
||||
return max(16, min(tile, triton.next_power_of_2(dstate)))
|
||||
|
||||
|
||||
@@ -299,7 +299,13 @@ class MHCPreDelayedOp(CustomOp):
|
||||
|
||||
Same gates as :class:`MHCPreOp`, but the stream collapse applies the
|
||||
caller's ``pre_mix`` and this sublayer's pre-mix is returned for the next
|
||||
sublayer seam. Returns post_mix, comb_mix, layer_input, next_pre_mix.
|
||||
sublayer seam.
|
||||
|
||||
Passing ``sublayer_out`` / ``post_layer_mix`` / ``comb_res_mix`` also
|
||||
applies the preceding post block, which lets AITER fold it into the pre
|
||||
projection and saves a launch. Returns residual, post_mix, comb_mix,
|
||||
layer_input, next_pre_mix; ``residual`` is the caller's own tensor when
|
||||
no post is requested.
|
||||
"""
|
||||
|
||||
# --8<-- [end:mhc_pre_delayed]
|
||||
@@ -307,6 +313,24 @@ class MHCPreDelayedOp(CustomOp):
|
||||
def enabled(cls) -> bool:
|
||||
return True
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
# Built here, not lazily: CustomOp resolves dispatch against the
|
||||
# current vLLM config, which is only set during model construction.
|
||||
self._post = MHCPostOp()
|
||||
|
||||
def _maybe_post(
|
||||
self,
|
||||
residual: torch.Tensor,
|
||||
sublayer_out: torch.Tensor | None,
|
||||
post_layer_mix: torch.Tensor | None,
|
||||
comb_res_mix: torch.Tensor | None,
|
||||
) -> torch.Tensor:
|
||||
if sublayer_out is None:
|
||||
return residual
|
||||
assert post_layer_mix is not None and comb_res_mix is not None
|
||||
return self._post(sublayer_out, residual, post_layer_mix, comb_res_mix)
|
||||
|
||||
def forward_cuda(
|
||||
self,
|
||||
residual: torch.Tensor,
|
||||
@@ -322,8 +346,14 @@ class MHCPreDelayedOp(CustomOp):
|
||||
x: torch.Tensor | None = None,
|
||||
norm_weight: torch.Tensor | None = None,
|
||||
norm_eps: float = 1e-6,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
return torch.ops.vllm.mhc_pre_delayed_tilelang(
|
||||
sublayer_out: torch.Tensor | None = None,
|
||||
post_layer_mix: torch.Tensor | None = None,
|
||||
comb_res_mix: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
residual = self._maybe_post(
|
||||
residual, sublayer_out, post_layer_mix, comb_res_mix
|
||||
)
|
||||
return residual, *torch.ops.vllm.mhc_pre_delayed_tilelang(
|
||||
residual,
|
||||
fn,
|
||||
hc_scale,
|
||||
@@ -354,7 +384,10 @@ class MHCPreDelayedOp(CustomOp):
|
||||
x: torch.Tensor | None = None,
|
||||
norm_weight: torch.Tensor | None = None,
|
||||
norm_eps: float = 1e-6,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
sublayer_out: torch.Tensor | None = None,
|
||||
post_layer_mix: torch.Tensor | None = None,
|
||||
comb_res_mix: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
# The AITER delayed path drives mhc_pre_gemm_sqrsum against `residual`
|
||||
# and folds no RMSNorm, so it cannot serve the model-entry broadcast
|
||||
# (which projects a narrower `x`) or a fused norm. Both are handled by
|
||||
@@ -364,7 +397,26 @@ class MHCPreDelayedOp(CustomOp):
|
||||
and norm_weight is None
|
||||
and _aiter_mhc_supported(residual, None, supports_norm=False)
|
||||
):
|
||||
return torch.ops.vllm.mhc_pre_delayed_aiter(
|
||||
from vllm._aiter_ops import rocm_aiter_ops
|
||||
|
||||
num_tokens = residual.numel() // (residual.shape[-1] * residual.shape[-2])
|
||||
# Folding the post in only pays while the residual still fits in
|
||||
# cache; past that AITER's heuristic wants the separate kernels,
|
||||
# which can ask for a non-temporal store and a large-m split-k.
|
||||
if sublayer_out is not None and (
|
||||
rocm_aiter_ops.mhc_fused_post_pre_delayed_prefers_unfused(num_tokens)
|
||||
):
|
||||
residual = self._maybe_post(
|
||||
residual, sublayer_out, post_layer_mix, comb_res_mix
|
||||
)
|
||||
sublayer_out = None
|
||||
# The op writes the folded post's residual into this buffer rather
|
||||
# than returning it, since on the unfused path it has none of its
|
||||
# own and an op must not hand back one of its inputs.
|
||||
residual_out = (
|
||||
torch.empty_like(residual) if sublayer_out is not None else None
|
||||
)
|
||||
rest = torch.ops.vllm.mhc_pre_delayed_aiter(
|
||||
residual,
|
||||
fn,
|
||||
hc_scale,
|
||||
@@ -375,9 +427,17 @@ class MHCPreDelayedOp(CustomOp):
|
||||
hc_post_mult_value,
|
||||
sinkhorn_repeat,
|
||||
pre_mix,
|
||||
sublayer_out,
|
||||
post_layer_mix,
|
||||
comb_res_mix,
|
||||
residual_out,
|
||||
)
|
||||
return (residual if residual_out is None else residual_out), *rest
|
||||
residual = self._maybe_post(
|
||||
residual, sublayer_out, post_layer_mix, comb_res_mix
|
||||
)
|
||||
if HAS_TILELANG_MHC:
|
||||
return torch.ops.vllm.mhc_pre_delayed_tilelang(
|
||||
return residual, *torch.ops.vllm.mhc_pre_delayed_tilelang(
|
||||
residual,
|
||||
fn,
|
||||
hc_scale,
|
||||
@@ -392,6 +452,7 @@ class MHCPreDelayedOp(CustomOp):
|
||||
norm_weight,
|
||||
norm_eps,
|
||||
)
|
||||
# The post is already applied, so it must not be requested again.
|
||||
return self.forward_native(
|
||||
residual,
|
||||
fn,
|
||||
@@ -423,7 +484,13 @@ class MHCPreDelayedOp(CustomOp):
|
||||
x: torch.Tensor | None = None,
|
||||
norm_weight: torch.Tensor | None = None,
|
||||
norm_eps: float = 1e-6,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
sublayer_out: torch.Tensor | None = None,
|
||||
post_layer_mix: torch.Tensor | None = None,
|
||||
comb_res_mix: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
residual = self._maybe_post(
|
||||
residual, sublayer_out, post_layer_mix, comb_res_mix
|
||||
)
|
||||
post_mix, comb_mix, layer_input, next_pre_mix = (
|
||||
mhc_kernels.mhc_pre_delayed_torch(
|
||||
residual,
|
||||
@@ -440,6 +507,7 @@ class MHCPreDelayedOp(CustomOp):
|
||||
)
|
||||
)
|
||||
return (
|
||||
residual,
|
||||
post_mix,
|
||||
comb_mix,
|
||||
_apply_mhc_norm(layer_input, norm_weight, norm_eps),
|
||||
|
||||
@@ -120,7 +120,7 @@ def get_quantization_config(quantization: str) -> type[QuantizationConfig]:
|
||||
# The v4.1 class is the v4 one extended to accept model_type
|
||||
# "deepseek_v41" and its 32x32 MXFP8 linear layout. V4.1 has
|
||||
# platform-specific implementations for both CUDA and ROCm.
|
||||
from vllm.models.deepseek_v4_1 import (
|
||||
from vllm.models.deepseek_v41 import (
|
||||
DeepseekV4FP8Config as DeepseekV41FP8Config,
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Sparse Attention Indexer that scores only the candidate blocks.
|
||||
|
||||
DeepSeek V4.1 two-level selection: the candidate-source indexer publishes
|
||||
the top candidate blocks and later indexers pick their top-k inside them.
|
||||
`SparseAttnIndexer` does that by computing dense logits over the whole
|
||||
context and masking; this layer instead calls DeepGEMM's sparse MQA-logits
|
||||
kernels on the candidate blocks only, so the work is O(candidate blocks)
|
||||
instead of O(context). It requires the `DeepseekV41SparseIndexerBackend`
|
||||
metadata (see ``AttentionConfig.indexer_sparse_logits``).
|
||||
"""
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm import _custom_ops as ops
|
||||
from vllm.forward_context import get_forward_context
|
||||
from vllm.model_executor.kernels.attention.dsa.sparse_mqa_logits import (
|
||||
has_deep_select,
|
||||
sparse_mqa_logits_paged_decode,
|
||||
sparse_mqa_logits_prefill_chunk,
|
||||
)
|
||||
from vllm.model_executor.layers.sparse_attn_indexer import (
|
||||
_gather_workspace_shapes,
|
||||
kv_cache_as_quant_view,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.deep_gemm import has_deep_gemm_sparse_mqa
|
||||
from vllm.v1.attention.backends.mla.indexer import (
|
||||
DeepseekV32IndexerPrefillChunkMetadata,
|
||||
)
|
||||
from vllm.v1.attention.backends.mla.sparse_indexer import (
|
||||
DeepseekV41SparseIndexerMetadata,
|
||||
)
|
||||
from vllm.v1.worker.workspace import current_workspace_manager
|
||||
|
||||
|
||||
def _prefill_k_workspaces(
|
||||
total_seq_lens: int, head_dim: int
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""The packed MXFP4 K-gather workspace ``(values, scales)``, shared with
|
||||
the dense indexer layers of the same model."""
|
||||
values_spec, scales_spec = _gather_workspace_shapes(
|
||||
total_seq_lens, head_dim, current_platform.fp8_dtype(), use_fp4_cache=True
|
||||
)
|
||||
k_quant, k_scale = current_workspace_manager().get_simultaneous(
|
||||
values_spec, scales_spec
|
||||
)
|
||||
return k_quant, k_scale
|
||||
|
||||
|
||||
def _gather_prefill_chunk_k(
|
||||
kv_cache: torch.Tensor,
|
||||
k_quant_full: torch.Tensor,
|
||||
k_scale_full: torch.Tensor,
|
||||
chunk: DeepseekV32IndexerPrefillChunkMetadata,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Gather one prefill chunk's paged K into the packed workspace."""
|
||||
assert chunk.local_cu_seq_lens is not None
|
||||
k_quant = k_quant_full[: chunk.max_local_total_seq_lens]
|
||||
k_scale = k_scale_full[: chunk.max_local_total_seq_lens]
|
||||
if not chunk.skip_kv_gather and chunk.local_total_seq_lens > 0:
|
||||
ops.cp_gather_indexer_k_quant_cache(
|
||||
kv_cache,
|
||||
k_quant,
|
||||
k_scale,
|
||||
chunk.block_table,
|
||||
chunk.local_cu_seq_lens,
|
||||
)
|
||||
return k_quant, k_scale
|
||||
|
||||
|
||||
class SparseMQAIndexer(nn.Module):
|
||||
"""Candidate-consuming indexer on DeepGEMM's sparse MQA-logits kernels.
|
||||
|
||||
Only valid for indexer layers that read candidate blocks with the MXFP4
|
||||
indexer cache on SM100. The K cache is written by the model before this
|
||||
runs; ``forward`` takes the same arguments as `SparseAttnIndexer` so the
|
||||
attention layer can call either.
|
||||
"""
|
||||
|
||||
weights_dtype = torch.bfloat16
|
||||
"""Per-head weights dtype the sparse kernels take. The fused Q RoPE-quant
|
||||
kernel writes it directly so no cast runs per step."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
k_cache,
|
||||
topk_tokens: int,
|
||||
head_dim: int,
|
||||
max_total_seq_len: int,
|
||||
topk_indices_buffer: torch.Tensor,
|
||||
candidate_blocks: torch.Tensor,
|
||||
candidate_block_size: int,
|
||||
):
|
||||
super().__init__()
|
||||
if not (
|
||||
current_platform.is_cuda()
|
||||
and current_platform.is_device_capability_family(100)
|
||||
and has_deep_gemm_sparse_mqa()
|
||||
):
|
||||
raise ValueError(
|
||||
"SparseMQAIndexer requires an SM100-class GPU and DeepGEMM >= 2.8."
|
||||
)
|
||||
if not has_deep_select():
|
||||
raise ValueError(
|
||||
"SparseMQAIndexer requires the DeepSelect top-k extension "
|
||||
"(vllm._deepselect_C)."
|
||||
)
|
||||
self.k_cache = k_cache
|
||||
self.topk_tokens = topk_tokens
|
||||
self.head_dim = head_dim
|
||||
self.max_total_seq_len = max_total_seq_len
|
||||
self.topk_indices_buffer = topk_indices_buffer
|
||||
self.candidate_blocks = candidate_blocks
|
||||
self.candidate_block_size = candidate_block_size
|
||||
|
||||
def _reserve_workspaces(self, device: torch.device) -> None:
|
||||
"""Profiling run: claim the K-gather workspace and the peak sparse
|
||||
logits allocation so the memory estimate covers them."""
|
||||
_prefill_k_workspaces(self.max_total_seq_len, self.head_dim)
|
||||
max_logits_bytes = envs.VLLM_SPARSE_INDEXER_MAX_LOGITS_MB * 1024 * 1024
|
||||
torch.empty(max_logits_bytes, dtype=torch.uint8, device=device)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
q_quant: tuple[torch.Tensor, torch.Tensor],
|
||||
k: torch.Tensor | None,
|
||||
weights: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
attn_metadata = get_forward_context().attn_metadata
|
||||
if not isinstance(attn_metadata, dict):
|
||||
self._reserve_workspaces(hidden_states.device)
|
||||
return self.topk_indices_buffer
|
||||
|
||||
metadata = attn_metadata[self.k_cache.prefix]
|
||||
assert isinstance(metadata, DeepseekV41SparseIndexerMetadata), (
|
||||
"SparseMQAIndexer needs DeepseekV41SparseIndexerBackend metadata"
|
||||
)
|
||||
assert k is None, "the model writes the indexer K cache"
|
||||
q_values, q_scale = q_quant
|
||||
kv_cache = self.k_cache.kv_cache
|
||||
topk_tokens = self.topk_tokens
|
||||
topk_indices_buffer = self.topk_indices_buffer
|
||||
topk_indices_buffer[: hidden_states.shape[0]] = -1
|
||||
sparse_block_kv = metadata.sparse_block_kv
|
||||
|
||||
if metadata.num_prefills > 0:
|
||||
prefill = metadata.prefill
|
||||
sparse_chunks = metadata.sparse_prefill
|
||||
assert prefill is not None and sparse_chunks is not None
|
||||
k_quant_full, k_scale_full = _prefill_k_workspaces(
|
||||
self.max_total_seq_len, self.head_dim
|
||||
)
|
||||
for chunk, rows in zip(prefill.chunks, sparse_chunks):
|
||||
k_quant, k_scale = _gather_prefill_chunk_k(
|
||||
kv_cache, k_quant_full, k_scale_full, chunk
|
||||
)
|
||||
if chunk.local_total_seq_lens == 0:
|
||||
continue # buffer already holds -1
|
||||
start, end = chunk.token_start, chunk.token_end
|
||||
rows.kernel_metadata = sparse_mqa_logits_prefill_chunk(
|
||||
q_values[start:end].view(torch.int8),
|
||||
q_scale[start:end],
|
||||
k_quant.view(torch.int8),
|
||||
k_scale.view(torch.int32).squeeze(-1),
|
||||
weights[start:end],
|
||||
chunk.cu_seqlen_ks,
|
||||
chunk.cu_seqlen_ke,
|
||||
self.candidate_blocks[start:end],
|
||||
self.candidate_block_size,
|
||||
sparse_block_kv,
|
||||
topk_tokens,
|
||||
topk_indices_buffer[start:end, :topk_tokens],
|
||||
sparse_indices=rows.sparse_indices,
|
||||
end=rows.end,
|
||||
col_indices=rows.col_indices,
|
||||
kernel_metadata=rows.kernel_metadata,
|
||||
)
|
||||
|
||||
if metadata.num_decodes > 0:
|
||||
decode_rows = metadata.sparse_decode
|
||||
assert decode_rows is not None and decode_rows.block_table is not None
|
||||
assert decode_rows.row_indices is not None
|
||||
num_rows = decode_rows.row_ke.shape[0]
|
||||
if num_rows > 0:
|
||||
decode_rows.kernel_metadata = sparse_mqa_logits_paged_decode(
|
||||
q_values[:num_rows].view(torch.int8).unsqueeze(1),
|
||||
q_scale[:num_rows].unsqueeze(1),
|
||||
kv_cache_as_quant_view(kv_cache, self.head_dim, use_fp4_cache=True),
|
||||
weights[:num_rows],
|
||||
decode_rows.row_ke,
|
||||
decode_rows.block_table,
|
||||
decode_rows.row_indices,
|
||||
self.candidate_blocks[:num_rows],
|
||||
self.candidate_block_size,
|
||||
sparse_block_kv,
|
||||
topk_tokens,
|
||||
topk_indices_buffer[:num_rows, :topk_tokens],
|
||||
row_ks=decode_rows.row_ks,
|
||||
sparse_indices=decode_rows.sparse_indices,
|
||||
end=decode_rows.end,
|
||||
col_indices=decode_rows.col_indices,
|
||||
kernel_metadata=decode_rows.kernel_metadata,
|
||||
)
|
||||
return topk_indices_buffer
|
||||
@@ -15,7 +15,6 @@ import vllm.envs as envs
|
||||
from vllm.config import ModelConfig, VllmConfig, set_current_vllm_config
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.attention import is_deferred_attention_layer
|
||||
from vllm.model_executor.layers.hpc import HpcModule
|
||||
from vllm.model_executor.layers.quantization.base_config import (
|
||||
QuantizationConfig,
|
||||
QuantizeMethodBase,
|
||||
@@ -154,15 +153,6 @@ def process_weights_after_loading(
|
||||
with device_loading_context(module, target_device):
|
||||
module.process_weights_after_loading(model_config.dtype)
|
||||
|
||||
# Process HPC modules (HpcRopeNorm, etc.) that rely on
|
||||
# process_weights_after_loading being called from the model's
|
||||
# load_weights(). When using DummyModelLoader (e.g. profiling or
|
||||
# sleep/wake_up reload), the model's load_weights() is not called, so we
|
||||
# must handle HPC modules here generically.
|
||||
for _, module in model.named_modules():
|
||||
if isinstance(module, HpcModule):
|
||||
module.process_weights_after_loading(model)
|
||||
|
||||
# Model-level post-load hook, after the per-layer quant finalize.
|
||||
if hasattr(model, "process_weights_after_loading"):
|
||||
model.process_weights_after_loading()
|
||||
|
||||
@@ -60,6 +60,7 @@ from vllm.distributed import (
|
||||
ensure_model_parallel_initialized,
|
||||
init_distributed_environment,
|
||||
)
|
||||
from vllm.engine.arg_utils import EngineArgs
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.model_loader import get_model_loader
|
||||
from vllm.model_executor.model_loader.utils import process_weights_after_loading
|
||||
@@ -70,13 +71,15 @@ from vllm.model_executor.model_loader.weight_cache.protocol import (
|
||||
check_ipc_platform_support,
|
||||
check_ipc_quant_support,
|
||||
ensure_private_socket_dir,
|
||||
get_physical_device_id,
|
||||
get_current_device_uuid,
|
||||
get_socket_path,
|
||||
recv_msg,
|
||||
send_msg,
|
||||
verify_peer_is_owner,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.argparse_utils import FlexibleArgumentParser
|
||||
from vllm.utils.network_utils import get_distributed_init_method, get_open_port
|
||||
from vllm.utils.torch_utils import set_default_torch_dtype
|
||||
|
||||
logger = init_logger("vllm.model_executor.model_loader.weight_cache.daemon")
|
||||
@@ -90,11 +93,14 @@ def export_entries(
|
||||
``named_parameters``/``named_buffers`` are iterated with
|
||||
``remove_duplicate=False`` so tied weights (e.g. ``lm_head.weight`` sharing
|
||||
storage with ``embed_tokens.weight``) are not silently dropped. Each unique
|
||||
tensor is exported once; every additional name that refers to the same
|
||||
tensor is exported once per call; every additional name that refers to the same
|
||||
tensor object is recorded in the returned alias map so the client can
|
||||
re-establish the shared identity instead of allocating uninitialized
|
||||
memory for it.
|
||||
|
||||
CUDA reduction arguments must be exported separately for each consumer so
|
||||
that PyTorch registers a reference for each IPC mapping's lifetime.
|
||||
|
||||
Returns:
|
||||
A ``(entries, aliases)`` pair where ``entries`` maps a canonical name to
|
||||
its ``TensorEntry`` and ``aliases`` maps each duplicate name to its
|
||||
@@ -164,8 +170,6 @@ class WeightCacheDaemon:
|
||||
self.distributed_init_method = distributed_init_method
|
||||
self.socket_dir = socket_dir
|
||||
self.model: torch.nn.Module | None = None
|
||||
self.entries: dict[str, TensorEntry] = {}
|
||||
self.aliases: dict[str, str] = {}
|
||||
# Fingerprint before loading: process_weights_after_loading may
|
||||
# mutate hf_config.quantization_config.
|
||||
self.cache_config = WeightCacheKey.from_model_config(
|
||||
@@ -187,17 +191,11 @@ class WeightCacheDaemon:
|
||||
with set_current_vllm_config(self.vllm_config):
|
||||
ensure_model_parallel_initialized(tp_size, 1)
|
||||
self.model = get_daemon_model(self.vllm_config)
|
||||
self._export_entries()
|
||||
logger.info(
|
||||
"Weight cache daemon rank %d cached %d tensors",
|
||||
"Weight cache daemon rank %d loaded model",
|
||||
self.tp_rank,
|
||||
len(self.entries),
|
||||
)
|
||||
|
||||
def _export_entries(self) -> None:
|
||||
assert self.model is not None
|
||||
self.entries, self.aliases = export_entries(self.model)
|
||||
|
||||
def serve_forever(self, ready_callback: Callable[[], None] | None = None) -> None:
|
||||
"""Serve requests until terminated.
|
||||
|
||||
@@ -209,7 +207,7 @@ class WeightCacheDaemon:
|
||||
ready_callback: Invoked once the socket is bound and listening,
|
||||
so the launcher can report overall readiness.
|
||||
"""
|
||||
socket_path = self._socket_path()
|
||||
socket_path = self._socket_path
|
||||
ensure_private_socket_dir(
|
||||
os.path.dirname(socket_path), strict_perms=self.socket_dir is None
|
||||
)
|
||||
@@ -268,12 +266,9 @@ class WeightCacheDaemon:
|
||||
) from e
|
||||
return lock_fd
|
||||
|
||||
@property
|
||||
def _socket_path(self) -> str:
|
||||
device_index = torch.accelerator.current_device_index()
|
||||
gpu_id = get_physical_device_id(device_index)
|
||||
if gpu_id is None:
|
||||
gpu_id = device_index
|
||||
return get_socket_path(gpu_id, self.socket_dir)
|
||||
return get_socket_path(get_current_device_uuid(), self.socket_dir)
|
||||
|
||||
def _handle_connection(self, conn: socket.socket) -> None:
|
||||
request = recv_msg(conn)
|
||||
@@ -295,39 +290,33 @@ class WeightCacheDaemon:
|
||||
logger.warning("WeightCacheKey mismatch on fields: %s", mismatched)
|
||||
send_msg(conn, {"status": "mismatch", "fields": mismatched})
|
||||
return
|
||||
if not self.entries:
|
||||
if self.model is None:
|
||||
send_msg(conn, {"status": "error", "message": "Weights were released"})
|
||||
return
|
||||
gpu_uuid = get_current_device_uuid()
|
||||
entries, aliases = export_entries(self.model)
|
||||
send_msg(
|
||||
conn,
|
||||
{
|
||||
"status": "ok",
|
||||
"entries": self.entries,
|
||||
"aliases": self.aliases,
|
||||
"gpu_uuid": self._gpu_uuid(),
|
||||
"entries": entries,
|
||||
"aliases": aliases,
|
||||
"gpu_uuid": gpu_uuid,
|
||||
},
|
||||
)
|
||||
logger.info_once(
|
||||
"Weight cache daemon rank %d sent %d tensors (+%d aliases) to engine",
|
||||
self.tp_rank,
|
||||
len(self.entries),
|
||||
len(self.aliases),
|
||||
len(entries),
|
||||
len(aliases),
|
||||
)
|
||||
|
||||
def _handle_release(self, conn: socket.socket) -> None:
|
||||
self.entries.clear()
|
||||
self.aliases.clear()
|
||||
self.model = None
|
||||
torch.accelerator.empty_cache()
|
||||
logger.info("Weight cache daemon rank %d released cached weights", self.tp_rank)
|
||||
send_msg(conn, {"status": "ok"})
|
||||
|
||||
def _gpu_uuid(self) -> str:
|
||||
props = torch.cuda.get_device_properties(
|
||||
torch.accelerator.current_device_index()
|
||||
)
|
||||
return str(props.uuid)
|
||||
|
||||
|
||||
def _run_daemon(
|
||||
tp_rank: int,
|
||||
@@ -359,10 +348,6 @@ def _reject_unsupported_parallelism(parallel_config: ParallelConfig) -> None:
|
||||
|
||||
|
||||
def main() -> None:
|
||||
from vllm.engine.arg_utils import EngineArgs
|
||||
from vllm.utils.argparse_utils import FlexibleArgumentParser
|
||||
from vllm.utils.network_utils import get_distributed_init_method, get_open_port
|
||||
|
||||
parser = FlexibleArgumentParser(
|
||||
description="Launch weight cache daemons (one per TP rank)."
|
||||
)
|
||||
|
||||
@@ -12,6 +12,10 @@ import torch.nn as nn
|
||||
|
||||
from vllm.config import ModelConfig, VllmConfig
|
||||
from vllm.config.load import LoadConfig
|
||||
from vllm.distributed import (
|
||||
get_tensor_model_parallel_rank,
|
||||
get_tensor_model_parallel_world_size,
|
||||
)
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.model_loader.base_loader import BaseModelLoader
|
||||
from vllm.model_executor.model_loader.default_loader import DefaultModelLoader
|
||||
@@ -27,7 +31,7 @@ from vllm.model_executor.model_loader.weight_cache.protocol import (
|
||||
WeightCacheUnavailableError,
|
||||
check_ipc_platform_support,
|
||||
check_ipc_quant_support,
|
||||
get_physical_device_id,
|
||||
get_current_device_uuid,
|
||||
get_socket_path,
|
||||
recv_msg,
|
||||
send_msg,
|
||||
@@ -56,7 +60,7 @@ class IpcModelLoader(BaseModelLoader):
|
||||
Extra config keys (via --model-loader-extra-config):
|
||||
|
||||
- socket_path: explicit daemon socket path. Defaults to a per-GPU path
|
||||
derived from the physical GPU id.
|
||||
derived from the physical GPU uuid.
|
||||
- socket_dir: directory containing the daemon sockets.
|
||||
- mode: "zero_copy" (default) or "copy".
|
||||
- fallback: fall back to disk loading when the daemon is unavailable or
|
||||
@@ -261,11 +265,6 @@ class IpcModelLoader(BaseModelLoader):
|
||||
def _fetch_entries(
|
||||
self, model_config: ModelConfig
|
||||
) -> tuple[dict[str, TensorEntry], dict[str, str]]:
|
||||
from vllm.distributed import (
|
||||
get_tensor_model_parallel_rank,
|
||||
get_tensor_model_parallel_world_size,
|
||||
)
|
||||
|
||||
cache_config = WeightCacheKey.from_model_config(
|
||||
model_config,
|
||||
tp_size=get_tensor_model_parallel_world_size(),
|
||||
@@ -317,22 +316,12 @@ class IpcModelLoader(BaseModelLoader):
|
||||
def _resolve_socket_path(self) -> str:
|
||||
if self.socket_path is not None:
|
||||
return self.socket_path
|
||||
device_index = torch.accelerator.current_device_index()
|
||||
gpu_id = get_physical_device_id(device_index)
|
||||
if gpu_id is None:
|
||||
raise WeightCacheUnavailableError(
|
||||
"Cannot infer the physical GPU id from CUDA_VISIBLE_DEVICES; "
|
||||
"pass socket_path via --model-loader-extra-config"
|
||||
)
|
||||
return get_socket_path(gpu_id, self.socket_dir)
|
||||
return get_socket_path(get_current_device_uuid(), self.socket_dir)
|
||||
|
||||
def _check_gpu_uuid(self, daemon_uuid: str | None) -> None:
|
||||
if daemon_uuid is None:
|
||||
return
|
||||
props = torch.cuda.get_device_properties(
|
||||
torch.accelerator.current_device_index()
|
||||
)
|
||||
local_uuid = str(props.uuid)
|
||||
local_uuid = get_current_device_uuid()
|
||||
if daemon_uuid != local_uuid:
|
||||
raise CacheConfigMismatchError(
|
||||
f"Daemon GPU {daemon_uuid} != engine GPU {local_uuid}; "
|
||||
|
||||
@@ -23,14 +23,19 @@ from dataclasses import dataclass, fields
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
from torch.multiprocessing.reductions import rebuild_cuda_tensor, reduce_tensor
|
||||
from transformers.utils import SAFE_WEIGHTS_INDEX_NAME
|
||||
|
||||
import vllm.version
|
||||
from vllm.config import ModelConfig
|
||||
from vllm.model_executor.layers.quantization.base_config import QuantizeMethodBase
|
||||
from vllm.model_executor.model_loader.weight_utils import (
|
||||
filter_duplicate_safetensors_files,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.hashing import safe_hash
|
||||
|
||||
SOCKET_NAME_TEMPLATE = "vllm_weight_cache_gpu{gpu_id}.sock"
|
||||
SOCKET_NAME_TEMPLATE = "vllm_weight_cache_{gpu_uuid}.sock"
|
||||
SOCKET_DIR_TEMPLATE = "vllm_weight_cache_{uid}"
|
||||
|
||||
_LEN_STRUCT = struct.Struct("!Q")
|
||||
@@ -102,20 +107,9 @@ def check_ipc_quant_support(model: torch.nn.Module) -> None:
|
||||
)
|
||||
|
||||
|
||||
def get_physical_device_id(device_index: int) -> int | None:
|
||||
"""Map a local CUDA device index to the physical GPU id.
|
||||
|
||||
Returns None if CUDA_VISIBLE_DEVICES contains non-integer entries
|
||||
(e.g. GPU UUIDs), in which case an explicit socket path is required.
|
||||
"""
|
||||
visible = os.environ.get("CUDA_VISIBLE_DEVICES")
|
||||
if not visible:
|
||||
return device_index
|
||||
entries = visible.split(",")
|
||||
try:
|
||||
return int(entries[device_index])
|
||||
except (IndexError, ValueError):
|
||||
return None
|
||||
def get_current_device_uuid() -> str:
|
||||
"""UUID of the physical GPU backing the current accelerator device."""
|
||||
return current_platform.get_device_uuid(torch.accelerator.current_device_index())
|
||||
|
||||
|
||||
def get_socket_dir(socket_dir: str | None = None) -> str:
|
||||
@@ -132,9 +126,9 @@ def get_socket_dir(socket_dir: str | None = None) -> str:
|
||||
)
|
||||
|
||||
|
||||
def get_socket_path(gpu_id: int, socket_dir: str | None = None) -> str:
|
||||
def get_socket_path(gpu_uuid: str, socket_dir: str | None = None) -> str:
|
||||
directory = get_socket_dir(socket_dir)
|
||||
return os.path.join(directory, SOCKET_NAME_TEMPLATE.format(gpu_id=gpu_id))
|
||||
return os.path.join(directory, SOCKET_NAME_TEMPLATE.format(gpu_uuid=gpu_uuid))
|
||||
|
||||
|
||||
def ensure_private_socket_dir(directory: str, strict_perms: bool = True) -> None:
|
||||
@@ -245,12 +239,6 @@ def hash_checkpoint(model: str) -> str | None:
|
||||
"""
|
||||
if not os.path.isdir(model):
|
||||
return None
|
||||
from transformers.utils import SAFE_WEIGHTS_INDEX_NAME
|
||||
|
||||
from vllm.model_executor.model_loader.weight_utils import (
|
||||
filter_duplicate_safetensors_files,
|
||||
)
|
||||
|
||||
files = glob.glob(os.path.join(model, "*.safetensors"))
|
||||
if os.path.isfile(os.path.join(model, SAFE_WEIGHTS_INDEX_NAME)):
|
||||
files = filter_duplicate_safetensors_files(
|
||||
@@ -337,8 +325,6 @@ class TensorEntry:
|
||||
|
||||
@classmethod
|
||||
def from_tensor(cls, tensor: torch.Tensor, kind: str) -> "TensorEntry":
|
||||
from torch.multiprocessing.reductions import reduce_tensor
|
||||
|
||||
tensor = tensor.detach()
|
||||
if tensor.is_cuda:
|
||||
_, ipc_args = reduce_tensor(tensor)
|
||||
@@ -349,8 +335,6 @@ class TensorEntry:
|
||||
if self.ipc_args is None:
|
||||
assert self.cpu_tensor is not None
|
||||
return self.cpu_tensor
|
||||
from torch.multiprocessing.reductions import rebuild_cuda_tensor
|
||||
|
||||
args = list(self.ipc_args)
|
||||
# Index 6 of the args from reduce_tensor is the device index. It must
|
||||
# be retargeted to the local index since the daemon and the engine may
|
||||
|
||||
@@ -22,6 +22,7 @@ from vllm.model_executor.layers.quantization import QuantizationConfig
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
from vllm.multimodal.inputs import (
|
||||
MultiModalFieldConfig,
|
||||
MultiModalKwargsItem,
|
||||
MultiModalKwargsItems,
|
||||
)
|
||||
from vllm.multimodal.parse import MultiModalDataItems
|
||||
@@ -687,28 +688,22 @@ class Blip2ForConditionalGeneration(
|
||||
tower_model="vision_model",
|
||||
)
|
||||
|
||||
def get_num_mm_encoder_tokens(
|
||||
def get_mm_lora_token_counts(
|
||||
self,
|
||||
num_image_tokens: int,
|
||||
) -> int:
|
||||
if num_image_tokens <= 0:
|
||||
return 0
|
||||
assert num_image_tokens % self.config.num_query_tokens == 0, (
|
||||
*,
|
||||
modality: str,
|
||||
mm_kwargs: MultiModalKwargsItem | None,
|
||||
num_mm_embeds: int,
|
||||
) -> tuple[int, int | None]:
|
||||
del modality, mm_kwargs
|
||||
if num_mm_embeds <= 0:
|
||||
return 0, 0
|
||||
assert num_mm_embeds % self.config.num_query_tokens == 0, (
|
||||
"The number of image tokens must be a multiple of "
|
||||
"the number of query tokens."
|
||||
)
|
||||
num_images = num_image_tokens / self.config.num_query_tokens
|
||||
return num_images * self._vision_tokens_per_image
|
||||
|
||||
def get_num_mm_connector_tokens(
|
||||
self,
|
||||
num_vision_tokens: int,
|
||||
) -> int:
|
||||
if num_vision_tokens <= 0:
|
||||
return 0
|
||||
assert num_vision_tokens % self._vision_tokens_per_image == 0, (
|
||||
"The number of vision tokens must be a multiple of "
|
||||
"the number of tokens per image."
|
||||
num_images = num_mm_embeds // self.config.num_query_tokens
|
||||
return (
|
||||
num_images * self._vision_tokens_per_image,
|
||||
num_images * self.config.num_query_tokens,
|
||||
)
|
||||
num_images = num_vision_tokens / self._vision_tokens_per_image
|
||||
return num_images * self.config.num_query_tokens
|
||||
|
||||
@@ -305,10 +305,14 @@ class Eagle3DeepseekV2ForCausalLM(LocalArgmaxMixin, DeepseekV2ForCausalLM):
|
||||
self.logits_processor = LogitsProcessor(
|
||||
self.config.draft_vocab_size, scale=logit_scale
|
||||
)
|
||||
self.draft_id_to_target_id = nn.Parameter(
|
||||
torch.zeros(self.config.draft_vocab_size, dtype=torch.long),
|
||||
requires_grad=False,
|
||||
)
|
||||
target_vocab_size = vllm_config.model_config.get_vocab_size()
|
||||
if self.config.draft_vocab_size != target_vocab_size:
|
||||
self.draft_id_to_target_id = nn.Parameter(
|
||||
torch.zeros(self.config.draft_vocab_size, dtype=torch.long),
|
||||
requires_grad=False,
|
||||
)
|
||||
else:
|
||||
self.draft_id_to_target_id = None
|
||||
|
||||
def embed_input_ids(
|
||||
self,
|
||||
|
||||
@@ -53,7 +53,7 @@ from vllm.utils.torch_utils import async_tensor_h2d
|
||||
from vllm.v1.outputs import LogprobsTensors
|
||||
from vllm.v1.sample.ops.topk_topp_sampler import apply_top_k_top_p
|
||||
from vllm.v1.worker.gpu.attn_utils import build_attn_metadata
|
||||
from vllm.v1.worker.gpu.buffer_utils import UvaBackedTensor, async_copy_to_gpu
|
||||
from vllm.v1.worker.gpu.buffer_utils import UvaBackedTensor
|
||||
from vllm.v1.worker.gpu.input_batch import InputBatch
|
||||
from vllm.v1.worker.gpu.model_states.interface import ModelState
|
||||
from vllm.v1.worker.gpu.sample.logprob import compute_topk_scores
|
||||
@@ -1159,7 +1159,7 @@ class DiffusionSampler:
|
||||
return
|
||||
# Move the slot indices across once, up front: indexing a device
|
||||
# tensor with a numpy array copies them over synchronously each time.
|
||||
ps_gpu = async_copy_to_gpu(
|
||||
ps_gpu = async_tensor_h2d(
|
||||
ps.astype(np.int64), device=states.is_encoder_phase.device
|
||||
)
|
||||
states.init_canvas(ps_gpu)
|
||||
@@ -1266,7 +1266,7 @@ class DiffusionSampler:
|
||||
# was truncated near max_model_len, in which case the scheduler gave us
|
||||
# fewer than CL logits for that request.
|
||||
valid_canvas_len_np = per_req_nlogits_np[per_req_nlogits_np > 0]
|
||||
valid_canvas_len = async_copy_to_gpu(
|
||||
valid_canvas_len = async_tensor_h2d(
|
||||
valid_canvas_len_np.astype(np.int64), device=device
|
||||
)
|
||||
|
||||
|
||||
@@ -54,6 +54,7 @@ from vllm.model_executor.models.utils import (
|
||||
)
|
||||
from vllm.model_executor.models.vision import get_vit_attn_backend
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
from vllm.multimodal.inputs import MultiModalKwargsItem
|
||||
from vllm.sequence import IntermediateTensors
|
||||
from vllm.transformers_utils.configs.dotsocr import DotsOCRConfig, DotsVisionConfig
|
||||
from vllm.utils.tensor_schema import TensorSchema, TensorShape
|
||||
@@ -718,13 +719,16 @@ class DotsOCRForCausalLM(nn.Module, SupportsMultiModal, SupportsPP, SupportsLoRA
|
||||
|
||||
return image_embeds.split(sizes)
|
||||
|
||||
def get_num_mm_encoder_tokens(self, num_image_tokens: int) -> int:
|
||||
def get_mm_lora_token_counts(
|
||||
self,
|
||||
*,
|
||||
modality: str,
|
||||
mm_kwargs: MultiModalKwargsItem | None,
|
||||
num_mm_embeds: int,
|
||||
) -> tuple[int, int | None]:
|
||||
del modality, mm_kwargs
|
||||
merge_size = self.vision_tower.spatial_merge_size
|
||||
return num_image_tokens * (merge_size**2)
|
||||
|
||||
def get_num_mm_connector_tokens(self, num_vision_tokens: int) -> int:
|
||||
merge_size = self.vision_tower.spatial_merge_size
|
||||
return num_vision_tokens // (merge_size**2)
|
||||
return num_mm_embeds * (merge_size**2), num_mm_embeds
|
||||
|
||||
def embed_multimodal(self, **kwargs: object) -> MultiModalEmbeddings:
|
||||
image_input = self._parse_and_validate_image_input(**kwargs)
|
||||
|
||||
@@ -19,6 +19,7 @@ from vllm.model_executor.models.module_mapping import MultiModelKeys
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
from vllm.multimodal.inputs import (
|
||||
MultiModalFieldConfig,
|
||||
MultiModalKwargsItem,
|
||||
MultiModalKwargsItems,
|
||||
)
|
||||
from vllm.multimodal.parse import ImageProcessorItems, ImageSize, MultiModalDataItems
|
||||
@@ -686,43 +687,16 @@ class Gemma3ForConditionalGeneration(
|
||||
tower_model="vision_tower",
|
||||
)
|
||||
|
||||
def get_num_mm_encoder_tokens(self, num_image_tokens: int) -> int:
|
||||
"""
|
||||
Calculate the number of tokens output by the vision encoder.
|
||||
|
||||
The vision encoder processes images into patch embeddings. For Gemma3,
|
||||
the relationship between prompt placeholder tokens and actual vision
|
||||
encoder output tokens depends on the patch grid size.
|
||||
|
||||
Args:
|
||||
num_image_tokens: Number of image placeholder tokens in the prompt
|
||||
(typically mm_tokens_per_image per image)
|
||||
|
||||
Returns:
|
||||
Number of tokens output by the vision encoder
|
||||
"""
|
||||
# For Gemma3, the vision encoder outputs tokens_per_side x tokens_per_side
|
||||
# tokens per image. Since num_image_tokens represents the number of
|
||||
# connector output tokens (mm_tokens_per_image = 256), and tokens_per_side
|
||||
# is sqrt(256) = 16, we need to account for the token expansion.
|
||||
# Based on empirical testing, the multiplier of 16 works correctly.
|
||||
return num_image_tokens * 16
|
||||
|
||||
def get_num_mm_connector_tokens(self, num_vision_tokens: int) -> int:
|
||||
"""
|
||||
Calculate the number of tokens output by the multimodal connector.
|
||||
|
||||
The connector applies projection and normalization but maintains the
|
||||
token count for Gemma3.
|
||||
|
||||
Args:
|
||||
num_vision_tokens: Number of tokens from vision encoder
|
||||
|
||||
Returns:
|
||||
Number of tokens after connector processing
|
||||
"""
|
||||
# The Gemma3 connector maintains a 1:1 token mapping
|
||||
return num_vision_tokens
|
||||
def get_mm_lora_token_counts(
|
||||
self,
|
||||
*,
|
||||
modality: str,
|
||||
mm_kwargs: MultiModalKwargsItem | None,
|
||||
num_mm_embeds: int,
|
||||
) -> tuple[int, int | None]:
|
||||
del modality, mm_kwargs
|
||||
tower_tokens = num_mm_embeds * 16
|
||||
return tower_tokens, tower_tokens
|
||||
|
||||
def get_encoder_cudagraph_config(self):
|
||||
from vllm.v1.worker.encoder_cudagraph_defs import (
|
||||
|
||||
@@ -24,6 +24,7 @@ from PIL import Image as PILImage
|
||||
from torch import nn
|
||||
from transformers import AutoModel, BatchFeature
|
||||
from transformers.models.gemma4 import (
|
||||
Gemma4AudioFeatureExtractor,
|
||||
Gemma4Config,
|
||||
Gemma4Processor,
|
||||
Gemma4VisionConfig,
|
||||
@@ -456,6 +457,28 @@ class Gemma4ProcessingInfo(BaseProcessingInfo):
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _dummy_audio_num_samples(processor: Any) -> int:
|
||||
"""Length in samples of a worst-case dummy audio item.
|
||||
|
||||
``fft_length`` is set in ``Gemma4AudioFeatureExtractor.__init__`` and is not
|
||||
defined by ``Gemma4UnifiedAudioFeatureExtractor``, which the encoder-free
|
||||
Gemma 4 variant uses. Reading it unconditionally therefore raises
|
||||
``AttributeError`` during memory profiling on that variant, which is reached
|
||||
whenever audio is the modality with the largest per-item token count.
|
||||
|
||||
For any other extractor, fall back to the audio budget the processor itself
|
||||
declares -- the same pair of values used to warn about over-long audio
|
||||
elsewhere in this file.
|
||||
"""
|
||||
feature_extractor = processor.feature_extractor
|
||||
if isinstance(feature_extractor, Gemma4AudioFeatureExtractor):
|
||||
return feature_extractor.fft_length
|
||||
|
||||
sampling_rate = feature_extractor.sampling_rate
|
||||
max_duration_s = processor.audio_seq_length * processor.audio_ms_per_token / 1000.0
|
||||
return int(max_duration_s * sampling_rate)
|
||||
|
||||
|
||||
class Gemma4DummyInputsBuilder(BaseDummyInputsBuilder[Gemma4ProcessingInfo]):
|
||||
def get_dummy_text(self, mm_counts: Mapping[str, int]) -> str:
|
||||
num_images = mm_counts.get("image", 0)
|
||||
@@ -508,7 +531,7 @@ class Gemma4DummyInputsBuilder(BaseDummyInputsBuilder[Gemma4ProcessingInfo]):
|
||||
}
|
||||
|
||||
if num_audios > 0:
|
||||
audio_len = processor.feature_extractor.fft_length
|
||||
audio_len = _dummy_audio_num_samples(processor)
|
||||
data["audio"] = self._get_dummy_audios(
|
||||
length=audio_len,
|
||||
num_audios=num_audios,
|
||||
|
||||
@@ -83,6 +83,7 @@ from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
from vllm.multimodal.inputs import (
|
||||
MultiModalFeatureSpec,
|
||||
MultiModalFieldConfig,
|
||||
MultiModalKwargsItem,
|
||||
MultiModalKwargsItems,
|
||||
VideoItem,
|
||||
)
|
||||
@@ -2378,19 +2379,16 @@ class Glm4vForConditionalGeneration(
|
||||
tower_model="visual.",
|
||||
)
|
||||
|
||||
def get_num_mm_encoder_tokens(
|
||||
def get_mm_lora_token_counts(
|
||||
self,
|
||||
num_image_tokens: int,
|
||||
) -> int:
|
||||
*,
|
||||
modality: str,
|
||||
mm_kwargs: MultiModalKwargsItem | None,
|
||||
num_mm_embeds: int,
|
||||
) -> tuple[int, int | None]:
|
||||
del modality, mm_kwargs
|
||||
merge_size = self.config.vision_config.spatial_merge_size
|
||||
return num_image_tokens * (merge_size**2)
|
||||
|
||||
def get_num_mm_connector_tokens(
|
||||
self,
|
||||
num_vision_tokens: int,
|
||||
) -> int:
|
||||
merge_size = self.config.vision_config.spatial_merge_size
|
||||
return num_vision_tokens // (merge_size**2)
|
||||
return num_mm_embeds * (merge_size**2), num_mm_embeds
|
||||
|
||||
|
||||
@MULTIMODAL_REGISTRY.register_processor(
|
||||
|
||||
@@ -14,7 +14,7 @@ from transformers import PretrainedConfig
|
||||
|
||||
from vllm.model_executor.layers.quantization import QuantizationConfig
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
from vllm.multimodal.inputs import BatchedTensorInputs
|
||||
from vllm.multimodal.inputs import BatchedTensorInputs, MultiModalKwargsItem
|
||||
from vllm.multimodal.parse import (
|
||||
ImageEmbeddingItems,
|
||||
ImageProcessorItems,
|
||||
@@ -178,16 +178,17 @@ class H2OVLChatModel(InternVLChatModel):
|
||||
prefix=prefix,
|
||||
)
|
||||
|
||||
def get_num_mm_encoder_tokens(self, num_image_tokens: int) -> int:
|
||||
if num_image_tokens <= 0 or self.num_image_token <= 0:
|
||||
return 0
|
||||
def get_mm_lora_token_counts(
|
||||
self,
|
||||
*,
|
||||
modality: str,
|
||||
mm_kwargs: MultiModalKwargsItem | None,
|
||||
num_mm_embeds: int,
|
||||
) -> tuple[int, int | None]:
|
||||
del modality, mm_kwargs
|
||||
if num_mm_embeds <= 0 or self.num_image_token <= 0:
|
||||
return 0, 0
|
||||
|
||||
num_patches = num_image_tokens // self.num_image_token
|
||||
return num_patches * (self.patch_tokens + 1)
|
||||
|
||||
def get_num_mm_connector_tokens(self, num_vision_tokens: int) -> int:
|
||||
if num_vision_tokens <= 0 or self.num_image_token <= 0:
|
||||
return 0
|
||||
|
||||
num_patches = num_vision_tokens // (self.patch_tokens + 1)
|
||||
return num_patches * self.num_image_token
|
||||
num_patches = num_mm_embeds // self.num_image_token
|
||||
tower_tokens = num_patches * (self.patch_tokens + 1)
|
||||
return tower_tokens, num_patches * self.num_image_token
|
||||
|
||||
@@ -300,8 +300,11 @@ class HYV3Attention(nn.Module):
|
||||
prefix=f"{prefix}.attn",
|
||||
)
|
||||
if self.use_qk_norm:
|
||||
self.q_norm = RMSNorm(self.head_dim, rms_norm_eps)
|
||||
self.k_norm = RMSNorm(self.head_dim, rms_norm_eps)
|
||||
# The HPC fused kernel reads norm weights directly in float32;
|
||||
# the fallback path keeps the model default dtype.
|
||||
norm_dtype = torch.float32 if rope_support else None
|
||||
self.q_norm = RMSNorm(self.head_dim, rms_norm_eps, dtype=norm_dtype)
|
||||
self.k_norm = RMSNorm(self.head_dim, rms_norm_eps, dtype=norm_dtype)
|
||||
|
||||
# HPC fused RoPE + QK-Norm + KV-Cache-Write (+ optional FP8 Q quant).
|
||||
# HunYuan V3 applies QK-Norm *before* RoPE, so NORM_THEN_ROPE.
|
||||
|
||||
@@ -39,6 +39,7 @@ from vllm.model_executor.models.module_mapping import MultiModelKeys
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
from vllm.multimodal.inputs import (
|
||||
MultiModalFieldConfig,
|
||||
MultiModalKwargsItem,
|
||||
MultiModalKwargsItems,
|
||||
)
|
||||
from vllm.multimodal.parse import ImageProcessorItems, MultiModalDataItems
|
||||
@@ -837,20 +838,14 @@ class Idefics3ForConditionalGeneration(
|
||||
tower_model="model.vision_model",
|
||||
)
|
||||
|
||||
def get_num_mm_encoder_tokens(
|
||||
def get_mm_lora_token_counts(
|
||||
self,
|
||||
num_image_tokens: int,
|
||||
) -> int:
|
||||
*,
|
||||
modality: str,
|
||||
mm_kwargs: MultiModalKwargsItem | None,
|
||||
num_mm_embeds: int,
|
||||
) -> tuple[int, int | None]:
|
||||
del modality, mm_kwargs
|
||||
hf_config = self.config
|
||||
scale_factor = hf_config.scale_factor
|
||||
|
||||
return num_image_tokens * scale_factor**2
|
||||
|
||||
def get_num_mm_connector_tokens(
|
||||
self,
|
||||
num_vision_tokens: int,
|
||||
) -> int:
|
||||
hf_config = self.config
|
||||
scale_factor = hf_config.scale_factor
|
||||
|
||||
return num_vision_tokens // scale_factor**2
|
||||
return num_mm_embeds * scale_factor**2, num_mm_embeds
|
||||
|
||||
@@ -31,7 +31,7 @@ import torch
|
||||
import torch.nn as nn
|
||||
from torch import Tensor
|
||||
from transformers.models.whisper.tokenization_whisper import LANGUAGES
|
||||
from typing_extensions import Self, TypeIs
|
||||
from typing_extensions import Self, TypeIs, deprecated
|
||||
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.quantization import QuantizationConfig
|
||||
@@ -420,23 +420,16 @@ class SupportsMultiModal(SupportsMultiModalEmbeddings, Protocol):
|
||||
|
||||
yield
|
||||
|
||||
def get_num_mm_encoder_tokens(self, num_image_tokens: int) -> int:
|
||||
"""
|
||||
Implement this function to enable LoRA support
|
||||
for the tower module of the multi-modal model.
|
||||
Given the number of image tokens, output the number of
|
||||
multi-modal encoder tokens.
|
||||
"""
|
||||
...
|
||||
@deprecated(
|
||||
"get_num_mm_encoder_tokens is deprecated; use get_mm_lora_token_counts instead."
|
||||
)
|
||||
def get_num_mm_encoder_tokens(self, num_image_tokens: int) -> int: ...
|
||||
|
||||
def get_num_mm_connector_tokens(self, num_vision_tokens: int) -> int:
|
||||
"""
|
||||
Implement this function to enable LoRA support
|
||||
for the connector module of the multi-modal model.
|
||||
Given the number of vision tokens, output the number of
|
||||
multi-modal connector tokens.
|
||||
"""
|
||||
...
|
||||
@deprecated(
|
||||
"get_num_mm_connector_tokens is deprecated; use "
|
||||
"get_mm_lora_token_counts instead."
|
||||
)
|
||||
def get_num_mm_connector_tokens(self, num_vision_tokens: int) -> int: ...
|
||||
|
||||
def get_mm_lora_token_counts(
|
||||
self,
|
||||
|
||||
@@ -29,6 +29,7 @@ from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
from vllm.multimodal.inputs import (
|
||||
BatchedTensorInputs,
|
||||
MultiModalFieldConfig,
|
||||
MultiModalKwargsItem,
|
||||
MultiModalKwargsItems,
|
||||
)
|
||||
from vllm.multimodal.parse import (
|
||||
@@ -914,19 +915,20 @@ class InternVLChatModel(
|
||||
tower_model="vision_model",
|
||||
)
|
||||
|
||||
def get_num_mm_encoder_tokens(self, num_image_tokens: int) -> int:
|
||||
if num_image_tokens <= 0 or self.num_image_token <= 0:
|
||||
return 0
|
||||
def get_mm_lora_token_counts(
|
||||
self,
|
||||
*,
|
||||
modality: str,
|
||||
mm_kwargs: MultiModalKwargsItem | None,
|
||||
num_mm_embeds: int,
|
||||
) -> tuple[int, int | None]:
|
||||
del modality, mm_kwargs
|
||||
if num_mm_embeds <= 0 or self.num_image_token <= 0:
|
||||
return 0, 0
|
||||
|
||||
num_patches = num_image_tokens // self.num_image_token
|
||||
return num_patches * (self.patch_tokens + 1)
|
||||
|
||||
def get_num_mm_connector_tokens(self, num_vision_tokens: int) -> int:
|
||||
if num_vision_tokens <= 0 or self.num_image_token <= 0:
|
||||
return 0
|
||||
|
||||
num_patches = num_vision_tokens // (self.patch_tokens + 1)
|
||||
return num_patches * self.num_image_token
|
||||
num_patches = num_mm_embeds // self.num_image_token
|
||||
tower_tokens = num_patches * (self.patch_tokens + 1)
|
||||
return tower_tokens, num_patches * self.num_image_token
|
||||
|
||||
# -- SupportsEncoderCudaGraph protocol methods --
|
||||
|
||||
|
||||
@@ -40,6 +40,7 @@ from vllm.multimodal.inputs import (
|
||||
ImageItem,
|
||||
MultiModalFeatureSpec,
|
||||
MultiModalFieldConfig,
|
||||
MultiModalKwargsItem,
|
||||
MultiModalKwargsItems,
|
||||
VideoItem,
|
||||
)
|
||||
@@ -1495,13 +1496,16 @@ class BaseKeyeModule(nn.Module, SupportsMultiModal):
|
||||
tower_model="visual.",
|
||||
)
|
||||
|
||||
def get_num_mm_encoder_tokens(self, num_image_tokens: int) -> int:
|
||||
def get_mm_lora_token_counts(
|
||||
self,
|
||||
*,
|
||||
modality: str,
|
||||
mm_kwargs: MultiModalKwargsItem | None,
|
||||
num_mm_embeds: int,
|
||||
) -> tuple[int, int | None]:
|
||||
del modality, mm_kwargs
|
||||
merge_size = self.config.vision_config.spatial_merge_size
|
||||
return num_image_tokens * merge_size**2
|
||||
|
||||
def get_num_mm_connector_tokens(self, num_vision_tokens: int) -> int:
|
||||
merge_size = self.config.vision_config.spatial_merge_size
|
||||
return num_vision_tokens // merge_size**2
|
||||
return num_mm_embeds * merge_size**2, num_mm_embeds
|
||||
|
||||
|
||||
@MULTIMODAL_REGISTRY.register_processor(
|
||||
|
||||
@@ -35,6 +35,7 @@ from vllm.model_executor.models.module_mapping import MultiModelKeys
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
from vllm.multimodal.inputs import (
|
||||
MultiModalFieldConfig,
|
||||
MultiModalKwargsItem,
|
||||
MultiModalKwargsItems,
|
||||
)
|
||||
from vllm.multimodal.parse import ImageProcessorItems, ImageSize, MultiModalDataItems
|
||||
@@ -1284,12 +1285,13 @@ class Lfm2VLForConditionalGeneration(
|
||||
tower_model="vision_tower",
|
||||
)
|
||||
|
||||
def get_num_mm_encoder_tokens(self, num_image_tokens: int) -> int:
|
||||
def get_mm_lora_token_counts(
|
||||
self,
|
||||
*,
|
||||
modality: str,
|
||||
mm_kwargs: MultiModalKwargsItem | None,
|
||||
num_mm_embeds: int,
|
||||
) -> tuple[int, int | None]:
|
||||
del modality, mm_kwargs
|
||||
downsample_factor = self.config.downsample_factor
|
||||
|
||||
return num_image_tokens * downsample_factor**2
|
||||
|
||||
def get_num_mm_connector_tokens(self, num_vision_tokens: int) -> int:
|
||||
downsample_factor = self.config.downsample_factor
|
||||
|
||||
return num_vision_tokens // downsample_factor**2
|
||||
return num_mm_embeds * downsample_factor**2, num_mm_embeds
|
||||
|
||||
@@ -335,10 +335,14 @@ class Eagle3LlamaForCausalLM(_Eagle3LlamaForCausalLMBase):
|
||||
self.logits_processor = LogitsProcessor(
|
||||
self.config.draft_vocab_size, scale=logit_scale
|
||||
)
|
||||
self.draft_id_to_target_id = nn.Parameter(
|
||||
torch.zeros(self.config.draft_vocab_size, dtype=torch.long),
|
||||
requires_grad=False,
|
||||
)
|
||||
target_vocab_size = vllm_config.model_config.get_vocab_size()
|
||||
if self.config.draft_vocab_size != target_vocab_size:
|
||||
self.draft_id_to_target_id = nn.Parameter(
|
||||
torch.zeros(self.config.draft_vocab_size, dtype=torch.long),
|
||||
requires_grad=False,
|
||||
)
|
||||
else:
|
||||
self.draft_id_to_target_id = None
|
||||
|
||||
self.use_parallel_drafting = speculative_config.parallel_drafting
|
||||
|
||||
|
||||
@@ -28,6 +28,7 @@ from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
from vllm.multimodal.cache import BaseMultiModalProcessorCache
|
||||
from vllm.multimodal.inputs import (
|
||||
MultiModalFieldConfig,
|
||||
MultiModalKwargsItem,
|
||||
MultiModalKwargsItems,
|
||||
)
|
||||
from vllm.multimodal.parse import (
|
||||
@@ -739,18 +740,12 @@ class LlavaForConditionalGeneration(
|
||||
tower_model="vision_tower",
|
||||
)
|
||||
|
||||
def get_num_mm_encoder_tokens(
|
||||
def get_mm_lora_token_counts(
|
||||
self,
|
||||
num_image_tokens: int,
|
||||
) -> int:
|
||||
# LLaVA's vision encoder outputs one token per patch without
|
||||
# spatial merging or pixel shuffle
|
||||
return num_image_tokens
|
||||
|
||||
def get_num_mm_connector_tokens(
|
||||
self,
|
||||
num_vision_tokens: int,
|
||||
) -> int:
|
||||
# LLaVA's MLP projector outputs the same number of tokens
|
||||
# as it receives from the vision encoder (1:1 mapping)
|
||||
return num_vision_tokens
|
||||
*,
|
||||
modality: str,
|
||||
mm_kwargs: MultiModalKwargsItem | None,
|
||||
num_mm_embeds: int,
|
||||
) -> tuple[int, int | None]:
|
||||
del modality, mm_kwargs
|
||||
return num_mm_embeds, num_mm_embeds
|
||||
|
||||
@@ -17,6 +17,7 @@ from vllm.model_executor.models.clip import CLIPVisionModel
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
from vllm.multimodal.inputs import (
|
||||
MultiModalFieldConfig,
|
||||
MultiModalKwargsItem,
|
||||
MultiModalKwargsItems,
|
||||
)
|
||||
from vllm.multimodal.parse import (
|
||||
@@ -494,31 +495,30 @@ class LlavaNextVideoForConditionalGeneration(
|
||||
tower_model="vision_tower",
|
||||
)
|
||||
|
||||
def get_num_mm_encoder_tokens(
|
||||
def get_mm_lora_token_counts(
|
||||
self,
|
||||
num_video_tokens: int,
|
||||
) -> int:
|
||||
*,
|
||||
modality: str,
|
||||
mm_kwargs: MultiModalKwargsItem | None,
|
||||
num_mm_embeds: int,
|
||||
) -> tuple[int, int | None]:
|
||||
del modality, mm_kwargs
|
||||
|
||||
# Invert the spatial pooling done by `vision_resampler`: each frame
|
||||
# contributes `pooled_grid_length ** 2` tokens after the language
|
||||
# model's placeholder count, but `patch_grid_length ** 2` tokens
|
||||
# when it leaves the vision encoder.
|
||||
pooled_tokens_per_frame = self.pooled_grid_length**2
|
||||
if num_video_tokens <= 0 or pooled_tokens_per_frame <= 0:
|
||||
return 0
|
||||
|
||||
num_frames = num_video_tokens // pooled_tokens_per_frame
|
||||
return num_frames * (self.patch_grid_length**2)
|
||||
|
||||
def get_num_mm_connector_tokens(
|
||||
self,
|
||||
num_vision_tokens: int,
|
||||
) -> int:
|
||||
# The projector is length-preserving; it runs after
|
||||
# `vision_resampler` has already pooled each frame down to
|
||||
# `pooled_grid_length ** 2` tokens.
|
||||
patch_tokens_per_frame = self.patch_grid_length**2
|
||||
if num_vision_tokens <= 0 or patch_tokens_per_frame <= 0:
|
||||
return 0
|
||||
if (
|
||||
num_mm_embeds <= 0
|
||||
or pooled_tokens_per_frame <= 0
|
||||
or patch_tokens_per_frame <= 0
|
||||
):
|
||||
return 0, 0
|
||||
|
||||
num_frames = num_vision_tokens // patch_tokens_per_frame
|
||||
return num_frames * (self.pooled_grid_length**2)
|
||||
num_frames = num_mm_embeds // pooled_tokens_per_frame
|
||||
return (
|
||||
num_frames * patch_tokens_per_frame,
|
||||
num_frames * pooled_tokens_per_frame,
|
||||
)
|
||||
|
||||
@@ -674,14 +674,6 @@ class MiniCPMV4_6ProcessingInfo(MiniCPMVProcessingInfo):
|
||||
|
||||
|
||||
class MiniCPMV4_6ViTWindowAttentionSelfAttn(nn.Module):
|
||||
hf_to_vllm_mapper = WeightsMapper(
|
||||
orig_to_new_stacked={
|
||||
".q_proj": (".qkv_proj", "q"),
|
||||
".k_proj": (".qkv_proj", "k"),
|
||||
".v_proj": (".qkv_proj", "v"),
|
||||
}
|
||||
)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config,
|
||||
@@ -729,10 +721,6 @@ class MiniCPMV4_6ViTWindowAttentionSelfAttn(nn.Module):
|
||||
out, _ = self.out_proj(attn_out)
|
||||
return out
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
loader = AutoWeightsLoader(self)
|
||||
return loader.load_weights(weights, mapper=self.hf_to_vllm_mapper)
|
||||
|
||||
|
||||
class MiniCPMV4_6ViTWindowAttentionMerger(nn.Module):
|
||||
def __init__(
|
||||
@@ -971,6 +959,11 @@ class MiniCPMV4_6ForConditionalGeneration(
|
||||
supports_encoder_tp_data = True
|
||||
|
||||
hf_to_vllm_mapper = WeightsMapper(
|
||||
orig_to_new_stacked={
|
||||
".q_proj": (".qkv_proj", "q"),
|
||||
".k_proj": (".qkv_proj", "k"),
|
||||
".v_proj": (".qkv_proj", "v"),
|
||||
},
|
||||
orig_to_new_prefix={
|
||||
# transformers v5.7+ uses `vision_tower` and nests `vit_merger`
|
||||
# inside it. Order matters: more specific prefix must come first.
|
||||
@@ -982,7 +975,7 @@ class MiniCPMV4_6ForConditionalGeneration(
|
||||
"model.language_model.": "language_model.model.",
|
||||
"lm_head.": "language_model.lm_head.",
|
||||
"mtp.": None,
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
packed_modules_mapping = {
|
||||
|
||||
@@ -60,6 +60,7 @@ from vllm.model_executor.models.module_mapping import MultiModelKeys
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
from vllm.multimodal.inputs import (
|
||||
MultiModalFieldConfig,
|
||||
MultiModalKwargsItem,
|
||||
MultiModalKwargsItems,
|
||||
)
|
||||
from vllm.multimodal.parse import ImageProcessorItems, ImageSize, MultiModalDataItems
|
||||
@@ -1281,21 +1282,18 @@ class Llama4ForConditionalGeneration(
|
||||
tower_model="vision_model.",
|
||||
)
|
||||
|
||||
def get_num_mm_encoder_tokens(self, num_image_tokens: int) -> int:
|
||||
def get_mm_lora_token_counts(
|
||||
self,
|
||||
*,
|
||||
modality: str,
|
||||
mm_kwargs: MultiModalKwargsItem | None,
|
||||
num_mm_embeds: int,
|
||||
) -> tuple[int, int | None]:
|
||||
del modality, mm_kwargs
|
||||
vision_config = self.config.vision_config
|
||||
patches_per_chunk = Mllama4ProcessingInfo.get_patch_per_chunk(vision_config)
|
||||
if num_image_tokens <= 0 or patches_per_chunk <= 0:
|
||||
return 0
|
||||
if num_mm_embeds <= 0 or patches_per_chunk <= 0:
|
||||
return 0, 0
|
||||
raw_patches = (vision_config.image_size // vision_config.patch_size) ** 2
|
||||
num_chunks = num_image_tokens // patches_per_chunk
|
||||
# Encoder processes raw_patches + 1 (CLS) per chunk
|
||||
return num_chunks * (raw_patches + 1)
|
||||
|
||||
def get_num_mm_connector_tokens(self, num_vision_tokens: int) -> int:
|
||||
vision_config = self.config.vision_config
|
||||
raw_patches = (vision_config.image_size // vision_config.patch_size) ** 2
|
||||
if num_vision_tokens <= 0:
|
||||
return 0
|
||||
num_chunks = num_vision_tokens // (raw_patches + 1)
|
||||
patches_per_chunk = Mllama4ProcessingInfo.get_patch_per_chunk(vision_config)
|
||||
return num_chunks * patches_per_chunk
|
||||
num_chunks = num_mm_embeds // patches_per_chunk
|
||||
return num_chunks * (raw_patches + 1), num_chunks * patches_per_chunk
|
||||
|
||||
@@ -47,6 +47,7 @@ from vllm.model_executor.model_loader.weight_utils import default_weight_loader
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
from vllm.multimodal.inputs import (
|
||||
MultiModalFieldConfig,
|
||||
MultiModalKwargsItem,
|
||||
MultiModalKwargsItems,
|
||||
)
|
||||
from vllm.multimodal.parse import ImageSize, MultiModalDataItems
|
||||
@@ -1104,11 +1105,15 @@ class Moondream3ForCausalLM(nn.Module, SupportsMultiModal, SupportsPP):
|
||||
def get_language_model(self) -> nn.Module:
|
||||
return self.text
|
||||
|
||||
def get_num_mm_encoder_tokens(self, num_image_tokens: int) -> int:
|
||||
return num_image_tokens
|
||||
|
||||
def get_num_mm_connector_tokens(self, num_vision_tokens: int) -> int:
|
||||
return num_vision_tokens
|
||||
def get_mm_lora_token_counts(
|
||||
self,
|
||||
*,
|
||||
modality: str,
|
||||
mm_kwargs: MultiModalKwargsItem | None,
|
||||
num_mm_embeds: int,
|
||||
) -> tuple[int, int | None]:
|
||||
del modality, mm_kwargs
|
||||
return num_mm_embeds, num_mm_embeds
|
||||
|
||||
def _split_pixel_values(
|
||||
self,
|
||||
|
||||
@@ -23,6 +23,7 @@ from vllm.config import VllmConfig
|
||||
from vllm.config.multimodal import BaseDummyOptions, VideoDummyOptions
|
||||
from vllm.inputs import MultiModalDataDict, MultiModalInput
|
||||
from vllm.logger import init_logger
|
||||
from vllm.lora.layers.base import BaseLayerWithLoRA
|
||||
from vllm.model_executor.layers.activation import ReLUSquaredActivation
|
||||
from vllm.model_executor.layers.layernorm import RMSNorm
|
||||
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
|
||||
@@ -30,6 +31,7 @@ from vllm.model_executor.models.interfaces import (
|
||||
HasInnerState,
|
||||
IsHybrid,
|
||||
MultiModalEmbeddings,
|
||||
SupportsLoRA,
|
||||
SupportsMultiModal,
|
||||
SupportsMultiModalPruning,
|
||||
)
|
||||
@@ -897,11 +899,22 @@ class NanoNemotronVLDummyInputsBuilder(
|
||||
dummy_inputs=NanoNemotronVLDummyInputsBuilder,
|
||||
)
|
||||
class NemotronH_Nano_VL_V2(
|
||||
nn.Module, HasInnerState, IsHybrid, SupportsMultiModal, SupportsMultiModalPruning
|
||||
nn.Module,
|
||||
HasInnerState,
|
||||
IsHybrid,
|
||||
SupportsMultiModal,
|
||||
SupportsMultiModalPruning,
|
||||
SupportsLoRA,
|
||||
):
|
||||
requires_sequential_video_encoding = True
|
||||
"""Temporarily needed for dynamic res video w/ conv3d, doesn't support bs>1 yet"""
|
||||
|
||||
# LoRA covers the language model only
|
||||
is_non_gated_moe = NemotronHForCausalLM.is_non_gated_moe
|
||||
packed_modules_mapping = NemotronHForCausalLM.packed_modules_mapping
|
||||
embedding_modules = NemotronHForCausalLM.embedding_modules
|
||||
lora_skip_prefixes = NemotronHForCausalLM.lora_skip_prefixes
|
||||
|
||||
hf_to_vllm_mapper = WeightsMapper(
|
||||
orig_to_new_prefix={
|
||||
"language_model.backbone": "language_model.model",
|
||||
@@ -1331,7 +1344,19 @@ class NemotronH_Nano_VL_V2(
|
||||
|
||||
# Create final video embeddings, merging text embeddings for indicator
|
||||
# tokens with video embeddings
|
||||
text_embeddings = self.get_language_model().embed_input_ids(repl_token_ids)
|
||||
|
||||
# LoRA support -
|
||||
# These replacement tokens are produced inside the encoder, so they are
|
||||
# absent from the request-token batch that the LoRA adapter index
|
||||
# mapping is built from, and there can be more
|
||||
# of them than max_num_batched_tokens.
|
||||
# Embed them with the base weights -
|
||||
# the LoRA delta is undefined for tokens with no mapping entry.
|
||||
embed_tokens = self.get_language_model().model.embed_tokens
|
||||
if isinstance(embed_tokens, BaseLayerWithLoRA):
|
||||
embed_tokens = embed_tokens.base_layer
|
||||
text_embeddings = embed_tokens(repl_token_ids)
|
||||
|
||||
final_video_embeddings = _merge_multimodal_embeddings(
|
||||
inputs_embeds=text_embeddings,
|
||||
multimodal_embeddings=video_embeddings,
|
||||
|
||||
@@ -25,7 +25,11 @@ import torch
|
||||
from torch import nn
|
||||
|
||||
from vllm.compilation.decorators import support_torch_compile
|
||||
from vllm.config import CacheConfig, ModelConfig, VllmConfig
|
||||
from vllm.config import (
|
||||
CacheConfig,
|
||||
ModelConfig,
|
||||
VllmConfig,
|
||||
)
|
||||
from vllm.config.parallel import ParallelConfig
|
||||
from vllm.distributed import get_ep_group, get_tensor_model_parallel_world_size
|
||||
from vllm.distributed.communication_op import tensor_model_parallel_all_gather
|
||||
@@ -38,12 +42,14 @@ from vllm.model_executor.layers.fused_moe import (
|
||||
activation_without_mul,
|
||||
fused_moe_make_expert_params_mapping,
|
||||
)
|
||||
from vllm.model_executor.layers.fusion.fused_act_quant import maybe_fused_act_quant
|
||||
from vllm.model_executor.layers.layernorm import RMSNorm
|
||||
from vllm.model_executor.layers.linear import (
|
||||
ColumnParallelLinear,
|
||||
QKVParallelLinear,
|
||||
ReplicatedLinear,
|
||||
RowParallelLinear,
|
||||
UnquantizedLinearMethod,
|
||||
)
|
||||
from vllm.model_executor.layers.logits_processor import LogitsProcessor
|
||||
from vllm.model_executor.layers.mamba.mamba_mixer2 import MambaMixer2
|
||||
@@ -118,7 +124,7 @@ class NemotronHMLP(nn.Module):
|
||||
|
||||
def forward(self, x: torch.Tensor):
|
||||
x, _ = self.up_proj(x)
|
||||
x = self.act_fn(x)
|
||||
x = maybe_fused_act_quant(self.act_fn, x, self.down_proj)
|
||||
x, _ = self.down_proj(x)
|
||||
return x
|
||||
|
||||
@@ -199,6 +205,17 @@ class NemotronHMoE(nn.Module):
|
||||
disable_tp=self.is_sequence_parallel,
|
||||
prefix=f"{prefix}.fc2_latent_proj",
|
||||
)
|
||||
# A bias-free, unquantized linear commutes with the TP sum
|
||||
# (sum_r W x_r == W sum_r x_r), so one reduce after the transform
|
||||
# suffices. Test the layer, not the model-wide `quant_config`: ModelOpt
|
||||
# excludes the latent projections, so quantized checkpoints still get
|
||||
# an UnquantizedLinearMethod here.
|
||||
self.fc2_latent_proj.reduce_commutative = (
|
||||
not config.mlp_bias
|
||||
and isinstance(
|
||||
self.fc2_latent_proj.quant_method, UnquantizedLinearMethod
|
||||
)
|
||||
)
|
||||
else:
|
||||
self.fc1_latent_proj = None
|
||||
self.fc2_latent_proj = None
|
||||
|
||||
@@ -677,14 +677,18 @@ class OpenPanguSinkAttention(nn.Module):
|
||||
},
|
||||
)
|
||||
else:
|
||||
self.param_sink_value = torch.zeros(
|
||||
(
|
||||
self.param_sink_number,
|
||||
self.num_kv_heads,
|
||||
self.v_channels,
|
||||
self.register_buffer(
|
||||
"param_sink_value",
|
||||
torch.zeros(
|
||||
(
|
||||
self.param_sink_number,
|
||||
self.num_kv_heads,
|
||||
self.v_channels,
|
||||
),
|
||||
device=current_platform.current_device(),
|
||||
dtype=config.torch_dtype,
|
||||
),
|
||||
device=current_platform.current_device(),
|
||||
dtype=config.torch_dtype,
|
||||
persistent=False,
|
||||
)
|
||||
# To enable dummy run with out weight
|
||||
self.post_weight_load()
|
||||
|
||||
@@ -24,7 +24,11 @@ from vllm.model_executor.models.interfaces import (
|
||||
SupportsPP,
|
||||
)
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
from vllm.multimodal.inputs import MultiModalFieldConfig, MultiModalKwargsItems
|
||||
from vllm.multimodal.inputs import (
|
||||
MultiModalFieldConfig,
|
||||
MultiModalKwargsItem,
|
||||
MultiModalKwargsItems,
|
||||
)
|
||||
from vllm.multimodal.parse import (
|
||||
ImageEmbeddingItems,
|
||||
ImageProcessorItems,
|
||||
@@ -487,11 +491,15 @@ class OpenVLAForActionPrediction(nn.Module, SupportsMultiModal, SupportsPP):
|
||||
tower_model="vision_backbone",
|
||||
)
|
||||
|
||||
def get_num_mm_encoder_tokens(self, num_image_tokens: int) -> int:
|
||||
return num_image_tokens
|
||||
|
||||
def get_num_mm_connector_tokens(self, num_vision_tokens: int) -> int:
|
||||
return num_vision_tokens
|
||||
def get_mm_lora_token_counts(
|
||||
self,
|
||||
*,
|
||||
modality: str,
|
||||
mm_kwargs: MultiModalKwargsItem | None,
|
||||
num_mm_embeds: int,
|
||||
) -> tuple[int, int | None]:
|
||||
del modality, mm_kwargs
|
||||
return num_mm_embeds, num_mm_embeds
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
def maybe_rename_vision_weights(
|
||||
|
||||
@@ -14,6 +14,7 @@ from vllm.logger import init_logger
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
from vllm.multimodal.inputs import (
|
||||
MultiModalFieldConfig,
|
||||
MultiModalKwargsItem,
|
||||
MultiModalKwargsItems,
|
||||
)
|
||||
from vllm.multimodal.parse import (
|
||||
@@ -401,8 +402,12 @@ class PaliGemmaForConditionalGeneration(
|
||||
tower_model="vision_tower",
|
||||
)
|
||||
|
||||
def get_num_mm_encoder_tokens(self, num_image_tokens: int) -> int:
|
||||
return num_image_tokens
|
||||
|
||||
def get_num_mm_connector_tokens(self, num_vision_tokens: int) -> int:
|
||||
return num_vision_tokens
|
||||
def get_mm_lora_token_counts(
|
||||
self,
|
||||
*,
|
||||
modality: str,
|
||||
mm_kwargs: MultiModalKwargsItem | None,
|
||||
num_mm_embeds: int,
|
||||
) -> tuple[int, int | None]:
|
||||
del modality, mm_kwargs
|
||||
return num_mm_embeds, num_mm_embeds
|
||||
|
||||
@@ -42,6 +42,7 @@ from vllm.model_executor.models.utils import WeightsMapper
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY, MultiModalKwargsItems
|
||||
from vllm.multimodal.inputs import (
|
||||
MultiModalFieldConfig,
|
||||
MultiModalKwargsItem,
|
||||
MultiModalKwargsOptionalItems,
|
||||
NestedTensors,
|
||||
)
|
||||
@@ -623,17 +624,18 @@ class PixtralForConditionalGeneration(
|
||||
tower_model="vision_encoder",
|
||||
)
|
||||
|
||||
def get_num_mm_encoder_tokens(self, num_image_tokens: int) -> int:
|
||||
def get_mm_lora_token_counts(
|
||||
self,
|
||||
*,
|
||||
modality: str,
|
||||
mm_kwargs: MultiModalKwargsItem | None,
|
||||
num_mm_embeds: int,
|
||||
) -> tuple[int, int | None]:
|
||||
del modality, mm_kwargs
|
||||
if getattr(self, "patch_merger", None) is None:
|
||||
return num_image_tokens
|
||||
return num_mm_embeds, num_mm_embeds
|
||||
merge_size = self.vision_args.spatial_merge_size
|
||||
return num_image_tokens * (merge_size**2)
|
||||
|
||||
def get_num_mm_connector_tokens(self, num_vision_tokens: int) -> int:
|
||||
if getattr(self, "patch_merger", None) is None:
|
||||
return num_vision_tokens
|
||||
merge_size = self.vision_args.spatial_merge_size
|
||||
return num_vision_tokens // (merge_size**2)
|
||||
return num_mm_embeds * (merge_size**2), num_mm_embeds
|
||||
|
||||
|
||||
# Vision encoder
|
||||
|
||||
@@ -70,6 +70,7 @@ from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
from vllm.multimodal.inputs import (
|
||||
MultiModalFeatureSpec,
|
||||
MultiModalFieldConfig,
|
||||
MultiModalKwargsItem,
|
||||
MultiModalKwargsItems,
|
||||
)
|
||||
from vllm.multimodal.parse import MultiModalDataItems
|
||||
@@ -2050,21 +2051,15 @@ class Qwen2_5_VLForConditionalGeneration(
|
||||
tower_model="visual.",
|
||||
)
|
||||
|
||||
def get_num_mm_encoder_tokens(
|
||||
def get_mm_lora_token_counts(
|
||||
self,
|
||||
num_image_tokens: int,
|
||||
) -> int:
|
||||
*,
|
||||
modality: str,
|
||||
mm_kwargs: MultiModalKwargsItem | None,
|
||||
num_mm_embeds: int,
|
||||
) -> tuple[int, int | None]:
|
||||
del modality, mm_kwargs
|
||||
hf_config = self.config
|
||||
vision_config = hf_config.vision_config
|
||||
merge_size = vision_config.spatial_merge_size
|
||||
|
||||
return num_image_tokens * merge_size**2
|
||||
|
||||
def get_num_mm_connector_tokens(
|
||||
self,
|
||||
num_vision_tokens: int,
|
||||
) -> int:
|
||||
hf_config = self.config
|
||||
vision_config = hf_config.vision_config
|
||||
merge_size = vision_config.spatial_merge_size
|
||||
return num_vision_tokens // merge_size**2
|
||||
return num_mm_embeds * merge_size**2, num_mm_embeds
|
||||
|
||||
@@ -66,6 +66,7 @@ from vllm.multimodal.inputs import (
|
||||
ImageItem,
|
||||
MultiModalFeatureSpec,
|
||||
MultiModalFieldConfig,
|
||||
MultiModalKwargsItem,
|
||||
MultiModalKwargsItems,
|
||||
VideoItem,
|
||||
)
|
||||
@@ -1747,21 +1748,15 @@ class Qwen2VLForConditionalGeneration(
|
||||
tower_model="visual.",
|
||||
)
|
||||
|
||||
def get_num_mm_encoder_tokens(
|
||||
def get_mm_lora_token_counts(
|
||||
self,
|
||||
num_image_tokens: int,
|
||||
) -> int:
|
||||
*,
|
||||
modality: str,
|
||||
mm_kwargs: MultiModalKwargsItem | None,
|
||||
num_mm_embeds: int,
|
||||
) -> tuple[int, int | None]:
|
||||
del modality, mm_kwargs
|
||||
hf_config = self.config
|
||||
vision_config = hf_config.vision_config
|
||||
merge_size = vision_config.spatial_merge_size
|
||||
|
||||
return num_image_tokens * merge_size**2
|
||||
|
||||
def get_num_mm_connector_tokens(
|
||||
self,
|
||||
num_vision_tokens: int,
|
||||
) -> int:
|
||||
hf_config = self.config
|
||||
vision_config = hf_config.vision_config
|
||||
merge_size = vision_config.spatial_merge_size
|
||||
return num_vision_tokens // merge_size**2
|
||||
return num_mm_embeds * merge_size**2, num_mm_embeds
|
||||
|
||||
@@ -67,6 +67,7 @@ from vllm.multimodal.inputs import (
|
||||
AudioItem,
|
||||
MultiModalFeatureSpec,
|
||||
MultiModalFieldConfig,
|
||||
MultiModalKwargsItem,
|
||||
MultiModalKwargsItems,
|
||||
)
|
||||
from vllm.multimodal.parse import (
|
||||
@@ -625,16 +626,19 @@ class Qwen3ASRForConditionalGeneration(
|
||||
tower_model=["audio_tower."],
|
||||
)
|
||||
|
||||
def get_num_mm_encoder_tokens(self, num_audio_tokens: int) -> int:
|
||||
"""Return the number of tokens processed by the audio tower encoder.
|
||||
|
||||
Required for LoRA support on the tower module.
|
||||
"""
|
||||
def get_mm_lora_token_counts(
|
||||
self,
|
||||
*,
|
||||
modality: str,
|
||||
mm_kwargs: MultiModalKwargsItem | None,
|
||||
num_mm_embeds: int,
|
||||
) -> tuple[int, int | None]:
|
||||
del modality, mm_kwargs
|
||||
# For Qwen3-ASR, the audio tower produces one embedding per audio
|
||||
# placeholder token inserted into the prompt (no additional
|
||||
# merge/downsample step like vision towers). Therefore, the encoder
|
||||
# token budget is identity.
|
||||
return num_audio_tokens
|
||||
return num_mm_embeds, None
|
||||
|
||||
@classmethod
|
||||
def get_speech_to_text_config(
|
||||
|
||||
@@ -254,7 +254,10 @@ class Qwen3DSparkForCausalLM(DFlashQwen3ForCausalLM):
|
||||
self.config.draft_vocab_size, scale=logit_scale
|
||||
)
|
||||
self.target_vocab_size = vllm_config.model_config.get_vocab_size()
|
||||
if self.config.draft_vocab_size != self.target_vocab_size:
|
||||
# Only a pruned draft (subset of the target vocab) needs a d2t mapping to
|
||||
# scatter ids up. A draft >= the target vocab (e.g. padded to the target's
|
||||
# physical embedding size) maps identically, so no d2t is needed.
|
||||
if self.config.draft_vocab_size < self.target_vocab_size:
|
||||
self.draft_id_to_target_id = nn.Parameter(
|
||||
torch.zeros(self.config.draft_vocab_size, dtype=torch.long),
|
||||
requires_grad=False,
|
||||
@@ -334,7 +337,7 @@ class Qwen3DSparkForCausalLM(DFlashQwen3ForCausalLM):
|
||||
# embed_tokens / lm_head are optional; when omitted they are shared from
|
||||
# the target by load_dspark_model, so skip the unloaded params here.
|
||||
uses_expanded_input_vocab = self.config.vocab_size > self.target_vocab_size
|
||||
uses_reduced_vocab = self.config.draft_vocab_size != self.target_vocab_size
|
||||
uses_reduced_vocab = self.config.draft_vocab_size < self.target_vocab_size
|
||||
if uses_expanded_input_vocab and not includes_embed_tokens:
|
||||
raise ValueError(
|
||||
"Qwen3 DSpark checkpoints whose input vocab_size is larger than "
|
||||
|
||||
@@ -309,10 +309,14 @@ class Eagle3Qwen3ForCausalLM(Qwen3ForCausalLM):
|
||||
self.logits_processor = LogitsProcessor(
|
||||
self.config.draft_vocab_size, scale=logit_scale
|
||||
)
|
||||
self.draft_id_to_target_id = nn.Parameter(
|
||||
torch.zeros(self.config.draft_vocab_size, dtype=torch.long),
|
||||
requires_grad=False,
|
||||
)
|
||||
target_vocab_size = vllm_config.model_config.get_vocab_size()
|
||||
if self.config.draft_vocab_size != target_vocab_size:
|
||||
self.draft_id_to_target_id = nn.Parameter(
|
||||
torch.zeros(self.config.draft_vocab_size, dtype=torch.long),
|
||||
requires_grad=False,
|
||||
)
|
||||
else:
|
||||
self.draft_id_to_target_id = None
|
||||
|
||||
self.use_parallel_drafting = vllm_config.speculative_config.parallel_drafting
|
||||
|
||||
|
||||
@@ -378,7 +378,7 @@ class Qwen3NextAttention(nn.Module):
|
||||
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 (current_platform.is_cuda() or current_platform.is_xpu())
|
||||
and supports_dtype
|
||||
and (text_only or supports_mrope)
|
||||
)
|
||||
|
||||
@@ -3077,24 +3077,18 @@ class Qwen3VLForConditionalGeneration(
|
||||
tower_model="visual.",
|
||||
)
|
||||
|
||||
def get_num_mm_encoder_tokens(
|
||||
def get_mm_lora_token_counts(
|
||||
self,
|
||||
num_image_tokens: int,
|
||||
) -> int:
|
||||
*,
|
||||
modality: str,
|
||||
mm_kwargs: MultiModalKwargsItem | None,
|
||||
num_mm_embeds: int,
|
||||
) -> tuple[int, int | None]:
|
||||
del modality, mm_kwargs
|
||||
hf_config = self.config
|
||||
vision_config = hf_config.vision_config
|
||||
merge_size = vision_config.spatial_merge_size
|
||||
|
||||
return num_image_tokens * merge_size**2
|
||||
|
||||
def get_num_mm_connector_tokens(
|
||||
self,
|
||||
num_vision_tokens: int,
|
||||
) -> int:
|
||||
hf_config = self.config
|
||||
vision_config = hf_config.vision_config
|
||||
merge_size = vision_config.spatial_merge_size
|
||||
return num_vision_tokens // merge_size**2
|
||||
return num_mm_embeds * merge_size**2, num_mm_embeds
|
||||
|
||||
|
||||
@lru_cache
|
||||
|
||||
@@ -377,7 +377,7 @@ _MULTIMODAL_MODELS = {
|
||||
"DeepseekV4ForConditionalGeneration",
|
||||
),
|
||||
"DeepseekV41ForCausalLM": (
|
||||
"vllm.models.deepseek_v4_1",
|
||||
"vllm.models.deepseek_v41",
|
||||
"DeepseekV41ForCausalLM",
|
||||
),
|
||||
"Dots3NoteForCausalLM": (
|
||||
@@ -645,7 +645,7 @@ _SPECULATIVE_DECODING_MODELS = {
|
||||
"DFlashMuseGlimmerAssistantModel": ("qwen3_dflash", "DFlashQwen3ForCausalLM"),
|
||||
"DSparkDraftModel": ("vllm.models.deepseek_v4", "DSparkDeepseekV4ForCausalLM"),
|
||||
"DSparkV41DraftModel": (
|
||||
"vllm.models.deepseek_v4_1",
|
||||
"vllm.models.deepseek_v41",
|
||||
"DSparkDeepseekV4ForCausalLM",
|
||||
),
|
||||
"Qwen3DSparkModel": ("qwen3_dspark", "Qwen3DSparkForCausalLM"),
|
||||
@@ -713,6 +713,7 @@ _TRANSFORMERS_SUPPORTED_MODELS = {
|
||||
"GPTBigCodeForCausalLM": ("transformers", "TransformersForCausalLM"),
|
||||
"HunYuanDenseV1ForCausalLM": ("transformers", "TransformersForCausalLM"),
|
||||
"HunYuanMoEV1ForCausalLM": ("transformers", "TransformersMoEForCausalLM"),
|
||||
"NanbeigeForCausalLM": ("transformers", "TransformersForCausalLM"),
|
||||
"OlmoForCausalLM": ("transformers", "TransformersForCausalLM"),
|
||||
"Olmo2ForCausalLM": ("transformers", "TransformersForCausalLM"),
|
||||
"Olmo3ForCausalLM": ("transformers", "TransformersForCausalLM"),
|
||||
|
||||
@@ -29,6 +29,7 @@ from vllm.model_executor.models.module_mapping import MultiModelKeys
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
from vllm.multimodal.inputs import (
|
||||
MultiModalFieldConfig,
|
||||
MultiModalKwargsItem,
|
||||
MultiModalKwargsItems,
|
||||
NestedTensors,
|
||||
)
|
||||
@@ -373,9 +374,9 @@ def _build_chunk_attn_metadata(
|
||||
valid/padding boundary (equivalent to the key-padding mask the HF
|
||||
implementation uses), while every row still flows through the
|
||||
(potentially LoRA-wrapped) linears, keeping the per-chunk token counts
|
||||
constant as required by `get_num_mm_encoder_tokens` /
|
||||
`get_num_mm_connector_tokens`. Queries at padding positions produce
|
||||
(garbage) outputs, which are trimmed by `audio_token_len` downstream.
|
||||
constant as required by `get_mm_lora_token_counts`. Queries at padding
|
||||
positions produce (garbage) outputs, which are trimmed by `audio_token_len`
|
||||
downstream.
|
||||
"""
|
||||
batch_size = feature_lens.shape[0]
|
||||
starts = np.arange(batch_size, dtype=np.int64) * seq_len
|
||||
@@ -684,7 +685,7 @@ class UltravoxModel(nn.Module, SupportsMultiModal, SupportsPP, SupportsLoRA):
|
||||
|
||||
# LoRA on the tower/connector requires per-item token counts that are
|
||||
# predictable from the placeholder count alone (see
|
||||
# `get_num_mm_encoder_tokens`), so pad every audio chunk's mel input
|
||||
# `get_mm_lora_token_counts`), so pad every audio chunk's mel input
|
||||
# to the tower's full context instead of the batch's max length.
|
||||
self.pad_audio_to_max_context = bool(
|
||||
lora_config is not None and lora_config.enable_tower_connector_lora
|
||||
@@ -769,22 +770,26 @@ class UltravoxModel(nn.Module, SupportsMultiModal, SupportsPP, SupportsLoRA):
|
||||
self.config.audio_config.max_source_positions / self.config.stack_factor
|
||||
)
|
||||
|
||||
def get_num_mm_encoder_tokens(self, num_audio_tokens: int) -> int:
|
||||
def get_mm_lora_token_counts(
|
||||
self,
|
||||
*,
|
||||
modality: str,
|
||||
mm_kwargs: MultiModalKwargsItem | None,
|
||||
num_mm_embeds: int,
|
||||
) -> tuple[int, int | None]:
|
||||
del modality, mm_kwargs
|
||||
# With `pad_audio_to_max_context` (enforced when tower/connector LoRA
|
||||
# is enabled), the tower's LoRA-wrapped linears always run on
|
||||
# `max_source_positions` conv-downsampled tokens per chunk, regardless
|
||||
# of the valid frame count.
|
||||
num_chunks = math.ceil(num_audio_tokens / self._get_max_tokens_per_chunk())
|
||||
return num_chunks * self.config.audio_config.max_source_positions
|
||||
|
||||
def get_num_mm_connector_tokens(self, num_encoder_tokens: int) -> int:
|
||||
num_chunks = math.ceil(num_mm_embeds / self._get_max_tokens_per_chunk())
|
||||
tower_tokens = num_chunks * self.config.audio_config.max_source_positions
|
||||
# The connector runs on the frame-stacked tower output. Stacking pads
|
||||
# each chunk to a multiple of `stack_factor`, so this is
|
||||
# ceil(max_source_positions / stack_factor) tokens per chunk (188 for
|
||||
# whisper's 1500), not `num_encoder_tokens // stack_factor` (187).
|
||||
max_source_positions = self.config.audio_config.max_source_positions
|
||||
num_chunks = num_encoder_tokens // max_source_positions
|
||||
return num_chunks * self._get_max_tokens_per_chunk()
|
||||
# whisper's 1500), not `tower_tokens // stack_factor` (187).
|
||||
connector_tokens = num_chunks * self._get_max_tokens_per_chunk()
|
||||
return tower_tokens, connector_tokens
|
||||
|
||||
def _audio_features_to_embeddings(
|
||||
self,
|
||||
@@ -866,7 +871,7 @@ class UltravoxModel(nn.Module, SupportsMultiModal, SupportsPP, SupportsLoRA):
|
||||
# Pad every chunk to the tower's full context so the number of
|
||||
# tokens processed by the tower/connector per chunk is constant,
|
||||
# keeping the LoRA token mappings computed by
|
||||
# `get_num_mm_encoder_tokens`/`get_num_mm_connector_tokens` exact.
|
||||
# `get_mm_lora_token_counts` exact.
|
||||
# Attention to the extra padding is masked via `audio_lens`.
|
||||
# Over-long inputs are not trimmed here; the tower raises on them.
|
||||
pad_len = self.audio_tower.max_context_length - audio_features.shape[-1]
|
||||
|
||||
@@ -217,9 +217,15 @@ class VoxtralRealtimeGeneration(VoxtralForConditionalGeneration, SupportsRealtim
|
||||
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
|
||||
super().__init__(vllm_config=vllm_config, prefix=prefix)
|
||||
|
||||
assert (
|
||||
not vllm_config.compilation_config.cudagraph_mode.has_full_cudagraphs()
|
||||
), "Voxtral realtime doesn't support full cudagraphs yet. Please use PIECEWISE."
|
||||
# Full cudagraphs are supported for decode-only batches (the encoder's
|
||||
# block-pooling attention builder is capture-safe for uniform
|
||||
# single-token decode). Mixed/prefill batches are not, so block only
|
||||
# pure FULL; FULL_DECODE_ONLY and FULL_AND_PIECEWISE are allowed.
|
||||
cudagraph_mode = vllm_config.compilation_config.cudagraph_mode
|
||||
assert not cudagraph_mode.mixed_mode().has_full_cudagraphs(), (
|
||||
"Voxtral realtime supports full cudagraphs for decode-only batches. "
|
||||
"Use cudagraph_mode=FULL_DECODE_ONLY or FULL_AND_PIECEWISE (not FULL)."
|
||||
)
|
||||
|
||||
self.time_embedding: TimeEmbedding = TimeEmbedding(
|
||||
dim=self.config.text_config.hidden_size
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import copy
|
||||
import functools
|
||||
import logging
|
||||
import math
|
||||
from dataclasses import replace
|
||||
from fractions import Fraction
|
||||
from functools import partial
|
||||
from typing import ClassVar
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
@@ -27,6 +27,7 @@ from vllm.model_executor.models.whisper import WhisperPosEmbedType
|
||||
from vllm.utils.math_utils import cdiv
|
||||
from vllm.v1.attention.backend import (
|
||||
AttentionBackend,
|
||||
AttentionCGSupport,
|
||||
AttentionMetadata,
|
||||
AttentionType,
|
||||
CommonAttentionMetadata,
|
||||
@@ -123,6 +124,16 @@ def create_whisper_attention_backend_with_block_pooling(
|
||||
underlying_impl = underlying_attn_backend.get_impl_cls()
|
||||
|
||||
class WhisperCausalAttentionWithBlockPoolingBuilder(underlying_builder): # type: ignore
|
||||
# Full cudagraphs only for uniform single-token decode: capture bakes in
|
||||
# tensor addresses, so `build` writes metadata into persistent buffers
|
||||
# (below). Prefill/mixed batches fall back to piecewise.
|
||||
_cudagraph_support: ClassVar[AttentionCGSupport] = (
|
||||
AttentionCGSupport.UNIFORM_SINGLE_TOKEN_DECODE
|
||||
)
|
||||
# Disable the update_block_table fast path: it would bypass block pooling
|
||||
# by splicing the raw slot_mapping/block_table into cached metadata.
|
||||
supports_update_block_table: bool = False
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
kv_cache_spec: AttentionSpec,
|
||||
@@ -150,6 +161,38 @@ def create_whisper_attention_backend_with_block_pooling(
|
||||
# num_heads_q for the encoder is the same as num_kv_heads
|
||||
# (no GQA in whisper encoder)
|
||||
self.num_heads_q = kv_cache_spec.num_kv_heads
|
||||
# Persistent capture-safe buffers for pooled metadata; lazily sized
|
||||
# on first `build` to match the incoming tensors' dtype/device.
|
||||
self._pool_buffers_ready = False
|
||||
|
||||
def _maybe_init_pool_buffers(
|
||||
self, common_attn_metadata: CommonAttentionMetadata
|
||||
) -> None:
|
||||
if self._pool_buffers_ready:
|
||||
return
|
||||
device = common_attn_metadata.slot_mapping.device
|
||||
sched = self.vllm_config.scheduler_config
|
||||
self._qsl_buf = torch.empty(
|
||||
sched.max_num_seqs + 1,
|
||||
dtype=common_attn_metadata.query_start_loc.dtype,
|
||||
device=device,
|
||||
)
|
||||
self._seq_buf = torch.empty(
|
||||
sched.max_num_seqs,
|
||||
dtype=common_attn_metadata.seq_lens.dtype,
|
||||
device=device,
|
||||
)
|
||||
self._slot_buf = torch.empty(
|
||||
sched.max_num_batched_tokens * block_pool_size,
|
||||
dtype=common_attn_metadata.slot_mapping.dtype,
|
||||
device=device,
|
||||
)
|
||||
self._pool_arange = torch.arange(
|
||||
block_pool_size,
|
||||
dtype=common_attn_metadata.slot_mapping.dtype,
|
||||
device=device,
|
||||
)
|
||||
self._pool_buffers_ready = True
|
||||
|
||||
def build(
|
||||
self,
|
||||
@@ -157,27 +200,62 @@ def create_whisper_attention_backend_with_block_pooling(
|
||||
common_attn_metadata: CommonAttentionMetadata,
|
||||
fast_build: bool = False,
|
||||
) -> AttentionMetadata:
|
||||
new_common_attn_metadata = copy.deepcopy(common_attn_metadata)
|
||||
new_common_attn_metadata.query_start_loc *= block_pool_size
|
||||
new_common_attn_metadata.query_start_loc_cpu *= block_pool_size
|
||||
new_common_attn_metadata.seq_lens *= block_pool_size
|
||||
if new_common_attn_metadata.seq_lens_cpu_upper_bound is not None:
|
||||
new_common_attn_metadata.seq_lens_cpu_upper_bound *= block_pool_size
|
||||
new_common_attn_metadata.num_actual_tokens *= block_pool_size
|
||||
new_common_attn_metadata.max_query_len *= block_pool_size
|
||||
new_common_attn_metadata.max_seq_len *= block_pool_size
|
||||
original_slot_mapping = common_attn_metadata.slot_mapping
|
||||
common_prefix_len *= block_pool_size
|
||||
new_common_attn_metadata.slot_mapping = (
|
||||
(
|
||||
original_slot_mapping.unsqueeze(1) * block_pool_size
|
||||
+ torch.arange(block_pool_size, device=original_slot_mapping.device)
|
||||
)
|
||||
.flatten()
|
||||
.clamp(min=-1)
|
||||
cm = common_attn_metadata
|
||||
self._maybe_init_pool_buffers(cm)
|
||||
|
||||
# Scale query_start_loc / seq_lens into the persistent buffers.
|
||||
n = cm.query_start_loc.numel()
|
||||
assert n <= self._qsl_buf.numel(), (
|
||||
f"{n=} exceeds pooled query_start_loc buffer {self._qsl_buf.numel()}"
|
||||
)
|
||||
qsl_buf = self._qsl_buf[:n]
|
||||
qsl_buf.copy_(cm.query_start_loc)
|
||||
qsl_buf.mul_(block_pool_size)
|
||||
|
||||
r = cm.seq_lens.numel()
|
||||
assert r <= self._seq_buf.numel(), (
|
||||
f"{r=} exceeds pooled seq_lens buffer {self._seq_buf.numel()}"
|
||||
)
|
||||
seq_buf = self._seq_buf[:r]
|
||||
seq_buf.copy_(cm.seq_lens)
|
||||
seq_buf.mul_(block_pool_size)
|
||||
|
||||
# Expand each slot into block_pool_size contiguous slots. Padding
|
||||
# slots (-1) stay -1 after clamp so the KV write is skipped.
|
||||
m = cm.slot_mapping.numel()
|
||||
assert m * block_pool_size <= self._slot_buf.numel(), (
|
||||
f"pooled slot_mapping {m * block_pool_size} exceeds buffer "
|
||||
f"{self._slot_buf.numel()}"
|
||||
)
|
||||
slot_buf = self._slot_buf[: m * block_pool_size]
|
||||
slot_buf.view(m, block_pool_size).copy_(
|
||||
cm.slot_mapping.unsqueeze(1) * block_pool_size + self._pool_arange
|
||||
)
|
||||
slot_buf.clamp_(min=-1)
|
||||
|
||||
# CPU tensors aren't captured; fresh scaled copies avoid mutating
|
||||
# the runner's shared buffers.
|
||||
qsl_cpu = cm.query_start_loc_cpu * block_pool_size
|
||||
seq_lens_cpu_upper_bound = (
|
||||
cm.seq_lens_cpu_upper_bound * block_pool_size
|
||||
if cm.seq_lens_cpu_upper_bound is not None
|
||||
else None
|
||||
)
|
||||
|
||||
new_common_attn_metadata = cm.replace(
|
||||
query_start_loc=qsl_buf,
|
||||
query_start_loc_cpu=qsl_cpu,
|
||||
seq_lens=seq_buf,
|
||||
seq_lens_cpu_upper_bound=seq_lens_cpu_upper_bound,
|
||||
num_actual_tokens=cm.num_actual_tokens * block_pool_size,
|
||||
max_query_len=cm.max_query_len * block_pool_size,
|
||||
max_seq_len=cm.max_seq_len * block_pool_size,
|
||||
slot_mapping=slot_buf,
|
||||
)
|
||||
return super().build(
|
||||
common_prefix_len, new_common_attn_metadata, fast_build
|
||||
common_prefix_len * block_pool_size,
|
||||
new_common_attn_metadata,
|
||||
fast_build,
|
||||
)
|
||||
|
||||
# NOTE: We need a custom impl so we can use the transformed slot_mapping
|
||||
|
||||
Reference in New Issue
Block a user