Skip to content

[PERF] Quantization pipeline: GPU memory leak (p2p_move_nested closure cycle pins every layer's replay outputs, ~1 GiB/layer at 70B), AWQ host round-trip and duplicate sibling captures, missing :in= Hessian dedup tags #4020

Closed

Description

@Qubitium

Audit of main @ 5f5eaad on RTX 4090.

Test models: random Llama, h2048 / i5504, 8 layers, bf16; and a Llama with true 70B layer dims (h8192 / i28672, 64 heads / 8 KV heads), 2 and 5 layers.

Calibration: 128 × 512 tokens, GPTQ 4-bit gs128 and AWQ 4-bit gs128 GEMM, default offload_to_disk=True.

Every change below leaves the packed qweight/scales/qzeros/g_idx bitwise identical (SHA of every tensor compared). The host was loaded (load average 12–15 on 16 cores), so CPU-bound wall times vary ±30%. Per-phase timers and memory numbers are stable.

1. GPU memory leak: every layer's replay outputs stay on GPU until Python's cyclic GC happens to run (high)

gptqmodel/utils/p2p.py:2033-2043 (p2p_move_nested._walk) and :2088-2097 (_rebuild) are nested, self-recursive closures. Each one sits in a reference cycle with its own closure cell, and that cell also holds tensors, the list of every tensor passed in. move_nested_to_device (utils/looper_helpers.py:175) calls this for every batch of every forward pass, so each batch's cached hidden state is pinned until a generational GC collects the cycle. In practice that doesn't happen within a run.

Minimal repro on the real function, two GPUs, gc disabled to make it deterministic:

x = torch.randn(1024, 1024, device="cuda:0"); r = weakref.ref(x)
out = p2p_move_nested({"h": x}, torch.device("cuda:1")); del out, x
# x8:  alive before gc: 8/8, cuda:0 still holds 32 MiB  ->  after gc.collect(): 0/8, 0 MiB

In real runs:

  • At the end of an 8-layer GPTQ run, CUDA memory history shows 1792 MB still live: 896 tensors (7 layers × 128) allocated from _replay_layer_outputs. Their referrer chain ends in a closure cell of p2p_move_nested.<locals>._walk.
  • MemDiag "active" climbs +0.25 GiB per layer (8-layer), in both GPTQ and AWQ.
  • At 70B dims it is +1 GiB per layer, with allocator retries rising 0 → 3.

Fix: move both helpers to module level, e.g. _p2p_walk_tensors(item, out) / _p2p_rebuild(item, replacements), or convert them to iterative loops.

run peak GPU alloc before → after packed-tensor hash
8-layer GPTQ 2405 → 1009–1050 MB (−57%) identical
8-layer GPTQ, 2048-token seqs 2440 → 1112 MB identical
8-layer AWQ 5405 → 3869 MB identical
5-layer, 70B-dim GPTQ 19221 → 16149 MB; active levels off at 2.05 GiB instead of +1 GiB/layer identical

At 70B scale that is up to ~1 GiB × 80 layers retained, which means OOM or heavy allocator thrashing unless GC happens to fire. A test asserting that torch.cuda.memory_allocated stays flat across layers would catch regressions.

2. AWQ copies the FP reference output to host and straight back to GPU on every scale search

gptqmodel/looper/awq_processor.py:1843 moves each reference chunk to host (.detach().cpu(), "so scale search does not keep the full activation tensor resident on GPU"). _compute_best_scale (:2378, reference_chunks = [chunk.to(device) ...]) then moves every chunk back to GPU and keeps them there for the whole 20-ratio grid. The stated goal is never achieved, and each scaling group per layer pays a blocking D2H + H2D of the full activation, plus an extra host copy.

Fix: drop the .cpu(). Peak GPU memory is unchanged, because the full reference is on GPU during the grid anyway. 8-layer: _search_best_scale time outside the grid 12.5 → 8.7 s, with the hash identical.

3. AWQ q/k/v and gate/up each capture and process the same input separately

awq_processor.py:584-641 (_record_input_feature, .detach().cpu() at :618) copies the input once per module, :1258 concatenates once per module, and quantization/awq/quantize/scale.py:179-184 divides in place once per module. That is 7 captures per layer where 4 are unique. At 70B, k/v/up are ~3 GB per layer of redundant D2H, host RAM, cat and divide.

Prototype:

  • When a sibling's hook sees the same source tensor (weakref + _version, skipped for inference tensors) in the same batch, reuse the host copy.
  • Cache torch.cat by the tuple of input ids.
  • In apply_scale, divide each shared tensor once per scale, cloning first if a different scale reaches an already-divided tensor.

8-layer timings: _record_input_feature 9.5 → 6.5 s, _layer_input_features 4.6 → 3.3 s, apply_scale 0.87 → 0.65 s.

Items 1–3 combined:

  • 8-layer AWQ: wall time 73–84 s → 67–75 s (~−9%), peak GPU 5.4 → 3.87 GB, RSS 6.78 → 5.76 GB, hash identical (also with 2048-token sequences: 57.0 → 50.4 s).
  • 70B dims: RSS −15% (19.2 → 16.3 GB) and hash identical. Wall time is unchanged within noise there, because clip search and the scale grid (~25 s per layer each) dominate.

Limitation: the reuse only triggers without a keep-mask (batch size 1 or unpadded). With padded batches, _masked_hook_wrapper (module_looper.py:1613) builds a new masked tensor per sibling. The result is still correct, but there's no gain.

4. GPTQ Hessian input dedup (#3052) is off for several model definitions because they lack :in= tags

HessianInputDedup only engages on explicit :in=<tag> entries. These trees list q/k/v and gate/up without tags:

  • definitions/glm.py:23,25
  • mistral3.py:24,26
  • gemma4.py:31-40, 247-256
  • exaone4.py:25,34
  • hunyuan_v1_dense.py:25,32
  • apertus.py:28
  • the VL path of gemma3.py:139,148

Measured cost of no dedup (70B-dim Llama with hessian.dedup_shared_inputs=False): add_batch 7.94 → 9.78 s for 2 layers, i.e. ~0.9 s per layer or ~8% of per-layer time, with the hash identical either way. Fix: add :in= tags, after confirming per architecture that the siblings really receive the same tensor (not measured on those architectures themselves).

Rejected and unmeasured

  • Rejected: in-place Hessian accumulation (H.addmm_(X.T, X) instead of matmul + add_, gptq.py:751-766, 1065). It is ~30% faster per batch and saves one C² buffer, but cuBLAS picks a different reduction for some shapes, and 7.6% of qweight nibbles flip end to end (the baseline is deterministic). It is not bitwise, so it isn't proposed.
  • Unmeasured: on 70B down_proj, H + L + two cholesky_inverse temporaries are 4 × C² = 12.5 GB of the 16.1 GB peak (gptq.py:1819). H is kept on GPU only for a rare retry. Parking it in pinned host memory during the inverse, keeping the diagonal, would save ~3.1 GB (−19% peak) for ~0.15–0.3 s per down_proj.
  • Unmeasured: STOP_FORWARD_EXCEPTION is one shared exception instance, so after a raise its __traceback__ keeps the last forward's frames and activations alive. This is bounded to one batch.

🤖 Generated with Claude Code

Activity

  1. added
    bug
    on Nov 14, 2026
  2. Qubitium commented on Nov 14, 2026

    @Qubitium
    CollaboratorAuthor

    #4041 item 3 lists more siblings that share an input without an :in= tag (perf only), beyond the list here. A check across 100 definitions found no wrong :in= tags.

  3. Qubitium commented on Nov 14, 2026

    @Qubitium
    CollaboratorAuthor

    Follow-up on #4043: the AWQ sibling-capture dedup never fires. Captured features are inference tensors, so the _version key is always None (336/336 rejected). There is also a latent apply_scale multi-group bug. See #4051 item 2.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugperformance

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions