Skip to content

[CUDA] Compact runtime KV columns after sessions close - #25647

Open
Gasoonjia wants to merge 5 commits into
gasoonjia/runtime-columns-abi2-pr1from
gasoonjia/runtime-kv-column-shrink-pr2
Open

Gasoonjia wants to merge 5 commits into
gasoonjia/runtime-columns-abi2-pr1from
gasoonjia/runtime-kv-column-shrink-pr2

Conversation

@Gasoonjia

@Gasoonjia Gasoonjia commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

CUDA KV caches compact physical columns after explicit session closure, low occupancy and a quiet interval, preserving still-open histories. CUDA graphs rebind after storage moves, and bounded allocator trimming returns retired KV storage. Compaction defaults to a 500 ms delay; the serving CLI can disable it with --kv_column_compaction_delay_ms=-1.

Stacked on #25621. A100 native tests and same-PTE mini checks cover failure rollback, Runner-driven shrink/regrow, exact logits, the occupancy boundary, disabled compaction and preservation of unrelated allocator reserves. DFlash tests cover speculative continuation after a live target-cache column moves.

Authored with OpenAI Codex assistance.

@Gasoonjia

Copy link
Copy Markdown
Contributor Author

@claude /pr-review Please review current head bd0aa213c9f3ab94558ac4e7e50d615a268f27db against its direct base PR #25621. This follow-up only adds physical-column compaction after explicit closure, low occupancy and a quiet interval; still-open histories remain live. It includes runner idle maintenance, CUDA graph rebinding and an existing allocator trim after old-buffer fencing. A100 validation passed: 80 cache tests, 231 runner tests, 2 stream tests, same-PTE finite bit-exact growth/shrink/regrow with wrapped Ring and inactive open owners, and CUDA graph capture/replay. Paired mini steady decode c1/c2/c4/c8 has a maximum observed regression of 0.59%; the inherited narrowed probe also passed. No 5090/full-model performance claim. Please finish with Approve / Request Changes / Needs Discussion. Do not rerun or dispatch CI.

@pytorch-bot

pytorch-bot Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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, 1 Unrelated Failure

As of commit 6d9ecfd with merge base 5f6a523 (image):

BROKEN TRUNK - The following job 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 24, 2026
@claude

claude Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

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


Review of bd0aa21 against #25621: the problems are in the compaction policy and how it is wired in, not in the column remap. Compaction is on by default with no off switch, and every idle gap triggers a shrink→regrow cycle with graph recapture whose cost has not been measured. Separately, the CI EvidenceExecutor wrapper drops the new on_idle hook, so no CI job runs real CUDA compaction through the Runner. Request Changes.

PR Review: #25647, detailed findings

Summary

The PR adds idle-time compaction of CUDA KV physical columns. It adds CudaKVCache::compact_columns, CudaExecutor::on_idle/compact_kv_columns, and a Runner Executor::on_idle hook that is re-armed after a failure. Compaction moves live owners into the lowest columns, rebinds graphs and trims the allocator.

Problems found:

  • Default-on compaction (major): compaction is enabled for every CudaExecutor and there is no documented way to turn it off. After each idle gap, the next burst replays the whole growth and graph-recapture sequence. The steady-decode numbers do not cover that path.
  • CI wrapper drops the hook: the in-tree CI EvidenceExecutor decorator does not forward on_idle.
  • on_idle contract: the quiet interval relies on an undocumented 20 ms poll, and the bool result cannot tell "not yet due", "not applicable" and "failed" apart.
  • Smaller issues: test gaps, a missing threading note, extra copies on growth, and two code-quality points.

Not traced: whether the DFlash executor keeps target-cache addresses across a target compaction. Only its on_idle hunk was reviewed. Nothing was built or run here; as you asked, CI was not re-run or dispatched.

