Add nvfp4 support to reshape_and_cache_flash (#37332)
Signed-off-by: Shiyang Chen <shiychen@nvidia.com>
This commit is contained in:
@@ -42,7 +42,12 @@ from vllm.utils.flashinfer import (
|
||||
)
|
||||
from vllm.utils.math_utils import cdiv
|
||||
from vllm.utils.platform_utils import is_pin_memory_available
|
||||
from vllm.utils.torch_utils import is_quantized_kv_cache, is_strictly_contiguous
|
||||
from vllm.utils.torch_utils import (
|
||||
is_quantized_kv_cache,
|
||||
is_strictly_contiguous,
|
||||
nvfp4_kv_cache_full_dim,
|
||||
nvfp4_kv_cache_split_views,
|
||||
)
|
||||
from vllm.v1.attention.backend import (
|
||||
AttentionBackend,
|
||||
AttentionCGSupport,
|
||||
@@ -355,6 +360,10 @@ class FlashInferBackend(AttentionBackend):
|
||||
head_size: int,
|
||||
cache_dtype_str: str = "auto",
|
||||
) -> tuple[int, ...]:
|
||||
if cache_dtype_str == "nvfp4":
|
||||
# Packed layout: fp4 data + fp8 block scales in last dim
|
||||
last_dim = nvfp4_kv_cache_full_dim(head_size)
|
||||
return (num_blocks, 2, block_size, num_kv_heads, last_dim)
|
||||
return (num_blocks, 2, block_size, num_kv_heads, head_size)
|
||||
|
||||
@staticmethod
|
||||
@@ -608,11 +617,19 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
|
||||
self.cache_dtype = self.cache_config.cache_dtype
|
||||
# Cannot use self.kv_cache_spec.dtype here because kv_cache_spec
|
||||
# storage dtype may not be the same as the op dtype (uint8 vs fp8_e4m3)
|
||||
self.kv_cache_dtype = FlashInferBackend.get_fp8_dtype_for_flashinfer(
|
||||
self.cache_dtype
|
||||
)
|
||||
self.is_kvcache_nvfp4 = self.cache_dtype == "nvfp4"
|
||||
if self.is_kvcache_nvfp4:
|
||||
# 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.cache_dtype
|
||||
)
|
||||
else:
|
||||
self.cache_dtype = "auto"
|
||||
self.is_kvcache_nvfp4 = False
|
||||
assert self.kv_cache_spec.dtype == self.model_config.dtype
|
||||
self.kv_cache_dtype = self.kv_cache_spec.dtype
|
||||
|
||||
@@ -626,7 +643,13 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
|
||||
can_use_trtllm
|
||||
and not vllm_config.attention_config.disable_flashinfer_q_quantization
|
||||
):
|
||||
self.q_data_type = self.kv_cache_dtype
|
||||
if self.is_kvcache_nvfp4:
|
||||
# NVFP4 KV cache uses FP8 quantized queries
|
||||
self.q_data_type = FlashInferBackend.get_fp8_dtype_for_flashinfer(
|
||||
"fp8_e4m3"
|
||||
)
|
||||
else:
|
||||
self.q_data_type = self.kv_cache_dtype
|
||||
else:
|
||||
self.q_data_type = self.model_config.dtype
|
||||
|
||||
@@ -1228,6 +1251,8 @@ class FlashInferImpl(AttentionImpl):
|
||||
self.sliding_window[0] if self.sliding_window is not None else -1
|
||||
)
|
||||
self.kv_cache_dtype = kv_cache_dtype
|
||||
self.is_kvcache_nvfp4 = kv_cache_dtype == "nvfp4"
|
||||
self.fp4_data_dim = head_size // 2 if self.is_kvcache_nvfp4 else 0
|
||||
self.logits_soft_cap = logits_soft_cap
|
||||
self.kv_sharing_target_layer_name = kv_sharing_target_layer_name
|
||||
|
||||
@@ -1406,7 +1431,16 @@ class FlashInferImpl(AttentionImpl):
|
||||
num_prefill_tokens = attn_metadata.num_prefill_tokens
|
||||
|
||||
stride_order = FlashInferBackend.get_kv_cache_stride_order()
|
||||
kv_cache_permute = kv_cache.permute(*stride_order)
|
||||
kv_cache_permute = kv_cache.permute(*stride_order) # HND and contiguous
|
||||
|
||||
# For NVFP4, the kv_cache last dim is full_dim (data + scale packed).
|
||||
# Split into correctly-strided data and scale views.
|
||||
nvfp4_kv_data = None
|
||||
nvfp4_kv_block_scales = None
|
||||
if self.is_kvcache_nvfp4:
|
||||
nvfp4_kv_data, nvfp4_kv_block_scales = nvfp4_kv_cache_split_views(
|
||||
kv_cache_permute
|
||||
)
|
||||
|
||||
use_dcp = self.dcp_world_size > 1
|
||||
|
||||
@@ -1490,8 +1524,20 @@ class FlashInferImpl(AttentionImpl):
|
||||
assert self.o_sf_scale is None
|
||||
out = output[num_decode_tokens:]
|
||||
|
||||
if attn_metadata.q_data_type != FP8_DTYPE and is_quantized_kv_cache(
|
||||
self.kv_cache_dtype
|
||||
prefill_kv_block_scales = None
|
||||
if self.is_kvcache_nvfp4:
|
||||
# NVFP4 trtllm-gen kernel requires FP8 query.
|
||||
assert attn_metadata.q_data_type == FP8_DTYPE, (
|
||||
"NVFP4 KV cache requires FP8 quantized queries for "
|
||||
"trtllm-gen prefill. Set "
|
||||
"disable_flashinfer_q_quantization=False."
|
||||
)
|
||||
mock_kv_cache = nvfp4_kv_data
|
||||
mock_block_table = block_tables_prefill
|
||||
prefill_kv_block_scales = nvfp4_kv_block_scales # noqa: F841
|
||||
elif (
|
||||
attn_metadata.q_data_type != FP8_DTYPE
|
||||
and self.kv_cache_dtype.startswith("fp8")
|
||||
):
|
||||
# TRTLLM prefill attention does not support BF16 Q
|
||||
# and fp8 kv cache. So to enable prefill attention
|
||||
@@ -1636,7 +1682,9 @@ class FlashInferImpl(AttentionImpl):
|
||||
|
||||
trtllm_batch_decode_with_kv_cache(
|
||||
query=decode_query,
|
||||
kv_cache=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,
|
||||
@@ -1667,11 +1715,13 @@ class FlashInferImpl(AttentionImpl):
|
||||
# and value[:num_actual_tokens] because the reshape_and_cache_flash
|
||||
# op uses the slot_mapping's shape to determine the number of
|
||||
# actual tokens.
|
||||
k_cache = kv_cache[:, 0]
|
||||
v_cache = kv_cache[:, 1]
|
||||
torch.ops._C_cache_ops.reshape_and_cache_flash(
|
||||
key,
|
||||
value,
|
||||
kv_cache[:, 0],
|
||||
kv_cache[:, 1],
|
||||
k_cache,
|
||||
v_cache,
|
||||
slot_mapping,
|
||||
self.kv_cache_dtype,
|
||||
layer._k_scale,
|
||||
|
||||
@@ -17,7 +17,7 @@ from vllm.logger import init_logger
|
||||
if TYPE_CHECKING:
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.utils.math_utils import cdiv
|
||||
from vllm.utils.torch_utils import get_dtype_size
|
||||
from vllm.utils.torch_utils import get_dtype_size, nvfp4_kv_cache_full_dim
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
@@ -38,11 +38,20 @@ 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
|
||||
|
||||
@property
|
||||
def is_per_token_head(self) -> bool:
|
||||
"""True for any per-token-head quantization mode."""
|
||||
return self >= 2
|
||||
return self in (
|
||||
KVQuantMode.INT8_PER_TOKEN_HEAD,
|
||||
KVQuantMode.FP8_PER_TOKEN_HEAD,
|
||||
)
|
||||
|
||||
@property
|
||||
def is_nvfp4(self) -> bool:
|
||||
"""True for NVFP4 packed quantization mode."""
|
||||
return self == KVQuantMode.NVFP4
|
||||
|
||||
|
||||
def get_kv_quant_mode(kv_cache_dtype: str) -> KVQuantMode:
|
||||
@@ -51,7 +60,9 @@ def get_kv_quant_mode(kv_cache_dtype: str) -> KVQuantMode:
|
||||
return KVQuantMode.INT8_PER_TOKEN_HEAD
|
||||
if kv_cache_dtype == "fp8_per_token_head":
|
||||
return KVQuantMode.FP8_PER_TOKEN_HEAD
|
||||
if kv_cache_dtype.startswith("fp8"):
|
||||
if kv_cache_dtype == "nvfp4":
|
||||
return KVQuantMode.NVFP4
|
||||
if isinstance(kv_cache_dtype, str) and kv_cache_dtype.startswith("fp8"):
|
||||
return KVQuantMode.FP8_PER_TENSOR
|
||||
return KVQuantMode.NONE
|
||||
|
||||
@@ -237,6 +248,19 @@ class FullAttentionSpec(AttentionSpec):
|
||||
|
||||
@property
|
||||
def real_page_size_bytes(self) -> int:
|
||||
if self.kv_quant_mode.is_nvfp4:
|
||||
# Packed layout per head: fp4 data + fp8 block scales.
|
||||
# fp4 data: head_size//2 bytes (2 fp4 values per byte)
|
||||
# fp8 block scale: head_size//16 bytes (1 scale per 16 elements)
|
||||
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)
|
||||
)
|
||||
return (
|
||||
self.block_size
|
||||
* self.num_kv_heads
|
||||
|
||||
Reference in New Issue
Block a user