Repository navigation
perf(quantization): release replay activations and dedup AWQ captures (#4020) - #4043
Merged
Merged
Conversation
added 3 commits
November 14, 2026 17:07
…tures (#4020) Four memory/lifetime fixes in the quantization pipeline. Every change leaves the packed qweight/scales/qzeros/g_idx tensors bitwise identical (SHA-256 of every packed tensor compared before and after on 8-layer GPTQ, 8-layer AWQ and 5-layer 70B-dim GPTQ runs). 1. `p2p_move_nested` walked and rebuilt its input with nested, self-recursive closures. A function that references itself is only reachable through its own closure cell, so the cell, the function and `tensors` (every leaf passed in) formed an island that only the cyclic GC could free. `move_nested_to_device` calls it for every batch of every forward, so each batch's replayed hidden state stayed resident: 8-layer GPTQ peaked at 2141.5 MB and still held 1547.6 MB at the end; 5-layer 70B-dim GPTQ peaked at 19221 MB and held 4148 MB. Both helpers are now module-level (`_p2p_walk_tensors`, `_p2p_rebuild`), the traversal is iterative, and the order is unchanged. Peak: 967.5 MB (8-layer) and 16149 MB (70B-dim). 2. AWQ moved every FP reference chunk to host and `_compute_best_scale` moved every chunk straight back for the whole 20-ratio grid, so the D2H/H2D and the extra host copy bought nothing. The chunks now stay on the replay device. 3. AWQ captured q/k/v and gate/up separately even though both siblings read the same activation object: 7 captures per layer where 4 are unique, plus one `torch.cat` and one in-place scale division per module. Captures now share one host copy per `(batch, id(source), source._version)` (weakref-validated, never for masked or inference tensors), `torch.cat` is cached per input-id tuple, and `apply_scale` divides a shared tensor once per group. 8-layer AWQ peak 5389.2 -> 3853.2 MB and host RSS 9152 -> 8436 MB. 4. `HessianInputDedup` only groups leaves that declare the same `:in=<tag>`, and only for model types with a verified real forward. Adds the tags to the trees the issue listed plus real-forward cases for the dense architectures: `glm`, `exaone4`, `hunyuan_v1_dense`, `apertus`, `gemma4_text`. The VL wrappers (`mistral3`, `gemma3` VL, `gemma4` composite) are tagged but stay inert until a tiny multimodal forward exists to verify them. Adds `docs/quantization-memory.md` (linked from README) with the before/after flows, and regression tests for the closure cycle, the capture sharing, the single division, the device-resident reference, and the shared-input plans.
# Conflicts: # gptqmodel/models/definitions/apertus.py # gptqmodel/models/definitions/exaone4.py # gptqmodel/quantization/awq/quantize/scale.py
This was referenced Nov 14, 2026
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 #4020
TL;DR
Four lifetime fixes in the quantization pipeline, ~180 net lines of source (plus tests and one docs page). The architectural consequence: a replayed batch's activations now die with the batch instead of waiting for Python's cyclic GC, and AWQ pays one capture / one concat / one scale per unique activation instead of one per projection. Every packed tensor stays bitwise identical.
1. The problem
move_nested_to_device(gptqmodel/utils/looper_helpers.py:172) callsp2p_move_nestedfor every batch of every forward. Its traversal and rebuild were nested, self-recursive closures:flowchart TD subgraph OLD["BEFORE - closure cycle pins every batch"] direction TB CALL["move_nested_to_device<br/>once per batch per forward"] --> FN["p2p_move_nested"] FN --> WALK["nested _walk closure"] WALK -->|"self-recursive reference"| CELL["closure cell"] CELL -->|"holds"| WALK CELL -->|"holds"| TENS["tensors: every leaf passed in"] TENS --> ACT["layer replay outputs<br/>stay allocated on the source device"] REB["nested _rebuild closure"] --> CELL2["second closure cell"] CELL2 --> REB CELL2 --> REPL["replacements: every moved tensor"] ACT --> GC["only a generational gc.collect frees them"] REPL --> GC end style OLD fill:#fff1f0,stroke:#d4380d style ACT fill:#ffccc7,stroke:#cf1322 style REPL fill:#ffccc7,stroke:#cf1322 style GC fill:#ffccc7,stroke:#cf1322A function that refers to itself is reachable only through its own closure cell, so the cell, the function and everything else in that closure (
tensors) form an island that only a cyclic collection can free. CPython runs that collector on allocation counts, not on quantization progress, so the island survived the run._walkovertensors(gptqmodel/utils/p2p.py:2033-2043)_p2p_walk_tensors(item, out)(gptqmodel/utils/p2p.py:2009), iterative_rebuildoverreplacements(gptqmodel/utils/p2p.py:2088-2097)_p2p_rebuild(item, replacements)(gptqmodel/utils/p2p.py:2031)The other three items, with the mechanism each replaces (line numbers from the #4020 audit):
_search_best_scalemoved each chunk to host (awq_processor.py:1843),_compute_best_scalemoved it back (:2378) for the 20-ratio grid_build_chunked_reference_outputs,awq_processor.py:2370).detach().cpu()per module (awq_processor.py:618), onetorch.catper module (:1258), one in-placediv_per module (quantization/awq/quantize/scale.py:179-184)(batch, id(source), source._version), one cat per input-id tuple, one division per group:in=tags, so every projection captured its own Hessianglm,exaone4,hunyuan_v1_dense,apertus,gemma4_text2. The new flow
flowchart LR subgraph NEW["AFTER - no closure, no cycle"] direction TB C2["move_nested_to_device"] --> P2["p2p_move_nested"] P2 --> W2["_p2p_walk_tensors<br/>module level, no closure"] P2 --> R2["_p2p_rebuild<br/>module level, no closure"] W2 --> L2["tensors list<br/>local to the call"] R2 --> M2["replacements dict<br/>local to the call"] L2 --> F2["freed when the call returns"] M2 --> F2 end style NEW fill:#f6ffed,stroke:#389e0d style F2 fill:#d9f7be,stroke:#237804flowchart TD subgraph NEW3["AFTER - one host copy per source tensor"] direction TB A2["hidden state x"] --> S["_materialize_host_feature<br/>one D2H per source id + version"] S --> Q2["q_proj entry"] S --> K2["k_proj entry"] S --> V2["v_proj entry"] Q2 --> C4["one torch.cat per identical capture list"] K2 --> C4 V2 --> C4 C4 --> D4["one div per group"] end style NEW3 fill:#f6ffed,stroke:#389e0d3. Per-subsystem detail
AWQ capture sharing invariants
_materialize_host_feature(gptqmodel/looper/awq_processor.py:663) keys the cache on(batch_index, id(source), source._version)and revalidates with aweakref, so a recycled id cannot hand a sibling the wrong activations. The cache is dropped when the calibration batch changes and when the layer finalizes. Masked captures (a fresh masked tensor per sibling) and inference tensors (no version counter) are never shared.torch.catper identical capture list._layer_input_features(awq_processor.py:1227) caches the concatenation by the tuple of input ids.apply_scale(scale.py:139) tracks the group that already divided each object; a tensor reached by a different group is restored from a pristine clone taken before the first division.Hessian dedup gating
flowchart TD TREE["module tree leaf<br/>q_proj:0:in=x"] --> TAG{"same parent and same in tag?"} TAG -->|"no"| SINGLE["singleton group<br/>own Hessian capture"] TAG -->|"yes"| VER{"model_type in<br/>shared_input_verified_model_types?"} VER -->|"no"| SINGLE VER -->|"yes"| GROUP["shared group<br/>leader captures, followers adopt"] GROUP --> ADOPT["adopt_hessian_from(leader)<br/>plus SharedHessianFactorCache"] style SINGLE fill:#fffbe6,stroke:#d48806 style ADOPT fill:#d9f7be,stroke:#237804The gate is deliberate: a wrong tag silently reuses another module's Hessian, so a tag only activates after
tests/module_tree/test_shared_input_cpu_forward.pyobserves a real forward and confirms both siblings received the same tensor. That probe immediately paid off: my first pass assumed GLM's MLP was fused and left it untagged, and the probe reportedUNDECLARED shared input: mlp.gate_proj ~ mlp.up_projon the converted tree.4. Failure and ambiguity contract
_masked_hook_wrapper)_version):in=tagsdedup_shared_inputs=False5. Change inventory
gptqmodel/utils/p2p.pygptqmodel/looper/awq_processor.pygptqmodel/quantization/awq/quantize/scale.pyglm.py,exaone4.py,hunyuan_v1_dense.py,apertus.py,gemma4.py,gemma3.py,mistral3.py:in=tags plus verified model typesdocs/quantization-memory.md,README.mdtests/test_p2p_copy_utils.py,tests/test_awq_scale_search_memory.py,tests/module_tree/test_shared_input_cpu_forward.py6. Tests / guarantees
test_p2p_move_nested_does_not_pin_inputs_until_gcassert 8 == 0before the fixtest_p2p_nested_helpers_are_module_leveltest_p2p_move_nested_does_not_pin_peer_copies_until_gctest_siblings_share_one_host_copy/test_distinct_sources_are_not_shared/test_mutated_source_is_not_reused/test_capture_cache_is_per_batchtest_layer_input_features_concatenates_identical_lists_oncetest_apply_scale_divides_shared_feature_oncecapture / scalestest_apply_scale_restores_shared_feature_for_a_second_grouptest_chunked_reference_outputs_stay_on_the_replay_devicetest_plan_matches_real_forward_inputs[glm/exaone4/hunyuan_v1_dense/apertus/gemma4_text]7. Validation
RTX 4090 (48 GiB), CUDA 13.0 / torch 2.16.0, transformers 5.22.2, 4-bit gs128, 128 x 512 calibration tokens,
offload_to_diskdefault. The 4090 was shared with other workers, and the same configuration varied by 30-50% in wall time between runs, so device memory and packed hashes are the reported metrics and no wall-time claim is made. "Before" isorigin/mainatff8443d6ain a separate worktree; "after" is this branch merged with that same commit. Packed SHA-256 covers everyqweight/qzeros/scales/g_idxtensor in the saved checkpoint.157265fa...157265fa...identicalb709e98b...b709e98b...identicald7246844...d7246844...identicalPer-item isolation:
.detach().cpu()restored on top of this branch: peak device memory is 3853.2 MB on both sides, which confirms the issue's prediction that the host round-trip never lowered peak memory. Wall 71.1 s vs 56.97 s (single runs) and 63.5 s vs 62.2 s (earlier pair) move in the expected direction but are inside this host's noise floor, so I am not claiming the issue's 12.5 -> 8.7 s_search_best_scalewin. What the change removes is one blocking D2H + H2D and one duplicate host copy per scaling group; the packed hash is unchanged.dedup_shared_inputs=True3803fa7b...dedup_shared_inputs=False3803fa7b...identicalFive captures per layer (q/k/v plus gate/up) collapse to two. The wall time of that A/B moved in both directions across repeated runs (25.9/34.5 s vs 32.1/38.1 s in one pair, 45.2 s vs 36.6 s in another), so I am not claiming the issue's ~0.9 s/layer figure on this host.
Commands
Pre-fix failure evidence (same tests against
origin/main):8. Reviewer notes
_rocm_nested_peer_disabled()isTrue), sop2p_move_nestedreturnsP2P_NOT_APPLICABLEbefore traversing and the leak does not exist on ROCm;move_nested_to_devicefalls back tonested_move_to. The liveness regression therefore skips on ROCm, and the module-level helper test still runs there._raw_peer_copy_unsafe()isTruewith the expandable-segments allocator, sop2p_move_nestedwithholds raw copies and returnsP2P_NOT_APPLICABLE. The measured repro is the traversal path, which runs before that decision;_rebuildwas moved for the same structural reason and is covered by the module-level helper test.test_p2p_move_nested_does_not_pin_peer_copies_until_gcskips here for the same reason.latest_batchaggregation branch,features[name] = tensors[-1]keeps the captured host object itself. On a CPU-only run the old code stored a distinctdetach()view per sibling, soapply_scale's in-place division hit the same storage once per module (double/triple division). Sharing makes it one division per group, which is the intended AWQ math. Fixed-length calibration (the measured runs) goes throughtorch.cat, which copies, so the packed hashes are unaffected._masked_hook_wrapper(module_looper.py:1613) builds a new masked tensor per sibling. Results stay correct; there is just no gain for padded batches.mistral3,gemma3VL and thegemma4composite tree carry:in=tags but their model types are not inshared_input_verified_model_types, becauseAutoModelForCausalLM.from_configcannot build them and no tiny multimodal forward exists to verify the tags. Dedup stays off (the fail-safe default) until such a fixture lands.down_projHessian parking from the issue are untouched; both change numerics or need a separate bitwise argument.