Code Quality

  • examples/models/muse-glimmer/runtime/cuda_dflash_executor.cpp:794-797: on_idle() forwards to target_->on_idle() without the failed_ check that every other entry point in this file makes (:733, :800, :844). A failed DFlash executor therefore keeps compacting and rebinding its target cache. Fix this →

  • backends/cuda/runtime/cuda_kv_pool.cpp:514: the new same-width relocation path (columns == columns_ && relocate) is never called.

    • The cache only calls pool_.resize_columns when target != columns_ (cuda_kv_cache.cpp:1400).
    • The only direct test call is an identity growth (test_cuda_kv_cache.cpp:3519).
    • Separately, cuda_kv_cache.cpp:1379 re-checks sequence.column < target - 1, which the enclosing if at :1377 already guarantees.

    Fix this →

Infrastructure

  • .ci/scripts/muse_glimmer_batching_workload.h:103: ci::EvidenceExecutor forwards initialize() and preferred_batch_tokens() but not the new on_idle(). The base default returns true, so the CUDA serving smoke never compacts and nothing reports it.

    • The smoke wraps the real executor at .ci/scripts/muse_glimmer_batching_smoke.cpp:75 and runs it through the Runner owned by ServingRuntime.
    • The probe calls on_idle() by hand, and runner_test.cpp only uses FakeExecutor.
    • So no CI path exercises the Runner calling a real CudaExecutor::on_idle. Untested as a result: 20 ms polling reaching the 500 ms quiet interval, re-arm on close, and regrow under live traffic.
    • Because the default is a no-op returning true, any future decorator will also drop maintenance without any signal.

    Fix this →

Testing

  • extension/llm/batching/test/runner_test.cpp:382: IdleHookRunsBetweenBatchesOnTheEngineThread would still pass if on_idle moved before the continue, i.e. ran after every batch while more work is ready. A single engine thread cannot call it during the held execute anyway. Add two back-to-back ready batches and assert that on_idle is not called between them.
  • backends/cuda/runtime/test/test_cuda_kv_cache.cpp:3399-3412: CompactionReturnsUnusedReservationToTheDriver reads before without trimming first. The ≥ 8 MB drop can then come from blocks that earlier tests left cached in the process-wide pool, rather than from the KV backing. Trim before reading before.
  • backends/cuda/runtime/test/test_cuda_kv_cache.cpp:2923: GrowthAndSparseIdCompactionPreserveAllKV dropped the assertion that seq_rm alone leaves physical_columns and allocated_bytes unchanged. That invariant is what keeps storage moves out of the close path, so keep it, placed before the new compact_columns(0). Fix this →
  • No cache-level test makes a contraction with relocated owners fail. An example is an allocation failure while moving columns 5 and 7 to 0 and 1, followed by checking that columns_, owner columns, KV data and bindings are unchanged. The only failure test is the pool-level identity growth at test_cuda_kv_cache.cpp:3519.
  • examples/models/muse-glimmer/tests/check_runtime_kv_columns.py (main): --check-compaction is an on/off flag with one caller, .github/workflows/cuda.yml:719, which always sets it. A local run without the flag silently skips the new scenario. Fix this →

API Design

  • extension/llm/batching/executor.h:89-94: the bool on_idle() contract cannot express "not yet due", "nothing to do / not supported" and "failed" separately, and it does not say how often the hook is called.

    • Quiet interval depends on a 20 ms poll: it only fires because the Runner re-polls on its existing wait_for(20ms) (runner.cpp:819). compact_columns returns Ok when it skips because the cache is not yet quiet (cuda_kv_cache.cpp:1285-1288). The hook therefore reports success either way, and the Runner keeps calling it every 20 ms while idle. If the Runner switched to an untimed wait, compaction would stop with no error.
    • NotSupported counted as a failure: a fixed-column cache returns NotSupported (cuda_kv_cache.cpp:1271-1272). CudaExecutor::on_idle logs that at Error level and returns false, so the Runner counts a maintenance failure on every re-arm (cuda_executor.cpp:1122-1128). This is latent in-tree, but a fixed column policy is a configuration, not a failure.
    • Re-arm triggers: the header says retries pause "until another batch or owner closure". The code only re-arms on a CloseCommand (runner.cpp:885). The owner closures on the open and clone failure paths (runner.cpp:930, :998) do not re-arm.

    Fix: either document the polling cadence and the re-arm triggers, or return a small status (e.g. done / retry-at / failed) and treat NotSupported as done.

