Skip to content

[CUDA] Grow batched-sequence KV columns at runtime - #25621

Open
Gasoonjia wants to merge 3 commits into
mainfrom
gasoonjia/runtime-columns-abi2-pr1
Open

Gasoonjia wants to merge 3 commits into
mainfrom
gasoonjia/runtime-columns-abi2-pr1

Conversation

@Gasoonjia

@Gasoonjia Gasoonjia commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

CUDA batched-sequence KV caches grow physical session columns on admission using the five-field sequence interface by default. Live history survives resizing, and CUDA graphs rebind when storage moves. Shrinking and idle maintenance are separate follow-ups.

Native cache tests and a same-export mini-model check cover KV preservation, sparse owners, wrapped Ring cloning, failed admissions and recovery, and graph recapture. Resize documentation describes its transient old-plus-replacement memory requirement.

Authored with OpenAI Codex assistance.

@pytorch-bot

pytorch-bot Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❗ 1 Active SEVs

There are 1 currently active SEVs. If your PR is affected, please view them below:

⏳ 2 Pending, 2 Unrelated Failures

As of commit 21587c4 with merge base 5f6a523 (image):

BROKEN TRUNK - The following jobs failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

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 23, 2026
@github-actions

Copy link
Copy Markdown

This PR needs a release notes: label

If your change should be included in the release notes (i.e. would users of this library care about this change?), please use a label starting with release notes:. This helps us keep track and include your important work in the next release notes.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "release notes: none"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

@Gasoonjia

Copy link
Copy Markdown
Contributor Author

@claude /pr-review Please review current head a80ab388ca89eec12df66fe87588a31ed595e827 against main. This replaces #25324 with the exact same head and diff, hosted directly in the upstream repository. Recheck current-head CI and the documented expected-failure gate; prior validation does not establish new-head CI success. 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 @Gasoonjia's task in 50m 41s —— View job


Needs Discussion. The opt-in ABI 2 runtime-columns path has no correctness blocker, but three design problems need a fix or explicit sign-off:

  • No hysteresis in idle compaction: it shrinks on every session close and regrows on the next burst.
  • Device-wide memory trim on every resize: each column resize, including admission-time growth, trims the device's whole allocator and graph memory.
  • Idle failures are silently dropped.

CI also can't confirm the expected-failure gate on a80ab388: no CUDA job has started, and MLX Voxtral realtime is still running.

Full review of a80ab388 against main

PR Review: #25621

Summary

This PR adds an opt-in ABI 2 for the CUDA batched-sequence KV cache:

  • Int32[S,5] seq_info that carries the runtime column pitch.
  • Geometric column growth at admission.
  • Idle compaction through a new Executor::on_idle() hook.
  • The muse_glimmer_runtime_kv_probe diagnostic and its CI job.

I found no correctness blocker. ABI 1 behaviour is unchanged unless a model is exported with --runtime-kv-columns. The problems are the cost of the resize policy and how its failures surface; see Performance and API Design.

Current-head CI vs. the documented gate (snapshot 21:29Z; nothing was dispatched, rerun or cancelled):

Gate item (PR body) a80ab388
unittest-cuda (system): four DFlash failures, same as main Queued and not started in both the PR run and the push run. Unverified.
unittest-cuda (kernel): the earlier run failed in dependency install, "not a pass" Queued, not started. No passing kernel run exists yet.
CUDA jobs that exercise this diff (unittest-cuda-runtime, unittest-cuda-muse-glimmer-batching, the three muse-glimmer e2e jobs) Queued, not started. Unverified.
MLX: one unexplained Voxtral realtime failure In the PR run, test-mlx-voxtral-realtime and test-mlx-dflash are still running and all other MLX jobs passed. The push run passed, but voxtral-realtime was skipped there. Unverified.
Arm/QNN failures match main Test ARM Backend and Test QNN Backend passed in both runs. The only trunk failure, test_smaller_stories_llama_vkml, was curl: (56) Recv failure: Connection reset by peer while downloading the Vulkan SDK. The same job passed in the push trunk run.
CoreML failed during environment setup Passed in both runs.
Not in the gate pull / unittest / windows failed inside pip install . with Cannot restore timestamp ".../XNNPACK/CMakeFiles/generate.stamp": Access is denied (MSB8066). That looks like a Windows file-lock flake rather than this diff. The push-run twin is still running.

