[Refactor] Normalize DeepSeek V4.1 model package naming (#56741)
Signed-off-by: Bugen Zhao <i@bugenzhao.com>
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""DeepSeek V4.1 fused ops.
|
||||
|
||||
Single bridging point for the kernels V4.1 shares verbatim with V4: the
|
||||
re-exports below are the only place this package reaches into
|
||||
``vllm.models.deepseek_v4``, so submodules import them from ``.`` instead of
|
||||
naming the V4 path themselves. Keep these imports above the ``.``-relative
|
||||
ones — ``indexer_k_store`` reads them off this partially-initialized module.
|
||||
"""
|
||||
|
||||
from vllm.models.deepseek_v4.common.ops.fused_indexer_q import (
|
||||
MXFP4_BLOCK_SIZE,
|
||||
fused_indexer_q_rope_quant,
|
||||
)
|
||||
from vllm.models.deepseek_v4.common.ops.fused_indexer_q import (
|
||||
_fp32x2_to_fp4x2 as _fp32x2_to_fp4x2, # re-export for .indexer_k_store
|
||||
)
|
||||
from vllm.models.deepseek_v4.common.ops.fused_inv_rope_fp8_quant import (
|
||||
fused_inv_rope_fp8_quant,
|
||||
)
|
||||
|
||||
from .cache_utils import (
|
||||
build_flashinfer_mixed_sparse_indices,
|
||||
combine_topk_swa_indices,
|
||||
compute_global_topk_indices_and_lens,
|
||||
dequantize_and_gather_k_cache,
|
||||
quantize_and_insert_k_cache,
|
||||
)
|
||||
from .indexer_k_store import indexer_k_norm_rope_store
|
||||
|
||||
__all__ = [
|
||||
"MXFP4_BLOCK_SIZE",
|
||||
"build_flashinfer_mixed_sparse_indices",
|
||||
"combine_topk_swa_indices",
|
||||
"compute_global_topk_indices_and_lens",
|
||||
"dequantize_and_gather_k_cache",
|
||||
"fused_indexer_q_rope_quant",
|
||||
"fused_inv_rope_fp8_quant",
|
||||
"indexer_k_norm_rope_store",
|
||||
"quantize_and_insert_k_cache",
|
||||
]
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,383 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""V4.1 state saving/compression and independently schedulable cache insertion."""
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import tl, triton
|
||||
|
||||
if current_platform.is_rocm():
|
||||
from vllm.platforms.rocm import _ON_GFX950
|
||||
else:
|
||||
_ON_GFX950 = False
|
||||
|
||||
# The ring and raw rows a ratio-2 request program pools are not adjacent, so
|
||||
# reading them as one tile means joining two pointers. ROCm's Triton fails to
|
||||
# legalize `tt.join` on pointers, so there the two rows are loaded separately.
|
||||
_JOIN_ROW_PTRS = not current_platform.is_rocm()
|
||||
|
||||
|
||||
def fused_save_compress_norm(
|
||||
kv_score: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
state_cache: torch.Tensor | None,
|
||||
slot_mapping: torch.Tensor,
|
||||
query_start_loc: torch.Tensor | None,
|
||||
token_to_req_indices: torch.Tensor | None,
|
||||
rms_norm_weight: torch.Tensor,
|
||||
rms_norm_eps: float,
|
||||
compress_ratio: int,
|
||||
latent_out: torch.Tensor,
|
||||
) -> None:
|
||||
"""Pool each closed group into a normalized BF16 latent; save FP32 states.
|
||||
|
||||
The latent feeds the main-cache insert and the indexer K path, which the
|
||||
attention layer schedules on separate streams.
|
||||
|
||||
Ratio 2 keeps one ring block per request holding the open group's rows:
|
||||
position ``p`` lives in row ``p % capacity`` and ``slot_mapping`` encodes
|
||||
``block * capacity + p % capacity``. The grid has one program per request
|
||||
followed by one per pair of packed tokens. A request program handles the
|
||||
group that the chunk's first token closes with its predecessor's ring row,
|
||||
then stores the chunk's last ``capacity`` rows to the ring; because the
|
||||
same program does both, ring reads and writes never race. A pair program
|
||||
handles the group that ends inside its pair, reading both rows from the
|
||||
raw input. Ratio 1 has no ring and one program per token; ``slot_mapping``
|
||||
then only marks valid tokens.
|
||||
|
||||
Args:
|
||||
kv_score: FP32 [tokens, 512] for CR1, [tokens, 1024] for CR2.
|
||||
positions: Absolute positions of the packed request tokens.
|
||||
state_cache: Ring FP32 [blocks, capacity, 1024] KV/score states (CR2).
|
||||
slot_mapping: Ring slots (CR2) or main-cache slots (CR1).
|
||||
query_start_loc: [num_reqs + 1] token offsets of each request's chunk.
|
||||
token_to_req_indices: Request indices for the packed token rows.
|
||||
rms_norm_weight: BF16 [512] normalization weight.
|
||||
rms_norm_eps: RMSNorm epsilon.
|
||||
compress_ratio: Group size, either 1 or 2.
|
||||
latent_out: BF16 [tokens, 512], written only at valid group boundaries.
|
||||
"""
|
||||
assert compress_ratio in (1, 2)
|
||||
assert kv_score.dtype == torch.float32
|
||||
assert kv_score.shape[1] == 512 * compress_ratio and kv_score.stride(1) == 1
|
||||
assert latent_out.shape == (kv_score.shape[0], 512)
|
||||
assert latent_out.is_contiguous() and latent_out.dtype == torch.bfloat16
|
||||
assert positions.is_contiguous() and slot_mapping.is_contiguous()
|
||||
# Rows stay 64-byte aligned, as the kernel's tl.multiple_of hint promises.
|
||||
assert kv_score.stride(0) % 16 == 0
|
||||
if compress_ratio == 2:
|
||||
assert state_cache is not None and query_start_loc is not None
|
||||
assert token_to_req_indices is not None
|
||||
assert query_start_loc.is_contiguous()
|
||||
assert token_to_req_indices.is_contiguous()
|
||||
assert state_cache.dtype == torch.float32
|
||||
assert state_cache.shape[2] == 1024 and state_cache.stride(2) == 1
|
||||
assert state_cache.stride(1) % 16 == 0
|
||||
state_stride, state_row_stride, state_block = (
|
||||
state_cache.stride(0),
|
||||
state_cache.stride(1),
|
||||
state_cache.shape[1],
|
||||
)
|
||||
num_reqs = query_start_loc.numel() - 1
|
||||
else:
|
||||
state_cache = query_start_loc = token_to_req_indices = None
|
||||
state_stride = state_row_stride = state_block = 1
|
||||
num_reqs = 0
|
||||
num_tokens = slot_mapping.numel()
|
||||
assert num_tokens <= min(kv_score.shape[0], positions.numel())
|
||||
if num_tokens == 0:
|
||||
return
|
||||
grid = num_reqs + triton.cdiv(num_tokens, compress_ratio)
|
||||
_fused_save_compress_norm_kernel[(grid,)](
|
||||
kv_score,
|
||||
positions,
|
||||
state_cache,
|
||||
slot_mapping,
|
||||
query_start_loc,
|
||||
token_to_req_indices,
|
||||
rms_norm_weight,
|
||||
latent_out,
|
||||
num_tokens,
|
||||
num_reqs,
|
||||
RAW_STRIDE=kv_score.stride(0),
|
||||
STATE_STRIDE=state_stride,
|
||||
STATE_ROW_STRIDE=state_row_stride,
|
||||
STATE_BLOCK=state_block,
|
||||
COMPRESS_RATIO=compress_ratio,
|
||||
EPS=rms_norm_eps,
|
||||
JOIN_ROW_PTRS=_JOIN_ROW_PTRS,
|
||||
num_warps=4,
|
||||
**({"launch_pdl": False} if current_platform.is_cuda() else {}),
|
||||
)
|
||||
|
||||
|
||||
@triton.jit(do_not_specialize=["num_tokens", "num_reqs"])
|
||||
def _fused_save_compress_norm_kernel(
|
||||
raw,
|
||||
positions,
|
||||
state,
|
||||
state_slots,
|
||||
query_start_loc,
|
||||
req_ids,
|
||||
norm_weight,
|
||||
latent,
|
||||
num_tokens,
|
||||
num_reqs,
|
||||
RAW_STRIDE: tl.constexpr,
|
||||
STATE_STRIDE: tl.constexpr,
|
||||
STATE_ROW_STRIDE: tl.constexpr,
|
||||
STATE_BLOCK: tl.constexpr,
|
||||
COMPRESS_RATIO: tl.constexpr,
|
||||
EPS: tl.constexpr,
|
||||
JOIN_ROW_PTRS: tl.constexpr,
|
||||
):
|
||||
pid = tl.program_id(0)
|
||||
d = tl.arange(0, 512)
|
||||
|
||||
if COMPRESS_RATIO == 2: # noqa: SIM102 (constexpr branch, then runtime)
|
||||
if pid < num_reqs:
|
||||
# Request program: the group closed by the chunk's first token,
|
||||
# then the ring tail store.
|
||||
start = tl.load(query_start_loc + pid)
|
||||
end = tl.load(query_start_loc + pid + 1)
|
||||
if start >= end:
|
||||
return
|
||||
state_slot = tl.load(state_slots + start)
|
||||
if state_slot < 0:
|
||||
return
|
||||
position = tl.load(positions + start)
|
||||
if (position + 1) % 2 == 0:
|
||||
ring = state + (state_slot // STATE_BLOCK).to(tl.int64) * STATE_STRIDE
|
||||
prev = ring + ((position - 1) % STATE_BLOCK) * STATE_ROW_STRIDE
|
||||
current = raw + start.to(tl.int64) * RAW_STRIDE
|
||||
if JOIN_ROW_PTRS:
|
||||
# Joining pointers hides row alignment from Triton; restate it.
|
||||
rows = tl.multiple_of(tl.join(prev, current)[:, None], (16, 16))
|
||||
kv = tl.load(rows + d[None, :])
|
||||
score = tl.load(rows + 512 + d[None, :])
|
||||
# Every lane has read the ring before the tail store below
|
||||
# writes it.
|
||||
tl.debug_barrier()
|
||||
pooled = tl.sum(kv * tl.softmax(score, 0), 0)
|
||||
else:
|
||||
kv_prev = tl.load(prev + d)
|
||||
score_prev = tl.load(prev + 512 + d)
|
||||
kv_current = tl.load(current + d)
|
||||
score_current = tl.load(current + 512 + d)
|
||||
# Every lane has read the ring before the tail store below
|
||||
# writes it.
|
||||
tl.debug_barrier()
|
||||
peak = tl.maximum(score_prev, score_current)
|
||||
weight_prev = tl.exp(score_prev - peak)
|
||||
weight_current = tl.exp(score_current - peak)
|
||||
pooled = (kv_prev * weight_prev + kv_current * weight_current) / (
|
||||
weight_prev + weight_current
|
||||
)
|
||||
_store_latent(pooled, start, norm_weight, latent, EPS)
|
||||
num_rows = tl.minimum(end - start, STATE_BLOCK)
|
||||
for k in tl.range(0, num_rows):
|
||||
token = end - num_rows + k
|
||||
slot = tl.load(state_slots + token)
|
||||
if slot >= 0:
|
||||
row = (
|
||||
state
|
||||
+ (slot // STATE_BLOCK).to(tl.int64) * STATE_STRIDE
|
||||
+ (slot % STATE_BLOCK) * STATE_ROW_STRIDE
|
||||
)
|
||||
src = raw + token.to(tl.int64) * RAW_STRIDE
|
||||
tl.store(row + d, tl.load(src + d))
|
||||
tl.store(row + 512 + d, tl.load(src + 512 + d))
|
||||
return
|
||||
|
||||
# Group program: one token (ratio 1) or the token of the pair that ends
|
||||
# a group (ratio 2). A chunk's first token belongs to its request program.
|
||||
t = (pid - num_reqs) * COMPRESS_RATIO
|
||||
if COMPRESS_RATIO == 2:
|
||||
t += (tl.load(positions + t) + 1) % 2
|
||||
state_slot = tl.load(state_slots + t, t < num_tokens, other=-1)
|
||||
if state_slot < 0:
|
||||
return
|
||||
if COMPRESS_RATIO == 1:
|
||||
pooled = tl.load(raw + t.to(tl.int64) * RAW_STRIDE + d)
|
||||
else:
|
||||
if t == tl.load(query_start_loc + tl.load(req_ids + t)):
|
||||
return
|
||||
rows = raw + (t.to(tl.int64) - 1 + tl.arange(0, 2)[:, None]) * RAW_STRIDE
|
||||
kv = tl.load(rows + d[None, :])
|
||||
score = tl.load(rows + 512 + d[None, :])
|
||||
pooled = tl.sum(kv * tl.softmax(score, 0), 0)
|
||||
_store_latent(pooled, t, norm_weight, latent, EPS)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _store_latent(pooled, t, norm_weight, latent, EPS: tl.constexpr):
|
||||
d = tl.arange(0, 512)
|
||||
weight = tl.load(norm_weight + d).to(tl.float32)
|
||||
variance = tl.sum(pooled * pooled, 0) / 512
|
||||
normed = pooled * tl.rsqrt(variance + EPS) * weight
|
||||
tl.store(latent + t.to(tl.int64) * 512 + d, normed.to(tl.bfloat16))
|
||||
|
||||
|
||||
def rope_quant_insert(
|
||||
latent: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
cos_sin_cache: torch.Tensor,
|
||||
kv_cache: torch.Tensor,
|
||||
slot_mapping: torch.Tensor,
|
||||
compress_ratio: int,
|
||||
fp8_scale: torch.Tensor | None = None,
|
||||
) -> None:
|
||||
"""Apply GPT-J RoPE and publish a latent to the compressed KV cache.
|
||||
|
||||
The BF16 latent supplies both NoPE quantization and RoPE input. It is read
|
||||
only for valid slots at group boundaries. The cache dtype selects the
|
||||
layout: ``uint8`` is the fp8_ds_mla paged layout (576 value bytes and eight
|
||||
segregated UE8M0 scale bytes per token, including one zero padding scale);
|
||||
``bfloat16`` and ``float8_e4m3fn`` are the plain [448 NoPE | 64 RoPE] rows
|
||||
read by FlashInfer, the latter scaled by the per-tensor ``fp8_scale``.
|
||||
"""
|
||||
assert compress_ratio in (1, 2)
|
||||
assert latent.shape[1] == 512 and latent.dtype == torch.bfloat16
|
||||
assert latent.is_contiguous()
|
||||
num_tokens = slot_mapping.numel()
|
||||
assert num_tokens <= min(latent.shape[0], positions.numel())
|
||||
if num_tokens == 0:
|
||||
return
|
||||
launch_kwargs = {"launch_pdl": False} if current_platform.is_cuda() else {}
|
||||
if kv_cache.dtype == torch.uint8:
|
||||
assert kv_cache.shape[-1] == 584
|
||||
_rope_quant_insert_kernel[(num_tokens,)](
|
||||
latent,
|
||||
positions,
|
||||
cos_sin_cache,
|
||||
kv_cache,
|
||||
slot_mapping,
|
||||
COS_STRIDE=cos_sin_cache.stride(0),
|
||||
CACHE_STRIDE=kv_cache.stride(0),
|
||||
CACHE_BLOCK=kv_cache.shape[1],
|
||||
COMPRESS_RATIO=compress_ratio,
|
||||
SANITIZE_CACHE_NANS=_ON_GFX950,
|
||||
num_warps=4,
|
||||
**launch_kwargs,
|
||||
)
|
||||
return
|
||||
|
||||
assert kv_cache.dtype in (torch.bfloat16, torch.float8_e4m3fn)
|
||||
assert kv_cache.shape[-1] == 512 and kv_cache.stride(-1) == 1
|
||||
store_fp8 = kv_cache.dtype == torch.float8_e4m3fn
|
||||
if store_fp8:
|
||||
assert fp8_scale is not None and fp8_scale.numel() == 1
|
||||
assert fp8_scale.dtype == torch.float32
|
||||
_rope_plain_insert_kernel[(num_tokens,)](
|
||||
latent,
|
||||
positions,
|
||||
cos_sin_cache,
|
||||
kv_cache,
|
||||
slot_mapping,
|
||||
fp8_scale if store_fp8 else None,
|
||||
COS_STRIDE=cos_sin_cache.stride(0),
|
||||
CACHE_STRIDE=kv_cache.stride(0),
|
||||
ROW_STRIDE=kv_cache.stride(1),
|
||||
CACHE_BLOCK=kv_cache.shape[1],
|
||||
COMPRESS_RATIO=compress_ratio,
|
||||
STORE_FP8=store_fp8,
|
||||
num_warps=4,
|
||||
**launch_kwargs,
|
||||
)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _rope_quant_insert_kernel(
|
||||
latent,
|
||||
positions,
|
||||
cos_sin,
|
||||
cache,
|
||||
cache_slots,
|
||||
COS_STRIDE: tl.constexpr,
|
||||
CACHE_STRIDE: tl.constexpr,
|
||||
CACHE_BLOCK: tl.constexpr,
|
||||
COMPRESS_RATIO: tl.constexpr,
|
||||
SANITIZE_CACHE_NANS: tl.constexpr,
|
||||
):
|
||||
t = tl.program_id(0)
|
||||
slot = tl.load(cache_slots + t)
|
||||
if slot < 0:
|
||||
return
|
||||
position = tl.load(positions + t)
|
||||
if (position + 1) % COMPRESS_RATIO != 0:
|
||||
return
|
||||
d = tl.arange(0, 512)
|
||||
normed = tl.load(latent + t.to(tl.int64) * 512 + d).to(tl.float32)
|
||||
page = cache + (slot // CACHE_BLOCK).to(tl.int64) * CACHE_STRIDE
|
||||
values = page + (slot % CACHE_BLOCK) * 576
|
||||
scales = page + CACHE_BLOCK * 576 + (slot % CACHE_BLOCK) * 8
|
||||
|
||||
quant = tl.reshape(normed, (8, 64))
|
||||
amax = tl.maximum(tl.max(tl.abs(quant), 1), 1e-4)
|
||||
exponent = tl.ceil(tl.log2(amax * (1.0 / 448.0)))
|
||||
scaled = quant * tl.reshape(tl.exp2(-exponent), (8, 1))
|
||||
fp8 = tl.clamp(scaled, -448.0, 448.0).to(tl.float8e4nv)
|
||||
packed = tl.reshape(fp8.to(tl.uint8, bitcast=True), (512,))
|
||||
tl.store(values + d, packed, d < 448)
|
||||
s = tl.arange(0, 8)
|
||||
max_encoded: tl.constexpr = 254.0 if SANITIZE_CACHE_NANS else 255.0
|
||||
encoded = tl.minimum(tl.maximum(exponent + 127.0, 0.0), max_encoded)
|
||||
tl.store(scales + s, encoded.to(tl.uint8), s < 7)
|
||||
tl.store(scales + 7, tl.full((), 0, tl.uint8))
|
||||
|
||||
even, odd = tl.split(tl.reshape(normed, (256, 2)))
|
||||
pair = tl.arange(0, 256) - 224
|
||||
cs = cos_sin + (position // COMPRESS_RATIO * COMPRESS_RATIO) * COS_STRIDE
|
||||
c = tl.load(cs + tl.maximum(pair, 0), pair >= 0, other=1.0).to(tl.float32)
|
||||
s = tl.load(cs + 32 + tl.maximum(pair, 0), pair >= 0, other=0.0).to(tl.float32)
|
||||
rotated = tl.interleave(even * c - odd * s, odd * c + even * s)
|
||||
if SANITIZE_CACHE_NANS:
|
||||
rotated = tl.where(rotated == rotated, rotated, 0.0)
|
||||
rope_dst = (values + 448).to(tl.pointer_type(tl.bfloat16))
|
||||
tl.store(rope_dst + d - 448, rotated.to(tl.bfloat16), d >= 448)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _rope_plain_insert_kernel(
|
||||
latent,
|
||||
positions,
|
||||
cos_sin,
|
||||
cache,
|
||||
cache_slots,
|
||||
fp8_scale,
|
||||
COS_STRIDE: tl.constexpr,
|
||||
CACHE_STRIDE: tl.constexpr,
|
||||
ROW_STRIDE: tl.constexpr,
|
||||
CACHE_BLOCK: tl.constexpr,
|
||||
COMPRESS_RATIO: tl.constexpr,
|
||||
STORE_FP8: tl.constexpr,
|
||||
):
|
||||
t = tl.program_id(0)
|
||||
slot = tl.load(cache_slots + t)
|
||||
if slot < 0:
|
||||
return
|
||||
position = tl.load(positions + t)
|
||||
if (position + 1) % COMPRESS_RATIO != 0:
|
||||
return
|
||||
d = tl.arange(0, 512)
|
||||
normed = tl.load(latent + t.to(tl.int64) * 512 + d).to(tl.float32)
|
||||
|
||||
# NoPE pairs load (cos, sin) = (1, 0), so the rotation is the identity there.
|
||||
even, odd = tl.split(tl.reshape(normed, (256, 2)))
|
||||
pair = tl.arange(0, 256) - 224
|
||||
cs = cos_sin + (position // COMPRESS_RATIO * COMPRESS_RATIO) * COS_STRIDE
|
||||
c = tl.load(cs + tl.maximum(pair, 0), pair >= 0, other=1.0).to(tl.float32)
|
||||
s = tl.load(cs + 32 + tl.maximum(pair, 0), pair >= 0, other=0.0).to(tl.float32)
|
||||
row = tl.interleave(even * c - odd * s, odd * c + even * s).to(tl.bfloat16)
|
||||
|
||||
dst = (
|
||||
cache
|
||||
+ (slot // CACHE_BLOCK).to(tl.int64) * CACHE_STRIDE
|
||||
+ (slot % CACHE_BLOCK) * ROW_STRIDE
|
||||
)
|
||||
if STORE_FP8:
|
||||
scaled = row.to(tl.float32) * (1.0 / tl.load(fp8_scale))
|
||||
tl.store(dst + d, tl.clamp(scaled, -448.0, 448.0).to(tl.float8e4nv))
|
||||
else:
|
||||
tl.store(dst + d, row)
|
||||
@@ -0,0 +1,253 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Indexer K production for DeepSeek V4.1 kv-source layers.
|
||||
|
||||
In v4.1 the index key is derived from the *main* compressor's latent:
|
||||
``k = k_norm(wk(latent))`` (reference model.py Indexer.forward), then RoPE'd
|
||||
at the group's first-token position and MXFP4/FP8-quantized into the paged
|
||||
indexer K cache. The ``wk(latent)`` GEMM runs in torch; this kernel fuses the
|
||||
remaining k_norm → RoPE → quant → paged store, one program per token.
|
||||
|
||||
Unlike the legacy (v4.0) indexer path there is no per-token pooling from a
|
||||
compressor state cache: the latent already stands for a whole group, so only
|
||||
group-boundary tokens ``(position + 1) % compress_ratio == 0`` produce a key.
|
||||
"""
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import tl, triton
|
||||
|
||||
from . import MXFP4_BLOCK_SIZE, _fp32x2_to_fp4x2
|
||||
|
||||
# ROCm tiled ("SHUFFLE") indexer K value layout, mirroring
|
||||
# indexer_k_quant_and_cache_triton's defaults: 16 positions x 16 bytes.
|
||||
_BLOCK_TILE_SIZE = 16
|
||||
_HEAD_TILE_SIZE = 16
|
||||
|
||||
|
||||
def indexer_k_norm_rope_store(
|
||||
k_pre: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
cos_sin_cache: torch.Tensor,
|
||||
rms_norm_weight: torch.Tensor,
|
||||
rms_norm_eps: float,
|
||||
k_cache: torch.Tensor,
|
||||
kv_slot_mapping: torch.Tensor,
|
||||
compress_ratio: int,
|
||||
use_fp4_cache: bool,
|
||||
) -> None:
|
||||
"""k_norm → RoPE → quant → paged store for indexer keys.
|
||||
|
||||
Args:
|
||||
k_pre: [num_tokens, 128] bf16, the ``wk(latent)`` projection. Only
|
||||
group-boundary rows are read.
|
||||
positions: [num_tokens] int64 token positions.
|
||||
cos_sin_cache: [max_pos, rope_head_dim] GPT-J layout (cos half, then
|
||||
sin half), from the layer's compress-RoPE instance.
|
||||
rms_norm_weight: [128] k_norm weight.
|
||||
k_cache: uint8 paged indexer cache [num_blocks, block_size, row_bytes].
|
||||
kv_slot_mapping: [num_tokens] slots in the indexer cache (-1 = skip).
|
||||
compress_ratio: group size; keys are emitted at group boundaries.
|
||||
use_fp4_cache: MXFP4 (2 nibbles/byte + ue8m0 per 32) when True, else
|
||||
per-token FP8 with a single fp32 scale.
|
||||
"""
|
||||
num_tokens = kv_slot_mapping.numel()
|
||||
assert k_pre.ndim == 2 and k_pre.shape[1] == 128
|
||||
assert k_pre.dtype == torch.bfloat16 and k_pre.stride(1) == 1
|
||||
assert num_tokens <= k_pre.shape[0] and num_tokens <= positions.numel()
|
||||
assert compress_ratio in (1, 2)
|
||||
if num_tokens == 0:
|
||||
return
|
||||
|
||||
head_dim = k_pre.shape[1]
|
||||
if use_fp4_cache:
|
||||
token_stride = head_dim // 2
|
||||
scale_dim = head_dim // MXFP4_BLOCK_SIZE
|
||||
else:
|
||||
token_stride = head_dim
|
||||
scale_dim = 4 # single float32 scale
|
||||
|
||||
# ROCm reads this cache back with the 16x16-tiled ("SHUFFLE") value
|
||||
# layout: cp_gather_indexer_k_quant_cache_triton on prefill and aiter's
|
||||
# deepgemm_fp8_paged_mqa_logits(Preshuffle=True) on decode both select it
|
||||
# from ``block_size > 1``, matching the v4.0 writer
|
||||
# (indexer_k_quant_and_cache_triton). Writing row-major here would hand
|
||||
# both readers permuted key bytes.
|
||||
block_size = k_cache.shape[1]
|
||||
shuffle = current_platform.is_rocm() and block_size > 1
|
||||
if shuffle:
|
||||
if use_fp4_cache:
|
||||
raise NotImplementedError(
|
||||
"MXFP4 indexer K cache has no tiled ROCm layout; "
|
||||
"the ROCm readers only implement the FP8 one."
|
||||
)
|
||||
if block_size % _BLOCK_TILE_SIZE != 0 or head_dim % _HEAD_TILE_SIZE != 0:
|
||||
raise ValueError(
|
||||
f"ROCm tiled indexer K cache needs block_size "
|
||||
f"({block_size}) % {_BLOCK_TILE_SIZE} == 0 and head_dim "
|
||||
f"({head_dim}) % {_HEAD_TILE_SIZE} == 0."
|
||||
)
|
||||
|
||||
launch_kwargs = {"launch_pdl": False} if current_platform.is_cuda() else {}
|
||||
_indexer_k_norm_rope_quant_store_kernel[(num_tokens,)](
|
||||
k_pre,
|
||||
k_pre.stride(0),
|
||||
positions,
|
||||
rms_norm_weight,
|
||||
rms_norm_eps,
|
||||
cos_sin_cache,
|
||||
cos_sin_cache.stride(0),
|
||||
k_cache,
|
||||
kv_slot_mapping,
|
||||
k_cache.shape[1],
|
||||
HEAD_SIZE=head_dim,
|
||||
ROPE_HEAD_DIM=64,
|
||||
COMPRESS_RATIO=compress_ratio,
|
||||
TOKEN_STRIDE=token_stride,
|
||||
SCALE_DIM=scale_dim,
|
||||
KV_BLOCK_STRIDE=k_cache.stride(0),
|
||||
FP8_MAX=448.0,
|
||||
USE_FP4=use_fp4_cache,
|
||||
SHUFFLE=shuffle,
|
||||
BLOCK_TILE_SIZE=_BLOCK_TILE_SIZE,
|
||||
HEAD_TILE_SIZE=_HEAD_TILE_SIZE,
|
||||
num_warps=1,
|
||||
**launch_kwargs,
|
||||
)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _indexer_k_norm_rope_quant_store_kernel(
|
||||
k_pre_ptr,
|
||||
k_pre_stride,
|
||||
positions_ptr,
|
||||
rms_norm_weight_ptr,
|
||||
rms_norm_eps,
|
||||
cos_sin_cache_ptr,
|
||||
cos_sin_stride,
|
||||
k_cache_ptr,
|
||||
kv_slot_mapping_ptr,
|
||||
kv_cache_block_size,
|
||||
HEAD_SIZE: tl.constexpr,
|
||||
ROPE_HEAD_DIM: tl.constexpr,
|
||||
COMPRESS_RATIO: tl.constexpr,
|
||||
TOKEN_STRIDE: tl.constexpr,
|
||||
SCALE_DIM: tl.constexpr,
|
||||
KV_BLOCK_STRIDE: tl.constexpr,
|
||||
FP8_MAX: tl.constexpr,
|
||||
USE_FP4: tl.constexpr,
|
||||
SHUFFLE: tl.constexpr,
|
||||
BLOCK_TILE_SIZE: tl.constexpr,
|
||||
HEAD_TILE_SIZE: tl.constexpr,
|
||||
):
|
||||
token_idx = tl.program_id(0)
|
||||
|
||||
kv_slot_idx = tl.load(kv_slot_mapping_ptr + token_idx)
|
||||
if kv_slot_idx < 0:
|
||||
return
|
||||
position = tl.load(positions_ptr + token_idx)
|
||||
# Only the last token of a group publishes that group's index key.
|
||||
if (position + 1) % COMPRESS_RATIO != 0:
|
||||
return
|
||||
|
||||
block = tl.arange(0, HEAD_SIZE)
|
||||
|
||||
# ── k_norm (fp32 throughout, bf16 roundtrip like the reference) ────
|
||||
k = tl.load(k_pre_ptr + token_idx * k_pre_stride + block).to(tl.float32)
|
||||
rms_w = tl.load(rms_norm_weight_ptr + block).to(tl.float32)
|
||||
variance = tl.sum(k * k, axis=0) / HEAD_SIZE
|
||||
k = (k * tl.rsqrt(variance + rms_norm_eps) * rms_w).to(tl.bfloat16)
|
||||
k = k.to(tl.float32)
|
||||
|
||||
# ── Register-based GPT-J forward RoPE in fp32 ─────────────────────
|
||||
# A latent stands for the first token of its group, so group j takes
|
||||
# position j * compress_ratio.
|
||||
NUM_PAIRS: tl.constexpr = HEAD_SIZE // 2
|
||||
NOPE_HEAD_DIM: tl.constexpr = HEAD_SIZE - ROPE_HEAD_DIM
|
||||
NOPE_PAIRS: tl.constexpr = NOPE_HEAD_DIM // 2
|
||||
HALF_ROPE: tl.constexpr = ROPE_HEAD_DIM // 2
|
||||
|
||||
even, odd = tl.split(tl.reshape(k, (NUM_PAIRS, 2))) # each [NUM_PAIRS]
|
||||
pair_idx = tl.arange(0, NUM_PAIRS)
|
||||
rope_pair_local = pair_idx - NOPE_PAIRS
|
||||
is_rope_pair = rope_pair_local >= 0
|
||||
cs_idx = tl.maximum(rope_pair_local, 0)
|
||||
|
||||
compressed_pos = (position // COMPRESS_RATIO) * COMPRESS_RATIO
|
||||
cache_base = cos_sin_cache_ptr + compressed_pos * cos_sin_stride
|
||||
cos_v = tl.load(cache_base + cs_idx, mask=is_rope_pair, other=1.0)
|
||||
sin_v = tl.load(cache_base + HALF_ROPE + cs_idx, mask=is_rope_pair, other=0.0)
|
||||
|
||||
new_even = even * cos_v - odd * sin_v
|
||||
new_odd = odd * cos_v + even * sin_v
|
||||
|
||||
# bf16 roundtrip for parity with the reference / Q-side kernel numerics.
|
||||
new_even = new_even.to(tl.bfloat16).to(tl.float32)
|
||||
new_odd = new_odd.to(tl.bfloat16).to(tl.float32)
|
||||
|
||||
# ── Paged cache pointers (segregated: values first, then scales) ──
|
||||
kv_block_idx = kv_slot_idx // kv_cache_block_size
|
||||
kv_pos_in_block = kv_slot_idx % kv_cache_block_size
|
||||
cache_block_ptr = k_cache_ptr + kv_block_idx.to(tl.int64) * KV_BLOCK_STRIDE
|
||||
if SHUFFLE:
|
||||
# [block_size // BT, HEAD_SIZE // HT, BT, HT] value tiles.
|
||||
val_ptr = (
|
||||
cache_block_ptr
|
||||
+ (kv_pos_in_block // BLOCK_TILE_SIZE) * BLOCK_TILE_SIZE * TOKEN_STRIDE
|
||||
+ (kv_pos_in_block % BLOCK_TILE_SIZE) * HEAD_TILE_SIZE
|
||||
)
|
||||
else:
|
||||
val_ptr = cache_block_ptr + kv_pos_in_block * TOKEN_STRIDE
|
||||
scale_ptr = (
|
||||
cache_block_ptr
|
||||
+ kv_cache_block_size * TOKEN_STRIDE
|
||||
+ kv_pos_in_block * SCALE_DIM
|
||||
)
|
||||
|
||||
if USE_FP4:
|
||||
# MXFP4: each 32-element block = 16 consecutive even/odd pairs, so
|
||||
# tiling the halves into (N_BLOCKS, 16) lands one block per row.
|
||||
N_QUANT_BLOCKS: tl.constexpr = HEAD_SIZE // 32
|
||||
HALF_BLOCK: tl.constexpr = 16
|
||||
even_2d = tl.reshape(new_even, (N_QUANT_BLOCKS, HALF_BLOCK))
|
||||
odd_2d = tl.reshape(new_odd, (N_QUANT_BLOCKS, HALF_BLOCK))
|
||||
|
||||
amax = tl.maximum(
|
||||
tl.max(tl.abs(even_2d), axis=1),
|
||||
tl.max(tl.abs(odd_2d), axis=1),
|
||||
)
|
||||
amax = tl.maximum(amax, 6.0 * (2**-126))
|
||||
# ue8m0 block scale: 2^ceil(log2(amax / 6.0)), stored (exp + 127).
|
||||
log2_ratio = tl.ceil(tl.log2(amax * (1.0 / 6.0)))
|
||||
log2_ratio = tl.minimum(tl.maximum(log2_ratio, -127.0), 127.0)
|
||||
inv_scale = tl.exp2(-log2_ratio)
|
||||
ue8m0 = (log2_ratio + 127.0).to(tl.uint8) # [N_QUANT_BLOCKS]
|
||||
|
||||
inv_scale_col = tl.reshape(inv_scale, (N_QUANT_BLOCKS, 1))
|
||||
packed = _fp32x2_to_fp4x2(
|
||||
even_2d * inv_scale_col, odd_2d * inv_scale_col
|
||||
) # (N_BLOCKS, HALF_BLOCK) uint8
|
||||
packed_flat = tl.reshape(packed, (TOKEN_STRIDE,))
|
||||
|
||||
tl.store(val_ptr + tl.arange(0, TOKEN_STRIDE), packed_flat)
|
||||
tl.store(scale_ptr + tl.arange(0, SCALE_DIM), ue8m0)
|
||||
else:
|
||||
# Per-token FP8 (single 128-wide block) with one float32 scale.
|
||||
result = tl.interleave(new_even, new_odd) # [HEAD_SIZE] fp32
|
||||
result_bf16 = result.to(tl.bfloat16).to(tl.float32)
|
||||
INV_FP8_MAX: tl.constexpr = 1.0 / FP8_MAX
|
||||
absmax = tl.maximum(tl.max(tl.abs(result_bf16), axis=0), 1e-4)
|
||||
exponent = tl.ceil(tl.log2(absmax * INV_FP8_MAX))
|
||||
inv_scale = tl.exp2(-exponent)
|
||||
x_clamped = tl.clamp(result_bf16 * inv_scale, -FP8_MAX, FP8_MAX)
|
||||
x_uint8 = x_clamped.to(tl.float8e4nv).to(tl.uint8, bitcast=True)
|
||||
if SHUFFLE:
|
||||
tiled = (
|
||||
block // HEAD_TILE_SIZE * BLOCK_TILE_SIZE * HEAD_TILE_SIZE
|
||||
+ block % HEAD_TILE_SIZE
|
||||
)
|
||||
tl.store(val_ptr + tiled, x_uint8)
|
||||
else:
|
||||
tl.store(val_ptr + block, x_uint8)
|
||||
tl.store(scale_ptr.to(tl.pointer_type(tl.float32)), tl.exp2(exponent))
|
||||
@@ -0,0 +1,142 @@
|
||||
# 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.quantization.utils.quant_utils import kMxfp8Dynamic
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import tl, triton
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _norm_row(x, weight, row, stride, eps, SIZE: tl.constexpr, BLOCK: tl.constexpr):
|
||||
cols = tl.arange(0, BLOCK)
|
||||
w = tl.load(weight + cols, cols < SIZE, 0).to(tl.float32)
|
||||
values = tl.load(x + row * stride + cols, cols < SIZE, 0).to(tl.float32)
|
||||
rrms = tl.rsqrt(tl.sum(values * values, 0) / SIZE + eps)
|
||||
return values * rrms * w
|
||||
|
||||
|
||||
@triton.jit(do_not_specialize=["num_tokens"])
|
||||
def _q_kv_norm_quant_kernel(
|
||||
q,
|
||||
kv,
|
||||
qw,
|
||||
kvw,
|
||||
qo,
|
||||
kvo,
|
||||
scales,
|
||||
num_tokens,
|
||||
q_stride,
|
||||
kv_stride,
|
||||
eps,
|
||||
Q_SIZE: tl.constexpr,
|
||||
KV_SIZE: tl.constexpr,
|
||||
BLOCK: tl.constexpr,
|
||||
LAUNCH_PDL: tl.constexpr,
|
||||
):
|
||||
row = tl.program_id(0).to(tl.int64)
|
||||
cols = tl.arange(0, BLOCK)
|
||||
if LAUNCH_PDL:
|
||||
tl.extra.cuda.gdc_wait()
|
||||
tl.extra.cuda.gdc_launch_dependents()
|
||||
if tl.program_id(1) == 0:
|
||||
groups = tl.arange(0, BLOCK // 32)
|
||||
if row < num_tokens:
|
||||
y = _norm_row(q, qw, row, q_stride, eps, Q_SIZE, BLOCK)
|
||||
# Preserve the materialized normalization output's rounding boundary.
|
||||
y = y.to(q.dtype.element_ty).to(tl.float32)
|
||||
grouped = tl.reshape(y, (BLOCK // 32, 32))
|
||||
amax = tl.max(tl.abs(grouped), 1)
|
||||
normalized = amax * (1.0 / 448.0)
|
||||
bits = normalized.to(tl.uint32, bitcast=True)
|
||||
exponent = (bits >> 23) & 255
|
||||
mantissa = bits & 0x7FFFFF
|
||||
bump = (mantissa != 0) & ~((exponent == 0) & (mantissa <= 0x400000))
|
||||
sf = tl.minimum(exponent + bump, 254)
|
||||
sf = tl.where(normalized <= 0, 0, sf)
|
||||
# Match FlashInfer's UE8M0 conversion, including zero/subnormal scales.
|
||||
inv_bits = tl.where(sf == 0, 0, (254 - sf) << 23)
|
||||
inv_scale = inv_bits.to(tl.float32, bitcast=True)
|
||||
quantized = tl.reshape(grouped * inv_scale[:, None], (BLOCK,))
|
||||
tl.store(qo + row * Q_SIZE + cols, quantized, cols < Q_SIZE)
|
||||
else:
|
||||
sf = tl.full((BLOCK // 32,), 0, tl.uint32)
|
||||
padded_groups: tl.constexpr = triton.cdiv(Q_SIZE // 32, 4) * 4
|
||||
sf = tl.where(groups < Q_SIZE // 32, sf, 0)
|
||||
# F8_128x4: [row/128, group/4, row%32, row%128/32, group%4].
|
||||
offsets = (
|
||||
row // 128 * (128 * padded_groups)
|
||||
+ groups // 4 * 512
|
||||
+ row % 32 * 16
|
||||
+ row % 128 // 32 * 4
|
||||
+ groups % 4
|
||||
)
|
||||
tl.store(scales + offsets, sf, groups < padded_groups)
|
||||
elif row < num_tokens:
|
||||
y = _norm_row(kv, kvw, row, kv_stride, eps, KV_SIZE, BLOCK)
|
||||
tl.store(kvo + row * KV_SIZE + cols, y, cols < KV_SIZE)
|
||||
|
||||
|
||||
def fused_q_kv_rmsnorm_quant(
|
||||
qr: torch.Tensor,
|
||||
kv: torch.Tensor,
|
||||
q_weight: torch.Tensor,
|
||||
kv_weight: torch.Tensor,
|
||||
eps: float,
|
||||
) -> tuple[QuantizedActivation, torch.Tensor]:
|
||||
"""Normalize Q/KV and quantize Q with FlashInfer's swizzled MXFP8 scales."""
|
||||
assert qr.ndim == kv.ndim == 2 and qr.shape[0] == kv.shape[0]
|
||||
assert qr.stride(-1) == kv.stride(-1) == 1
|
||||
assert q_weight.is_contiguous() and kv_weight.is_contiguous()
|
||||
assert qr.shape[1] % 32 == 0
|
||||
tokens, q_size = qr.shape
|
||||
kv_size = kv.shape[1]
|
||||
qo = torch.empty(qr.shape, dtype=torch.float8_e4m3fn, device=qr.device)
|
||||
kvo = torch.empty(kv.shape, dtype=kv.dtype, device=kv.device)
|
||||
padded_tokens = triton.cdiv(tokens, 128) * 128
|
||||
padded_groups = triton.cdiv(q_size // 32, 4) * 4
|
||||
scales = torch.empty(
|
||||
padded_tokens * padded_groups, dtype=torch.uint8, device=qr.device
|
||||
)
|
||||
if tokens:
|
||||
block = triton.next_power_of_2(max(q_size, kv_size))
|
||||
_q_kv_norm_quant_kernel[(padded_tokens, 2)](
|
||||
qr,
|
||||
kv,
|
||||
q_weight,
|
||||
kv_weight,
|
||||
qo,
|
||||
kvo,
|
||||
scales,
|
||||
tokens,
|
||||
qr.stride(0),
|
||||
kv.stride(0),
|
||||
eps,
|
||||
q_size,
|
||||
kv_size,
|
||||
block,
|
||||
current_platform.is_arch_support_pdl(),
|
||||
num_warps=8 if block >= 2048 else 4,
|
||||
)
|
||||
return QuantizedActivation(qo, scales, qr.dtype, qr.shape, kMxfp8Dynamic), kvo
|
||||
|
||||
|
||||
def can_fuse_query_quant(linears: list[torch.nn.Module]) -> bool:
|
||||
"""Require both local projections to use the same MXFP8 activation ABI."""
|
||||
if not current_platform.is_cuda():
|
||||
return False
|
||||
from vllm.model_executor.kernels.linear.mxfp8.flashinfer import (
|
||||
FlashInferCutedslMxfp8LinearKernel,
|
||||
FlashInferCutlassMxfp8LinearKernel,
|
||||
)
|
||||
|
||||
# QuantKey does not encode scale layout; restrict this producer to the
|
||||
# consumers that accept F8_128x4 swizzled scales.
|
||||
return all(
|
||||
getattr(linear, "input_quant_key", None) == kMxfp8Dynamic
|
||||
and type(getattr(getattr(linear, "quant_method", None), "kernel", None))
|
||||
in (FlashInferCutedslMxfp8LinearKernel, FlashInferCutlassMxfp8LinearKernel)
|
||||
for linear in linears
|
||||
)
|
||||
Reference in New Issue
Block a user