[Feature] KV cache per-token-head INT8/FP8 quantization (#38378)

Signed-off-by: JartX <sagformas@epdcenter.es>
Signed-off-by: Wentao Ye <44945378+yewentao256@users.noreply.github.com>
Co-authored-by: yangyang4991 <yangyang4991@gmail.com>
Co-authored-by: Wentao Ye <44945378+yewentao256@users.noreply.github.com>
Co-authored-by: Isotr0py <2037008807@qq.com>
This commit is contained in:
JartX
2026-04-02 08:13:26 -04:00
committed by GitHub
co-authored by yangyang4991 Wentao Ye Isotr0py
parent 4eefbf9609
commit 2ce3d0ce36
16 changed files with 1308 additions and 66 deletions
@@ -3,10 +3,16 @@
import torch
from vllm.model_executor.layers.quantization.utils.quant_utils import (
FP8_DTYPE,
get_fp8_min_max,
)
from vllm.platforms import current_platform
from vllm.triton_utils import tl, triton
from vllm.utils.torch_utils import is_quantized_kv_cache
FP8_MIN, FP8_MAX = get_fp8_min_max()
@triton.jit
def reshape_and_cache_kernel_flash(
@@ -118,6 +124,198 @@ def reshape_and_cache_kernel_flash(
return
# ---------------------------------------------------------------------------
# Per-token-head dynamic quantization kernel
# Grid: (num_tokens, NUM_KV_HEADS)
# Each program handles one (token, head) pair:
# 1. Loads K (or V) for that single head
# 2. Computes absmax across head_size → scale = absmax / QUANT_MAX
# 3. Quantizes and stores the data + per-head scale
#
# Parametrised by QUANT_MAX / QUANT_MIN so the same code path works
# for int8 (±127/128), fp8_e4m3 (±448), and other formats.
# ---------------------------------------------------------------------------
@triton.jit
def _reshape_cache_per_token_head(
key_ptr, # [num_tokens, num_kv_heads, head_size]
value_ptr, # [num_tokens, num_kv_heads, head_size_v]
key_cache_ptr, # [num_blocks, block_size, num_kv_heads, head_size]
value_cache_ptr, # [num_blocks, block_size, num_kv_heads, head_size_v]
k_scale_cache_ptr, # [num_blocks, block_size, num_kv_heads] float32
v_scale_cache_ptr, # [num_blocks, block_size, num_kv_heads] float32
slot_mapping_ptr, # [num_tokens]
stride_key_tok: tl.int64,
stride_key_head: tl.int64,
stride_val_tok: tl.int64,
stride_val_head: tl.int64,
stride_kc_blk: tl.int64, # key_cache stride over blocks
stride_kc_slot: tl.int64, # key_cache stride over slots
stride_kc_head: tl.int64, # key_cache stride over heads
stride_vc_blk: tl.int64,
stride_vc_slot: tl.int64,
stride_vc_head: tl.int64,
stride_ks_blk: tl.int64, # k_scale_cache stride[0] (blocks)
stride_ks_slot: tl.int64, # k_scale_cache stride[1] (slots)
stride_ks_head: tl.int64, # k_scale_cache stride[2] (heads)
stride_vs_blk: tl.int64, # v_scale_cache stride[0] (blocks)
stride_vs_slot: tl.int64, # v_scale_cache stride[1] (slots)
stride_vs_head: tl.int64, # v_scale_cache stride[2] (heads)
block_size: tl.constexpr,
head_size: tl.constexpr,
head_size_v: tl.constexpr,
HEAD_SIZE_PADDED: tl.constexpr, # next_power_of_2(max(head_size, head_size_v))
QUANT_MAX: tl.constexpr = 127.0,
QUANT_MIN: tl.constexpr = -128.0,
):
tok = tl.program_id(0)
head = tl.program_id(1)
slot = tl.load(slot_mapping_ptr + tok).to(tl.int64)
if slot < 0:
return
blk = slot // block_size
slot_in_blk = slot % block_size
dim_offs = tl.arange(0, HEAD_SIZE_PADDED)
# ---- Key: load one head → absmax → quantize → store -------------------
k_mask = dim_offs < head_size
k_h = tl.load(
key_ptr + tok * stride_key_tok + head * stride_key_head + dim_offs,
mask=k_mask,
other=0.0,
).to(tl.float32)
k_scale = tl.maximum(tl.max(tl.abs(k_h)) / QUANT_MAX, 1e-6)
tl.store(
k_scale_cache_ptr
+ blk * stride_ks_blk
+ slot_in_blk * stride_ks_slot
+ head * stride_ks_head,
k_scale,
)
k_q = tl.clamp(k_h * (1.0 / k_scale), QUANT_MIN, QUANT_MAX)
tl.store(
key_cache_ptr
+ blk * stride_kc_blk
+ slot_in_blk * stride_kc_slot
+ head * stride_kc_head
+ dim_offs,
k_q,
mask=k_mask,
)
# ---- Value: same per-head approach ------------------------------------
v_mask = dim_offs < head_size_v
v_h = tl.load(
value_ptr + tok * stride_val_tok + head * stride_val_head + dim_offs,
mask=v_mask,
other=0.0,
).to(tl.float32)
v_scale = tl.maximum(tl.max(tl.abs(v_h)) / QUANT_MAX, 1e-6)
tl.store(
v_scale_cache_ptr
+ blk * stride_vs_blk
+ slot_in_blk * stride_vs_slot
+ head * stride_vs_head,
v_scale,
)
v_q = tl.clamp(v_h * (1.0 / v_scale), QUANT_MIN, QUANT_MAX)
tl.store(
value_cache_ptr
+ blk * stride_vc_blk
+ slot_in_blk * stride_vc_slot
+ head * stride_vc_head
+ dim_offs,
v_q,
mask=v_mask,
)
# Mapping from cache torch dtype to (QUANT_MAX, QUANT_MIN) for the
# per-token-head quantization kernel.
_PER_TOKEN_HEAD_QUANT_PARAMS: dict[torch.dtype, tuple[float, float]] = {
torch.int8: (127.0, -128.0),
FP8_DTYPE: (FP8_MAX, FP8_MIN),
}
def triton_reshape_and_cache_flash_per_token_head_quant(
key: torch.Tensor, # [num_tokens, num_kv_heads, head_size]
value: torch.Tensor, # [num_tokens, num_kv_heads, head_size_v]
key_cache: torch.Tensor, # [num_blocks, block_size, num_kv_heads, head_size]
value_cache: torch.Tensor, # [num_blocks, block_size, num_kv_heads, head_size_v]
k_scale_cache: torch.Tensor, # [num_blocks, block_size, num_kv_heads] float32
v_scale_cache: torch.Tensor, # [num_blocks, block_size, num_kv_heads] float32
slot_mapping: torch.Tensor, # [num_tokens]
):
"""Quantize key/value per (token, head) and write to paged cache.
Computes one scale = absmax / QUANT_MAX per (token, head), stores
quantized data in key_cache/value_cache, and stores the float32
scale in k_scale_cache/v_scale_cache.
The quantization range (QUANT_MAX, QUANT_MIN) is derived from the
cache tensor dtype so the same code path works for int8 and fp8.
"""
cache_dtype = key_cache.dtype
quant_params = _PER_TOKEN_HEAD_QUANT_PARAMS.get(cache_dtype)
if quant_params is None:
raise ValueError(
f"Per-token-head quantization not supported for cache dtype "
f"{cache_dtype}. Supported: {list(_PER_TOKEN_HEAD_QUANT_PARAMS)}"
)
quant_max, quant_min = quant_params
num_tokens, num_kv_heads, head_size = key.shape
head_size_v = value.shape[2]
head_size_padded = triton.next_power_of_2(max(head_size, head_size_v))
block_size = key_cache.shape[1]
if current_platform.is_rocm() or current_platform.is_xpu():
num_warps = 4
else:
num_warps = min(16, max(1, head_size_padded // 32))
_reshape_cache_per_token_head[(num_tokens, num_kv_heads)](
key_ptr=key,
value_ptr=value,
key_cache_ptr=key_cache,
value_cache_ptr=value_cache,
k_scale_cache_ptr=k_scale_cache,
v_scale_cache_ptr=v_scale_cache,
slot_mapping_ptr=slot_mapping,
stride_key_tok=key.stride(0),
stride_key_head=key.stride(1),
stride_val_tok=value.stride(0),
stride_val_head=value.stride(1),
stride_kc_blk=key_cache.stride(0),
stride_kc_slot=key_cache.stride(1),
stride_kc_head=key_cache.stride(2),
stride_vc_blk=value_cache.stride(0),
stride_vc_slot=value_cache.stride(1),
stride_vc_head=value_cache.stride(2),
stride_ks_blk=k_scale_cache.stride(0),
stride_ks_slot=k_scale_cache.stride(1),
stride_ks_head=k_scale_cache.stride(2),
stride_vs_blk=v_scale_cache.stride(0),
stride_vs_slot=v_scale_cache.stride(1),
stride_vs_head=v_scale_cache.stride(2),
block_size=block_size,
head_size=head_size,
head_size_v=head_size_v,
HEAD_SIZE_PADDED=head_size_padded,
QUANT_MAX=quant_max,
QUANT_MIN=quant_min,
num_warps=num_warps,
)
def triton_reshape_and_cache_flash(
key: torch.Tensor, # [num_tokens, num_heads, head_size]
value: torch.Tensor, # [num_tokens, num_heads, head_size]
@@ -224,7 +422,6 @@ def triton_reshape_and_cache_flash(
block_size=block_size,
x=x,
USE_HEAD_MAJOR_LAYOUT=use_head_major_layout,
# FP8 flags
FP8_KV_CACHE=FP8_KV_CACHE,
# autotune parameters
TILE_SIZE=TILE_SIZE,
+189 -36
View File
@@ -13,6 +13,7 @@ import vllm.envs as envs
from vllm.logger import init_logger
from vllm.platforms import current_platform
from vllm.triton_utils import tl, triton
from vllm.v1.kv_cache_interface import KVQuantMode
logger = init_logger(__name__)
is_batch_invariant = envs.VLLM_BATCH_INVARIANT
@@ -32,6 +33,63 @@ def apply_softcap(S, x):
return x * (p1 - p2) / (p1 + p2)
@triton.jit
def _prepare_kv_tile(
data,
Q,
tensor_scale,
scale_cache_ptr,
physical_block_idx,
seq_offset,
kv_head_idx,
stride_s_blk,
stride_s_slot,
stride_s_head,
tile_mask,
BLOCK_SIZE: tl.constexpr,
KV_QUANT_MODE: tl.constexpr,
):
"""Prepare a loaded KV tile for attention computation.
Casts the raw KV data to Q's dtype and loads per-token-head scales
when applicable:
- ``KV_QUANT_MODE == 0``: cast only (no-op for bf16/fp16).
- ``KV_QUANT_MODE == 1`` (FP8 per-tensor): dequantize inline
using the tensor-wide scale.
- ``KV_QUANT_MODE >= 2`` (per-token-head int8/fp8): cast to Q's
dtype and return per-head scales separately — the caller applies
them after the dot product for better numerical efficiency.
Returns ``(data, token_head_scales)``. *token_head_scales* is only
meaningful when ``KV_QUANT_MODE >= 2``; callers gate its use on
the same constexpr so the compiler eliminates dead code.
"""
# KV_QUANT_MODE values: 0=none, 1=fp8 per-tensor,
# 2=int8 per-token-head, 3=fp8 per-token-head
# Placeholder scales (float32) — never read when KV_QUANT_MODE < 2.
unused_scales = tile_mask.to(tl.float32)
if KV_QUANT_MODE == 1: # FP8 per-tensor
if Q.dtype.is_fp8():
return data.to(Q.dtype), unused_scales
return (data.to(tl.float32) * tl.load(tensor_scale)).to(Q.dtype), unused_scales
if KV_QUANT_MODE >= 2: # per-token-head (int8 or fp8)
scale_idx = (
physical_block_idx * stride_s_blk
+ (seq_offset % BLOCK_SIZE) * stride_s_slot
+ kv_head_idx * stride_s_head
)
token_head_scales = tl.load(
scale_cache_ptr + scale_idx, mask=tile_mask, other=1.0
)
return data.to(Q.dtype), token_head_scales
# .to(Q.dtype) is a no-op when data is already Q's type (bf16/fp16),
# but required so Triton sees consistent return types across branches.
return data.to(Q.dtype), unused_scales
@triton.jit
def find_seq_idx(
query_start_len_ptr,
@@ -105,8 +163,20 @@ def kernel_unified_attention_2d(
num_seqs: tl.int32,
BLOCK_M: tl.constexpr, # int
USE_FP8: tl.constexpr, # bool
# KV cache quantization: 0=none, 1=fp8, 2=per-token-head
KV_QUANT_MODE: tl.constexpr = 0,
FP8_MIN: tl.constexpr = float8_info.min,
FP8_MAX: tl.constexpr = float8_info.max,
# Per-token-head scale caches (KV_QUANT_MODE >= 2)
# Shape: [num_blocks, block_size, num_kv_heads]
k_scale_cache_ptr=None,
v_scale_cache_ptr=None,
stride_ks_blk=0,
stride_ks_slot=0,
stride_ks_head=0,
stride_vs_blk=0,
stride_vs_slot=0,
stride_vs_head=0,
):
q_block_global_idx = tl.program_id(0)
kv_head_idx = tl.program_id(1)
@@ -258,14 +328,21 @@ def kernel_unified_attention_2d(
mask=dim_mask[:, None] & tile_mask[None, :],
other=0.0,
)
if K_load.dtype.is_fp8():
if Q.dtype.is_fp8():
K = K_load
else:
K = (K_load.to(tl.float32) * tl.load(k_scale)).to(Q.dtype)
else:
K = K_load
K, k_token_head_scales = _prepare_kv_tile(
K_load,
Q,
k_scale,
k_scale_cache_ptr,
physical_block_idx,
seq_offset,
kv_head_idx,
stride_ks_blk,
stride_ks_slot,
stride_ks_head,
tile_mask,
BLOCK_SIZE,
KV_QUANT_MODE,
)
# V : (TILE_SIZE, HEAD_SIZE)
V_load = tl.load(
@@ -273,14 +350,21 @@ def kernel_unified_attention_2d(
mask=dim_mask[None, :] & tile_mask[:, None],
other=0.0,
)
if V_load.dtype.is_fp8():
if Q.dtype.is_fp8():
V = V_load
else:
V = (V_load.to(tl.float32) * tl.load(v_scale)).to(Q.dtype)
else:
V = V_load
V, v_token_head_scales = _prepare_kv_tile(
V_load,
Q,
v_scale,
v_scale_cache_ptr,
physical_block_idx,
seq_offset,
kv_head_idx,
stride_vs_blk,
stride_vs_slot,
stride_vs_head,
tile_mask,
BLOCK_SIZE,
KV_QUANT_MODE,
)
# Compute attention mask: causal by default (key <= query)
query_abs_pos = context_len + query_pos[:, None]
@@ -318,7 +402,12 @@ def kernel_unified_attention_2d(
# S : (BLOCK_M, TILE_SIZE)
S = tl.zeros(shape=(BLOCK_M, TILE_SIZE), dtype=tl.float32)
S += scale * tl.dot(Q, K)
# Per-token-head quant: fuse softmax_scale with per-head k_scale
# to avoid a separate BLOCK_M × TILE_SIZE multiply on S.
if KV_QUANT_MODE >= 2:
S += tl.dot(Q, K) * (scale * k_token_head_scales[None, :])
else:
S += scale * tl.dot(Q, K)
if USE_SOFTCAP:
S = apply_softcap(S, softcap)
@@ -382,7 +471,12 @@ def kernel_unified_attention_2d(
)
# acc : (BLOCK_M, HEAD_SIZE_PADDED)
acc += tl.dot(P.to(V.dtype), V)
# Per-token-head quant: apply v_scale to P instead of V.
if KV_QUANT_MODE >= 2:
P_v = (P * v_token_head_scales[None, :]).to(V.dtype)
acc += tl.dot(P_v, V)
else:
acc += tl.dot(P.to(V.dtype), V)
# epilogue
acc = acc / L[:, None]
@@ -453,6 +547,18 @@ def kernel_unified_attention_3d(
USE_MM_PREFIX: tl.constexpr, # bool
MAX_MM_RANGES: tl.constexpr, # int
mm_prefix_range_ptr, # [num_seqs] - prefix length for each sequence
# KV cache quantization: 0=none, 1=fp8, 2=per-token-head
KV_QUANT_MODE: tl.constexpr = 0,
# Per-token-head scale caches (KV_QUANT_MODE >= 2)
# Shape: [num_blocks, block_size, num_kv_heads]
k_scale_cache_ptr=None,
v_scale_cache_ptr=None,
stride_ks_blk=0,
stride_ks_slot=0,
stride_ks_head=0,
stride_vs_blk=0,
stride_vs_slot=0,
stride_vs_head=0,
):
q_block_global_idx = tl.program_id(0)
kv_head_idx = tl.program_id(1)
@@ -613,14 +719,21 @@ def kernel_unified_attention_3d(
mask=dim_mask[:, None] & tile_mask[None, :],
other=0.0,
)
if K_load.dtype.is_fp8():
if Q.dtype.is_fp8():
K = K_load
else:
K = (K_load.to(tl.float32) * tl.load(k_scale)).to(Q.dtype)
else:
K = K_load
K, k_token_head_scales = _prepare_kv_tile(
K_load,
Q,
k_scale,
k_scale_cache_ptr,
physical_block_idx,
seq_offset,
kv_head_idx,
stride_ks_blk,
stride_ks_slot,
stride_ks_head,
tile_mask,
BLOCK_SIZE,
KV_QUANT_MODE,
)
# V : (TILE_SIZE, HEAD_SIZE)
V_load = tl.load(
@@ -628,14 +741,21 @@ def kernel_unified_attention_3d(
mask=dim_mask[None, :] & tile_mask[:, None],
other=0.0,
)
if V_load.dtype.is_fp8():
if Q.dtype.is_fp8():
V = V_load
else:
V = (V_load.to(tl.float32) * tl.load(v_scale)).to(Q.dtype)
else:
V = V_load
V, v_token_head_scales = _prepare_kv_tile(
V_load,
Q,
v_scale,
v_scale_cache_ptr,
physical_block_idx,
seq_offset,
kv_head_idx,
stride_vs_blk,
stride_vs_slot,
stride_vs_head,
tile_mask,
BLOCK_SIZE,
KV_QUANT_MODE,
)
# Compute attention mask: causal by default (key <= query)
query_abs_pos = context_len + query_pos[:, None]
@@ -672,7 +792,13 @@ def kernel_unified_attention_3d(
# S : (BLOCK_M, TILE_SIZE)
S = tl.zeros(shape=(BLOCK_M, TILE_SIZE), dtype=tl.float32)
S += scale * tl.dot(Q, K)
# Per-token-head quant: fuse softmax_scale with per-head k_scale
# to avoid a separate BLOCK_M × TILE_SIZE multiply on S.
if KV_QUANT_MODE >= 2:
S += tl.dot(Q, K) * (scale * k_token_head_scales[None, :])
else:
S += scale * tl.dot(Q, K)
if USE_SOFTCAP:
S = apply_softcap(S, softcap)
@@ -736,7 +862,12 @@ def kernel_unified_attention_3d(
)
# acc : (BLOCK_M, HEAD_SIZE_PADDED)
acc += tl.dot(P.to(V.dtype), V)
# Per-token-head quant: apply v_scale to P instead of V.
if KV_QUANT_MODE >= 2:
P_v = (P * v_token_head_scales[None, :]).to(V.dtype)
acc += tl.dot(P_v, V)
else:
acc += tl.dot(P.to(V.dtype), V)
segm_output_offset = (
query_offset_0[:, None].to(tl.int64)
@@ -911,6 +1042,10 @@ def unified_attention(
# Optional tensor for prefix lengths (PrefixLM support)
mm_prefix_range=None,
use_alibi_sqrt=False,
# KV cache quantization mode and per-token-head scale caches.
kv_quant_mode: KVQuantMode = KVQuantMode.NONE,
k_scale_cache=None, # [num_blocks, block_size, num_kv_heads] float32
v_scale_cache=None, # [num_blocks, block_size, num_kv_heads] float32
):
assert causal, "Only causal attention is supported"
assert q_descale is None, "Q scales not supported"
@@ -1040,6 +1175,15 @@ def unified_attention(
num_seqs=num_seqs,
BLOCK_M=BLOCK_M,
USE_FP8=output_scale is not None,
KV_QUANT_MODE=kv_quant_mode,
k_scale_cache_ptr=k_scale_cache,
v_scale_cache_ptr=v_scale_cache,
stride_ks_blk=k_scale_cache.stride(0) if k_scale_cache is not None else 0,
stride_ks_slot=k_scale_cache.stride(1) if k_scale_cache is not None else 0,
stride_ks_head=k_scale_cache.stride(2) if k_scale_cache is not None else 0,
stride_vs_blk=v_scale_cache.stride(0) if v_scale_cache is not None else 0,
stride_vs_slot=v_scale_cache.stride(1) if v_scale_cache is not None else 0,
stride_vs_head=v_scale_cache.stride(2) if v_scale_cache is not None else 0,
)
else:
kernel_unified_attention_3d[
@@ -1092,6 +1236,15 @@ def unified_attention(
num_seqs=num_seqs,
BLOCK_M=BLOCK_M,
NUM_SEGMENTS_PER_SEQ=num_par_softmax_segments,
KV_QUANT_MODE=kv_quant_mode,
k_scale_cache_ptr=k_scale_cache,
v_scale_cache_ptr=v_scale_cache,
stride_ks_blk=k_scale_cache.stride(0) if k_scale_cache is not None else 0,
stride_ks_slot=k_scale_cache.stride(1) if k_scale_cache is not None else 0,
stride_ks_head=k_scale_cache.stride(2) if k_scale_cache is not None else 0,
stride_vs_blk=v_scale_cache.stride(0) if v_scale_cache is not None else 0,
stride_vs_slot=v_scale_cache.stride(1) if v_scale_cache is not None else 0,
stride_vs_head=v_scale_cache.stride(2) if v_scale_cache is not None else 0,
)
reduce_segments[(q.shape[0], num_query_heads)](
output_ptr=out,