Not fully reviewed:

  • backends/cuda/runtime/test/test_cuda_kv_cache.cpp (+646, partly)
  • backends/cuda/runtime/test/test_cuda_backend_execute.cpp (+183, partly)
  • backends/cuda/tests/test_offgraph_kv_batched_sequence.py (diff only)
  • examples/models/muse-glimmer/tests/check_runtime_kv_columns.py (diff only)

Code Quality

  • (minor) sdpa_varlen doesn't enforce its 5-wide layout precondition (backends/cuda/triton/kernels/sdpa_varlen.py:456-465).
    • The docstring (408-411) requires contiguous column/head lanes for 5-wide seq_info. The kernels compute stride_kr = columns * stride_kc and ignore key.stride(0) (94-96, 254-256).
    • The wrapper only checks stride(-1) == 1 and shape[1] in (4, 5), so a permuted or sliced K/V view is mis-addressed with no error. The in-tree lowering passes dense storage and is unaffected.
    • Fix: when seq_info.shape[1] == 5, raise unless key.stride(2) == D and key.stride(1) == Hkv * D, and the same for value. Fix this →
  • (minor) The generic allocator carries one caller's ordering rule (extension/cuda/cuda_allocator.cpp:847-850).
    • The rule is "must not allocate a host snapshot that can throw before pitch reconciliation".
    • It exists because resize_columns trims after the pool commits (cuda_kv_pool.cpp:605-616) but before ensure_columns updates columns_ and the column mapping (cuda_kv_cache.cpp:1385-1388).
    • Only the global operator new override in extension/cuda/test/cuda_allocator_exit.cpp enforces it.
    • Fix: trim in ensure_columns after reconciliation, and the constraint goes away. Fix this →

Testing

  • (major) Nothing tests idle compaction through the production path.
    • The probe sleeps 550 ms and calls on_idle() directly (examples/models/muse-glimmer/tests/runtime_kv_columns_probe.cpp:290-292).
    • RunnerMaintenanceTest.IdleHookRunsBetweenBatchesOnTheEngineThread uses a FakeExecutor (extension/llm/batching/test/runner_test.cpp:382-387).
    • Untested: a Runner driving CudaExecutor::on_idle on a real ABI-2 cache.
    • Untested: cache activity inside the 500 ms grace suppressing compaction.
    • Untested: the failure and poison path. The PR body lists real-cache fault injection as a follow-up.
    • Fix this →

API Design

  • (major) The new Executor::on_idle() hook can't report failure, and CudaExecutor drops it (extension/llm/batching/executor.h:97-100, runner.cpp:801-809, cuda_executor.cpp:1127-1135).
    • on_idle() returns void, the Runner only catches exceptions, and the compaction Error goes only to ET_LOG, which is compiled out of release builds.
    • The PR body defers "release observability", but two problems go beyond logging:
      • No backoff. A failure before commit rolls back and leaves the trigger condition true. The Runner's idle loop then retries every 500 ms, paying a device sync and two allocator/graph trims each time.
      • Silent poisoning. A failure after commit sets poisoned_ (cuda_kv_cache.cpp:1389-1391). Every later admission and step then fails, and nothing points back at idle maintenance.
    • Fix: return Error from on_idle() so the Runner can record it and back off. Alternatively, back off inside CudaExecutor and expose a failure count and the last error via kv_metrics(). Fix this →
  • (minor) graph_metrics() can't tell "no data" from "no failures."
    • CudaKVCache::graph_metrics returns {} by default (backends/cuda/runtime/cuda_kv_cache.h:101-103), and only cuda_kv_cache.cpp:1244-1247 overrides it.
    • As a result, CudaExecutor::graph_metrics (cuda_executor.cpp:1103-1105) reports all-zero counters for every other cache kind and for any method the pool never bound. A capture_failures == 0 check passes vacuously in both cases.
    • Fix: return std::optional<CudaGraphMetrics>, and have the probe and checker require metrics for graph-enabled methods. Fix this →
  • (minor) The generic cache API drifted from its docs.
    • kBatchedSequenceRuntime is described as "Batched-sequence ABI 2" (extension/llm/cache/cache_registry.h:79-81). That is the CUDA lowering's term, not a backend-agnostic contract such as "physical width can change between forwards; the pitch arrives in the step's seq_info".
    • The README "Cache kinds" table (extension/llm/cache/README.md:137-142) doesn't list the new kind.
    • seq_new() may now return nullopt for "insufficient resources" (cache.h:114-115). But max_seqs() (110-113) still says callers can size themselves against it to avoid work seq_new would refuse. That no longer holds for this kind, and SessionTable (session_table.cpp:83-84) reports both causes as the same nullopt.
    • Fix this →

