Repository navigation
fix(looper): key shared KV cache per batch and refresh on replay (#4182) - #4242
Merged
Merged
Conversation
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.
# Conflicts: # README.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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_kvlayer (Hymba) consumed batch 0's K/V and the pre-quant FP capture was never replaced by the post-quant replay.shared_kv_cache_dictis 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:447on the parent commit) andrun_parallel(:749) wroteshared_kv_cache_dict[layer_index]only whenis None, and both readprev_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'sattn_key_value. In addition, the first publish is the pre-quant (FP) forward; the post-quant replay could never replace it, so layerL+1paired 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).forward_executor.py:409serial,:787parallel).forward_executor.py:516serial,:848parallel), so the replay's quantized-path K/V wins.run_layer_stageevicts every(layer_index - 1, *)slot (stage_layer.py:1706), keeping the cache bounded by2 * batch_count.Before / after
Repro: drive
ForwardExecutor.run_singlewith 4 batches; layer 0 publishes FP K/V (tag0.0) and then replays (tag100.0); layer 1 consumes withreuse_kv=True.kv_last_layervalues63e07a758[0.0, 0.0, 0.0, 0.0](every batch got batch 0's FP K/V)[0, 1][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.0offset 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:#383Committed reference page:
docs/looper-shared-kv-cache.md, linked fromREADME.mdanddocs/README.md.2. Smaller items (all fixed)
stage_layer.py:1542ignored_drain_finalize_futuresfinalize_oknow gatescommit_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_failsNoneoutput dropped withneed_outputs=True_store_outputis positional,_store_missing_output/_pad_output_slotskeep early-stop slots, and empty batches are not forwardedtest_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_slotstage_subset.py:1423dynamic-dict write without lock_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_lockrun_parallel/weight_only_looper.py:638,685leaked futures_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_failureutils/p2p.pytype(item)(generator)/ skipped containerskey_cache/value_cacheare walked and rebuilttests/test_p2p_nested_walk.pyutils/logger.py:256counted processors_summary_layer_countcounts distinct"layer"records, falling back tolen(result)for the legacy layer-keyed shapetest_summary_counts_decoder_layers_when_result_is_keyed_by_processorThe
stage_subset.py:1423GIL=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.pytest tests/module_tree/test_forward_executor_shared_kv.py -qpytest tests/module_tree/test_forward_executor_parallel.py -qpytest tests/test_p2p_nested_walk.py -qpytest tests/test_quantize_run_summary.py -qpytest tests/test_stage_modules.py -qorigin/main(DummyLooperlackslayer_modules_for_prefix); all 3 new tests passpytest tests/test_weight_only_looper.py -qorigin/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 -qPYTHON_GIL=0 pytest <new/related tests> -qruff check gptqmodel docs/eora tests setup.pyorigin/mainmerge rerunHardware: CPU only for the new regression tests. No GPU kernel was exercised, and no Hymba checkpoint run was performed; the test drives
ForwardExecutorwith a recording module that returns batch-specific K/V.tests/test_p2p_copy_utils.pywas not run because it needs two free CUDA devices and the assigned pair is shared.4. Residual risk
ForwardExecutor/cache boundary, where the bug lived.GPTQProcessor.forward.replay_after_processfeeds the replay's hidden states into the next layer, so the FP K/V would be mismatched.