# Pooled top-k with page table (`dsa_pooled_logits_page_table`) | ServingStudio Kernel Library

Select each row's top pools from indexer logits and write its packed page table.

Each of the batch_size · next_n rows has seq tokens, seq / kpool complete pools and one FP32 logit per pool. The kernel selects the top_k largest logits of the row (all of them when the row is shorter) and writes the row's page table as dsa_pooled_topk_page_table does: the tokens of the selected pools and the trailing partial pool, mapped through the block table, packed to the front, -1 after, with a valid count. Rows of a request have 4·context_len − (next_n − 1 − j) − (request mod 4) tokens.

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

## Formula

- `rows = batch_size · next_n; L_j = seq_j / kpool pools`
- `selected = top_k pools of logits[j, :L_j]; page table as dsa_pooled_topk_page_table`
- `logical bytes = 4·Σ_j L_j + rows · (4·top_k + 8 + 4·(top_k + kpool − 1) + 4·page_table_width + 4)`
- `GB/s = logical bytes / 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. One launch. Before timing, the selected pool values are checked against torch.topk per row and the page table and valid counts against the reference built from the kernel's own selection.

## Caveats

- Rows whose top_k-th score is tied may select other pools than another top-k kernel; the selected values are the same.
- Time follows the score distribution (as dsa_persistent_topk_decode).
- The vendored kernel is compiled for top_k 512, kpool 4, page_table_width 2176 and 64-token blocks; the runner refuses other shapes.

## Arguments

| Argument | Type | Unit | Meaning |
| --- | --- | --- | --- |
| `batch_size` | number | requests | Requests decoded together. |
| `context_len` | number | pools | Complete pools in each request's longest row. |
| `next_n` | number | tokens | Query rows per request in a decode step. |
| `max_model_len` | number | tokens | Tokens one request's block table can address. |
| `logits_row_stride` | number | elements | Physical spacing between logit rows. |
| `top_k` | number | pools | Pools selected per query row. |
| `kpool` | number | tokens | Tokens per pool. |
| `page_table_width` | number | slots | Width of each page-table row. |
| `block_size` | number | tokens | Tokens in each KV cache block. |
| `logits_dtype` | dtype |  | Element type of the indexer logits. |
| `index_dtype` | label |  | Element type of the page-table slots. |
| `context_mode` | label |  | Score distribution: uniform_measured draws from a measured live-indexer distribution (as dsa_persistent_topk_decode), uniform_random standard normals. |

## Metrics

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

## Backends

- `cuda_threshold_filter_radix`: Vendored CUDA kernel (not a fork path): one CTA of 512 threads per row streams the row's logits once, takes a threshold from an 8-ary count search over the first batch, keeps the scores above it in per-lane buffers, selects exactly by an 11-bit radix over the survivors (exact fallback over the whole row on overflow) and builds the page table in its epilogue. dtypes `fp32`, SM targets `sm_100a`, GPUs B200-SXM-180GB, GB200-Superchip.

## Measured rows

None measured yet.

## API

- This kind: https://servingstudio.cs.washington.edu/api/public/v1/kernels/dsa_pooled_logits_page_table
- Measured rows: https://servingstudio.cs.washington.edu/api/public/v1/kernels/dsa_pooled_logits_page_table/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_logits_page_table/configs

## Torch reference

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

```python
"""Torch semantics for the pooled DSA indexer's post-top-k page table.

The pooled (kpool) DSA indexer selects ``top_k`` pools of ``kpool`` tokens per
query row. Sparse MLA then needs the physical cache slots of those tokens plus
the row's trailing partial pool, packed as one ``page_table_width`` wide row.
This module states that mapping in plain Torch, independent of vLLM, Triton
and CUDA extensions. It follows the vLLM fork's decode chain (fork 5629b26):

1. ``expand_pools_and_append_tail`` (``models/glm5next/nvidia/ops/
   kpool_compress.py``): history column ``c < top_k * kpool`` is token
   ``pool[c // kpool] * kpool + c % kpool`` or -1 when the pool id is -1;
   tail column ``top_k * kpool + j`` (``j < kpool - 1``) is token
   ``(seq // kpool) * kpool + j`` when ``j < seq % kpool``, else -1;
2. that row copied into a -1 filled ``page_table_width`` buffer;
3. ``triton_convert_req_index_to_global_index(..., return_valid_counts=True)``
   (``v1/attention/backends/mla/sparse_utils.py``): a token whose block is
   inside the block table becomes ``block_table[req, tok // block_size] *
   block_stride + tok % block_size``; the valid slots are packed to the front
   in column order (``COMPACT_TO_FRONT``), the rest -1, with one count per row.

Token ids are int32 as in the fork (the pool id is cast to int64, scaled, and
the expanded row stored as int32, so ``pool * kpool`` wraps like int32).
"""

from __future__ import annotations

import torch

__all__ = ["pooled_page_table_reference", "pooled_topk_reference_values"]


def _expand(pool: torch.Tensor, seq: torch.Tensor, kpool: int) -> torch.Tensor:
    rows, top_k = pool.shape
    pid = pool.to(torch.int64)
    cols = torch.arange(top_k * kpool, device=pool.device)
    hist = pid[:, cols // kpool] * kpool + (cols % kpool)
    # int32 store of the int64 product (two's complement wrap)
    hist = ((hist + 2**31) % 2**32 - 2**31).to(torch.int64)
    hist = torch.where(pid[:, cols // kpool] >= 0, hist, torch.full_like(hist, -1))
    seq64 = seq.to(torch.int64)
    tail_start = (seq64 // kpool) * kpool
    tail_count = seq64 - tail_start
    j = torch.arange(kpool - 1, device=pool.device)
    tail = tail_start[:, None] + j[None, :]
    tail = torch.where(j[None, :] < tail_count[:, None], tail, torch.full_like(tail, -1))
    return torch.cat([hist, tail], dim=1)


def pooled_page_table_reference(
    pool: torch.Tensor,
    seq_lens: torch.Tensor,
    req_id: torch.Tensor,
    block_table: torch.Tensor,
    *,
    kpool: int,
    block_size: int,
    block_stride: int,
    page_table_width: int,
) -> tuple[torch.Tensor, torch.Tensor]:
    """Return ``(page_table [rows, width] int32, valid_counts [rows] int32)``."""
    if pool.ndim != 2 or seq_lens.shape != (pool.shape[0],) or req_id.shape != (pool.shape[0],):
        raise ValueError("pool [rows, top_k], seq_lens [rows] and req_id [rows] required")
    tokens = _expand(pool, seq_lens, kpool)
    if tokens.shape[1] > page_table_width:
        raise ValueError("page_table_width must hold top_k * kpool + kpool - 1 tokens")
    blocks = torch.div(tokens, block_size, rounding_mode="floor")
    valid = (tokens >= 0) & (blocks < block_table.shape[1])
    safe_blocks = torch.where(valid, blocks, torch.zeros_like(blocks))
    pages = block_table.to(torch.int64)[req_id.to(torch.int64)[:, None], safe_blocks]
    phys = pages * block_stride + tokens % block_size
    phys = (phys + 2**31) % 2**32 - 2**31
    rows = tokens.shape[0]
    counts = valid.sum(dim=1)
    # stable compaction: destination of each valid slot = its rank among the row's valid slots
    dest = torch.cumsum(valid.to(torch.int64), dim=1) - 1
    out = torch.full((rows, page_table_width), -1, dtype=torch.int64, device=pool.device)
    r_idx, c_idx = valid.nonzero(as_tuple=True)
    out[r_idx, dest[r_idx, c_idx]] = phys[r_idx, c_idx]
    return out.to(torch.int32), counts.to(torch.int32)


def pooled_topk_reference_values(
    logits: torch.Tensor, lengths: torch.Tensor, top_k: int
) -> list[torch.Tensor]:
    """Per row, the sorted values of the ``min(top_k, length)`` largest valid logits."""
    out = []
    for row in range(logits.shape[0]):
        length = int(lengths[row])
        k = min(top_k, length)
        out.append(torch.sort(torch.topk(logits[row, :length], k).values).values)
    return out
```

---

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