Skip to content

perf(gptq): resolve the desc_act sink-row cap without syncing per add_batch (#4950) - #4976

Merged
Qubitium merged 1 commit into
mainfrom
root/descact-cap-sync-4950
Nov 17, 2026
Merged

Qubitium merged 1 commit into
mainfrom
root/descact-cap-sync-4950

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

#4909 fixed #4742 by capping each calibration row's norm before X^T X, but it
computed the cap in resolve_sink_row_cap_scale, which compute_hessian_xtx
called on every add_batch of every module with desc_act=True. That did
four device-to-host reads per call (bool(isfinite(norms).all()),
bool(isfinite(threshold)), float(threshold), bool((scale >= 1).all())),
and whenever a cap applied it moved the GEMM off the fp32 matmul fast path
onto the leased chunk-workspace path (chunk_size = rows). add_batch runs
inside the layer forward hooks, so every read drained the CUDA queue in the
middle of the calibration forward: desc_act=True quantization was ~2x slower.

The cap's numerics are unchanged. Only how they are computed changed.

What Changed

  • GPTQ.resolve_sink_row_cap_threshold (new) derives
    min(p99.9, N x median) from one torch.sort of the row norms, entirely on
    device. The old early-return cases (a non-finite row norm, a non-finite or
    non-positive threshold) now fold into the tensor as threshold = +inf
    through torch.where, which makes every scale 1 — the same Hessian the old
    None produced, without a host read.
  • GPTQ._sink_row_cap_scale_from_threshold (new) builds the per-row clamp on
    device; resolve_sink_row_cap_scale keeps its old signature as a pure
    function of the matrix (the [QUALITY] GPTQ desc_act=True on Llama-3.1-8B is worse than RTN (PPL 11.62 vs 10.22): layers.1.mlp.down_proj columns saturate on BOS-sink Hessian, 10/160 wikitext windows reach PPL 800-12000 (#4393 unsolved for desc_act) #4742 tests use it).
  • GPTQ.compute_hessian_xtx multiplies the fp32 staging copy by the scale and
    stays on the single-GEMM fast path instead of switching to the chunk lease.
    The multiply is out of place when the input is already fp32, because
    matrix.to(torch.float32) then returns the caller's tensor and activations
    can be shared by several projections.
  • sink_row_cap_median_multiple tolerates a capture built without qcfg
    (the GPTQ.__new__ accumulators in tests/test_rocm_quant_blas.py), which
    fixes two tests that fail on main for the same reason.
  • docs/gptq-hessian-accumulation.md gains a desc_act sink-row cap section
    with the shipped flow diagram; docs/rocm-default-environment.md and
    tests/test_docs_contract_refs.py follow the moved line numbers.

Deliberately not done: caching the threshold on the first batch. It is the
cheapest way to skip the per-batch sort, and it was implemented and measured,
but it decides later batches against a stale bound. On Qwen2.5-0.5B-Instruct it
changed the quantized checkpoint (wikitext-2 PPL 20.78 vs 20.32) for a ~2 s
gain on the whole run. The per-batch decision is kept so the Hessian stays
bitwise identical to main.

Tests

export CUDA_HOME=/usr/local/cuda PATH=/usr/local/cuda/bin:$PATH \
  TORCH_CUDA_ARCH_LIST=8.0 TORCH_NO_COMPILER_WRAPPER=1 \
  GPTQ_BYPASS_SAFETY_CHECKS=1 LOGBAR_ANIMATION=0 CUDA_VISIBLE_DEVICES=5 \
  PYTHONPATH=$PWD HF_HUB_OFFLINE=1

# new regression: red on origin/main, green here
/root/venv-kernels/bin/python /tmp/root-rt.py tests/test_descact_cap_sync_4950.py -q
# origin/main @ f160a408d: 3 failed, 2 passed
#   AssertionError: desc_act sink-row cap read the host on every add_batch:
#     16 reads for 4 batches
#   AttributeError: type object 'GPTQ' has no attribute
#     'resolve_sink_row_cap_threshold'
#   AssertionError: capped desc_act batch left the fp32 matmul fast path
#     for the chunk workspace: [64]
# this branch: 5 passed

/root/venv-kernels/bin/python /tmp/root-rt.py \
  tests/test_descact_sink_4742.py tests/test_descact_cap_sync_4950.py \
  tests/test_gptq.py tests/test_gptq_cuda.py tests/test_gptq_fallback_offset.py \
  tests/test_gptq_hessian_accumulation.py tests/test_gptq_hessian_alloc_fallback_4350.py \
  tests/test_gptq_hessian_pipeline.py tests/test_gptq_keep_mask_device.py \
  tests/test_gptq_mock_group_order.py tests/test_gptq_post_inverse_fallback_4400.py \
  tests/test_gptq_shared_hessian.py tests/test_gptq_static_group_order.py \
  tests/test_gptq_workspace_release.py \
  tests/kernels/test_kernel_compile_levels_quant.py \
  tests/test_quantize_call_signature_4868.py tests/test_quantize_config_offload_tempdir.py \
  tests/test_quantize_device_sequence_4875.py tests/test_quantize_in_session_4381.py \
  tests/test_quantize_run_summary.py tests/test_quantized_embeddings.py -q
# 561 passed, 10 skipped, 1 failed
#   tests/test_quantize_in_session_4381.py::test_rehome_qqq_initializes_torch_cache_after_class_switch
#   AttributeError: 'QQQTorchLinear' object has no attribute '_torch_dropped_checkpoint'
#   -- identical failure on unmodified origin/main (env/transformers 5.20.2), not a delta

/root/venv-kernels/bin/python /tmp/root-rt.py tests/test_rocm_quant_blas.py -q
# this branch: 26 passed
# origin/main: 2 failed, 24 passed -- both failures are
#   AttributeError: 'GPTQ' object has no attribute 'qcfg'
#   from the GPTQ.__new__ accumulators, which the getattr in
#   sink_row_cap_median_multiple now tolerates

/root/venv-kernels/bin/python /tmp/root-rt.py tests/test_docs_contract_refs.py -q
# 16 passed, 4 failed -- the same 4 pre-existing base.py line-citation
# failures as origin/main; the two rocm-default-environment citations this
# PR moves now resolve

/root/venv-py3.14t-gil0/bin/ruff check gptqmodel/quantization/gptq.py \
  tests/test_descact_cap_sync_4950.py tests/test_docs_contract_refs.py
# All checks passed!

New test (tests/test_descact_cap_sync_4950.py, CPU-only, no checkpoint):

  1. counts torch.Tensor.item/__bool__/__float__/__int__ on the device path for
    4 and 12 add_batch calls: 16 reads on main (4 per batch), 0 here;
  2. pins that the cap is decided from the batch being accumulated: three
    batches with different norm distributions must reproduce main's per-batch
    capped H bitwise (torch.equal);
  3. asserts a capped batch never enters borrow_materialized_chunk_fp32;
  4. asserts the [QUALITY] GPTQ desc_act=True on Llama-3.1-8B is worse than RTN (PPL 11.62 vs 10.22): layers.1.mlp.down_proj columns saturate on BOS-sink Hessian, 10/160 wikitext windows reach PPL 800-12000 (#4393 unsolved for desc_act) #4742 cap is in force on the very first batch;
  5. asserts the single-batch capped H is bitwise equal to main's formula.

Numerics

H is bitwise identical to main for the #4742 fixture (single batch) and for
a 3-batch sequence (torch.equal, 0 tolerance). End-to-end, the quantized
Qwen2.5-0.5B checkpoint gives the same wikitext-2 PPL as main:

quantize region "Forward" (21504) "Pre-quant forward" PPL
pre-#4909 7edbca826^ 157.3 s 2.53 s 27.6 s 20.278
main run A 174.8 s 12.22 s 41.0 s 20.319
main run B 79.9 s 23.09 s 58.5 s 20.319
this PR run A 60.2 s 8.50 s 41.7 s 20.319
this PR run B 45.7 s 8.67 s 30.4 s 20.319

Qwen2.5-0.5B-Instruct, GPTQConfig(bits=4, group_size=128, desc_act=True),
128 C4 rows, fp16, CUDA_VISIBLE_DEVICES=5 on a shared 8x PG506 (80-92 GiB of
98 GiB already in use by other tenants). Wall-clock and the forward region
move a lot with that contention — the sync-heavy main path suffers most,
which is the bug — so the paired region totals matter more than the absolute
seconds.

GPTQ.compute_hessian_xtx microbenchmark (fp16, cols=896, rows=512, 20
iterations, same box):

cap applied cap disabled default
main 7.70 ms 0.215 ms 0.187 ms
this PR 0.61 ms 0.218 ms 0.189 ms

Of the remaining 0.61 ms, 0.25 ms is the row-norm + sort decision and the rest
is the fp32 GEMM plus the row scale. The cap disabled/default paths are
untouched.

  • Unit tests have been executed and passed, or the reason they are not applicable is documented.
  • I added a new simple/fast unit test for this change, or documented why that is not applicable.

Model Support / Module Plan

Not applicable: no MODEL_MAP, definition, alias, module-plan or fusion change.

Logic Flow Documentation

  • The desc_act sink-row cap flow is documented with a Mermaid diagram and
    a before/after table in docs/gptq-hessian-accumulation.md#desc_act-sink-row-cap,
    linked from README.md. The removed mechanism (four host reads plus the
    chunk-lease switch) is tabulated with file:line evidence.
flowchart TD
    A["compute_hessian_xtx(matrix)"] --> B["resolve_hessian_chunk_size"]
    B --> C["resolve_sink_row_cap_threshold(matrix, chunk_size)"]
    C --> D{"sink_row_cap_median_multiple()"}
    D -- None --> E["no cap"]
    D -- "N > 0" --> F["_sink_row_norms: fp32 row L2, chunk-staged"]
    F --> G["torch.sort(norms) once"]
    G --> H["threshold = min(ordered[p99.9], N x ordered[median])"]
    H --> I{"every norm finite and threshold > 0?"}
    I -- No --> J["threshold = +inf, so every scale is 1"]
    I -- Yes --> K["keep threshold"]
    K --> L["_sink_row_cap_scale_from_threshold: clamp(threshold / norm, max=1)"]
    J --> L
    L --> M{"chunk_size is None?"}
    M -- Yes --> N["fp32 fast path: (X * s)^T (X * s)"]
    M -- No --> O["chunk lease: (X_c * s_c)^T (X_c * s_c) per chunk"]
    classDef bad fill:#fdd,stroke:#c33
    class J bad
Loading

AWQ onboarding safety

Not applicable: no model/alias onboarding and no AWQ grouping, search, replay
or fold change.

`resolve_sink_row_cap_scale` ran on every `add_batch` of every module when
`desc_act=True`, and it read the host four times per call:
`bool(isfinite(norms).all())`, `bool(isfinite(threshold))`,
`float(threshold)` and `bool((scale >= 1).all())`. `add_batch` runs inside the
layer forward hooks, so each read drained the CUDA queue mid-calibration.
When a cap applied it also left the single fp32 `X^T X` GEMM for the leased
chunk-workspace path (`chunk_size = rows`).

Compute the whole cap decision with tensor ops and fold the per-row scale into
the existing fp32 fast path:

* `resolve_sink_row_cap_threshold` derives `min(p99.9, N x median)` from one
  device sort of the row norms and turns a non-finite/non-positive threshold
  (where the old code returned `None`) into `+inf` through `torch.where`;
* `_sink_row_cap_scale_from_threshold` builds the per-row clamp on device;
* `compute_hessian_xtx` multiplies the fp32 staging copy by the scale instead
  of switching to the chunk lease, so a capped batch keeps the single-GEMM
  path. The multiply is out of place when the input is already fp32, because
  `matrix.to(float32)` then returns the caller's (possibly shared) tensor.

The cap is still decided per batch, so the Hessian is bitwise identical to the
pre-#4950 formula for one batch and for a batch sequence. Caching the threshold
on the first batch was tried and rejected: it changed the quantized Qwen2.5-0.5B
checkpoint (wikitext PPL 20.78 vs 20.32).

`test_descact_cap_sync_4950.py` pins the absence of per-`add_batch` host reads,
the fast-path choice, the first-batch cap and the bitwise H. It fails on
`main` (16 host reads for 4 batches, no device-only threshold resolver, one
chunk lease per capped batch) and passes here.

Qwen2.5-0.5B-Instruct, 4-bit/gs128/desc_act, 128 C4 rows, fp16, shared PG506
(two runs each, the box is 80-92 GiB of 98 GiB busy): region "Forward" over
21504 calls 12.2-23.1 s -> 8.5-8.7 s, `quantize()` 79.9-174.8 s -> 45.7-60.2 s,
wikitext-2 PPL unchanged at 20.319 (pre-#4909: Forward 2.53 s, PPL 20.278).
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