# Pooled indexer key cache update (`dsa_pooled_index_cache_update`) | ServingStudio Kernel Library

Stash each decode/verify token's index key in its request's tail ring and compress every pool it completes into the paged FP8 index cache.

A pooled DSA indexer caches one key per pool_size consecutive tokens. During decode and speculative verify, one program per request walks its next_n new tokens in position order. Every token's BF16 key and gate score go into the request's tail ring; a token that closes a pool first combines the pool's keys with a per-element softmax over gate score plus a learned per-slot bias, rotates the result with a 128-point Hadamard transform and stores it as FP8 with one power-of-two scale in a page-planar cache page. Request r's first new token sits at pool phase pool_size - 1 - (r mod pool_size), so request 0 always completes a pool and the requests cover every phase.

Category: Attention; group: DSA. Interactive page: https://servingstudio.cs.washington.edu/kernels.html?kind=dsa_pooled_index_cache_update. All kernel kinds: https://servingstudio.cs.washington.edu/kernels.md.

## Formula

- `pooled = Σ_slot softmax_slot(score + ape) · key; cache = FP8(H128 · pooled / s), s = 2^ceil(log2(max|H128 · pooled| / 448))`
- `C = completed pools; R = num_requests · next_n`
- `B = R · 8 · index_dim (BF16 key + score in, and into the ring) + C · (pool_size − 1) · 4 · index_dim (ring reads) + C · (index_dim + 4) + R · 12`
- `GB/s = B / time`

## How it is measured

GPU kernel time from CUPTI activity records, averaged over repeated launches in one capture. The L2 cache is flushed before each launch, so the numbers are cold-cache times. The call is one Triton launch, _kpool_decode_update_batched_kernel; operand construction and the check against the PyTorch reference run before timing.

## Caveats

- Time is set by the longest program, so it follows next_n and the pool phase; with next_n \< pool_size the rows assume a request that completes a pool in this step (one in pool_size steps for a lone request).
- On SM100-family GPUs the scale is stored as four equal UE8M0 bytes, elsewhere as an FP32; the device picks it, so it is not a key field.
- GB/s counts logical key, score, ring, cache and index bytes, not physical transactions.

## Arguments

| Argument | Type | Unit | Meaning |
| --- | --- | --- | --- |
| `num_requests` | number | requests | Requests decoded together. |
| `next_n` | number | tokens | New tokens per request in this step. |
| `pool_size` | number | tokens | Tokens compressed into one cached index key. |
| `tail_ring` | number | tokens | Slots in each request's raw-token tail ring. |
| `index_dim` | number | elements | Elements in each index key. |
| `block_size` | number | pools | Pooled keys stored in each cache page. |
| `input_dtype` | dtype |  | Element type of the new keys, gate scores and tail ring. |
| `cache_dtype` | dtype |  | Element type of the cached pooled keys. |

## Metrics

- Time (`time_ms`, ms)
- Throughput (`tflops`, TFLOPS)
- Memory bandwidth (`memory_bandwidth_gbps`, GB/s)
- Energy (`energy_j`, J)

## Backends

- `vllm_fork_triton`: The vLLM fork's kpool_decode_update_and_maybe_write_cache_batched: one Triton program per request over its next_n tokens. dtypes `bf16`, KV dtypes `fp8_e4m3`, compute capability 8.9 or newer, GPUs H100-SXM5-80GB, H100-PCIe-80GB, H200-SXM-141GB, B200-SXM-180GB, B300-SXM-288GB, GB200-Superchip, H800-SXM5-80GB, H20-SXM-96GB, L40, L40S, L4.

## Measured rows

52 rows in all.

| GPU | Backend | Precision | Rows |
| --- | --- | --- | --- |
| NVIDIA B200 | `vllm_fork_triton` | `bf16` | 52 |

## Used by these deployments

- [GLM-5.3-Flash NVFP4: ServingStudio design: DP attention, KDA TP groups, fused EP MoE, DFlash speculative decoding](https://servingstudio.cs.washington.edu/models/GLM-5.3-Flash-NVFP4/glm53_flash_nvfp4_dp_attn_kda_tp_fused_ep_moe_dflash2.md) (`GLM-5.3-Flash-NVFP4/glm53_flash_nvfp4_dp_attn_kda_tp_fused_ep_moe_dflash2`)
- [GLM-5.3-Flash NVFP4: vLLM, DP attention, EP MoE](https://servingstudio.cs.washington.edu/models/GLM-5.3-Flash-NVFP4/glm53_flash_vllm_nvfp4_dp_attn_ep_moe.md) (`GLM-5.3-Flash-NVFP4/glm53_flash_vllm_nvfp4_dp_attn_ep_moe`)
- [GLM-5.3-Flash NVFP4: vLLM, DP attention, EP MoE, DFlash speculative decoding](https://servingstudio.cs.washington.edu/models/GLM-5.3-Flash-NVFP4/glm53_flash_vllm_nvfp4_dp_attn_ep_moe_dflash2.md) (`GLM-5.3-Flash-NVFP4/glm53_flash_vllm_nvfp4_dp_attn_ep_moe_dflash2`)
- [GLM-5.3-Flash NVFP4: vLLM, TP attention, EP or TP MoE](https://servingstudio.cs.washington.edu/models/GLM-5.3-Flash-NVFP4/glm53_flash_vllm_nvfp4_kda_dsa_moe.md) (`GLM-5.3-Flash-NVFP4/glm53_flash_vllm_nvfp4_kda_dsa_moe`)
- [GLM-5.3-Flash NVFP4: vLLM, PP](https://servingstudio.cs.washington.edu/models/GLM-5.3-Flash-NVFP4/glm53_flash_vllm_nvfp4_pp_kda_dsa_moe.md) (`GLM-5.3-Flash-NVFP4/glm53_flash_vllm_nvfp4_pp_kda_dsa_moe`)
- [GLM-5.3-Flash: vLLM, DP attention, EP MoE](https://servingstudio.cs.washington.edu/models/GLM-5.3-Flash/glm53_flash_vllm_fp8_dp_attn_ep_moe.md) (`GLM-5.3-Flash/glm53_flash_vllm_fp8_dp_attn_ep_moe`)
- [GLM-5.3-Flash: vLLM, TP attention, EP or TP MoE](https://servingstudio.cs.washington.edu/models/GLM-5.3-Flash/glm53_flash_vllm_fp8_kda_dsa_moe.md) (`GLM-5.3-Flash/glm53_flash_vllm_fp8_kda_dsa_moe`)
- [GLM-5.3-Flash: vLLM, PP](https://servingstudio.cs.washington.edu/models/GLM-5.3-Flash/glm53_flash_vllm_fp8_pp_kda_dsa_moe.md) (`GLM-5.3-Flash/glm53_flash_vllm_fp8_pp_kda_dsa_moe`)

## API

- This kind: https://servingstudio.cs.washington.edu/api/public/v1/kernels/dsa_pooled_index_cache_update
- Measured rows: https://servingstudio.cs.washington.edu/api/public/v1/kernels/dsa_pooled_index_cache_update/rows (filter by any column, such as `?gpu=NVIDIA%20H200`; `format=csv` for CSV)
- Configs the public deployments ask of it: https://servingstudio.cs.washington.edu/api/public/v1/kernels/dsa_pooled_index_cache_update/configs

## Torch reference

What the kind computes, as Torch code (`profiling/runners/attention/dsa_pooled_index_cache_update_reference.py` in ServingStudio Sim):

```python
"""Torch semantics for the pooled index-key decode/verify cache update.

Source: the vLLM fork's
``vllm.models.glm5next.nvidia.ops.kpool_compress.kpool_decode_update_and_maybe_write_cache_batched``
(fork 5629b2614). Each request feeds ``next_n`` new tokens in position order.
Every token is stashed (raw key and gate score, BF16) in its request's tail
ring; a token whose position closes a pool (``pos % pool_size == pool_size - 1``)
and whose pool slot is mapped first compresses the pool: a per-dimension
softmax over ``score + ape`` weights the pool's keys, the BF16-rounded sum is
rotated by the orthonormal Hadamard-128 and quantized to FP8 with one
power-of-two scale per pooled key, written into the page-planar index cache.

This is written independently of the Triton kernel, from the operation's
definition (Sylvester Hadamard matrix, explicit softmax), and is used only to
check the production callable outside timing. Requests are independent, so
the reference runs them together and steps through the ``next_n`` tokens in
order, which is the ordering the operation requires.
"""

from __future__ import annotations

import functools

import torch

_FP8_E4M3_MAX = 448.0
_AMAX_FLOOR = 1e-4


def hadamard_matrix(n: int, *, device: torch.device | str = "cpu") -> torch.Tensor:
    """Orthonormal Sylvester Hadamard matrix of order ``n`` (a power of two), FP32."""
    return _hadamard_matrix(n, str(device))


@functools.lru_cache(maxsize=8)
def _hadamard_matrix(n: int, device: str) -> torch.Tensor:
    if n <= 0 or n & (n - 1):
        raise ValueError(f"Hadamard order must be a power of two, got {n}")
    h = torch.ones((1, 1), dtype=torch.float32, device=device)
    base = torch.tensor([[1.0, 1.0], [1.0, -1.0]], dtype=torch.float32, device=device)
    while h.shape[0] < n:
        h = torch.kron(h, base)
    return h / (n**0.5)


def compress_pool(
    keys: torch.Tensor, scores: torch.Tensor, ape: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor]:
    """Compress pools ``[..., pool_size, dim]`` into fp32 values ``[..., dim]`` and scales."""
    logits = scores.float() + ape.float()
    weights = torch.softmax(logits, dim=-2)
    pooled = (weights * keys.float()).sum(dim=-2)
    pooled = pooled.to(torch.bfloat16).float()
    h = hadamard_matrix(pooled.shape[-1], device=pooled.device)
    rotated = (pooled @ h.T).to(torch.bfloat16).float()
    amax = torch.clamp_min(rotated.abs().amax(dim=-1), _AMAX_FLOOR)
    scale = torch.exp2(torch.ceil(torch.log2(amax / _FP8_E4M3_MAX)))
    quantized = torch.clamp(rotated / scale[..., None], -_FP8_E4M3_MAX, _FP8_E4M3_MAX)
    return quantized, scale


def dsa_pooled_index_cache_update_reference(
    tail: torch.Tensor,
    tail_slot_mapping: torch.Tensor,
    key: torch.Tensor,
    slot_score: torch.Tensor,
    ape: torch.Tensor,
    slot_mapping: torch.Tensor,
    positions: torch.Tensor,
    pool_size: int,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
    """Apply the update to ``tail`` in place; return the pooled keys it writes.

    Returns ``(cache_slots [C] int64, quantized values [C, dim] fp32, scales [C] fp32)``
    for every completed pool, so the caller can compare against whatever scale
    encoding the device's cache uses.
    """
    num_requests, next_n, _ = key.shape
    ring = tail.shape[2]
    rows = torch.arange(num_requests)
    offsets = torch.arange(pool_size)
    slots, values, scales = [], [], []
    for t in range(next_n):
        pos = positions[:, t].long()
        loc = slot_mapping[:, t].long()
        tslot = tail_slot_mapping[:, t].long()
        block = tslot.clamp_min(0) // ring
        complete = (pos >= 0) & (loc >= 0) & (pos % pool_size == pool_size - 1)
        if bool(complete.any()):
            r = rows[complete]
            start = pos[complete] - (pool_size - 1)
            phys = (start[:, None] + offsets[None, :]) % ring
            b = block[complete][:, None]
            keys = tail[b, 0, phys].clone()
            scores = tail[b, 1, phys].clone()
            keys[:, -1] = key[r, t]
            scores[:, -1] = slot_score[r, t]
            quantized, scale = compress_pool(keys, scores, ape)
            slots.append(loc[complete])
            values.append(quantized)
            scales.append(scale)
        stash = (pos >= 0) & (tslot >= 0)
        tail[block[stash], 0, pos[stash] % ring] = key[stash, t].to(tail.dtype)
        tail[block[stash], 1, pos[stash] % ring] = slot_score[stash, t].to(tail.dtype)
    if not slots:
        dim = key.shape[2]
        return torch.empty(0, dtype=torch.long), torch.empty(0, dim), torch.empty(0)
    return torch.cat(slots), torch.cat(values), torch.cat(scales)


__all__ = [
    "compress_pool",
    "dsa_pooled_index_cache_update_reference",
    "hadamard_matrix",
]
```

---

This page as Markdown: https://servingstudio.cs.washington.edu/kernels/dsa_pooled_index_cache_update.md. A guide to the whole site for AI agents: [llms.txt](https://servingstudio.cs.washington.edu/llms.txt).