Thread Safety

  • backends/cuda/batching/cuda_executor.h:237-238: compact_kv_columns() is a new public mutator, but unlike its neighbours it does not say it must be called between executes, on the engine thread. Its guard reads the plain bool raw_executing_ (cuda_executor.cpp:1104-1105). An application thread calling it while a Runner drives the executor is a data race on that flag. Fix this →

Performance

  • backends/cuda/batching/cuda_executor.h:94 (major): compaction is on by default (500 ms) for every CudaExecutor.

    • No off switch: nothing in-tree except the probe sets the delay. Negative values are rejected (cuda_executor.cpp:340), and only an undocumented milliseconds::max() disables compaction.
    • Shrink/regrow cycle: after any idle gap over 500 ms with occupancy below 25%, the columns shrink (e.g. 17→2). The next burst then regrows them 2→3→5→9→17 through ensure_columns (cuda_kv_cache.cpp:1363-1370).
    • Recapture on every resize: each resize calls invalidate_bindings() (cuda_kv_pool.cpp:589). Every graph-enabled handle then takes an eager step plus a recapture about log2(N) times per burst, while earlier sessions in that burst are already decoding. Before this PR that cost was paid once per process.
    • Not measured: the paired numbers cover steady decode only, not first-token latency after an idle gap.
    • Undocumented policy: the config comment does not mention the hard-coded 25% threshold or spare = live (cuda_executor.cpp:1114-1121).

    Please measure first-token latency for a burst after an idle gap, and either add a documented way to disable compaction (e.g. std::optional) or default it to off. Also consider hysteresis, such as never shrinking below the previous burst's high-water mark.

  • backends/cuda/runtime/cuda_kv_cache.cpp:1309: release_cached_memory(device) runs cudaMemPoolTrimTo(pool, 0) on the device's shared allocator pool (extension/cuda/cuda_allocator.cpp:815). That releases blocks cached by every other user of the pool on that GPU, and their next allocation has to re-reserve from the driver. The only other caller (cuda_backend.cpp:981-982) is delegate teardown, and its comment calls out this device-wide scope. Consider a non-zero minBytesToKeep, or a dedicated pool for KV.

  • backends/cuda/runtime/cuda_kv_pool.cpp:556-578: growth now issues one cudaMemcpy2DAsync per retained owner, per layer, for K and V. Before, it issued one per layer, and every pair during growth maps a column to itself. With 48 layers and 16 owners that is 1536 launches instead of 96. These run on the engine thread at admission, and the default-on compaction above makes growth recur. Merge runs where both from and to are consecutive. Fix this →

  • extension/llm/batching/runner.cpp:803-808: on_idle() runs as soon as execute_one_batch_() returns false, without checking inbox_ or is_running_(). An open that arrived in the meantime, or a shutdown, then waits behind a full compaction: allocation, copies, several stream syncs and the trim. The open may then regrow the columns straight away. Fix this →

Recommendation

Request Changes

None of these findings is a correctness defect in the remap, the copy bounds or the old-buffer fencing. Two things block approval:

  1. EvidenceExecutor must forward on_idle. Without that, CI never runs Runner-driven compaction on real CUDA.
  2. Default-on compaction needs a documented off switch, and either first-token latency data for a burst after an idle gap or a default of off.

The remaining items can be fixed in this PR or in a follow-up.

Review steps

  • Gathered context: diff against origin/gasoonjia/runtime-columns-abi2-pr1, a single commit, 17 files.
  • Ran three independent reviewers.
  • Merged duplicate findings.
  • Checked every finding against the code. Dropped: findings about the error-poisoning paths, wall-clock flakiness in the Python check, and peak memory while shrinking, which were either unconfirmed or too minor, and the silent catch (...), which matches the other catch sites in runner.cpp.

--- · Branch: gasoonjia/runtime-kv-column-shrink-pr2

@Gasoonjia

Copy link
Copy Markdown
Contributor Author

@claude /pr-review Please re-review current head 0a09ac4577ece45e02fab50344f71d09dbad6dfa against direct base #25621. This single update resolves the confirmed findings from your previous Request Changes: forwarding on_idle through CI/DFlash decorators, skipping maintenance with queued commands or shutdown, re-arming only after actual owner closure, documented optional disable/500 ms/low-occupancy policy, bounded pool-only trimming, coalesced copies with host bookkeeping before GPU allocation, and contraction-failure rollback plus actual Runner coverage.

A100 validation passed: 81 cache, 232 Runner, 27 allocator and 2 stream cases; four allocator fallback-only cases correctly skip on this memory-pool device. Same-PTE finite exact logits and Runner outputs pass through growth/shrink/regrowth while preserving inactive open histories. A paired actual-Runner mini burst test (ABBA ×4, same CPU/GPU/PTE, equal 600 ms idle gap) measured survivor TTFT 1.146→1.160 ms and regrown eight-session TTFT 1.608→1.680 ms. This measures idle/regrowth cost, not a full-model or 5090 claim. Ten local CI-wiring/workload checks and formatting passed.

Please finish with Approve / Request Changes / Needs Discussion. Do not dispatch, rerun, or cancel CI.

@claude

claude Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

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


Request Changes: idle KV-column compaction is on by default, no in-tree Muse Glimmer serving or DFlash path can turn it off, and no test checks the disabled path or the bounded trim.

PR Review: #25647, detailed findings

Summary

The PR shrinks the CUDA off-graph KV cache's physical columns after sessions close. While idle, the Runner calls the new Executor::on_idle() hook, and CudaExecutor::on_idle runs compact_columns, which moves live owners into fewer columns and trims the allocator pool.

Remaining problems:

  • Automatic compaction defaults to 500 ms, and no in-tree serving path can change or disable it.
  • The tests cannot tell bounded trimming from unbounded, or the disabled policy from the enabled one.
  • There are smaller API and code-quality issues.

Nothing was built or run for this review, and CI was not touched. The A100 results are the author's.

API Design

  • The CudaAllocator::release_cached_memory docs do not cover the new parameters (extension/cuda/cuda_allocator.h:130-158).

    • min_bytes_to_keep has only the lone // line at 154, outside the /** */ block. trim_graph_memory is not documented at all.
    • The sentence "Unused graph memory is trimmed device-wide…" is now true only when trim_graph_memory is true.
    • With a negative index, the same min_bytes_to_keep applies to each device's pool separately, and the docs don't say so.

    Add @param entries for both parameters. Alternatively, leave release_cached_memory unchanged and give the KV cache its own pool-only trim function. Fix this →

Testing

  • No test would fail if compaction trimmed the pool to zero (backends/cuda/runtime/test/test_cuda_kv_cache.cpp:3401-3417).

    • CompactionReturnsUnusedReservationToTheDriver calls release_cached_memory(device) before reading before, so no other user's unused reservation is left in the pool.
    • An unbounded cudaMemPoolTrimTo(pool, 0) would give the same after, and every assertion would still pass, including the bound at 3417.
    • The allocator test at test_cuda_allocator.cpp:926 passes min_bytes_to_keep = 0, so no test anywhere uses a nonzero value.

    After the initial trim, free an unrelated block into the pool. After compaction, assert that its bytes are still reserved. Fix this →

  • Nothing tests the disabled policy or the 25% threshold (examples/models/muse-glimmer/tests/runtime_kv_columns_probe.cpp:289-308, check_runtime_kv_columns.py:304-306).

    • In the -1 (nullopt) run, the first idle poll after the last close satisfies wait_for(9, 1), before any 500 ms delay could expire. The run would still pass if nullopt fell back to the default delay.
    • idle_columns is computed from the flag at line 294 and returned as is, so the Python asserts at 304-305 only compare the flag with itself.
    • No unit test covers kv_column_compaction_delay = std::nullopt or the 4 * live + 1 >= physical_columns gate at cuda_executor.cpp:1117-1118.
    • Every session in a generate() call gets the same prompt {1, 2, 3, salt} and seed 0. The output comparison at 306 therefore cannot detect two owners being swapped during remapping.

    Fix this →

