Add nvfp4 kv cache support (#40177)

Signed-off-by: Shiyang Chen <shiychen@nvidia.com>
This commit is contained in:
sychen52
2026-05-01 04:55:16 +00:00
committed by GitHub
parent 941fb50835
commit 947138b6c2
8 changed files with 503 additions and 96 deletions
+12
View File
@@ -1884,6 +1884,18 @@ class VllmConfig:
"in the middle of a mm input"
)
@model_validator(mode="after")
def validate_nvfp4_kv_cache_with_mla(self) -> "VllmConfig":
if self.model_config is None:
return self
if self.cache_config.cache_dtype == "nvfp4" and self.model_config.use_mla:
raise ValueError(
"nvfp4 KV cache is not supported with MLA (Multi-head Latent "
"Attention) backends. Please use a different --kv-cache-dtype "
"(e.g., 'fp8' or 'auto') for MLA models such as DeepSeek."
)
return self
@model_validator(mode="after")
def validate_mamba_block_size(self) -> "VllmConfig":
if self.model_config is None:
@@ -114,12 +114,12 @@ QUANT_ALGOS = [
# MIXED_PRECISION,
"MIXED_PRECISION",
]
KV_CACHE_QUANT_ALGOS = ["FP8"]
KV_CACHE_QUANT_ALGOS = ["FP8", "NVFP4"]
class ModelOptFp8KVCacheMethod(BaseKVCacheMethod):
class ModelOptKVCacheMethod(BaseKVCacheMethod):
"""
Supports loading kv-cache scaling factors from FP8 checkpoints.
Supports loading kv-cache scaling factors from FP8 or NVFP4 checkpoints.
"""
def __init__(self, quant_config: "ModelOptQuantConfigBase"):
@@ -995,7 +995,7 @@ class ModelOptFp8MoEMethod(FusedMoEMethodBase):
ModelOptFp8Config.LinearMethodCls = ModelOptFp8LinearMethod
ModelOptFp8Config.FusedMoEMethodCls = ModelOptFp8MoEMethod
ModelOptFp8Config.KVCacheMethodCls = ModelOptFp8KVCacheMethod
ModelOptFp8Config.KVCacheMethodCls = ModelOptKVCacheMethod
class ModelOptNvFp4Config(ModelOptQuantConfigBase):
@@ -1488,7 +1488,7 @@ class ModelOptNvFp4FusedMoE(FusedMoEMethodBase):
ModelOptNvFp4Config.LinearMethodCls = ModelOptNvFp4LinearMethod
ModelOptNvFp4Config.FusedMoEMethodCls = ModelOptNvFp4FusedMoE
ModelOptNvFp4Config.KVCacheMethodCls = ModelOptFp8KVCacheMethod
ModelOptNvFp4Config.KVCacheMethodCls = ModelOptKVCacheMethod
class ModelOptMxFp8Config(ModelOptQuantConfigBase):
@@ -2018,7 +2018,7 @@ class ModelOptMxFp8FusedMoE(FusedMoEMethodBase):
# Register the method classes for ModelOptMxFp8Config
ModelOptMxFp8Config.LinearMethodCls = ModelOptMxFp8LinearMethod
ModelOptMxFp8Config.FusedMoEMethodCls = ModelOptMxFp8FusedMoE
ModelOptMxFp8Config.KVCacheMethodCls = ModelOptFp8KVCacheMethod
ModelOptMxFp8Config.KVCacheMethodCls = ModelOptKVCacheMethod
class ModelOptMixedPrecisionConfig(ModelOptQuantConfigBase):
@@ -2166,7 +2166,7 @@ class ModelOptMixedPrecisionConfig(ModelOptQuantConfigBase):
# KV-cache quantization
if isinstance(layer, Attention):
if self.kv_cache_quant_method:
return ModelOptFp8KVCacheMethod(self)
return ModelOptKVCacheMethod(self)
return None
# Excluded layers
+114 -15
View File
@@ -332,6 +332,7 @@ class FlashInferBackend(AttentionBackend):
"fp8",
"fp8_e4m3",
"fp8_e5m2",
"nvfp4",
]
@staticmethod
@@ -388,13 +389,15 @@ class FlashInferBackend(AttentionBackend):
return stride_order
@staticmethod
def get_fp8_dtype_for_flashinfer(kv_cache_dtype: str) -> torch.dtype:
def get_dtype_for_flashinfer(kv_cache_dtype: str) -> torch.dtype:
if kv_cache_dtype in ("fp8", "fp8_e4m3"):
return torch.float8_e4m3fn
elif kv_cache_dtype == "fp8_e5m2":
return torch.float8_e5m2
elif kv_cache_dtype == "nvfp4":
return torch.uint8
else:
raise ValueError(f"Unrecognized FP8 dtype: {kv_cache_dtype}")
raise ValueError(f"Unrecognized dtype: {kv_cache_dtype}")
@classmethod
def get_supported_head_sizes(cls) -> list[int]:
@@ -622,9 +625,8 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
# For NVFP4, kv_cache_dtype stays as the string "nvfp4"
# which is passed to FlashInferImpl
self.kv_cache_dtype = self.cache_dtype
raise NotImplementedError("nvfp4 KV cache is not yet supported")
else:
self.kv_cache_dtype = FlashInferBackend.get_fp8_dtype_for_flashinfer(
self.kv_cache_dtype = FlashInferBackend.get_dtype_for_flashinfer(
self.cache_dtype
)
else:
@@ -645,7 +647,7 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
):
if self.is_kvcache_nvfp4:
# NVFP4 KV cache uses FP8 quantized queries
self.q_data_type = FlashInferBackend.get_fp8_dtype_for_flashinfer(
self.q_data_type = FlashInferBackend.get_dtype_for_flashinfer(
"fp8_e4m3"
)
else:
@@ -765,8 +767,13 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
dcp_a2a=self.dcp_a2a,
)
else:
# NVFP4 KV cache requires the trtllm-gen backend inside
# the wrapper; fa2/fa3 do not support nvfp4.
backend = "trtllm-gen" if self.is_kvcache_nvfp4 else "auto"
self._prefill_wrapper = BatchPrefillWithPagedKVCacheWrapper(
self._get_workspace_buffer(), get_kv_cache_layout()
self._get_workspace_buffer(),
get_kv_cache_layout(),
backend=backend,
)
assert self._prefill_wrapper is not None
return self._prefill_wrapper
@@ -786,6 +793,9 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
paged_kv_indptr = None
paged_kv_indices = None
paged_kv_last_page_len = None
# NVFP4 KV cache requires the trtllm-gen backend inside
# the wrapper; fa2/fa3 do not support nvfp4.
backend = "trtllm-gen" if self.is_kvcache_nvfp4 else "auto"
decode_wrapper = BatchDecodeWithPagedKVCacheWrapper(
self._get_workspace_buffer(),
get_kv_cache_layout(),
@@ -797,6 +807,7 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
# at least as good as cuda cores for all attention ops in latest
# gpus.
use_tensor_cores=True,
backend=backend,
)
# save the decode wrapper
@@ -1148,6 +1159,12 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
prefill_wrapper,
BatchPrefillWithPagedKVCacheWrapper,
)
# NVFP4 trtllm kernel only supports FP8 output;
# use FP8 o_data_type so the wrapper matches the
# FP8 output buffer allocated in forward().
o_dtype = (
FP8_DTYPE if self.is_kvcache_nvfp4 else self.model_config.dtype
)
prefill_wrapper.plan(
qo_indptr=qo_indptr_prefill_cpu,
paged_kv_indptr=paged_kv_indptr_prefill_cpu,
@@ -1163,7 +1180,7 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
logits_soft_cap=self.logits_soft_cap,
q_data_type=self.q_data_type,
kv_data_type=self.kv_cache_dtype,
o_data_type=self.model_config.dtype,
o_data_type=o_dtype,
fixed_split_size=self.prefill_fixed_split_size,
disable_split_kv=self.disable_split_kv,
)
@@ -1197,6 +1214,12 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
# Use the persistent buffer with padding length,
# instead of the same address but chunked version
# in atten_metadata when using cudagraph.
# NVFP4 trtllm kernel only supports FP8 output;
# use FP8 o_data_type so the wrapper matches the
# FP8 output buffer allocated in forward().
o_dtype = (
FP8_DTYPE if self.is_kvcache_nvfp4 else self.model_config.dtype
)
fast_plan_decode(
decode_wrapper,
indptr_cpu=self.paged_kv_indptr.cpu[: num_input_tokens + 1],
@@ -1215,7 +1238,7 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
logits_soft_cap=self.logits_soft_cap,
q_data_type=self.q_data_type,
kv_data_type=self.kv_cache_dtype,
o_data_type=self.model_config.dtype,
o_data_type=o_dtype,
fixed_split_size=self.decode_fixed_split_size,
disable_split_kv=self.disable_split_kv,
)
@@ -1300,6 +1323,17 @@ class FlashInferImpl(AttentionImpl):
self.bmm2_scale: float | None = None
self.o_sf_scale: float | None = None
# Pre-allocated FP8 output buffer for NVFP4 without fused output quant.
if self.is_kvcache_nvfp4 and vllm_config is not None:
max_num_tokens = vllm_config.scheduler_config.max_num_batched_tokens
self._nvfp4_fp8_out = torch.empty(
(max_num_tokens, num_heads, head_size),
dtype=FP8_DTYPE,
device="cuda",
)
else:
self._nvfp4_fp8_out = None
dcp_a2a = (
vllm_config is not None
and vllm_config.parallel_config.decode_context_parallel_size > 1
@@ -1420,7 +1454,7 @@ class FlashInferImpl(AttentionImpl):
if self.kv_sharing_target_layer_name is None and is_quantized_kv_cache(
self.kv_cache_dtype
):
torch_dtype = FlashInferBackend.get_fp8_dtype_for_flashinfer(
torch_dtype = FlashInferBackend.get_dtype_for_flashinfer(
self.kv_cache_dtype
)
kv_cache = kv_cache.view(torch_dtype)
@@ -1500,13 +1534,37 @@ class FlashInferImpl(AttentionImpl):
)
assert prefill_wrapper._sm_scale == self.scale
assert prefill_wrapper._causal
if self.is_kvcache_nvfp4:
kv_cache_permute = nvfp4_kv_data
kv_cache_sf = (
nvfp4_kv_block_scales if self.is_kvcache_nvfp4 else None
)
# NVFP4 trtllm kernel only supports FP8 output.
# Use a pre-allocated FP8 buffer and dequantize
# afterwards.
needs_fp8_out_prefill = (
self.is_kvcache_nvfp4 and output.dtype != FP8_DTYPE
)
if needs_fp8_out_prefill:
out_prefill = self._nvfp4_fp8_out[:num_prefill_tokens]
else:
out_prefill = output[num_decode_tokens:]
prefill_wrapper.run(
prefill_query,
kv_cache_permute,
k_scale=layer._k_scale_float,
v_scale=layer._v_scale_float,
out=output[num_decode_tokens:],
out=out_prefill,
kv_cache_sf=kv_cache_sf,
)
if needs_fp8_out_prefill:
output[
num_decode_tokens : num_decode_tokens + num_prefill_tokens
].copy_(out_prefill.to(output.dtype))
else:
assert isinstance(attn_metadata.prefill, TRTLLMPrefill)
# prefill_query may be non-contiguous or have degenerate strides
@@ -1537,6 +1595,12 @@ class FlashInferImpl(AttentionImpl):
assert self.o_sf_scale is None
out = output[num_decode_tokens:]
# NVFP4 trtllm kernel only supports FP8 output.
# Use a pre-allocated FP8 buffer and dequantize afterwards.
needs_fp8_out = self.is_kvcache_nvfp4 and output.dtype != FP8_DTYPE
if needs_fp8_out:
out = self._nvfp4_fp8_out[:num_prefill_tokens]
prefill_kv_block_scales = None
if self.is_kvcache_nvfp4:
# NVFP4 trtllm-gen kernel requires FP8 query.
@@ -1547,7 +1611,7 @@ class FlashInferImpl(AttentionImpl):
)
mock_kv_cache = nvfp4_kv_data
mock_block_table = block_tables_prefill
prefill_kv_block_scales = nvfp4_kv_block_scales # noqa: F841
prefill_kv_block_scales = nvfp4_kv_block_scales
elif (
attn_metadata.q_data_type != FP8_DTYPE
and self.kv_cache_dtype.startswith("fp8")
@@ -1598,8 +1662,14 @@ class FlashInferImpl(AttentionImpl):
sinks=self.sinks,
o_sf_scale=self.o_sf_scale,
out=out,
kv_cache_sf=prefill_kv_block_scales,
)
if needs_fp8_out:
output[
num_decode_tokens : num_decode_tokens + num_prefill_tokens
].copy_(out[:num_prefill_tokens].to(output.dtype))
if num_decode_tokens > 0:
decode_query = query[:num_decode_tokens]
assert decode_query.shape[0] == num_decode_tokens
@@ -1612,6 +1682,18 @@ class FlashInferImpl(AttentionImpl):
assert decode_wrapper._logits_soft_cap == (self.logits_soft_cap or 0.0)
assert decode_wrapper._sm_scale == self.scale
if self.is_kvcache_nvfp4:
kv_cache_permute = nvfp4_kv_data
kv_cache_sf = nvfp4_kv_block_scales if self.is_kvcache_nvfp4 else None
# NVFP4 kernel only supports FP8 output.
# Use a pre-allocated FP8 buffer and dequantize afterwards.
needs_fp8_out = self.is_kvcache_nvfp4 and output.dtype != FP8_DTYPE
if needs_fp8_out:
out_decode = self._nvfp4_fp8_out[:num_decode_tokens]
else:
out_decode = output[:num_decode_tokens]
if use_dcp:
decode_query = get_dcp_group().all_gather(
decode_query.contiguous(), dim=-2
@@ -1630,6 +1712,7 @@ class FlashInferImpl(AttentionImpl):
out=output_tmp,
lse=lse,
return_lse=True,
kv_cache_sf=kv_cache_sf,
)
output[:num_decode_tokens] = self.dcp_combine(
output_tmp,
@@ -1642,8 +1725,12 @@ class FlashInferImpl(AttentionImpl):
kv_cache_permute,
k_scale=layer._k_scale_float,
v_scale=layer._v_scale_float,
out=output[:num_decode_tokens],
out=out_decode,
kv_cache_sf=kv_cache_sf,
)
if needs_fp8_out:
output[:num_decode_tokens].copy_(out_decode.to(output.dtype))
else:
# decode_query may be non-contiguous or have degenerate strides
assert isinstance(attn_metadata.decode, TRTLLMDecode)
@@ -1686,6 +1773,12 @@ class FlashInferImpl(AttentionImpl):
assert self.o_sf_scale is None
out = output[:num_decode_tokens]
# NVFP4 trtllm kernel only supports FP8 output.
# Use a pre-allocated FP8 buffer and dequantize afterwards.
needs_fp8_out = self.is_kvcache_nvfp4 and output.dtype != FP8_DTYPE
if needs_fp8_out:
out = self._nvfp4_fp8_out[:num_decode_tokens]
if num_decode_tokens % attn_metadata.num_decodes != 0:
# This gets triggered when the dummy_run forces
# attention to be initialized with q_len = 0
@@ -1695,9 +1788,9 @@ class FlashInferImpl(AttentionImpl):
trtllm_batch_decode_with_kv_cache(
query=decode_query,
kv_cache=nvfp4_kv_data
if self.is_kvcache_nvfp4
else kv_cache_permute,
kv_cache=(
nvfp4_kv_data if self.is_kvcache_nvfp4 else kv_cache_permute
),
workspace_buffer=workspace_buffer,
block_tables=block_tables_decode,
seq_lens=seq_lens_decode,
@@ -1709,7 +1802,13 @@ class FlashInferImpl(AttentionImpl):
o_sf_scale=self.o_sf_scale,
out=out,
q_len_per_req=q_len_per_req,
kv_cache_sf=(
nvfp4_kv_block_scales if self.is_kvcache_nvfp4 else None
),
)
if needs_fp8_out:
output[:num_decode_tokens].copy_(out.to(output.dtype))
return output_padded
def do_kv_cache_update(
+10
View File
@@ -151,6 +151,16 @@ class AttentionSpec(KVCacheSpec):
@property
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)
)
return (
2
* self.block_size