Repository navigation
[Triton/Gluon] fp8_mqa_logits: caller-owned and packed output - #7517
Conversation
fp8_mqa_logits allocates its [seq_len, seq_len_kv] fp32 output on every call. A chunked long-context prefill calls it once per chunk and indexer layer with seq_len_kv growing by the chunk size each step, so each call asks the PyTorch caching allocator for a block slightly larger than any it holds: it reserves a new one every step. In ATOM's DCP8 Kimi-K3.1 prefill that ratcheted ~15 GiB of reserved memory in a minute until HBM was exhausted. Add `logits=None`: when given, a [seq_len, seq_len_kv] float32 view with a unit column stride and a row stride of at least seq_len_kv (e.g. a view of a persistent workspace), the kernel writes into it -- only each row's [cu_starts, cu_ends) columns, as before -- and clean_logits fills it. The allocating path is unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
One backend per PR: PR title tags & labels: |
READY FOR HUMAN REVIEWPR Self-ReviewRevision Author self-review accepted. Readiness report: Author answers
Show the author's self-review answersBehavior and intentValidation and unverified scopePR-specific questionChanged op testsPR state
Copilot findings
Code and op-test hygiene
Required CI
Shadow mode reports what would block but keeps the status successful. Set |
There was a problem hiding this comment.
🟡 Changes recommended
Test buffers lack an explicit float32 dtype, so a float64 default causes valid-buffer failures and tests dtype rejection instead of the intended shape and stride validation.
3 open issues
What changed in this PR
This PR lets fp8_mqa_logits reuse a caller-owned output buffer, reducing repeated allocations during chunked prefill. Calls without logits= retain the existing allocation behavior, and the kernels are unchanged.
Changes:
- Add optional output-buffer validation for shape, dtype, strides, and device.
- Support cleaning the supplied view without modifying row padding.
- Add tests for output equivalence, write bounds, and malformed buffers.
| File | Description |
|---|---|
op_tests/triton_tests/attention/test_fp8_mqa_logits.py |
Tests caller-buffer reuse, masking, write bounds, and invalid layouts. |
aiter/ops/triton/attention/fp8_mqa_logits.py |
Adds and documents the optional logits buffer and validates its properties. |
Review effort: Balanced
|
@copilot could you please check if the aligned allocation is necessary for the caller-owned logits buffer? |
No. The 256-column rounding is only used for internally allocated output; it is not required for a caller-owned buffer. The kernels use the passed strides and bound stores to |
valarLip
left a comment
There was a problem hiding this comment.
⚠️ Action required before merge (4)
- Give every float tensor in the new tests an explicit
dtype=torch.float32, and pin each malformed-buffer case to its own error. Inop_tests/triton_tests/attention/test_fp8_mqa_logits.py,plane(L282), therandnforq_fp8(L301), and theshape/pitch/column_stridebuffers (L309-313) use the default dtype, which breaksop_tests/triton_tests/README.mdrule 2. With a float64 default, the three bad-layout cases would hit the dtype check first and still pass. Addmatch=topytest.raises(L316) so each case proves its own branch. These are Copilot's two findings, which you confirmed but have not pushed yet. - Test the layouts the docstring promises, plus the device check. Today only the 256-aligned pitch at storage offset 0 runs. Add a packed non-aligned pitch (
pitch = s_kwith s_k = 113 or 1560). Add a larger pitch at a nonzero offset (for examplealigned + 17, offset 37), with a NaN guard before the view as well as after it. Add a CPU buffer to thebadlist forlogits.device != Q.device(fp8_mqa_logits.py:157), which no test reaches now. This is Copilot's third finding, which you also confirmed. - Name the new argument
out: torch.Tensor | None = None. Sibling ops already use that name:pa_mqa_logits.py:564,sparse_mla.py:711,qsa.py:222andpa_prefill_sparse.py:77.logitsalso shares its name with the return value (docstring L131) and with the local variable. Rename it before ROCm/ATOM#3043 starts to depend on the name. - Fix the docstring. The Returns line
(must be initialized to -inf, because of causal masking)(fp8_mqa_logits.py:131) is wrong whenclean_logits=False. Change it to say "-inf outside each row's range only when clean_logits". Cut the 9-line parameter entry (L119-128) to the contract: shape, dtype, strides, device, andValueErroron a mismatch. Move the allocator rationale to the PR description (Triton README rules 18 and 21).
Checked and correct: the Triton, gfx950 and gfx1250 kernels honor any row stride of at least seq_len_kv and any storage offset. The gfx950 kernel widens stride_logits_s to int64 (_gluon_kernels/gfx950/.../fp8_mqa_logits.py:966), and no kernel writes past column seq_len_kv. CI is green.
Reviewed at d0c586b. Follow-up, not for this PR: flydsl_fp8_mqa_logits calls itself a drop-in for this op, but it has the same per-call allocation and no output argument.
…youts Rename the caller-owned output argument from `logits` to `out`. The sibling ops use `out`, and the FP4 MQA kernels already take `out` and `out_offsets`. Cut the docstring to the contract. The return value is -inf outside each row's range only when `clean_logits` is set. Tests: - Give each float tensor an explicit dtype. - Match each malformed-buffer case to its own error. - Add a CPU buffer case for the device check. - Add a tight pitch (s_k) and a larger pitch at a nonzero offset, with NaN guards before and after the view. Benchmark: use an int64 prefix sum for packed offsets. An int32 sum wraps at long contexts.
| cu_starts, | ||
| cu_ends, | ||
| clean_logits=True, | ||
| out=None, |
There was a problem hiding this comment.
Out of date: ROCm/ATOM#3043 now calls out= / out_offsets= (_score_concat_passes in atom/model_ops/indexer/score.py), and its logits= signature probe is removed. The rename follows the reviewer request to match the sibling ops.
…asses Packed rows (V4.1's layout: `band_offsets`, offset top-k) are now the only FP8 prefill path. The rectangular key-window path, the aiter signature probes and both fallbacks are gone. The probes were already broken: aiter's routed `top_k_per_row_decode` (ROCm/aiter#7850) hides `row_starts` from `inspect.signature`, so packed never ran on current aiter. This needs `fp8_mqa_logits(out=, out_offsets=)` from ROCm/aiter#7517. The key workspace has a fixed size: one request of `max_model_len` plus a step's tokens. A step whose keys exceed it is gathered and scored in passes of whole requests (`concat_passes`). Each pass's rows are split over every DCP rank, so no rank waits on another's share. Under DCP a pass reads this rank's shard into its slot, all-gathers in place and restores key order; `_all_gather_slot` serves this and the selection gather. The old allocating DCP key gather is removed. The plane holds a PCP/DCP rank's share of a step's rows, each up to `max_model_len`, within the logits budget, and is shared with decode. FP4 (one range) and FP8 (passes) build their DCP gather indices with one helper. The pass planner and key workspace live in `indexer/workspace.py` with V4.1's packed helpers and import no aiter, so the CPU job tests them. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Done in 94c1aa9. Item by item:
The benchmark now uses an int64 prefix sum for packed offsets (Copilot's finding). Test run on MI355X: 245 passed. The description has the results. |
valarLip
left a comment
There was a problem hiding this comment.
⚠️ Action required before merge (3)
- Test packed rows with BLOCK_M=2 and a KV split together. No
test_fp8_mqa_logits_packedshape reaches this gfx950 path (_gluon_kernels/gfx950/.../fp8_mqa_logits.py:1121-1128, twoout_offsetsbases plus the split'srow_endsclamp). Today (4097, 1025, 32 heads) gives BLOCK_M=2 with no split, and (9, 65539) gives a split with BLOCK_M=1. Add(1019, 40000)to therows, keyslist (32 heads: BLOCK_M=2, 3 splits), the same shape astest_fp8_mqa_logits_into_caller_buffer. A CPU replay of the address math is correct for this case, so this is a missing test, not a known bug. - State the packed size contract and fix the stale comments.
fp8_mqa_logits.py:124-128: say thatoutmust holdout_offsets[i] + (min(cu_ends[i], seq_len_kv) - max(cu_starts[i], 0))elements for each row. The wrapper does not check this, and it cannot check without a host sync. Returns (L131-132): add "not in packed mode", because packed gaps keep their old values. L140 "Initialize with -inf because of causal masking" now sits above the packed branch. L333: the relaxed-store comment does not mentionpacked. Thelogits_ptr # fp32 [seq_len, seq_len_kv]comments (Triton:25, gfx950:903, gfx1250:596) are wrong in packed mode, andout_offsets_ptrhas no comment. - Small items. Add
out: torch.Tensor | None = None, out_offsets: torch.Tensor | None = None, as item 3 of my previous review asked (the name is fixed, but the type is not). Add@torch.inference_mode()totest_fp8_mqa_logits_rejects_malformed_packed_output(test_fp8_mqa_logits.py:430). Optional: the gfx1250 packed path rebases the pointer on each row, somax_logits_offset(L270-274) can beseq_len_kv - 1instead oflogits.numel() - 1. With the current value, a packed buffer above 2^31 elements does not use buffer stores.
Checked and correct: the Triton, gfx950 (BLOCK_M 1/2, KV split, reversed storage order) and gfx1250 kernels write out[out_offsets[i] + k] for key cu_starts[i] + k, and nothing else. The trailing-block clamp keeps the read of out_offsets[row_id + 1] in bounds. ROCm/ATOM#3043 calls out=/out_offsets=, so Copilot's logits= comment is out of date. CI is green, and one wheel build is still pending.
Re-reviewed at 94c1aa9. Already fixed: explicit float32 test dtypes and per-case match=, aligned/tight/offset layouts with NaN guards and a CPU-device case, rename to out, docstring contract, int64 benchmark prefix sum.
…V split - Docstring: row i needs out_offsets[i] + min(cu_ends[i], seq_len_kv) - max(cu_starts[i], 0) elements of out; the wrapper does not check this. Packed gaps keep their values, so -inf applies only outside packed mode. - Fix the comments above the allocation and the relaxed store, and describe logits_ptr and out_offsets_ptr in the Triton, gfx950 and gfx1250 kernels. - Type out and out_offsets. - Tests: add (1019, 40000) to the packed shapes, which gives BLOCK_M=2 with 3 KV splits on gfx950; run the malformed packed cases in inference mode.
|
Done in 3a50de0:
|
There was a problem hiding this comment.
🔵 Needs a closer look
Human assessment is needed because an unpublished finding identifies a 32-bit kernel stride limitation that can cause incorrect row addressing for valid large-pitch output buffers.
1 open issue
1 resolved since last review
Review effort: Balanced
valarLip
left a comment
There was a problem hiding this comment.
✅ LGTM
Checked and correct at this head: the Triton, gfx950 (BLOCK_M 1/2, KV split, reversed storage order, clamped trailing block) and gfx1250 kernels write out[out_offsets[i] + k] for key cu_starts[i] + k, and nothing else. (1019, 40000) now runs packed BLOCK_M=2 with 3 KV splits on gfx950, and all 8 cases pass on MI35X CI. The docstring states the packed size contract, and the stale comments are fixed. ROCm/ATOM#3043 calls out=/out_offsets=, so Copilot's open logits= comment is out of date. CI is green.
Re-reviewed at 3a50de0. Already fixed: packed BLOCK_M=2 + KV split test shape, packed out size contract and the "not in packed mode" Returns note, stale allocation/relaxed-store/logits_ptr comments, torch.Tensor | None annotations, inference_mode on the malformed-packed test. Deferred by the author (optional): gfx1250 packed max_logits_offset can be seq_len_kv - 1.
…es (#3043) * fix(indexer): keep FP8 prefill index logits and gathered keys in persistent workspaces The FP8 prefill (concat) indexer allocated, per 8K chunk and per indexer layer, buffers sized by the step's context: each band's dense logits inside aiter's fp8_mqa_logits (up to the 2 GiB budget, e.g. 1024 rows x 350K keys = 1.4 GiB per rank under DCP8) and the gathered keys (DCP shard, all-gather output and the de-interleaved copy, ~45 MiB each at 350K). Their size grows every chunk of a long prefill, so the caching allocator never reuses last chunk's block and reserves a new one: Kimi-K3.1-Pro 1P1D DCP8 reserved +15 GiB in a minute until HBM was full, and a hipMalloc that then never returned left the ranks deadlocked in their collectives. The memory profile (an 8K prefill with no history) never reaches these sizes, so the KV budget did not leave room either. - The concat path scores its bands into the builder's LogitsWorkspace (the decode plane, sized for the larger of the two needs) at the pitch aiter pads to, through fp8_mqa_logits(logits=...) when aiter provides it. - Gathered keys live in a ConcatKeyWorkspace held for the server's life and doubled only when a step's keys outgrow it; under DCP the shard is read straight into this rank's slot of the all-gather buffer, gathered in place and de-interleaved with index_select(out=). - Both are allocated before the memory profile, so the KV budget counts them. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(indexer): default logits budget to 1024 MiB * fix(indexer): group prefill requests within fixed workspace capacity * bench(indexer): compare decode scoring under logits budgets * bench(indexer): drop the logits-budget bench script from this PR Keeps the PR within the 15-file limit; the script is a manual GPU bench, not collected by pytest. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(indexer): trim the grouping tests to the CPU unit set Drop the GPU/RCCL grouping tests (skipped in non-GPU CI) and the CPU tests that repeat coverage kept elsewhere: the pack tests live in test_sparse_indexer_chunk.py, per-group banding in the scoring test. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(indexer): keep the logits budget default at 2048 MiB Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(indexer): score each FP8 prefill band against its own requests' keys A concat band's logits row was as wide as the step's keys, every request's together, while the plane is sized for one request of the model length. A legal batch could therefore need a row wider than the plane. 67e1e68 answered that by gathering and scoring requests in groups, but under DCP the query rows stayed split over the whole step, so a group's rows usually belonged to one or two ranks: the others gathered its keys and waited, and scoring ran rank after rank, about 4-6x the critical path on a 3.55M-key Kimi-K3.1 C72 step (host-side cost model). A row only reads its own request's keys. Each band now scores against a window of the gathered keys, the requests its rows belong to (`concat_window_bands`), so its pitch is that window's width. One request is at most the model length, which the plane holds a row of, so no step needs grouping for the logits. Bands pack neighbouring requests while they fit and cut a request whose rows do not. The request grouping is removed: keys are gathered once per step (one DCP all-gather) and every rank scores its contiguous share of the step's rows, as on main. The key workspace grows, with a warning, when a step's keys outgrow it, as before 67e1e68. Bounding that is left to a follow-up. Co-Authored-By: Claude Opus 5.5 <[email protected]> * refactor(indexer): share workspace band execution with V4.1 * feat(indexer): pack FP8 prefill logits in the shared workspace * fix(indexer): pack FP8 prefill rows only and gather keys in bounded passes Packed rows (V4.1's layout: `band_offsets`, offset top-k) are now the only FP8 prefill path. The rectangular key-window path, the aiter signature probes and both fallbacks are gone. The probes were already broken: aiter's routed `top_k_per_row_decode` (ROCm/aiter#7850) hides `row_starts` from `inspect.signature`, so packed never ran on current aiter. This needs `fp8_mqa_logits(out=, out_offsets=)` from ROCm/aiter#7517. The key workspace has a fixed size: one request of `max_model_len` plus a step's tokens. A step whose keys exceed it is gathered and scored in passes of whole requests (`concat_passes`). Each pass's rows are split over every DCP rank, so no rank waits on another's share. Under DCP a pass reads this rank's shard into its slot, all-gathers in place and restores key order; `_all_gather_slot` serves this and the selection gather. The old allocating DCP key gather is removed. The plane holds a PCP/DCP rank's share of a step's rows, each up to `max_model_len`, within the logits budget, and is shared with decode. FP4 (one range) and FP8 (passes) build their DCP gather indices with one helper. The pass planner and key workspace live in `indexer/workspace.py` with V4.1's packed helpers and import no aiter, so the CPU job tests them. Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs(indexer): the logits budget also sizes packed FP8 prefill rows Co-Authored-By: Claude Opus 5.5 <[email protected]> * refactor(indexer): drop dead score_topk keys and split the DCP gather builders - `score_topk(keys=)` and `_score_concat`'s gathered keys lost their only caller with the old DCP gather; both are removed. - `ConcatPass.dcp`, `ConcatKeys.workspace`, `IndexRows.workspace` and `IndexRows.passes` carry their types. Packed concat rows keep their bands in each pass only. - `_build_dcp_indexer_prefill_meta` (a whole step, FP4) and `_dcp_pass_gathers` (FP8 passes) each have one result; both use `_dcp_shard_lengths` and `_dcp_gathers`. - `PackedRows` stays with V4.1, its only user. `cdiv` joins the indexer's shared helpers. Co-Authored-By: Claude Opus 5.5 <[email protected]> * refactor(indexer): name the DCP pass gather and test its index on the CPU - `DcpGather` (`local_total`, `local_cu`, `gather_index`) replaces the anonymous tuple on `ConcatPass.dcp`, and `StagedIndexRows.passes` and the builder's `gathers` carry their types. - The gather index is host arithmetic in `indexer/workspace.py` (`dcp_gather_index`); the builder only uploads it, with `upload_numpy`. A CPU test shards keys over 4 ranks with interleave 2 and checks that each pass's index returns every key once, in order. - `cdiv` comes from `atom.mono.plan.shard`; one `cp_gather` call serves both gather paths. Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs(indexer): the logits budget sizes one band, for decode and FP8 prefill envs.py said the budget sizes only the decode logits workspace. It also sizes the packed FP8 prefill plane, and the workspace takes the larger of the two. plane_capacity and LogitsWorkspace.for_rows return one band of up to `rows` rows, not a plane that holds every band. Zip the passes with their DCP gathers strictly, and build ConcatPass in one call. docs/model_ops_guide.md keeps main's row; the plane is described in environment_variables.md. Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Claude Opus 5.5 <[email protected]>



Motivation
A long chunked prefill calls
fp8_mqa_logitswith more keys in each chunk. The wrapper allocates a new and larger output in each call, so the caching allocator keeps a new and larger block each time. ROCm/ATOM#3043 keeps one output buffer for the life of the server. Packed rows also remove the columns that a row does not see.Technical details
out=: an optional output from the caller. For rectangular output,outis[seq_len, seq_len_kv]float32 onQ.device, with a unit column stride and a row stride of at leastseq_len_kv. A mismatch raisesValueError. Withoutout, the wrapper allocates the output as before.out_offsets=: an optional contiguous[seq_len]int32 or int64 tensor onQ.device. Thenoutmust be a contiguous 1-D float32 buffer. Row i writes its scores for keys[cu_starts[i], cu_ends[i])from elementout_offsets[i]. The rows must not overlap. The kernel does not write other elements, andclean_logitshas no effect.PACKEDconstexpr and an offsets pointer. Withoutout_offsets, they calculate the same addresses as before and compile to the same instructions. Their names gainPACKED_0(for example..._RELAXED_STORE_0_PACKED_0_HAS_KV_SPLIT_1), which shows in traces.Q(seq_len == 0) returns the empty output without a launch. Before, the gfx950 Gluon path raisedZeroDivisionErroron it, and the Triton path already returned the empty output.outis the same as in the sibling ops and in the FP4 MQA kernels (out,out_offsets).--layout allocated|dense|packedand rotating buffers. Packed offsets use an int64 prefix sum.Test plan
op_tests/triton_tests/attention/test_fp8_mqa_logits.pyon gfx950.out, noout_offsets) bit by bit, and the compiled instructions, between main and main with this PR merged.Test results
MI355X (gfx950),
rocm/atom-dev:nightly_202611131030(aiter 43840ae) with this PR at 3a50de0:test_fp8_mqa_logits.py: 253 passed. This includes the 158 existing tests (also the 8 outputs above 2 GiB) and the new tests.clean_logitson and off) give bit-identical outputs, shapes and strides. Every compiled variant (16 Gluon, 5 Triton) has the same instructions. The device time does not change. A launch-bound call of about 30 us takes about 1 us more on the host.clean_logits: allocated 1598, dense 1583, packed 1767 TFLOPS. A packed run with 65536 query rows and 65536 keys completes.Not verified: gfx1250 at run time (compile checks only), and gfx942 at this revision (an earlier revision: 204 passed on MI308X).
PR Self-Review
Reviewed revision
3a50de0
Behavior and intent
fp8_mqa_logitscan write into a buffer from the caller (out), as a rectangular view or as packed rows (out_offsets). Calls without these arguments give the same results with the same instructions. They differ only in the kernel names (PACKED_0) and in an emptyQ, which now returns the empty output on every path. Before this PR, each call allocated its output, and the size followed the key count. A caller with a key count that grows in each call could not reuse a block, so reserved memory increased until the GPU had no free memory.Validation and unverified scope
See "Test results". Command:
python -m pytest -q op_tests/triton_tests/attention/test_fp8_mqa_logits.pyin the container above, one MI355X. gfx1250 is compiled but not run. gfx942 is not run at this revision.PR-specific question
Without this PR, the new tests fail at the call, because
outandout_offsetsdo not exist. The existing tests only call the allocating path. They do not cover a caller buffer with a different pitch or offset, packed rows, writes outside each row's range, or the validation errors.Changed op tests
op_tests/triton_tests/attention/test_fp8_mqa_logits.py: caller buffers with an aligned pitch, a tight pitch and a larger pitch at a nonzero offset, with NaN guards; one test for each validation error (shape, stride, dtype, device); packed rows with int32 and int64 offsets, reversed storage order, empty rows and guards. Not redundant: no other test calls these arguments.op_tests/op_benchmarks/triton/bench_fp8_mqa_logits.py: the three output layouts with rotating buffers. Not redundant: the old benchmark only measured the allocating path.