Skip to content

[Sgl Atom][perf] plugin per-layer host path: QSA FlyDSL K/V in place, GDN wrapper state once per forward - #3433

Closed
ZLkanyo009 wants to merge 18 commits into
mainfrom
lingzha/qwen4-plugin-layer-host-trim
Closed

ZLkanyo009 wants to merge 18 commits into
mainfrom
lingzha/qwen4-plugin-layer-host-trim

Conversation

@ZLkanyo009

@ZLkanyo009 ZLkanyo009 commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

Under SGLang (page 64) every QSA layer of an eager Qwen3.8-Flash-Next prefill takes the aiter FlyDSL sparse attention (aiter.ops.qsa.qsa_sparse_prefill). Profiling a prefix-hit prefill (8192 tokens, 6080 cached) showed that the per-layer host path in Qwen4ExpAttention._flydsl_attention repeated work that is the same for the whole forward, and copied data the kernel can read where it is:

  • with a prefix, each layer index_selected the whole context's K and V rows (8192 x 256 bf16 each) out of its paged pool;
  • each layer padded the top-k selection with -1 to the kernel width; F.pad clones the selection (about 17 MB at 2112 rows x 2051 columns) even when no padding is needed;
  • each layer re-read the env flag, re-ran the layer support check and the per-call checks (width, 2**31-byte limit, graph capture, dtype, host lengths) and rebuilt the per-request prefix lengths, although all of them are the same for every QSA layer of a forward.

The SGLang GDN wrapper had the same pattern: after its compute every SGLangGatedDeltaNet layer re-derived the forward mode, the SGLang linear backend, the radix-track metadata and destination slots, and asked SGLang's mamba pool for a freshly built MambaPool.State of layer views; the binder rebuilt every GDN layer's KVCacheTensor each forward.

This PR removes those. Same reads, same kernels, same arguments to them; it does not touch SGLang or aiter and adds no environment variables.

Depends on #3422 (merged in as 71fe84dee): the GDN part reworks the layer forward that #3422 changes. Only the commits below belong to this PR:

Changes

  • K/V read in place through aiter's slot table (qwen4_exp_bridge.py, qsa_attention.py). qsa_sparse_prefill has taken kv_slots since it was added ([FlyDSL] Add QSA sparse prefill attention for MI308 aiter#6576): K/V can be a token pool [P, HK, 256] read through a contiguous int32 slot table, provided every four-token block of a request (the final partial one included) sits in four consecutive pool rows starting at a multiple of four, which any page size divisible by four guarantees. aiter documents the result as the same as for K/V packed by those slots. The bridge already requires the page size to be divisible by the compress ratio (4), and now emits the context rows as int32 (once per forward). The layer passes the pool and the table; int64 rows, a strided pool or a page size not divisible by four keep the gather.
  • Selection written at the kernel width (qsa_attention.py). forward computes the selection width before selecting (_selection_widths, the same helper the selection uses). The first QSA layer of the forward allocates one [rows, kernel width] int32 buffer filled with -1, and every layer's selection writes its leading columns in place (qsa_select_paged_tokens(..., out=), or qsa_expand_block_indices(..., out=) on the sequence-parallel path). That buffer goes to the kernel as is. Nothing writes the columns past the selection, so they stay -1 for every layer; aiter's selection recovery only reads indices. A selection that is not a view of the buffer is still padded.
  • Checks once per forward (qsa_attention.py, qwen4_exp_attn.py). The flag, the layer support check, the per-call checks, the kernel width and the prefix lengths are made by the first QSA layer (_FlyDSLPrefill) and kept on the forward's Qwen4ExpQSAMetadata.flydsl_prefill (init=False, so for_tokens copies start without one). The key holds everything the decision reads from the layer and its inputs (ratio, budget, heads, head dim, KV dtype, rows, query dtype, selection width, index size); a layer with another key builds its own.
  • Native ATOM, whose QSA metadata has no FlyDSL layout (host_lens is None), skips the new pre-selection step and keeps its path.
  • GDN wrapper state once per forward (attention_gdn.py).
    • _GDNStep is built once in SGLangGDNForwardContext.build from the forward batch and linear backend it already resolves (forward mode, track metadata, conv destination slots), and bind publishes it through a ContextVar for that forward batch only. A layer whose forward batch has a step takes its pool views, pops its chunk states and writes the snapshots: the conv window index_put, then SGLang's _track_mamba_state_extend, the same calls in the same order as the per-layer path. Decode, missing conv slots, and models that do not go through bind keep the per-layer path.
    • _mamba_layer_cache: HybridReqToTokenPool.mamba2_layer_cache builds a new MambaPool.State of views on every call (at_layer_idx). A layer's views are reused while the pool holds the same state object and layer map. Only SGLang's own accessor is cached, and never with a HiCache transfer counter, whose per-layer wait lives in that accessor. _build_kv_cache_tensors (all GDN layers, every forward) reuses its KVCacheTensors on the same terms.

Tests (tests/test_qwen4_exp_qsa_flydsl_gate.py, tests/plugin/test_sglang_qwen4_exp_graph_padding.py, tests/plugin/test_sglang_gdn_layer_step.py):

  • one layout per forward; the kernel-width buffer reaches the kernel without a copy and keeps -1 past the selection across layers; the pool and the int32 slot table go to the kernel, int64 rows and a strided pool are still gathered; the bridge's rows are int32;
  • GDN (CPU): view reuse and invalidation on real SGLang pool classes, no caching with a transfer counter or a foreign / overridden accessor, the binder's KV tensors, which forwards get a step and which keep the per-layer path, a layer only uses the step of its own forward batch, bind scopes the step; six GDN layers sharing one step write the same conv and SSM pool bytes as the per-layer path through SGLang's real _track_mamba_state_extend (4 row mixes x KV / VK SSM view).
  • GPU: the real kernel on the slot table with the in-place selection, two layers sharing one layout, gives the same bits (torch.equal) as gathered rows plus a padded copy: 8192 with 6080 cached, a second prefill chunk, three requests with unaligned prefixes, a short context (narrower selection, padded to 1027), no prefix. Stale pool rows hold random finite values. The sequence-parallel expansion into the buffer matches a fresh one bit for bit.

Performance

Qwen3.8-Flash-Next-PTPC-FP8 on MI308X: TP2, EP2, --attention-backend aiter, page 64, chunked prefill 8192, EAGLE 3/1/4, radix cache on, eager prefill.

Host time per QSA layer of the FlyDSL part (no profiler; groups of 12 calls, GPU drained between groups, median of 3 rounds; the selection itself is the same on both sides and excluded):

                                      before    this PR
8192/6080, 1 request                   143.0     104.7   us per QSA layer
10240/7104, 1 request                  143.8     104.1
4 requests, 6080 cached each           144.8     105.8

With 12 QSA layers that is about -0.46 ms of host time per target prefill forward (the MTP layer in the draft extend saves another ~0.04 ms). A profiled target forward (no stack, 8192/6080) confirms it in the server: 24 index_select gathers and 12 padding copies (DtoD) fewer per forward, one fill more.

Bit-for-bit on GPU at these shapes (TP2 rank: 12 q / 1 kv heads x 256, 4096-page pool with random stale rows, two layers per case): 8192/6080, 10240/7104, four requests 6080+2112/2112/2112/1856, second chunk 8192+2048, three requests with unaligned prefixes (6001+2111, 0+300, 1234+517), 200+300, 0/0/100 + 100/37/250, no prefix: every output and every selection is torch.equal to the current path.

GDN host time without the profiler (MI308X, pinned cores, median of 7 rounds of 20 groups; TP2-rank shapes: 36 GDN layers, conv 5120 x 3, SSM 24 x 128 x 128, real SGLang pool objects, the backend resolved through SGLang's forward context; both sides on SGLang's eager track helper):

                                              per-layer path   this PR
radix-track part of a GDN layer (us/layer)          70.0          62.2   (36 layers: -0.28 ms / forward)
  mamba2_layer_cache view                            5.4           0.45
binder's KVCacheTensor build (us/forward)          230.9           2.2   (-0.23 ms / forward)
_GDNStep build (us/forward)                            -           1.3

Bit for bit on GPU at these shapes: 6 track-row mixes x FlyDSL-decode VK view on/off, 36 layers each, whole conv and SSM pools torch.equal to the per-layer path.

TTFT (issue protocol, input_ids): the machine was shared (load 10-33), so server sessions started at different times differ by 20-30 ms at c=1. Instead, one server process switched between the current and the new path with a signal (a measurement-only patch, not part of this PR), alternating waves pair by pair (ABBA). Every wave refilled its prefix, used a fresh tail, and was checked to hit exactly 6080 / 7104 cached tokens; pair 0 (warm-up) is dropped.

GDN part alone, on the eager track path (this PR's head; QSA part on in both modes)
case          c   pairs   median off -> on (ms)   paired diff: median (mean +- SEM)   new faster
8192/6080     1    22       226.2 -> 222.5           -4.1  (-10.1 +- 4.7)              16/22
10240/7104    1    22       228.4 -> 225.9           -2.3  ( +5.5 +- 6.2)              16/22

measured before the move, while #3422 still had a fused radix-track kernel:
QSA part alone (GDN part on in both modes)
case          c   pairs   median off -> on (ms)   paired diff: median (mean +- SEM)   new faster
8192/6080     1    20       227.4 -> 226.0           -2.9  (-10.1 +- 6.2)              16/20
10240/7104    1    20       226.3 -> 227.0           -0.6  ( +0.7 +- 3.6)              13/20

QSA and GDN parts together
8192/6080     1    36       (two runs)               -3.1  ( -1.5 +- 2.8)              25/36
10240/7104    1    36       (two runs)               -3.9  ( -6.5 +- 2.2)              30/36
8192/6080     4    12       610.8 -> 607.9           -3.5  ( -0.9 +- 5.3)              10/12
10240/7104    4    12       952.1 -> 942.5           -7.3  ( -6.0 +- 9.0)               9/12
Native 8192/6080 c=1, 16 pairs: 390.5 -> 389.5, -1.2 (-0.0 +- 1.8); Native has no FlyDSL layout

Nothing is slower beyond noise (the positive means, +0.7 ms and +5.5 ms, are inside their SEM and come with 13/20 and 16/22 pairs faster; the +5.5 ms is one slow "on" wave). The saving is about the size of the wave-to-wave spread, so it shows as a consistent small shift rather than a clear step.

Acc

GSM8K, 5-shot, chat completions, max_gen_toks=4096, until=<|im_end|>, temperature 0, limit=200, radix cache and MTP on. Both runs on main + #3422 (then with its fused radix-track kernel); "after" adds the QSA part and the GDN part (then on top of that kernel). The GDN part on the eager path writes the same bytes as the per-layer path (tests above), so it was not rerun:

          exact_match (strict / flexible)   MTP accept rate   accept len
before    0.980 / 0.980                     0.718             3.151
after     0.985 / 0.985                     0.719             3.155

Accept rate and accept len are averaged from the server's Decode batch log lines during the run, weighted by running requests.

Notes

  • About 85 us of the remaining ~105 us per layer is aiter's own entry; of that, about 24 us is its per-call validation and workspace lookup (the rest launches the five FlyDSL kernels). Skipping those for the 11 later layers of a forward needs a prepared-call API in aiter; it is not done here.
  • The QSA part does not depend on any other open PR. The GDN part sits on [Sgl Atom][perf] Qwen4Exp prefill host-sync cleanup (TTFT unchanged) #3422 (merged in) and should merge after it.

cc @valarLip

ZLkanyo009 and others added 13 commits November 16, 2026 08:28
A prefill rewrites each request's GDN checkpoint, so the plugin parks the
ring cursor of its slot at 0. It did so at the end of every GDN layer, and
`slot_idx[slot_idx >= 0]` reads the live-slot count back to the host, so a
Qwen3.8-Flash prefill (36 GDN layers) took 36 blocking D2H reads, each one
draining the GPU queue before the host could launch the next layer.

The cursor is one per slot, shared by every layer, and nothing reads it
during an extend forward. Park it once per forward in
`SGLangGDNForwardContext._build_gdn_metadata`, the counterpart of Native's
`GDNAttentionMetadataBuilder._attach_replayssm`, and route pad rows to a
spare trailing entry instead of filtering them with a boolean mask, so the
reset issues no host read. The parked value stays 0 and the slots are the
same rows of SGLang's `mamba_cache_indices`.

Co-authored-by: Cursor <[email protected]>
…data

`_build_gdn_metadata` sized the extend metadata with
`int(query_start_loc[-1].item())`, one blocking D2H per prefill.
`HybridLinearAttnBackend._forward_metadata` builds that same
`query_start_loc` from `extend_start_loc` / `extend_seq_lens` and stores the
host sum of `extend_seq_lens_cpu` next to it as `logical_num_tokens`, which
is the same number. Use it, and keep the device read only when SGLang left
it unset or the metadata had to be reconstructed.

Co-authored-by: Cursor <[email protected]>
…e QSA

`ATOMAttnBackendForSgl.init_forward_metadata` already skipped the MHA
tables for TARGET_VERIFY and draft-extend under native QSA, but an extend
still went through `_init_extend_mha`. That gathers `kv_indices` over the
whole context and syncs on `kv_indices[token_num:]` in SGLang's
`AiterIndicesUpdaterPrefill`, once for the target prefill and once more for
the draft prefill (the draft runner's extend), and QSA reads none of it:
the QSA layers take their tables from the plugin's QSA metadata, and no
other reader of this backend's `forward_metadata` runs during an extend.
Take the same placeholder for every extend.

Co-authored-by: Cursor <[email protected]>
The mamba radix cache extend snapshot per GDN layer was a conv-window
gather + index_put in the plugin, then h[src] + cast + index_put (and a
slot-to-slot copy for aligned rows) in SGLang's
_track_mamba_state_extend: five to seven small kernels per layer per
prefill.

write_radix_track_snapshots performs the same copies from the same
SGLang track metadata in one Triton launch, addressing every tensor by
its real strides (transposed conv pool, VK SSM view, column slice of the
fused projection) and casting h to the pool dtype as the eager path
does. Recompute rows (Mamba2 only), non-4-D h and CPU tensors keep the
eager path. SGLang is not modified.

Tests compare the pools bit for bit against the eager path across pool
views and target mixes, and check the single launch.

Co-authored-by: Cursor <[email protected]>
The track rows, their slots, the conv window length and the grid's row
count of write_radix_track_snapshots come from SGLang's forward metadata
and are the same for every GDN layer of a forward. RadixTrackPlan holds
that half (built once per forward by the caller); write() adds the
layer's conv input, pools and chunk states and launches the same kernel
with the same arguments. write_radix_track_snapshots keeps its signature
and now builds a plan and writes it.

fused_track_metadata_supported is the metadata half of
fused_track_supported, so a forward can decide it once.

Co-authored-by: Cursor <[email protected]>
…orward

After its compute every SGLangGatedDeltaNet layer re-derived the same
forward-level state: the forward mode, the SGLang attention backend and
its linear child, the track metadata, the conv destination slots and the
radix-track launch arguments, and it asked SGLang's mamba pool for its
layer views, which builds a new MambaPool.State dataclass on every call
(at_layer_idx). The forward-context binder asked for all of them again.

- _GDNStep: built once in SGLangGDNForwardContext.build from the same
  forward batch and linear backend, published by bind for that forward
  batch. A layer whose forward batch has a step takes _track_extend, which
  only pops its chunk states and writes the precomputed RadixTrackPlan.
  Unusual metadata (recompute rows, missing SSM indices or conv slots),
  decode, and forwards without a step keep the per-layer path.
- _mamba_layer_cache: a layer's mamba2_layer_cache views are reused while
  the pool holds the same state object and layer map. Only SGLang's own
  HybridReqToTokenPool / MambaPool.State accessor is cached, and never with
  a HiCache transfer counter, whose per-layer wait lives in the accessor.
  _build_kv_cache_tensors reuses its KVCacheTensors on the same terms.

Same reads, same kernels, same arguments; the pools are written byte for
byte as before.

Co-authored-by: Cursor <[email protected]>
…ects at kernel width

Under SGLang (page 64) each QSA layer of an eager prefill took the aiter
FlyDSL sparse attention through a host path that repeated per layer what
is the same for the whole forward, and copied data the kernel can read
where it is:

- K/V: with a prefix, each layer index_selected the whole context's K and
  V rows out of its paged pool. aiter's qsa_sparse_prefill reads a token
  pool in place through a slot table (kv_slots) when every four-token
  block of a request sits in four consecutive pool rows starting at a
  multiple of four, which a page size divisible by four guarantees (the
  bridge already requires the page to be divisible by the compress
  ratio, 4). The bridge now emits the context rows as int32, the slot
  table's type; the layer passes the pool and the table. aiter documents
  the result as the same as for the packed rows.
- Selection: each layer padded its selection with -1 to the kernel width
  (a copy, also when the width already matched). The first layer of the
  forward now allocates one kernel-width buffer filled with -1, and every
  layer's selection writes its leading columns in place; the columns past
  the selection are never written, so they stay -1.
- Checks: the flag, the layer support check, the per-call checks, the
  width and the per-request prefix lengths are made once per forward
  (_FlyDSLPrefill, kept on the forward's QSA metadata, keyed by
  everything they read from the layer and its inputs).

Native ATOM, whose metadata has no FlyDSL layout, keeps its path.

Co-authored-by: Cursor <[email protected]>
…reuse

- test_sglang_gdn_layer_step.py (CPU): layer views are reused while the
  SGLang pool keeps its state object and are rebuilt for a new one; a
  HiCache transfer counter, a foreign pool or an overridden accessor asks
  every time; the binder's KV tensors are the views SGLang builds; which
  forwards get a precomputed plan and which keep the per-layer path; a
  layer only uses the step of its own forward batch; bind scopes the step.
- test_sglang_gdn_radix_track_fused.py (GPU): the forward-level path
  writes the same bytes as the per-layer path over several layers that
  share one step, and a reused plan matches the one-shot call.

Co-authored-by: Cursor <[email protected]>
…-width selection

- One layout per forward (checks and prefix lengths made once), a new one
  for another row count.
- The kernel-width selection buffer reaches the kernel as is, -1 past the
  selection, reused by a second layer.
- With a prefix the pool and the bridge's int32 slot table go to the
  kernel; int64 rows or a strided pool are gathered as before.
- GPU: the real kernel on the slot table and the in-place selection gives
  the same bits as gathered rows and a padded copy (hit, second chunk,
  mixed unaligned prefixes, short, no prefix).
- The bridge's context rows are int32 and contiguous.

Co-authored-by: Cursor <[email protected]>
…buffer

The sequence-parallel path expands the all-gathered groups itself; into a
column prefix of the kernel-width buffer it writes the same columns as
into a fresh tensor and leaves -1 past them (GPU).

Co-authored-by: Cursor <[email protected]>
@github-actions

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every eligible PR before approval:

  • ✅ Pre Checkin: Black, Ruff, catalog schema validation, non-GPU unit tests

Heavy model tests:

  • ✅ Gate checks are published on every PR so required checks do not stay missing
  • ✅ Expensive jobs run only after the PR is approved, or when a matching ci:* label is present
  • ✅ Pre Checkin must pass before approved heavy jobs continue
  • ✅ Without a matching label, expensive jobs also require a relevant path
  • ✅ A matching ci:* label is an explicit request and can open the gate even when paths would otherwise skip it

Path scope:

  • Native ATOM, vLLM, and SGLang use ignore lists: docs/markdown and unrelated plugin or Mesh paths are skipped
  • ATOMesh uses an include list: Mesh code, ATOMesh scripts/workflows/catalogs, OpenAI entrypoints, and Slurm helpers
  • Relevant path alone does not start expensive jobs; approval still opens the automatic path-scoped gate
Label Tests
ci:full Run all heavy PR model tests: native ATOM, vLLM, SGLang, and ATOMesh
ci:atom Run native ATOM model accuracy tests
ci:vllm Run ATOM vLLM OOT model accuracy tests
ci:sglang Run ATOM SGLang model accuracy tests
ci:mesh Run ATOMesh accuracy/benchmark gates for Mesh-related changes

Without a matching ci:* label, heavy jobs are skipped when the path is not relevant or the PR is not approved.
Add labels via the sidebar or gh pr edit 3433 --add-label <label>

root and others added 5 commits November 16, 2026 20:15
…his PR

Reverts f12cdd0, 723ade6, a662c62 and 4980bc0. The radix-track plan
(S3) only exists to feed the fused track kernel, which leaves this PR in the
next commit. The forward-level GDN step and the pool view reuse (S4/S6) move
to #3433 on the eager track path.

Co-authored-by: Cursor <[email protected]>
Reverts f2ca56a. A same-process paired A/B on the issue #576 SGLang
command shows no TTFT gain from the one-launch track snapshot over the eager
index_put + SGLang `_track_mamba_state_extend` (numbers in the PR). The
eager path keeps the copies in SGLang's own helper, so a change in its track
metadata cannot silently diverge in ATOM.

Co-authored-by: Cursor <[email protected]>
…ata path too

The extend park read the live slots before the reconstruct_linear_metadata
fallback, so a forward without SGLang's GDN metadata never parked the cursor
(as on main). Take the slots after the fallback, and import sglang lazily in
the park test like the other plugin tests.

Co-authored-by: Cursor <[email protected]>
…a/qwen4-plugin-layer-host-trim

The per-forward GDN step reworks the layer forward that #3422 changes;
this PR builds on it and merges after it.
…orward

Moved here from #3422 (a662c62, 723ade6), now on SGLang's eager track
path instead of the dropped fused kernel.

Each GDN layer re-derived, after its compute, the forward mode, the SGLang
linear backend, its track metadata and the conv destination slots, and asked
the mamba pool for a fresh `MambaPool.State` of layer views. A `_GDNStep`
built once per bound forward now holds the first part (published through a
ContextVar by `SGLangGDNForwardContext.bind`, used only for the forward batch
it was built from), and the layer views are reused while the pool holds the
same state object; a HiCache transfer counter or a non-SGLang pool keeps the
per-call lookup. The binder's KV tensor build reuses the same views.

The snapshots themselves are unchanged: the conv window `index_put` and
SGLang's `_track_mamba_state_extend`, in the same order. A CPU test compares
the step against the per-layer path pool byte for byte.

Co-authored-by: Cursor <[email protected]>
@ZLkanyo009 ZLkanyo009 changed the title [Sgl Atom][perf] QSA FlyDSL prefill: read K/V in place and select at the kernel width [Sgl Atom][perf] plugin per-layer host path: QSA FlyDSL K/V in place, GDN wrapper state once per forward Nov 16, 2026
@ZLkanyo009

Copy link
Copy Markdown
Contributor Author

Following the #3422 review: #3422 dropped its fused radix-track kernel, and the per-forward GDN wrapper state I had added there (_GDNStep, reuse of the mamba pool's layer views and of the binder's KV tensors) moved here as a6247ac12, now on SGLang's eager track path.

                                         per-layer path   this PR
radix-track part of a GDN layer (us/layer)    70.0          62.2
binder's KVCacheTensor build (us/forward)    230.9           2.2
  • TTFT: same-process paired A/B, c=1, 22 pairs, QSA part on in both modes. The paired diff median is -4.1 ms at 8192/6080 and -2.3 ms at 10240/7104, with 16/22 pairs faster in each case.

Title and description are updated with the GDN part and these numbers. Lint (black, ruff) is clean. On CPU, test_sglang_gdn_layer_step.py has 24 passed, test_sglang_gdn_replayssm_prefill.py 13 passed, test_sglang_gdn_forward_context.py 19 passed, and test_sglang_gdn_radix_track.py 11 passed with 1 skipped.

cc @valarLip

@valarLip valarLip left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

⚠️ Action required before merge (5)

  1. Split the PR: send the QSA part (2a10bc2f0, ba95fcb35, 2c75761f0) on its own from main, and hold the GDN part (a6247ac12) until #3422 merges. Right now this branch merges #3422 in, and #3422 is still in changes-requested. Merging this PR as it stands would also land #3422's code. The QSA part does not depend on #3422 (your Notes say so), so it can be reviewed and merged by itself.
  2. Remove the SGLang probing from the GDN part. attention_gdn.py:346 _state_slice_accessor compares SGLang methods by identity through getattr(..., None) inside except Exception. _pool_layer_views (:397) and _GDNStep.__init__ (:433) read pool, backend and metadata attributes through getattr(..., None) and silently drop to the per-layer path when one is missing. getattr(forward_context, "step", None) (:1415) guards a dataclass field that always exists. This is the probing we asked you to remove on #3428 and #3429. The underlying cost is SGLang's: MambaPool.State.at_layer_idx builds new views on every call. Fix that in SGLang, or keep one view list built once from the pool (allocated once at startup) and read its attributes directly. Then drop _STATE_SLICE_TYPES and the id()-keyed _POOL_LAYER_VIEWS, which holds strong references and is never pruned.
  3. Keep one extend-track path, not two. _track_extend (:695) is a second copy of the extend half of _track_mamba_states (:631), and _GDNStep.__init__ re-derives the same conditions. The two must stay in sync. Let _track_mamba_states take the per-forward state, so a change in SGLang's track metadata only has to be handled in one place.
  4. Pass kv_slots always, and delete the hand copy of aiter's slot-table contract. qsa_attention.py:743 checks slots.dtype == torch.int32 and k_cache.shape[1] % 4 == 0 and contiguous, with the comment "which is aiter's slot-table contract". The bridge is the only producer of context_slots, and it now always emits int32. It already requires block_size % compress_ratio == 0, and the gate only allows ratio 4. aiter validates dtype and contiguity itself. So the gather branch never runs, and the condition is a copy of an aiter rule. Delete both, plus the int64/strided test cases. Do the same for the pad fallback at :762: on the production path selected is always a view of plan.indices. While you are in _flydsl_call_fallback_reason, don't extend the existing mirrors (2**31, _FLYDSL_WIDTHS). If ATOM needs them before calling aiter, ask aiter to expose a support query.
  5. Drop the getattr defense for test objects, and make the new tests run in CI. qsa_attention.py:239: getattr(qsa, "flydsl_prefill", None) exists only because the tests pass a SimpleNamespace. Use qsa.flydsl_prefill and build a real Qwen4ExpQSAMetadata in the tests. The three new CPU tests in tests/test_qwen4_exp_qsa_flydsl_gate.py are skipped in CI by its module-level importorskip("aiter.ops.enum"), and tests/plugin/test_sglang_gdn_layer_step.py sits under the --ignored tests/plugin. Move the CPU cases somewhere the pre-checkin job runs them.

Minor: qwen4_exp_attn.py:80 says "Not copied by for_tokens", but for_tokens returns self when nothing is trimmed. index_bytes is always 4, so it does not belong in the key. _selection_widths is now computed twice per layer. The test name test_mixed_prefix_batch_gathers_full_contexts is stale. The ci:sglang accuracy jobs are still pending.


Reviewed at a6247ac. Perf (per-layer host time, paired TTFT) and GSM8K numbers are provided. Bit-exact GPU checks are described. The QSA root cause and fix (aiter's existing kv_slots, in-place kernel-width selection) are in ATOM's own host path and are fine in principle. Merges cleanly with #3426/#3428/#3429/#3430.

@valar-cop valar-cop 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.

some changes needed..

ci green.

if self._uses_native_qsa() and (
forward_batch.forward_mode.is_target_verify()
forward_batch.forward_mode.is_extend()
or is_draft_extend_mode(forward_batch.forward_mode, include_v2=True)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

this hunk and gdn_replayssm.py + its tests come from #3422, which is still changes-requested. split the QSA part out and hold this until #3422 merges..

_STATE_SLICE_TYPES: dict[tuple[type, type, type], bool] = {}


def _state_slice_accessor(pool: Any, mamba_pool: Any, state: Any) -> bool:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

remove the getattr probing and both module-level caches, the id()-keyed one never gets pruned. fix at_layer_idx in sglang or build the view list once at startup..

if indices is None:
return None
return indices[: int(forward_batch.batch_size)]
def _track_extend(self, step: _GDNStep, mixed_qkv: torch.Tensor) -> None:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

_track_extend duplicates _track_mamba_states, and the copy already drops the dst fallback. let _track_mamba_states take the per-forward state instead..

if slots is None:
k, v = key.contiguous(), value.contiguous()
elif (
slots.dtype == torch.int32

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

this re-implements aiter's slot-table check and the gather/pad branch cannot run. pass kv_slots when context_slots is not None and delete the fallbacks, ask aiter for a support query instead of the mirrors..

assert len(active) == 1 and len(flydsl) == 3


def test_layout_is_made_once_per_forward(flydsl, monkeypatch):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

these tests never run, importorskip on aiter skips the cpu job and tests/plugin is ignored. move the cpu cases to a module the pre-checkin job collects..

columns,
index_bytes,
)
plan = getattr(qsa, "flydsl_prefill", None)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

the getattr probe only exists for the SimpleNamespace tests. use qsa.flydsl_prefill and build a real metadata in the test..

host_lens: tuple[tuple[int, ...], tuple[int, ...]] | None = None
context_slots: torch.Tensor | None = None
# The forward's FlyDSL attention layout, left by its first QSA layer
# (`qsa_attention._FlyDSLPrefill`). Not copied by `for_tokens`.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

comment is wrong, for_tokens returns self when nothing trimmed. index_bytes is always 4, drop it from the key, and the width is computed twice per layer..

@ZLkanyo009

Copy link
Copy Markdown
Contributor Author

Thanks for the review. All five items and the Minors are addressed. This PR is now split in two:

1. Split. Done as above. Merging #3450 lands no #3422 code.

2. SGLang probing in the GDN part (local, comes with the GDN PR). _state_slice_accessor and _STATE_SLICE_TYPES are gone, and so is the id()-keyed _POOL_LAYER_VIEWS. The per-layer conv and SSM views are now taken once from the state tensors SGLang allocates at startup, reading pool.mamba_pool.mamba_cache.conv[0][i] / .temporal[i] over pool.mamba_map. One view list is held, for the one pool, and it is not keyed by id(). With a HiCache layer_transfer_counter, the per-call pool.mamba2_layer_cache stays, because the per-layer wait lives there. The step reads forward_batch.mamba_track_mask, linear_backend.forward_metadata and the ForwardMetadata fields directly. bind reads forward_context.step directly; the field no longer has a default. No getattr(..., None) or except Exception is added. A CPU test checks the views against SGLang's own MambaPool.State.at_layer_idx slices (pointer, shape, stride). The underlying cost, at_layer_idx building every field's views on each call, would be cheaper to fix in SGLang (cache per-layer views, or return just the requested fields). That is outside this repo, so I did not do it; tell me if you want an upstream SGLang change instead of the one-time view list.

3. One extend-track path. _track_extend is deleted. _track_mamba_states(step, mixed_qkv) is the only track path. _GDNStep holds what is the same for every layer of a forward: the decode or extend decision, the backend, its metadata, and the conv destination slots, including the mamba_track_indices[mask rows] fallback when the backend did not cache conv_states_mask_indices (the fallback the copy had dropped). bind builds the step once, and a layer with no step bound for its batch builds one the same way.

4. QSA kv_slots (#3450, c547285eb). kv_slots=context_slots is passed whenever context_slots is not None. The hand copy of aiter's slot-table rule, the gather branch, the pad branch, and the int64 / strided tests are deleted. forward builds the layout before selecting, so the selection is always written into the kernel-width buffer. The 2**31 and _FLYDSL_WIDTHS checks are not extended: the byte check is now a plain int32 term, and there is no new mirror. A support query from aiter (does this width / row count / dtype take the FlyDSL path) would let ATOM drop both; that is a suggestion for aiter.

5. Tests.

  • getattr(qsa, "flydsl_prefill", None) is gone: the code reads qsa.flydsl_prefill, and the tests build a real Qwen4ExpQSAMetadata.
  • The QSA CPU cases moved to tests/model_ops/test_qsa_flydsl_prefill_host.py (17 cases). It imports through atom_without_aiter, with no module-level importorskip.
  • The first CI run showed the runner has no einops, which qwen4_exp_attn imports through gdn_attn. tests/aiter_stub.py now stands it in where it is not installed (844a4855f).
  • The GDN step tests move to tests/test_sglang_gdn_layer_step.py (in the GDN PR). It does not need SGLang; only the at_layer_idx comparison skips without it.

Minor.

  • The qwen4_exp_attn.py comment now says that for_tokens returns a copy without the layout when it trims rows, and the same object, layout included, when it trims nothing.
  • index_bytes is dropped from the key.
  • _selection_widths runs once per forward, inside the layout (a test counts it over 12 layers).
  • The test is renamed test_mixed_prefix_batch_reads_full_contexts_through_the_slot_table.

Verification (QSA part, #3450 head, MI308X):

  • Bit for bit on GPU against main: 8 cases × 2 layers (8192/6080, 10240/7104, 4 requests with 6080 cached each, a second chunk, three unaligned prefixes, two short contexts, no prefix). Every output and every selection is torch.equal to main's path.
  • Host time of the FlyDSL part per QSA layer: 136.3 → 94.2 µs (8192/6080), 135.7 → 94.1 µs (10240/7104), 137.7 → 94.8 µs (4 requests). aiter's own entry is about 87 µs of that.
  • CPU module: 17 passed, both with aiter and with aiter, SGLang and einops all blocked (the CPU job's environment).
  • GPU tests (gate, host and graph padding): 104 passed.
  • GDN rework (local): the GDN plugin tests and the new step module give 156 passed on GPU. The one failure there, test_extend_metadata_keeps_states_only_when_tracking, fails the same way on the unchanged base (a CPU tensor reaches Triton). The new step module passes 18 with 1 skip in the CPU-job emulation.

cc @valarLip

@ZLkanyo009

Copy link
Copy Markdown
Contributor Author

Closing this as split per the review:

cc @valarLip

@ZLkanyo009 ZLkanyo009 closed this Nov 17, 2026
zhuyuhua-v pushed a commit that referenced this pull request Nov 18, 2026
…3422)

* perf(sglang/gdn): park the ReplaySSM cursor once per prefill forward

A prefill rewrites each request's GDN checkpoint, so the plugin parks the
ring cursor of its slot at 0. It did so at the end of every GDN layer, and
`slot_idx[slot_idx >= 0]` reads the live-slot count back to the host, so a
Qwen3.8-Flash prefill (36 GDN layers) took 36 blocking D2H reads, each one
draining the GPU queue before the host could launch the next layer.

The cursor is one per slot, shared by every layer, and nothing reads it
during an extend forward. Park it once per forward in
`SGLangGDNForwardContext._build_gdn_metadata`, the counterpart of Native's
`GDNAttentionMetadataBuilder._attach_replayssm`, and route pad rows to a
spare trailing entry instead of filtering them with a boolean mask, so the
reset issues no host read. The parked value stays 0 and the slots are the
same rows of SGLang's `mamba_cache_indices`.

Co-authored-by: Cursor <[email protected]>

* perf(sglang/gdn): take the extend token count from SGLang's host metadata

`_build_gdn_metadata` sized the extend metadata with
`int(query_start_loc[-1].item())`, one blocking D2H per prefill.
`HybridLinearAttnBackend._forward_metadata` builds that same
`query_start_loc` from `extend_start_loc` / `extend_seq_lens` and stores the
host sum of `extend_seq_lens_cpu` next to it as `logical_num_tokens`, which
is the same number. Use it, and keep the device read only when SGLang left
it unset or the metadata had to be reconstructed.

Co-authored-by: Cursor <[email protected]>

* perf(sglang/qwen4-exp): skip FlashInfer MHA extend tables under native QSA

`ATOMAttnBackendForSgl.init_forward_metadata` already skipped the MHA
tables for TARGET_VERIFY and draft-extend under native QSA, but an extend
still went through `_init_extend_mha`. That gathers `kv_indices` over the
whole context and syncs on `kv_indices[token_num:]` in SGLang's
`AiterIndicesUpdaterPrefill`, once for the target prefill and once more for
the draft prefill (the draft runner's extend), and QSA reads none of it:
the QSA layers take their tables from the plugin's QSA metadata, and no
other reader of this backend's `forward_metadata` runs during an extend.
Take the same placeholder for every extend.

Co-authored-by: Cursor <[email protected]>

* perf(sglang/gdn): write radix-track extend snapshots in one launch

The mamba radix cache extend snapshot per GDN layer was a conv-window
gather + index_put in the plugin, then h[src] + cast + index_put (and a
slot-to-slot copy for aligned rows) in SGLang's
_track_mamba_state_extend: five to seven small kernels per layer per
prefill.

write_radix_track_snapshots performs the same copies from the same
SGLang track metadata in one Triton launch, addressing every tensor by
its real strides (transposed conv pool, VK SSM view, column slice of the
fused projection) and casting h to the pool dtype as the eager path
does. Recompute rows (Mamba2 only), non-4-D h and CPU tensors keep the
eager path. SGLang is not modified.

Tests compare the pools bit for bit against the eager path across pool
views and target mixes, and check the single launch.

Co-authored-by: Cursor <[email protected]>

* perf(sglang/gdn): split the radix-track launch into a per-forward plan

The track rows, their slots, the conv window length and the grid's row
count of write_radix_track_snapshots come from SGLang's forward metadata
and are the same for every GDN layer of a forward. RadixTrackPlan holds
that half (built once per forward by the caller); write() adds the
layer's conv input, pools and chunk states and launches the same kernel
with the same arguments. write_radix_track_snapshots keeps its signature
and now builds a plan and writes it.

fused_track_metadata_supported is the metadata half of
fused_track_supported, so a forward can decide it once.

Co-authored-by: Cursor <[email protected]>

* perf(sglang/gdn): derive the GDN wrapper's per-layer state once per forward

After its compute every SGLangGatedDeltaNet layer re-derived the same
forward-level state: the forward mode, the SGLang attention backend and
its linear child, the track metadata, the conv destination slots and the
radix-track launch arguments, and it asked SGLang's mamba pool for its
layer views, which builds a new MambaPool.State dataclass on every call
(at_layer_idx). The forward-context binder asked for all of them again.

- _GDNStep: built once in SGLangGDNForwardContext.build from the same
  forward batch and linear backend, published by bind for that forward
  batch. A layer whose forward batch has a step takes _track_extend, which
  only pops its chunk states and writes the precomputed RadixTrackPlan.
  Unusual metadata (recompute rows, missing SSM indices or conv slots),
  decode, and forwards without a step keep the per-layer path.
- _mamba_layer_cache: a layer's mamba2_layer_cache views are reused while
  the pool holds the same state object and layer map. Only SGLang's own
  HybridReqToTokenPool / MambaPool.State accessor is cached, and never with
  a HiCache transfer counter, whose per-layer wait lives in the accessor.
  _build_kv_cache_tensors reuses its KVCacheTensors on the same terms.

Same reads, same kernels, same arguments; the pools are written byte for
byte as before.

Co-authored-by: Cursor <[email protected]>

* test(sglang/gdn): cover the forward-level GDN step and the pool view reuse

- test_sglang_gdn_layer_step.py (CPU): layer views are reused while the
  SGLang pool keeps its state object and are rebuilt for a new one; a
  HiCache transfer counter, a foreign pool or an overridden accessor asks
  every time; the binder's KV tensors are the views SGLang builds; which
  forwards get a precomputed plan and which keep the per-layer path; a
  layer only uses the step of its own forward batch; bind scopes the step.
- test_sglang_gdn_radix_track_fused.py (GPU): the forward-level path
  writes the same bytes as the per-layer path over several layers that
  share one step, and a reused plan matches the one-shot call.

Co-authored-by: Cursor <[email protected]>

* test(sglang/gdn): give the fused-track test's mode stub is_target_verify

Co-authored-by: Cursor <[email protected]>

* revert(sglang/gdn): drop the radix-track plan and the GDN step from this PR

Reverts f12cdd0, 723ade6, a662c62 and 4980bc0. The radix-track plan
(S3) only exists to feed the fused track kernel, which leaves this PR in the
next commit. The forward-level GDN step and the pool view reuse (S4/S6) move
to #3433 on the eager track path.

Co-authored-by: Cursor <[email protected]>

* revert(sglang/gdn): drop the fused radix-track kernel

Reverts f2ca56a. A same-process paired A/B on the issue #576 SGLang
command shows no TTFT gain from the one-launch track snapshot over the eager
index_put + SGLang `_track_mamba_state_extend` (numbers in the PR). The
eager path keeps the copies in SGLang's own helper, so a change in its track
metadata cannot silently diverge in ATOM.

Co-authored-by: Cursor <[email protected]>

* fix(sglang/gdn): park the ReplaySSM cursor on the reconstructed-metadata path too

The extend park read the live slots before the reconstruct_linear_metadata
fallback, so a forward without SGLang's GDN metadata never parked the cursor
(as on main). Take the slots after the fallback, and import sglang lazily in
the park test like the other plugin tests.

Co-authored-by: Cursor <[email protected]>

* fix(sglang/gdn): read SGLang's logical_num_tokens instead of probing for it

`_build_gdn_metadata` took the extend token count from
`getattr(fm, "logical_num_tokens", None)` and fell back to
`query_start_loc[-1].item()`. `logical_num_tokens` is a declared
`ForwardMetadata` field (SGLang v0.5.21 on; the release image runs
v0.5.22), and SGLang sets it for every extend, so the probe only hid a
too-old SGLang and would quietly bring back the sync this PR removes.

Read `fm.logical_num_tokens` in the branch that has SGLang's metadata.
Only the `reconstruct_linear_metadata` path, which has no host count,
still reads `query_start_loc[-1]` back. `live_slots = idx` is assigned
once, after the branch.

The test stand-ins for `ForwardMetadata` now carry the field, set to
what SGLang computes for them. The token-count test's second case is the
reconstructed path instead of an unset field.

Co-authored-by: Cursor <[email protected]>

* refactor(sglang/gdn): drop the None slot path of note_full_state_write

Its only caller, the extend branch of `_build_gdn_metadata`, always has
the slot tensor. The per-layer `_verify_cache_slots` that could return
None went away with the per-layer park.

Co-authored-by: Cursor <[email protected]>

* test(sglang/gdn): pin which forward modes park the ReplaySSM cursor

The removed per-layer `is_draft_extend_v2()` guard now rests on SGLang's
`is_extend()` leaving DRAFT_EXTEND_V2 out. The mode test covers that
case, and MIXED as a mode that parks.

The module docstring no longer points at Native's `_attach_replayssm`,
which parks at -1 with a boolean mask; `note_full_state_write` already
says why the plugin parks at 0.

Co-authored-by: Cursor <[email protected]>

* test(sglang/qwen4-exp): import ForwardMode lazily in the native-QSA skip test

Same as the ReplaySSM prefill test: the other plugin tests import SGLang
inside the test, not at module level.

Co-authored-by: Cursor <[email protected]>

---------

Co-authored-by: Cursor <[email protected]>
Co-authored-by: root <[email protected]>
valarLip pushed a commit that referenced this pull request Nov 19, 2026
…ot table and select at the kernel width (#3450)

* perf(sglang/qwen4-exp): QSA FlyDSL prefill reads K/V in place and selects at kernel width

Under SGLang (page 64) each QSA layer of an eager prefill took the aiter
FlyDSL sparse attention through a host path that repeated per layer what
is the same for the whole forward, and copied data the kernel can read
where it is:

- K/V: with a prefix, each layer index_selected the whole context's K and
  V rows out of its paged pool. aiter's qsa_sparse_prefill reads a token
  pool in place through a slot table (kv_slots) when every four-token
  block of a request sits in four consecutive pool rows starting at a
  multiple of four, which a page size divisible by four guarantees (the
  bridge already requires the page to be divisible by the compress
  ratio, 4). The bridge now emits the context rows as int32, the slot
  table's type; the layer passes the pool and the table. aiter documents
  the result as the same as for the packed rows.
- Selection: each layer padded its selection with -1 to the kernel width
  (a copy, also when the width already matched). The first layer of the
  forward now allocates one kernel-width buffer filled with -1, and every
  layer's selection writes its leading columns in place; the columns past
  the selection are never written, so they stay -1.
- Checks: the flag, the layer support check, the per-call checks, the
  width and the per-request prefix lengths are made once per forward
  (_FlyDSLPrefill, kept on the forward's QSA metadata, keyed by
  everything they read from the layer and its inputs).

Native ATOM, whose metadata has no FlyDSL layout, keeps its path.

Co-authored-by: Cursor <[email protected]>

* test(qwen4-exp): QSA FlyDSL prefill layout, in-place reads and kernel-width selection

- One layout per forward (checks and prefix lengths made once), a new one
  for another row count.
- The kernel-width selection buffer reaches the kernel as is, -1 past the
  selection, reused by a second layer.
- With a prefix the pool and the bridge's int32 slot table go to the
  kernel; int64 rows or a strided pool are gathered as before.
- GPU: the real kernel on the slot table and the in-place selection gives
  the same bits as gathered rows and a padded copy (hit, second chunk,
  mixed unaligned prefixes, short, no prefix).
- The bridge's context rows are int32 and contiguous.

Co-authored-by: Cursor <[email protected]>

* test(qwen4-exp): sharded QSA selection written into the kernel-width buffer

The sequence-parallel path expands the all-gathered groups itself; into a
column prefix of the kernel-width buffer it writes the same columns as
into a fresh tensor and leaves -1 past them (GPU).

Co-authored-by: Cursor <[email protected]>

* perf(qwen4-exp): QSA FlyDSL prefill always reads K/V through the slot table

Review of #3433. The bridge is the only producer of `context_slots`, always
as int32, and already requires a page size divisible by the compress ratio,
so `kv_slots` is passed whenever there are context rows; aiter validates the
slot table itself. The gather branch and the hand copy of aiter's slot-table
rule go away. So does the pad fallback: `forward` builds the layout before
the selection and writes it into the kernel-width buffer, which is what the
kernel gets.

The layout is now looked up once per layer in `forward` (no second lookup in
`_flydsl_attention`), computes the selection width itself (once per forward
instead of once per layer), reads `qsa.flydsl_prefill` directly, and no
longer keys on the index size, which is always int32. The metadata comment
now says what `for_tokens` does with the layout.

Co-authored-by: Cursor <[email protected]>

* test(qwen4-exp): run the QSA FlyDSL host cases in the CPU job

The CPU cases of `tests/test_qwen4_exp_qsa_flydsl_gate.py` were skipped by
its module-level `importorskip("aiter.ops.enum")`. They move to
`tests/model_ops/test_qsa_flydsl_prefill_host.py`, which imports the model
code through `atom_without_aiter` and builds a real `Qwen4ExpQSAMetadata`
per forward. The int64 / strided gather cases go with the branch they
covered. The gate module keeps the GPU cases; its bit-for-bit reference is
now the kernel called directly on gathered rows and a padded selection.

Co-authored-by: Cursor <[email protected]>

* test: stand in einops for model code imported without AITER

The CPU job installs no einops (ATOM does not depend on it), and
`qwen4_exp_attn` reaches it through `gdn_attn` -> `attention_gdn`, so the new
QSA host cases errored at setup there. `stubbed_external_kernel_modules` now
serves it like aiter and triton, only where it is not installed, so a host
with einops keeps the real one.

Co-authored-by: Cursor <[email protected]>

* build: declare einops; drop its test stand-in

Review of #3450. Model code imports einops at module level (`attention_gdn`,
`fla_ops/chunk`, `qwen3_next`, `kimi_k3/model`, ...), but it was not a
declared dependency, so the CPU job, which installs ATOM through pip, had
none. Declare it (the image ships 0.8.2) and drop the einops branch that
844a485 added to `tests/aiter_stub.py`, which is back to its earlier form.

Co-authored-by: Cursor <[email protected]>

* refactor(qwen4-exp): reference aiter's support query at the QSA mirrors

Review of #3450. The FlyDSL selection widths and the 2**31-byte check
mirror aiter's `qsa_sparse_prefill`; each mirror now points to
ROCm/aiter#8083, which exposes them as `qsa_sparse_prefill_widths()` and
`qsa_sparse_prefill_supports_selection()`, and goes once it lands.

`_FlyDSLPrefill` keeps its row count as `rows` instead of reading it back
from the key, and its docstring says why the host lengths may stay out of
the key: the layout lives on one forward's metadata, which the bridge builds
anew each forward, and a trimming `for_tokens` drops it.

Co-authored-by: Cursor <[email protected]>

* refactor(qwen4-exp): make the selection-width helper public for the QSA layout

Self-review of #3450. `qsa_attention` imported the private
`_selection_widths` from `qwen4_exp/ops/qsa.py` to size the kernel-width
selection buffer before selecting. It is now `qsa_selection_widths`; its two
callers in `ops/qsa.py` and the host test's spy follow, and nothing else
used it.

`_FlyDSLPrefill`'s docstring now names everything the layout reads from the
forward's metadata and keeps out of the key (the host lengths, plus the block
table width and longest sequence behind the selection width), and the comment
in `forward` no longer describes the code this PR replaced. No behavior
change.

Co-authored-by: Cursor <[email protected]>

* docs: ATOM_QSA_FLYDSL_ATTN reads prefixed K/V in place

Self-review of #3450. The variable's row still said prefixed chunks gather
their requests' full-context K/V from the paged cache once per layer; with
this PR they read it in place through the bridge's slot table.

Co-authored-by: Cursor <[email protected]>

* qwen4_exp: QSA FlyDSL prefill asks aiter for its widths, selection limit and GPU

aiter.ops.qsa answers the selection widths, the selection byte limit and
whether the kernel runs on this GPU (ROCm/aiter#8083), so the layer and the
SGLang bridge ask it instead of mirroring them: _FLYDSL_WIDTHS, the 2**31-byte
check and the gfx942 check go.

* qwen4_exp: name the QSA selection width; correct the 67-column test docstring

The selection's own width is selection_width, not columns. A 40-token context
reaches 10 groups, rounded up to a power of two: 16, so 67 columns.

* qwen4_exp: call aiter's qsa_sparse_prefill directly; document the #8083 query

aiter.ops.qsa is imported at module level now, so the lazy
_flydsl_attention_op() wrapper has no reason left: qsa_sparse_prefill joins
that import and the layer calls it; the tests patch that name.

The ATOM_QSA_FLYDSL_ATTN row described the old mirrored rules (non-gfx942,
fixed budgets, a padded selection's 2**31 bytes) and ROCm/aiter#6576. It now
says the layer falls back where aiter reports no widths, has none for the
budget, or rejects the selection, and that every import needs ROCm/aiter#8083.

* qwen4_exp: ATOM_QSA_FLYDSL_ATTN names ROCm/aiter#8083; test the forward's selection wiring

The envs.py comment still said gfx942 and ROCm/aiter#6576. aiter reports where
the kernel runs (qsa_sparse_prefill_widths()), and qsa_attention imports its
queries at module level, so every import needs ROCm/aiter#8083, flag on or off.

test_forward_selects_into_the_kernel_buffer runs Qwen4ExpAttention.forward on
a prefill with spies for the selection ops and the kernel, whole and
sequence-parallel: the layout is made, the selection is written into its
kernel-width buffer (out=, out[:, :width] when sharded), and the kernel reads
that buffer.

---------

Co-authored-by: root <[email protected]>
Co-authored-by: Cursor <[email protected]>
zhuyuhua-v pushed a commit that referenced this pull request Nov 24, 2026
…pool views (#3516)

* build: declare einops

The same one-line change as fd34b78 on #3450. Model code imports einops at
module level (`atom/model_ops/attention_gdn.py`, `fla_ops/chunk.py`, ...), but
it is not a declared dependency, so the CPU job, which installs ATOM through
pip, has none, and a test that imports the SGLang GDN wrapper cannot be
collected there. The image ships einops 0.8.2.

* perf(sglang/gdn): derive the GDN wrapper's per-layer state once per forward

Split out of #3433 at review (a6247ac there, with the changes its review
asked for); #3422, which it builds on, is on main now.

After its compute, every GDN layer re-derived the forward mode, SGLang's
linear backend, the radix-track metadata and the conv destination slots, and
asked the mamba pool for its views through `mamba2_layer_cache`, where
`MambaPool.State.at_layer_idx` builds a new view of every state field on each
call. The binder did the same for every mamba layer on every forward.

- `_GDNStep(forward_batch)` holds what every layer of one forward reads after
  its compute: verify or not, decode track, the backend and its track
  metadata, the conv source rows and destination slots.
  `SGLangGDNForwardContext.build` makes one and `bind` publishes it through a
  ContextVar for the forward batch it was built from; a layer whose batch has
  no bound step builds its own.
- `_track_mamba_states(step, mixed_qkv)` stays the one track path. The
  snapshot writes are unchanged: the conv window `index_put` and SGLang's
  `_track_mamba_state_extend`, in the same order.
- `_layer_states` gets the layer's pool index from SGLang's
  `mamba2_layer_index`, which also holds the HiCache per-layer transfer wait,
  and returns views taken once from the state tensors SGLang allocates at
  startup (`pool.mamba_pool.mamba_cache`). The binder's KV tensors are built
  from the same views.

Same pool bytes as main for 12 track-row / SSM-view cases over 36 layers,
through SGLang's real `_track_mamba_state_extend` and `MambaPool` state
(MI308X). Host time of one GDN layer's track 80.2 -> 62.7 us, of the
binder's KV tensor build 461 -> 38 us per forward.

Tests: `tests/test_sglang_gdn_layer_step.py` runs in the CPU job (imports
through `atom_without_aiter`; only the comparison with SGLang's own accessor
needs SGLang and skips without it). The `tests/plugin` doubles of the pool,
the forward batch and the forward context get the fields the wrapper now
reads directly.

* fix(sglang/gdn): refresh cached layer views when mamba state is rebound

Keep both pool and mamba_cache identity in the layer-view cache. Rebinding
state on an existing pool now returns slices of the replacement tensors;
a new pool sharing the same state still gets its own layer mapping.
The per-layer HiCache transfer wait remains on every lookup.

CPU validation: 21 passed, 1 skipped. Removing either identity guard
fails its corresponding regression test. Black, Ruff, and diff checks pass.
ZLkanyo009 added a commit that referenced this pull request Dec 3, 2026
…f transposing h (#3432)

* perf(sglang/gdn): park the ReplaySSM cursor once per prefill forward

A prefill rewrites each request's GDN checkpoint, so the plugin parks the
ring cursor of its slot at 0. It did so at the end of every GDN layer, and
`slot_idx[slot_idx >= 0]` reads the live-slot count back to the host, so a
Qwen3.8-Flash prefill (36 GDN layers) took 36 blocking D2H reads, each one
draining the GPU queue before the host could launch the next layer.

The cursor is one per slot, shared by every layer, and nothing reads it
during an extend forward. Park it once per forward in
`SGLangGDNForwardContext._build_gdn_metadata`, the counterpart of Native's
`GDNAttentionMetadataBuilder._attach_replayssm`, and route pad rows to a
spare trailing entry instead of filtering them with a boolean mask, so the
reset issues no host read. The parked value stays 0 and the slots are the
same rows of SGLang's `mamba_cache_indices`.

Co-authored-by: Cursor <[email protected]>

* perf(sglang/gdn): take the extend token count from SGLang's host metadata

`_build_gdn_metadata` sized the extend metadata with
`int(query_start_loc[-1].item())`, one blocking D2H per prefill.
`HybridLinearAttnBackend._forward_metadata` builds that same
`query_start_loc` from `extend_start_loc` / `extend_seq_lens` and stores the
host sum of `extend_seq_lens_cpu` next to it as `logical_num_tokens`, which
is the same number. Use it, and keep the device read only when SGLang left
it unset or the metadata had to be reconstructed.

Co-authored-by: Cursor <[email protected]>

* perf(sglang/qwen4-exp): skip FlashInfer MHA extend tables under native QSA

`ATOMAttnBackendForSgl.init_forward_metadata` already skipped the MHA
tables for TARGET_VERIFY and draft-extend under native QSA, but an extend
still went through `_init_extend_mha`. That gathers `kv_indices` over the
whole context and syncs on `kv_indices[token_num:]` in SGLang's
`AiterIndicesUpdaterPrefill`, once for the target prefill and once more for
the draft prefill (the draft runner's extend), and QSA reads none of it:
the QSA layers take their tables from the plugin's QSA metadata, and no
other reader of this backend's `forward_metadata` runs during an extend.
Take the same placeholder for every extend.

Co-authored-by: Cursor <[email protected]>

* perf(sglang/gdn): write radix-track extend snapshots in one launch

The mamba radix cache extend snapshot per GDN layer was a conv-window
gather + index_put in the plugin, then h[src] + cast + index_put (and a
slot-to-slot copy for aligned rows) in SGLang's
_track_mamba_state_extend: five to seven small kernels per layer per
prefill.

write_radix_track_snapshots performs the same copies from the same
SGLang track metadata in one Triton launch, addressing every tensor by
its real strides (transposed conv pool, VK SSM view, column slice of the
fused projection) and casting h to the pool dtype as the eager path
does. Recompute rows (Mamba2 only), non-4-D h and CPU tensors keep the
eager path. SGLang is not modified.

Tests compare the pools bit for bit against the eager path across pool
views and target mixes, and check the single launch.

Co-authored-by: Cursor <[email protected]>

* fix(sglang/gdn): keep only the most recent FlyDSL prefill schedules

`_flydsl_prefill_metadata` memoizes AITER GDN prefill schedules by
(lengths, query_start_loc data_ptr, _version). An AITER schedule holds a
strong reference to its offset tensor and is only usable with that exact,
unmodified tensor, outside graph capture. SGLang builds a fresh
query_start_loc for every eager extend, so every prefill forward added an
entry that could never hit again and pinned three small device tensors
for the lifetime of the server.

Bound the memo to the 8 most recently used entries, the same policy as
FLA's `tensor_cache`. Reuse of an unchanged buffer still hits; an evicted
entry only drops the cache's reference, the in-flight forward keeps its
own.

Co-authored-by: Cursor <[email protected]>

* perf(gdn): run FlyDSL GDN prefill under ReplaySSM

`select_policy` turned off both FlyDSL GDN stages once ReplaySSM was on,
so every MTP deployment (ReplaySSM defaults on with speculative decoding,
Native and SGLang alike) fell back to the Triton chunked prefill. Only
FlyDSL decode conflicts with ReplaySSM: it needs the state pool stored as
VK, while the ReplaySSM kernels address a contiguous KV checkpoint.
FlyDSL prefill reads the initial state through the pool's strides, returns
the final state as a logical KV view that the layer writes back with the
same index_copy_ as the Triton path, and writes no records, so it leaves
exactly the checkpoint ReplaySSM expects.

Keep decode off under ReplaySSM and let prefill follow
ATOM_GDN_PREFILL_BACKEND as it does without the ring: drop the ReplaySSM
gates in select_policy, the Native GDN layer and Qwen4Exp finish_prefill.
The SGLang plugin picks the policy up unchanged; its gfx942 gate stays.
ATOM_GDN_PREFILL_BACKEND=triton restores the previous dispatch.

Co-authored-by: Cursor <[email protected]>

* perf(gdn): let write_state_checkpoints read a VK-stored h

The checkpoint writer read `h` as contiguous KV and silently misread
anything else. FlyDSL stores its chunk states VK, so its prefill copies
the whole `h` (about 100 MB per layer at 8192 tokens, TP2) into KV only
for this writer, and SGLang's radix track, to pick a few rows out of it.

Take `h` as a logical [..., H, K, V] tensor stored KV or VK, read off its
strides the way the pool's layout already is (STATE_VK). When `h` and the
pool store the state the same way, the copy walks storage order on both
sides; otherwise it walks the KV side and remaps the other, as the RTP
checkpoint writer does. Any other inner layout raises instead of being
read as KV. KV sources (the Triton `h`, `h_snap`) take the same path as
before.

No caller passes a VK `h` yet; the FlyDSL wrapper follows separately.

Co-authored-by: Cursor <[email protected]>

* perf(sglang/gdn): walk VK order in the radix-track kernel when h and pool are VK

`write_radix_track_snapshots` already reads `h` by its real strides, so a
view over FlyDSL's VK chunk states needs no change to be correct. With
FlyDSL decode the SSM pool is VK as well, and walking logical KV order
then strides both the read and the write. Walk VK order when both sides
store VK: per launch 48 -> 12 us for one unaligned row, 96 -> 20 us for
four (24 heads of 128x128, MI308X). Every other case, including every
launch with a Triton `h`, keeps the existing order.

Tests run the fused kernel and SGLang's eager helper on VK views of `h`
bit for bit, including K != V.

Co-authored-by: Cursor <[email protected]>

* perf(gdn): hand out FlyDSL's chunk states as a KV view, not a copy

`gdn_flydsl.prefill(..., keep_intermediate_states=True)` transposed the
whole VK `h` into a contiguous KV copy in every GDN layer that keeps
snapshots: SGLang's radix track and Native checkpoints, with or without
MTP. That copy is 0.13 / 0.39 / 0.50 ms per layer at 2112 / 6336 / 8192
tokens (TP2, MI308X), and one more `h`-sized allocation at the peak.

Both consumers now address `h` by its strides, so return
`h.transpose(-1, -2)`, the logical KV view of the same storage, the way
the final state is already returned: same shape, same values, same row
per chunk boundary. `snapshot_layout="vk"` is unchanged, and the RTP
wrapper, which asks for it, still gets the VK tensor itself.

Co-authored-by: Cursor <[email protected]>

* perf(sglang/gdn): split the radix-track launch into a per-forward plan

The track rows, their slots, the conv window length and the grid's row
count of write_radix_track_snapshots come from SGLang's forward metadata
and are the same for every GDN layer of a forward. RadixTrackPlan holds
that half (built once per forward by the caller); write() adds the
layer's conv input, pools and chunk states and launches the same kernel
with the same arguments. write_radix_track_snapshots keeps its signature
and now builds a plan and writes it.

fused_track_metadata_supported is the metadata half of
fused_track_supported, so a forward can decide it once.

Co-authored-by: Cursor <[email protected]>

* perf(sglang/gdn): derive the GDN wrapper's per-layer state once per forward

After its compute every SGLangGatedDeltaNet layer re-derived the same
forward-level state: the forward mode, the SGLang attention backend and
its linear child, the track metadata, the conv destination slots and the
radix-track launch arguments, and it asked SGLang's mamba pool for its
layer views, which builds a new MambaPool.State dataclass on every call
(at_layer_idx). The forward-context binder asked for all of them again.

- _GDNStep: built once in SGLangGDNForwardContext.build from the same
  forward batch and linear backend, published by bind for that forward
  batch. A layer whose forward batch has a step takes _track_extend, which
  only pops its chunk states and writes the precomputed RadixTrackPlan.
  Unusual metadata (recompute rows, missing SSM indices or conv slots),
  decode, and forwards without a step keep the per-layer path.
- _mamba_layer_cache: a layer's mamba2_layer_cache views are reused while
  the pool holds the same state object and layer map. Only SGLang's own
  HybridReqToTokenPool / MambaPool.State accessor is cached, and never with
  a HiCache transfer counter, whose per-layer wait lives in the accessor.
  _build_kv_cache_tensors reuses its KVCacheTensors on the same terms.

Same reads, same kernels, same arguments; the pools are written byte for
byte as before.

Co-authored-by: Cursor <[email protected]>

* test(sglang/gdn): cover the forward-level GDN step and the pool view reuse

- test_sglang_gdn_layer_step.py (CPU): layer views are reused while the
  SGLang pool keeps its state object and are rebuilt for a new one; a
  HiCache transfer counter, a foreign pool or an overridden accessor asks
  every time; the binder's KV tensors are the views SGLang builds; which
  forwards get a precomputed plan and which keep the per-layer path; a
  layer only uses the step of its own forward batch; bind scopes the step.
- test_sglang_gdn_radix_track_fused.py (GPU): the forward-level path
  writes the same bytes as the per-layer path over several layers that
  share one step, and a reused plan matches the one-shot call.

Co-authored-by: Cursor <[email protected]>

* test(sglang/gdn): give the fused-track test's mode stub is_target_verify

Co-authored-by: Cursor <[email protected]>

* test(sglang/gdn): run the forward-level track plan tests on a VK h too

Co-authored-by: Cursor <[email protected]>

* revert(sglang/gdn): drop the radix-track plan and the GDN step from this PR

Reverts f12cdd0, 723ade6, a662c62 and 4980bc0. The radix-track plan
(S3) only exists to feed the fused track kernel, which leaves this PR in the
next commit. The forward-level GDN step and the pool view reuse (S4/S6) move
to #3433 on the eager track path.

Co-authored-by: Cursor <[email protected]>

* revert(sglang/gdn): drop the fused radix-track kernel

Reverts f2ca56a. A same-process paired A/B on the issue #576 SGLang
command shows no TTFT gain from the one-launch track snapshot over the eager
index_put + SGLang `_track_mamba_state_extend` (numbers in the PR). The
eager path keeps the copies in SGLang's own helper, so a change in its track
metadata cannot silently diverge in ATOM.

Co-authored-by: Cursor <[email protected]>

* fix(sglang/gdn): park the ReplaySSM cursor on the reconstructed-metadata path too

The extend park read the live slots before the reconstruct_linear_metadata
fallback, so a forward without SGLang's GDN metadata never parked the cursor
(as on main). Take the slots after the fallback, and import sglang lazily in
the park test like the other plugin tests.

Co-authored-by: Cursor <[email protected]>

* Limit ReplaySSM FlyDSL GDN prefill to gfx942; keep RTP-LLM on Triton

Review follow-up for the ReplaySSM FlyDSL prefill switch:

- select_policy enables FlyDSL prefill under ReplaySSM only on gfx942,
  where Native MTP GSM8K and TTFT were measured. Other arches keep the
  Triton prefill under ReplaySSM until they have the same data. Native
  and every select_policy caller get the gate.
- RTP-LLM _configure_gdn_backends keeps Triton prefill when the metadata
  has replayssm set. RTP-LLM does not set it today, so its behaviour is
  unchanged.
- Move the policy matrix to tests/test_gdn_flydsl_policy.py. It loads
  gdn_flydsl.py with Triton stubbed, so the non-GPU unit tests run it
  without AITER or Triton. Cover the gfx942 gate and the arch check.
- Assert that finish_prefill builds the FlyDSL schedule with
  replayssm=True, and builds none when FlyDSL prefill is off.
- GPU tests expect the gate on non-gfx942 devices.

Co-authored-by: Cursor <[email protected]>

* test(sglang/gdn): SGLang's eager radix track reads FlyDSL's KV view of h bit for bit

Co-authored-by: Cursor <[email protected]>

* refactor(gdn): no default for the checkpoint kernel's H_VK; drop a dead stride test

`_copy_checkpoints_kernel` gave the new `H_VK` constexpr a default of False.
Its only caller, `write_state_checkpoints`, always passes it, and a caller
that left it out would read a VK-stored `h` as KV without an error. It now
has no default; it moves ahead of the defaulted constexprs, and the launch
passes every constexpr by keyword.

`write_state_checkpoints` tested `h`'s inner strides for VK with an extra
`!= (k * v, v, 1)` conjunct. That conjunct only changes the answer when
K == V == 1, where the KV and VK layouts are the same and both index maps give
the same address, so it goes, together with two redundant `tuple()` calls. The
docstring no longer explains the refusal by what the writer used to do.

No caller's checkpoint changes: KV sources (the Triton `h`, `h_snap`) still
launch with H_VK=False and FlyDSL's view with H_VK=True.

Co-authored-by: Cursor <[email protected]>

* test(gdn): run the checkpoint writer's layout refusal in the pre-checkin gate

`tests/test_gdn_flydsl_snapshot_layout.py` was meant as the CPU half of this
PR's tests, but both of its cases `importorskip`ped Triton, and "Run non-GPU
unit tests" has none: at 641c147 its log shows them as
"SKIPPED ... GDN prefill requires Triton" and "... GDN checkpoints require
Triton". So CI ran none of the PR's new tests.

- The refusal of an `h` that is neither KV- nor VK-stored is host logic that
  runs before any launch. The test now loads `state_checkpoint.py` from its
  source with Triton stubbed for the import, the way
  `tests/test_gdn_flydsl_policy.py` loads `gdn_flydsl.py`, so the gate runs it.
- The CPU check that the KV snapshot is a view of the kernel's storage is
  removed. It replaced every call inside `prefill` with a stub, looked the RTP
  wrapper up with `getattr`, and was skipped in CI too. The GPU test
  `test_flydsl_kv_snapshot_is_a_view_of_the_vk_snapshot` checks the same
  contract on the real FlyDSL kernel: same values, VK storage, same allocator
  peak.
- A test docstring no longer describes the KV copy as what the view replaces.

Checked with triton, aiter, flydsl and sglang made unimportable and no GPU
visible: the new case passes, and it fails on the base tree, which has no
check (the writer runs on to `triton.cdiv`). The old file, run the same way,
reports the same two skips as CI.

Co-authored-by: Cursor <[email protected]>

* test(gdn): track strided snapshots through the frontend forward

Give the eager-track test the full mamba pool state/index contract and
exercise SGLangGatedDeltaNet.forward instead of its changing private track
argument. Keep the real SGLang eager writer; only the unrelated base GDN
compute is replaced with a supplied output and snapshot. This lets the
same test exercise main and the forward-level step introduced by #3516
without adding a production shim or probing private signatures.

* docs(gdn): require transpose views for VK checkpoints

* docs: clarify GDN snapshot contract and add test licenses

Address review 6041313871: add the requested MIT and copyright headers
to the two new regression tests and identify RTP as the only raw-VK
checkpoint consumer. The shared writer requires the default KV view.

Validation: 3 files syntax-checked; executable AST unchanged; Black,
Ruff, and diff checks pass; CPU snapshot-layout test: 1 passed.
No GPU rerun for these license/docstring-only edits.

---------

Co-authored-by: Cursor <[email protected]>
Co-authored-by: root <[email protected]>
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.

3 participants