Skip to content

refactor(unified-memory): route the KV read path through one id translator - #35247

Closed
caihuali95 wants to merge 10 commits into
sgl-project:mainfrom
caihuali95:mainline/read-loc-triton
Closed

caihuali95 wants to merge 10 commits into
sgl-project:mainfrom
caihuali95:mainline/read-loc-triton

Conversation

@caihuali95

@caihuali95 caihuali95 commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Note on scope — this PR was split out. It was previously part of #34613 alongside the
migration of the remaining attention backends. Separating the mechanism from the migration
keeps this PR reviewable as a pure refactor, and leaves #34613 as the backend-enablement
change. The stack was also reordered per review: the read path now lands FIRST, so the
write-loc refactor (#35245) can be built directly on the translator instead of being
relocated onto it afterwards. Stack order: #34602 → this PR → #35245 → #34613.

Only the last 2 commits are for this PR. The other commits are from #34602.

Motivation

Each attention backend gathers req_to_token itself and then translates the result, so id-space
knowledge is duplicated across every backend and every forward mode. That duplication is what
made the read path the harder half to extend: a new backend must re-derive which table to read,
which translation applies, and where in the sequence to apply it.

Modifications

Introduces a single object that owns every id-space decision on the read path, and points the
Triton backend at it. Index construction becomes a fused gather-and-translate that emits
kernel-facing ids directly into each row's live prefix, so there is no longer a fill-then-translate
sequence that a caller could forget, duplicate, or apply to the wrong extent. Per-batch results
live on the translator, not on the ForwardBatch: the eager view is memoized in a single
translator-resident slot keyed by batch identity, so one metadata build's many consumers share
one table build without adding any ForwardBatch field (more hybrid attention kinds mean more
id spaces per forward — one batch field per id space does not scale). The write path is
untouched here; it moves onto the same object in #35245.

Byte-identical for non-unified pools, where the translator resolves to the raw req_to_token
and request indices the backends used before.

Note: revalidated on the restructured series, rebased onto current main. Accuracy is GSM8K at n=200 per cell over the full cache x sched x cg x page-size grid (60 unified-vs-baseline pairs, 68/68 cells clean); speed is the product-config serving matrix (12 pairs, 5/5 cells clean). Measured against the parent PR, this PR's own drift is a median +0.08% ITL (range -0.42 … +0.89%), i.e. the read-path refactor is free.

Accuracy Tests

GSM8K, unified vs. baseline.

Model family Median Δ Range
Qwen3.5-9B +0.75 pt -3.5 … +2.0
Kimi-Linear-48B +0.00 pt -1.5 … +1.5
Falcon-H1-7B +0.25 pt -4.0 … +2.0
gpt-oss-20b +0.25 pt -5.5 … +4.5

Speed Tests and Profiling

Serving benchmark (heavy-decode, radix-retract), unified vs. baseline at matched attention backend.

Model family Median Δ ITL
Qwen3.5-9B +0.58%
Kimi-Linear-48B +1.14%
Falcon-H1-7B +0.24%
gpt-oss-20b -0.94%

Checklist

Review and Merge Process

  1. Ping Merge Oncalls to start the process. See the PR Merge Process.
  2. Get approvals from CODEOWNERS and other reviewers.
  3. Trigger CI tests with comments or contact authorized users to do so.
    • Common commands include /tag-and-rerun-ci, /tag-run-ci-label, /rerun-failed-ci
  4. After green CI and required approvals, ask Merge Oncalls or people with Write permission to merge the PR.

CI States

Latest PR Test (Base): ❌ Run #33365729787
Latest PR Test (Extra): ❌ Run #33365729495
Latest PR Test (AMD ROCm 7.2): ❌ Run #33365729635

@caihuali95
caihuali95 force-pushed the mainline/read-loc-triton branch from 6c36f53 to 4fae7d0 Compare August 28, 2026 21:03
@ch-wan
ch-wan force-pushed the mainline/read-loc-triton branch 9 times, most recently from 5b8c569 to b46decb Compare August 30, 2026 22:05
Caihua Li and others added 8 commits August 30, 2026 22:11
A KV slot can be named in more than one id space. `req_to_token` stores a
VIRTUAL id, which keeps naming the same logical slot even after the pool moves
data around. A kernel, though, has to index the per-layer K/V tensors with the
id those tensors actually use. On a plain pool the two are the same and nothing
needs doing. Under the unified memory pool they differ, so somebody has to
convert — and today every attention backend converts for itself, which means
each one has to know the pool's internals and each one is a place to get it
wrong.

This adds the object that does the converting, so backends stop doing it. New
module, unwired: nothing consumes it until the next commit.

Backends receive a `KVIndexTable`, which answers one question — what do I gather
from, and which row is mine? On a plain pool it hands back `req_to_token` and
`req_pool_indices` themselves, so those servers behave exactly as before: no
copy, no kernel, no change. Under the unified pool it hands back a freshly
built array of converted ids with one row per batch lane.

One array serves every backend because converting only rewrites the page number
and keeps the offset inside the page. A backend that wants a 2-D block table
uses the rows as they are; a backend that wants a flat per-token list rebuilds
one arithmetically. That is why this does not have to produce two shapes.

Per-batch results live on the translator rather than on the ForwardBatch: a
forward can carry several id spaces at once and adding a batch field per space
does not scale. The result is memoized in a single slot keyed by batch
identity, so the many consumers of one metadata build share one build, and the
next batch replaces it.

- python/sglang/srt/mem_cache/kv_index_translator.py: `KVIndexTranslator`
  checks once, by type, whether the active pool needs conversion at all — and
  requires that the pool this runner reads and writes is the one the
  allocator's ids address. Sliding-window models get a second array built
  straight from the same virtual ids through the sliding-window pool's own
  map, never by converting the full-attention ids twice. Buffers used under
  cuda graphs are zero-filled, because entry 0 is the reserved padding slot in
  every id space; a replay refreshes only the live prefix in place and never
  swaps the buffer, since the recorded graph baked in its address. `seq_lens`
  is always supplied by the caller, never read off a batch: which lengths
  cover the slots a kernel will read is the caller's knowledge.
- python/sglang/kernels/ops/kvcache/kv_read_table.py: the fused
  gather-and-convert kernel behind it, writing each row's live prefix only,
  with a pure-torch reference path for CPU. Unwritten and freed entries both
  land on the padding slot, so a kernel dereferences padding rather than a
  wild address.
- python/sglang/kernels/ops/kvcache/__init__.py: register the new kernel.
- test/registered/unit/mem_cache/test_kv_index_translator.py: pin that a plain
  pool gets back the very same objects (the property that keeps those servers
  byte-identical); the built table against an independent per-element
  reference over a real sliding-window pool, across page sizes and both
  multiplier regimes; padding for dead lanes, unwritten slots and freed pages;
  the cuda-graph buffer contract; the caller-owned fill; the pool-ownership
  check over the real factory; and the single-slot memo.

Co-Authored-By: Claude Fable 5 <[email protected]>
The Triton backend builds its read indices straight out of `req_to_token`, then
converts the result itself when the pool needs it. That leaves the backend
holding pool knowledge it should not need, and it does the work in the wrong
order: it fills a buffer with ids of one kind and rewrites them afterwards, so
every branch has to remember to rewrite, over exactly the right range.

Point it at the table the translator hands out instead, and the conversion
disappears from this file. Byte-identical on a plain pool, where that table IS
`req_to_token` plus `req_pool_indices` — the same two objects, so those gathers
are unchanged down to the tensor.

The write path is deliberately untouched here. The backend keeps converting its
own write locations for now; that half moves in the next PR, and mixing the two
would make this diff impossible to check.

- python/sglang/srt/layers/attention/triton_backend.py: take the batch's read
  table once and thread it through every index builder — decode, extend and
  the sliding-window fill. The two eager conversion passes over freshly built
  indices are gone, and so is the one that rewrote the cuda-graph read buffers
  before replay: under the unified pool those buffers are filled from tables
  the translator has already refreshed, so the ids come out ready to use. What
  used to be a read+write refill method is now write-only, and renamed to say
  so. A sliding-window fill asks the table for its swa array. The one
  conversion left on this path belongs to plain SWA pools and their own
  full->swa map, behind a type check on the pool rather than a probe for an
  attribute.
- python/sglang/kernels/ops/kvcache/kv_indices.py: the index kernel learns what
  one source entry covers, so it can rebuild flat token ids from a
  page-granular table. That is what lets one table serve both the backends
  that want a 2-D block table and those that want a flat list.
- python/sglang/srt/model_executor/model_runner.py: build the translator once
  per runner and hand it to the backends.
- test/registered/attention/test_create_kvindices.py: cover a page-granular
  source against the token-granular reference.

Co-Authored-By: Claude Fable 5 <[email protected]>
…onstexpr

`create_flashinfer_kv_indices_triton` declares `req_to_token_ptr_stride` as
`tl.constexpr`, which was free while the only caller passed
`req_to_token.stride(0)` -- one value for the life of the process. It is not
free now: under the unified pool the argument is `index_table.row_stride`,
i.e. the eager table's width, which `index_table_for_batch` recomputes per
batch as `ceil(max_seq_len / page_size)`. A constexpr is part of Triton's
specialization key, so every distinct batch max-seq-len compiles a fresh
kernel -- a recompile every few decode steps at small page sizes.

Make it a runtime argument. `ENTRY_PAGE_SIZE` stays constexpr: it is the page
size, fixed for the run, and it selects between two different address
computations.

Also widen `req_pool_index` to int64 before it multiplies the stride. The
product indexes `req_to_token`, whose element count exceeds int32 on a large
`max_num_reqs x max_context_len` table.

Co-Authored-By: Claude Opus 5 <[email protected]>
… not just the reference

The module contract says a `-1` in `req_to_token` lands on entry 0, the
reserved sink, and the CPU reference implements it (`torch.where(tok < 0, 0,
tok // page_size)`). The Triton kernel did not, so the two halves of one
function disagreed -- and CI only exercises the CPU half.

At `page_size > 1` truncating division hid it: `-1 // ps` is 0, and
`MultiEndedAllocator.clear()` pins `virtual_to_physical[0] = 0`, so the lane
reached the sink anyway. At `page_size == 1` there is nothing to truncate:
`-1 // 1` is -1, so the load reads `v2p[-1]` -- one element before the table
-- and `tl.maximum(phys * mult, 0)` passes whatever was there through as a
live KV id. Measured on an H200 by backing `v2p` with a tensor whose
preceding element was set to 123456789: the kernel emitted 987654312
(= 123456789 * 8) where the sink was expected.

No mainline path puts `-1` inside a row's live prefix today, so this is the
guard the module documents rather than a live miscompute. One `tl.where`
makes both page sizes and both implementations agree.

Co-Authored-By: Claude Opus 5 <[email protected]>
…ns_cpu

`index_table_for_batch` took `seq_lens_cpu is not None` as "the CPU mirror is
live". It is not that signal, and the code this series replaces said so in as
many words:

    seq_lens_sum is the reliable "mirror present" signal: it is
    None-preserving into the replay view, unlike seq_lens_cpu (always a
    non-None but stale slice for gpu_only batches).

Here the consequence is worse than the one that comment guarded. The value
sets the table's WIDTH, so a stale-and-smaller max silently under-sizes it:
the columns past the built prefix keep the fresh zeros -- entry 0, the sink --
for tokens the kernel genuinely wants to read. Wrong attention output, no
error anywhere.

Only the eager path reaches this today (every replay path goes through
`build_index_table(captured=True)`), so this is disarming the trap rather than
fixing a live miscompute. Use `seq_lens_sum` as the guard and keep the table's
own width as the fallback, which is always safe.

The unit fake grows the field, defaulting to the real sum, so a case that
wants the gpu_only regime asks for it explicitly.

Co-Authored-By: Claude Opus 5 <[email protected]>
Same pass as the parent PR, over what this one added.

- `kv_index_translator` module docstring: the three id spaces, the table shape
  and the affine rebuild law stay -- that is the subsystem's contract and a
  module docstring is where design rationale belongs. The argument for having
  a choke point at all ("each backend would be a place to get it wrong") is
  PR-body material and goes, along with the WHY/WHAT section headings that
  only make sense to someone deciding whether to approve it.
- `kv_read_table` module docstring: same, condensed.
- The `-1` guard keeps the fact that makes it necessary -- Triton's `//`
  truncates, so `-1 // 1` is -1 and would read before the table -- and drops
  the retelling of how the two implementations came to disagree.
- `index_table_for_batch` keeps the trap (`seq_lens_cpu` is non-None but stale
  on a gpu_only batch, and a stale max under-sizes the table); drops the walk
  through the consequence.
- Triton backend's write hook and two test fixtures: keep the constraint, drop
  the derivation.

Co-Authored-By: Claude Opus 5 <[email protected]>
Leftovers from the rename. The module is the translator, what it hands out is
the read table, and the per-forward write target is the write loc -- a few
comments and one test class still said choke point / canonical / rail.

Co-Authored-By: Claude Opus 5 <[email protected]>
…, not a mode

`build_index_table(captured=True)` said the wrong thing. Nothing about the
call is captured -- all six call sites are in `init_forward_metadata_out_graph`
(or `_apply_cuda_graph_metadata`, which it calls), so the build kernel runs
out of graph on both arms. What the flag actually selected was the
DESTINATION: the module's own pre-allocated buffers, because a captured graph
will later bake their pointers, versus a fresh allocation. That is a property
of the buffer, not of the caller's graph state, and a reader who takes
`captured=True` to mean "this runs inside a graph" is misled.

It was not really a choice either: every explicit caller passed `True`.
`False` was only ever reached through `index_table_for_batch`.

So pass the buffer. `out=` / `out_sliding_window=` replace `captured`, and
`out=None` allocates as before -- which is the shape `fill_read_table(out=...)`
already had for trtllm_mla / flashmla, so the two are now one operation and
`fill_read_table` is a three-line wrapper that returns the tensor instead of
the table. The width rule comes with it: a caller-owned table may be padded
wider than req_to_token's span, so both paths clamp.

`ensure_capture_buffers` goes; `make_read_table_buffers` gives the same
zero-filled shape and the BACKEND owns what it allocates, next to every other
capture-stable buffer it already holds -- which is where cuda-graph loc
management belongs. The implicit "call ensure_capture_buffers first" ordering,
enforced by a runtime assert, becomes unrepresentable: you cannot pass a
buffer you have not made.

Co-Authored-By: Claude Opus 5 <[email protected]>
@ch-wan
ch-wan force-pushed the mainline/read-loc-triton branch from b46decb to 09d556c Compare August 30, 2026 22:14
@ch-wan

ch-wan commented Aug 30, 2026

Copy link
Copy Markdown
Collaborator

@codex

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Aug 30, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-08-31T06:54:23.058275Z 4e48ddd New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 09d556c56c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +738 to +741
def _fill_cuda_graph_write_locs(
self, forward_batch: ForwardBatch, bs: int
) -> Optional[torch.Tensor]:
"""Unified pool: eager v2p translate of the cuda-graph read+write LOC buffers,
run BEFORE graph.replay() reading the live post-compaction v2p, so the
captured graph carries zero translate nodes. No-op for non-unified pools.

Read buffers (full kv_indices, SWA window) are translated IN PLACE; the
full-attn WRITE loc is RETURNED as the [:n] view of the backend-owned
out_cache_loc_full_physical buffer. Eager .item() bounds are fine here
(out-of-graph), so no in-graph translate variant is needed.
"""Unified pool: eager v2p translate of the cuda-graph WRITE loc into

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve read translation for DCP graph buffers

When unified memory, Triton DCP (dcp_size > 1), and CUDA graphs are enabled together, _update_decode_kv_buffers still fills cuda_graph_kv_indices through _dcp_kv_indices, which gathers raw virtual IDs from req_to_token and ignores the translated index_table. This helper previously translated that read buffer before replay, but it now handles writes only, so the captured attention kernel indexes the physical/dense KV storage with virtual IDs after allocation or compaction, producing incorrect reads or out-of-bounds accesses. Keep the DCP read-buffer translation or make the DCP gather consume the translated table.

Useful? React with 👍 / 👎.

@ch-wan

ch-wan commented Aug 30, 2026

Copy link
Copy Markdown
Collaborator

The mechanism is real, but the configuration is rejected at boot, so it is not reachable.

handle_unified_memory_pool (python/sglang/srt/arg_groups/kv_cache_hook.py) asserts
cfg.dcp_size == 1 under --enable-unified-memory, and attn_dcp_size is
dcp_size if dcp_enabled else 1 (runtime_context.py), so self.dcp_size > 1 in the
Triton backend implies a server that refused to start. DCP support for the unified pool
is separate in-progress work; it will relax that assert and wire the DCP gather at the
same time.

Worth recording for whoever does that: on the pre-PR code the eager DCP branches were
never translated either — _translate_kv_loc sat inside the non-DCP else: at both
eager sites. Only the cuda-graph buffer got translated, and only incidentally, because
_translate_cuda_graph_shared_pool_locs rewrote cuda_graph_kv_indices[:n_kv] in place
after _update_decode_kv_buffers had filled it, whatever filled it. So unified+DCP was
half-translated rather than working, which is why the guard exists.

Every caller owns the block table it passes in and discards the return
value; the docstring also still named the pre-into= parameter.
@ch-wan ch-wan added run-ci CI: run the baseline test suite on this PR and removed run-ci CI: run the baseline test suite on this PR labels Aug 31, 2026
The comments this PR adds that narrate their own call site, and the
em-dashes it introduces in comments and docstrings (.claude/rules/comment-style.md
requires ASCII). Only lines this PR owns; pre-existing text is left alone.
@ch-wan ch-wan closed this Aug 31, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants