[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
+132 -18
View File
@@ -33,9 +33,14 @@ from vllm.v1.attention.backends.utils import get_kv_cache_layout
from vllm.v1.attention.ops.triton_prefill_attention import context_attention_fwd
from vllm.v1.attention.ops.triton_reshape_and_cache_flash import (
triton_reshape_and_cache_flash,
triton_reshape_and_cache_flash_per_token_head_quant,
)
from vllm.v1.attention.ops.triton_unified_attention import unified_attention
from vllm.v1.kv_cache_interface import AttentionSpec
from vllm.v1.kv_cache_interface import (
AttentionSpec,
get_kv_quant_mode,
kv_cache_uses_per_token_head_scales,
)
logger = init_logger(__name__)
@@ -270,6 +275,8 @@ class TritonAttentionBackend(AttentionBackend):
"fp8",
"fp8_e4m3",
"fp8_e5m2",
"int8_per_token_head",
"fp8_per_token_head",
]
@staticmethod
@@ -302,6 +309,18 @@ class TritonAttentionBackend(AttentionBackend):
) -> tuple[int, ...]:
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.
from vllm.utils.torch_utils import (
STR_DTYPE_TO_TORCH_DTYPE,
get_dtype_size,
)
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)
return (num_blocks, 2, block_size, num_kv_heads, head_size)
@staticmethod
@@ -365,6 +384,62 @@ class TritonAttentionBackend(AttentionBackend):
class TritonAttentionImpl(AttentionImpl):
# Per-token-head quant: scale views carved from inline head padding.
_k_scale_cache: torch.Tensor | None = None
_v_scale_cache: torch.Tensor | None = None
def _ensure_scale_caches(self, kv_cache: torch.Tensor) -> None:
"""Extract per-head scale views from the padded head dimension.
The KV cache shape is ``(num_blocks, 2, block_size, nkv, hs+pad)``
where ``pad = sizeof(float32) / sizeof(cache_dtype)``. The last
``pad`` elements of each head hold one float32 scale. We create
strided float32 views over those bytes.
Scale shape: ``(num_blocks, block_size, num_kv_heads)``
"""
if self._k_scale_cache is not None:
return
from vllm.utils.torch_utils import get_dtype_size
num_blocks, _, block_size, nkv, padded_hs = kv_cache.shape
dtype_sz = kv_cache.element_size()
scale_pad = get_dtype_size(torch.float32) // dtype_sz # e.g. 4
hs = padded_hs - scale_pad
raw = kv_cache.untyped_storage()
base_f32 = torch.tensor([], dtype=torch.float32, device=kv_cache.device).set_(
raw
)
# In the raw bytes, each (block, kv_half, slot, head) occupies
# padded_hs * dtype_sz bytes. The scale float32 sits at byte
# offset hs * dtype_sz within that region.
kv_half_bytes = block_size * nkv * padded_hs * dtype_sz
full_block_f32 = 2 * kv_half_bytes // 4 # stride between blocks
slot_f32 = nkv * padded_hs * dtype_sz // 4 # stride between slots
head_f32 = padded_hs * dtype_sz // 4 # stride between heads
scale_off_f32 = hs * dtype_sz // 4 # offset to scale within head
# K scales: kv_half=0
self._k_scale_cache = torch.as_strided(
base_f32,
size=(num_blocks, block_size, nkv),
stride=(full_block_f32, slot_f32, head_f32),
storage_offset=scale_off_f32,
)
self._k_scale_cache.fill_(1.0)
# V scales: kv_half=1, offset by kv_half_bytes
v_base_f32 = kv_half_bytes // 4
self._v_scale_cache = torch.as_strided(
base_f32,
size=(num_blocks, block_size, nkv),
stride=(full_block_f32, slot_f32, head_f32),
storage_offset=v_base_f32 + scale_off_f32,
)
self._v_scale_cache.fill_(1.0)
def fused_output_quant_supported(self, quant_key: QuantKey):
return quant_key == kFp8StaticTensorSym
@@ -418,6 +493,9 @@ class TritonAttentionImpl(AttentionImpl):
self.use_alibi_sqrt = use_alibi_sqrt
self.supports_quant_query_input = current_platform.is_cuda()
self._kv_quant_mode = get_kv_quant_mode(kv_cache_dtype)
self._is_per_token_head_quant = self._kv_quant_mode.is_per_token_head
def forward(
self,
layer: torch.nn.Module,
@@ -480,15 +558,35 @@ class TritonAttentionImpl(AttentionImpl):
layer,
)
# For decoder and cross-attention, use KV cache as before
key_cache, value_cache = kv_cache.unbind(1)
if is_quantized_kv_cache(self.kv_cache_dtype):
if key_cache.dtype != self.fp8_dtype:
# Per-token-head quantized KV cache: use separate scale caches.
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)
assert layer._q_scale_float == 1.0, (
"A non 1.0 q_scale is not currently supported."
k_descale = None
v_descale = None
k_scale_cache = self._k_scale_cache
v_scale_cache = self._v_scale_cache
# FP8 per-tensor / auto path (original flow).
else:
key_cache, value_cache = kv_cache.unbind(1)
if is_quantized_kv_cache(self.kv_cache_dtype):
if key_cache.dtype != self.fp8_dtype:
key_cache = key_cache.view(self.fp8_dtype)
value_cache = value_cache.view(self.fp8_dtype)
assert layer._q_scale_float == 1.0, (
"A non 1.0 q_scale is not currently supported."
)
descale_shape = (
attn_metadata.query_start_loc.shape[0] - 1,
key_cache.shape[2],
)
k_descale = layer._k_scale.expand(descale_shape)
v_descale = layer._v_scale.expand(descale_shape)
k_scale_cache = None
v_scale_cache = None
cu_seqlens_q = attn_metadata.query_start_loc
seqused_k = attn_metadata.seq_lens
@@ -502,7 +600,6 @@ class TritonAttentionImpl(AttentionImpl):
softmax_segm_max = attn_metadata.softmax_segm_max
softmax_segm_expsum = attn_metadata.softmax_segm_expsum
descale_shape = (cu_seqlens_q.shape[0] - 1, key_cache.shape[2])
mm_prefix_range_tensor = attn_metadata.mm_prefix_range_tensor
unified_attention(
@@ -522,8 +619,8 @@ class TritonAttentionImpl(AttentionImpl):
block_table=block_table,
softcap=self.logits_soft_cap,
q_descale=None, # Not supported
k_descale=layer._k_scale.expand(descale_shape),
v_descale=layer._v_scale.expand(descale_shape),
k_descale=k_descale,
v_descale=v_descale,
seq_threshold_3D=seq_threshold_3D,
num_par_softmax_segments=num_par_softmax_segments,
softmax_segm_output=softmax_segm_output,
@@ -532,6 +629,9 @@ class TritonAttentionImpl(AttentionImpl):
sinks=self.sinks,
output_scale=output_scale,
mm_prefix_range=mm_prefix_range_tensor,
kv_quant_mode=self._kv_quant_mode,
k_scale_cache=k_scale_cache,
v_scale_cache=v_scale_cache,
)
return output
@@ -555,10 +655,10 @@ class TritonAttentionImpl(AttentionImpl):
attn_metadata: Encoder attention metadata
layer: The attention layer
"""
# For encoder attention, process FP8 quantization if needed
# Quantized KV cache is not supported for encoder attention.
if is_quantized_kv_cache(self.kv_cache_dtype):
raise NotImplementedError(
"quantization is not supported for encoder attention"
"quantized KV cache is not supported for encoder attention"
)
# Use encoder-specific metadata for sequence information
@@ -594,16 +694,28 @@ class TritonAttentionImpl(AttentionImpl):
# For encoder attention,
# we use direct Q, K, V tensors without caching
return
# For decoder and cross-attention, use KV cache as before
key_cache, value_cache = kv_cache.unbind(1)
# Reshape the input keys and values and store them in the cache.
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)
triton_reshape_and_cache_flash_per_token_head_quant(
key,
value,
key_cache,
value_cache,
self._k_scale_cache,
self._v_scale_cache,
slot_mapping,
)
return
# For decoder and cross-attention, use KV cache as before.
key_cache, value_cache = kv_cache.unbind(1)
if is_quantized_kv_cache(self.kv_cache_dtype):
key_cache = key_cache.view(self.fp8_dtype)
value_cache = value_cache.view(self.fp8_dtype)
# triton kernel does not support uint8 kv_cache
# (because some explicit casts (e.g. float8_e4m3fnuz)
# are not supported)
triton_reshape_and_cache_flash(
key,
value,
@@ -616,6 +728,8 @@ class TritonAttentionImpl(AttentionImpl):
)
def fused_rope_kvcache_supported(self):
if self._is_per_token_head_quant:
return False
return rocm_aiter_ops.is_enabled()
def do_rope_and_kv_cache_update(