Skip to content

fix(looper): release replayed calibration batches at their last use - #5928

Merged
Qubitium merged 1 commit into
mainfrom
fix/replay-release-consumed-inputs-5735
Nov 20, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/replay-release-consumed-inputs-5735

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

The post-quant replay in _replay_layer_outputs is the last reader of the
cached calibration activations: right after it returns, the layer stage calls
processor.clear_cache_data() and processor.receive_layer_inputs(outputs).
The executor still kept every consumed input batch alive until the whole
replay finished, so every layer boundary held two full activation sets
(n_samples x seq_len x hidden x dtype_bytes) instead of one set plus one
batch.

This change releases each cached batch as soon as its output is stored.
Inputs are only dropped when the replay feeds receive_layer_inputs;
replays into a separate pristine/clean cache opt out because their inputs can
alias the live layer cache. Disk-backed input sequences are immutable and are
left untouched.

Fixes #5735

What Changed

  • ForwardExecutor.run_single / run_parallel / run take
    consume_inputs: bool = False. When set, each batch's slot in the
    list-backed input cache is emptied after its output is stored (after the
    per-batch progress accounting, so row counts are unchanged).
  • ModuleLooper._run_forward_batches threads the flag through.
  • _replay_layer_outputs takes consume_inputs: Optional[bool] = None and
    defaults it to the processor's forward.replay_after_process policy: that
    replay feeds receive_layer_inputs, so it owns the last use. The
    pristine-group replay at _capture_pristine_group_context passes False
    explicitly because clean_layer_inputs may alias the main cache.
  • ForwardExecutor._release_consumed_input only mutates list-backed
    caches; DiskBackedLayerOutputSequence is a read-only Sequence and keeps
    no resident activations.

No numeric, checkpoint, or API change: only tensor lifetime changes.

Tests

New file tests/test_replay_input_release_5735.py (7 nodes) covers, with the
real ForwardExecutor and real tensors:

  • serial replay releases batches one at a time and the input tensors are
    garbage-collected (weakref);
  • without consume_inputs the whole set stays alive (unchanged behavior);
  • parallel replay releases each resolved batch;
  • an immutable disk-backed input sequence is left untouched;
  • _replay_layer_outputs consumes by default for a replay_after_process
    processor, and keeps inputs when the caller replays into a separate cache
    or when a later processor still reads them.

Red on base 9d9dbffaf (same test file, unmodified source):

PYTHONPATH=<base-tree> /root/venv/bin/python -m pytest \
  tests/test_replay_input_release_5735.py -q -p no:randomly
# 6 failed, 1 passed

The behavioral node fails with the retained slots still full
([1, 1, 1, 1] at every batch) instead of draining to [0, 0, 0, 1].

Green on this branch:

PYTHONPATH=<pr-tree> /root/venv/bin/python -m pytest \
  tests/test_replay_input_release_5735.py \
  tests/test_stage_modules.py \
  tests/test_quantization_lifecycle_contracts.py \
  tests/test_forward_executor_device_filter_5848.py \
  tests/module_tree/test_forward_executor_parallel.py \
  tests/module_tree/test_forward_executor_shared_kv.py \
  tests/test_dp_subset_early_stop_4904.py \
  tests/test_moe_forward_lifecycle_5520.py -q -p no:randomly
# 94 passed, 2 skipped

format/check.sh (ruff 0.14.2) passes.

Measured Impact

Real GPTQ run on CPU with HuggingFaceTB/SmolLM2-135M
(QuantizeConfig(bits=4, group_size=128, device="cpu"),
CalibrationConfig(dataset=8 tokenized paragraphs, batch_size=1),
BACKEND.TORCH, 29 decoder layers, 8 batches). ForwardExecutor.run_single
was instrumented to sum tensor.nbytes over the live slots of
processor.inputs_cache.layer_inputs at every forward_batch_completed of the
apply_moe_config=False post-quant replay.

Metric Units Before After Change
Bytes retained at the last replay batch, max over 29 layers B 524,160 62,208 −461,952 (−88.1%)
Bytes retained at the last replay batch, sum over 29 layers B 15,200,640 1,804,032 −13,396,608 (−88.1%)
Quantized state_dict SHA-256 hex ee2f3bb26c51… ee2f3bb26c51… unchanged (bit-identical)
Quantize wall time s 79.4 78.4 −1.0 (within run-to-run noise)

For an N-batch calibration run the retained term at the last batch drops from
one full activation set to the last batch. The 8.43x ratio here is
524,160 / 62,208 (the final batch is smaller than the earlier ones).

Commands and conditions: each tree (base-5735 at 9d9dbffaf, work-5735
at this branch) ran the same /root/bench_5735.py with
PYTHONPATH=<tree> /root/venv/bin/python /root/bench_5735.py. The script is
not committed. CPU-only host; the same lifetime semantics apply to CUDA
tensors, but no GPU memory counter was measured here.

Review Requirements

  • Reproduced the retention on the base tree and proved the fix with the
    same instrumented real-model run.
  • Quantized weights are bit-identical to the base tree.
  • Verified the pristine-cache replay still keeps its inputs.
  • Native CUDA activation peak remains unmeasured on this host (no CUDA
    toolkit / GPU quantization run available).

…5735)

The post-quant replay that feeds receive_layer_inputs is the last reader of
the cached activations, but the executor kept every consumed batch alive
until the whole replay ended. Each layer boundary therefore held two full
activation sets. Release each batch as its output is stored.
@Qubitium
Qubitium marked this pull request as ready for review November 20, 2026 15:16
@Qubitium
Qubitium merged commit 74a480e into main Nov 20, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/replay-release-consumed-inputs-5735 branch November 20, 2026 15:17
Qubitium added a commit that referenced this pull request Nov 22, 2026
…rip, PARO/offload, LFM3 tests) (#5980)

* fix(awq): restore scale search for PanGu, Bailing-MoE, Nemotron-H, Inkling2

#5978 deferred AWQ scaling for four families by returning empty fold groups.
Restore every group that measures output-neutral on the real forward and keep
only the folds that are provably non-neutral:

- gpt_pangu: generic planner, minus the top block's `attn.q_proj` in the
  `ln_1` group (it consumes `custom_query`, not the norm). `ln_1 -> k/v`,
  `attn.v_proj -> attn.c_proj`, `ln_2 -> mlp.c_fc` are neutral; the
  `c_fc -> c_proj` source stays `nosrc`.
- bailing_moe: drop the `isinstance(BailingConfig): return []` override and
  use the generic planner. All groups are neutral on dense/mla/hybrid/
  legacy_gqa (worst 1.9e-07).
- nemotron_h: generic planner for dense Mamba/attention/MLP mixers. Only the
  native `NemotronHMoE` mixer stays plain (one norm feeds shared and routed
  experts; shared-only fold 2.4e-2). Also move `A_log`/`D`/`dt_bias` out of
  the `mixer` tuple: as Parameters they closed the q/k/v subset and folded
  `o_proj` from the block norm (8.1e-2).
- inkling2_loop: keep the per-expert `up_proj -> down_proj` folds
  (1.9e-07..3.5e-06). Drop the tree-order `post_attention_layernorm` and
  `o_proj.linear -> gate_proj` groups, which follow module order rather than
  data flow and change the layer output by 8e-2..4e-1.

Tests pin neutrality on production configs and pin the dropped folds as
non-neutral, so a future planner change cannot silently reintroduce them.

* fix(quantize): honor the quantization device dtype and leave the model in eval

Three independent round-trip bugs that made an in-session model disagree with
the checkpoint it just saved:

- loader: auto dtype only followed `quantize_config.device` for MiMo sources.
  On an MPS/CUDA host a CPU quantization therefore loaded and re-saved the
  dense source in the host dtype (fp16) while a CPU reload resolved bf16,
  so the round trip was not dtype-preserving. Honor the quantization device
  for every `BaseQuantizeConfig`.
- torch qlinear: wide `_decode_248_weight` cast fp16 scales to bf16 before
  the multiply while the fused/compiled path multiplies in fp32 and rounds
  once. Compute wide decodes in fp32 (fp64 when requested) and cast the
  product once, so eager and compiled decode are bitwise equal (#5740).
- base: the quantize loop installs fresh kernel modules that start in
  training mode; their `train` transition also restores the checkpoint
  zero-point layout. Call `model.eval()` at the end of `quantize()` so an
  in-session forward decodes through the same path as the saved checkpoint.

* fix: stop a PARO placeholder rotation and a cached import traceback from failing runs

- paro_processor: `pack_module()` treated the minimal placeholder triple
  `pairs=(1,)`, `theta=(1,)`, `channel_scales=(1,)` used by packing-only
  callers as real rotation state and raised the #5659 `(8,128)` vs `(1,)`
  shape error. Keep the freshly built layer's identity rotation for that
  exact placeholder; a real krot mismatch still raises.
- humming: the optional-import `ModuleNotFoundError` was cached with its
  traceback. Kernel discovery imports every qlinear module from inside
  `quantize()`, so the retained stack pinned the model and its run-exit
  state; `del model` could never run the offload finalizer and left
  `offload/run-*` behind (#4595). Clear `__traceback__`/`__context__`/
  `__cause__`; type and message are unchanged.

* test: record Humming as fusion-excluded and fix the PARO looper stub

- test_fusion_kernel_backends: `HummingLinear`/`AwqHummingLinear` were added
  by #5966 without a fusion spec or an `EXCLUDED` entry, so the registry
  contract failed. Humming's `post_init()` replaces checkpoint tensors with
  shape-padded JIT operands and a per-layer `LayerConfig`; there is no
  concatenable native layout, so list both as excluded with that rationale.
- test_paro: `_replay_layer_outputs()` now always passes `consume_inputs=`
  (since #5928) but the first `_DummyLooper` stub kept the old signature.
  Accept and discard the keyword; test semantics are unchanged.

* test(lfm3): match the shipped AWQ fold contract

#5978 suppresses the `operator_norm -> q/k/v` fold on LFM3 attention layers
because the sigmoid gate consumer is left on the divided norm (uncompensated
delta 5.5e-2; compensating it rewrites non-quantized gate weights). The conv
layer still folds both input norms. Update the LFM3 tests to that contract
instead of the pre-#5978 expectation, and pin the suppression plus its
measured error so the decision is explicit.

* test(fusion): skip the TorchInt8Linear cache-race pair on darwin

`TorchInt8Linear` has no darwin implementation, so the two race tests failed
with a backend-availability error rather than exercising the cache. Gate the
module on the platform the kernel supports.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant