fused_qk_attention
turboquant_vllm.triton.fused_qk_attention ¶
Fused Triton kernel for TQ4 nibble-packed attention scores.
Computes Q @ compressed_K^T directly from nibble-packed 4-bit
indices without materializing decompressed key tensors. Reduces
per-layer memory traffic from ~25 MB to ~3 MB during decode.
Key math::
<q, R^T @ centroids[idx]> = <R @ q, centroids[idx]>
Pre-rotate the query once (q_rot = q @ Pi_T), then the kernel
does: score[s] = norm[s] * sum_d(q_rot[d] * centroids[idx[s,d]]) * scale
Based on the Dejan.ai TurboQuant Triton kernel, adapted for:
- Nibble-packed 4-bit indices (two per uint8 byte)
- fp32 norms (fp16 causes precision loss at 10K+ tokens)
- Configurable GQA (tested with 4:1 ratio for Molmo2)
Attributes:
| Name | Type | Description |
|---|---|---|
fused_qk_scores |
Tensor
|
Python wrapper that launches the Triton kernel. |
Examples:
scores = fused_qk_scores(
q_rotated, # [B, n_q_heads, q_len, head_dim]
packed_indices, # [B, n_kv_heads, kv_len, head_dim // 2] uint8
norms, # [B, n_kv_heads, kv_len] fp32
centroids, # [16] fp32 (for 4-bit)
scale=1 / 128**0.5,
n_q_heads=32,
n_kv_heads=8,
)
See Also
:mod:turboquant_vllm.kv_cache: CompressedDynamicCache that produces
the nibble-packed indices and fp32 norms consumed by this kernel.
Dejan.ai TurboQuant blog <https://dejan.ai/blog/turboquant/>_:
Original Triton kernel reference.
Functions¶
fused_qk_scores ¶
fused_qk_scores(
q_rotated: Tensor,
packed_indices: Tensor,
norms: Tensor,
centroids: Tensor,
scale: float,
*,
n_q_heads: int,
n_kv_heads: int,
) -> Tensor
Compute attention scores from pre-rotated queries and nibble-packed keys.
The query must be pre-rotated by the TurboQuant rotation matrix
(q_rot = q @ Pi_T) so the kernel avoids the expensive 128x128
rotation matmul in its inner loop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q_rotated
|
Tensor
|
Pre-rotated query, shape
|
required |
packed_indices
|
Tensor
|
Nibble-packed 4-bit key indices, shape
|
required |
norms
|
Tensor
|
Key vector norms, shape
|
required |
centroids
|
Tensor
|
Lloyd-Max centroid values, shape |
required |
scale
|
float
|
Attention scale factor (typically |
required |
n_q_heads
|
int
|
Number of query attention heads. |
required |
n_kv_heads
|
int
|
Number of key-value attention heads. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Attention scores, shape |
Source code in src/turboquant_vllm/triton/fused_qk_attention.py
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 | |