[Feature] Triton INT4 per-token-head KV cache quantization (#40835)

Signed-off-by: JartX <sagformas@epdcenter.es>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
This commit is contained in:
JartX
2026-06-24 10:21:25 +00:00
committed by GitHub
co-authored by mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
parent d20dbf921b
commit 70749fdcca
10 changed files with 1462 additions and 111 deletions
+1
View File
@@ -29,6 +29,7 @@ CacheDType = Literal[
"turboquant_4bit_nc",
"turboquant_k3v4_nc",
"turboquant_3bit_nc",
"int4_per_token_head",
"int8_per_token_head",
"fp8_per_token_head",
"nvfp4",
+1
View File
@@ -39,6 +39,7 @@ STR_DTYPE_TO_TORCH_DTYPE = {
"fp8_e4m3": torch.uint8,
"fp8_e5m2": torch.uint8,
"int8": torch.int8,
"int4_per_token_head": torch.uint8,
"int8_per_token_head": torch.int8,
"fp8_per_token_head": torch.uint8,
"fp8_inc": torch.float8_e4m3fn,
+33 -16
View File
@@ -258,6 +258,7 @@ class TritonAttentionBackend(AttentionBackend):
"fp8",
"fp8_e4m3",
"fp8_e5m2",
"int4_per_token_head",
"int8_per_token_head",
"fp8_per_token_head",
]
@@ -301,9 +302,11 @@ class TritonAttentionBackend(AttentionBackend):
if block_size % 16 != 0:
raise ValueError("Block size must be a multiple of 16.")
if kv_cache_uses_per_token_head_scales(cache_dtype_str):
# Pad head_size by sizeof(float32)/sizeof(cache_dtype) so
# the per-head scale fits inline. The backend extracts
# data[:head_size] and scale[head_size:] via typed views.
# Pad the head dim by sizeof(float32)/sizeof(cache_dtype) so the
# per-(token, head) scale fits inline after the quantized data;
# the backend extracts data[:head_size] and scale[head_size:] via
# typed views (see _ensure_scale_caches). INT4 packs two values
# per byte, so the data occupies only head_size // 2 bytes.
from vllm.utils.torch_utils import (
STR_DTYPE_TO_TORCH_DTYPE,
get_dtype_size,
@@ -311,7 +314,11 @@ class TritonAttentionBackend(AttentionBackend):
cache_dtype = STR_DTYPE_TO_TORCH_DTYPE[cache_dtype_str]
scale_pad = get_dtype_size(torch.float32) // get_dtype_size(cache_dtype)
return (num_blocks, 2, block_size, num_kv_heads, head_size + scale_pad)
if get_kv_quant_mode(cache_dtype_str) == KVQuantMode.INT4_PER_TOKEN_HEAD:
data_head_size = head_size // 2
else:
data_head_size = head_size
return (num_blocks, 2, block_size, num_kv_heads, data_head_size + scale_pad)
return (num_blocks, 2, block_size, num_kv_heads, head_size)
@staticmethod
@@ -587,18 +594,14 @@ class TritonAttentionImpl(AttentionImpl):
layer,
)
# Per-token-head quantized KV cache: use separate scale caches.
# Per-token-head quantized KV cache: handled by the core unified
# kernel, which dequantizes per-(token, head) inline via constexpr
# branches (INT8 / FP8) and dispatches to the packed INT4 kernel.
if self._is_per_token_head_quant:
self._ensure_scale_caches(kv_cache)
key_cache, value_cache = kv_cache.unbind(1)
if key_cache.dtype == torch.uint8:
key_cache = key_cache.view(self.fp8_dtype)
value_cache = value_cache.view(self.fp8_dtype)
q_descale = None
k_descale = None
v_descale = None
key_cache, value_cache = self._pth_key_value_caches(kv_cache)
k_scale_cache = self._k_scale_cache
v_scale_cache = self._v_scale_cache
q_descale = k_descale = v_descale = None
# FP8 per-tensor / auto path (original flow).
else:
key_cache, value_cache = kv_cache.unbind(1)
@@ -675,6 +678,17 @@ class TritonAttentionImpl(AttentionImpl):
return output
def _pth_key_value_caches(
self, kv_cache: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor]:
"""Per-token-head K/V cache views (ensures scale caches; FP8 retyped)."""
self._ensure_scale_caches(kv_cache)
key_cache, value_cache = kv_cache.unbind(1)
if self._kv_quant_mode == KVQuantMode.FP8_PER_TOKEN_HEAD:
key_cache = key_cache.view(self.fp8_dtype)
value_cache = value_cache.view(self.fp8_dtype)
return key_cache, value_cache
def _forward_encoder_attention(
self,
query: torch.Tensor,
@@ -737,7 +751,9 @@ class TritonAttentionImpl(AttentionImpl):
if self._is_per_token_head_quant:
self._ensure_scale_caches(kv_cache)
key_cache, value_cache = kv_cache.unbind(1)
if key_cache.dtype == torch.uint8:
k_scale_cache = self._k_scale_cache
v_scale_cache = self._v_scale_cache
if self._kv_quant_mode == KVQuantMode.FP8_PER_TOKEN_HEAD:
key_cache = key_cache.view(self.fp8_dtype)
value_cache = value_cache.view(self.fp8_dtype)
triton_reshape_and_cache_flash_per_token_head_quant(
@@ -745,9 +761,10 @@ class TritonAttentionImpl(AttentionImpl):
value,
key_cache,
value_cache,
self._k_scale_cache,
self._v_scale_cache,
k_scale_cache,
v_scale_cache,
slot_mapping,
kv_quant_mode=self._kv_quant_mode,
)
return
# For decoder and cross-attention, use KV cache as before.
File diff suppressed because it is too large Load Diff
@@ -10,6 +10,7 @@ from vllm.model_executor.layers.quantization.utils.quant_utils import (
from vllm.platforms import current_platform
from vllm.triton_utils import tl, triton
from vllm.utils.torch_utils import is_quantized_kv_cache
from vllm.v1.kv_cache_interface import KVQuantMode
FP8_MIN, FP8_MAX = get_fp8_min_max()
@@ -276,6 +277,7 @@ def triton_reshape_and_cache_flash_per_token_head_quant(
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]
kv_quant_mode: KVQuantMode,
):
"""Quantize key/value per (token, head) and write to paged cache.
@@ -283,9 +285,26 @@ def triton_reshape_and_cache_flash_per_token_head_quant(
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.
INT4 needs sub-byte packing + a Hadamard rotation, so it is handled by
its own kernel; INT8 / FP8 share this kernel, with the quantization
range (QUANT_MAX, QUANT_MIN) derived from the cache tensor dtype.
"""
if kv_quant_mode == KVQuantMode.INT4_PER_TOKEN_HEAD:
from vllm.v1.attention.ops.int4_per_token_head import (
reshape_and_cache_int4,
)
reshape_and_cache_int4(
key,
value,
key_cache,
value_cache,
slot_mapping,
k_scale_cache=k_scale_cache,
v_scale_cache=v_scale_cache,
)
return
cache_dtype = key_cache.dtype
quant_params = _PER_TOKEN_HEAD_QUANT_PARAMS.get(cache_dtype)
if quant_params is None:
@@ -259,7 +259,8 @@ def kernel_unified_attention(
stride_vs_head: tl.int64 = None,
# KV cache quantization mode handled inside this kernel via constexpr
# branches: NONE (0), FP8_PER_TENSOR (1), INT8_PER_TOKEN_HEAD (2),
# FP8_PER_TOKEN_HEAD (3).
# FP8_PER_TOKEN_HEAD (3). Sub-byte INT4 (4) uses its own
# int4_per_token_head kernel, not this one.
KV_QUANT_MODE: tl.constexpr = 0,
FP8_MIN: tl.constexpr = float8_info.min,
FP8_MAX: tl.constexpr = float8_info.max,
@@ -824,6 +825,47 @@ def unified_attention(
use_causal = bool(causal) if not use_per_seq_causal else True
per_seq_causal_ptr = causal if use_per_seq_causal else None
# Sub-byte packed mode (INT4) needs a bespoke kernel (split-dot +
# sub-byte unpack); everything else goes through the core kernel below.
if kv_quant_mode == KVQuantMode.INT4_PER_TOKEN_HEAD:
assert use_causal and not use_per_seq_causal, (
"INT4_PER_TOKEN_HEAD only supports causal attention"
)
from vllm.v1.attention.ops.int4_per_token_head import (
unified_attention_int4,
)
if sinks is not None:
assert sinks.shape[0] == q.shape[1], "Sinks must be num_query_heads size"
unified_attention_int4(
q=q,
k_cache=k,
v_cache=v,
out=out,
cu_seqlens_q=cu_seqlens_q,
max_seqlen_q=max_seqlen_q,
seqused_k=seqused_k,
max_seqlen_k=max_seqlen_k,
softmax_scale=softmax_scale,
window_size=window_size,
block_table=block_table,
softcap=softcap,
sinks=sinks,
alibi_slopes=alibi_slopes,
use_alibi_sqrt=use_alibi_sqrt,
qq_bias=qq_bias,
output_scale=output_scale,
mm_prefix_range=mm_prefix_range,
k_scale_cache=k_scale_cache,
v_scale_cache=v_scale_cache,
seq_threshold_3D=seq_threshold_3D,
num_par_softmax_segments=num_par_softmax_segments,
softmax_segm_output=softmax_segm_output,
softmax_segm_max=softmax_segm_max,
softmax_segm_expsum=softmax_segm_expsum,
)
return
if sinks is not None:
assert sinks.shape[0] == q.shape[1], "Sinks must be num_query_heads size"
+21 -21
View File
@@ -41,7 +41,8 @@ class KVQuantMode(IntEnum):
FP8_PER_TENSOR = 1 # per-tensor scales (current fp8 path)
INT8_PER_TOKEN_HEAD = 2 # per-token-head dynamic scales for int8
FP8_PER_TOKEN_HEAD = 3 # per-token-head dynamic scales for fp8
NVFP4 = 4 # packed fp4 data + fp8 block scales
INT4_PER_TOKEN_HEAD = 4 # packed 2×int4/byte, RHT + asymmetric zp
NVFP4 = 5 # packed fp4 data + fp8 block scales
@property
def is_per_token_head(self) -> bool:
@@ -49,6 +50,7 @@ class KVQuantMode(IntEnum):
return self in (
KVQuantMode.INT8_PER_TOKEN_HEAD,
KVQuantMode.FP8_PER_TOKEN_HEAD,
KVQuantMode.INT4_PER_TOKEN_HEAD,
)
@property
@@ -59,6 +61,8 @@ class KVQuantMode(IntEnum):
def get_kv_quant_mode(kv_cache_dtype: str) -> KVQuantMode:
"""Map a ``kv_cache_dtype`` string to a :class:`KVQuantMode`."""
if kv_cache_dtype == "int4_per_token_head":
return KVQuantMode.INT4_PER_TOKEN_HEAD
if kv_cache_dtype == "int8_per_token_head":
return KVQuantMode.INT8_PER_TOKEN_HEAD
if kv_cache_dtype == "fp8_per_token_head":
@@ -184,19 +188,16 @@ class AttentionSpec(KVCacheSpec):
def real_page_size_bytes(self) -> int:
if self.kv_quant_mode.is_nvfp4:
# Packed layout: fp4 data + fp8 block scales per head.
full_dim = nvfp4_kv_cache_full_dim(self.head_size)
return (
2
* self.block_size
* self.num_kv_heads
* full_dim
* get_dtype_size(self.dtype)
)
head_dim = nvfp4_kv_cache_full_dim(self.head_size)
elif self.kv_quant_mode == KVQuantMode.INT4_PER_TOKEN_HEAD:
head_dim = self.head_size // 2
else:
head_dim = self.head_size
return (
2
* self.block_size
* self.num_kv_heads
* self.head_size
* head_dim
* get_dtype_size(self.dtype)
)
@@ -314,17 +315,12 @@ class FullAttentionSpec(AttentionSpec):
last_dim = nvfp4_kv_cache_full_dim(
self.head_size
) + nvfp4_kv_cache_full_dim(self.head_size_v)
return (
self.block_size
* self.num_kv_heads
* last_dim
* get_dtype_size(self.dtype)
)
elif self.kv_quant_mode == KVQuantMode.INT4_PER_TOKEN_HEAD:
last_dim = self.head_size // 2 + self.head_size_v // 2
else:
last_dim = self.head_size + self.head_size_v
return (
self.block_size
* self.num_kv_heads
* (self.head_size + self.head_size_v)
* get_dtype_size(self.dtype)
self.block_size * self.num_kv_heads * last_dim * get_dtype_size(self.dtype)
)
@@ -390,10 +386,14 @@ class MLAAttentionSpec(FullAttentionSpec):
# V3.2 main MLA: 656-byte custom layout (kv_lora_rank=512 +
# qk_rope_head_dim=64, head_size=576). See flashmla_sparse.py.
return self.block_size * 656
if self.kv_quant_mode == KVQuantMode.INT4_PER_TOKEN_HEAD:
head_dim = self.head_size // 2
else:
head_dim = self.head_size
return (
self.storage_block_size
* self.num_kv_heads
* self.head_size
* head_dim
* get_dtype_size(self.dtype)
)