Skip to content

[CUDA] Share Ring staging over private owner KV rows - #25422

Open
Gasoonjia wants to merge 19 commits into
pytorch:gasoonjia/runtime-columns-abi2-pr1from
Gasoonjia:shared-ring-staging-pr2
Open

Gasoonjia wants to merge 19 commits into
pytorch:gasoonjia/runtime-columns-abi2-pr1from
Gasoonjia:shared-ring-staging-pr2

Conversation

@Gasoonjia

@Gasoonjia Gasoonjia commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Builds on #25621. Each session gets an independently sized KV span that grows on demand, and Ring layers share staging for the current forward instead of reserving write headroom per session. This reduces GPU memory use when session lengths differ and at high concurrency; host undo history preserves Ring clone/rewind behavior.

Opt in with --private-kv-rows for CUDA solo, text-only BF16 batching. Tests cover private-row growth, shared staging, clone/rewind, memory bounds, and CUDA graph replay. Numerical and performance qualification is still in progress.

Authored with OpenAI Codex assistance.

Decouple sequence IDs from physical storage columns so the
batched-sequence cache can start with 2 physical columns and grow or
shrink at runtime instead of always allocating max_seqs + 1 columns.

- CudaKVPool gains resize_columns() with declared vs physical column
  counts, transactional replacement copies, and binding invalidation on
  column moves (mirroring grow()).
- CudaBatchedSequenceCache tracks IDs and physical columns separately,
  uploads a 5-wide seq_info whose last field is the runtime pitch, and
  adds ensure_columns()/compact_columns() behind an inflight guard.
- The lowering pass gains manifest version 2 with runtime_columns, the
  SDPA kernel reads the runtime pitch via INFO_WIDTH, and CudaExecutor
  reads get_offgraph_kv_sequence_info_abi (1 or 2) from the program.
- ABI-1 behaviour is unchanged: the new paths are gated on
  CacheConfig::runtime_sequence_columns and manifest version 2.

Tests: extended test_cuda_kv_cache and
test_offgraph_kv_batched_sequence, plus an opt-in Muse-Glimmer
runtime KV probe. The SDPA ring-scan logic from the experiment patch
was intentionally not ported: main's ring handling is kept and only
the runtime-pitch change is included.

This is PR 1 of the runtime-columns series; per-owner capacities
(ABI 3) build on the ID/column split introduced here.
- Revert the unrelated O0 -> O2 change in export_solo.py.
- Recover a prepared-but-uncommitted ABI-2 step in the next
  prepare_step (fence all streams, then clear inflight_) instead of
  wedging the cache until clear() drops every sequence; add a
  regression test.
- Grow physical columns geometrically and trim the allocator only on
  the compact path, avoiding one full KV copy per admission.
- Reject runtime columns + DFlash in CudaExecutor and in the
  batched-sequence cache factory.
- Gate the seq_clone fence/poison on runtime columns so ABI-1 clone
  failures are unchanged; refuse seq_rm for a declared sequence in
  both ABIs.
- Fix the lintrunner CMake formatting failure and stale seq_info
  width comments.
- Pool resize comment and lowering .get() redundancy left as-is:
  resize_columns is only called from ensure_columns, and the .get()
  keeps LowerOffGraphKVPass usable with manifests not built by the
  parser.
Merge upstream f63b372 without changing the runtime-columns feature delta. Integration verified with assistance from OpenAI Codex.
Abort prepared forwards independently of logging, qualify capture and replay through counters, and retain idle compaction headroom across bursts. Add release-path recovery, allocation-free trimming, and native burst regression coverage. Authored with OpenAI Codex assistance.
@Gasoonjia

Copy link
Copy Markdown
Contributor Author

@claude /pr-review Please review this feature at head 7697b418ab984497ed87dbbeb67b2b987328d11e against gasoonjia/runtime-columns-abi2-pr1-stack-base, including the frozen ABI, independent owner rows, shared Ring staging, clone/rewind and graph lifecycle, and actual test coverage. The native timing gate includes undo transfers and requires a median throughput regression no larger than2%. Finish with an explicit Approve / Request Changes / Needs Discussion and identify current-head CI or validation blockers. Do not dispatch or rerun CI and preserve existing GitHub branches and records.

@pytorch-bot

pytorch-bot Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/executorch/25422

Note: Links to docs will display an error until the docs builds have been completed.

❌ 4 New Failures, 1 Unclassified Failure

As of commit 785257e with merge base ec5937f (image):

NEW FAILURES - The following jobs have failed:

  • pull / test-arm-backend-public-api-backward-compatibility / linux-job (gh)
    RuntimeError: Command bash /__w/_temp/exec_script failed with exit code 56
  • Test CUDA Builds / unittest-cuda (system) / linux-job (gh)
    backends/cuda/tests/test_sdpa_varlen.py::SdpaVarlenTest::test_dynamic_dflash_context_window
  • Test CUDA Builds / unittest-cuda-muse-glimmer-batching / linux-job (gh)
    AssertionError: ('after-4', {'allocator_reserved_bytes': 33554432, 'allocator_reserved_high_bytes': 33554432, 'allocator_used_bytes': 1035776, 'allocator_used_high_bytes': 17675264, 'archive_append_time_ns': 0, 'archive_transfer_time_ns': 0, 'cache_commit_time_ns': 17753, 'cache_prepare_time_ns': 11072588, 'column_resize_count': 1, 'declared_columns': 65, 'device_staging_bytes': 0, 'device_used_bytes': 789315584, 'flat_capacity': 16, 'host_undo_bytes': 0, 'live_KV_bytes': 1032192, 'live_sequences': 62, 'logical_length': 14, 'method_calls': [{'calls': 0, 'capture_failures': 0, 'captures': 0, 'method': 'forward_1', 'replays': 0}, {'calls': 0, 'capture_failures': 0, 'captures': 0, 'method': 'forward_2', 'replays': 0}, {'calls': 0, 'capture_failures': 0, 'captures': 0, 'method': 'forward_4', 'replays': 0}, {'calls': 0, 'capture_failures': 0, 'captures': 0, 'method': 'forward_8', 'replays': 0}, {'calls': 0, 'capture_failures': 0, 'captures': 0, 'method': 'forward_16', 'replays': 0}, {'calls': 0, 'capture_failures': 0, 'captures': 0, 'method': 'forward_32', 'replays': 0}, {'calls': 14, 'capture_failures': 0, 'captures': 2, 'method': 'forward_64', 'replays': 10}, {'calls': 1, 'capture_failures': 0, 'captures': 0, 'method': 'forward_others', 'replays': 0}], 'physical_columns': 63, 'pid': 114610, 'row_growth_count': 2}, {'allocator_reserved_bytes': 33554432, 'allocator_reserved_high_bytes': 33554432, 'allocator_used_bytes': 1088284, 'allocator_used_high_bytes': 2662172, 'archive_append_time_ns': 1183139, 'archive_transfer_time_ns': 232583, 'cache_commit_time_ns': 1440622, 'cache_prepare_time_ns': 16410724, 'column_resize_count': 8, 'declared_columns': 65, 'device_staging_bytes': 65536, 'device_used_bytes': 822870016, 'flat_capacity': 16, 'host_undo_bytes': 2096640, 'live_KV_bytes': 1016832, 'live_sequences': 62, 'logical_length': 14, 'method_calls': [{'calls': 0, 'capture_failures': 0, 'captures': 0, 'method': 'forward_1', 'replays': 0}, {'calls': 0, 'capture_failures': 0, 'captures': 0, 'method': 'forward_2', 'replays': 0}, {'calls': 0, 'capture_failures': 0, 'captures': 0, 'method': 'forward_4', 'replays': 0}, {'calls': 0, 'capture_failures': 0, 'captures': 0, 'method': 'forward_8', 'replays': 0}, {'calls': 0, 'capture_failures': 0, 'captures': 0, 'method': 'forward_16', 'replays': 0}, {'calls': 0, 'capture_failures': 0, 'captures': 0, 'method': 'forward_32', 'replays': 0}, {'calls': 14, 'capture_failures': 0, 'captures': 3, 'method': 'forward_64', 'replays': 8}, {'calls': 1, 'capture_failures': 0, 'captures': 0, 'method': 'forward_others', 'replays': 0}], 'physical_columns': 63, 'pid': 117578, 'row_growth_count': 7})
  • trunk / test-models-macos-cpu (emformer_join, xnnpack-quantization-delegation) / macos-job (gh)
    RuntimeError: Command bash /Users/ec2-user/runner/_work/_temp/exec_script failed with exit code 1

UNCLASSIFIED FAILURE - DrCI could not classify the following job because the workflow did not run on the merge base. The failure may be pre-existing on trunk or introduced by this PR:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Nov 21, 2026
@claude

claude Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Claude finished @Gasoonjia's task in 53m 45s —— View job


PR Review: #25422

Request Changes: at 7697b41, cloning a Ring owner can feed an unwritten row into attention, one aborted forward wedges every session, and the 2% gate blocks PR CI without timing the growth and restore costs ABI 3 adds; Lint is red, and the native-gate and Triton jobs have not reported yet.

Detailed review

Summary

This PR adds opt-in ABI 3 (--private-kv-rows) for CUDA batched-sequence KV:

  • packed per-owner row spans that grow independently;
  • one shared per-layer Ring staging buffer, followed by a Ring write after attention;
  • host undo history for clone and rewind;
  • a native probe that compares ABI 2 and ABI 3 on exact logits, memory, graph replay and a 2% throughput gate.

Verdict: Request Changes. There is a correctness bug on the clone path, an abort contract that takes down every session, and a timing gate that is fragile as a PR check and does not measure ABI 3's new costs.

The frozen descriptor ABI, manifest validation and private_kv_write.py raised no findings. I did not review backends/cuda/runtime/test/test_ring_history.cpp or backends/cuda/runtime/test/test_private_row_layout.cpp in depth; both pass in unittest-cuda-runtime.

Code Quality

  • The first step on a clone can read an unwritten Ring slot (major).
    • restore_private writes only [keep − W + 1, keep), which is W − 1 rows (backends/cuda/runtime/cuda_kv_cache.cpp:1697-1699).
    • _private_rows treats [absolute_start − capacity, absolute_start) as retained, which is W rows once capacity == W. It loads V under valid & retained, with no visibility mask (backends/cuda/triton/kernels/sdpa_varlen.py:69-79).
    • The Ring sweep covers [kv_end − RING, kv_end) (:177-179, :207). For any step narrower than max_write, which includes every decode step, position keep − W is read from physical slot keep % W.
    • That position is masked out (:241), but tl.dot(p, v) still multiplies its V row by p = 0 (:268, and :454 in split-K).
    • In clone_private, that slot belongs to a span that prepare_private just got from allocate_layer (cuda_kv_pool.cpp:538-554), which calls allocate_async with no memset. If the stream-ordered pool hands back NaN or Inf bytes, the clone's attention becomes NaN. The step then writes NaN K/V back, so the session stays corrupted.
    • Trigger: seq_clone(src, upto ≥ W) on a model with a Ring layer, for example sharing the prefix of a prompt of 2048 or more tokens.
    • The tests cannot see it. test_sdpa_varlen_private.py:72 writes every retained row into its NaN-filled storage. The probe's floor-replay step (check_private_kv_rows.py:61-63, a clone at 128 with W = 16) passes only while the pool happens to return finite bytes.
    • Fix: bound retained to min(capacity, WINDOW − 1) rows by passing WINDOW into _private_rows, or zero slot keep % W in restore_private. Add a kernel case that writes only the W − 1 restored rows into NaN storage. Fix this →

Infrastructure

  • The 2% timing gate is a hard PR-CI check.
    • check_private_kv_rows.py runs in unittest-cuda-muse-glimmer-batching (.github/workflows/cuda.yml:722-724). That job triggers on every PR that touches backends/cuda, backends/aoti, extension/llm/batching, extension/llm/serving, examples/models/muse-glimmer or cuda.yml (:661-674).
    • require_performance (check_private_kv_rows.py:173-182) fails if any of 14 ratios (2 head dims × 7 concurrencies) drops below 0.98. Each ratio is a median of three tiny-model rounds of 20 steps on the mt-l-x86aavx2-11-41-a10g runner.
    • A zero-tolerance 2% threshold over 14 checks is prone to false failures on unrelated PRs.
    • The job runs under set -eux (:688), so a failure also skips the pytest block (:726-731) and the DFlash tests after it.
    • Fix: keep the exact-logits, memory and graph assertions blocking, make the throughput check report-only in PR CI, and run the blocking gate in a dedicated benchmark or periodic job. Fix this →

Testing

  • The gate does not time what ABI 3 adds.
    • The bench steps (check_private_kv_rows.py:65-84) start after seed prefill and warm steps have already grown every owner to its final capacity. So no per-owner growth, relayout, rebind or recapture is timed.
    • Clone and rewind run only outside the timed window. "Includes undo transfers" therefore covers commit-time archiving, but not restores.
    • The probe already records elapsed_seconds for clone and rewind (runtime_kv_columns_probe.cpp:272, :308-311), but the checker ignores it.
    • The gate's geometry (one Ring layer, W = 16, one KV head) keeps each restore at 15 KiB or less, against about 78 MiB for the default config (see Performance). A pass says little about the shipped model.
    • Two of the three rounds run ABI 2 first (:233), so the median of three does not cancel an order effect. Use an even number of rounds with balanced order.
  • Graph lifecycle is asserted only once.
    • The only capture/replay check is check_private_kv_rows.py:226-229: forward_64 recaptures once across remove + compact.
    • Nothing checks eager steps, recapture or replay across per-owner growth or clone, although both go through prepare_private → invalidate_bindings().
    • The ABI 1/2 tests in the same file do check graph transitions (for example GrowthDropsACapturedGraphOnlyWhenStorageMoves, test_cuda_kv_cache.cpp:943). The CudaPrivateCacheTest cases (:3871-4045) assert no cuda_graph_state transitions, and they drive a fake write_step (:3795) instead of the kernels. Fix this →

API Design

  • An aborted forward makes the whole ABI 3 cache unusable (major).
    • abort_step sets poisoned_ on every ABI 3 abort (cuda_kv_cache.cpp:1341-1346).

    • After that, declare_step (:957), seq_new (:998), seq_clone (:1024), seq_rm (:1076) and rewind (:1102) fail for every owner until clear(), and clear() drops all sequences.

    • The interface contract (cuda_kv_cache.h:95-97) still describes abort as a fence that leaves claimed rows in place.

    • The batching stack cannot recover:

      • extension/llm/batching/runner.cpp:1234-1253 fails only the batch's sessions and keeps scheduling;
      • nothing there calls clear();
      • cuda_executor.cpp:551-555 routes ABI 3 to this cache unchanged.
    • So one failed forward makes every later step and admission fail.

    • Fix:

      • Scope the failure to the owners in pending_runs_. Their committed windows are still intact in RingHistory, so either restore them, or mark only those owners unusable until seq_rm or rewind.
      • Update the header and private_kv_rows.md:47-48.
      • Extend the single-owner AbortedPrivateForwardRequiresClearBeforeReuse so that an owner outside the aborted step can still step.

      Fix this →

Performance

  • Each owner's admission or growth relayouts every owner and recaptures every graph (major).
    • make_private_row_layout packs spans in owner order with no slack (private_row_layout.h:73-90). An owner's first touch or doubling therefore moves the spans of every later owner in each layer whose capacity it changes: all 52 layers while the owner is below W, then the 13 flat layers.
    • For each changed layer, prepare_private:
      1. allocates a fresh buffer and copies all owners' live rows into it (cuda_kv_pool.cpp:362-415), keeping old and new allocations until the fence;
      2. synchronizes the device and the stream (:337-339, :433-436);
      3. calls invalidate_bindings() (:437), which clears every binding, recaptures every Replay graph and forces an eager step on every handle (:759-779).
    • The ABI 2 path in the same file grows columns geometrically specifically to avoid this: "admitting N sessions one column at a time costs N full copies" (cuda_kv_cache.cpp:1802-1804). ABI 3 brings that cost back for every owner's admission and every doubling, which is the common case when sessions start at different times.
    • private_kv_rows.md:43-45 says only "affected" bindings and graphs are invalidated.
    • Suggested fix: use slack or chunked spans, and grow owners that are scheduled together in one relayout.
  • Rewind and clone restore the whole window from pageable memory.
    • rewind (cuda_kv_cache.cpp:1101-1119) always calls restore_private, even for a no-op rewind.
    • restore_private copies W − 1 rows per Ring layer and plane from pageable RingHistory pages, at most 64 rows per copy, then calls cudaStreamSynchronize (:1688-1730).
    • For the default config (39 Ring layers, W = 2048, 2 KV heads × 128) that is about 78 MiB in roughly 2.5k pageable H2D copies per rewind or clone. ABI 2's rewind is metadata-only, and its clone copies device to device.
    • Only rows overwritten since position need restoring. That is at most length − position rows, which the rewind floor caps at max_write (ring_history.h:194).
    • A clone can copy the rows still resident in the source span device to device, and read only the evicted rows from history. Fix this →
  • Host undo memory has no budget.
    • RingHistory keeps min(ctx, W + max_write − 1) rows per owner and Ring layer in pageable pages (ring_history.h:60-61). That is a full copy of the legacy device Ring, while the device side saves only max_write − 1 rows. Combined host and device memory therefore grows by W rows per owner per Ring layer.

      --max-step-tokens Host undo per owner Device memory saved per owner
      4096 (CLI default) about 234 MiB (about 14.6 GiB at 64 owners) about 156 MiB
      128 about 83 MiB about 4.8 MiB
    • There is no budget or knob. The gate's memory check (check_private_kv_rows.py:206-217) counts only device bytes and asserts only host_undo_bytes > 0.

    • Suggested fix: archive rows as they leave the device Ring (copy-before-overwrite needs only max_write − 1 rows), or document the footprint and gate it against a budget.

Recommendation

Request Changes. The clone NaN path (Code Quality), the abort scope (API Design) and the per-owner relayout cost must be addressed. Fix the gate's placement and coverage gaps before treating its 2% result as qualification.

CI and validation status at the current head 7697b41 (read only; I did not dispatch or rerun anything):

  • Failing: Lint (run 44945202843). CMAKEFORMAT flags the new et_cxx_test(test_cuda_private_row_layout …) call at backends/cuda/CMakeLists.txt:534-537; lintrunner -a fixes it. Fix this →
  • Not yet reported (validation blockers):
    • unittest-cuda-muse-glimmer-batching is the only job that runs check_private_kv_rows.py, so there is no exact-logits, memory, graph or 2% timing evidence at this head yet.
    • unittest-cuda (system) runs test_sdpa_varlen_private.py and test_private_kv_manifest.py.
    • Also still running in Test CUDA Builds: unittest-cuda (kernel), test-models-cuda, test-cuda-merged-pte-a100, the three muse-glimmer e2e jobs and both quantized-gemm jobs.
    • Also still running elsewhere: pull, Test Vulkan Backend (specialized runners) and Build Windows CUDA Wheels.
  • Passed:
    • unittest-cuda-runtime: all 86 test_cuda_kv_cache tests (including the five CudaPrivateCacheTest cases), 13 test_cuda_ring_history tests and 9 test_cuda_private_row_layout tests.
    • test-executorch-cuda-build-13.2 and test-executorch-cuda-build-13.4, export-cuda-multi-arch-a100, merge-and-test-cuda-multi-arch-a10g, test-cuda-phonon, check-all-cuda-builds, and Test CUDA Windows Export and E2E.
    • Every other completed workflow passed or was skipped. The cancelled periodic run 44945203235 was superseded by a successful one (44945206308).

@Gasoonjia

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

Please review repaired head a2f0f87f73d5ee27ddf9a364eab962d1e24ebfb6 on this same PR (stack 2/5), including all changed code and unit-test coverage. The current base includes qualified #25324 and upstream main 8c3f75dfb1d70ad12161ab3c42b06b7e7a65e8ce.

The repair addresses your clone/unwritten-slot, abort-scope, owner-relayout, restore-transfer, timing coverage and CMAKEFORMAT findings. It selects Ring source addresses before K/V loads, uses stable spans within a geometric arena, scopes failed forwards to their owners, and fences failed preparation before reuse. Tests include NaN-filled restored Ring history, 64 staggered admissions and graph transitions, failed late staging allocation with cross-stream retry, and failed preparation/compaction fence recovery. The native checker now uses four balanced rounds, times growth and restore separately, and has a material driver-release fixture; PR timing is report-only, not performance qualification. Host undo RAM is explicitly bounded and reported. An inherited owner-count automatic-idle heuristic remains documented as required allocator-policy work for PR3; current driver qualification covers explicit compaction.

Local evidence: 29 production C++ tests pass with ASan/UBSan, 8 parser/manifest contract tests, 7 native-gate/workload tests, and 6 CI configuration tests pass; actual CUDA translation units pass host syntax/type checks. Formatting checks pass. CUDA cannot execute on this Mac, and this new head has no GPU qualification yet.

The prior head's native job 136971041339 failed d256/floor-replay with NaN mismatch. System job 136971041471 had 4 established baseline DFlash failures and 4 real private attention shared-memory failures (106496–172032 bytes required on A10G's 101376-byte limit). Do not treat those private failures as infrastructure; check whether the repaired source and new-head CI close them. Please distinguish numerical/resource/memory/graph passes from timing acceptance and inspect actual current-head results before recommending the next feature. Do not dispatch or rerun CI. No previous approval should be presumed. Review generated with AI should identify the tool.

@claude

claude Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Claude finished @Gasoonjia's task —— review in progress

Todo

  • Gather context (diff vs origin/gasoonjia/runtime-columns-abi2-pr1-stack-base, commits 7697b41 → a2f0f87)
  • Three-reviewer panel over all changed files
  • Consolidate + fact-check findings against a2f0f87 (incl. ring_history.h, private_row_layout.h, both new gtest files, cache_registry.h, executor/cache headers)
  • Current-head CI (run 44953277486): Lint ✅, unittest-cuda-runtime ✅, CUDA 13.2/13.4 builds ✅, a100 export ✅; native gate, unittest-cuda (system), unittest-cuda (kernel), test-models-cuda, a10g merge and e2e jobs still running. I'm waiting on them and not dispatching or rerunning anything
  • Map prior-head failures (d256/floor-replay NaN; 4 private-attention smem failures) to new-head results
  • Post final review

View job run

@Gasoonjia

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

Please complete a fresh code review and post a final code verdict for unchanged head a2f0f87f73d5ee27ddf9a364eab962d1e24ebfb6. The preceding review run 44953318068 ended in failure without a final verdict; its log reports is_error:true and HTTP 401 Bad credentials while updating the comment.

Do not wait for still-running CI inside this review action. Review the code and tests, consolidate and fact-check findings, and post the completed findings/verdict now. List unfinished CI explicitly as pending validation. An approval of code with pending CI does not authorize the next stacked feature: I will keep PR3-5 gated until the necessary exact-head numerical/resource/memory/graph and performance evidence is complete. Do not dispatch or rerun CI.

Current-head evidence: Linux CUDA runtime job136995887754 passed 91 KV-cache,16 Ring-history,13 private-row-layout tests, including late-allocation rollback fences, cross-stream retry, failed-fence clear recovery, staggered64-owner growth, resident clone/rewind and graph replay. Both quantized-GEMM jobs136995887902/136995887905 passed. Windows runtime jobs passed but their selected tests exclude the new private-KV tests, so do not claim those as ABI3 behavioral coverage. Lint passed. The Mac Buck job failed in Anaconda dependency metadata download (HTTP429), before tests. Native batching136995887681, system136995887915, kernel136995888004 and full-model E2E are still running as of2026-11-21T23:00UTC. No GPU performance qualification is claimed yet.

Use the current base and all24 changed files for the review; do not infer approval from the earlier partial comment. This is stack2/5 on qualified #25324 plus upstream main. Existing ABI1/2 are defaults. The experimental ABI3's host-RAM budget and explicit-compaction behavior are documented, with byte-aware automatic idle reclamation retained as required PR3 scope.

@claude

claude Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Claude finished @Gasoonjia's task in 57m 18s —— View job


Request Changes on a2f0f87: the Buck triton_kernels target omits the new private_kv_write.py, which breaks every Buck import of the CUDA backend; a reused owner ID inherits a closed owner's span, which compaction can't reclaim; and the native ABI 2/3 gate feeds one constant token, so it can't detect row-placement bugs. The exact-head native, system, kernel and E2E GPU jobs are still pending validation.

Detailed review (generated with Claude Code)

PR Review: #25422

Summary

This PR adds the opt-in ABI 3 (--private-kv-rows) CUDA batched-sequence cache. It provides per-owner private row spans per layer, shared per-layer Ring K/V staging, host copy-on-write Ring undo pages, new Triton stage/write/attention paths, and a native ABI 2 vs. ABI 3 qualification gate. I reviewed all 24 changed files against the current base gasoonjia/runtime-columns-abi2-pr1-stack-base and took nothing from the earlier partial comment. Findings: one blocker (Buck packaging), two major issues (span inheritance that contradicts the documented memory contract; a native gate whose exact-logit check can't see row placement), and minor items.

Code Quality

  • Minor: the test-only fence hook is a static thread_local on the production pool (backends/cuda/runtime/cuda_kv_pool.h:190, cuda_kv_pool.cpp:35), and every private fence checks it (cuda_kv_pool.cpp:535-539). That is a hidden global seam on the production fence path. Inject the fence function through the pool/cache constructor instead, defaulting to the CUDA sync, and keep the state explicit.

Infrastructure

  • Minor: the timing gate is enforced on PR-scoped runs, and its comment is wrong.
    • .github/workflows/cuda.yml:743-748 says "Periodic/push runs enforce the 2% gate", but the workflow has no schedule trigger (:16-51).
    • Enforcement therefore happens on push (main, release/* and the PR-scoped ciflow/cuda/* tags) and on workflow_dispatch.
    • A noisy A10G result will fail ciflow-tagged PR runs, the case the comment says must not happen. It can also redden main/release pushes for unrelated changes when is-full-run (:675) schedules this job, and no periodic run exists to catch drift.
    • Fix: enforce only on an explicit opt-in (a workflow_dispatch input or a dedicated scheduled job), report everywhere else, and correct the comment.
  • Question (low confidence): this job keeps timeout: 120 (cuda.yml:681). It now also runs 4 AOTI exports and 16 probe runs (each with a 900 s timeout, examples/models/muse-glimmer/tests/check_private_kv_rows.py:190) after the existing batching tests. Please check the pending native job's wall time against that limit.

Testing

  • Major: the native gate's exact-logit equality is insensitive to which rows attention reads.
    • Why: every step feeds token 13 to every owner at every position (check_private_kv_rows.py:26). V carries no position: examples/models/muse-glimmer/model/model.py:376/387/392 produce it from the normed input, and QK-norm and RoPE touch only Q/K (:400-414). So in every layer, all owners' V rows are identical, and attention returns that row whichever rows it reads.
    • What it can catch: ABI 2 vs. ABI 3 equality catches only NaN, never-written/zero rows, or cross-layer reads.
    • What it misses: cross-owner aliasing, a wrong Ring slot, a stage/history swap, stale rows from a relocated or removed owner, and wrong clone/rewind restore rows all give bit-identical logits. A wrong row count is caught only if rounding happens to differ.
    • Why it matters: this gate is the only test that runs the real kernels against cache-built descriptors.
      • The C++ cache tests stand in for the kernels with host cudaMemcpy at cache-computed addresses (backends/cuda/runtime/test/test_cuda_kv_cache.cpp:3995-4044).
      • test_sdpa_varlen_private.py uses hand-built layouts.
      • No full-model E2E job exports with --private-kv-rows.
    • Fix: use tokens that differ per owner and per position, as check_runtime_kv_columns.py already does for ABI 2. ABI 2 equality should remain exact.

API Design

  • Major: a reused owner ID inherits a closed owner's span, and compaction can't shrink it.
    • Contract broken: backends/cuda/runtime/private_kv_rows.md:14-15 says "A long owner does not increase other owners' row capacities", and :19-21 says explicit compaction releases unused spans and slack.
    • How it happens:
      1. seq_rm leaves the device span in place (cuda_kv_cache.cpp:1076-1099), and non-compact preparation retains it (cuda_kv_pool.cpp:285-290).
      2. seq_new takes the lowest free ID (free_sequence_id, cuda_kv_cache.cpp:1841-1848) as the column without touching its span (:1000-1005).
      3. make_private_row_layout keeps old for every live owner, compact or not (backends/cuda/runtime/private_row_layout.h:81). test_private_row_layout.cpp:87,89 encode this no-shrink behavior.
    • Trigger: a 4K-token session closes and a new 1-token session gets its ID. The new session holds the old flat capacity (up to the context) and the Ring capacity (W), and compact_kv_columns(0) can't reclaim either while the session lives.
    • Consequence: under churn, each ID's capacity drifts to its historical maximum, which erodes ABI 3's memory advantage in long-running servers. PR3's byte-aware idle reclamation would inherit this, because it can only drop free IDs.
    • Fix: in compact mode, plan live owners from required rather than old. This is address-safe: a wrapped Ring owner already requires W, and otherwise every retained position is below the new capacity, so pos % capacity is unchanged. Additionally or instead, have free_sequence_id prefer an ID with no span.
  • Minor: three ABIs are encoded as two booleans.
    • make_cuda_batched_sequence_kv_cache(geometry, cfg, runtime_columns, private_rows) (cuda_kv_cache.h:251) rejects the invalid (true, true) pair only at runtime (cuda_kv_cache.cpp:2215).
    • The constructor sets runtime_columns_ = runtime_columns || private_rows (:845) but derives info_width_ from the raw flag (:849), so call sites need runtime_columns_ && !private_rows_ checks (:1001-1012).
    • The executor passes abi == 2 || abi == 3 (backends/cuda/batching/cuda_executor.cpp:603).
    • An enum class for the sequence-info ABI would make the invalid state unrepresentable.

Backward Compatibility

  • Blocker: Buck builds of the CUDA backend can't import it.
    • The triton_kernels srcs (backends/cuda/BUCK:211-235) list sdpa_varlen.py but not the new triton/kernels/private_kv_write.py, and no Buck target uses glob().
    • backends/cuda/passes/lower_offgraph_kv.py:13-16 imports that module unconditionally at module level, and cuda_backend.py:39 and cuda_weight_collector.py:19 import lower_offgraph_kv.
    • So every Buck/fbcode consumer of the CUDA backend fails with ModuleNotFoundError, including ABI 1/2 users.
    • CI provides no evidence either way: the only Buck job hit HTTP 429 before running anything.
    • Fix: add the file to triton_kernels. Also register test_sdpa_varlen_private.py and test_private_kv_manifest.py in backends/cuda/tests/targets.bzl, as their siblings test_sdpa_varlen and test_offgraph_kv* are.

Performance

  • Required before qualification (not a blocker for an opt-in ABI): the per-commit archive cost is unmeasured at MG scale.
    • archive_private_step (cuda_kv_cache.cpp:1646-1685) puts three things on every step's critical path: a D2H copy of every staged K/V row on every Ring layer, a stream fence (:1672), and host copy-on-write appends (:1673-1683).
    • At the documented MG geometry (39 Ring layers, 2 KV heads × 128, BF16), that is about 39 KB/token: about 2.5 MB per 64-owner decode step and about 164 MB per 4096-token prefill chunk.
    • The gate's toy model (one Ring layer, one KV head; check_private_kv_rows.py:147-156) moves 0.5–1 KB/token, so even an enforced 2% pass doesn't bound MG's overhead.
    • Before PR3–5, measure MG-geometry decode and prefill with the archive on. If the cost is material, overlap it: an event-fenced D2H on a side stream, consumed lazily by clone/rewind.
  • Minor: every ABI 3 seq_rm performs a device-wide fence. cuda_kv_cache.cpp:1082-1086 calls pool_.synchronize(/*all_streams=*/true), which runs cudaDeviceSynchronize (cuda_kv_pool.cpp:538). Each session close therefore stalls every stream on the device, including other models in the process. Fence only the copies that can still read that owner's host pages.

Recommendation

Request Changes

  • Blocker: the Buck packaging gap breaks existing ABI 1/2 Buck consumers.
  • Fix in this PR:
    • The span inheritance, because PR3's reclamation builds on this span policy.
    • The native gate's workload, because the gate is the only real kernel-plus-cache integration check and currently can't fail on row-placement bugs.
  • Scope: this verdict covers code at a2f0f87 only. It is not CI qualification and does not authorize PR3–5.

Pending validation (read-only snapshot at about 23:55Z; nothing was dispatched or rerun):

  • Cited exact-head jobs, still pending: native batching 136995887681, system 136995887915, kernel 136995888004 and the full-model E2E jobs. My snapshot doesn't show their status.
  • Newer run: CUDA run 44961922435 was created at 23:27:59Z, after the jobs you cited. I can't confirm its head SHA from this action, so verify it is a2f0f87 before counting it as exact-head evidence. All its GPU jobs are in progress:
    • runtime 137022570542
    • MG batching/native gate 137022570549
    • kernel 137022570671
    • system 137022570676
    • quantized GEMM 137022570649 and 137022570668
    • MG E2E 137022570788, 137022570858 and 137022570866
    • test-models 137022570481, phonon 137022570621, CUDA 13.2/13.4 builds 137022570693 and 137022570734, and multi-arch A10G 137027651876
  • Passed at this head, per your report:
    • Linux CUDA runtime 136995887754 (91 KV-cache + 16 Ring-history + 13 private-row-layout tests). These tests stand in for the kernels (see Testing).
    • Quantized GEMM 136995887902 and 136995887905.
    • Lint.
  • Not ABI 3 evidence:
    • Windows runtime jobs, whose test selection excludes the private-KV tests.
    • Full-model E2E jobs: only check_private_kv_rows.py passes --private-kv-rows.
    • Mac Buck, an infrastructure failure (HTTP 429) before tests, which also leaves the Buck blocker unexercised.
  • Performance: nothing is qualified. PR-event native runs pass --report-performance (cuda.yml:746-747), so a green native job is numerical/memory/graph evidence only.

Prior-head failures:

  • d256 floor-replay NaN (native job 136971041339):
    • The source caps Ring history at min(capacity, W-1) and masks the unused oldest slot out of both the K and V loads (backends/cuda/triton/kernels/sdpa_varlen.py:70-96).
    • test_sdpa_varlen_private.py:155-168 adds a NaN-arena regression at d128/d256 with W ∈ {1, 31, 257}.
    • It remains pending on the real gate until the exact-head native job reports. Per the Testing finding, a pass would show only that the NaN is gone, not that the right rows are read.
  • Private-attention shared-memory overflows (106496–172032 B vs. the A10G's 101376 B, system job 136971041471):
    • The kernel now selects the history or staging address before a single tl.load (sdpa_varlen.py:90-96), with the legacy BLOCK_N/num_stages (:698-703, :743-747). That is consistent with dropping the duplicated tiles.
    • Triton's shared-memory allocation is fixed only at compile time, so this stays unverified until the system job reports. Do not treat it as closed before then.

🤖 Review generated with Claude Code

@Gasoonjia

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

Please review the complete updated feature at f1c2402e58f9be67df8d9b823eebc0a1545760e0 against gasoonjia/runtime-columns-abi2-pr1-stack-base (27 changed files), including the new repair. The preceding code-only review finished; this is a new-head review request.

The blocking Buck kernel packaging was fixed in 8a469bab6; the new private-attention and manifest tests now have Buck targets and required dependencies. Source-tree CI derives package/dependency checks from their actual imports. Compaction now plans live owners from current requirements rather than inherited capacity, with host planner tests, a CUDA cache test retaining another wrapped owner, and a native ID-reuse case. Native tokens now differ by owner, position and session lifetime; equality rejects non-finite output and stays exact. Production MG attention/cache geometry has a separate A100 profile/CI (52 layers, 39 Ring layers, W2048, write4096, 64 owners, logical128K), with small weights and accounted host undo reporting. It does not claim full 30B performance. Automatic timing reports without failing unrelated jobs; the standalone 2% qualification gate remains unchanged and default-on.

Local validation: 31 production host C++ tests with ASAN/UBSAN, 8 actual parser/ABI tests, 13 checker/gate/workload tests and 10 CI configuration tests pass; actual C++ translation units pass declaration-only syntax. Three independent reviewers covered all 27 files; the missing test dependency they found was corrected and covered.

Please give a final code verdict without waiting for long GPU CI. Inspect current CI read-only; do not dispatch or rerun CI. Predecessor 8a469bab6 runtime job 137022570542 passed 92 KV-cache, 16 Ring-history and 13 planner tests; its native/system/kernel jobs remain live. Those do not validate this new head. The predecessor a2f0f87 native numerical/memory/graph job passed but performance did not (steady about 9–19% lower, worst growth ratio 0.6308); the earlier constant-token workload is also insufficient to qualify row placement. Performance remains unqualified and PR3–5 are not started.

The production-shaped archive cost, current-head exact GPU integration and <=2% performance gate remain required before moving to PR3. No released GPU host is reused. Minor test-hook/ABI API suggestions from the previous review remain tracked, rather than being represented as fixed.

@claude

claude Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

PR review in progress: #25422 at f1c2402

  • Gather the diff and context for 27 files against gasoonjia/runtime-columns-abi2-pr1-stack-base
  • Run three independent reviews
  • Consolidate the findings
  • Fact-check against the current head (in progress)
  • Post the final verdict

Confirmed so far

  • The f1c2402 change at private_row_layout.h:81 also applies to the fragmentation fallback at :147-151. Owners repacked by that fallback get exactly their required capacity. On the next growth step, the layout crosses arena_limit again and triggers another full repack.
  • This is reachable at MG Ring geometry with the default initial_capacity=512 (64 owners, W=2048). Lockstep decode from token 1025 through 2048 hits the fallback on every step in all 39 Ring layers. Each hit does a device-wide sync, a fresh arena allocation, a D2D copy of all live KV, and graph invalidation.

Dropped after checking

  • A suspected issue where a rewind validation rejection marks the session failed is not reachable. SequenceCache::can_rewind applies the same written - max_write floor first, and that path returns false without marking the session failed.

CI is being inspected read-only; nothing has been dispatched or rerun.

View job run

@Gasoonjia

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

Please review the new head a84132acb022427bc348568e7fd888a7b0334c25 against the existing stacked base, including all31changed files. This request is for changed source, not a duplicate review of f1c2402.

The repair preserves growth slack during automatic Ring packing and restricts compile-only metadata placeholders to explicitly runtime-owned empty KV storage in the final program. Graph-owned aliases, nonzero metadata, original autotuning inputs and production attention geometry remain preserved. It adds production/default-initial-capacity growth regressions, actual compile-hook tests and flushed export-resource diagnostics.

Three blind local reviewers covered the complete diff with no findings. Local32C++ ASAN/UBSAN,10Torch/hook,15checker and11CI configuration tests pass. The new host test rejects the preceding planner at token1025. Declaration-only C++ checking is not CUDA execution.

Current-head natural-push CI must supply new GPU evidence. Earlier runtime/system passes and earlier report-only green timing jobs do not qualify this head. The <=2% same-work steady/lifecycle performance gate remains required before PR3. Read-only CI inspection only: do not manually dispatch or rerun workflows.

@claude

claude Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

PR Review: #25422

Status: I finished the read-only CI refresh for a84132a and am fact-checking the last findings before I post the review.

  • Read the full stacked diff (31 files) and the review checklist
  • Get findings from the independent reviewers and merge them
  • Download the logs for the two current-head CUDA failures (unittest-cuda-runtime, unittest-cuda-muse-glimmer-batching). Neither log prints a detailed error message.
  • Find the likely shared cause. check_compiled rejects the 0-byte compiled constants that the new runtime-owned KV placeholders produce (see cuda_kv_pool.cpp:1137-1144 and cuda_backend.py:606-610,636-640).
  • Refresh the remaining CI status (read-only)
  • Re-check the cited lines for the performance findings
  • Post the final review

View job run

@Gasoonjia

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

Please review current head 9c82784c72d9b63b68030ff8154c4330ead7a608 against the existing stack base, with the repository's three independent blind-reviewer workflow and a read-only refresh of natural-push CUDA CI. The PR body describes the final feature and current validation limits. The new tests exercise the actual Inductor constructor and include an actual nested CUDA backend compile context; host-only results do not qualify GPU behavior.

Keep all numerical, owner-lifecycle, graph, memory and <=2% performance gates. Do not restart or dispatch CI, lower the production geometry, weaken the runtime metadata checks, or treat report-only timing as performance approval. Please post a final verdict for this head when the review and relevant CI evidence are available.

@claude

claude Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

Needs Discussion (provisional while the ABI 3 CUDA jobs run): the three-reviewer pass found no numerical or owner-lifecycle defect at 9c82784, but the ≤2% performance gate is unqualified because automatic CI only reports timings, and ABI 3's blocking per-step host archive is its main risk.

Detailed review of PR #25422 at 9c82784 (Claude Code)

Summary

This PR adds ABI 3 (--private-kv-rows), which has four parts:

  • per-owner private KV row spans in a geometric per-layer arena;
  • a shared per-layer Ring write staging buffer;
  • a host copy-on-write history for Ring rewinds and clones;
  • an AOTI export path that keeps runtime-owned KV constants empty while declaring their logical extent.

Three independent blind reviews covered the 31-file diff against gasoonjia/runtime-columns-abi2-pr1-stack-base (c0c114e). None found a numerical or owner-lifecycle defect. The problems found:

  • a per-step host synchronization that puts the unqualified ≤2% gate at risk;
  • a path-filter gap in the production-geometry CI job;
  • qualification output that looks like performance approval;
  • a graph gate that only checks forward_64;
  • an out-of-bounds read after a failed construction.

Two test files got only partial review: the private-row sections of backends/cuda/runtime/test/test_cuda_kv_cache.cpp, and test_private_row_layout.cpp, where only the test list was checked.

Infrastructure

  • .github/workflows/cuda.yml:805: unittest-cuda-private-kv-mg-ring is the only job that runs the production Ring geometry. Its if: filter does not include backends/aoti or extension/llm/batching, but ABI 3 depends on both:

    • Every ABI 3 export goes through the new get_aoti_program_compile_context_manager hook in backends/aoti/aoti_backend.py.
    • The probe links cuda_executor, which builds on extension/llm/batching/executor.h, util/session_table.h and executor_utils.h.

    A change confined to those paths skips the mg-ring qualification, while unittest-cuda-muse-glimmer-batching (line 666) still runs. Add both paths to the filter.

Testing

  • examples/models/muse-glimmer/tests/check_private_kv_rows.py:627-641: report-only output reads like a qualification.

    • Every automatic run uses --report-performance, whose help text at line 516 says it "does not qualify perf". Yet when the medians pass, it prints PERFORMANCE_QUALIFIED: all median ratios >= 0.98.
    • qualification.json is written before the timing check and records neither the timing mode nor a verdict, so the uploaded cuda-private-kv-mg-ring artifact looks the same as one from an enforced run.
    • The per-phase values in that file are seconds stored under *_time_ns keys (lines 356-364).

    Record the mode and the verdict in the JSON, and use a non-qualifying label in report mode. Fix this →

  • check_private_kv_rows.py:568-571: across compaction, the graph gate asserts one recapture, more than one replay and no capture failures, but only for forward_64. The final message at line 641 still says "per-stage replay passed". Any other captured stage could recapture on every step, or fail capture, and the gate would still pass. Apply the same assertions to every captured stage. Fix this →

  • check_private_kv_rows.py:544-555: the cross-ABI savings gate compares only the counters the cache reports about itself: ABI 3's live_KV_bytes + device_staging_bytes against ABI 2's live_KV_bytes. Allocator and driver counters are compared only within ABI 3, around compaction (lines 566-567 and 578). A side or scratch buffer missing from metrics() would still pass. Also compare allocator_used_bytes (or driver used memory) between ABI 2 and ABI 3 at the saturated tags.

  • backends/cuda/tests/test_runtime_owned_kv.py:138-161: the alignment subtest uses an extent that is already a multiple of 64. Alignments 1 and 64 therefore produce the same data_size line, and the rounding is never exercised. Fix this →

  • test_runtime_owned_kv.py:240-385: ProgramCompileContextTest rebuilds method bodies with ast and runs them with exec in fake namespaces. It tests copies of those methods, not the installed ones, so it can drift from the real code.

  • D=256 private kernel: _num_stages selects a multi-stage pipeline for D=256 on GPUs with at least 160 KiB of shared memory, and that pipeline never runs on a GPU in CI:

    • The mini profile and test_sdpa_varlen_private.py run on A10G (99 KiB, which gets one stage).
    • The A100 mg-ring profile is D=128 only (check_private_kv_rows.py:521).

Performance

  • backends/cuda/runtime/cuda_kv_cache.cpp:1670-1713: ABI 3 blocks the host on every step of a model with Ring layers.

    • commit_step → archive_private_step copies the staged rows into pinned memory, calls pool_.synchronize() (a blocking stream sync), then copies them into host pages with memcpy. ABI 2's commit only records an event.
    • restore_private (lines 1715-1810) issues pageable host-to-device cudaMemcpyAsync calls of at most 64 rows each, per plane and per layer.

    private_kv_rows.md documents both, but they are the most likely way to miss the ≤2% gate, and that gate has not been enforced at this head. If the enforced run misses, the likely fixes are deferring the host append behind an event instead of synchronizing in commit_step, and restoring from pinned pages in batched copies.

  • backends/cuda/runtime/ring_history.h (append) and private_kv_rows.md:95-170:

    • Host undo memory has no budget knob. The doc's own bound is about 14.8 GiB at mg-ring with 64 owners.
    • Pages are allocated with std::make_shared and there is no error path. Running out of host memory therefore escapes commit_step as std::bad_alloc, rather than returning an Error that retires the step.
    • Rows are archived when written, so each owner retains W + max_write − 1 rows per Ring layer. Archiving only the rows a step is about to evict would retain far fewer; I have low confidence that this fits the fused write path.

Code Quality

  • backends/cuda/runtime_owned_kv.py:84-115: constant_info_sizes swaps wrapper.prefix for a ConstantInfoWriter proxy that forwards through __getattr__. It then regex-rewrites the constants_info_[i].data_size = 0; lines Inductor emits.

    • This conflicts with CLAUDE.md's rule against dynamic setattr/getattr patterns.
    • It ties ABI 3 exports to Inductor's exact codegen text, and to every constructor line going through prefix.writeline.
    • It does fail closed (lines 102 and 113), so an Inductor bump breaks ABI 3 exports instead of corrupting them.

    One explicit rewrite of the generated prefix after orig_codegen_model_constructor returns would avoid the forwarding proxy.

  • backends/cuda/runtime/cuda_kv_cache.cpp:902-911 and 1415-1418: a failed RingHistory::create for a later Ring layer can lead to an out-of-bounds read.

    1. The constructor sets error_ and returns before archive_staging_ and archive_bytes_ are sized.
    2. make_cuda_batched_sequence_kv_cache (line 2266) still returns the object and leaves the error for first use.
    3. metrics() does not check error_, and reads archive_bytes_[layer] for each earlier non-null history, which is an out-of-bounds read on an empty vector.

    Size both vectors before the loop, or return nullptr from the factory when construction fails, as it already does for invalid geometry. Fix this →

Recommendation

Needs Discussion (provisional until the ABI 3 jobs finish).

  • Performance is not qualified at 9c82784.

    • Automatic runs pass --report-performance, and there is no workflow_dispatch run with enforce_private_kv_performance=true for this head.
    • Report-only PERFORMANCE_* lines do not count as approval.
    • Approval needs an enforced run on this head for both mini (A10G) and mg-ring (A100), with every median ratio ≥ 0.98. As requested, I did not dispatch or rerun anything.
  • CI (natural-push run 44974801333, checked read-only at 03:08 UTC):

    • Passed: unittest-cuda-runtime, merge-and-test-cuda-multi-arch-a10g, export-cuda-multi-arch-a100, test-cuda-phonon, the CUDA 13.2 and 13.4 builds, check-all-cuda-builds and unittest-cuda-quantized-gemm (int4).
    • Within unittest-cuda-runtime: on GPU, all 14 test_runtime_owned_kv.py tests passed, including the nested real-backend-context test. test_cuda_ring_history passed 16 of 16, test_cuda_private_row_layout 17 of 17 and test_cuda_kv_cache 95 of 95.
    • Still running: the ABI 3 gates in unittest-cuda-muse-glimmer-batching (the mini checker) and unittest-cuda-private-kv-mg-ring. Also running: unittest-cuda (system) and (kernel), quantized-GEMM large-int5-int6-int8-graph-timing, the three muse-glimmer E2E jobs, test-models-cuda and test-cuda-merged-pte-a100.

    If any ABI 3 numerical, lifecycle, graph or memory gate fails, the verdict becomes Request Changes.

  • Fix before landing, whatever CI shows: the mg-ring path filter, the report-mode labelling, the graph gate that only checks forward_64, and the metrics() out-of-bounds read.

Generated with Claude Code. I will update this comment once the remaining ABI 3 jobs report.

View job run

@Gasoonjia

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

Please review the complete PR #25422 feature at 3e0fb18bfa72eaf522adbbce06a13cc1fee92e7b against its stacked base, including the full unit and native qualification coverage, and inspect current-head CI when available. Preserve the <=2% steady/lifecycle performance requirement; report-only timing or older-head GPU results do not qualify this head. Do not dispatch or rerun CI. Please post your final verdict when the required results are available.

@claude

claude Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

Claude finished @Gasoonjia's task in 49m 31s —— View job


PR Review: #25422 at 3e0fb18

Request Changes: ABI 3 still drains the GPU and appends host undo pages on every Ring commit, 3e0fb18 has no enforced ≤2% steady/lifecycle result (its GPU jobs are still pending and run report-only), and the newest commit also changes the ABI 2 compaction that the gate uses as its reference.

Detailed review

Summary

This PR adds ABI 3 (--private-kv-rows): per-owner private KV spans in a geometric per-layer arena, shared per-layer Ring staging, and copy-on-write host undo pages for clone/rewind. It also adds mini and mg-ring native gates against ABI 2. I found one blocker, three major problems and one minor test problem.

Scope: c0c114e...3e0fb18, all 31 files. The PR head moved to 221af30 at about 03:58Z, after this review started. This job can't fetch new commits, so 221af30 is not reviewed here.

Testing

  • major — the mg-ring gate doesn't time or compare the costliest ABI 3 paths (examples/models/muse-glimmer/tests/check_private_kv_rows.py:100-118, 233-277, 482-543).
    • paired_timings times only three things: 1-token bench-c{c}-* decode, restore-c*, and growth-c*.
      • Each restore-c* cycle clones upto=seed+23 from an owner at seed+24 and then rewinds 1 position, about one evicted row per Ring layer.
      • growth-c* runs after clear, with 8-token seeds that never reach the 2048 window.
    • The paths where ABI 3 adds the most work run untimed:
      • the 4096-token seed-c* and production-ring-seed-* commits, about 160 MB of D2H archive each at this geometry;
      • the 8192→4096 floor restore.
    • Past the window at production geometry, only the 2-owner production-ring-floor-replay compares logits. Every bench-c{c} and restore-c*-step uses save=False.
    • So even an enforced pass would not cover large-write archive cost, deep-restore cost, or multi-owner wrapped-Ring exactness.
    • Fix this →
  • minor — ProgramCompileContextTest tests copies of the code, not the code (backends/cuda/tests/test_runtime_owned_kv.py:241-386).
    • It execs method and function bodies pulled out with ast.parse, inside stub namespaces (orig_clone/orig_get_const lambdas).
    • It asserts on ast.unparse argument text.
    • Formatting or a rename breaks it, and it never runs the hooks CudaBackend actually installs. test_actual_cpu_clone_and_serialization_hooks_keep_owned_views_empty doesn't test the actual hooks despite its name.
    • Fix this →

Performance

  • blocker — ABI 3 blocks the host on every Ring forward (backends/cuda/runtime/cuda_kv_cache.cpp:1335, 1670-1713).
    • commit_step → archive_private_step queues D2H copies of pending_width_ rows × 2 planes for every Ring layer (39 in mg-ring).
    • It then waits on pool_.synchronize() (1698) and runs RingHistory::append on the host: memcpy plus copy-on-write page allocation.
    • ABI 2 commit only does mark_step_done (1341). Every ABI 3 decode step therefore adds a full stream drain plus host work, which removes the CPU/GPU overlap that graph replay relies on.
    • The lifecycle path adds two more fences: ABI 3 seq_rm drains all streams (1100-1101), and restore_private synchronizes its stream (1802).
    • Possible secondary cost (low confidence): _private_rows in sdpa_varlen.py reloads Layout/Step metadata and does a runtime modulo per key block, for both K and V.
    • private_kv_rows.md:98-102 acknowledges this cost but doesn't bound it.
    • The only timing evidence is the author's report-only 9c82784 run: steady 0.815–0.914, lifecycle down to 0.633, against 0.98. 3e0fb18 doesn't touch this path.
    • Fix this →
  • major — the newest commit changes default ABI 2 compaction, which is also the gate's reference (backends/cuda/runtime/cuda_kv_pool.cpp:886-898, reached from cuda_kv_cache.cpp:1935-1940 and on_idle at backends/cuda/batching/cuda_executor.cpp:1130).
    • Every shrinking compaction now trims survivors to the smallest initial·2^k ≥ min(live_rows, limit−1)+1. That can leave a single free row.
    • A resumed survivor then needs an all-layer replacement, copy and rebind within a step or two. The tests now pin that regrowth:
      • test_cuda_kv_cache.cpp:3427/3430 (flat_capacity 4; the exact 2/17 byte ratio relaxed to EXPECT_LT);
      • ContractionDropsClosedOwnersUnusedRowCapacity (3509-3513).
    • It also moves the benchmark baseline. Each clear+compact in the gate (check_private_kv_rows.py:234, 267) now resets ABI 2 to its initial height, so the timed growth-c* totals compare ABI 3 against a different ABI 2 than the stack base.
    • It contradicts private_kv_rows.md:6 ("existing ABI 1/2 … runtime paths are unchanged").
    • The trim was motivated by the 40 GB A100 replacement peak. It only helps once the longest owner has closed, and no production-geometry ABI 2 result exists at this head.
    • Fix this →
  • major — ABI 3 compaction keeps spare spans at full capacity (backends/cuda/runtime/cuda_kv_cache.cpp:1575-1589).
    • With compact, up to spare closed owners keep private_required_ = capacity. They are picked by lowest ID, not by size.
    • on_idle passes spare = live_sequences. A closed low-ID 128K owner at mg-ring geometry therefore keeps about 1.6 GiB of full-attention rows (13 × 131072 × 512 B × 2) plus about 78 MiB of Ring rows indefinitely, while ABI 2 trims the same height.
    • This contradicts private_kv_rows.md:23-27 ("releasing inherited excess as well as unused spans and arena slack").
    • Packed compaction also leaves no arena headroom, so the first resumed span growth replaces the arena.
    • Fix this →

Recommendation

Request Changes

Blocking: the per-forward host fence above, and the lack of any qualifying performance result for this head. The ABI 2 trim, the spare-span retention and the gate coverage also need fixing before the head can be qualified.

Evidence at 3e0fb18, checked at 04:22Z. Nothing was dispatched or rerun.

  • Numerical, memory and graph: no result yet.
    • In "Test CUDA Builds" 44981770009 (checkout Merge 3e0fb18 into c0c114e), every GPU job is still unfinished.
    • That includes unittest-cuda-private-kv-mg-ring, unittest-cuda-muse-glimmer-batching (mini gate), unittest-cuda-runtime (new ring_history/private_row_layout ctests), unittest-cuda (kernel)/(system) and the e2e jobs.
  • Timing: not qualified, and automatic CI can't qualify it.
    • Both gates run --report-performance, so they will record performance_qualified: false whatever the ratios.
    • Meeting ≤2% needs an enforce_private_kv_performance=true dispatch at the final head, and none exists.
    • The 9c82784 ratios above are older-head and report-only. They don't qualify anything, and they fall well short of 0.98.
  • 221af30: its run 44982952033 is still queued and isn't covered here. It needs its own green blocking checks and an enforced performance run.

Generated with Claude Code

@Gasoonjia

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

Please review current head 221af301aa09f40622031b9a44c24254de6601af of #25422 against its unchanged stacked base c0c114e7c61ad76294f7304a28b1f09d5f5f6172. Follow the repository three-blind-reviewer full-diff workflow and report any changed file not reached. Inspect CI read-only; do not dispatch, rerun or cancel jobs.

The new commit batches independent private metadata/undo copies on CUDA13.2+ non-legacy streams, skips stable-generation owner layout reconstruction, and avoids temporary maps for sorted unique archive runs. Verify stream ordering, host staging/descriptor lifetime, legacy/older runtime fallback, error fencing, transactional validation, graph bindings and numerical coverage. Neither archive fences nor measured lifecycle work were removed. Local CPU-only speedups do not establish GPU/native qualification. Predecessor9c passed native exact finite logits, memory and graph gates but failed all42 <=2% timing points in report-only CI; production failed ABI2 late contraction and did not reach ABI3. Distinguish new-head evidence from predecessor results and keep the performance gate required before PR3. The remaining stack explicitly retains byte-aware allocator reclamation, router coalescing and prefix save/restore scope.

@claude

claude Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

Claude finished @Gasoonjia's task in 45m 11s —— View job


I found no production correctness defect in 221af30, but its new cross-stream test can't fail on the stream-ordering or layout-skip bugs it is meant to catch, and this head has no native numerical, memory, graph or timing results yet, so my verdict is Needs Discussion.

Detailed review: 221af30 against the stacked base c0c114e

Summary

The PR switches ABI 3 private KV rows to shared Ring staging. Its newest commit, 221af30, does three things:

  • it batches the private metadata uploads and the Ring undo archives with cudaMemcpyBatchAsync, on CUDA 13.2+ and non-legacy streams only;
  • it skips rebuilding owner layouts while the layout generation is unchanged;
  • it adds a fast path to RingHistory::append for sorted, unique owner runs.

I found no production defect in stream ordering, staging and descriptor lifetime, the legacy-stream and pre-13.2 fallback, error fencing, the transactional validation in append, or graph bindings. The problems below are a test that can't catch what it targets, two maintainability issues, and the performance gate, which is still open.

All three reviewers read the full production diff. These files were only partly covered:

  • test_cuda_kv_cache.cpp outside the private-cache fixture and the new tests (about lines 3962–4231);
  • test_ring_history.cpp outside the two new tests;
  • most of cuda_kv_pool.h;
  • .github/workflows/cuda.yml outside the private-KV and runtime jobs (about lines 780–964).

Code Quality

  • enqueue_private_copies takes hidden inputs.

    • It reads three member vectors (cuda_kv_cache.cpp:2210–2212) that upload_private (2086–2117) and archive_private_step (1720–1735) each clear and refill. That is a side channel, and CLAUDE.md asks for explicit state management.
    • Its kind argument only affects the fallback loop, because cudaMemcpyBatchAsync infers the copy direction from the pointers.
    • Neither error message (1694, 1707) includes cudaGetErrorString, while the non-private upload() does (2072–2076). A batch failure in the field therefore reports no CUDA error.

    Passing the descriptors in explicitly would make the contract visible and stop a future caller from enqueueing a stale list. Fix this →

  • A metrics counter is now the cache key for the layout upload.

    • In the base, column_resize_count is only a metric. ABI 2 resize_columns bumps it (cuda_kv_pool.cpp:972), and metrics() reports it.
    • This PR adds a second bump at cuda_kv_pool.cpp:487 and keys layout_uploaded_ on the counter. With 221af30, both the staging rebuild in build_private_step (cuda_kv_cache.cpp:1637) and the upload (2108) are skipped based on it.
    • The skip is correct today. After the first allocation, every private_layouts_ swap (493) comes after the bump at 487, and layout_uploaded_{-1} covers the first allocation.
    • The risk is a future change to how the metric counts, for example no longer counting relayouts that change nothing. That would leave stale owner_layout rows on the device, and KV writes would silently land in the wrong spans.

    A dedicated layout generation in the pool, bumped next to the swap, would make this invariant explicit. Fix this →

Testing

  • CopyBatchesPreserveMetadataAcrossStreamsAndGrowth can't fail on the bugs it targets (test_cuda_kv_cache.cpp:4188–4226; all three reviewers found this).

    • Stream ordering is never exercised.

      • write_step calls cudaStreamSynchronize(stream) right after prepare_step and rebind_for_execute (4069–4072).
      • The fake forward then writes K/V with synchronous cudaMemcpy from pageable vectors on the legacy stream (4088–4092).
      • commit_step synchronizes again (cuda_kv_cache.cpp:1743).

      So the test never checks that the metadata batch is ordered before the stream work that reads it, or that the undo batch (srcAccessOrder = Stream) is ordered after the stream work that writes k_stage/v_stage. A reordered or wrong-stream batch would still pass.

    • Rows archived on two of the three streams are never read back.

      • With kPrivateWindow = 5, rewind(0, 8) gives restore_plan(5, 8, 9) = {start 4, resident_start 5}, so only position 4 is restored from host undo history.
      • Position 4 was archived in round 4, on cudaStreamPerThread.
      • Rows archived on the legacy stream (rounds 0, 3 and 6, which use the fallback loop) and on the non-blocking stream (rounds 2, 5 and 8) are never restored.
    • The layout skip is only checked against itself. The fake forward (4073–4076) and expect_history (4111–4113) both read the device flat_layout/ring_layout. A stale layout after growth would be written and read at the same wrong offsets, and the test would still pass.

    • The clone destination is never checked. seq_clone(0, 8) returns owner 2, but nothing checks what it contains.

    To fix it:

    • enqueue the fake writes on stream with no host sync;
    • after each round, compare the device layouts with spans computed independently;
    • pick rewind and clone points that restore rows archived on each stream;
    • check the clone destination.

    Fix this →

Performance

  • 221af30 has no GPU or native qualification yet. CI status at this head, from run 44982952033 as of 04:41Z:

    • Passed: lint, the CUDA 13.2 and 13.4 builds, and unittest-cuda-runtime. That job built with toolkit 13.2.86 and passed 98/98 test_cuda_kv_cache tests and 18/18 test_cuda_ring_history tests, including the new ones, so the batch path compiled and ran on a GPU.
    • Still pending: unittest-cuda-private-kv-mg-ring (job 137087346323), unittest-cuda-muse-glimmer-batching, the kernel and system unit tests, and the end-to-end jobs.

    So this head has no exact-logits, memory, graph or timing result yet. The 9c82784 passes don't carry over, because 221af30 rewrites the upload, layout and archive paths those gates exercise. The predecessor's 0 of 42 timing points within 2% is still the only native timing data. Its production run stopped at ABI 2's late contraction, so no head has a production-geometry ABI 3 result. Local CPU-only speedups can't stand in for any of this.

  • Nothing in CI enforces the timing gate before PR3. PR runs pass --report-performance (cuda.yml:854–858), so even a green mg-ring run at this head only reports timing.

    • Please run workflow_dispatch with enforce_private_kv_performance=true at 221af30 (or its successor) and link that run before PR3 builds on this PR.
    • Use the per-phase CPU wall times in qualification.json (archive_transfer_time_s, cache_commit_time_s, cache_prepare_time_s) to show which phase moved.
    • Batching cuts the number of enqueue calls, but archive_private_step still blocks the host on pool_.synchronize() on every commit (cuda_kv_cache.cpp:1743). At MG geometry that block follows a 78-descriptor D2H batch (39 Ring layers × 2 planes). The native data should show whether this fence, rather than enqueue overhead, was behind the 42 failures.

Recommendation

Needs Discussion. I found no production correctness defect; I can't formally approve. Before merge:

  • strengthen the test above so it can fail on ordering and layout-skip bugs;
  • get the native mg-ring job passing at this head, because none of the predecessor's native results apply to 221af30.

The enforced timing run is still required before PR3. As the stack plan says, byte-aware allocator reclamation, router coalescing and prefix save/restore remain later scope.

Review generated with Claude Code.

Add opt-in ABI3 for independently growing owner history and per-layer step
staging while preserving geometric Ring growth and clone/rewind semantics.
Review the private row planner and pool, then cache/undo ownership, then
Triton addressing, lowering and native qualification.

Authored with OpenAI Codex.
Preserve owner spans inside a geometric arena and copy only evicted history
on restore. Select Ring source addresses before tile loads, retire failed
owners independently, and fence preparation rollback before cross-stream reuse.
Extend native qualification to lifecycle timings and driver-visible contraction.

Authored with OpenAI Codex.
Review the target-aware SDPA pipeline policy and its device/export-budget tests first, then the Buck kernel package registration and import-contract test. The cache phase counters and native report keep the existing end-to-end performance gate while exposing preparation, commit and archive wall-time costs; the archive counters include device waits and are subsets of commit.

Authored with OpenAI Codex.
Compact live spans from their current requirements so a short session can release capacity inherited from a closed long session. Exercise real native cache/kernel integration with owner- and position-varying tokens, rejecting matching non-finite logits and checking ID reuse. Add a separate production MG attention/cache geometry profile, its bounded host undo accounting and A100 CI; keep automatic timing report-only without treating it as performance qualification.
…ation

Limit unused replacement row height during trimming width contraction while retaining live Ring history and transactional commits. Keep construction-error metrics safe and verify allocator savings, every captured forward stage and unambiguous timing qualification. Preserve runtime-owned AOTI constant extents through an explicit post-generation rewrite.

Authored with Codex (OpenAI).
Batch independent metadata and Ring undo transfers while preserving stream ordering and host fences. Reuse physical layout descriptors and validate sorted archive owners without temporary map nodes. Keep older CUDA and legacy stream copies supported, and cover transactional archive validation and stream/growth behavior.

Authored with Codex (OpenAI).
@Gasoonjia
Gasoonjia force-pushed the shared-ring-staging-pr2 branch from 221af30 to 785257e Compare November 23, 2026 20:39
@github-actions github-actions Bot added ciflow/trunk module: arm Issues related to arm backend labels Nov 23, 2026
@Gasoonjia
Gasoonjia changed the base branch from gasoonjia/runtime-columns-abi2-pr1-stack-base to gasoonjia/runtime-columns-abi2-pr1 November 23, 2026 20:40
@Gasoonjia

Copy link
Copy Markdown
Contributor Author

@claude /pr-review Please review current head 785257ee4afa77a2de615a6f1e1bab95ec526467 against gasoonjia/runtime-columns-abi2-pr1. The eight existing PR2 patches were rebased unchanged onto #25621. Review the PR2-only delta against its actual base; GPU exact correctness and <=2% steady/lifecycle performance are still unresolved and must not be claimed as qualified. Finish with explicit Approve / Request Changes / Needs Discussion. Do not dispatch, rerun or cancel CI, and do not merge PRs or delete branches.

@claude

claude Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Claude finished reviewing PR #25422 · View job run

Request Changes. ABI 3 blocks the host on every commit, can crash on a host OOM in its ≈14.8 GiB undo history, and synchronizes the whole device on every seq_rm; the new compile hooks also change every CUDA low-memory export, and with all GPU jobs for 785257e still queued, GPU exactness and the ≤2% steady/lifecycle gate remain unqualified.

Detailed review

Summary

PR2 adds cache ABI 3 (kBatchedSequencePrivate):

  • Each owner gets private row spans in a per-layer arena.
  • Ring layers share one [1, max_write, Hkv, D] K/V stage.
  • A host-side RingHistory serves rewind and clone.

It also adds compile-time placeholders for runtime-owned KV, a one-stage D=256 fallback in sdpa_varlen, height trimming when ABI 2 contracts, and an A100 job that qualifies ABI 3 on MG geometry. Four of the problems below block approval.

  • Not qualified: GPU exact correctness and the ≤2% steady/lifecycle gate are still open.
    • In Test CUDA Builds (run 45261692100), every GPU job for this head was still queued when I checked. That includes unittest-cuda-private-kv-mg-ring, unittest-cuda-runtime, both unittest-cuda shards and unittest-cuda-muse-glimmer-batching.
    • Across all workflows, 35 of 48 runs had passed, none had failed and 9 were pending.
    • Automatic timing is report-only even after those jobs finish.
    • I did not dispatch, rerun or cancel anything.
  • Scope:
    • I reviewed git diff origin/gasoonjia/runtime-columns-abi2-pr1...HEAD (31 files, +6854/−94).
    • The checkout is shallow, so I could not confirm that the eight patches were rebased onto [CUDA] Grow batched-sequence KV columns at runtime #25621 unchanged. The findings apply to the diff as it stands.
    • These files were only partly read:
      • test_cuda_kv_cache.cpp outside the private-cache fixture.
      • check_private_kv_rows.py beyond what its gate tests exercise.
      • The MG runtime-KV probe sources.
      • The Triton kernel bodies in sdpa_varlen.py.

Code Quality

  • RingHistory::append can't fail cleanly on a host OOM, and nothing checks the ≈14.8 GiB worst case (major).
    • Where: backends/cuda/runtime/ring_history.h:130-163, reached from backends/cuda/runtime/cuda_kv_cache.cpp:1748.
    • What happens: After validation, append advances owners one run at a time and allocates pages lazily with std::make_shared (145-147), including copy-on-write copies of pages shared with a clone.
    • Worst case: Geometry fixes it at max_seqs × Ring layers × (window + max_write − 1) rows, which host_undo_budget puts at ≈14.8 GiB for MG (examples/models/muse-glimmer/tests/test_private_kv_rows_gate.py:352-357). The runtime neither checks nor reports this figure, and callers can't cap it.
    • Failure: If the host can't supply it, std::bad_alloc escapes commit_step with some owners already advanced. The cache, RingHistory and CudaExecutor have no catch, so abort_step never runs.
    • Fix: Allocate all of a step's pages before mutating any owner and return Error::MemoryAllocationFailed. Check the worst case against a configurable budget when the ABI 3 cache is created.
    • Fix this →

Infrastructure

  • Question: should the MG A100 job run its timing sweep on every matching PR?
    • Where: .github/workflows/cuda.yml:802-858.
    • Cost: unittest-cuda-private-kv-mg-ring has a 180-minute timeout on mt-l-x86iavx512-11-125-a100.
    • Triggers: Any change under backends/cuda, backends/aoti, extension/llm/batching, extension/llm/cache or examples/models/muse-glimmer, plus full runs (805-812). The PR describes this ABI as experimental and off by default.
    • Signal: Timing is report-only unless someone dispatches with enforce_private_kv_performance=true (854-858), so on PRs that share of the A100 time gates nothing.
    • Suggestion: Keep the blocking exactness, memory and graph checks on PRs, and move the timing repeats to workflow_dispatch or a nightly run.
    • Fix this →

Testing

  • The private-cache fixture can't detect stream-ordering bugs, and it never checks a clone destination.
    • Where: backends/cuda/runtime/test/test_cuda_kv_cache.cpp:4069-4072 and 4088.
    • Why it can't fail: write_step calls cudaStreamSynchronize after prepare_step/rebind_for_execute, then fakes the forward with a synchronous cudaMemcpy. A missing event between the async metadata upload, the forward's stage writes and the D2H archive on pool_.stream() would still pass.
    • Affected test: That includes CopyBatchesPreserveMetadataAcrossStreamsAndGrowth, despite its name. It also clones owner 0 into owner 2 (4219) and never reads owner 2's layout or history.
    • Fix: Write the fake payload with cudaMemcpyAsync on the step stream, delayed by a cudaLaunchHostFunc and with no host sync. Then assert on owner 2.
    • Fix this →
  • Nothing compares ABI 2 against the base, though this PR changes code that ABI 1/2 run.
    • Comparison: The ≤2% gate compares ABI 3 with ABI 2 built from the same head.

    • Changes it can't see:

      • CudaKVPool::resize_columns now trims height when it contracts (backends/cuda/runtime/cuda_kv_pool.cpp:885-898).
      • sdpa_varlen now forces one pipeline stage in both kernels for D=256 on GPUs with less than 160 KiB of shared memory (backends/cuda/triton/kernels/sdpa_varlen.py:48-54).

      A regression in either moves both sides of the comparison, so the gate can't see it.

    • Untested branch: CI runs only on A100s, so the one-stage branch never runs there (cuda.yml:842).

    • Fix: Add a test that patches triton_compiler.max_shared_mem to take that branch and checks D=256 outputs. Then either measure ABI 2 contraction lifecycle against the base, or move these ABI 2 changes into their own PR with their own evidence.

    • Fix this →

Backward Compatibility

  • The runtime-owned compile hooks run for every CUDA low-memory export, not only for off-graph KV programs.
    • Scope: backends/cuda/cuda_backend.py:1725-1739 installs RuntimeOwnedKVCompileBuffers for every CUDA program. In low-memory mode, _codegen_model_constructor_with_owned_sizes (680-706) therefore wraps constructor codegen for every model, including ones with only in-graph KV.
    • Memory: The hook builds constants (690-693) through the patched get_original_value_of_constant before constant_info_sizes can find there is nothing to patch.
      • The patched getter returns a new full-size CPU torch.zeros for each emptied graph-owned KV buffer (658-664).
      • The list keeps every one of them alive across orig_codegen_model_constructor.
      • A low-memory export of a static-cache model therefore holds its whole KV cache on CPU at once, which is exactly what low-memory mode exists to avoid.
    • Fragility: ABI 1/2 off-graph exports now depend on a regex rewrite of Inductor's emitted constants_info_[i].data_size = N; line (backends/cuda/runtime_owned_kv.py:84-109). If a PyTorch pin changes that line, every off-graph export fails with "Missing runtime-owned AOTI constant size emission".
    • Coverage: The tests exec AST-extracted copies of these functions in hand-built namespaces (backends/cuda/tests/test_runtime_owned_kv.py:243-256, 343-346). No test runs the installed hooks on a program whose graph-owned constants were emptied.
    • Fix:
      • Install the guard only when the program has runtime-owned storages.
      • Compute all_cuda and the owned sizes in a streaming pass instead of keeping every tensor in a list.
      • Add a test that runs the real _compile_time_cpu_clones on a model with an in-graph KV buffer.
    • Fix this →

Performance

  • Every Ring commit blocks the host on the GPU (blocker for the ≤2% gate).
    • Where: backends/cuda/runtime/cuda_kv_cache.cpp:1737-1756.
    • What happens: On every step, archive_private_step enqueues a D2H copy of the shared stage into archive_staging_ and then calls pool_.synchronize() (1743), which waits for both the forward and the copy. It then appends to each layer's RingHistory before commit_step returns. There is no opt-out.
    • Effect: The host can't prepare or launch step N+1 while step N runs, which removes the CPU/GPU overlap ABI 2 keeps in steady decode. This fits the steady-decode ratios reported for the predecessor, 9c82784 (0.815–0.914).
    • Fix: Reuse of the stage on the device is already stream-ordered, so only the host's read of archive_staging_ needs a fence.
      • Double-buffer archive_staging_.
      • Record an event after the D2H copy.
      • Run append lazily, at the next commit_step or before any rewind/seq_clone/seq_rm that reads history.
    • Fix this →
  • ABI 3 seq_rm synchronizes the whole device on every removal.
    • Where: backends/cuda/runtime/cuda_kv_cache.cpp:1104-1108.
    • What happens: seq_rm already refuses to run while inflight_ is set, and the archive, restore and clone paths all end fenced. It still calls pool_.synchronize(/*all_streams=*/true), which is cudaDeviceSynchronize() (cuda_kv_pool.cpp:525-548).
    • Effect: Every stream on the device stalls at each request completion, including other models' streams. A failed sync poisons the whole cache.
    • Why it looks unnecessary: The only work after the sync is a host-side history->erase, and I found no pending device work it needs to wait for (medium confidence). If there is some, wait on that operation's event instead.
    • Fix this →
  • Restore copies host history one pageable chunk at a time (minor).
    • Where: backends/cuda/runtime/cuda_kv_cache.cpp:1803-1821.
    • What happens: restore_private issues one H2D cudaMemcpyAsync per chunk of up to 64 rows, straight from RingHistory's pageable pages.
    • Effect: At MG's W=2048, a rewind or clone across evicted rows can take about 32 chunks × 2 planes × 39 Ring layers ≈ 2.5K staged copies, which counts against the lifecycle half of the gate.
    • Fix: Pack the chunks into pinned staging and submit them with one enqueue_private_copies call.
    • Fix this →

Recommendation

Request Changes

Four issues block approval:

  1. archive_private_step blocks the host on every commit.
  2. RingHistory::append has no allocation-failure path.
  3. ABI 3 seq_rm synchronizes the whole device.
  4. The compile hooks apply to every CUDA low-memory export.

Even with those fixed, GPU exact correctness and the ≤2% steady/lifecycle gate remain unqualified for 785257e. No GPU job had finished on this head when I checked, and automatic timing is report-only, so this review does not qualify either. Both need results from unittest-cuda-private-kv-mg-ring and an enforced timing dispatch.

🤖 Generated with Claude Code

@Gasoonjia
Gasoonjia force-pushed the gasoonjia/runtime-columns-abi2-pr1 branch 3 times, most recently from 3bff904 to 21587c4 Compare November 24, 2026 10:48

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/trunk CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. module: arm Issues related to arm backend

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant