Skip to content

fix(looper): key shared KV cache per batch and refresh on replay (#4182) - #4242

Merged
Qubitium merged 2 commits into
mainfrom
fix/issue-4182-shared-kv
Nov 16, 2026
Merged

Qubitium merged 2 commits into
mainfrom
fix/issue-4182-shared-kv

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Fixes #4182

TL;DR

Cross-layer KV reuse was keyed by layer only and published only when the slot was empty, so every batch of a reuse_kv layer (Hymba) consumed batch 0's K/V and the pre-quant FP capture was never replaced by the post-quant replay. shared_kv_cache_dict is now keyed by (layer_index, batch_idx), read per batch, and overwritten on every publish. The six smaller looper edge cases in the issue are also fixed.

1. Cross-layer KV reuse (main item)

Root cause

ForwardExecutor.run_single (gptqmodel/looper/forward_executor.py:447 on the parent commit) and run_parallel (:749) wrote shared_kv_cache_dict[layer_index] only when is None, and both read prev_kv = shared_kv_cache_dict.get(layer_index - 1) once before the batch loop (:324, :624). Every batch of the consuming layer therefore received batch 0's attn_key_value. In addition, the first publish is the pre-quant (FP) forward; the post-quant replay could never replace it, so layer L+1 paired quantized hidden states with FP K/V.

Fix

  • ForwardExecutor._shared_kv_key(layer_index, batch_idx) is the single key constructor (forward_executor.py:122).
  • The predecessor slot is read inside the per-batch loop (forward_executor.py:409 serial, :787 parallel).
  • The slot is overwritten on every publish (forward_executor.py:516 serial, :848 parallel), so the replay's quantized-path K/V wins.
  • run_layer_stage evicts every (layer_index - 1, *) slot (stage_layer.py:1706), keeping the cache bounded by 2 * batch_count.

Before / after

Repro: drive ForwardExecutor.run_single with 4 batches; layer 0 publishes FP K/V (tag 0.0) and then replays (tag 100.0); layer 1 consumes with reuse_kv=True.

observed kv_last_layer values cache keys
parent 63e07a758 [0.0, 0.0, 0.0, 0.0] (every batch got batch 0's FP K/V) [0, 1]
this PR [100.0, 110.0, 120.0, 130.0] (each batch's own replay K/V) [(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), ...]

The four values are distinct, and the 100.0 offset proves the replay overwrote the FP capture.

flowchart TD
    A["Layer L pre-quant FP forward"] --> B["read shared_kv_cache_dict[(L-1, b)]<br/>forward_executor.py:409"]
    B --> C["kv_last_layer for batch b"]
    C --> D["module returns attn_key_value"]
    D --> E["write shared_kv_cache_dict[(L, b)]<br/>forward_executor.py:516"]
    E --> F["Layer L post-quant replay"]
    F --> G["read shared_kv_cache_dict[(L-1, b)] per batch"]
    G --> H["quantized hidden states feed L+1"]
    H --> I["overwrite shared_kv_cache_dict[(L, b)]<br/>with replay K/V"]
    I --> J["Layer L+1"]
    J --> K["evict every (L, *) slot<br/>stage_layer.py:1706"]
    style K fill:#efe,stroke:#383
Loading

Committed reference page: docs/looper-shared-kv-cache.md, linked from README.md and docs/README.md.

2. Smaller items (all fixed)

Item Fix Test
stage_layer.py:1542 ignored _drain_finalize_futures finalize_ok now gates commit_layer(); a failed finalizer only requests loop stop and skips the durable boundary (stage_layer.py:1492, :1592, :1634) test_run_layer_stage_skips_boundary_commit_when_finalize_fails
None output dropped with need_outputs=True _store_output is positional, _store_missing_output/_pad_output_slots keep early-stop slots, and empty batches are not forwarded test_serial_forward_keeps_slots_for_early_stopped_batches, test_serial_forward_pads_trailing_early_stop_slots, test_parallel_forward_keeps_each_batch_on_its_own_slot
stage_subset.py:1423 dynamic-dict write without lock Extracted _record_dynamic_exclusion, which takes _dynamic_lock_for(qcfg.dynamic) test_runtime_dynamic_exclusion_records_pattern_under_dynamic_lock, test_runtime_dynamic_exclusion_waits_for_the_dynamic_lock
run_parallel / weight_only_looper.py:638,685 leaked futures Resolve every submitted future, then raise the first error (mirrors _collect_worker_results) test_parallel_forward_drains_every_submitted_worker_before_raising, test_weight_only_quantize_subset_drains_workers_after_a_failure, test_weight_only_finalize_subset_drains_workers_after_a_failure
utils/p2p.py type(item)(generator) / skipped containers Namedtuples rebuild positionally; dataclass fields and cache key_cache/value_cache are walked and rebuilt tests/test_p2p_nested_walk.py
utils/logger.py:256 counted processors _summary_layer_count counts distinct "layer" records, falling back to len(result) for the legacy layer-keyed shape test_summary_counts_decoder_layers_when_result_is_keyed_by_processor

The stage_subset.py:1423 GIL=0 race is unproven: the test proves the writer serializes on the config's dynamic lock (it blocks while a reader holds it), not that the race reproduced. The lock is added for the invariant regardless.

3. Tests / validation

All commands run from the clone root with OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 OPENBLAS_NUM_THREADS=4 NUMEXPR_NUM_THREADS=4 PYTHONPATH=$PWD.

Command Result
pytest tests/module_tree/test_forward_executor_shared_kv.py -q 3 passed (parent: 3 failed)
pytest tests/module_tree/test_forward_executor_parallel.py -q 6 passed (parent: 4 failed)
pytest tests/test_p2p_nested_walk.py -q 3 passed (parent: 3 failed)
pytest tests/test_quantize_run_summary.py -q 24 passed; new test fails on parent
pytest tests/test_stage_modules.py -q 46 passed, 6 failed — the same 6 fail on origin/main (DummyLooper lacks layer_modules_for_prefix); all 3 new tests pass
pytest tests/test_weight_only_looper.py -q 18 passed, 1 failed — same failure on origin/main (test_weight_only_looper_respects_dense_and_moe_vram_strategy_devices, host device enumeration)
pytest tests/test_compute_device_filter.py tests/test_looper_helpers.py -q passed
PYTHON_GIL=0 pytest <new/related tests> -q 17 passed
ruff check gptqmodel docs/eora tests setup.py All checks passed
post-origin/main merge rerun 55 passed

Hardware: CPU only for the new regression tests. No GPU kernel was exercised, and no Hymba checkpoint run was performed; the test drives ForwardExecutor with a recording module that returns batch-specific K/V. tests/test_p2p_copy_utils.py was not run because it needs two free CUDA devices and the assigned pair is shared.

4. Residual risk

  • No end-to-end Hymba quantization run: the change is covered at the ForwardExecutor/cache boundary, where the bug lived.
  • Both the consumer's pre-quant forward and its replay now read the producer's replay K/V. That is the intended pairing: GPTQProcessor.forward.replay_after_process feeds the replay's hidden states into the next layer, so the FP K/V would be mismatched.
  • The empty-slot path skips batches with no cached activation; a processor that expected to forward an empty batch would now skip it (previously those batches were silently shifted instead).
  • The dynamic-lock race is fixed by invariant, not reproduced.

Cross-layer KV reuse (Hymba) cached a layer's attn_key_value by layer only,
so every batch of the consuming layer received batch 0's K/V, and the
pre-quant FP capture was never replaced by the post-quant replay.

Key shared_kv_cache_dict by (layer_index, batch_idx), read the previous
layer's slot per batch, and overwrite it on every publish so the replay's
quantized-path K/V wins. Evict every batch of the previous layer.

Also fix the smaller looper edge cases in #4182: honor the finalize drain
result before committing a durable layer boundary, keep early-stop batch
slots aligned, take the dynamic-config lock for runtime MoE exclusions,
drain submitted workers before propagating the first failure, walk tensors
inside dataclasses and cache objects (and rebuild namedtuples), and count
decoder layers instead of processors in the quantize summary.
Comment thread tests/test_weight_only_looper.py Dismissed
Comment thread tests/test_weight_only_looper.py Dismissed
Comment thread gptqmodel/looper/forward_executor.py Dismissed
Comment thread gptqmodel/looper/weight_only_looper.py Dismissed
Comment thread gptqmodel/looper/weight_only_looper.py Dismissed
@Qubitium
Qubitium merged commit 870fb44 into main Nov 16, 2026
9 checks passed
@Qubitium
Qubitium deleted the fix/issue-4182-shared-kv branch November 16, 2026 05:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] Looper: cross-layer KV reuse (Hymba) keeps only batch 0's KV; checkpoint/drain and batch-alignment edge cases

1 participant