Thread Safety

  • (low confidence) A partly failed prepare_step isn't fenced (backends/cuda/runtime/cuda_kv_cache.cpp:1127-1178).
    • inflight_ is set only on success (1178). Suppose pool_.prepare() grows storage on the caller's stream, and then reserve_staging, upload/fence_staging or plan.plan fails. The backend's kv_prepared guard never arms, so abort_step() doesn't run.
    • A later ABI-2 seq_clone on cudaStreamPerThread could then read storage before the grow copy lands. This only applies to methods that run on a caller-provided stream; the default stream has no race.
    • I didn't confirm that pool_.prepare() leaves that copy unfenced. If it does, setting inflight_ as soon as pool_.prepare() succeeds closes the gap.

Performance

  • (major) Idle compaction has no hysteresis (backends/cuda/batching/cuda_executor.cpp:1117-1129).
    • The shrink trigger (2·live+1 < physical) and the target are the same value: compact_columns(live) gives min(max_seqs, 2·live) + 1 (cuda_kv_cache.cpp:1330-1333).
    • Every session that closes while the runner is idle triggers a resize 500 ms later. Draining nine idle-open sessions from 17 columns costs eight resizes (17→15→13→…→3→2).
    • At zero live sessions the cache drops to 2 columns. The next burst of nine admissions then pays 2→3→5→9→17 again: four resizes, each a device sync, a copy of every retained column and an invalidate_bindings() that drops all CUDA graphs for recapture. That undoes the rationale in the comment at cuda_kv_cache.cpp:1320-1324.
    • Compaction runs on the engine thread before wait_for (runner.cpp:804), so requests that arrive meanwhile queue behind it.
    • The 500 ms grace and the spare rule are hard-coded.
    • Fix: add hysteresis, for example shrink only when physical > 4·live+1, or floor at a decaying high-water mark. Make the grace and spare count CudaExecutorConfig knobs. Fix this →
  • (major) Admission-time growth trims the device's whole allocator and graph memory.
    • ensure_columns hard-codes trim_unused=true (cuda_kv_cache.cpp:1373-1381). Every resize, not just compaction, therefore calls CudaAllocator::release_cached_memory(device_): before allocating (cuda_kv_pool.cpp:530-532), after commit (610-616), and again on rollback (540-542).
    • That call runs cudaMemPoolTrimTo(pool, 0) and cudaDeviceGraphMemTrim(device). The latter is documented at extension/cuda/cuda_allocator.cpp:833-836 as releasing unused graph memory "cached by every user of the device".
    • So each admission that grows the cache makes the next forward re-reserve its workspace and graph memory, and the same goes for any other model or library on the device.
    • Fix: pass trim_unused only for compaction, and leave growth on the cached pool. Fix this →
  • (minor) Growth briefly holds old and new storage, up to 1.77× ABI 1's footprint (cuda_kv_cache.cpp:1325-1329; cuda_kv_pool.cpp:544-554 vs 598-600).
    • Every replacement is allocated before any old layer is freed.
    • With max_seqs = 21 (the probe default), 9→17 needs 26 column-widths and 17→22 needs 39. ABI 1 allocates its 22 up front and never allocates at admission.
    • So on a GPU sized for ABI 1, ABI 2 admission can return nullopt.
    • Fix: when the doubled width lands near max_seqs + 1, grow straight to it; 9→22 needs 31 and skips a resize. Otherwise, document the transient. Fix this →

Recommendation

