Skip to content

perf(quantization): release replay activations and dedup AWQ captures (#4020) - #4043

Merged
Qubitium merged 3 commits into
mainfrom
fix/issue-4020
Nov 14, 2026
Merged

Qubitium merged 3 commits into
mainfrom
fix/issue-4020

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

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) calls p2p_move_nested for 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:#cf1322
Loading

A 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.

Mechanism Before After
Traversal nested _walk over tensors (gptqmodel/utils/p2p.py:2033-2043) module-level _p2p_walk_tensors(item, out) (gptqmodel/utils/p2p.py:2009), iterative
Rebuild nested _rebuild over replacements (gptqmodel/utils/p2p.py:2088-2097) module-level _p2p_rebuild(item, replacements) (gptqmodel/utils/p2p.py:2031)
Traversal order depth-first, declaration order unchanged (explicit stack, children pushed reversed)
Tensor lifetime until a cyclic GC pass reference counted, released with the result

The other three items, with the mechanism each replaces (line numbers from the #4020 audit):

Item Old mechanism New mechanism
AWQ FP reference _search_best_scale moved each chunk to host (awq_processor.py:1843), _compute_best_scale moved it back (:2378) for the 20-ratio grid chunks stay on the replay device (_build_chunked_reference_outputs, awq_processor.py:2370)
AWQ sibling captures one .detach().cpu() per module (awq_processor.py:618), one torch.cat per module (:1258), one in-place div_ per module (quantization/awq/quantize/scale.py:179-184) one host copy per (batch, id(source), source._version), one cat per input-id tuple, one division per group
Hessian dedup q/k/v and gate/up listed without :in= tags, so every projection captured its own Hessian tags added and verified by a real forward for glm, exaone4, hunyuan_v1_dense, apertus, gemma4_text

2. 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:#237804
Loading
flowchart 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:#389e0d
Loading

3. Per-subsystem detail

AWQ capture sharing invariants

  1. One host copy per unique source tensor. _materialize_host_feature (gptqmodel/looper/awq_processor.py:663) keys the cache on (batch_index, id(source), source._version) and revalidates with a weakref, 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.
  2. One torch.cat per identical capture list. _layer_input_features (awq_processor.py:1227) caches the concatenation by the tuple of input ids.
  3. One scale division per tensor per group. 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:#237804
Loading

The 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.py observes 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 reported UNDECLARED shared input: mlp.gate_proj ~ mlp.up_proj on the converted tree.

4. Failure and ambiguity contract

Situation Before After
A batch's activations are dropped retained until a cyclic GC pass released immediately
Same activation object captured by siblings copied, concatenated and divided once per module copied, concatenated and divided once per group
Two different scale groups reach one shared tensor n/a (no sharing) second group restarts from a pristine clone
Padded batch (_masked_hook_wrapper) per-module masked tensor unchanged; no sharing attempted
Inference tensor (no _version) copied per module unchanged; no sharing attempted
Unverified model type with :in= tags inert (singletons) inert (singletons)
dedup_shared_inputs=False dedup off dedup off

5. Change inventory

Area File Purpose
p2p gptqmodel/utils/p2p.py module-level walk/rebuild helpers, iterative traversal
AWQ gptqmodel/looper/awq_processor.py shared host capture, cached concat, device-resident reference chunks
AWQ math gptqmodel/quantization/awq/quantize/scale.py divide a shared feature once per group
Definitions glm.py, exaone4.py, hunyuan_v1_dense.py, apertus.py, gemma4.py, gemma3.py, mistral3.py :in= tags plus verified model types
Docs docs/quantization-memory.md, README.md flow reference, linked from README
Tests tests/test_p2p_copy_utils.py, tests/test_awq_scale_search_memory.py, tests/module_tree/test_shared_input_cpu_forward.py regressions

6. Tests / guarantees

Test Invariant it pins
test_p2p_move_nested_does_not_pin_inputs_until_gc with cyclic GC disabled, a dropped batch is 0/8 alive and device memory returns to baseline; fails assert 8 == 0 before the fix
test_p2p_nested_helpers_are_module_level the helpers are module-level, closure-free, and preserve depth-first order
test_p2p_move_nested_does_not_pin_peer_copies_until_gc same guarantee on the peer-copy branch (skips where raw peer copies are withheld)
test_siblings_share_one_host_copy / test_distinct_sources_are_not_shared / test_mutated_source_is_not_reused / test_capture_cache_is_per_batch sharing is exact, never across distinct or mutated sources
test_layer_input_features_concatenates_identical_lists_once one concatenation serves every sibling
test_apply_scale_divides_shared_feature_once one division, compared against an independent closed-form oracle capture / scales
test_apply_scale_restores_shared_feature_for_a_second_group a second group starts from the pristine capture
test_chunked_reference_outputs_stay_on_the_replay_device no host round-trip in the FP reference
test_plan_matches_real_forward_inputs[glm/exaone4/hunyuan_v1_dense/apertus/gemma4_text] the new tags match a real forward, with no undeclared sharing

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_disk default. 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" is origin/main at ff8443d6a in a separate worktree; "after" is this branch merged with that same commit. Packed SHA-256 covers every qweight/qzeros/scales/g_idx tensor in the saved checkpoint.

Run Peak device alloc Live at end of run Retries Packed SHA-256
8-layer GPTQ, before 2397.5 MB 1803.6 MB 0 157265fa...
8-layer GPTQ, after 952.8 MB (-60.3%) 267.6 MB 0 157265fa... identical
8-layer AWQ, before 5389.2 MB 1892.1 MB 8 b709e98b...
8-layer AWQ, after 3853.2 MB (-28.5%) 356.1 MB 7 b709e98b... identical
5-layer 70B-dim GPTQ, before 19221.0 MB 4148.3 MB 4 d7246844...
5-layer 70B-dim GPTQ, after 16149.0 MB (-16.0%) 1076.3 MB 4 d7246844... identical

Per-item isolation:

  • Item 1 is isolated by the GPTQ pair above (items 2 and 3 only touch AWQ).
  • Item 2 is isolated by re-running 8-layer AWQ with only the .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_scale win. What the change removes is one blocking D2H + H2D and one duplicate host copy per scaling group; the packed hash is unchanged.
  • Items 2+3 together are the AWQ before/after row above (-28.5% peak, identical hash).
  • Host RSS did not move reproducibly (one 8-layer AWQ pair measured 9152 -> 8436 MB, another 8675 -> 8756 MB), so it is not claimed.
  • Item 4 is measured as a count, not a wall time. On a 2-layer EXAONE 4 decoder at 70B dimensions (h8192/i28672, 64 heads, 8 KV heads), 128 x 512 tokens:
Setting Adopted followers Leader groups Packed SHA-256
dedup_shared_inputs=True 6/6 4 3803fa7b...
dedup_shared_inputs=False 0 0 3803fa7b... identical

Five 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

# CUDA venv
CUDA_VISIBLE_DEVICES=GPU-1892aea4-... PYTHONPATH=$PWD /opt/venvs/cu130t/bin/python -m pytest   tests/test_p2p.py tests/test_p2p_copy_utils.py tests/test_awq_scale_search_memory.py   tests/test_awq_scale_folding.py tests/module_tree/test_shared_input_cpu_forward.py -q
  -> 347 passed, 30 skipped

CUDA_VISIBLE_DEVICES=GPU-1892aea4-... PYTHONPATH=$PWD /opt/venvs/cu130t/bin/python -m pytest   tests/test_awq_scaling_groups.py tests/test_awq_moe_router_scaling.py   tests/test_awq_mla_scaling.py tests/test_awq_empty_groups.py -q
  -> 36 passed   (the AWQ tests main added while this branch was open)

# ROCm venv (HIP_VISIBLE_DEVICES=0 only)
HIP_VISIBLE_DEVICES=0 PYTHONPATH=$PWD /opt/venvs/rocm101t/bin/python -m pytest   tests/test_p2p.py tests/test_p2p_copy_utils.py tests/test_awq_scale_search_memory.py   tests/test_awq_scale_folding.py tests/test_awq_scaling_groups.py -q
  -> 130 passed, 31 skipped

HIP_VISIBLE_DEVICES=0 PYTHONPATH=$PWD /opt/venvs/rocm101t/bin/python -m pytest   tests/module_tree/test_shared_input_cpu_forward.py -q
  -> 242 passed

# lint
ruff check gptqmodel docs/eora tests setup.py
  -> All checks passed!

Pre-fix failure evidence (same tests against origin/main):

tests/test_p2p_copy_utils.py::test_p2p_move_nested_does_not_pin_inputs_until_gc
  assert 8 == 0
tests/test_p2p_copy_utils.py::test_p2p_nested_helpers_are_module_level  (AttributeError)
tests/test_awq_scale_search_memory.py: 5 failed, 3 passed

8. Reviewer notes

  • ROCm. The nested peer path is disabled by default there (_rocm_nested_peer_disabled() is True), so p2p_move_nested returns P2P_NOT_APPLICABLE before traversing and the leak does not exist on ROCm; move_nested_to_device falls back to nested_move_to. The liveness regression therefore skips on ROCm, and the module-level helper test still runs there.
  • The peer-copy branch could not be exercised on this host. _raw_peer_copy_unsafe() is True with the expandable-segments allocator, so p2p_move_nested withholds raw copies and returns P2P_NOT_APPLICABLE. The measured repro is the traversal path, which runs before that decision; _rebuild was 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_gc skips here for the same reason.
  • One deliberate behaviour change. In the latest_batch aggregation branch, features[name] = tensors[-1] keeps the captured host object itself. On a CPU-only run the old code stored a distinct detach() view per sibling, so apply_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 through torch.cat, which copies, so the packed hashes are unaffected.
  • Limitation (as in the issue). Capture sharing only triggers without a keep-mask: _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.
  • VL tags are inert on purpose. mistral3, gemma3 VL and the gemma4 composite tree carry :in= tags but their model types are not in shared_input_verified_model_types, because AutoModelForCausalLM.from_config cannot build them and no tiny multimodal forward exists to verify the tags. Dedup stays off (the fail-safe default) until such a fixture lands.
  • Not in scope. The rejected in-place Hessian accumulation and the unmeasured down_proj Hessian parking from the issue are untouched; both change numerics or need a separate bitwise argument.

gptqmodel-agent 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
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