Repository navigation
GPTQ
🏠 Home · 🧭 Choose a method · 🚀 Quickstart · 🧰 Help
On this page
Compress model weights with a recipe that matches your calibration budget. For model authors choosing a first low-bit checkpoint: start with GPTQ, compare RTN as a simple baseline, and explore GPTAQ when native-versus-quantized input drift deserves extra work and memory.
| Choose | Choose this when… | Consider another path when… |
|---|---|---|
| GPTQ | You can provide representative calibration and want second-order weight-error compensation | You have no calibration data → RTN; your deployment expects AWQ layouts → AWQ |
| GPTAQ | You want to test a native-input correction for drift introduced by quantized replay, and can afford its extra state | Memory is tight, or you need ordinary GPTQ's chunked/shared Hessian or low-sample/NaN recovery policies → GPTQ |
| G2PTQ | You want to test block-level gradient compensation with a GPTQ checkpoint | You need to avoid differentiable block replay during calibration → GPTQ |
| JointQ | You want to refine group scales and integer codes together using the calibration Hessian | You need a lower-cost solve → GPTQ |
| ADMM-Q | You want to compare an iterative whole-layer Hessian solve using the same GPTQ packing | You need a single-pass weight solve → GPTQ |
| RTN | You need a calibration-free rounding baseline or a quick compatible export | Low-bit quality matters enough to collect calibration → compare GPTQ/AWQ on held-out data |
Your route: 🧭 Compare the algorithms · 🚀 Quantize a model · 🔬 Math and intuition, controls, and internals.
GPT-QModel provides these related weight-quantization paths:
| Path | Configuration | Calibration | What it optimizes |
|---|---|---|---|
| GPTQ | GPTQConfig(...) |
Required | Layer-output reconstruction using input second-order statistics and compensation of rounding errors in the remaining weights |
| GPTAQ | GPTQConfig(gptaq=GPTAQConfig(...)) |
Required, including a native-input reference pass | GPTQ-style reconstruction plus a correction for the difference between native and replayed inputs |
| G2PTQ | GPTQConfig(g2ptq=G2PTQConfig(...)) |
Required, including differentiable block replay | GPTQ's second-order update plus a first-order correction bounded by a per-row trust region |
| JointQ | GPTQConfig(jointq=JointQConfig(...)) |
Required | Hessian-weighted reconstruction through coupled scale and integer refinement |
| ADMM-Q | ADMMQConfig(...) |
Required | Hessian-weighted layer reconstruction with alternating continuous updates and discrete grid projections, followed by optional PairSwap refinement |
| RTN | RTNConfig(...) |
Not required | Direct round-to-nearest weight quantization, optionally with weight-range smoothing/search; no Hessian |
These are quantization algorithms, not inference kernels. Quantization produces rounded weights and scale/zero/group metadata; packing then encodes them for a checkpoint and runtime backend. RTN can produce a GPTQ-format checkpoint without running the GPTQ algorithm. Similarly, GPTAQ still belongs to the METHOD.GPTQ family. RTNConfig also uses METHOD.GPTQ; there is no METHOD.RTN. Its uses_weight_only_lifecycle() selects the calibration-free path, while the export format determines the checkpoint's method family.
The name GPTAQ needs particular care:
- The activation-aware algorithm is implemented by
GPTAQingptqmodel/quantization/gptaq.py. Select it withgptaq=GPTAQConfig(...). -
FORMAT.GPTQ_V2, whose string value is"gptq_v2", is a checkpoint zero-point convention. It is not a switch for the GPTAQ algorithm. - There is no
v2field in the currentGPTQConfig. Do not copyv2=Truefrom a different API or an older example into a current configuration.
This page describes public source revision 2aee8ddc2. The method-specific configuration API, protocol compiler, and W4A policies below should be read in that source context. See Installation and Quickstart for installation and QuantizeConfig Reference for the complete shared configuration surface.
Install a matching GPT-QModel environment and choose an accessible supported model. The examples use a local ./source-model directory. For GPTQ/GPTAQ, create calibration.txt with one representative text sample per line; do not use evaluation examples as calibration. Samples of 10 tokens or fewer are dropped by the default length filter.
Plan space for source weights, the dense input-width-squared Hessian and factorization workspace, and (for GPTAQ) native-reference state. Offload and Hessian chunking help particular allocations; they do not cap total memory. Check NVIDIA CUDA and AMD ROCm backend contracts separately; an available Triton installation is not a hardware-support matrix.
The examples use exported config classes from gptqmodel.quantization. Start with a compatible saved layout, then select an inference backend; neither gptq_v2 nor a backend name chooses GPTAQ for you.
Use representative calibration text from the deployment domain. The example reads your finite calibration file. Use real task-relevant text; a few synthetic strings would only demonstrate the API, not establish accuracy.
from pathlib import Path
from gptqmodel import CalibrationConfig, GPTQModel
from gptqmodel.quantization import GPTQConfig
calibration_texts = [
text for text in Path("calibration.txt").read_text(encoding="utf-8").splitlines()
if text.strip()
]
qcfg = GPTQConfig(
bits=4,
group_size=128,
sym=True,
true_sequential=True,
)
model = GPTQModel.load("./source-model", quantize_config=qcfg)
model.quantize(CalibrationConfig(dataset=calibration_texts, batch_size=1))
model.save("./model-gptq")This keeps the current default group-aware ordering. For classic global act-order, specify:
qcfg = GPTQConfig(
bits=4,
group_size=128,
desc_act=True,
act_group_aware=False,
static_groups=True,
true_sequential=True,
damp_percent=0.05,
damp_auto_increment=0.01,
)For an explicitly natural-order experiment, set both desc_act=False and act_group_aware=False. Change one factor at a time when comparing accuracy.
Reuse the calibration-file preparation from the GPTQ example; the top-level gptaq setting enables the required native-reference capture.
from gptqmodel import CalibrationConfig, GPTQModel
from gptqmodel.quantization import GPTAQConfig, GPTQConfig
qcfg = GPTQConfig(
bits=4,
group_size=128,
act_group_aware=False,
gptaq=GPTAQConfig(alpha=0.25, device="cpu"),
)
model = GPTQModel.load("./source-model", quantize_config=qcfg)
model.quantize(CalibrationConfig(dataset=calibration_texts))
model.save("./model-gptaq")The model lifecycle inserts native input capture; do not bypass it by constructing an unprepared GPTAQ task and assuming its reference inputs will exist. Ordinary GPTQ and GPTAQ both reject a missing calibration dataset at the model API level. GPTAQ and FOEM support classic desc_act, group-aware act_group_aware, or natural order. An explicit act_group_aware=False in an example selects natural order when desc_act=False; it is not a GPTAQ requirement.
G2PTQ refreshes a grouped Fisher Hessian and a weight gradient before quantizing each decoder block or sequential subset. Intermediate blocks use block-output mean squared error (MSE). With kl_last_block=True (the default), the final Transformer block uses a KL objective on logits from the model's final norm, when declared, and a supported output head. This applies even if the output head stays dense. A head being quantized separately can use KL directly on its logits. Set kl_last_block=False to use MSE throughout.
The final-block path supports a linear, Conv1D, or tied-embedding head. If the path is unavailable, for example because the model definition preprocesses head inputs through a custom hook, G2PTQ warns once and uses block-wise MSE for that block. The differentiable replay runs during quantization. The result uses the selected GPTQ checkpoint layout, records the solver settings under meta.g2ptq, and loads with compatible GPTQ backends.
Reuse the representative calibration_texts from the GPTQ example. seed controls the Fisher noise and KL label draws for block refresh. It defaults to 0. The draws are derived from that seed and the layer index, independently of the global PyTorch RNG.
from gptqmodel import CalibrationConfig, GPTQModel
from gptqmodel.quantization import G2PTQConfig, GPTQConfig
config = GPTQConfig(bits=4, group_size=128, g2ptq=G2PTQConfig(seed=0))
model = GPTQModel.load("Qwen/Qwen2.5-0.5B-Instruct", quantize_config=config)
model.quantize(CalibrationConfig(dataset=calibration_texts))
model.save("qwen2.5-0.5b-g2ptq")A module missing either its grouped Hessians or its weight gradient uses GPTQ compensation. Look for the G2PTQ: Module ... has no block statistics warning after a direct hf_quantize() solve or a missed refresh. Standard GPTQ fallback cases, such as zero samples or calibration below the fallback threshold, keep their usual handling. A failed replay also logs a warning for the affected block. See the configuration fields, G²PTQ paper, and repository benchmarks and replay details.
If a memory allocation fails during the grouped column pass on CUDA or ROCm, G2PTQ restarts the pass once on CPU using the weights from before the pass began. Other block-pass errors propagate. A NaN loss with fallback configured restores the captured Hessian diagonal and retries through GPTQ's mock-quantization path. With fallback disabled, a NaN loss raises ValueError.
When requantizing endpoints, G2PTQ skips grouped replay for token-ID embedding tables and quantizes them with plain GPTQ. An eligible linear output head still runs the G2PTQ refresh with head preprocessing and uses the KL objective by default. This also applies when requantize(embed_quant_mode=QuantizeEmbed.BOTH) includes both endpoint types. Endpoint replay details.
ADMM-Q uses GPTQ's calibration activations to build a Hessian for each linear layer. It alternates between a continuous Hessian-weighted update and projection onto the per-group quantization grid. PairSwap then tries paired changes to nearby integer codes. The solver keeps the initial round-to-nearest (RTN) projection if its final reconstruction objective is non-finite or worse than that baseline.
Reuse the representative calibration_texts from the GPTQ example.
from gptqmodel import ADMMQConfig, CalibrationConfig, GPTQModel
qcfg = ADMMQConfig(bits=4, group_size=128)
model = GPTQModel.load("./source-model", quantize_config=qcfg)
model.quantize(CalibrationConfig(dataset=calibration_texts, batch_size=1))
model.save("./model-admmq")
reloaded = GPTQModel.load("./model-admmq")The default configuration permits up to 300 iterations, enables one guarded grid refresh on stagnation, and enables PairSwap. Use pairswap_mode="off" to skip the local search. For a quality comparison, keep the calibration and packing settings fixed across solvers and evaluate the reloaded checkpoints on held-out data.
ADMM-Q supports 3–8-bit weight-only quantization. GPT-QModel rejects 2 bits in ADMM-Q run configs and dynamic rules. Loading a legacy 2-bit ADMM-Q checkpoint also raises an error. The paper's 2-bit results use SpinQuant W2A4KV4, with rotation and quantization of both activations and the KV cache. See the ADMM-Q paper and implementation notes.
Omitting mse enables shrink-grid search with MSEConfig(norm=2.0) at 3 bits and disables it at 4–8 bits. Pass mse=0 to disable it explicitly. The repository's ADMM-Q perplexity benchmark accepts --mse-norm to compare settings.
adaptive_penalty=True selects the penalty schedule per layer using the preconditioned Hessian's condition number. The solver uses the configured rho and rho_update at or below 5e4. Above 5e4, it uses rho=0.05, and above 3e5 it uses rho=0.01. Both overrides use rho_update=1.05 at the configured update_iter interval. Set adaptive_penalty=False to use the configured schedule for all layers. The benchmark has the equivalent --admmq-adaptive-penalty {on,off} flag and defaults to on. Completed solves report the selected schedule in admmq_diagnostics["rho_initial"] and admmq_diagnostics["rho_update"].
Layers that lack sufficient calibration samples use the GPTQ family's configured fallback. If the ADMM-Q solve hits a supported accelerator allocation failure, it retries on CPU with the original inputs. An eigendecomposition failure, non-finite eigenvalues, a non-finite iterate, or non-finite reconstruction loss triggers the GPTQ RTN fallback for that layer. The per-module record gives the cause in fallback_reason. If the fallback also returns non-finite weights, quantization raises an error. See the solver implementation.
ADMM-Q uses float64 torch.linalg.eigh to factorize the Hessian. Layers on CPU, CUDA, and ROCm solve on their source device. Layers on other device families, including MPS, XPU, and NPU, run the solve on CPU and return the reconstructed weights to the source module's device for replay.
The saved checkpoint uses the selected GPTQ layout and its compatible inference backends. It publishes quant_method="gptq", records method="admmq", and stores the solver settings under meta. See the ADMMQConfig reference and algorithm, paper, and benchmark results.
After quantize(), read model.admmq_diagnostics on the same model instance. summary reports the module names under early_stop_layers, max_iter_layers, and rtn_fallback_layers. Reaching max_iter means the solver used its full budget. The summary also reports grid refresh and PairSwap activity, finite min/median/max for iteration counts and condition numbers, and a separate condition_number_nonfinite count.
diagnostics = model.admmq_diagnostics
if diagnostics is not None:
print(diagnostics["summary"]["rtn_fallback_layers"])
for name, entry in diagnostics["layers"].items():
print(name, entry["stop_reason"], entry["fallback_reason"])layers uses full module names as keys. Each record includes the stop reason (early_stop, max_iter, skipped, or fallback), iteration counts, condition number, and refinement and fallback details. GPT-QModel logs one aggregate diagnostics warning when any module was skipped, used RTN fallback, or had a non-finite condition number.
Diagnostics are runtime-only, so a reloaded checkpoint starts with model.admmq_diagnostics = None. On resume, the report covers modules processed in that invocation. A fully restored run produces no new report. Complete diagnostics schema.
This example needs the supported local source model but no calibration file. Optional refinement or preprocessing may introduce its own data requirements.
from gptqmodel import GPTQModel
from gptqmodel.quantization import FORMAT, RTNConfig
qcfg = RTNConfig(bits=4, group_size=128, sym=True, format=FORMAT.GPTQ)
model = GPTQModel.load("./source-model", quantize_config=qcfg)
model.quantize()
model.save("./model-rtn")This is a native weight-only lifecycle. It does not manufacture an identity Hessian or feed dummy calibration through GPTQ. It is useful as a direct rounding baseline, but its error statistic is not GPTQ's Hessian reconstruction loss.
from gptqmodel.quantization import FORMAT, GPTQConfig
qcfg = GPTQConfig(
bits=4,
group_size=128,
sym=False,
format=FORMAT.GPTQ_V2,
)This selects affine asymmetric weight quantization and v2 checkpoint zero semantics. It does not enable GPTAQ. Conversely, gptaq=GPTAQConfig(...) does not require sym=False.
Legacy gptq (v1) serialization shifts packed zeros by one; loading for a v2-requiring kernel applies the corresponding correction. This matters particularly for asymmetric zero points. MIN_VERSION_WITH_V2 is "0.9.0": the loader guards asymmetric format="gptq" checkpoints using quantizer producer/version metadata. Its helper methods have historical names such as is_quantized_by_gptaq(), but the actual check is for a gptqmodel producer version at or above that minimum; the name is not proof that GPTAQ ran.
Do not fix compatibility by editing checkpoint_format, sym, or packed qzeros manually. Format conversion is bit-layout-aware; for example, INT3 zero fields can span packed words. Choose a compatible exporter/loader/backend and preserve the recorded producer metadata. See Packing Formats and Compatibility.
import torch
from gptqmodel.quantization import GPTQConfig, HessianConfig, MSEConfig
qcfg = GPTQConfig(
bits=4,
group_size=128,
hessian=HessianConfig(
chunk_size=1024,
staging_dtype=torch.float32,
dedup_shared_inputs=True,
),
mse=MSEConfig(norm=2.4, grid_budget="128M"),
)The example values 1024, 2.4, and "128M" are explicit choices, not project defaults. Hessian chunking bounds input-materialization work; it does not remove the dense [in_features, in_features] Gram matrix or its factorization. MSE workspace budgets are separate from Hessian memory.
HessianConfig field |
Default | Meaning |
|---|---|---|
chunk_size |
None |
Optional row-count limit for Hessian accumulation chunks |
chunk_bytes |
None |
Optional chunk byte budget |
staging_dtype |
torch.float32 |
Staging dtype; allowed choices are float32, float16, and bfloat16
|
dedup_shared_inputs |
True |
Enable compatible shared-input Hessian reuse |
The Gram products and accumulated Hessian are float32. A lower staging dtype changes staging/storage behavior; it does not make Cholesky a low-bit operation. chunk_size takes precedence over chunk_bytes when both are set. A byte budget smaller than one row still stages at least one row. Lower-precision staging is used only for FP16/BF16 inputs, and BF16 additionally requires device support; otherwise staging falls back to FP32. These controls apply to ordinary GPTQ's accumulation, not GPTAQ's overridden recurrence.
Idle staging storage is bounded per device: the pool keeps the most recently released shape and evicts older idle shapes until their combined storage with that shape is at most twice the retained shape's idle storage. In-use buffers, the Hessian itself, and allocator reservations are outside this bound. See staging pool source.
For embeddings, GPTQ uses a dedicated diagonal-statistics path: it counts calibration token IDs instead of constructing a dense one-hot input matrix. Internally, the embedding weight is transposed so these statistics index vocabulary/token columns. Token IDs outside [0, num_embeddings) are rejected. The embedding solve quantizes weight groups with the applicable ordering, restores the weight/group layout, and reports a diagonal-weighted reconstruction loss. static_groups=True bypasses embedding ordering; this path does not run the dense inverse-factor/error-update loop or the ordinary early low-sample fallback. Do not interpret embedding token-frequency statistics as the dense Linear Hessian described above.
MSEConfig field |
Default | Meaning |
|---|---|---|
norm |
0.0 |
Exponent of the reconstruction-error objective; search runs when positive |
grid_budget |
None |
GPTQ/quantizer vectorized shrink-grid scratch target |
At the low-level Quantizer.configure(trits=True) API, MSE searches three-level candidates by shrinking the positive and negative endpoints around zero. It includes the original endpoints as the starting candidate.
The implicit budget is 16 MiB on CPU and 256 MiB on non-CPU devices. Byte budgets accept nonnegative integers or strings with binary K, M, or G suffixes and an optional B. For example, "128M" means 128 * 2**20 bytes. 0 selects single-candidate chunks. The budget sizes individual calibration workspaces. mse=2.4 is equivalent to MSEConfig(norm=2.4). Reserve clip_grid_budget for AWQ configs.
Reading the diagram: Alternative paths, not consecutive stages. GPTQ/GPTAQ repeat per layer and subset; GPTQ_V2 selects zero-point storage, not GPTAQ.
Text version of the workflow
- GPTQ: Capture calibration → Build inverse factor → Round and compensate → Pack weights.
- GPTAQ: Capture native inputs → Compare replayed inputs → Apply GPTAQ correction → Pack weights.
- RTN: no calibration: Read module weights → Fit group ranges → Round directly → Pack compatible layout.
RTN asks which representable value is nearest to each weight. GPTQ also asks how that rounding changes outputs for the observed inputs, then adjusts weights still to be rounded. GPTAQ adds a native-input reference to address drift from quantized replay. These are local objectives: choose between them by evaluating the finished model, not by comparing unlike log-loss fields.
For a linear layer, let the weight matrix have shape [out_features, in_features], and let calibration inputs be rows of a matrix X with shape [tokens, in_features]. The reconstruction objective compares the original and rounded layer outputs:
For an individual output row, the quadratic error is controlled by the input Gram matrix. GPT-QModel accumulates unnormalized X.T @ X contributions and materializes
where N is the accumulated activation-row/token count after the module-specific input reshape. This is the Hessian of the layerwise quadratic reconstruction objective, not a full-model loss Hessian obtained by backpropagation.
The optimal-brain-quantization (OBQ) idea is to round one weight coordinate and adjust the remaining coordinates using inverse-Hessian information. GPTQ applies that idea across output rows together, in a shared column order, and batches the expensive updates into blocks. RTN instead rounds each group without compensating the other columns for the introduced error.
Practical consequences:
- Calibration inputs affect GPTQ's result even though only weights are stored at low precision.
- An unobserved input direction has no calibration evidence; the implementation must explicitly handle zero diagonal entries.
- A small layer reconstruction loss is not a downstream benchmark score.
- GPTQ alone is not activation quantization. Low-precision activation policies are separate, explicit options.
GPTQ.hessian_inverse(H) first regularizes the diagonal and attempts Cholesky factorization. On the normal CPU/CUDA path, it computes a Cholesky factor of the regularized Hessian, applies torch.cholesky_inverse, and takes an upper Cholesky factor of that inverse.
Consequently, the variable named Hinv in the quantization loop is an upper-triangular inverse factor, not simply a dense inverse matrix. If the regularized Hessian is Hλ, the factor U satisfies:
For a working column w, rounded column q, and factor diagonal d = U[i, i], the eager loop computes:
The within-block loss contribution is (w - q).square() / d.square(), divided by two after the block. The accumulated error matrix updates later blocks through a matrix multiplication. This is why replacing the inverse factor with an ordinary inverse would not be equivalent.
Damping adds a diagonal term before factorization:
| Name | Current meaning | GPTQ default / behavior |
|---|---|---|
damp_percent |
Dimensionless fraction λ multiplying the mean Hessian diagonal |
Dataclass field starts as None; normalized GPTQ default is 0.05
|
damp_auto_increment |
Additive step for the compatible retry grid | Field starts as None; normalized GPTQ default is 0.01
|
damp in returned results/logging |
The damping fraction actually selected by the inverse routine | May differ from the requested starting fraction |
percdamp |
Argument name in the low-level Hugging Face compatibility wrapper | Wrapper default is 0.01, not the GPTQConfig default |
0.05 means five percent of the mean live Hessian diagonal. When unobserved input columns have a zero diagonal, the solver replaces those entries with the live mean and zeroes their weight columns.
Configuration validates 0 < damp_percent < 1. Negative damp_auto_increment is rejected; zero is accepted and leaves only the starting damping candidate. With a positive increment, candidates reproduce repeated floating-point addition from the configured start while the next candidate remains below 1.0. The inverse routine restores the diagonal between probes and can retry with up to six diagonal-floor attempts. Normal CPU/CUDA probes use torch.linalg.cholesky_ex(..., check_errors=False); NPU uses npu_inverse_cholesky_factor.
GPTQ, GPTAQ, and FOEM try the first additive retry before building the full grid. If that probe fails and the grid would exceed 65,536 candidates, they log the suggested minimum increment, skip the remaining grid, and continue with diagonal-floor recovery. If you hit that diagnostic, increase damp_auto_increment or start with a higher damp_percent. See the shared inverse routine.
An unrecoverable factorization returns (None, 1.0). The ordinary quantization loop can then proceed without Hessian error updates. This is distinct from the separate insufficient-calibration fallback policy, which may select RTN before an inverse is attempted. Inspect the selected damping, fallback warnings, samples, and loss together rather than assuming that a completed run used the original settings for every module.
Classic activation ordering (desc_act=True, also called act-order) sorts input columns by descending Hessian diagonal. GPTQ permutes both weights and the Hessian, quantizes in that order, and restores the original column order before returning the weight tensor. It also restores the group-index mapping needed by packing/inference.
The current API additionally provides group-aware ordering:
| Setting | Effective GPTQ default | Behavior |
|---|---|---|
desc_act |
False |
Global descending Hessian-diagonal order when enabled |
act_group_aware |
True after normalization |
Uses local group permutations and a global group permutation, composes them, and extends the permutation over a partial tail |
Both False
|
Explicit opt-out | Natural input-column order |
Both explicitly True
|
Invalid | Raises a configuration error |
Both fields are declared as optional and initially default to None; the table lists the resolved GPTQ behavior. Setting desc_act=True without specifying act_group_aware automatically disables group-aware ordering with a warning. Set act_group_aware=False explicitly to make classic act-order intent unambiguous. A group_size <= 0 likewise disables act_group_aware with a warning even when it was set explicitly: the flag only permutes channels inside a quantization group, and a single full-row group leaves nothing to reorder.
Do not assume that desc_act=False alone means no ordering: the current GPTQ default still enables act_group_aware. Ordering and group-index support must also be compatible with the chosen inference kernel; see Kernel Backends Reference.
Classic act-order now bounds extreme calibration-row contributions to the Hessian by default. With desc_act=True and act_group_aware=False, HessianConfig.sink_row_cap_median_multiple=4.0 caps each row's L2 norm at min(p99.9 of row norms, 4 × median) before XᵀX, preserving direction while reducing attention-sink dominance. The threshold uses the whole batch, independent of Hessian chunking; non-finite norms or a nonpositive threshold skip the cap. The default group-aware path is unchanged. Set the multiplier to 0 or None to disable this behavior; the setting survives configuration save/reload. This is separate from dropping sink tokens with CalibrationConfig(exclude_attention_sinks=True). Validate checkpoint quality, especially for Llama-3 classic act-order, rather than treating either mitigation as a quality guarantee. See Hessian configuration and the accumulator implementation.
The cap stays on the activation device, avoiding a per-batch GPU-to-host synchronization to read the threshold. Unchunked Hessian accumulation still uses a single matrix multiplication. See the sink-row cap implementation notes.
GPTAQ and FOEM compute the same cap from the current activation rows and apply the same factors to the paired native rows before forming the cross moment. GPTAQ accumulation · FOEM accumulation
group_size is the number of input columns sharing a scale/zero point for an output row. It is not the block-update width. The default group size is 128; -1 selects a full-row group. GPTQ.quantize(blocksize=128) controls the computational block width independently.
For full-row quantization, keep one quantizer per output row, spanning its input columns. This is per-output-channel granularity, not one scale for the entire tensor:
from gptqmodel.quantization import GPTQConfig
full_row = GPTQConfig(
bits=4, group_size=-1, act_group_aware=False, static_groups=False,
)Full-row GPTQ normalizes the ordering flag away: GPTQConfig(group_size=-1) warns that act_group_aware has no effect and disables it, where earlier revisions rejected the combination at task construction. Set act_group_aware=False explicitly to silence the warning; static_groups still expects a positive group step, so keep static_groups=False for full-row use. RTNConfig(group_size=-1) has no group-aware ordering field and does not have this restriction.
static_groups |
Parameter discovery | Interaction with classic act-order |
|---|---|---|
False (default) |
Refresh quantizer parameters at group boundaries using the current working weight matrix | Groups follow the processing order and require the corresponding g_idx mapping |
True |
Deep-copy and fit one quantizer per original group before the column loop | The column's original index selects the precomputed group after either the desc_act or group-aware permutation |
The static-group implementation iterates with range(0, columns, group_size). Use a positive group size when requesting static groups; group_size=-1 is the full-row mode, not a positive iteration step for that precomputation. Static groups do not disable the Hessian or the sequential error correction.
Static scales/zeros stay in original-group order after group-aware quantization; only dynamically fitted parameters need the inverse group permutation. Both eager and eligible native block-update paths use each reordered column's original group, including blocks spanning multiple static groups. mock_quantization=True also selects the correct per-column static quantizer. For non-static positive groups, its work blocks follow group_size so each group is fitted and quantized with its own parameters even when that size differs from blocksize; it is not ordinary Hessian error compensation. Full-row symmetric mock quantization uses the fitted grid, including code 0 (the signed level −8 at 4 bits). GPTQ, GPTAQ, and FOEM resolve the static group mapping once per module when ordering permutes the columns.
The ordering and static-group descriptions above refer to ordinary GPTQ's dense-Hessian solve. GPTAQ and embeddings have separate loops; their differences are described below.
true_sequential=True is the default. Model definitions organize a layer into subsets of modules. The looper quantizes a subset, replays its quantized activations, then uses those updated activations to calibrate later subsets in the layer.
With true_sequential=False, ModuleLooper combines the subsets into a single subset. Later modules therefore do not receive the same within-layer sequential replay. This is separate from GPTQ's per-column loop and its blocksize.
The source explicitly warns that disabling sequential replay can produce lower but misleading reconstruction losses and worse post-quantization behavior. Leave it enabled unless an experiment deliberately studies that change, and evaluate the resulting model rather than comparing only logged layer losses.
GPTQConfig and RTNConfig inherit PreProcessorConfig, which inherits BaseQuantizeConfig. These are the central fields for this page; device scheduling, adapters, telemetry, and other shared controls are documented in QuantizeConfig Reference.
| Field | Declared default | Meaning / constraints |
|---|---|---|
bits |
4 |
Integer bit widths listed by the base config are 2, 3, 4, 5, 6, 7, 8; available layouts and kernels impose additional restrictions |
group_size |
128 |
Positive input-column group size, or -1 for a full-row group |
sym |
True |
Symmetric range selection; False enables affine asymmetric scale/zero selection |
desc_act |
None |
Resolves to False for both concrete configs |
true_sequential |
True |
Within-layer sequential calibration replay; meaningful for the calibration-driven lifecycle |
method |
METHOD.GPTQ |
Family identifier, including RTN's GPTQ-compatible weight-only configuration |
format |
FORMAT.GPTQ |
Exported checkpoint representation, not algorithm selection |
mse |
MSEConfig() |
Shrink-grid exponent and scratch budgets; a numeric value remains accepted as the legacy exponent form |
dynamic |
None |
Per-module overrides and negative skip rules |
fallback |
Fallback() |
Insufficient-calibration policy, defaulting to RTN below a "0.5%" threshold |
lm_head |
False |
Whether the output head is selected for quantization |
activation |
None |
Explicit opt-in input-activation policy; omitted for ordinary weight-only GPTQ |
pack_dtype |
torch.int32 |
Integer storage word type; not the model activation dtype |
pack_impl |
"auto" |
Packing hint; also accepts "original", "gpu", and "cpu". AUTO honors a resolved CPU target even when a GPU is visible. See packer selection. |
offload_to_disk |
True |
Offload completed module storage during quantization |
offload_to_disk_path |
None |
Optional offload directory |
device |
None |
Device selection, normalized by loading |
rotation |
None |
Optional rotation; choices are "hadamard" and "random"
|
preprocessors |
[] |
Preprocessor configurations |
smoother, smooth
|
None |
Inherited fields; the calibrated solve rejects active smoothers. Use fallback=Fallback(smooth=...) for fallback-only smoothing, or an RTNConfig for whole-model RTN. |
| Field | Declared default | Resolved default / meaning |
|---|---|---|
damp_percent |
None |
0.05 for GPTQ |
damp_auto_increment |
None |
0.01 for GPTQ |
act_group_aware |
None |
True for GPTQ, unless classic act-order disables it |
static_groups |
False |
Precompute group parameters before the column loop |
gptaq |
None |
A GPTAQConfig enables GPTAQ |
foem |
None |
Separate FOEM configuration; not GPTAQ and not enabled by default |
g2ptq |
None |
Opt-in G2PTQ block-gradient solver |
jointq |
None |
Opt-in JointQ scale-and-integer refinement |
moequant |
None |
Opt-in MoEQuant calibration for routed-expert affinity weighting, self-sampled calibration, or both |
mock_quantization |
False |
Simplified computation for loading/lifecycle validation; not a quality configuration |
hessian |
HessianConfig() |
Gram accumulation, staging, chunking, and shared-input deduplication controls |
GPTQConfig.allowed_quant_methods(self) returns (METHOD.GPTQ,). QuantizeConfig(...) is a backward-compatible factory that dispatches to concrete config classes; explicit GPTQConfig and RTNConfig make the desired lifecycle clearer.
GPTQ and QQQ calibration on Llama 3 default to excluding BOS attention sinks from their statistics. The Llama definition identifies these checkpoints by their "llama3" RoPE type. The default reduces the influence of the large BOS activation on the first decoder block's down-projection Hessian. See the calibration measurements.
Set an explicit policy on the calibration call to compare both settings after loading the source model with this config:
from gptqmodel import CalibrationConfig
from gptqmodel.quantization import GPTQConfig
qcfg = GPTQConfig(bits=4, group_size=128)
# After loading model with quantize_config=qcfg:
# model.quantize(CalibrationConfig(dataset=calibration, exclude_attention_sinks=True))
# Reload the source model before comparing with exclude_attention_sinks=False.CalibrationConfig.exclude_attention_sinks=None defers to the model definition. It resolves to False for staged GSQ, weight-only runs, and models or methods without an opt-in. An explicit True requests exclusion for a supported method, and False retains BOS even on Llama 3. When exclusion is enabled, every attended token matching tokenizer.bos_token_id is omitted from supported calibration statistics, including BOS at document boundaries inside a concatenated window and BOS at the first real position of a left-padded row. Token totals and fallback thresholds use the retained rows. If the tokenizer has no BOS ID, calibration logs a warning and keeps those statistics unfiltered.
The shared policy covers GPTQ, GPTAQ/FOEM Hessians and cross moments, QQQ, MACaQ, EXL3 capture, and AWQ activation features/search loss. Forward replay still runs all tokens so later tokens can attend to BOS; padding-only masks remain in use for MoE routing evidence and NVFP4 activation ranges. Natively routed expert rows without sequence alignment retain their sink rows; aligned all-expert bypass rows can be filtered. VLM batches whose expanded layer sequence cannot be aligned with input_ids retain the default mask. Compare held-out quality: exclusion can help or hurt depending on the model and method.
Migrate old GPTQConfig(exclude_attention_sinks=...) calls to CalibrationConfig.exclude_attention_sinks. The removed constructor field raises TypeError, and a dynamic override raises ValueError. VPTQ, Paro, and staged GPTQ GSQ reject True. Weight-only runs warn that an explicit True has no effect. EoRA binds a copy of the calibration policy with sink exclusion disabled. Calibrated runs record meta.calibration_exclude_attention_sinks=True when the resolved policy is enabled and omit the key when disabled. BOS positions are captured before the dataset is released. See the shared calibration contract.
Ordinary GPTQ checks coverage before materializing/inverting the Hessian. This is a per-module policy, not whole-model RTN selection and not the same as recovery from a failed Cholesky factorization.
Fallback field |
Dataclass default | Meaning |
|---|---|---|
strategy |
FallbackStrategy.RTN |
Weight-only rounding strategy when coverage is insufficient |
threshold |
"0.5%" |
Trigger when observed activation rows/tokens are strictly below this fraction of the processor's total calibration-token count |
smooth |
None |
Optional smoothing/range search for the fallback solve |
| Threshold configuration | Behavior |
|---|---|
fallback=None |
Disable the configured low-sample fallback and its NaN-to-mock retry policy; zero-sample modules still force RTN |
Fallback(threshold=True) |
Trigger only for zero observed samples; resolves to 1e-9 and uses strict <
|
Fallback(threshold=100) |
Trigger for fewer than 100 observed samples |
Fallback(threshold="0.5%") |
Compare against 0.005 * expected_total_samples; if the expected total is unavailable or zero, the resolver uses 1.0 as its base |
Fallback(threshold=0) or Fallback(threshold=False)
|
Disable the threshold, not the zero-sample RTN safety guard |
fallback={"strategy": "rtn"} |
Dictionary normalization uses the same "0.5%" threshold as Fallback() at this source pin; set another threshold explicitly when needed |
Thresholds must be finite and nonnegative. Malformed strings, negative values, NaN, and infinity raise at config construction, including in per-module fallback rules.
FallbackStrategy defines the string values "rtn", "midpoint", "mean", "median", and "stdclip". The non-RTN strategies select weight ranges, including a three-standard-deviation interval for stdclip. With sym=True, GPTQ centers the selected interval around zero using the larger absolute endpoint as its radius. This preserves the selected clipping radius while keeping the symmetric zero point fixed. A SmoothMSE fallback takes the MSE-search branch before strategy-specific range selection when the effective group size meets its threshold.
from gptqmodel.quantization import GPTQConfig
from gptqmodel.quantization.config import Fallback, FallbackStrategy
qcfg = GPTQConfig(
fallback=Fallback(strategy=FallbackStrategy.RTN, threshold="0.5%"),
)The early fallback returns a loss string of the form fallback(rtn): ... for RTN, not a GPTQ reconstruction loss. Ordinary GPTQ forces RTN when nsamples == 0, even with fallback=None, a disabled threshold, or another configured strategy: a zero Hessian must not classify every weight column as dead and produce an all-zero module. The warning names the affected module.
GPTAQ and FOEM also apply the configured absolute or percentage threshold before the Hessian solve. Percentage thresholds use the total calibration token count as the denominator, including when only a small fraction reaches a routed expert. A module with positive coverage strictly below the threshold uses the configured fallback strategy. Zero samples or a missing Hessian still trigger their separate guard, even if the threshold is disabled.
When every damping/diagonal-floor attempt fails, ordinary GPTQ continues through its no-Hessian rounding loop; GPTAQ and FOEM call _rtn_fallback_after_hessian_failure(), which delegates to _fallback_quantize(RTN). They do not run ordinary GPTQ's NaN-to-mock retry. Completion through any fallback is not evidence of downstream accuracy. See the GPTAQ solver and FOEM solver.
Ordinary GPTQ's NaN-to-mock retry captures the Hessian diagonal before activation ordering, then rebuilds it in natural column order for the retry. Reapplying desc_act or act_group_aware therefore preserves the primary solve's column/group ordering instead of silently losing it.
GPTAQConfig is a nested algorithm configuration, not a replacement for GPTQConfig:
@dataclass
class GPTAQConfig:
alpha: float = field(default=0.25)
device: Union[str, torch.device] = field(default="auto")| Field | Default | Meaning |
|---|---|---|
alpha |
0.25 |
Multiplier on the activation-difference correction; validated as numeric |
device |
"auto" |
Storage placement for captured native inputs; a non-empty string or torch.device
|
NativeProcessor resolves "auto" to the project's DEVICE_1, and "cpu" to CPU. This is native-reference storage placement, not a new checkpoint format. Extra native inputs and cross-term state increase memory requirements compared with ordinary GPTQ.
RTNConfig adds no Hessian, GPTAQ, or damping fields. It inherits the shared and preprocessor fields, declares method=METHOD.GPTQ and format=FORMAT.GPTQ, resolves desc_act to False, and returns True from uses_weight_only_lifecycle().
Do not select RTN with a nonexistent METHOD.RTN enum member. Use RTNConfig(...). Its GPTQ family identifier permits GPTQ-style export; its concrete class selects the weight-only path.
| Enum | String value | Interpretation |
|---|---|---|
METHOD.GPTQ |
"gptq" |
GPTQ family identifier |
FORMAT.GPTQ |
"gptq" |
Legacy/continuous GPTQ checkpoint layout |
FORMAT.GPTQ_V2 |
"gptq_v2" |
Continuous layout with corrected zero semantics |
FORMAT.GPTQ_P |
"gptq_p" |
Planar GPTQ layout, using v2 zero semantics on disk |
FORMAT.MARLIN |
"marlin" |
Legacy format enum; not the recommended format for new quantization |
FORMAT.BITBLAS |
"bitblas" |
BitBLAS export representation |
FORMAT.GEMM |
"gemm" |
AWQ GEMM representation, also listed for RTN export |
FORMAT.GEMV |
"gemv" |
AWQ GEMV representation, also listed for RTN export |
FORMAT.GEMV_FAST |
"gemv_fast" |
AWQ GEMV-fast representation, also listed for RTN export |
FORMAT.LLM_AWQ |
"llm-awq" |
LLM-AWQ representation, also listed for RTN export |
GPTQ_EXPORT_FORMATS lists GPTQ, GPTQ_V2, GPTQ_P, MARLIN, and BITBLAS. RTN_EXPORT_FORMATS lists GPTQ, GPTQ_V2, GPTQ_P, GEMM, GEMV, GEMV_FAST, and LLM_AWQ. A listed format does not guarantee that every bit width, group size, device, or backend supports it. In particular, BaseQModel.quantize() explicitly rejects new quantization into FORMAT.MARLIN and recommends FORMAT.GPTQ, which can use a Marlin inference kernel.
For the GPTQ family, 5-, 6-, and 7-bit layers require the planar layout. Configuration automatically changes a requested FORMAT.GPTQ or FORMAT.GPTQ_V2 to FORMAT.GPTQ_P if the base bit width or a non-negative dynamic override uses one of those widths. Do not infer that the continuous layouts support every integer listed in the base bits field.
The model-level method is declared in gptqmodel/models/base.py as follows (comments and body omitted):
def quantize(
self,
calibration: Optional[CalibrationConfig] = None,
*,
tokenizer: Optional[PreTrainedTokenizerBase] = None,
backend: Optional[Backend] = BACKEND.AUTO,
adapter: Adapter = None,
embed_quant_config: Optional[Union[QuantizeEmbedConfig, QuantizeEmbed]] = None,
embed_quant_mode: Optional[QuantizeEmbed] = None,
checkpoint: Optional["CheckpointConfig"] = None,
fuse: Optional[bool] = None,
) -> Dict[str, List[Dict[str, str]]]:
...Pass samples (raw-text collections or tokenized inputs) in CalibrationConfig.dataset. CalibrationConfig.sort supports "asc", "desc", "shuffle", and None; its default is "desc". Bare datasets and removed calibration keywords raise TypeError; see the calibration policy and migration table. A model definition that disables batch quantization can override the requested batch size. calibration=None is allowed by the signature so native weight-only configurations such as RTNConfig can use the same method; GPTQ and GPTAQ still require calibration at runtime.
The low-level task class in gptqmodel/quantization/gptq.py has these signatures (method declarations shown without bodies):
def __init__(self, module: nn.Module, qcfg: Optional[QuantizeConfig] = None, region_timer=None):
...
def quantize(
self,
blocksize=128,
):
...
def hf_quantize(
self,
blocksize=128,
percdamp=0.01,
damp_auto_increment=0.0015,
group_size=-1,
actorder=False,
static_groups=False,
act_group_aware: Optional[bool] = None,
):
...hf_quantize() copies its arguments onto the task configuration, resolves ordering, calls quantize(), assigns Q to the module weights, and returns (scale, zero, g_idx, duration, avg_loss, damp_percent). fasterquant() delegates to this compatibility path, without exposing its final act_group_aware parameter. Do not confuse the wrapper's 0.01/0.0015 damping defaults with the normalized GPTQConfig defaults 0.05/0.01. Its default group_size=-1 passes through the same _resolve_activation_ordering rule, so an existing group-aware ordering is disabled with a warning for full-row use.
The direct task quantize() result is:
(Q, scale, zero, g_idx, duration, avg_loss, damp, nsamples)Q is a dequantized representation of the rounded weights for module assignment and packing; it is not already the packed checkpoint qweight. GPTAQ and RTN return the corresponding eight-part payload so downstream packing can share the same interface.
GPTQ handles nn.Linear, Transformers Conv1D, nn.Conv1d, nn.Conv2d, and a dedicated nn.Embedding path. Linear-like inputs become two-dimensional rows. Convolution inputs are unfolded into receptive-field rows; Transformers Conv1D weights use the corresponding transposed weight convention. Tensor-parallel padding is handled before quantization where required.
GPTQ.add_batch(inp, out, batch_index=None) updates per-device Hessian partials and sample accounting. GPTQ, GPTAQ, and FOEM capture module inputs without copying the forward output. For eligible GPTQ batches, the FP32 Gram product accumulates directly into the running device partial with addmm_, avoiding a temporary Hessian-sized product. The chunked path can also accumulate directly into one FP32 square matrix. materialize_global_hessian() merges device partials in stable device order and applies the 2 / total_samples normalization. Hessian capture implementation
Materialization is cumulative: adding batches after a previous materialization retains that finalized Hessian, reweights it by the previous/new total sample counts, and adds the new partials at 2 / total_samples. Repeated finalization with no new batches does not count the same samples again. The copied-Hessian path retains the accumulated sample count too. This matters for incremental capture and shared Hessian consumers; finalizing once is not a reset operation.
snapshot_hessian() merges finalized and pending samples into an owned tensor without consuming/resetting live statistics or aliasing the task's Hessian. Reusing a Hessian after changing the target device moves the returned/consumed matrix to that target rather than leaving an inverse or solve on the old device. Convolution capture reproduces the module's actual padding, including supported nonzero modes and same/valid semantics. GPTQ and QQQ preserve Conv2d's height/width padding order when unfolding rows, including unequal per-axis padding, rectangular same kernels, and grouped convolutions.
When capture uses staged chunks, dtype conversion happens directly into the reusable staging and FP32 workspaces instead of allocating additional cast copies.
The processor's forward hook is responsible for supplying usable inputs. Masked inputs preserve per-sample boundaries where required, and embeddings have their own handling rather than being treated as ordinary Linear input activations.
For GPTAQ and positive-alpha FOEM, native capture splits [B, S, H] or flattened [B*S, H] inputs using the matching [B, S] keep mask into one native entry per kept sample, matching each later add_batch call. All-masked samples are skipped on both sides. This also covers flattened shared-expert inputs such as Qwen2-MoE and OPT feed-forward projections with calibration batch_size > 1. Sibling-sharing cache slots are released across all capture threads during processing and finalization, so source activations and masks are not retained after the layer or run. See native calibration batch split.
Fallback grids respect the packing contract: symmetric fallback strategies retain the fixed midpoint zero point required by symmetric kernels, while asymmetric SmoothMSE/centered ranges include zero so every exported zero point remains in [0, maxq]. These fixes keep the scored/reconstructed grid consistent with packed inference; they do not change the selected fallback policy. For 3-bit GPTQ, both matrix dimensions must be divisible by 32 and are checked before calibration; see packing compatibility.
Before the main loop, GPTQ:
- Checks whether observed calibration is below the configured fallback threshold.
- If a low-sample fallback is selected, releases Hessian partials before quantizing. With
Fallback(smooth=SmoothMSE())and captured samples, GPTQ first reduces the partials to a per-input-channel diagonal for the shrink search and prefers that live diagonal over an earlier finalized Hessian. - Otherwise finalizes the Hessian and clones weights to its compute device.
- Replaces zero Hessian diagonal entries with the mean of the live entries and zeroes the corresponding weight columns before fitting the initial per-channel grid. Damping therefore uses the live diagonal mean, and unobserved weight columns cannot set the scale for live columns.
- Precomputes static-group quantizers when requested.
- Applies classic or group-aware ordering.
- Computes or reuses the inverse factor and initializes output/loss buffers.
When GPTQ enters the lightweight fallback with a finalized Hessian, it extracts the per-channel diagonal if the SmoothMSE search needs it and releases the full Hessian before cloning the weights and allocating the output buffer. See the fallback implementation.
The implementation has targeted allocation-failure recovery around Hessian permutation, inversion, and the subsequent block-update pass that moves the affected work to CPU and logs a CPU fallback. CUDA-namespace checks also cover HIP-backed ROCm execution. This does not make CPU and GPU memory interchangeable: a dense Hessian still requires storage and factorization workspace on whichever device performs that stage.
For both desc_act and act_group_aware, permutation first gathers the Hessian, then the weight columns into temporary results, and commits them only after both gathers succeed. If a CUDA-namespace Hessian permutation raises an out-of-memory RuntimeError (including HIP-backed ROCm execution), CPU recovery starts from the original, unpermuted weights and Hessian and applies the ordering exactly once to each. This fixes incorrect quantization after a failed Hessian gather previously left the weights already permuted and the fallback permuted them a second time. Recovery disables the shared Hessian cache and refits quantizer parameters on the CPU-ordered weights; non-OOM errors and errors on other device types are re-raised. No new flag is required. See the GPTQ solver and permutation-OOM regression tests.
The standard quantizer in gptqmodel/quantization/quantizer.py exposes:
def __init__(self, qcfg: BaseQuantizeConfig, shape=1, name: str=None):
...
def configure(
self,
perchannel=False,
grid=100,
maxshrink=0.8,
trits=False,
bits: int | str | None = None,
sym: bool | None = None,
):
...
def find_params(
self,
x,
weight=False,
*,
scale_min: float | torch.Tensor = SCALE_STORAGE_FLOOR,
value_limit: float | torch.Tensor | None = None,
):
...The GPTQ processor calls configure(perchannel=True). Thus weight ranges are fitted per output channel, with group boundaries selecting the input-column subset. This differs from constructing a raw Quantizer and leaving its perchannel=False default unchanged.
For the standard affine path, with maxq = 2**bits - 1, quantization is:
q = torch.clamp(torch.round(x / scale) + zero, 0, maxq)
x_hat = scale * (q - zero)find_params() includes zero in the observed range. With sym=True, it always fits [-amax, +amax], where amax = max(abs(xmin), xmax), including groups containing only nonnegative values, and uses the fixed midpoint zero point. This repairs excessive positive saturation from fitting [0, xmax] against that midpoint; integer endpoint asymmetry remains part of the grid. Asymmetric quantization rounds -xmin / scale. All-zero ranges receive finite sentinel ranges. _replace_zero_scale() prevents division by zero and repairs undefined zero points in affected lanes. The corresponding symmetric fitting correction also applies to QQQ and the MLX RTN/GPTAQ/FOEM/QQQ implementations; no config default changes.
For FP16 and BF16 weights, Torch GPTQ, GPTAQ, and FOEM restrict the selected integer codes to values whose reconstructions fit the source weight dtype. For example, with symmetric INT4 and an FP16 group peak of 61440, code 0 would reconstruct to -65536. The solver selects code 1, which reconstructs to -57344 in FP16. Eager GPTQ and its fused CUDA block update enforce the same bounds, keeping calibration replay and packing on the same grid. A smoothed refit accounts for the scale factor reapplied after quantization. GPTQ finite reconstruction range
When mse.norm > 0, the shrink grid evaluates smaller ranges. With the raw quantizer defaults, candidates are based on p = 1 - i / grid for i in range(int(maxshrink * grid)). The search recomputes the scale and zero point for each candidate and ranks them by the sum of powered reconstruction errors. The exponent can be fractional, such as 2.4.
The initial affine fit, affine MSE candidates, and GPTQ's affine weight-only fallback grids divide each endpoint by maxq before subtracting when the difference between two finite endpoints would overflow. For finite spans they use (xmax - xmin) / maxq. The packed FP16 scale limits still apply. Shared affine scale fit
Before raising abs(x_hat - x) to norm, the scorer divides each residual by a common factor for that row, normally a power of two derived from the largest candidate step. Using the same factor for every candidate preserves the objective's ordering in exact arithmetic and reduces false zero-score ties from underflow on small-magnitude rows with a high exponent. Very large exponents can still produce underflow or overflow. See MSE objective normalization.
Ordinary GPTQ fits a full-projection grid for the ungrouped solve (group_size=-1). Grouped solves fit their own scales and zeros: static groups fit before the block pass, while dynamic groups refit at their group boundaries. Neither grouped solve pays for a whole-projection shrink search that it won't use.
The vectorized implementation preserves sequential candidate order and first-minimum tie-breaking, treats NaN objectives as non-winning, and preserves reduction order for transposed views. Scratch budgeting chunks the candidate evaluation; it is not a different codebook or an additional inference step. The asymmetric 2-bit implementation additionally searches an adjacent affine zero-point orientation.
The block solve needs the inverse factor, not the full FP32 calibration Hessian. After successful factoring, ordinary GPTQ releases the Hessian before entering this loop, including when desc_act or act_group_aware reordered it. GPTAQ and FOEM likewise release their full Hessian after factoring; the block pass keeps the factor and any feedback terms it still needs. This reduces overlapping live storage without changing the solve or removing the need to allocate the Hessian during capture. Hessian lifetime
In the ordinary non-mock path, GPTQ iterates blocks, normally 128 input columns at a time:
- Clone the current block into
W1and take output/loss slices. - At each column, select a static-group quantizer or refresh parameters at a dynamic group boundary. Dynamic parameters are fitted from the current outer working matrix
W, not refitted from the locally correctedW1after every column. - Quantize the column with
self.quantizer.quantize(w.unsqueeze(1)).flatten(). - Save the rounded column and its factor-normalized error.
- Correct the remaining columns inside
W1using the inverse-factor row. - Divide block loss by two and update columns after the block using
Err1.matmul(Hinv[i1:i2, i2:]). - Release block temporaries.
Finally, GPTQ restores ordering and module shape, builds g_idx, concatenates scales/zeros, and returns the payload. With a valid inverse and nonzero samples, average loss is the accumulated block-loss sum divided by nsamples. GPTQ, GPTAQ, and FOEM reduce each block’s loss into a scalar on the solve device, so the loss workspace is bounded by the block width. A no-inverse path omits Hessian corrections; its work chunks can align to positive group boundaries.
This separation between columnwise quantization and blockwise matrix updates is the core GPTQ acceleration structure. group_size, blocksize, calibration batch size, and Hessian accumulation chunk size control different parts of the algorithm.
The Torch GPTQ and QQQ solvers apply the trailing-column update in output-row tiles when the product would exceed 256 MiB. This reduces peak temporary memory for large projections, notably when quantizing the vocabulary head with GPTQ's lm_head=True. It bounds the product, not the full solve or the Hessian; there is no new config knob.
If the block pass runs out of memory on a CUDA-namespace device (including ROCm), its CPU retry starts from the original pre-pass weight, reapplies dead-column masking and activation ordering, and resets partial output/quantizer state. It does not continue from weights already modified by error propagation in a failed GPU pass. Caller-supplied working weights retain a host pre-pass copy; ordinary module weights can be reconstructed from their source. Static-group scales/zeros move to CPU for permutation, inverse, and block-pass recovery as needed. This preserves group lookup and avoids mixed-device metadata; it still requires host workspace. See the solver.
gptqmodel/quantization/gptq_cuda.py wraps a JIT-loaded Torch operator. The callable interface is:
def block_update_available() -> bool:
...
def gptq_block_update(
work: torch.Tensor,
hinv: torch.Tensor,
scale: torch.Tensor,
zero: torch.Tensor,
column_group: torch.Tensor,
quantized: torch.Tensor,
errors: torch.Tensor,
losses: torch.Tensor,
maxq: int,
) -> None:
...The wrapper uses gptqmodel_ext/gptq_block/gptq_block.cpp and gptq_block.cu. block_update_available() builds/loads on first use and returns False if CUDA compilation fails. The ordinary PyTorch loop remains the alternative.
| Dispatch condition | Requirement |
|---|---|
| Hessian factor | Must exist |
| Device | Working weights on a CUDA device |
| Block size | Requested blocksize == 128; only full 128-column blocks use the native update |
| Bit width | Integer 2–8, with the expected (1 << bits) - 1 quantizer bound |
| Quantizer | Exactly the standard Quantizer type |
| Mock mode | Disabled |
| Kernel policy |
KernelConfig.gptq_fused_block_update is True (default) |
| Extension |
block_update_available() succeeds |
The operator checks float32 work/factor/scale/zero/output tensors on the same CUDA device, a 128-by-128 factor block, 128 contiguous work columns, and CUDA int32 column-group indices. Python prepares group parameters before launch, including blocks that cross groups. Short tail blocks stay in the eager loop. The update to later blocks remains outside the fused within-block operator.
| Control | Purpose |
|---|---|
KernelConfig.gptq_fused_block_update=False |
Disable the optional native GPTQ update for diagnosis |
GPTQMODEL_GPTQ_BLOCK_BUILD_ROOT |
Override this extension's build directory |
GPTQMODEL_GPTQ_BLOCK_FORCE_REBUILD |
Request rebuilding through the JIT extension helper |
GPTQMODEL_EXT_VERBOSE |
Extension build verbosity |
This is a quantization-time accelerator, not Marlin, ExLlama, or another inference backend. It requires a working PyTorch extension toolchain and CUDA compilation support. The .cu implementation is not a blanket guarantee of support on every ROCm build: ROCm uses PyTorch's CUDA-facing device API too, but the extension must actually build/load. Failure to load leaves the eager path available.
For diagnosis, pass kernel={"gptq_fused_block_update": False} in the quantization config. This disables the optional block update, not accelerator placement or all CUDA execution. See KernelConfig; the former environment disable switch is no longer read.
GPU Hessian accumulation, permutation, inverse, and block-update recovery classify solver allocation errors such as CUSOLVER_STATUS_ALLOC_FAILED and HIPSOLVER_STATUS_ALLOC_FAILED as memory failures, not only messages containing “out of memory.” Eligible CUDA/HIP-runtime paths can therefore take their CPU retry. A non-positive-definite torch._C._LinAlgError remains a numerical failure and is not disguised as an allocation retry. Allocation-failure classifier.
Once Hinv exists, ordinary GPTQ releases self.H before allocating the weight-sized output/loss buffers. NaN/mock recovery retains only a natural-order diagonal snapshot when configured, then rebuilds the diagonal Hessian for a retry. If the block pass raises a classified allocation RuntimeError on a CUDA/HIP-runtime device, it retries the pass once on CPU, moving working weights and the inverse factor, refitting/resetting non-static group metadata or moving the precomputed static-group parameters. A second failure or an unrelated error propagates. Final reconstructed weights return to the original module device through safe_move_to(), even when its Hessian/compute device differed. This is automatic memory recovery, independent of the low-sample Fallback threshold; it is not an RTN substitution or a guarantee against all OOMs. See the post-inverse recovery tests.
At the pinned source, routed experts do not pair native and replayed tokens by call order: routing may change the token subset, so tasks structurally marked is_routed_expert omit the native delta and use GPTQ-style compensation. Modules with insufficient calibration coverage take the data-independent fallback instead. See the implementation.
GPTAQ subclasses GPTQ, but it keeps its own input-statistics recurrence and block loop. Its constructor takes module: NamedModule, a configuration, and the optional region timer. It consumes native inputs from module state under NATIVE_INPUTS_STATE_KEY = "native_inp".
The calibration lifecycle supplies two input streams:
| Stream | Role |
|---|---|
| Native reference | Detached inputs captured by NativeProcessor before the downstream quantized replay |
| Current/replayed input | Inputs seen during quantization after upstream changes and any active activation replay |
GPTAQ flattens all leading dimensions of Linear and Transformers Conv1D inputs, including 4-D multi-head latent attention (MLA) captures. When native correction is active, it flattens the matching native inputs the same way. It converts the aligned matrices to FP32 and maintains both H and dXXT. In its channel-by-token representation, the updates include inp @ inp.T and (native_inp - inp) @ inp.T. Its recurrence is normalized by calibration requests, while nsamples tracks activation columns/tokens.
GPTQ, GPTAQ, and FOEM unfold nn.Conv1d and nn.Conv2d activations using the layer's stride, dilation, and effective padding, including nonzero padding modes and asymmetric padding="same" splits. For grouped convolutions, each group contributes separate patch rows, so the column count matches one weight row. GPTAQ and FOEM use the same patches for the native-input correction and use each column's pre-update weight when applying that correction to later blocks. For GPTAQ and FOEM, tensor-parallel channel padding extends both replayed and native inputs with zeros before accumulation. BF16 asymmetric solves keep exact FP32 reconstruction for packing when BF16 rounding would change the selected codes. GPTAQ capture and solve · FOEM capture and solve
For GPTAQ and FOEM, the finalized Hessian's device is the solve device. Multi-GPU task reassignment moves dXXT alongside H and any cloned weights; the solvers also align their companion matrix and pre-cloned weights to H.device before quantization. This prevents a device-mismatch failure when calibration ran on one device but the solve moved elsewhere, including the single-device-accumulation fast path. The native-reference device setting is not a separate destination for the solve's correction matrix.
For a module using aligned native inputs, after neutralization, ordering, and inverse-factor computation, it forms the correction:
P = self.qcfg.gptaq.alpha * ((self.dXXT @ Hinv.T).triu(diagonal=1)) @ HinvThe GPTAQ column loop uses both Hessian compensation and this native-versus-current activation correction. _token_normalized_avg_loss() converts its batch-normalized loss sum into GPTQ-compatible token-normalized reporting. A prepared task must have non-None qcfg.gptaq; the loop checks this after computing the inverse and raises ValueError if it is absent. Constructing a task without its required native cache can fail earlier.
GPTAQ does not automatically inherit every optimization or recovery policy from GPTQ.quantize():
| Feature | GPTAQ behavior at this revision |
|---|---|
| Ordering | Implements desc_act, act_group_aware, and natural order; group-aware ordering permutes weights/Hessian/native cross-term together and restores packed group metadata |
| Input statistics | Its own float32 recurrence; does not use HessianConfig chunked Gram accumulation |
| Shared-input reuse | Compatible explicit groups can share capture within the same quantizer kind; followers copy both H and dXXT. Plain-GPTQ inverse-factor caching remains separate |
| Fused CUDA block update | Not used by the GPTAQ loop |
| Low-sample and NaN recovery | Coverage strictly below the configured absolute or percentage threshold uses the selected fallback. Zero samples and a missing Hessian have a separate guard. A NaN average loss raises ValueError. |
| Inverse failure | A classified CUDA/ROCm allocation failure during the inverse or native-delta product retries once on CPU; a missing factor selects shared data-independent RTN before the block loop |
| Input reshape | Flattens Linear/Transformers Conv1D inputs and unfolds nn.Conv1d/nn.Conv2d patches, including grouped convolutions; this does not imply embedding support |
GPTAQ and FOEM truncate tensor-parallel padding before reshaping weights and exporting scale/zero/group metadata. FOEM counts calibration tokens rather than forward requests for Hessian normalization and loss reporting; its native MLX shortcut is not selected for group-aware ordering or padded projections. These corrections do not add chunked/shared Hessian processing to either solver.
Both fit the initial per-channel grid after zeroing calibration-dead columns. FOEM skips empty routed batches before updating device statistics, so padding-only batches contribute neither tokens nor a division by zero.
For GPTAQ/FOEM inverse-stage CPU recovery, working weights, Hessian, native-delta state, ordering permutations, and static-group quantizers move together. The solver refits quantizer parameters on CPU, then returns reconstructed weights to the original module device. This includes cuSOLVER/hipSOLVER allocation failures and allocation failure in the native-delta product, but not arbitrary solver errors or a general block-loop OOM retry. Host workspace is still required. See the GPTAQ solver and FOEM solver.
The alpha-zero MLX FOEM shortcut applies beta to the first column of each subsequent group after its trailing Hessian update, matching Torch's block-boundary correction. With beta=0 that additional correction is a no-op; this does not broaden MLX eligibility. See MLX solver contracts.
A top-level or per-module dynamic rule that enables GPTAQ (including alpha=0) or FOEM with alpha > 0 requests the model-wide native capture pass. The matching per-module configuration still determines which solver runs on each projection. Quantization run plan
GPTAQ uses alpha to scale the replay-drift correction. Activation precision and Hessian damping have separate settings. Include GPTAQ's extra native-input cache and cross-term matrix in memory planning. The GB10 W4A4 campaign dropped GPTAQ from accuracy qualification because of its memory requirements. The guarded checkpoint-only experiment remains available.
gptqmodel/quantization/rtn.py defines:
def __init__(self, module: nn.Module, qcfg: RTNConfig):
...
def quantize(self):
...quantize() runs under torch.inference_mode(). The task supports nn.Linear, nn.Conv1d, nn.Conv2d, and Transformers Conv1D. It clones/reshapes weights, applies tensor-parallel padding if required, determines the effective group size, fits parameters per group, and directly rounds/dequantizes the weights. It never enters GPTQ's activation/Hessian lifecycle. If the subtraction of finite affine range endpoints overflows, the grid fit divides the endpoints before subtracting to preserve a representable scale.
Optional smoothing can change range fitting. A supplied SmoothMSE() defaults to steps=32 and maxshrink=0.8, so the smallest candidate retains 80% of the range. mse_optimal_quant() scores both clamp(maxshrink, 1e-3, 1.0) and the unshrunk multiplier 1.0, then probes the interior with a logarithmic ternary search and refines three nearby candidates. RTN weights squared error by each element's absolute weight plus the row's mean absolute weight. A narrower range wins only when it improves this weighted error over the unshrunk grid. The reported loss still uses mean absolute error (rtn: {mean_abs_err:.7f}); damping is 0.0 and sample count is 0 because no calibration inputs were captured.
Torch RTN bounds the integer codes so the reconstructed weight fits the finite range of the source floating-point dtype. With symmetric INT4 and an FP16 group peak of 61440, the lowest code would reconstruct to -65536 and become negative infinity on narrowing. The bound selects the next code, which reconstructs to -57344 after narrowing. The ordinary MSE shrink grid and the SmoothMSE search also apply the bound when scoring candidates. Row/column smoothing accounts for the factor restored after quantization. Finite reconstruction range
RTN skips unsupported placeholders in definitions that allow optional layers. For example, Nemotron-H can expose mixer.fc1_latent_proj as an nn.Identity when moe_latent_size is unset. RTN leaves that placeholder in place and continues quantizing the supported projections. A definition with layer_modules_strict=True still raises a missing-layer ValueError. See the weight-only looper and Nemotron-H definition.
RTN has a separate MLX quantization fast path:
| Eligibility | Required value |
|---|---|
| OS / architecture | Darwin / arm64 |
| Dependency |
mlx.core imports successfully |
| Weight device | CPU or MPS |
| Weight shape / size | Two-dimensional, at least 256 * 1024 elements |
| Smoothing | None |
| Bits | Integer 2–8 |
| Group size |
-1 or positive |
The MLX path returns quantized weights, scales, and zeros through DLPack. Otherwise RTN uses its Torch implementation. This is an Apple Silicon quantization optimization, not an MLX requirement for all RTN runs and not a promise that every resulting checkpoint has an MLX inference kernel. See MLX Apple Silicon.
For integer weight quantization, Quantizer.find_params(..., weight=True) bounds nonnegative scales at 2**-24, the smallest positive FP16 subnormal, before computing integer codes and affine zero points. MSE shrink candidates use the same bound before scoring. Near-dead groups, including scales that underflow to zero during arithmetic, therefore get a representable weight grid. Activation ranges and ternary endpoints retain their own semantics; exact zero ranges still use the sentinel-range handling above.
GPTQ fallback strategies and standalone RTN follow this storage contract too. SmoothMSE uses the 2**-24 floor during candidate selection and reconstruction. With SmoothRowCol(axis="row"), Torch RTN and GPTQ's RTN fallback divide the scale floor and any reconstruction cap by each row's smoothing factor before fitting. Each adjusted limit applies only to its own row. The MIDPOINT, MEAN, MEDIAN, and STDCLIP fallbacks also apply both limits in the smoothed domain so restored weights stay within the source dtype's finite range. Weight-grid fit limits · Quantization scale storage
The shared GPTQ PackableQuantLinear packers store scales as FP16, even when source weights or quantization arithmetic use BF16/FP32. pack_block(), pack_gpu(), and pack_original() call _scales_for_storage() before registering that buffer. Packing raises ValueError if a source scale is nonfinite, a finite scale becomes nonfinite in FP16, or a nonzero scale rounds to zero. The error names the tensor (for example, layer.q_proj.scales) and reports counts for source nonfinite, cast overflow, and cast underflow, plus the largest finite offending magnitude when available.
The guard checks the actual cast result, not a simple comparison against FP16's largest finite value:
| FP32 source scale | FP16 result | Packing behavior |
|---|---|---|
65504 or 65505
|
65504 |
Accepted; ordinary finite FP16 rounding is allowed |
65520 |
Infinity | Rejected as cast overflow; the preceding FP32 value still rounds to 65504
|
2**-25 |
Zero | Rejected as cast underflow; the next higher FP32 value rounds to the smallest FP16 subnormal, 2**-24
|
| Exact zero | Zero | Not rejected by this guard; the quantizer's _replace_zero_scale() separately handles zero scales before packing |
This is a checkpoint-representation limit, not a calibration-memory or inference-backend error. The packers do not clamp invalid stored scales: codes computed from the source scales would no longer match them. A wider source/model dtype does not widen these FP16 checkpoint buffers. Inspect the named module's weights and scale range before retrying, and do not patch the saved scales independently of their packed codes. This contract is specific to these shared GPTQ packers; Torch AWQ has its own source-precision storage behavior. See the source scale-storage guide.
The normal model API uses GPTQProcessor, not direct user-managed Hessians.
| Phase | Implementation behavior |
|---|---|
| Per-module configuration |
clone_gptq_config_for_module() deep-copies the config and applies supported dynamic overrides, including bits, group size, Hessian settings, and ADMM-Q solver settings
|
| Task selection |
preprocess() selects GPTAQ, G2PTQ, FOEM, ADMMQ, or JointQ according to the effective config, with GPTQ as the default |
| Quantizer setup | Configures each task quantizer with perchannel=True
|
| Capture |
pre_process_fwd_hook() routes activations to add_batch(), with masking/per-sample and embedding handling |
| Shared-input reuse | Compatible explicit shared-input groups can elect a Hessian leader; followers adopt copied Hessian data and can reuse compatible inverse factors |
| Solve |
process() calls g.quantize(), records timing/loss/sample/damping information, moves scale/zero/group payloads to CPU, and assigns rounded weights to the module |
| Pack |
submodule_finalize() creates the runtime quantized module and calls pack_module(...)
|
| Finish | Marks the model quantized and records METHOD.GPTQ or preserves METHOD.ADMMQ for ADMM-Q |
Shared-input deduplication through HessianConfig.dedup_shared_inputs=True requires an explicit model-plan group and matching capture signatures. GPTQ and ADMM-Q use the same signature, including Hessian settings. GPTAQ and FOEM each have their own signature, require matching native-delta modes, and copy dXXT alongside H. JointQ uses its own signature and shares only H. Attention-sink exclusion is shared by the calibration run. QQQ, VPTQ, MACaQ and eligible plain-GPTQ EXL3 captures use the same explicit model-plan leader election. QQQ GSQ and EXL3 w3 aliases already sharing state are excluded. Set dedup_shared_inputs=False to collect independently where the method exposes HessianConfig. MACaQ and EXL3 always use eligible groups. See the capture signature implementation.
Sharing requires matching effective sink-row caps, not just the same configured cap: activation-order options can change whether it applies to a projection. When a follower adopts a leader's Hessian, adopt_hessian_from() synchronizes and releases deferred reduction/copy-source references for both tasks immediately after adoption. It keeps the leader's live Hessian and the follower's private copy, but no longer retains obsolete reduction partials until each task enters quantize(). This reduces transient memory overlap for shared-input groups without changing dedup_shared_inputs or the quantization result. See the GPTQ implementation.
With activation-order permutation, GPTAQ and FOEM can release the original FP32 Hessian as soon as the solver switches to the permuted copy. This removes one input-width-squared tensor from the overlap at the solver's memory peak. If the per-module solve fails or is interrupted, the processor attempts to release Hessian state before re-raising. A shared capture stays live until its last owner releases it. See quantization memory.
For GPTAQ, BaseQModel inserts a NativeProcessor before quantization processing. It captures detached inputs on the configured native-reference device and transfers the cache into module state for the GPTAQ task. With the same prepared dataset and the standard model-capture hooks, GPTAQ and FOEM reuse the first-layer capture instead of repeating the initial model forward; each processor owns its own replay state. GPTAQ and FOEM pair native inputs to replay inputs by calibration batch index, so out-of-order device completion cannot silently mix batches. Their Hessian/native-delta partials accumulate per device and reduce in stable device order before solving, weighted by batch requests for GPTAQ and tokens for FOEM. See native passes. RTN instead selects the model's weight-only lifecycle through RTNConfig.uses_weight_only_lifecycle(); it does not invoke the GPTQ calibration processor with an empty dataset.
See Looper Processors, Quantization Lifecycle, and Model Definitions and Module Tree.
docs/quantization_protocol.md describes a version-2 protocol organized as version and ordered stages, with rules matching model objects and configuring weight, input, output, or kv_cache targets. Its key distinction for GPTQ is:
| Section | Question answered | Example intent |
|---|---|---|
prepare |
What transforms happen before quantization? | Weight smoothing |
quantize |
How are quantized values produced? | GPTQ versus RTN |
quantize.fallback |
What if calibration evidence is insufficient? | RTN fallback for sparse expert traffic |
export |
How is the result represented? | GPTQ-packed weights versus AWQ GEMM layout |
The design document contains forward-looking DSL examples, multi-rule patch semantics, and activation-aware activation_mode="ignore", "fake", and a reserved "real" mode. Those examples are not all implemented constructor arguments. In particular, they are not a v2 flag and should not be passed indiscriminately to GPTQConfig.
The implemented compiler parses protocol version 2 and requires exactly one rule carrying a weight target for config compilation; action-only rules/stages may accompany it. Aliases, stop, and non-default target replacement modes are rejected. This is not a general input/output/KV-cache compiler. Method compilation supports "gguf", "gptq", and "awq"; use RTNConfig directly for RTN.
Config compilation validates registered rule actions but does not execute them. apply_plan_actions() executes them against a live model; compile_and_apply_plan() combines those steps. Actions needing activation statistics, such as SmoothQuant, also need a calibration callback. See the public action guide before using multi-stage plans.
This single-rule GPTQ example uses the implemented mapping API:
from gptqmodel.quantization.protocol import compile_protocol_to_quantize_config
qcfg = compile_protocol_to_quantize_config({
"version": 2,
"stages": [{
"name": "ptq",
"rules": [{
"match": "*",
"weight": {
"quantize": {
"method": "gptq",
"bits": 4,
"group_size": 128,
"sym": True,
"desc_act": False,
"act_group_aware": True,
},
"export": {"format": "gptq"},
},
}],
}],
})The compiler rejects any rule requesting input, output, or kv_cache with NotImplementedError, even if that rule also contains weight. It rejects unknown weight.quantize arguments with ValueError rather than silently dropping them:
| Method | Accepted arguments beyond method
|
|---|---|
| GPTQ |
bits, group_size, sym, desc_act, act_group_aware
|
| AWQ |
bits, group_size, sym, desc_act
|
| GGUF | bits |
The parser also rejects unknown keys at the root, stage, rule, target, and export levels with ValueError. The error lists accepted keys and suggests a close spelling when one exists (for example, varient → variant). Rule stop and supported weight booleans (sym, desc_act, act_group_aware) must be actual booleans; a quoted "false" or a numeric 0 raises TypeError instead of being coerced.
The compiler rejects nonempty weight.export.options or a non-null weight.export.version with NotImplementedError, including for GGUF. weight.export.impl remains accepted but does not change the encoded layout or select a backend during compilation.
For example, act_order, damp_percent, fallback, symmetric, and group-size are not accepted weight-target keys. GPTQ/AWQ also reject weight.prepare; use the concrete config API for options outside this compiler subset. YAML parsing uses yaml.safe_load and requires PyYAML. Parsing a plan does not prove it can compile. See the compilation contract.
With activation=None, ordinary GPTQ keeps its weight-only calibration/inference behavior. The opt-in W4A policies change selected GEMM operands while retaining ordinary INT32-packed GPTQ qweight, qzeros, scales, and g_idx in the checkpoint. They do not establish that GPTAQ is enabled or that all model operations run at four or eight bits.
The GB10 guide distinguishes:
| Policy | Activation operand | Weight arithmetic |
|---|---|---|
w4afp8 |
E4M3 with one dynamic scale per token | Exact centered INT4 codes represented in E4M3; original GPTQ group scales applied to partial products |
w4a_nvfp4 |
E2M1 codes with per-16 E4M3 scales and a global scale | Two exact E2M1 integer planes reconstruct centered INT4 values; original GPTQ group scales remain authoritative |
Residual arithmetic, RMSNorm, attention internals, RoPE, SiLU, and the current KV cache are not thereby converted into fully low-precision arithmetic. The current transport keeps a wider reference for residual/norm operations; selected GEMMs consume encoded operands and scales. Q/K/V share an encoded normalized input, as do gate/up. The checkpoint weight codebook remains GPTQ's codebook.
For fresh quantization, activation replay rounds selected Linear inputs before Hessian capture and propagates their effects downstream. The replay keeps decoded GEMM operands in FP32 until the projection and returns outputs to the model dtype, matching the intended inference arithmetic. Merely attaching a policy to already packed weights does not redo the GPTQ solve.
| Component | Verified requirements / scope |
|---|---|
| Package at this source baseline | Python >=3.11; requirements include Torch >=2.15.0, and Transformers >=5.23.0,<5.24; consult the installation page for the complete environment |
| Ordinary GPTQ / GPTAQ | PyTorch computation plus a compatible selected model/device/backend; the optional CUDA block extension is not required for the eager algorithm |
| Native GPTQ block update | Working Torch JIT-extension/CUDA build toolchain; full 128-column blocks and the dispatch conditions above |
| RTN MLX fast path | Optional mlx.core, Darwin arm64, and the eligibility conditions above |
| W4A FP8 runtime | Linux CUDA, Triton FP8 support, FP16/BF16 model dtype; backend minimum compute capability (8, 9)
|
| W4A NVFP4 runtime | Linux CUDA, FP16/BF16, group size 128, symmetric 4-bit weights, desc_act=False, int32 packing; backend minimum compute capability (12, 1)
|
| GB10 recorded accuracy | Llama 3.2 1B Instruct and explicitly selected decoder coverage; not a guarantee for other models, hardware, or recipes |
The W4A backends have zero AUTO-selection priority. An ordinary GPTQ run does not opt into them by merely importing their module definitions. See FP8 and NVFP4 for full activation-policy and kernel requirements.
Both current W4A backends require 4-bit symmetric group-128 gptq/gptq_v2 checkpoints, desc_act=False, int32 packing, and lm_head=False. They declare input features divisible by 128 and output features divisible by 32, without automatic padding, training, or adapter support. The activation config rejects dynamic weight-layout overrides containing bits, sym, group_size, or desc_act. NVFP4 additionally checks for Triton activation packing, torch.float4_e2m1fn_x2, and torch.nn.functional.scaled_mm, ScalingType, and SwizzleType support. These restrictions also apply to the FP8 policy where applicable; the package dependency floor does not replace the native FP4 API checks. Do not assume that a CUDA device with FP8 support can execute NVFP4.
For an eligible model and device, the current explicit opt-in configuration can be written as:
qcfg = GPTQConfig(
bits=4,
group_size=128,
sym=True,
desc_act=False,
activation={
"mode": "w4a_nvfp4",
"recipe": "least_squares_grid",
"attention": {"mode": "w4afp8"},
},
)This selects a mixed operand policy, not a general accuracy guarantee. Current ActivationConfig accepts mode, recipe, attention, mlp, and global_scales; it does not accept the historical activation.version field shown in older experiment excerpts. Those policy versions are unrelated to the gptq_v2 checkpoint format. Use activation="w4afp8" for the separate per-token FP8 policy, or omit activation for ordinary GPTQ.
In training mode with gradient checkpointing enabled, the rebound W4A decoder forward calls Transformers' configured checkpoint function. The call changes a truthy use_cache to False. It also sets supplied past_key_values and layer_past to None, even when use_cache is absent or already false. Layers that explicitly declare they can checkpoint with a cache keep those arguments. Enable checkpointing through gradient_checkpointing_enable() to install the function before the training forward. W4A forward binding
docs/gptq-w4a-gb10.md is the usage/validation guide, while docs/gptq-w4a-accuracy-notes.md is an experimental log that includes failed and superseded runs. Its introductory description of an “accepted” balanced policy is not equivalent to a statistically passed noninferiority gate.
The appendix's latest full-model validation section, dated 2026-10-07, reports saved-checkpoint inference at runtime commit 7b6814c2. All 16 decoder layers and 112 projections were selected. Each policy was compared against its own same-weight W4A16 control over all 1,209 GSM8K Platinum rows:
| Policy | W4A16 correct / 1,209 | Activation-policy correct / 1,209 | Change | Paired 95% CI | Budget verdict |
|---|---|---|---|---|---|
Balanced A4: FP8 attention, NVFP4 MLP, least_squares_grid
|
502 (41.52%) | 474 (39.21%) | −2.316 percentage points | [−4.729, +0.097] pp | inconclusive |
Per-token FP8, w4afp8
|
432 (35.73%) | 438 (36.23%) | +0.496 percentage points | [−1.618, +2.611] pp | within_budget |
The two rows use different GPTQ weight checkpoints. Their absolute activation scores are not an A4-versus-A8 comparison. This particular validation covered saved-checkpoint inference, not fresh quantization.
Other useful lessons from the campaign:
- On one fixed A4-aware plain-GPTQ checkpoint, uniform dynamic NVFP4 scored 412/1,209 against 502/1,209 at W4A16: a −7.44 pp confirmed regression. Keeping attention at FP8, preserving the wider residual reference, and using
least_squares_gridrecovered the balanced policy's 474/1,209 without changing saved weight bytes. - The same checkpoint with all 16 MLPs promoted to FP8 scored 506/1,209 (+0.33 pp,
within_budget). Promoting only layers 10, 11, 12, and 15 scored 484/1,209 (−1.49 pp), but remainedinconclusive; a favorable point estimate is not a passed confidence-interval gate. - GPTAQ was dropped from A4 accuracy qualification because its extra state exceeded the GB10 memory budget with the required 2 GiB reserve. The GB10 wrapper supports a checkpoint-only GPTAQ experiment. The archived checkpoint received no A4 evaluation.
- Kernel-oracle, lifecycle, and encoded-boundary tests validate numerical/transport contracts. They do not establish downstream quality by themselves.
The guide's provisional acceptance test requires the paired 95% interval to rule out a loss greater than 2 percentage points on the full GSM8K Platinum dataset. An inconclusive verdict is not a pass. ARC-Challenge is a sensitivity diagnostic, not the controlling acceptance task.
For meaningful comparisons:
- Use identical weights for the W4A16 control and its activation-policy candidate; preserve the saved per-row baseline.
- Match rendered prompts, tokenizer artifacts, targets, row order, and generation settings. Freeze date-dependent chat-template content.
- Separate calibration/fit data, selection data, and benchmark evaluation data. The W4A calibration loader verifies artifacts and rejects normalized 13-word question overlaps against its evaluation exclusion registry.
- Verify actual decoder coverage. Historical two-layer fast checkpoints cannot stand in for a full 16-layer run just because the evaluation used all rows.
- Report point estimates, confidence intervals, and paired correctness flips. Recovered answers and changed answers are different statistics.
- Keep fresh calibration and loaded-checkpoint inference claims separate; neither retroactively validates the other.
For the representative GB10 calibration, the guide specifies 512 calibration rows with concatenation length 2,048. Its 32-record runs are transport checks, not a production calibration recipe. GB10 tests must run sequentially through tests/models/run_w4a_gb10_safe.sh, which preserves 2 GiB physical/cgroup memory headroom, disables swap in its scope, and guards the shared-memory GPU workload. Quantize/save and reload/audit run in separate guarded processes to avoid retaining quantization objects during a second model load.
See Evaluation and Troubleshooting and FAQ. Treat campaign numbers as model-, checkpoint-, policy-, prompt-, and runtime-specific measurements rather than universal GPTQ accuracy guarantees.
GPTQConfig.gsq opts calibrated nn.Linear modules into Gumbel-Softmax refinement after the ordinary GPTQ solve: hard code assignments are re-sampled against the calibration Hessian and kept only when an export-aware candidate improves the local objective. It requires format in GPTQ, GPTQ_V2, or GPTQ_P, plain GPTQ (no gptaq, foem, or mock_quantization), and calibration activations; tensor-parallel padded projections are rejected. RTNConfig.gsq offers the same refinement on scalar GPTQ or AWQ export formats, with AWQ-family formats requiring 4 bits. GPTQConfig.gsq_training instead selects the staged dense-Llama/Qwen3 block-training recipe (initializer gptq or rtn). See GSQ for field tables, per-module modules/dynamic selection, and staged requirements.
| Symptom or assumption | What to check |
|---|---|
“v2=True enables the current algorithm” |
No such GPTQConfig field exists; use nested GPTAQConfig for GPTAQ and FORMAT.GPTQ_V2 for checkpoint zeros |
“desc_act=False means natural order” |
GPTQ currently resolves act_group_aware to True; explicitly disable both for natural order |
| Ordering configuration error | Do not explicitly enable both classic and group-aware ordering |
Static groups with group_size=-1
|
Static precomputation expects a positive group step; use a positive group size or disable static groups |
| Full-row GPTQ warns about a no-op ordering flag |
group_size <= 0 leaves nothing for act_group_aware to permute, so the config disables it with a warning; set act_group_aware=False explicitly to silence it. Older revisions rejected the combination at task construction |
| GPTAQ does not honor a plain-GPTQ optimization/recovery setting | Its overridden recurrence and solve support group-aware ordering and failed-inverse RTN recovery, but not chunked Hessian accumulation, shared-factor reuse, fused block updates, or ordinary GPTQ's low-sample/NaN policies |
| Cholesky failure or unexpectedly large damping | Check calibration coverage, dead channels, selected retry damping, and fallback logs; a bigger damping value is not a proof of better accuracy |
| Some MoE experts have little traffic | GPTQ, GPTAQ, and FOEM apply the configured low-coverage threshold per module. Zero coverage also activates their separate safety guards. |
| Hessian staging is bounded but memory still grows | The dense square Hessian, inverse factor, weights, native-reference caches, and other workspace still consume memory |
| A run completes with NaN-related recovery warnings | GPTQ can retry with mock quantization when fallback is configured; inspect logs rather than accepting completion as a quality result |
Packing reports scale value(s) cannot be stored as fp16
|
Check the named tensor and nonfinite/overflow/underflow counts; a BF16/FP32 source does not widen the shared GPTQ packers' FP16 scales. See FP16 checkpoint scale range |
Comparing GPTQ and RTN avg_loss directly |
RTN reports mean absolute weight error as a string; GPTQ reports a sample-normalized Hessian reconstruction metric |
Assuming mock_quantization=True is a fast accuracy mode |
It uses simplified computation for validation, not the ordinary second-order solve |
| CUDA extension unavailable | Check compiler/build diagnostics or use the eager path; do not confuse it with the inference backend |
| Loading an asymmetric legacy checkpoint fails | Check original producer/version metadata and zero-point convention; do not hand-edit packed zeros |
| Good kernel parity but poor benchmark quality | Check full decoder coverage, calibration/evaluation disjointness, prompts/tokenization, and paired downstream measurements |
| W4A4 label interpreted as four-bit attention/KV/residual math everywhere | Only selected GEMM operands use the encoded formats; wider internal operators and residual references remain |
Research background: GPTQ: Accurate Post-Training Quantization for Generative Pre-trained Transformers. The GPTAQ correction and RTN behavior here are described by their GPT-QModel implementation links below.
Links below point to the documented revision so signatures and defaults can be audited independently of later changes.
| Source | Responsibilities |
|---|---|
gptqmodel/nn_modules/qlinear/__init__.py and docs/gptq-scale-storage-range.md
|
Shared GPTQ packers and FP16 scale-storage validation |
gptqmodel/quantization/gptq.py |
GPTQ tasks, Hessian lifecycle, inverse recovery, ordering, block loop, fallbacks, compatibility wrappers |
gptqmodel/quantization/quantizer.py |
Ranges, affine rounding, dead-column helpers, vectorized MSE grid |
gptqmodel/quantization/gptaq.py |
Native-reference cross term and activation-aware solve |
gptqmodel/quantization/rtn.py |
Weight-only rounding, smoothing, optional MLX dispatch |
gptqmodel/quantization/fallback_smooth.py |
Shared smoothing and ternary MSE range search used by RTN/fallbacks |
gptqmodel/utils/fallback.py |
Absolute/percentage threshold resolution and strict low-sample fallback comparison |
gptqmodel/quantization/gptq_cuda.py |
Optional native block-update loader |
gptqmodel/utils/env.py |
Boolean environment-flag parsing, including the CUDA block-update opt-out |
gptqmodel_ext/gptq_block |
C++ registration and CUDA within-block kernel |
gptqmodel/quantization/config.py |
Method-specific dataclasses, defaults, normalization, enums, serialization |
gptqmodel/looper/gptq_processor.py |
Task selection, dynamic config, hooks, shared inputs, quantization, packing |
gptqmodel/looper/native_processor.py |
GPTAQ/FOEM native input capture and placement |
gptqmodel/looper/module_looper.py |
Sequential subset replay and execution coordination |
gptqmodel/models/base.py |
Public quantization lifecycle, calibration requirements, processor construction |
gptqmodel/models/loader.py and gptqmodel/utils/model.py
|
Checkpoint compatibility and packed-zero conversion |
gptqmodel/quantization/protocol.py |
Implemented protocol parser and restricted config compiler |
docs/quantization_protocol.md |
Broader protocol design, matching/override model, algorithm/export distinction |
docs/gptq-w4a-gb10.md |
W4A usage, transport, requirements, quality gates, memory-safe validation |
docs/gptq-w4a-accuracy-notes.md |
Recorded experiments, failed candidates, same-weight comparisons, dated full-model results |
gptqmodel/nn_modules/qlinear/w4a_floatx.py and w4a_nvfp4.py
|
Actual FP8/NVFP4 backend support declarations and hardware validation |
pyproject.toml and requirements.txt
|
Python and dependency requirements at this revision |
Next: choose a method and dtype, reload your checkpoint, then evaluate it.
- What Is Quantization
- Installation and Quickstart
- QuantizeConfig Reference
- Quantization Lifecycle
- Looper Processors
- Packing Formats and Compatibility
- Kernel Backends Reference
- Loading and Inference
- Memory Offload and Multi-GPU
- FP8 and NVFP4
- MLX Apple Silicon
- AWQ
- GSQ
- Evaluation
- Troubleshooting and FAQ
- Developer Guide
Documentation home · Quickstart · Troubleshooting · Repository · PyPI
Public source 775013e41 declares package version 7.14.0. Individual pages identify their source revisions. Choose a method · Dtypes and formats. Maintained by ModelCloud.ai.
🧭 1 · Choose and understand
🚀 2 · Use it
- Installation and Quickstart
- Loading and Inference
- LeapQuant recurrent-state quantization
- Evaluation
- Serving
- Troubleshooting and FAQ
- Memory, Offload, Multi-GPU
- MLX / Apple Silicon
- Tenstorrent / Block Floats
- Hugging Face Integration
- Multimodal and MoE Models
🎛️ Methods and representations
Each guide: choose → examples → math / advanced
- GPTQ / GPTAQ / G2PTQ / ADMM-Q / RTN
- SINQ
- JointQ
- AWQ
- QQQ
- MACaQ / MXFP4
- EXL3
- CPTC
- VPTQ
- Tetra
- TWLA
- Paro
- FP8 and NVFP4
- NF12: lossless BF16 storage
- GGUF families
- BitsAndBytes: NF4 / FP4 / INT8
🧰 Refinement and execution
- GSQ refinement / allocation
- EoRA adapters
- Rotation, Smoothing, Norm Tuning
- Projection Fusion
- TurboQuant KV cache
🧠 3 · Theory and advanced reference