Needs Discussion

  • CI. None of the CUDA jobs that exercise this diff has started on a80ab388, including both CUDA gate items, and MLX Voxtral realtime is still running. Prior qualification of 952486c40 does not carry over. To confirm the gate on this head:
    • unittest-cuda (system) must finish with only the four documented DFlash failures.
    • unittest-cuda (kernel) must actually run its tests, which it hasn't done on any recorded run.
    • The remaining CUDA and MLX jobs must pass or match the gate.
  • Code. There is no blocker, and ABI 2 is opt-in. The three major items need a decision: fix them, or explicitly accept them as follow-ups. They are idle-compaction hysteresis, device-wide trims on growth, and on_idle failure handling. I would fix the trim-on-growth item now. It changes allocator behaviour for every user of the device, and the fix is one line in ensure_columns.
  • Path to Approve. Once CI confirms the gate and the major items are resolved, this is an Approve.

Task list

  • Read the PR context, comments and documented expected-failure gate
  • Diff a80ab388 against main (ec5937f8), 29 files
  • Run three independent reviews against .claude/skills/pr-review/review-checklist.md
  • Consolidate and fact-check findings
  • Recheck current-head CI against the gate (no dispatch, rerun or cancel)
  • Post final review

@Gasoonjia

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

Please review head 66a6470f5f8938948a917477331947cb7f44d399 against current main. This revision bounds idle-compaction retries, separates shrink hysteresis from retained capacity, avoids device-wide trims during admission, fences partial preparation failures, and validates runtime-pitch lane layout. Native qualification requires finite, identical logits.

Local validation: 230 Runner tests, 6 CI workload tests, Python checks, and host syntax/type checks of the actual CUDA pool/cache/tests/executor passed. GPU execution on this head is still pending normal CI; previous-head results are not claimed as qualification.

Keep the review focused on the runtime physical-column feature and its necessary contracts. Do not expand historical compatibility, allocator-retention policy, router, prefix, or unrelated kernel tuning.

@claude

claude Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Claude finished @Gasoonjia's task in 48m 22s —— View job


Request Changes: 66a6470 changed Executor::on_idle() to return bool but left the two void overrides this PR added to the CI harness, so the muse-glimmer batching CI job can't compile and none of the native ABI-2 qualification runs; the other five findings are minor.

PR Review: #25621 (head 66a6470 vs origin/main)

Summary

Adds ABI 2 for the CUDA batched-sequence off-graph KV cache: seq_info[:,4] carries a runtime physical column pitch, so CudaKVPool can grow owner columns on admission and compact them from a new Executor::on_idle() hook after 500 ms without cache activity.

There is one blocker, listed under Infrastructure. The CI harness overrides on_idle() with the old void signature, so the batching CI job fails to compile before any ABI-2 GPU qualification runs. The other findings are minor.

I found the blocker by reading the code, not by compiling it. CUDA CI on this head is still queued: 14 of 35 runs have passed and none have failed.

I did not fully review backends/cuda/runtime/test/test_cuda_backend_execute.cpp, backends/cuda/tests/test_offgraph_kv_batched_sequence.py, or the parts of backends/cuda/runtime/test/test_cuda_kv_cache.cpp outside ColumnGrowthFollowsPendingHistoryWrites.

Code Quality

  • Post-commit failure in resize_columns. CudaKVPool::resize_columns still runs a cudaStreamSynchronize and CudaAllocator::release_cached_memory after it has committed the new storage and set *committed = true (cuda_kv_pool.cpp:615-621).
    • That creates a committed-but-failed result. ensure_columns has to reconcile columns_ and the column map and then poison the cache (cuda_kv_cache.cpp:1389-1399).
    • It also forces a caller-specific no-host-allocation rule onto the generic allocator (cuda_allocator.cpp:847-850). The PR enforces that rule in tests by replacing global operator new in cuda_allocator_exit.cpp.
    • The header comment (cuda_kv_pool.h:92-93) blames failed "allocator trimming", but release_cached_memory returns void. Only the sync can fail.
    • Fix: run the post-commit sync and trim from compact_columns, after ensure_columns has reconciled. Then resize_columns can only fail before commit, and the committed out-parameter, the poison branch and the allocator constraint all go away. The pre-allocation trim at lines 535-537 can stay. Fix this →

