[Attention Backend] TurboQuant: 2-bit KV cache compression with 4x capacity (#38479)

Signed-off-by: vibhavagarwal5 <vibhavagarwal5@gmail.com>
Signed-off-by: Michael Goin <mgoin64@gmail.com>
Co-authored-by: Xinyu Chen <xinyu1.chen@intel.com>
Co-authored-by: Michael Goin <mgoin64@gmail.com>
This commit is contained in:
Vibhav Agarwal
2026-04-14 19:57:13 -07:00
committed by GitHub
co-authored by Xinyu Chen Michael Goin
parent 3bfe55a037
commit f4b42df048
27 changed files with 2963 additions and 3 deletions
@@ -0,0 +1,617 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Triton fused TurboQuant decode attention.
Decode path: Triton stage1 (split-KV tiled attention scoring + value
accumulation) + stage2 (log-sum-exp reduction across splits).
Supports FP8 (E4M3) keys, 3-bit and 4-bit uniform quantized values.
"""
import math
from typing import Any
import torch
from vllm.triton_utils import tl, triton
from vllm.v1.attention.ops.triton_decode_attention import (
_fwd_kernel_stage2,
)
_FP8_E4B15: dict[int, int] = {}
def _use_fp8_e4b15(device: int = 0) -> int:
"""Return 1 if device needs fp8e4b15 (Ampere/Ada, SM < 8.9), else 0."""
if device not in _FP8_E4B15:
cap = torch.cuda.get_device_capability(device)
_FP8_E4B15[device] = 1 if cap < (8, 9) else 0
return _FP8_E4B15[device]
# ---------------------------------------------------------------------------
# Stage 1: Fused TQ score + value accumulation (BLOCK_KV tiled)
# ---------------------------------------------------------------------------
@triton.jit
def _tq_decode_stage1(
# Precomputed query projection
Q_rot_ptr, # [B, Hq, D] float32
# Compressed KV cache (combined K+V)
KV_cache_ptr, # [num_blocks, block_size, Hk, padded_slot] uint8
# Block table and sequence info
Block_table_ptr, # [B, max_num_blocks] int32
Seq_lens_ptr, # [B] int32
# TQ parameters
Centroids_ptr, # [n_centroids] float32
# Output (intermediate for stage2)
Mid_o_ptr, # [B, Hq, NUM_KV_SPLITS, D+1] float32
# Strides
stride_qb,
stride_qh, # Q strides: [B, Hq, D]
stride_cache_block,
stride_cache_pos,
stride_cache_head, # KV cache
stride_bt_b, # block_table stride per batch
stride_mid_b,
stride_mid_h,
stride_mid_s, # mid_o strides
# Constexpr dims
NUM_KV_HEADS: tl.constexpr,
HEAD_DIM: tl.constexpr,
BLOCK_SIZE: tl.constexpr, # KV cache block_size (pages)
NUM_KV_SPLITS: tl.constexpr,
KV_GROUP_SIZE: tl.constexpr, # Hq // Hk
# TQ layout constants
MSE_BITS: tl.constexpr, # 3 or 4
MSE_BYTES: tl.constexpr, # ceil(D * mse_bits / 8)
KPS: tl.constexpr, # key_packed_size
VQB: tl.constexpr, # value_quant_bits (4 or 8=FP8)
VAL_DATA_BYTES: tl.constexpr, # ceil(D * vqb / 8) or D for FP8
# Score constants
ATTN_SCALE: tl.constexpr, # 1/sqrt(D)
# Block tile sizes
BLOCK_D: tl.constexpr, # next_power_of_2(HEAD_DIM)
BLOCK_KV: tl.constexpr, # tokens per tile (16)
KEY_FP8: tl.constexpr, # 1 if K is stored as FP8
NORM_CORRECTION: tl.constexpr = 0, # 1 = re-normalize centroids
FP8_E4B15: tl.constexpr = 0, # 1 = use e4b15 (Ampere/Ada), 0 = e4nv (Hopper+)
):
bid = tl.program_id(0) # batch index
hid = tl.program_id(1) # q_head index
sid = tl.program_id(2) # kv_split index
kv_head = hid // KV_GROUP_SIZE
# Sequence length for this batch
seq_len = tl.load(Seq_lens_ptr + bid)
# KV split range
split_len = tl.cdiv(seq_len, NUM_KV_SPLITS)
split_start = split_len * sid
split_end = tl.minimum(split_start + split_len, seq_len)
if split_start >= split_end:
return
# Dimension offsets
d_offs = tl.arange(0, BLOCK_D)
d_mask = d_offs < HEAD_DIM
kv_range = tl.arange(0, BLOCK_KV)
# Load query vector: q_rot — [BLOCK_D] float32
q_base = bid * stride_qb + hid * stride_qh
q_rot = tl.load(Q_rot_ptr + q_base + d_offs, mask=d_mask, other=0.0).to(tl.float32)
# Precompute byte/bit index vectors for MSE gather loads
if not KEY_FP8:
mse_bit_off = d_offs * MSE_BITS
mse_byte_idx = mse_bit_off // 8
mse_bit_shift = mse_bit_off % 8
mse_mask = (1 << MSE_BITS) - 1
# Precompute value bit/byte index vectors (loop-invariant)
if VQB == 3:
val_bit_off = d_offs * 3
val_byte_idx = val_bit_off // 8
val_bit_shift = val_bit_off % 8
# Online softmax accumulators
m_prev = -float("inf")
l_prev = 0.0
acc = tl.zeros([BLOCK_D], dtype=tl.float32)
bt_base = bid * stride_bt_b
# ================================================================
# TILED LOOP: process BLOCK_KV tokens per iteration
# ================================================================
for start_n in range(split_start, split_end, BLOCK_KV):
kv_offs = start_n + kv_range
kv_mask = kv_offs < split_end
page_idx = kv_offs // BLOCK_SIZE
page_off = kv_offs % BLOCK_SIZE
block_nums = tl.load(
Block_table_ptr + bt_base + page_idx,
mask=kv_mask,
other=0,
)
slot_bases = (
block_nums * stride_cache_block
+ page_off * stride_cache_pos
+ kv_head * stride_cache_head
)
# ============================================================
# COMPUTE ATTENTION SCORES: [BLOCK_KV]
# ============================================================
if KEY_FP8:
k_addrs = slot_bases[:, None] + d_offs[None, :]
k_raw = tl.load(
KV_cache_ptr + k_addrs,
mask=kv_mask[:, None] & d_mask[None, :],
other=0,
)
if FP8_E4B15:
k_float = k_raw.to(tl.float8e4b15, bitcast=True).to(tl.float32)
else:
k_float = k_raw.to(tl.float8e4nv, bitcast=True).to(tl.float32)
scores = (
tl.sum(
tl.where(d_mask[None, :], q_rot[None, :] * k_float, 0.0),
axis=1,
)
* ATTN_SCALE
)
scores = tl.where(kv_mask, scores, -float("inf"))
else:
# MSE unpack + norms
mse_addrs0 = slot_bases[:, None] + mse_byte_idx[None, :]
mse_raw0 = tl.load(
KV_cache_ptr + mse_addrs0,
mask=kv_mask[:, None] & d_mask[None, :],
other=0,
).to(tl.int32)
mse_raw1 = tl.load(
KV_cache_ptr + mse_addrs0 + 1,
mask=kv_mask[:, None] & d_mask[None, :],
other=0,
).to(tl.int32)
raw16 = mse_raw0 | (mse_raw1 << 8)
mse_idx = (raw16 >> mse_bit_shift[None, :]) & mse_mask
# Centroid gather + dot product
c_vals = tl.load(
Centroids_ptr + mse_idx,
mask=kv_mask[:, None] & d_mask[None, :],
other=0.0,
)
# Norm correction: re-normalize centroid vector to unit norm
if NORM_CORRECTION:
c_norm_sq = tl.sum(
tl.where(d_mask[None, :], c_vals * c_vals, 0.0),
axis=1,
)
c_inv_norm = 1.0 / tl.sqrt(c_norm_sq + 1e-16)
c_vals = c_vals * c_inv_norm[:, None]
term1 = tl.sum(
tl.where(d_mask[None, :], q_rot[None, :] * c_vals, 0.0),
axis=1,
)
# Load norms (fp16 -> fp32): norms are at MSE_BYTES offset
norm_bases = slot_bases + MSE_BYTES
n_lo = tl.load(KV_cache_ptr + norm_bases, mask=kv_mask, other=0).to(
tl.uint16
)
n_hi = tl.load(KV_cache_ptr + norm_bases + 1, mask=kv_mask, other=0).to(
tl.uint16
)
vec_norms = (n_lo | (n_hi << 8)).to(tl.float16, bitcast=True).to(tl.float32)
scores = vec_norms * term1 * ATTN_SCALE
scores = tl.where(kv_mask, scores, -float("inf"))
# ============================================================
# ONLINE SOFTMAX UPDATE (block-level)
# ============================================================
n_e_max = tl.maximum(tl.max(scores, 0), m_prev)
re_scale = tl.exp(m_prev - n_e_max)
p = tl.exp(scores - n_e_max)
# ============================================================
# VALUE LOAD + DEQUANTIZE: [BLOCK_KV, BLOCK_D]
# ============================================================
val_bases = slot_bases + KPS
if VQB == 3:
val_addrs0 = val_bases[:, None] + val_byte_idx[None, :]
val_raw0 = tl.load(
KV_cache_ptr + val_addrs0,
mask=kv_mask[:, None] & d_mask[None, :],
other=0,
).to(tl.int32)
val_raw1 = tl.load(
KV_cache_ptr + val_addrs0 + 1,
mask=kv_mask[:, None] & d_mask[None, :],
other=0,
).to(tl.int32)
raw16 = val_raw0 | (val_raw1 << 8)
v_idx = ((raw16 >> val_bit_shift[None, :]) & 0x7).to(tl.float32)
sc_bases = val_bases + VAL_DATA_BYTES
sc_lo = tl.load(KV_cache_ptr + sc_bases, mask=kv_mask, other=0).to(
tl.uint16
)
sc_hi = tl.load(KV_cache_ptr + sc_bases + 1, mask=kv_mask, other=0).to(
tl.uint16
)
v_scales = (
(sc_lo | (sc_hi << 8)).to(tl.float16, bitcast=True).to(tl.float32)
)
zr_lo = tl.load(KV_cache_ptr + sc_bases + 2, mask=kv_mask, other=0).to(
tl.uint16
)
zr_hi = tl.load(KV_cache_ptr + sc_bases + 3, mask=kv_mask, other=0).to(
tl.uint16
)
v_zeros = (zr_lo | (zr_hi << 8)).to(tl.float16, bitcast=True).to(tl.float32)
values = v_idx * v_scales[:, None] + v_zeros[:, None]
else: # VQB == 4
vb_idx = d_offs // 2
vb_shift = (d_offs % 2) * 4
val_addrs = val_bases[:, None] + vb_idx[None, :]
val_raw = tl.load(
KV_cache_ptr + val_addrs,
mask=kv_mask[:, None] & d_mask[None, :],
other=0,
).to(tl.int32)
v_idx = ((val_raw >> vb_shift[None, :]) & 0xF).to(tl.float32)
sc_bases = val_bases + VAL_DATA_BYTES
sc_lo = tl.load(KV_cache_ptr + sc_bases, mask=kv_mask, other=0).to(
tl.uint16
)
sc_hi = tl.load(KV_cache_ptr + sc_bases + 1, mask=kv_mask, other=0).to(
tl.uint16
)
v_scales = (
(sc_lo | (sc_hi << 8)).to(tl.float16, bitcast=True).to(tl.float32)
)
zr_lo = tl.load(KV_cache_ptr + sc_bases + 2, mask=kv_mask, other=0).to(
tl.uint16
)
zr_hi = tl.load(KV_cache_ptr + sc_bases + 3, mask=kv_mask, other=0).to(
tl.uint16
)
v_zeros = (zr_lo | (zr_hi << 8)).to(tl.float16, bitcast=True).to(tl.float32)
values = v_idx * v_scales[:, None] + v_zeros[:, None]
# ============================================================
# WEIGHTED VALUE ACCUMULATION
# ============================================================
acc = acc * re_scale + tl.sum(p[:, None] * values, 0)
l_prev = l_prev * re_scale + tl.sum(p, 0)
m_prev = n_e_max
# Store partial result
out_base = bid * stride_mid_b + hid * stride_mid_h + sid * stride_mid_s
safe_l = tl.where(l_prev > 0.0, l_prev, 1.0)
tl.store(Mid_o_ptr + out_base + d_offs, acc / safe_l, mask=d_mask)
lse = m_prev + tl.log(safe_l)
tl.store(Mid_o_ptr + out_base + HEAD_DIM, lse)
# ---------------------------------------------------------------------------
# Pre-dequant kernel: Bulk dequant K (MSE+norms) and V to fp16
# ---------------------------------------------------------------------------
@triton.jit
def _tq_full_dequant_kv(
KV_cache_ptr,
Block_table_ptr,
Centroids_ptr,
K_out_ptr, # [B, Hk, max_seq, D] float16
V_out_ptr, # [B, Hk, max_seq, D] float16
stride_ko_b,
stride_ko_h,
stride_ko_s,
stride_vo_b,
stride_vo_h,
stride_vo_s,
stride_cache_block,
stride_cache_pos,
stride_cache_head,
stride_bt_b,
HEAD_DIM: tl.constexpr,
BLOCK_SIZE: tl.constexpr,
NUM_KV_HEADS: tl.constexpr,
MSE_BYTES: tl.constexpr,
KPS: tl.constexpr,
VQB: tl.constexpr,
VAL_DATA_BYTES: tl.constexpr,
MSE_BITS: tl.constexpr,
KEY_FP8: tl.constexpr,
BLOCK_D: tl.constexpr,
NORM_CORRECTION: tl.constexpr = 0,
FP8_E4B15: tl.constexpr = 0, # 1 = use e4b15 (Ampere/Ada), 0 = e4nv (Hopper+)
):
"""Full dequant: reconstruct K (MSE centroids * norm or FP8) and V to fp16."""
pos = tl.program_id(0)
bh = tl.program_id(1)
bid = bh // NUM_KV_HEADS
hid = bh % NUM_KV_HEADS
page_idx = pos // BLOCK_SIZE
page_off = pos % BLOCK_SIZE
block_num = tl.load(Block_table_ptr + bid * stride_bt_b + page_idx)
slot_base = (
block_num * stride_cache_block
+ page_off * stride_cache_pos
+ hid * stride_cache_head
)
d_offs = tl.arange(0, BLOCK_D)
d_mask = d_offs < HEAD_DIM
# === K dequant ===
ko_base = bid * stride_ko_b + hid * stride_ko_h + pos * stride_ko_s
if KEY_FP8:
k_raw = tl.load(KV_cache_ptr + slot_base + d_offs, mask=d_mask, other=0)
if FP8_E4B15:
k_recon = k_raw.to(tl.float8e4b15, bitcast=True).to(tl.float32)
else:
k_recon = k_raw.to(tl.float8e4nv, bitcast=True).to(tl.float32)
tl.store(K_out_ptr + ko_base + d_offs, k_recon.to(tl.float16), mask=d_mask)
else:
# MSE unpack (3-bit or 4-bit) + norms
mse_bit_off = d_offs * MSE_BITS
mse_byte_idx = mse_bit_off // 8
mse_bit_shift = mse_bit_off % 8
mse_umask = (1 << MSE_BITS) - 1
mse_raw0 = tl.load(
KV_cache_ptr + slot_base + mse_byte_idx, mask=d_mask, other=0
).to(tl.int32)
mse_raw1 = tl.load(
KV_cache_ptr + slot_base + mse_byte_idx + 1, mask=d_mask, other=0
).to(tl.int32)
raw16_key = mse_raw0 | (mse_raw1 << 8)
mse_idx = (raw16_key >> mse_bit_shift) & mse_umask
k_mse = tl.load(Centroids_ptr + mse_idx, mask=d_mask, other=0.0)
# Norm correction: re-normalize centroid vector to unit norm
if NORM_CORRECTION:
c_norm_sq = tl.sum(tl.where(d_mask, k_mse * k_mse, 0.0), axis=0)
c_inv_norm = 1.0 / tl.sqrt(c_norm_sq + 1e-16)
k_mse = k_mse * c_inv_norm
# Norms at MSE_BYTES offset (no QJL bytes)
norm_base = slot_base + MSE_BYTES
n_lo = tl.load(KV_cache_ptr + norm_base).to(tl.uint16)
n_hi = tl.load(KV_cache_ptr + norm_base + 1).to(tl.uint16)
vec_norm = (n_lo | (n_hi << 8)).to(tl.float16, bitcast=True).to(tl.float32)
k_recon = vec_norm * k_mse
tl.store(K_out_ptr + ko_base + d_offs, k_recon.to(tl.float16), mask=d_mask)
# === V dequant ===
val_base = slot_base + KPS
if VQB == 4:
vb_idx = d_offs // 2
vb_shift = (d_offs % 2) * 4
val_raw = tl.load(KV_cache_ptr + val_base + vb_idx, mask=d_mask, other=0).to(
tl.int32
)
v_idx = ((val_raw >> vb_shift) & 0xF).to(tl.float32)
sc_base = val_base + VAL_DATA_BYTES
sc_lo = tl.load(KV_cache_ptr + sc_base).to(tl.uint16)
sc_hi = tl.load(KV_cache_ptr + sc_base + 1).to(tl.uint16)
v_scale = (sc_lo | (sc_hi << 8)).to(tl.float16, bitcast=True).to(tl.float32)
zr_lo = tl.load(KV_cache_ptr + sc_base + 2).to(tl.uint16)
zr_hi = tl.load(KV_cache_ptr + sc_base + 3).to(tl.uint16)
v_zero = (zr_lo | (zr_hi << 8)).to(tl.float16, bitcast=True).to(tl.float32)
v_vals = v_idx * v_scale + v_zero
elif VQB == 3:
# 3-bit value unpack: 8 values per 3 bytes
val_bit_off = d_offs * 3
val_byte_idx = val_bit_off // 8
val_bit_shift = val_bit_off % 8
val_raw0 = tl.load(
KV_cache_ptr + val_base + val_byte_idx, mask=d_mask, other=0
).to(tl.int32)
val_raw1 = tl.load(
KV_cache_ptr + val_base + val_byte_idx + 1, mask=d_mask, other=0
).to(tl.int32)
raw16_val = val_raw0 | (val_raw1 << 8)
v_idx = ((raw16_val >> val_bit_shift) & 0x7).to(tl.float32)
sc_base = val_base + VAL_DATA_BYTES
sc_lo = tl.load(KV_cache_ptr + sc_base).to(tl.uint16)
sc_hi = tl.load(KV_cache_ptr + sc_base + 1).to(tl.uint16)
v_scale = (sc_lo | (sc_hi << 8)).to(tl.float16, bitcast=True).to(tl.float32)
zr_lo = tl.load(KV_cache_ptr + sc_base + 2).to(tl.uint16)
zr_hi = tl.load(KV_cache_ptr + sc_base + 3).to(tl.uint16)
v_zero = (zr_lo | (zr_hi << 8)).to(tl.float16, bitcast=True).to(tl.float32)
v_vals = v_idx * v_scale + v_zero
else:
v_vals = tl.zeros([BLOCK_D], dtype=tl.float32)
vo_base = bid * stride_vo_b + hid * stride_vo_h + pos * stride_vo_s
tl.store(V_out_ptr + vo_base + d_offs, v_vals.to(tl.float16), mask=d_mask)
# ---------------------------------------------------------------------------
# Stage 2: Reuse from triton_decode_attention.py
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# Launcher — cached constants + fused GEMM
# ---------------------------------------------------------------------------
_layout_cache: dict = {}
def _get_layout(D, mse_bits, value_quant_bits, key_packed_size):
"""Get cached layout constants."""
key = (D, mse_bits, value_quant_bits, key_packed_size)
cfg = _layout_cache.get(key)
if cfg is None:
val_data_bytes = math.ceil(D * value_quant_bits / 8)
cfg = {
"mse_bytes": math.ceil(D * mse_bits / 8),
"val_data_bytes": val_data_bytes,
"mse_bits": mse_bits,
"n_centroids": 2**mse_bits,
"BLOCK_D": triton.next_power_of_2(D),
}
_layout_cache[key] = cfg
return cfg
def triton_turboquant_decode_attention(
query: torch.Tensor, # [B, Hq, D] — original query
kv_cache: torch.Tensor, # [num_blocks, block_size, Hk, padded_slot] uint8
block_table: torch.Tensor, # [B, max_num_blocks] int32
seq_lens: torch.Tensor, # [B] int32
Pi: torch.Tensor, # [D, D] float32
centroids: torch.Tensor, # [n_centroids] float32
scale: float,
mse_bits: int,
key_packed_size: int,
value_quant_bits: int,
key_fp8: bool = False,
norm_correction: bool = False,
PiT: torch.Tensor | None = None, # [D, D] pre-computed Pi.T contiguous
# Pre-allocated buffers (optional, avoids per-call allocation)
mid_o_buf: torch.Tensor | None = None,
output_buf: torch.Tensor | None = None,
lse_buf: torch.Tensor | None = None,
buf_holder: Any = None,
max_num_kv_splits: int = 32, # fixed split count (must be constant for cudagraph)
) -> torch.Tensor:
"""Launch fused TQ decode attention (Triton stage1 + stage2).
Returns: output tensor [B, Hq, D] in query's dtype.
"""
B, Hq, D = query.shape
Hk = kv_cache.shape[2]
block_size = kv_cache.shape[1]
kv_group_size = Hq // Hk
device = query.device
cfg = _get_layout(D, mse_bits, value_quant_bits, key_packed_size)
# Compute q_rot = q @ Pi.T (rotated query for MSE key scoring)
# FP8 path: pass query directly (float16); kernel casts inline.
# MSE path: still needs external GEMM (cuBLAS), so q_rot is float32.
if key_fp8:
q_rot = query.contiguous()
else:
q_float = query.float()
if PiT is None:
PiT = Pi.T.contiguous()
q_rot = (q_float @ PiT).contiguous()
NUM_KV_SPLITS = max_num_kv_splits
if (
mid_o_buf is not None
and mid_o_buf.shape[0] >= B
and mid_o_buf.shape[2] >= NUM_KV_SPLITS
):
mid_o = mid_o_buf[:B, :Hq, :NUM_KV_SPLITS, :]
else:
mid_o = torch.empty(
B,
Hq,
NUM_KV_SPLITS,
D + 1,
dtype=torch.float32,
device=device,
)
if buf_holder is not None:
buf_holder._tq_mid_o_buf = mid_o
# Stage 1: split-KV tiled attention scoring + value accumulation
fp8_e4b15 = _use_fp8_e4b15(device.index or 0)
BLOCK_KV = 4
grid = (B, Hq, NUM_KV_SPLITS)
_tq_decode_stage1[grid](
q_rot,
kv_cache,
block_table,
seq_lens,
centroids,
mid_o,
q_rot.stride(0),
q_rot.stride(1),
kv_cache.stride(0),
kv_cache.stride(1),
kv_cache.stride(2),
block_table.stride(0),
mid_o.stride(0),
mid_o.stride(1),
mid_o.stride(2),
NUM_KV_HEADS=Hk,
HEAD_DIM=D,
BLOCK_SIZE=block_size,
NUM_KV_SPLITS=NUM_KV_SPLITS,
KV_GROUP_SIZE=kv_group_size,
MSE_BITS=mse_bits,
MSE_BYTES=cfg["mse_bytes"],
KPS=key_packed_size,
VQB=value_quant_bits,
VAL_DATA_BYTES=cfg["val_data_bytes"],
ATTN_SCALE=scale,
BLOCK_D=cfg["BLOCK_D"],
BLOCK_KV=BLOCK_KV,
KEY_FP8=1 if key_fp8 else 0,
NORM_CORRECTION=1 if norm_correction else 0,
FP8_E4B15=fp8_e4b15,
num_warps=1,
num_stages=1,
)
# Stage 2: Reduce across KV splits
if output_buf is not None and output_buf.shape[0] >= B:
output = output_buf[:B, :Hq, :D]
else:
output = torch.empty(B, Hq, D, dtype=torch.float32, device=device)
if buf_holder is not None:
buf_holder._tq_output_buf = output
if lse_buf is not None and lse_buf.shape[0] >= B:
lse = lse_buf[:B, :Hq]
else:
lse = torch.empty(B, Hq, dtype=torch.float32, device=device)
if buf_holder is not None:
buf_holder._tq_lse_buf = lse
grid2 = (B, Hq)
_fwd_kernel_stage2[grid2](
mid_o,
output,
lse,
seq_lens,
mid_o.stride(0),
mid_o.stride(1),
mid_o.stride(2),
output.stride(0),
output.stride(1),
lse.stride(0),
NUM_KV_SPLITS=NUM_KV_SPLITS,
BLOCK_DV=cfg["BLOCK_D"],
Lv=D,
num_warps=4,
num_stages=2,
)
return output.to(query.dtype)
@@ -0,0 +1,441 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Fused Triton kernels for TurboQuant KV store.
Two kernels:
1. _tq_fused_store_fp8: FP8 key scatter + value uniform quantization.
2. _tq_fused_store_mse: Fused binary-search bucketize + MSE index
packing + value quantization.
The launcher `triton_turboquant_store` selects the appropriate kernel.
"""
import math
import torch
from vllm.triton_utils import tl, triton
from vllm.v1.attention.ops.triton_turboquant_decode import _use_fp8_e4b15
# ═══════════════════════════════════════════════════════════════════════
# Shared: value uniform quantization + pack + scale/zero store
# ═══════════════════════════════════════════════════════════════════════
@triton.jit
def _store_quantized_value(
Value_ptr,
KV_cache_ptr,
base, # pid * D offset into Value_ptr
slot_base, # byte offset into KV_cache_ptr for this slot+head
d_offs, # tl.arange(0, BLOCK_D)
d_mask, # d_offs < D
D: tl.constexpr,
KPS: tl.constexpr,
VQB: tl.constexpr,
VAL_DATA_BYTES: tl.constexpr,
BLOCK_D: tl.constexpr,
BLOCK_VAL: tl.constexpr,
BLOCK_GRP: tl.constexpr,
):
"""Uniform quantization of values to VQB bits, pack, and store with scale/zero."""
val_cache_offset = KPS
if VQB == 3:
val_vec = tl.load(Value_ptr + base + d_offs, mask=d_mask, other=0.0).to(
tl.float32
)
val_min = tl.min(tl.where(d_mask, val_vec, float("inf")), axis=0)
val_max = tl.max(tl.where(d_mask, val_vec, -float("inf")), axis=0)
v_scale = (val_max - val_min) / 7.0
v_scale = tl.where(v_scale > 1e-8, v_scale, 1e-8)
q_vals = tl.minimum(
tl.maximum(((val_vec - val_min) / v_scale + 0.5).to(tl.int32), 0), 7
)
grp_offs = tl.arange(0, BLOCK_GRP)
grp_mask = grp_offs < (D // 8)
q_grp = tl.reshape(q_vals, [BLOCK_GRP, 8])
shifts_3bit = tl.arange(0, 8) * 3
packed_24 = tl.sum(q_grp << shifts_3bit[None, :], axis=1)
b0 = (packed_24 & 0xFF).to(tl.uint8)
b1 = ((packed_24 >> 8) & 0xFF).to(tl.uint8)
b2 = ((packed_24 >> 16) & 0xFF).to(tl.uint8)
tl.store(
KV_cache_ptr + slot_base + val_cache_offset + grp_offs * 3,
b0,
mask=grp_mask,
)
tl.store(
KV_cache_ptr + slot_base + val_cache_offset + grp_offs * 3 + 1,
b1,
mask=grp_mask,
)
tl.store(
KV_cache_ptr + slot_base + val_cache_offset + grp_offs * 3 + 2,
b2,
mask=grp_mask,
)
sc_offset = val_cache_offset + VAL_DATA_BYTES
sc_f16 = v_scale.to(tl.float16)
sc_u16 = sc_f16.to(tl.uint16, bitcast=True)
tl.store(KV_cache_ptr + slot_base + sc_offset, (sc_u16 & 0xFF).to(tl.uint8))
tl.store(
KV_cache_ptr + slot_base + sc_offset + 1,
((sc_u16 >> 8) & 0xFF).to(tl.uint8),
)
zr_f16 = val_min.to(tl.float16)
zr_u16 = zr_f16.to(tl.uint16, bitcast=True)
tl.store(KV_cache_ptr + slot_base + sc_offset + 2, (zr_u16 & 0xFF).to(tl.uint8))
tl.store(
KV_cache_ptr + slot_base + sc_offset + 3,
((zr_u16 >> 8) & 0xFF).to(tl.uint8),
)
else: # VQB == 4
val_vec = tl.load(Value_ptr + base + d_offs, mask=d_mask, other=0.0).to(
tl.float32
)
val_min = tl.min(tl.where(d_mask, val_vec, float("inf")), axis=0)
val_max = tl.max(tl.where(d_mask, val_vec, -float("inf")), axis=0)
v_scale = (val_max - val_min) / 15.0
v_scale = tl.where(v_scale > 1e-8, v_scale, 1e-8)
# Quantize all D elements from register (no re-load)
q_all = tl.minimum(
tl.maximum(((val_vec - val_min) / v_scale + 0.5).to(tl.int32), 0), 15
)
# Reshape to pairs and pack two 4-bit values per byte
q_pairs = tl.reshape(q_all, [BLOCK_D // 2, 2])
shifts_4 = tl.arange(0, 2) * 4
packed_val = tl.sum((q_pairs & 0xF) << shifts_4[None, :], axis=1).to(tl.uint8)
val_offs = tl.arange(0, BLOCK_D // 2)
val_mask = val_offs < VAL_DATA_BYTES
tl.store(
KV_cache_ptr + slot_base + val_cache_offset + val_offs,
packed_val,
mask=val_mask,
)
sc_offset = val_cache_offset + VAL_DATA_BYTES
sc_f16 = v_scale.to(tl.float16)
sc_u16 = sc_f16.to(tl.uint16, bitcast=True)
tl.store(KV_cache_ptr + slot_base + sc_offset, (sc_u16 & 0xFF).to(tl.uint8))
tl.store(
KV_cache_ptr + slot_base + sc_offset + 1,
((sc_u16 >> 8) & 0xFF).to(tl.uint8),
)
zr_f16 = val_min.to(tl.float16)
zr_u16 = zr_f16.to(tl.uint16, bitcast=True)
tl.store(KV_cache_ptr + slot_base + sc_offset + 2, (zr_u16 & 0xFF).to(tl.uint8))
tl.store(
KV_cache_ptr + slot_base + sc_offset + 3,
((zr_u16 >> 8) & 0xFF).to(tl.uint8),
)
# ═══════════════════════════════════════════════════════════════════════
# FP8 key store + value uniform quantization
# ═══════════════════════════════════════════════════════════════════════
@triton.jit
def _tq_fused_store_fp8(
Key_ptr, # [NH, D] float16/bfloat16 — raw keys
Value_ptr, # [NH, D] float16/bfloat16 — raw values
KV_cache_ptr, # [total_bytes] uint8 (flattened view)
Slot_mapping_ptr, # [N] int32 — per-token slot indices
# Cache strides (for computing byte offsets)
stride_cache_block: tl.constexpr,
stride_cache_pos: tl.constexpr,
stride_cache_head: tl.constexpr,
# Dimensions
D: tl.constexpr,
H: tl.constexpr,
BLOCK_SIZE: tl.constexpr,
BLOCK_D: tl.constexpr,
# TQ layout
KPS: tl.constexpr,
# Value quantization
VQB: tl.constexpr,
VAL_DATA_BYTES: tl.constexpr,
# Packing block sizes
BLOCK_VAL: tl.constexpr,
BLOCK_GRP: tl.constexpr = 16,
FP8_E4B15: tl.constexpr = 0, # 1 = e4b15 (Ampere/Ada), 0 = e4nv (Hopper+)
):
"""FP8 key cast+scatter + value uniform quantization."""
pid = tl.program_id(0)
token_idx = pid // H
head_idx = pid % H
slot = tl.load(Slot_mapping_ptr + token_idx)
if slot < 0:
return
blk = slot // BLOCK_SIZE
off = slot % BLOCK_SIZE
slot_base = (
blk * stride_cache_block + off * stride_cache_pos + head_idx * stride_cache_head
)
base = pid * D
# ── FP8 KEY: cast to FP8 in-kernel and store ─────────────────
d_offs = tl.arange(0, BLOCK_D)
d_mask = d_offs < D
k_vals = tl.load(Key_ptr + base + d_offs, mask=d_mask, other=0.0)
k_fp8 = k_vals.to(tl.float8e4b15) if FP8_E4B15 else k_vals.to(tl.float8e4nv)
k_bytes = k_fp8.to(tl.uint8, bitcast=True)
tl.store(KV_cache_ptr + slot_base + d_offs, k_bytes, mask=d_mask)
# ── VALUE QUANTIZE + PACK ───────────────────────────────────────
_store_quantized_value(
Value_ptr,
KV_cache_ptr,
base,
slot_base,
d_offs,
d_mask,
D=D,
KPS=KPS,
VQB=VQB,
VAL_DATA_BYTES=VAL_DATA_BYTES,
BLOCK_D=BLOCK_D,
BLOCK_VAL=BLOCK_VAL,
BLOCK_GRP=BLOCK_GRP,
)
# ═══════════════════════════════════════════════════════════════════════
# Fused MSE store: bucketize + MSE index pack + norm store + value pack
# (eliminates 4 PyTorch kernel launches per layer vs pack-only kernel)
# ═══════════════════════════════════════════════════════════════════════
@triton.jit
def _tq_fused_store_mse(
# Post-rotation inputs
Y_ptr, # [NH, D] float32 — rotated normalized keys (x_hat @ PiT)
Norms_ptr, # [NH] float32 — key vector norms (||k||)
Value_ptr, # [NH, D] float32 — raw values
# Quantization tables
Midpoints_ptr, # [n_centroids-1] float32
# Cache and indexing
KV_cache_ptr, # [total_bytes] uint8 (flattened view)
Slot_mapping_ptr, # [N] int32 — per-token slot indices
# Cache strides
stride_cache_block: tl.constexpr,
stride_cache_pos: tl.constexpr,
stride_cache_head: tl.constexpr,
# Dimensions
D: tl.constexpr,
H: tl.constexpr,
BLOCK_SIZE: tl.constexpr,
BLOCK_D: tl.constexpr,
# TQ layout
MSE_BYTES: tl.constexpr,
KPS: tl.constexpr,
# Value quantization
VQB: tl.constexpr,
VAL_DATA_BYTES: tl.constexpr,
# Packing block sizes
BLOCK_VAL: tl.constexpr,
# MSE params
MSE_BITS: tl.constexpr,
N_CENTROIDS: tl.constexpr,
BLOCK_GRP: tl.constexpr = 16,
):
"""Fused MSE quantize + pack + store.
Performs binary-search bucketize, MSE index packing, norm storage,
and value quantization in one kernel.
"""
pid = tl.program_id(0)
token_idx = pid // H
head_idx = pid % H
slot = tl.load(Slot_mapping_ptr + token_idx)
if slot < 0:
return
blk = slot // BLOCK_SIZE
off = slot % BLOCK_SIZE
slot_base = (
blk * stride_cache_block + off * stride_cache_pos + head_idx * stride_cache_head
)
base = pid * D
d_offs = tl.arange(0, BLOCK_D)
d_mask = d_offs < D
# ── 1. BINARY SEARCH BUCKETIZE ───────────────────────────────────
# Midpoints are sorted (N_CENTROIDS-1 values); binary search finds
# insertion point in MSE_BITS iterations vs N_CENTROIDS-1 for linear.
y_vec = tl.load(Y_ptr + base + d_offs, mask=d_mask, other=0.0)
lo = tl.zeros([BLOCK_D], dtype=tl.int32)
hi = tl.full([BLOCK_D], N_CENTROIDS - 1, dtype=tl.int32)
for _ in range(MSE_BITS):
mid = (lo + hi) >> 1
# Clamp to valid midpoint index [0, N_CENTROIDS-2] for load safety;
# the search result (lo) is still correct since converged lanes
# don't change.
safe_mid = tl.minimum(mid, N_CENTROIDS - 2)
mid_val = tl.load(Midpoints_ptr + safe_mid, mask=d_mask, other=0.0)
lo = tl.where(y_vec >= mid_val, mid + 1, lo)
hi = tl.where(y_vec >= mid_val, hi, mid)
idx = tl.minimum(lo, N_CENTROIDS - 1)
# ── 2. PACK MSE INDICES from register idx ─────────────────────────
if MSE_BITS == 4:
idx_pairs = tl.reshape(idx, [BLOCK_D // 2, 2])
shifts_4 = tl.arange(0, 2) * 4
packed = tl.sum((idx_pairs & 0xF) << shifts_4[None, :], axis=1).to(tl.uint8)
mse_offs = tl.arange(0, BLOCK_D // 2)
mse_mask = mse_offs < MSE_BYTES
tl.store(KV_cache_ptr + slot_base + mse_offs, packed, mask=mse_mask)
elif MSE_BITS == 3:
grp_offs = tl.arange(0, BLOCK_GRP)
grp_mask = grp_offs < (D // 8)
idx_grp = tl.reshape(idx, [BLOCK_GRP, 8])
shifts_3 = tl.arange(0, 8) * 3
packed_24 = tl.sum((idx_grp & 0x7) << shifts_3[None, :], axis=1)
b0 = (packed_24 & 0xFF).to(tl.uint8)
b1 = ((packed_24 >> 8) & 0xFF).to(tl.uint8)
b2 = ((packed_24 >> 16) & 0xFF).to(tl.uint8)
tl.store(KV_cache_ptr + slot_base + grp_offs * 3, b0, mask=grp_mask)
tl.store(KV_cache_ptr + slot_base + grp_offs * 3 + 1, b1, mask=grp_mask)
tl.store(KV_cache_ptr + slot_base + grp_offs * 3 + 2, b2, mask=grp_mask)
# ── 3. STORE vec_norm (fp16, 2 bytes) ─────────────────────────────
norm_offset = MSE_BYTES
vn_f16 = tl.load(Norms_ptr + pid).to(tl.float16)
vn_u16 = vn_f16.to(tl.uint16, bitcast=True)
tl.store(KV_cache_ptr + slot_base + norm_offset, (vn_u16 & 0xFF).to(tl.uint8))
tl.store(
KV_cache_ptr + slot_base + norm_offset + 1, ((vn_u16 >> 8) & 0xFF).to(tl.uint8)
)
# ── 4. VALUE QUANTIZE + PACK ──────────────────────────────────────
_store_quantized_value(
Value_ptr,
KV_cache_ptr,
base,
slot_base,
d_offs,
d_mask,
D=D,
KPS=KPS,
VQB=VQB,
VAL_DATA_BYTES=VAL_DATA_BYTES,
BLOCK_D=BLOCK_D,
BLOCK_VAL=BLOCK_VAL,
BLOCK_GRP=BLOCK_GRP,
)
# ═══════════════════════════════════════════════════════════════════════
# Launcher
# ═══════════════════════════════════════════════════════════════════════
def triton_turboquant_store(
key: torch.Tensor, # [N, H, D] — raw keys (post-RoPE)
value: torch.Tensor, # [N, H, D] — raw values
kv_cache: torch.Tensor, # [num_blocks, block_size, Hk, padded_slot] uint8
slot_mapping: torch.Tensor, # [N] int32
PiT: torch.Tensor, # [D, D] float32
midpoints: torch.Tensor, # [n_centroids-1] float32
mse_bits: int,
key_packed_size: int,
value_quant_bits: int,
key_fp8: bool = False,
):
"""Launch TQ store kernel (FP8 or MSE path)."""
N, H, D = key.shape
NH = N * H
block_size = kv_cache.shape[1]
BLOCK_D = triton.next_power_of_2(D)
mse_bytes = math.ceil(D * mse_bits / 8)
n_centroids = 2**mse_bits
val_data_bytes = math.ceil(D * value_quant_bits / 8)
BLOCK_VAL = triton.next_power_of_2(val_data_bytes)
# Cache strides (element_size=1 for uint8, so stride in bytes = stride())
stride_block = kv_cache.stride(0)
stride_pos = kv_cache.stride(1)
stride_head = kv_cache.stride(2)
block_grp = triton.next_power_of_2(D // 8) if D >= 8 else 1
# ── FP8 PATH: in-kernel FP8 cast + scatter via fp8 kernel ──
if key_fp8:
k_flat = key.reshape(NH, D).contiguous()
v_flat = value.reshape(NH, D).contiguous()
fp8_e4b15 = _use_fp8_e4b15(key.device.index or 0)
grid = (NH,)
_tq_fused_store_fp8[grid](
k_flat,
v_flat,
kv_cache.view(-1),
slot_mapping,
stride_cache_block=stride_block,
stride_cache_pos=stride_pos,
stride_cache_head=stride_head,
D=D,
H=H,
BLOCK_SIZE=block_size,
BLOCK_D=BLOCK_D,
KPS=key_packed_size,
VQB=value_quant_bits,
VAL_DATA_BYTES=val_data_bytes,
BLOCK_VAL=BLOCK_VAL,
BLOCK_GRP=block_grp,
FP8_E4B15=fp8_e4b15,
num_warps=4,
num_stages=1,
)
return
# ── MSE PATH: external GEMM + fused bucketize/pack kernel ──
# Normalize + rotation GEMM externally (cuBLAS is faster than in-kernel)
k_flat = key.float().reshape(NH, D)
norms = k_flat.norm(dim=1, keepdim=True)
x_hat = k_flat / (norms + 1e-8)
y = x_hat @ PiT
v_flat = value.float().reshape(NH, D)
# Fused kernel: bucketize + MSE index pack + norm store + value pack
grid = (NH,)
_tq_fused_store_mse[grid](
y,
norms.squeeze(1),
v_flat,
midpoints,
kv_cache.view(-1),
slot_mapping,
stride_cache_block=stride_block,
stride_cache_pos=stride_pos,
stride_cache_head=stride_head,
D=D,
H=H,
BLOCK_SIZE=block_size,
BLOCK_D=BLOCK_D,
MSE_BYTES=mse_bytes,
KPS=key_packed_size,
VQB=value_quant_bits,
VAL_DATA_BYTES=val_data_bytes,
BLOCK_VAL=BLOCK_VAL,
MSE_BITS=mse_bits,
N_CENTROIDS=n_centroids,
BLOCK_GRP=block_grp,
num_warps=4,
num_stages=1,
)