Performance

  • Compaction is on by default, and in-tree deployments cannot turn it off (backends/cuda/batching/cuda_executor.h:92-97).

    • Only the probe sets kv_column_compaction_delay. These all use the 500 ms default:

      • the factory at examples/models/muse-glimmer/runtime/backend_factory.cpp:42-48;
      • the DFlash target_config at cuda_dflash_executor.cpp:547-557;
      • the legacy CudaExecutor::create overload at cuda_executor.cpp:322.

      MuseGlimmerBackendConfig has no field for the delay either. So no serving or DFlash deployment can use the documented "nullopt disables automatic compaction".

    • After a 500 ms lull below 25% occupancy, the next burst has to regrow the columns. Each regrowth resize invalidates bindings and recaptures CUDA graphs.

    • The memory needed for regrowth has already been returned to the driver. Under memory pressure, regrowth can fail, which shows up as sessions_refused.

    • A request that arrives just after the idle check waits on the engine thread until the whole compaction finishes.

    • The only measurement is the mini-model ABBA burst, where regrown eight-session TTFT went from 1.608 to 1.680 ms. There is no full-model measurement, and no test runs DFlash speculation after a target compaction.

    Pass the delay through MuseGlimmerBackendConfig into both executors, or default it to std::nullopt until a full-model measurement supports turning it on. Fix this →

Code Quality

  • owner_closed_ is a member flag used as a side channel (extension/llm/batching/runner.cpp:567). It is set at 936, 954 and 1006, and reset and read at 889 and 902. Instead, have the Open, Close and Clone overloads of process_command_ return whether they closed an owner, and OR the results in the std::visit loop. Fix this →

  • DFlash on_idle counts execute failures as idle-maintenance failures (examples/models/muse-glimmer/runtime/cuda_dflash_executor.cpp:796).

    • Failed batches re-arm the hook, because execute_one_batch_ returns true for them (runner.cpp:1272).
    • Once failed_ is set, each re-armed idle poll returns false and increments idle_maintenance_failures, although no maintenance ran.

    Return true when failed_ is set. Fix this →

  • The virtual compact_columns has a default argument (backends/cuda/runtime/cuda_kv_cache.h:111-113).

    • Calls through CudaKVCache get a zero quiet interval, but the override at cuda_kv_cache.cpp:1268 has no default. Which call forms compile therefore depends on the static type.
    • No other virtual function in the class has a default argument.

    Pass the interval explicitly at the call sites. Fix this →

Recommendation

Request Changes

Two things block approval:

  • The off switch. The PR documents nullopt as the way to disable automatic compaction, but no in-tree serving path can pass it. The 500 ms default has been measured only on the mini model. Passing the setting through, or defaulting to nullopt, is a small change.
  • The two Testing gaps. Without those tests, the last round's "optional disable" and "bounded pool-only trimming" fixes are unverified.

The API Design and Code Quality items can be fixed in this PR or in a follow-up.

Review steps

  • Gathered context: 2 commits on base b6a67f8, 21 files, +1125/−67, with no net .github/ change. The latest update, bd0aa21..0a09ac4, touches 18 files.
  • Ran three independent reviewers. Between them they read every changed file and reported 35 candidate findings.
  • Merged duplicate findings into seven.
  • Checked every finding against the code. Dropped as invalid, pre-existing or by design: silent test skips, the relative .ci header include, the cost of the 20 ms poll, the re-arm after an open rollback, ModuleExecutor not forwarding the hook, the quiet-interval reset after an explicit no-op compaction, and peak memory while compacting.
  • Built and ran nothing. CI was not dispatched, rerun or cancelled.

· Branch: gasoonjia/runtime-kv-column-shrink-pr2

@Gasoonjia

Copy link
Copy Markdown
Contributor Author

@claude /pr-review Please re-review current head 8c92806090ebe620b2752590bc8b229914854fe3 against PR1 (6c1bcceb51fb9e218e0811b3be2fc54f32eda7ce). Your final review's findings are addressed together:

  • The default-on policy can be disabled through the serving CLI, backend factory, DFlash target and both CudaExecutor creation interfaces; -1 disables, 0 uses the next idle opportunity, and 500 ms remains the default.
  • Real BatchSequence mini tests wait beyond 500 ms and observe actual physical columns for disabled/zero/default policies and the strict 25% boundary. Runner owners have distinct prompts. Bounded-trim tests retain a separate 32 MiB reserve and prove that a subsequent unbounded trim releases it.
  • Closed-owner tracking returns from command processing rather than using a mutable side channel; failed DFlash execution makes maintenance a no-op; compact_columns callers pass the delay explicitly; allocator API docs and the two cppcheck false positives are fixed.

A100 current-source qualification passed: 81 cache, 232 Runner, 27 allocator (four expected no-pool-only skips), two stream tests; same-PTE finite exact growth/shrink/regrow and graph checks; CLI build/validation and DFlash host cases. Three independent blind follow-up reviews found no new issues. PR1's only new change confines two POSIX workflow-execution checks to supported hosts. Normal push-triggered CI is running; please finish with Approve / Request Changes / Needs Discussion and do not dispatch or rerun CI.

@claude

claude Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Claude finished @Gasoonjia's task in 34m 36s —— View job


Approve: both blockers from the last review are fixed, and only three minor items remain: a config doc that misstates the 25% threshold, a two-owner contraction test that cannot tell its owners apart, and no DFlash test that keeps decoding after the target cache moves a live owner.

PR Review: #25647, detailed findings

Summary

The PR shrinks the CUDA KV cache's physical columns while the Runner is idle, once sessions have closed, occupancy is low and a quiet interval has passed. The latest commit lets every in-tree serving path set or disable that interval, and adds Runner, policy and bounded-trim tests.

Three minor problems remain. None of them is a correctness defect in the compaction itself:

  • The config doc measures the 25% threshold against the wrong column count.
  • The only test that relocates two owners gives both the same data.
  • No test keeps DFlash decoding after its target cache moves a live owner.

Nothing was built or run for this review, and CI was not touched. The A100 results are the author's.

API Design

  • The documented threshold is off by the scratch column (backends/cuda/batching/cuda_executor.h:92).

    • The CudaExecutorConfig doc says idle compaction "starts below 25% physical-column occupancy".
    • CudaExecutor::on_idle skips while 4 * live_sequences + 1 >= physical_columns (cuda_executor.cpp:1119-1120). That measures owners against the physical columns minus the scratch column.
    • Example: 2 owners in 9 physical columns is 22% physical occupancy, so by the doc it should compact, but it does not. check_policy asserts exactly that case at runtime_kv_columns_probe.cpp:345 ("25 percent occupancy must not compact").

    Reword the doc to "fewer than 25% of the non-scratch columns hold owners", or state the inequality. Fix this →

Testing

  • The only multi-owner contraction cannot tell its owners apart (backends/cuda/runtime/test/test_cuda_kv_cache.cpp:3723-3734, :3793-3798).

    • FailedContractionPreservesSparseOwners moves owners from columns 5 and 7 to columns 0 and 1, but it writes the same history = iota_rows(1) into both owners' K and V.
    • After the successful compaction, it checks only that flat_k columns 0 and 1 each equal history. It does not read flat_v there, and it does not check which column each owner ended up in, although it checks seq_info before compaction at :3790.
    • So a relocation that swaps the two owners, or copies column 5 into both destinations, still passes.
    • Every other contraction check keeps a single survivor: GrowthAndSparseIdCompactionPreserveAllKV, CloneAndContractionCopyWrappedRingHistory, CompactionReturnsUnusedReservationToTheDriver, and check_compaction, check_runner and check_policy in check_runtime_kv_columns.py. As a result, the run-coalescing copy in CudaKVPool::resize_columns (cuda_kv_pool.cpp:515-532) is never checked per owner.

    Seed distinct rows per owner, read back K and V, and assert each owner's seq_info column after compaction. Fix this →

  • No test keeps DFlash decoding after its target cache moves a live owner (examples/models/muse-glimmer/runtime/cuda_dflash_executor.cpp:795-798).

    • DFlash forwards on_idle to its target CudaExecutor, and MuseGlimmerBackendConfig defaults to 500 ms, so DFlash serving now compacts the target cache by default.
    • With the serving defaults (four sessions, no prefix cache), the target never grows past five columns, so idle compaction runs only once every owner has closed. With more sessions or a prefix cache, it can move live owners' columns.
    • The GPU CudaDFlashNative suite (cuda_dflash_native_test.cpp) never compacts the target, and the probe only drives a plain CudaExecutor.
    • The speculative path writes and rewinds target rows, and its kOwnerLimit static forward graphs recapture after a move. CI never runs any of that after a compaction.

    The test peer's four sessions never pass the idle gate with a survivor, so call the target's compact_kv_columns(0) directly: close all but the last-opened session, compact, and compare the survivor's next speculative steps with an uncompacted run. Fix this →

Recommendation

Approve

The two blockers from the last review are resolved:

  • Off switch: the delay now reaches --kv_column_compaction_delay_ms, MuseGlimmerBackendConfig, the DFlash target config and both CudaExecutor::create overloads. On the command line, −1 disables compaction and anything below −1 is rejected.
  • Tests: check_policy and check_runner wait past 500 ms and compare actual physical widths for −1, 0 and 500. CompactionReturnsUnusedReservationToTheDriver fails if the trim drops its unrelated 32 MiB reserve.

The three findings above are minor and can be fixed here or in a follow-up.

Review steps

  • Gathered context: 3 commits on 6c1bcce, 24 files, +1285/−84. The latest commit, 7c0bf60..8c92806, touches 14 files.
  • Ran three independent reviewers. Between them they read every changed file and reported 16 candidate findings.
  • Merged duplicates into 13: all three reviewers raised the default-on policy, and two raised the trim floor.
  • Checked every finding against the code. Dropped as resolved, by design or unreachable:
    • default-on compaction, now that the requested off switch reaches every in-tree path;
    • an Error log on every poll for fixed-column caches. It is unreachable because read_cache_geometry never sets dflash_block_size, so a CudaExecutor cache always grows;
    • an approximate trim floor, because cudaMemPoolTrimTo keeps only a total and other threads can use the pool during the resize. This only changes how much memory goes back to the driver;
    • no retry backoff after a failed maintenance, which is the documented contract;
    • a poisoned cache counting as an idle failure in CudaExecutor but not in DFlash, which needs a sticky CUDA error first;
    • the allocator unit test's loose bounded-trim check, since the KV test proves that memory is released;
    • token-only comparison in check_runner, since check_compaction checks a relocation at exact logits;
    • untested CLI and factory wiring, and the 500 ms default repeated across files. The assignments are trivial, and cuda_executor.h already repeats initial_capacity = -1 the same way;
    • the decorator-forwarding rule and the compact_kv_columns threading note, which earlier rounds asked for. A decorator's on_idle runs on the Runner thread, so it can meet the threading rule.
  • Built and ran nothing. CI was not dispatched, rerun or cancelled.

--- · Branch: gasoonjia/runtime-kv-column-shrink-pr2

Reclaim closed-owner storage between forwards after a configurable quiet interval, preserving still-open histories and recapturing graphs when columns move. Release observed frees through the existing CUDA allocator trim.

Authored with OpenAI Codex assistance.
@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 6d9ecfd1d29273b9f5b6d84160d5b5a542a67c9d. This PR remains directly stacked on #25621 and adds only explicit-close contraction, quiet-time maintenance and bounded trimming.

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 25m 3s —— View job


Approve: nothing in the rebased diff at 6d9ecfd blocks merging, and the one minor gap left is that no test runs the DFlash executor's on_idle, so if it stopped forwarding to the target, DFlash target compaction would silently stop.

Detailed review

Summary

Stacked on #25621, this PR lets the CUDA sequence-layout KV cache give physical columns back after sessions close. A new Runner hook, Executor::on_idle(), drives CudaExecutor compaction when occupancy is below 25% and the cache has been quiet for kv_column_compaction_delay (default 500 ms; nullopt or -1 turns it off). Compaction uses the same resize_columns path that growth now uses (coalesced 2D copies, rollback, graph rebinding). It then trims the shared pool to its earlier reservation minus the bytes it freed. No blocker or correctness defect was found; there is one minor test gap.

Testing

  • Minor: nothing tests that the DFlash executor forwards on_idle (examples/models/muse-glimmer/runtime/cuda_dflash_executor.cpp:795-798).
    • Why it matters: the only DFlash compaction test, SequenceTargetCompactionPreservesSpeculativeContinuation (examples/models/muse-glimmer/tests/cuda_dflash_native_test.cpp:800-910), compacts through Peer::compact_target, which calls CudaExecutor::compact_kv_columns(0) directly (line 154). Nothing in that file calls on_idle, and nothing in .ci/scripts checks column counts or KV metrics. If the override were deleted (the base Executor::on_idle returns true) or stopped forwarding to target_, every test would still pass, but DFlash serving would never compact its target. That is the regression the rule "Executor decorators must forward this hook" in executor.h is meant to prevent.

    • Test geometry: with one surviving owner the cache stays above the 25% threshold (4*1+1 >= 5), but an empty cache drops below it (4*0+1 < 5), so its 5 columns become 2.

    • Suggested fix:

      1. Pass std::chrono::milliseconds{0} as the trailing column_compaction_delay argument of the peer's cb::CudaExecutor::create (lines 49-55). No other test in the file calls on_idle, so none of them change.
      2. At the end of run(false), close owners[3], then add EXPECT_TRUE(executor_->on_idle()) and EXPECT_EQ(Peer::target_metrics(*executor_).physical_columns, 2).

      This can land as a follow-up. Fix this →

Recommendation

Approve

Nothing blocks merging. The only finding is a minor test gap, which can be fixed in a follow-up.

Review steps

  • Context: read the trigger comment, the earlier rounds and replies, and diffed 6d9ecfd against origin/gasoonjia/runtime-columns-abi2-pr1 ([CUDA] Grow batched-sequence KV columns at runtime #25621). Fetching the previous head 86de244 for an interdiff needed approval in this run, so I reviewed the whole current feature diff instead.
  • Reviewers: three independent reviewers went over the diff. Their roughly 25 candidates merged into about 20. All three raised the DFlash on_idle gap. None found a blocker or a defect in the column remap, copy bounds, rollback, graph rebinding or fencing.
  • Rebase onto main 5f6a523: main's change overlaps this PR only in three places: the cell-cache DFlash mask expectations, build_mask in cell_cache.cpp, and symmetric_window=True in the DFlash export. The new sequence-layout DFlash test compares two runs of the same re-exported fixture, and export_cuda_dflash_tiny.py matches export_dflash.py.
  • Fact-check: I checked every candidate against the code. These were not raised:
    • Compaction on by default (500 ms), with the default repeated in the config, the positional create, the DFlash config and the CLI: settled in earlier rounds. The off switch reaches every in-tree path, and the repetition matches initial_capacity = -1.
    • release_cached_memory gaining two defaulted parameters in the shared extension_cuda library: callers still compile unchanged, and docs/source/api-life-cycle.md covers only the source API life cycle, not binary compatibility.
    • Open-command rollback re-enabling idle maintenance: this can only happen while the Runner is stopping, so it is harmless. Clone rollback still re-enables it after an exception.
    • The trim floor's : 0 fallback: unreachable, because KV storage comes from the same pool through allocate_async. Races with other pool users were considered in earlier rounds.
    • Covered in earlier rounds:
      • the requirement that the whole cache be quiet (documented in cuda_kv_cache.h)
      • no retry or backoff after a failed compaction
      • peak memory during contraction
      • a poisoned cache counting as an idle failure
      • the relative .ci include
      • the 20 ms poll and the bool return contract
      • the growth of the positional overload (asked for earlier)
    • Harmless:
      • the test-only compact_kv_columns and its unused = 1 default
      • the pending_owners_.empty() guard
      • the probe flag name kv_compaction_delay_ms
      • the idle_maintenance_failures field having no comment
      • the CI fake's shared succeeds flag and its cppcheck suppressions
      • the allocator unit test's loose bound (the KV test covers it end to end)
      • the peer comment wording
      • the compact_columns interface doc
  • Not run: I built and ran nothing, and CI was not dispatched, rerun or cancelled.

--- · Branch: gasoonjia/runtime-kv-column-shrink-pr2

This branch was successfully deployed

1 active and 1 inactive deployments
upload-benchmark-results — 6d9ecfd1 Deployed Nov 24, 2026 by Gasoonjia via upload-benchmark-results #23384
cadence — 6d9ecfd1 Deployed Nov 24, 2026 by Gasoonjia via hifi5s-op-test / hifi5s #40763
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