Infrastructure

  • Blocker: the CI harness no longer compiles.
    • 66a6470 changed the base to virtual bool on_idle() (extension/llm/batching/executor.h:100). The overrides this PR added earlier are still void: EvidenceExecutor at .ci/scripts/muse_glimmer_batching_workload.h:110 and FakeExecutor at .ci/scripts/tests/muse_glimmer_batching_workload_test.cpp:39.
    • A void override of a bool virtual has a conflicting return type. That is a hard compile error with or without -Werror.
    • Where CI stops: the unittest-cuda-muse-glimmer-batching job runs test_muse_glimmer_batching_workload.py at cuda.yml:694 under set -eux. Its test_workload_without_a_model compiles this test and asserts a zero return code. So the job stops before the CUDA build, the batching ctest, the runtime-KV probe and check_runtime_kv_columns.py.
    • Other jobs that will fail: the smoke build at cuda.yml:706 includes the same header. So does the batching e2e job, which builds the smoke binary at test_model_e2e.sh:613. Both would fail the same way.
    • Effect on the reported local validation: the "CI workload tests passed" result can't include test_workload_without_a_model at this head.
    • Fix: return bool from both overrides. EvidenceExecutor should return inner_.on_idle(), and FakeExecutor should return a configurable value. successful_batch_owners should check that false passes through the wrapper. Fix this →
  • Logging is off for every CUDA runtime unit test. cuda.yml:819 now adds -DEXECUTORCH_ENABLE_LOGGING=OFF to the configure for all 13 unittest-cuda-runtime targets.
    • That includes the unrelated allocator, guard, stream and weight-cache tests. When one of them fails in CI, its ET_LOG(Error, …) context is gone and only the gtest assertion is left.
    • Fix: if the goal is to qualify KV recovery and graph counters without logging, build that variant in a separate directory for just the tests that need it (test_cuda_kv_cache, test_cuda_backend_execute). Leave the rest at the default. Fix this →

Testing

  • The 500 ms idle grace is untested. This covers the grace itself (cuda_executor.cpp:1113-1119) and the activity stamps that postpone it: open_session, close_session and clone at cuda_executor.cpp:654-664, and execute_raw at :716 and :725.
    • The probe's idle op always sleeps 550 ms before calling on_idle() (runtime_kv_columns_probe.cpp:290-292).
    • Its new, remove and clone ops go through cache_control(), which doesn't stamp activity.
    • So the native check would still pass if the grace were 0 or a stamp were dropped. Yet the grace is what stops compaction, with its resize and graph recapture, from firing in every short gap between batches.
    • Fix: make the grace a CudaExecutorConfig field. With a long grace, have the probe assert that an idle right after a step leaves column_resize_count unchanged. This makes the test deterministic and removes the fixed sleep. Fix this →

API Design

  • Zero graph counters are ambiguous. graph_metrics (cuda_kv_cache.h:99-104, cuda_kv_pool.cpp:442-453, exposed as CudaExecutor::graph_metrics) reads the delegate's CUDA graph counters through the KV pool's descriptors_.
    • Two cases return {0,0,0}: a method with no bound handle, and any layout other than the sequence layout. Both look the same as "never captured".
    • The native qualification captures == (2 if runtime_columns else 1) (check_runtime_kv_columns.py:178) depends on this accessor.
    • Fix: return std::optional<CudaGraphMetrics>, with nullopt when nothing tracks the method, so the absence is explicit. Fix this →

Performance

  • Every quiet period shrinks to the floor, and the next burst regrows. The idle trigger is physical > 2 && 4*live+1 < physical (cuda_executor.cpp:1113-1139).
    • With no live sequences it fires for any physical >= 3, and compact_columns(0) shrinks to the 2-column floor.
    • So after any quiet period over 500 ms, the next burst regrows step by step. For 5–8 sessions that is 2→3→5→9, the path check_runtime_kv_columns.py exercises. Even 2 sessions pay 3→2→3 per cycle.
    • Each resize reallocates and copies KV storage and calls invalidate_bindings(). Every graph-enabled method then runs eagerly and recaptures on the first requests after the idle period.
    • Fix: if first-request latency after idle matters, keep a floor above 2 when live == 0, or wait longer before shrinking below it. Fix this →

Recommendation

Request Changes

The on_idle() return-type mismatch stops the CI workload test and the smoke binary from compiling. That blocks the only job that runs native ABI-2 qualification. The other findings are minor and could be follow-ups.

  • Diff 66a6470 against origin/main
  • Three independent reviews, consolidated and fact-checked
  • Review posted

@Gasoonjia

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

Please review current head e05c4cab7f1b0eedb7e7f9a872721e8f7a2bcb07 against latest main. This adds only the CI workload wrapper and test adaptation for the bool idle-maintenance contract; the standalone test checks forwarding both success and failure and passes locally. Three independent reviewers checked this two-file delta without findings. The previous native batching job failed at those stale void overrides before any GPU test ran.

Keep this PR focused on runtime physical columns and the current exporter/runtime contract. New-head CI must qualify independently; no workflow dispatch, rerun or cancellation is requested.

@Gasoonjia

Copy link
Copy Markdown
Contributor Author

All four minor follow-ups from the approved review are addressed in b6a67f8696ffa73186bf28d79fca174b245f7857: documented CUDA batching Make target, a no-skip native cache CI guard, restoration of the original executor comments, and a correctness-only probe. The Make target uses the actual CPU count. Eight local CI-wiring checks and the rebuilt same-PTE A100 probe passed; production runtime/kernels are unchanged by this cleanup. The new shrink follow-up is #25647, directly based on this branch. Latest push CI remains in progress; the observed macOS lowbit failure occurs in Miniconda setup before the ExecuTorch checkout.

@Gasoonjia
Gasoonjia force-pushed the gasoonjia/runtime-columns-abi2-pr1 branch from 6c1bcce to 3bff904 Compare November 24, 2026 09:44
Grow physical session columns on admission using the default five-field sequence interface, preserving live KV and rebinding CUDA graphs after storage moves. Cover failed admission recovery and exact mini-model logits; keep shrinking as a separate follow-up.

Authored with OpenAI Codex assistance.
Use the documented batching target, enforce native cache coverage without skipped cases, and retain only correctness and graph counters in the probe. Bound the Make target parallelism to the available CPU count.
@Gasoonjia

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

Rebased onto main 5f6a52320 (CUDA DFlash symmetric per-query windows); please review the current feature diff at 21587c46ef8336a06cf49fbc134d7c2971691a9a. This PR remains growth only, with the latest five-field interface by default.

A100 checks of the rebased PR1/PR2 stack passed Python/kernel tests, native cache/Runner/allocator tests, fresh cell/sequence DFlash tests, and exact solo growth/shrink/regrowth with CUDA graphs. Normal push CI is pending; the allocator suite has four expected no-pool-only skips on this pool-enabled device.

@claude

claude Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Claude finished @Gasoonjia's task in 30m 46s —— View job


Approve: at 21587c4 I found no problems with live KV preservation, allocation-failure rollback or graph rebinding; the five follow-ups below (one test gap, one missing fallback, three cleanups) are all minor.

Detailed review

PR Review: #25621

Summary

The PR grows the batched-sequence KV storage's physical columns geometrically on admission (2 → 3 → 5 → 9 → … → max_seqs + 1). The pitch reaches the kernels as seq_info field 4. Each resize copies the live owner columns into the new storage and drops bindings and captured graphs, and a failed admission is rolled back.

I found no issues in live KV preservation, allocation-failure rollback or graph rebinding. Test coverage has one gap (grow-mode clear()). The other four items are a missing fallback and three cleanups.

Not fully reviewed:

  • backends/cuda/runtime/test/test_cuda_kv_cache.cpp: I read the new CudaRuntimeColumnCacheTest tests and their fixtures and skimmed the other changed lines.
  • backends/cuda/tests/test_offgraph_kv_batched_sequence.py and backends/cuda/tests/test_sdpa_varlen.py: skimmed.
  • examples/models/muse-glimmer/tests/runtime_kv_columns_probe.cpp and check_runtime_kv_columns.py: partly read.

CI was not rerun or dispatched. The A100 results and the four expected allocator skips come from your comment; I did not reproduce them.

Code Quality

  • stride_kr and stride_vr are dead kernel parameters.
    • They are declared at backends/cuda/triton/kernels/sdpa_varlen.py:60,63 and :215,218.
    • Both kernels then overwrite them with columns * stride_kc and columns * stride_vc, taken from seq_info field 4 (:93-95, :256-258).
    • The wrapper still passes key.stride(0) and value.stride(0) (:522,525, :561,564). The docstring at :416 says that value is not the row pitch.
    • So each launch passes a value that is ignored and would be wrong if a later change used it.
    • Fix: drop the two parameters and the four arguments. Fix this →
  • offgraph_kv_constant_methods is a change column growth doesn't need.
    • The helper is at backends/cuda/passes/lower_offgraph_kv.py:149-156 and is used once, at examples/models/muse-glimmer/export/export_solo.py:680.
    • It re-parses the manifest the caller just built, to return a value the caller already has: manifest["max_seqs"] is max_kv_seqs (export_solo.py:347, :522).
    • It also replaces the documented MAX_KV_SEQS_METHOD constant with a bare "get_offgraph_kv_max_seqs" string in the backend.
    • The sibling keys MAX_CELLS_METHOD and DRAFT_MAX_KV_SEQS_METHOD stay named constants in export_solo.py. The C++ side reads the key through kMaxSeqsMethod (backends/cuda/batching/cuda_executor.h:54).
    • Fix: restore constant_methods[MAX_KV_SEQS_METHOD] = max_kv_seqs with its comment, and drop the helper and its assertions (test_offgraph_kv_batched_sequence.py:550-553, :596-597). Fix this →
  • Rerunning check_runtime_kv_columns.py with the same --output-dir fails.
    • run() reuses <output-dir>/growing and <output-dir>/preallocated with mkdir(exist_ok=True) (examples/models/muse-glimmer/tests/check_runtime_kv_columns.py:121-122).
    • The probe refuses to overwrite an existing logits file (runtime_kv_columns_probe.cpp:145, "preserve prior logits").
    • Outside Actions, with no RUNNER_TEMP set, the CI command writes to /tmp/muse_glimmer_runtime_kv_columns. Running it locally a second time fails, and only after the full export. CI itself is unaffected, because each job starts with a clean temp directory.
    • Fix: delete the per-mode directory before starting the probe. Fix this →

Testing

  • The new grow-mode branch of clear() has no test.
    • The branch adds the all-streams fence and inflight_ = false (backends/cuda/runtime/cuda_kv_cache.cpp:887-901).
    • ClearRecoversAbandonedDFlashStep (test_cuda_kv_cache.cpp:2429) covers only DFlash, where grow_columns_ is false.
    • The fixture's clear() at :2209 runs before any storage is allocated, so it never reaches the fence.
    • No test abandons a prepared grow-mode step with clear() and then admits and prepares again. If a regression left inflight_ set, every later seq_new and seq_clone would return nullopt and no test would fail.
    • Fix this →

Performance

  • When the doubled resize can't be allocated, the admission is refused without trying a smaller one.
    • ensure_columns computes a single target, min(max_seqs + 1, max(live + 1, 2 * (columns_ - 1) + 1)), and calls resize_columns once (backends/cuda/runtime/cuda_kv_cache.cpp:1305-1309, :1341-1342).
    • Example: 16 owners use 17 physical columns, and max_seqs >= 32. The 17th admission needs new storage for 33 columns, about 1.94× the current KV, while the old storage is still held. If the device can fit 18 columns (about 1.06×) but not 33, the admission fails even though one more column would fit.
    • This is separate from the documented old-plus-new peak.
    • A retry is cheap. A failed resize_columns leaves the old storage and bindings intact (FailedColumnGrowthKeepsOldStorageAndBindingsUsable). The existing column mapping also fits live + 1, because growth only happens when owner columns 0..columns_-2 are all taken.
    • Fix: on allocation failure, retry once at live + 1 before refusing. Fix this →

Recommendation

Approve

None of the five items blocks merging. The clear() test and the live + 1 retry are the most useful follow-ups.

This branch was successfully deployed

1 active and 1 inactive deployments
upload-benchmark-results — 21587c46 Deployed Nov 24, 2026 by Gasoonjia via upload-benchmark-results #23383
cadence — 21587c46 Deployed Nov 24, 2026 by Gasoonjia via hifi-op-test / hifi4 #40762
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant