Skip to content
Qubitium edited this page Dec 1, 2026 · 31 revisions

🎲 GSQ: refine quantized weights, keep the format

🏠 Home · 🧭 Choose a method · 🚀 Quickstart · 🧰 Help

On this page

Runtime tuning below uses KernelConfig: pass kernel=... through the quantization/load API. Kernel-policy fields are not environment variables; build/cache and diagnostic controls remain separate.

GSQ spends extra quantization time searching for weight codes that better reproduce the original layer or block. It can improve a local reconstruction objective without introducing a new checkpoint format.

For: readers who already have a working quantization baseline and want to explore quality recovery. New to quantization? Start with Choosing a Method and Dtype.

Overview

GSQ adapts the Gumbel-Softmax quantization ideas from the IST-DASLab GSQ paper (Dadgarnia et al.) and its reference implementation into two opt-in refinement/training features plus related allocation tooling that run during quantization:

  • Local scalar refinement (GSQConfig): after a supported method's ordinary quantizer produces an initial quantized layer, candidates are scored against a method-specific local reconstruction objective. GPTQ searches hard exported codes per output row and can refit group scales; the separate affine adapter retains Gumbel-Softmax candidate training. The initializer is retained unless an export-aware candidate improves the objective.
  • Staged block training (GSQTrainingConfig): for a materialized dense Llama or Qwen3 model, decoder blocks are trained in reconstruction stages. The GPTQ shortcut packs each block before the next block's inputs are captured; AWQ integrates staged fitting at its scaled-teacher/packing boundary.
  • Non-uniform bit allocation (RCO): the staged GPTQ pipeline can select widths per block or projection from pre-trained arms. A separate reconstruction-error runner allocates AWQ, EXL3, or GGUF options under packed-weight budgets; it does not run GSQ training or the paper's differentiable KL search. Both pipelines export existing method formats.

GSQ is not a new runtime format: every path saves each method's existing scales, zero points, packing, and checkpoint layout. External runtimes and training integrations keep supporting only the formats they already accept. All options are off by default, they increase quantization time, and they are experimental adaptations: the paper's reported quality gains do not transfer automatically to any path. Measure downstream quality on your own workload before adopting GSQ broadly.

The API guidance here was checked against public source revision 44aa0f98e. The measurements below refer to the listed experiments. Use the source matching your installed GPT-QModel version.

🧭 Choose your starting point

Choose this when… Start here Consider another path when…
You want an incremental experiment on an existing supported quantizer. Local scalar refinement, usually the smallest change. Quantization time or candidate/optimizer memory is already tight: keep the base method first.
You can afford a longer dense Llama/Qwen3 reconstruction job. Staged Llama block training. Your model, transforms, or export do not pass the staged path's strict gates.
You have pre-trained width arms and want mixed precision. Staged RCO allocation. You have no arms: this is not a one-flag replacement for training them.
You want AWQ/EXL3/GGUF allocation from measured reconstruction errors. Format-aware allocation. You need teacher-KL GSQ training: this is a different search.

Before you start: retain a baseline checkpoint, use representative calibration and separate held-out evaluation, check the per-method limits, and budget for extra tensors beyond max_candidate_bytes. Keep NVIDIA CUDA and AMD ROCm backend requirements separate; a config accepting a method is not hardware qualification.

Read in three passes: use a small local experiment → understand the objective → advanced allocation and controls.

🧱 Choose a baseline before adding GSQ

Baseline What it does Relationship to GSQ
GPTQ (GPTQConfig) Uses calibration-derived second-order information to compensate weight-rounding error. Local scalar GSQ can refine its result under the constraints below.
GPTAQ (GPTQConfig(gptaq=...)) Adds correction informed by the difference between teacher and quantized-path inputs. A distinct correction choice, not another name for GSQ. This local GPTQ GSQ adapter and the public staged GPTQ shortcut reject gptaq/foem.
RTN (RTNConfig) Weight-only round-to-nearest baseline without the Hessian solve. Supports its own scalar GSQ adapter; staged training can also use initializer="rtn" under the GPTQ shortcut's separate gates.

See GPTQ, GPTAQ, and RTN for the base-method decision. First establish a baseline, then measure whether refinement is worth its extra quantization cost.

Workflow at a glance

Refinement, staged training, and budget allocation. Choose an optional quality workflow; keep the base method's checkpoint format.

Reading the diagram: These are alternative workflows, not a new dtype or universal accuracy guarantee. Check the page for each path's model, format, and configuration limits.

Text version of the workflow
  • Local scalar refinement: Run the base quantizer → Refine candidates → Keep a winning export → Pack normally.
  • Staged dense-model training: Start with dense weights → Reconstruct each block → Pack before continuing → Evaluate and save.
  • Format-aware reconstruction allocation: Measure candidate options → Apply a packed budget → Export selected options.

Open full-size SVG

🚀 Use it: start local, then consider staged training

Local scalar refinement

Enable it on the method's config. The supported method configs below accept either a GSQConfig or a dictionary:

from gptqmodel.quantization import GSQConfig, QuantizeConfig

quant_config = QuantizeConfig(
    bits=4,
    group_size=128,
    gsq=GSQConfig(enabled=True, steps=100, candidates=16, learn_scales=False),
)

Apply that config to an unquantized model using the ordinary API:

from gptqmodel import BACKEND, CalibrationConfig, GPTQModel

# calibration_texts: representative texts prepared by the caller.
# A handful of tiny strings is only an API demo, not an accuracy recipe.
model = GPTQModel.load("path/to/unquantized-model", quantize_config=quant_config)
logs = model.quantize(CalibrationConfig(dataset=calibration_texts), backend=BACKEND.GPTQ_TORCH)
model.save("model-gptq-gsq")

Evaluate the saved model against an otherwise matched run with gsq=None. A lower diagnostic after score only proves a better local objective. Evaluation covers held-out quality checks; Loading and Inference covers runtime selection.

For GPTQ, local GSQ applies to calibrated nn.Linear layers in the scalar FORMAT.GPTQ, FORMAT.GPTQ_V2, and FORMAT.GPTQ_P exports, at 2–8 bits and all GPTQ group sizes. The GPTQ path requires calibration activations and rejects tensor-parallel padded projections; when the data-independent fallback policy triggers, refinement is skipped and gsq_diagnostics records {"status": "skipped", "reason": "data_independent_fallback"}.

max_candidate_bytes bounds the code-candidate bank per output-row chunk (64 MiB by default); temporary tensors and, on adapters that use one, optimizer state need additional memory beyond that bound. learn_scales=True tunes stored scales where the method supports it — currently the GPTQ/AWQ affine paths; QQQ and Paro validation rejects it.

For GPTQ, refinement now searches the codes that packing will actually export instead of training a soft mixture whose hard result could leave the GPTQ initializer unchanged. learn_scales=True adds closed-form group-scale fitting after accepted code changes. Compare both settings against ordinary GPTQ on held-out data; a lower calibration objective alone does not establish a quality gain. The checkpoint remains the same GPTQ format, with scales, zero points, g_idx, and packed codes.

Staged Llama block training

gsq_training selects a staged reconstruction recipe instead of the ordinary loop. On GPTQConfig the initializer must be "gptq" or "rtn"; on AWQConfig pass {"initializer": "awq"} (the dict form fills it in automatically) and export must be 4-bit GEMM.

from gptqmodel.quantization import AWQConfig, FORMAT, GPTQConfig, GSQTrainingConfig

training = GSQTrainingConfig(enabled=True, epochs=20, qk_steps=2000)

gptq_config = GPTQConfig(
    bits=4, group_size=128, format=FORMAT.GPTQ_V2,
    act_group_aware=False, offload_to_disk=False,
    gsq_training=training,
)

awq_config = AWQConfig(
    bits=4, group_size=128, format=FORMAT.GEMM,
    gsq_training={"enabled": True, "epochs": 20, "qk_steps": 2000},
)

The GPTQ public staged path — quantize_llama_gsq_public for METHOD.GPTQ — enforces all of the following at this revision:

  • A fully materialized, unquantized dense Llama or Qwen3 in eval mode on one CPU or Torch CUDA-namespace device (NVIDIA CUDA, or the HIP-backed namespace on AMD ROCm), with attn_implementation="eager".
  • Symmetric W2/W3/W4 GPTQ scalar export (format GPTQ or GPTQ_V2) with desc_act and act_group_aware off. AWQ's W4 GEMM fitting uses the separate processor path described below, not this GPTQ shortcut.
  • pack_dtype int32 and the Torch packing backend (AUTO/GPTQ_TORCH).
  • No rotation, adapter, gptaq, foem, mock_quantization, static_groups, adjacent_model, adaptive_clipping, lm_head, preprocessors, smoother, offload_to_disk, or adaptive damping, and no adapter/embed_quant_config/checkpoint arguments or CalibrationConfig.adapter_dataset to quantize(). Staged GSQ rejects CalibrationConfig(exclude_attention_sinks=True) and resolves the default None to False, including for Llama 3. Unsupported options raise. dynamic is accepted only as a per-block width assignment, described in Non-uniform bit allocation (RCO).

The staged recipe trains all seven projections of every decoder block without dynamic skipping: query and key projections separately, value and output jointly against attention output, then the MLP projections against the decoder block output. It trains assignments and scales with the selected optimizer (Lion by default) under temperature and logit-multiplier schedules, and packs each block before capturing the next block's inputs. Block state can be checkpointed so a long W3/W2 run resumes safely; a resume validates capture metadata in the checkpoint signature. New checkpoints also record a rolling hash of their packed predecessors, and checkpoint gaps or changed predecessors are rejected before training — see Distributed execution and activation reuse for the prefix-import exception.

restore_best controls which epoch is exported:

restore_best Behavior
None (default) Automatic: selects the best held-out validation epoch when validation batches exist; exports the last epoch when they do not.
True Requires nonempty held-out validation batches for every reconstruction stage; staged runs without validation_documents raise.
False Always exports the last epoch.

Held-out validation uses validation documents supplied through the training capture path; ordinary calibration= alone does not create a held-out split for this guard.

The GPTQ public quantize() staged path keeps the model on one CPU or CUDA-namespace device. NVIDIA and AMD support depends on the architecture. Multi-rank execution is available only through the runtime entry point described in Distributed execution and activation reuse.

Staged GPTQ export preserves the model's dtype after training. For example, a BF16 model stays BF16 when the trained blocks become the inference model. Staged export implementation

AWQ is not the GPTQ shortcut. AWQ staged fitting runs inside AWQProcessor, after capturing the scaled pre-clipping teacher. It requires every declared projection, eager attention, no fallback targets, and no tensor-parallel padding. See the public AWQ boundary implementation. Do not assume the GPTQ-only dynamic, resume, or looper-bypass behavior applies to AWQ.

Staged AWQ installs refined replay weights by copying into the existing parameter under inference mode. This keeps the parameter's inference state consistent through finalization rather than producing a parameter without a usable version counter. It changes neither the staged objective nor the packed AWQ layout.

🧠 Go deeper: objectives, constraints, and advanced workflows

Concepts

What the two paths change

gsq and gsq_training are mutually exclusive on one config: validation raises when both are enabled. Local refinement still runs the base quantizer first and then perturbs the resulting hard assignments, so the base method's solve remains the initializer. GPTQ staged training is a separate loop inside quantize() — it dispatches before the ordinary looper pipeline, so ordinary processors (rotation, smoothing, GPTAQ, FOEM, adapters, preprocessors) are not silently applied on that shortcut. AWQ staged fitting instead uses AWQ's processor boundaries.

Local objective, not end-to-end training

Per-linear refinement optimizes each calibrated nn.Linear independently against its captured calibration statistics — a calibration Hessian for GPTQ, and captured moments for QQQ. It is not the paper's full block-training schedule and not a claim that downstream perplexity improves; it changes only the stored hard codes (and optionally stored scales where learn_scales is allowed).

Module selection

GSQConfig.modules is an optional tuple of regular expressions matched with pcre.search against the module's full name; a None value refines every eligible module. On the GPTQ processor path a dynamic override can also set gsq per module pattern (see QuantizeConfig reference):

dynamic={
    r".*self_attn\.(q_proj|k_proj)$": {"gsq": {"enabled": True, "steps": 50}},
    r"-:lm_head": {},                      # excluded entirely
}

🔬 What is being minimized?

For the GPTQ local path, let W be the original weight matrix with shape [out, in], Q its reconstructed quantized candidate, and X calibration inputs with shape [tokens, in]. The calibration Gram H is proportional to XᵀX; write H = LLᵀ. The code scores a normalized reconstruction loss:

$$\mathcal{L}(Q) =\frac{\|(Q-W)L\|_F^2}{\|WL\|_F^2}.$$

The denominator becomes 1 when its energy is below the implementation's FP32 epsilon guard. Up to a common positive normalization of H, the numerator measures ‖X(Q-W)ᵀ‖²_F: output error on the calibration directions, not language-model loss.

GPTQ scores the initializer and candidates as they would decode after packing. It recovers codes in FP32 with the returned scales, then decodes using scales rounded to the checkpoint's FP16 storage dtype. FP32 code recovery preserves exact initializers whose zero-point and scale product would overflow FP16. The hard search advances eight-column blocks in Gauss-Seidel order and considers immediate neighbouring codes. It accepts a candidate for an output row only when that row's score improves by more than 5%.

With learn_scales=True, each row can try a closed-form per-group least-squares scale fit even if its code search kept the current codes. Scale acceptance is also per row. max_candidate_bytes controls how many rows are processed together. The layer's before, after, and history scores use the combined teacher energy across all rows, so a zero-energy chunk contributes no artificial normalization term. Scalar refinement implementation

Both scalar refiners evaluate hard candidates on the stored scale grid. A row with nonfinite replay weights, out-of-range codes, or a nonfinite recovered objective is ineligible. A finite scale can still produce an out-of-range grid endpoint, such as -65536 for FP16. If no valid candidate improves the score, the original initializer tensor is kept verbatim.

GPTQ runs one code sweep with fixed scales. With learn_scales=True, it runs up to two rounds of code sweeps and scale fits, bounded by steps, and may stop earlier. Diagnostic history always has steps + 1 entries, repeating the final score after early convergence. The final score uses the exact replay tensor returned to the packer. A nonfinite objective or an aggregate after > before raises ValueError. See per-linear GPTQ refinement.

The separate affine adapter, used by AWQ and RTN, still trains a relaxed candidate. Each weight has valid candidate codes c_j, trainable logits ℓ_j, Gumbel noise g_j, and temperature τ > 0. Its relaxed code is

$$p_j=\frac{\exp((\ell_j+g_j)/\tau)} {\sum_k\exp((\ell_k+g_k)/\tau)}, \qquad \widetilde c=\sum_j p_jc_j, \qquad \widetilde w=s(\widetilde c-z).$$

Here s and z are the group's scale and zero point. For that affine adapter, Adam updates logits (and optionally allowed scales); export chooses hard codes and evaluates them again using the target packer's arithmetic and stored-scale dtype. Only a strictly better hard export replaces the initializer. Neither path saves soft probabilities or an optimizer in the checkpoint.

Other adapters use their own local metric; staged fitting reconstructs projection/attention/block targets instead. These equations do not imply that QQQ, AWQ, or staged GSQ all optimize an identical objective. See gsq_scalar.py.

The affine adapter skips a calibration-free weight-MSE code search when scales are fixed (learn_scales=False, with no Hessian, inputs, or cross moment): nearest rounding already minimizes that objective. It keeps the baseline weight/scales and packed codes, records skipped=True, and returns a one-entry baseline history instead of spending the configured step budget. RTN exposes that boolean in gsq_diagnostics. Calibration-aware searches and permitted scale learning still run.

Per-linear affine results preserve the input weight's inference-tensor state, including disabled and skipped paths. AWQ staging can install the returned tensors and replay later calibration batches without a version-counter error; this is separate from the existing staged-AWQ parameter-copy fix.

Per-method adapter constraints

Config Where refinement applies Validation constraints when gsq.enabled
GPTQConfig Calibrated nn.Linear layers format in GPTQ, GPTQ_V2, GPTQ_P; mock_quantization off; no gptaq/foem.
AWQConfig AWQ scalar export format in GEMM, GEMV, GEMV_FAST, LLM_AWQ; bits must be 4; non-GEMM formats also require group_size in -1, 32, 64, 128.
RTNConfig Scalar GPTQ or AWQ export format in GPTQ, GPTQ_V2, GEMM, GEMV, GEMV_FAST, LLM_AWQ; AWQ-family formats require bits 4.
QQQConfig QQQ packing format must be FORMAT.QQQ and learn_scales must stay False. Staged gsq_training is unsupported. Non-nn.Linear or TP-padded modules skip refinement.
ParoConfig 4-bit module-scope optimization bits 4, opt_scope "module", and opt_train_on_noisy_inputs False.

Each adapter keeps its method's native scales, zero points, packing, and format constraints; refinement records gsq_diagnostics (objective value before/after, or a skip reason) into the module state for writer-side provenance.

For QQQ, GSQ builds its Hessian and teacher cross moment from activations reconstructed using the Torch runtime quantizer's INT8 codes and FP32 row scales. An all-zero row uses a unit scale. If a positive row maximum divided by 127 rounds to zero in FP32, the quantizer uses 2**-149. Re-run quantization from the source model to apply corrected calibration to the refined weights. QQQ activation grid

For whole-row QQQ quantization, GSQ widens each raw weight scale to FP32 before dividing it by 16, matching the channel scale written by the packer. A small FP16 producer scale can therefore remain positive in the refinement grid even when dividing in FP16 would round it to zero. QQQ candidate decode

For AWQ GEMM/GEMV/GEMV_FAST (including LLM_AWQ), hard export scoring now recovers the exact codes the packer will write: form zero * source_scale in FP32, add the weight, divide by the stored scale in FP32, round, then clamp to the legal code range. GEMM keeps FP16/BF16 scales and otherwise stores FP16; GEMV variants store FP16. Learned GEMV scales are scored after the conversion to the returned source dtype as well as the final storage dtype, so a BF16 return cannot silently change a previously scored FP16 grid. The initializer and candidates use these same rules; only a strict improvement in the packed objective replaces the initializer. This corrects near-threshold rounding and scale-dtype mismatches without changing GSQ options. See AWQ code recovery.

Scalar GPTQ refinement first tries an undamped FP32 Cholesky factor of the symmetrized calibration Hessian. It checks that the factor's diagonal is finite even if the solver reports success, which catches a CUDA failure seen with rank-deficient routed-expert Hessians. If the factorization fails, GSQ retries with up to four diagonal-jitter additions before using a CPU FP64 eigendecomposition as a last resort. Running the eigensolver on the CPU avoids a large GPU workspace, especially for wide projections with limited calibration data. The factor returns to the original device. See metric-factor construction.

⚙️ Staged numerical behavior and execution

Half-precision staged training keeps every projection's sampling logits in FP32, widens half-precision softmax exponent/gradient arithmetic, and reduces reconstruction MSE in FP32 while leaving the model forward in its configured dtype. This avoids overflow from large sampling multipliers or squared residuals. A nonfinite objective/gradient raises a Python RuntimeError before optimizer.step() rather than poisoning the CUDA context with a device assert; distributed ranks agree on the finite check. These are numerical fixes, not new configuration switches.

Kernel acceleration

Empty CUDA/HIP training geometries do not launch zero-block kernels: an eligible empty cuda_rms_norm input returns an empty tensor with the same shape, dtype, and device before backend loading, while zero-row/zero-column scalar relaxation returns to the eager/autograd path. This does not relax the staged training requirement for nonempty calibration/validation data.

Staged W3/W4 training compiles a fused scalar-relaxation kernel instead of running the eager autograd path: through NVRTC on CUDA, and through HIPRTC on ROCm since 4b36fd61 — the HIPRTC backend is selected first when torch.version.hip is set and binds libhiprtc via ctypes, so it needs no build step or new dependency. Measured on an MI350X (gfx950): ~72 ms to ~14 ms per update at W3/W4 (~5x). W2 cannot use the fused path — the kernel needs a five-choice logits tensor and a non-None initial offset, and initial is None for W2 — so W2 always runs eagerly. KernelConfig.gsq_disable_cuda_relaxation=True forces the eager path everywhere; KernelConfig.gsq_disable_hip_relaxation=True skips only the HIPRTC backend. When a backend is unusable the module returns None and training silently continues on the eager path.

The fused path accepts BF16 or FP32 logits with FP32 initial values/scales. It now evaluates (logits * multiplier + noise) / temperature in FP32 and stores the softmax probability in FP32 for both forward reconstruction and backward gradients. For BF16 logits, the Gumbel-noise chain deliberately retains the BF16 rounding of the eager uniform/log operations; the exponent and probability are not rounded back to BF16. This fixes disagreement with eager relaxation during BF16 training. Unsupported dtype/layout/geometry or unavailable runtime compilers still return to eager. No new training flag is required; shared controls are also available as RuntimeConfig(gsq_disable_cuda_relaxation=True) or RuntimeConfig(gsq_disable_hip_relaxation=True). See the precision contract and oracle evidence.

Separately, when the group map is the standard contiguous arange(in) // group_size, the scale-gradient backward reduces as a segment sum instead of a colliding duplicate-index scatter_add_ — same terms, different reduction order (fp32 error ~1e-7, forward output bit-identical), ~1.45–1.54x faster per staged update at paper geometry on gfx950.

Distributed execution and activation reuse

The runtime entry point quantize_llama_gsq_model() — what run_arm.py and the reproduction scripts drive, distinct from the quantize() public path — accepts a distributed context: a GSQDistributed (gptqmodel/quantization/gsq_distributed.py) wrapping an already-initialized Gloo or NCCL torch.distributed process group (on ROCm the nccl backend name uses RCCL). Distributed execution requires enabled staged training; batch_size remains the global optimizer batch and must be divisible by world size, and microbatch_size must fit the per-rank local batch. Each global batch's documents shard into contiguous rank chunks, and dataset lengths that do not divide into complete global batches are rejected rather than truncated — so a 4096-document corpus at global batch 64 always produces the recipe's 1280 updates per stage regardless of world size.

Group rank zero is the primary: it owns GPTQ initialization and the fixed-quadratic Q/K fit and broadcasts the results, performs atomic checkpoint reads/writes, and drives the globally-weighted validation and best-epoch selection. Initial quantizer state is synchronized across ranks before the first fit evaluation; sampling RNGs are rank-local. Accumulated gradients and reported losses are weighted by reconstructed output-element counts and summed across ranks before each optimizer step — FP16/BF16 gradients reduce in bounded FP32 chunks. Capture and incremental replay are rank-local, but their failures propagate collectively. GSQDistributed never initializes torch.distributed itself; the caller owns process-group setup (e.g. torchrun), device selection, and optimizer steps.

Three memory knobs ride along on the same entry point:

Parameter Effect
target_cache — 'none' (default) | 'cpu' | 'device' Retain exact fixed stage targets — teacher outputs and the fixed post-attention residual — in host or device memory instead of recomputing them inside each update. A memory policy requires SDPA attention; the SDPA disk-capture path can still create temporary target caches even when the explicit policy is none.
activation_checkpointing — False (default) Recompute student activations during backward with a non-reentrant checkpoint, reducing activation storage; it does not redraw noise during backward or share a sample between microbatches.
reuse_capture — False (default) Advance train, calibration, and validation captures through each newly packed block — including its stored-scale rounding — instead of replaying the whole prefix for the next block. Requires memory-backed (CPU or device) capture; incompatible with the capture_directory disk spool. After a resumed prefix, the first unfinished block is still captured from the loaded prefix before incremental advancement continues.

resume_prefix_directory performs an explicit compatible-prefix import into a checkpoint_directory (required): completed blocks from another checkpoint tree are verified against the model, all document digests, bit widths, layer selection, the determinism setting, and the full GSQ recipe including microbatch size and seed — while device, distributed_world_size, target_cache, and activation_checkpointing may differ. Imported blocks are rewritten atomically under the destination signature and record imported_from; completed destination blocks take precedence over the import source, and the plan selects only one contiguous completed prefix — gaps are rejected before any training starts. Import carries completed blocks only, not an interrupted block's optimizer state. New checkpoints hash their preceding packed blocks into packed_prefix, so a changed predecessor is rejected; legacy checkpoints without that hash are accepted only when their earlier source files reproduce the packed prefix actually installed. Ordinary resume still requires the full execution signature.

The run record exposed as model.gsq_training_runs additionally stores world_size, target_cache, activation_checkpointing, reuse_capture, and resume_prefix_directory.

Non-uniform bit allocation (RCO)

A uniform staged arm stores a packed checkpoint per decoder block. Allocation can select one arm width for a whole block or select widths independently for its projections. The GSQ paper's 2.37 and 2.62 bits-per-parameter Llama rows use non-uniform assignments produced by RCO — Riemannian budget-constrained optimization (Helcig & Alistarh, arXiv 2605.00649, cited from the GSQ paper's Sec. 4.2 and Table 1). gptqmodel/quantization/rco.py is a dependency-free port of the IST-DASLab/RCO reference: its tangent projection, retraction, and momentum transport match the reference alpha bit-identically at tolerance 0.05 and 1e-6, and its knapsack rounder matches the reference solver exactly at 16 and 112 groups.

An assignment is expressed per decoder block:

  • On the public GPTQ staged path (quantize_llama_gsq_public), QuantizeConfig.dynamic accepts only whole-block width entries — {'model.layers.<n>': {'bits': 2|3|4}} — one width per selected block. Any other module name or any override field besides bits raises; a non-uniform export writes per-projection dynamic entries for modules whose width differs from the base bits and records the full map in meta['gsq_layer_bits'] — or meta['gsq_projection_bits'] for a per-projection run — so loaders rebuild each layer at its assigned width.
  • Internally, quantize_llama_gsq_model() accepts bits as a {layer_index: width} dict, and resolve_projection_bits/initialize_llama_gptq accept per-projection maps; projection_bits_for_budget builds a greedy exact-budget assignment interpolating two widths. rco_materialize.py consumes either a legacy whole-block layer_bits assignment or a complete per-projection projection_bits map.

scripts/gsq_paper/rco_allocate.py builds the width database from staged per-block checkpoint arms, runs the projected Gumbel search on held-out calibration documents, and decodes the soft solution to an assignment at or below --target-bits. rco_materialize.py installs each selected projection from the arm of its assigned width and runs the normal staged export without retraining.

python scripts/gsq_paper/rco_allocate.py --model meta-llama/Llama-3.2-1B-Instruct \
    --corpus /models/datasets/gsq-bench/fineweb-paper \
    --out /workspace/rco-2375 --target-bits 2.375 \
    --arms '/workspace/w{bits}gsq4096/ckpt' --steps 200
python scripts/gsq_paper/rco_materialize.py --model meta-llama/Llama-3.2-1B-Instruct \
    --assignment /workspace/rco-2375/assignment.json \
    --arms '/workspace/w{bits}gsq4096/ckpt' --out /workspace/rco-2375/model

The allocator's default --preset paper searches per-projection widths under a dense-teacher KL objective with W2/W3/W4 candidates and four Gumbel draws per update; --preset legacy reproduces the earlier whole-block cross-entropy search over W2/W3 with one draw. --objective, --grouping, --gumbel-samples and --kl-chunk-tokens override individual preset pieces, --teacher-cache device|disk bounds the frozen teacher's hidden-state scratch, and --layers is inferred from the checkpoint when omitted. --backend auto|torch|mlx selects the differentiable search backend — auto prefers the native MLX path (gptqmodel/quantization/rco_mlx.py) on Apple silicon, which requires macOS arm64 with pip install "gptqmodel[mlx]" and currently covers the llama/qwen3 decoder layouts — while --device auto picks the Torch device used to reconstruct the staged arms. Assignment decoding maximizes additive logit scores through budget_constrained_argmax: the search and final decode pass raw logits rather than softmax probabilities, which underflow the relative scores a budget-constrained decode needs; round_with_budget remains as the legacy probability-input wrapper.

Final decoding rechecks the parameter-weighted code cost in FP64 because the knapsack solver rounds each group's cost. If the assignment exceeds --target-bits, the allocator repeatedly selects the cheaper option with the smallest logit score drop per bit saved. In assignment.json, projection_bits_per_parameter reports the achieved cost, which can be below the target, and budget_repair_applied records whether a repair changed the assignment. If the target is below the cheapest feasible mix or decoding cannot produce an assignment within budget, the CLI exits without writing a new assignment.json. RCO discrete budget export

The maintained differentiable staged RCO search is GPU-only: MLX runs candidate replay, teacher KL, loss, and backward on Metal; Torch MPS/CUDA provide the alternative implementation. The small discrete budget DP and scalar retraction remain CPU host work. This is distinct from the reconstruction runner below, whose AWQ/GGUF scoring uses CPU weight quantizers. ANE/NPU has no backend, dispatch path, or benchmark target; the historical ANE qualification failed its accuracy/performance gates and its three benchmark scripts were removed. scripts/gsq_paper/bench_rco_backends.py remains the warm Torch-MPS versus MLX-Metal search benchmark, not an ANE benchmark.

Torch and MLX mix the stored candidate weights directly in the projection's weight dtype. A hard one-hot Gumbel selection reproduces the selected candidate exactly. This avoids the rounding error that can occur when a narrow dtype stores the difference between a candidate and the reference weight. RCO weight interpolation

For rco_allocate.py, omitted --batch-size means 4 sequences per forward on Torch, or max(1, --batch-tokens // sequence_length) on MLX. --batch-tokens defaults to 2048, and an explicit positive --batch-size overrides either default. At least one sequence is used even if it exceeds the token budget; this is batching guidance, not a hard memory cap. Calibration documents must share one length. Token-weighted batches retain the same token-mean objective. Native MLX interpolation stays in the model's weight dtype (including BF16), while teacher entropy is computed once outside the repeated KL step; the KL objective is unchanged.

Measured on Llama 3.2 1B under the legacy block-decision preset (16 blocks, {W2, W3} options, held-out NLL on all 128 validation sequences): both budgets are hit exactly — 2.3750 and 2.6250 bpp, max constraint drift 9.5e-7, with the paper's 6-of-16 and 10-of-16 promotions — but the allocation does not beat a uniform mix: RCO 2.375 gives NLL 5.157 and 2.625 gives 4.631, versus 5.808 for uniform W2 and 3.835 for uniform W3, which is worse than a linear interpolation of those endpoints (+0.089 and +0.056 NLL). The paper's near-W3 accuracy at 2.37 bpp depends on the per-layer sensitivity structure of 8B/70B models, which a 1B model with 16 near-uniform blocks does not have. Context and next steps: docs/experiments/gsq-paper-reproduction.md.

Projection discovery and complete assignments

discover_blocks() and discover_projections() in gptqmodel/quantization/rco.py resolve allocatable projections from the model definition, not a hard-coded seven-name Llama list or numeric-path heuristics. Pass a loaded BaseQModel wrapper to use its effective module tree and quantize config; a bare Torch model requires an explicit model_definition subclass of BaseQModel. The shared tree parser honors decoder # boundaries, exclusion/capture tags, aliases, expert placeholders, and model-specific layer/module hooks. Input/output embedding objects and negative dynamic matches are excluded.

Only declared, live nn.Linear or staged TorchLinear leaves are allocatable. Non-strict definitions may omit optional alternatives in heterogeneous blocks; missing required leaves, unsupported declared leaf types, skipped decoder blocks, empty inventories, or missing definitions raise instead of falling back to guessed projection names. Extra attention projections, such as Ripple's self_attn.g_proj, are included when declared. Discovery support does not extend the separate dense-Llama/Qwen3 GSQ training or MLX search architecture gates.

rco_allocate.py, rco_materialize.py, and staged export share this inventory. Materialization independently validates that the assignment covers every declared projection of every decoder block, accepts only W2/W3/W4, checks each arm's block index/width/group size, and rejects disagreement in shared non-projection block state. Old partial assignments must be regenerated; the assignment payload is not its own completeness authority.

Format-aware allocation for AWQ, EXL3, and GGUF

gptqmodel/quantization/rco_formats.py and scripts/gsq_paper/rco_format_allocate.py provide a separate measure → allocate → quantize workflow. All three adapters use measured reconstruction errors (search="reconstruction"), not Gumbel interpolation, teacher KL, or GSQ training. Lower error receives a higher solver score. A reconstruction allocation is not a downstream perplexity guarantee.

Method Default option set Packing and runtime constraints
AWQ W2, W3, W4 (--options 2,3,4) GEMM format; non-W4 modules need BACKEND.AWQ_TORCH. RCO options are a subset of AWQ's 2/3/4/8 config widths. Complete input groups and output width divisible by 8 are required.
EXL3 K2, K3, K4 (--options 2,3,4) Integer trellis depths; both feature dimensions divisible by 128. Native EXL3 quantization requirements still apply.
GGUF iq2_xxs,iq2_xs,iq2_s,q2_k,iq3_xxs,q3_k,q4_k,q5_k,q6_k Registered GGML aliases; cost includes block metadata and input-row padding. Dynamic entries preserve both width and subtype.

AWQ/EXL3 option overrides must be unique subsets of their default 2/3/4 widths. GGUF can use other supported aliases. For example, run from the source checkout:

python scripts/gsq_paper/rco_format_allocate.py measure \
    --method awq --model /path/to/dense-model --out /path/to/awq-scores.json \
    --options 2,3,4 --group-size 128 --no-sym --device cuda:0
python scripts/gsq_paper/rco_format_allocate.py allocate \
    --method awq --scores /path/to/awq-scores.json --target-bits 2.5 \
    --out /path/to/awq-plan.json
python scripts/gsq_paper/rco_format_allocate.py quantize \
    --method awq --model /path/to/dense-model --plan /path/to/awq-plan.json \
    --calibration /path/to/calibration.json --device cuda:0 \
    --out /path/to/mixed-awq

measure scores every option for each definition-declared projection. AWQ uses its affine pseudo-quantizer, GGUF round-trips through its GGML packer/dequantizer, and EXL3 invokes its native quantizer. AWQ measurement is a weight reconstruction proxy, not the final activation-aware scale/clip search. The default metric is squared relative Frobenius error; --hessian supplies a .pt dictionary of input second-moment matrices, one per measured module, and selects relative_hessian scoring against the original matrix. Each Hessian must be [in_features, in_features].

The relative reconstruction score divides by the actual positive reference energy. A zero reference energy with zero error scores zero. With nonzero error, the ratio is infinite and the runner rejects the score. RCO metrics

Runner options and validation

Flag Default / behavior
Positional stage Required: measure, allocate, or quantize.
--method Required: awq, exl3, or gguf; must agree with scores/plan.
--out Required output JSON path for measure/allocate, or checkpoint directory for quantize.
--options Comma-separated widths/aliases; the defaults are listed above. At allocate, an explicit list must match measured column order.
--target-bits 2.5; allocation budget in packed projection-weight bits per original parameter.
--group-size, --sym / --no-sym AWQ measure defaults: 128 and symmetric True. Later stages inherit measured settings; explicit disagreement raises.
--device, --dtype cuda:0, bfloat16. AWQ/GGUF scoring moves weight matrices to CPU; EXL3 uses the requested device's native quantizer. This is not a promise of CPU support for every final quantization method.
--hessian Optional Torch weights-only .pt input-second-moment dictionary for measure; must cover every measured module.
--limit 0 (all modules); positive values measure a prefix for experiments only. Partial-inventory plans cannot be quantized.
--resolution 0 (automatic DP resolution); positive overrides are capped to the DP memory budget.
--calibration Quantize-stage corpus: a JSON list, a JSON object with texts/text, or nonempty text lines. Supply representative calibration for methods that require it; GGUF keeps its weight-only lifecycle.

--model supplies the dense source for measure/quantize, --scores supplies measure JSON for allocate, and --plan supplies allocation JSON for quantize. --scores also accepts comma-separated files to combine option columns, but their method, settings, metric, parameter counts, shapes, and module coverage must agree; option labels must remain canonical and unique.

Budget scope and saved plan

The runner uses shape-aware costs: AWQ counts packed words, packed zero points, and FP16 group scales; EXL3 counts trellis bits, input/output scale vectors, and applicable codebook markers; GGUF counts complete padded GGML blocks. Budgets exclude biases, embeddings and other unquantized state, and container overhead — they are not a cap on the final directory size. The library API without shapes uses nominal per-option costs instead, and marks the plan accordingly.

The discrete solver minimizes additive reconstruction error under the discretized budget. Automatic resolution starts at max(256, 64 * module_count) and is capped by a 1 GiB DP-table budget. Any overspend caused by cost rounding is repaired using float64 costs; the achieved cost may be below the target, and an infeasible target below the cheapest assignment raises. This differs from the continuous equality constraint in the differentiable staged search.

Versioned score/plan JSON records settings, option labels, module shapes/counts, metric, assignment, per-module costs, achieved budget, dynamic, and any runtime note. RCOPlan.from_dict() revalidates the assignment, settings, costs, and budget. Before quantizing, the runner checks complete coverage against the freshly loaded model definition and verifies matrix shapes; rerun measure without --limit if coverage is partial. It then runs ordinary method quantization and save_quantized(), not staged-arm materialization. Mixed-width AWQ explicitly requests BACKEND.AWQ_TORCH; use that backend again when loading the checkpoint.

Configuration reference

GSQConfig

Field Declared type Declared default Meaning and validation
enabled bool False Master switch; must be bool. None/absent disables refinement entirely.
steps int 100 Requested refinement budget; integer >= 1. GPTQ caps hard search internally and pads diagnostic history after early convergence.
candidates int 33 Candidate count for relaxed adapters and candidate-bank budgeting; integer >= 2. GPTQ's hard search uses immediate code neighbours.
seed int 7 Refinement RNG seed for sampled adapters; integer >= 0. GPTQ's hard search does not sample logits.
learning_rate float 0.1 Relaxed-adapter optimizer rate; finite positive. Unused by GPTQ's hard search.
temperature_start float 1.0 Initial relaxed-adapter Gumbel-Softmax temperature; finite positive. Unused by GPTQ's hard search.
temperature_end float 0.1 Final relaxed-adapter temperature; finite positive. Unused by GPTQ's hard search.
max_candidate_bytes int 64 * 1024**2 Candidate-bank byte budget per output-row chunk; integer >= 1. Not a total-memory cap.
learn_scales bool False Tune stored scales where the method permits; rejected for QQQ and Paro.
modules Optional[Tuple[str, ...]] None Nonempty sequence of PCRE regular expressions restricting refinement to matching module full names; each pattern must compile.

Configs accept a GSQConfig, a dictionary (normalized to GSQConfig), or None.

GSQTrainingConfig

Field Declared type Declared default Meaning and validation
enabled bool False Master switch; must be bool.
initializer str 'gptq' gptq, rtn, or awq. GPTQ export requires gptq/rtn; AWQ export requires awq.
optimizer str 'lion' lion or adamw.
seed int 7 Training RNG seed; integer >= 0.
epochs int 20 Reconstruction epochs per stage; integer >= 1.
batch_size int 64 Documents per training batch; integer >= 1.
microbatch_size int 2 Microbatch documents; integer >= 1 and <= batch_size.
qk_steps int 2000 Update steps for the Q/K stage; integer >= 1.
damp_percent float 0.01 Hessian damping fraction for staged fitting; finite nonnegative.
assignment_lr float 1e-4 Assignment (logit) learning rate; finite and > 0.
scale_lr float 5e-5 Scale learning rate; finite and > 0.
weight_decay float 1.0 Optimizer weight decay; finite nonnegative.
betas tuple[float, float] (0.9, 0.95) Two optimizer moments, each in [0, 1).
temperature tuple[float, float] (2.0, 0.05) (start, end) sampling temperature endpoints; both positive.
multiplier tuple[float, float] (100.0, 500.0) (start, end) logit-scale multiplier endpoints; both positive.
warmup_steps int 0 LR warmup steps; integer >= 0.
min_lr float 0.1 Final LR fraction of peak; finite, <= 1.
decay str 'cosine' LR decay: cosine, linear, or constant.
restore_best bool | None None Best-validation-epoch export; see table above. None is auto.

training_kwargs() drops enabled and renames damp_percent to qk_damp_percent for the fitting entry points. to_dict() re-validates before serializing.

Serialization, diagnostics, and saved metadata

When a gsq/gsq_training option is set, to_dict() writes it into the quantize config payload:

Key Emitted by
gsq GPTQ, AWQ, RTN, QQQ, and Paro configs when gsq is not None (as a plain dict).
gsq_training GPTQConfig and AWQConfig when set, via GSQTrainingConfig.to_dict().

A staged run additionally records meta["gsq_training"] (per-block run metrics) and meta["gsq_training_recipe"] = "experimental_staged_llama_v1" in the saved checkpoint, and the model wrapper exposes gsq_training_run["blocks"]. A non-uniform run also records meta["gsq_layer_bits"] (the {layer_index: width} map) and publishes per-projection dynamic entries for blocks not at the base width. Per-module refinement leaves gsq_diagnostics in module state — before/after objective values, learn_scales, or a skipped status with its reason. These diagnostics are provenance, not a quality guarantee: a recorded after below before is a local-objective improvement, not evidence of better downstream accuracy.

Paper reproduction scripts and measured results

scripts/gsq_paper/ reproduces the paper's staged-GSQ comparison (App. G.1) on a single Llama 3.2 1B Instruct checkpoint — a GPTQ-only arm versus a GPTQ-initialized arm that also runs staged reconstruction training:

python scripts/gsq_paper/build_corpus.py --model meta-llama/Llama-3.2-1B-Instruct \
    --out /models/datasets/gsq-paper
scripts/gsq_paper/run_all.sh --model meta-llama/Llama-3.2-1B-Instruct \
    --corpus /models/datasets/gsq-paper --out /models/gsq-paper-out \
    --gpus 0,1,2,3,4,5 --bits "2 3 4"
python scripts/gsq_paper/compare_arms.py --corpus /models/datasets/gsq-paper \
    --models /models/gsq-paper-out/w{2,3,4}-gsq-s7/model \
             /models/gsq-paper-out/w{2,3,4}-gptq-s7/model \
    --dense meta-llama/Llama-3.2-1B-Instruct --n 128

Measured against matched GPTQ baselines on that model (group size 128, full 4096/512/128 splits, 20 epochs, 2000 Q/K steps): W2 −3.395 NLL / +1.19 avg accuracy, W4 −0.537 NLL / +0.30, while W3 is noise-dominated at this scale — three runs straddle the GPTQ baseline within a 0.219-NLL spread against a nominal 0.05 effect, below the evaluation's resolution. Documented deviations: the paper's final 2-bit scale-only end-to-end stage is absent (from both this implementation and the released reference), Q/K is fit on the GPTQ-initialization split rather than the training split, and the paper's Llama 3.1 8B/70B absolute numbers do not transfer to a 1B model. The scalar relaxation's scale-gradient backward reduces as a segment sum when the group map is contiguous — the standard staged case — and the collision-prone scatter_add_ remains only for non-contiguous maps. run_arm.py --deterministic still enables torch.use_deterministic_algorithms(True) (off by default) for bit-identical Q/K reruns.

For distributed and memory-bounded runs, run_arm.py additionally exposes --device (default cuda:0), --distributed (requires a torchrun launch with at least two ranks; --batch-size stays the global batch and must divide world size, and --microbatch must fit the local batch), --target-cache none|cpu|device, --activation-checkpointing, --reuse-capture, and --resume-prefix-from PATH (explicit compatible-prefix import; requires --resume). See Distributed execution and activation reuse for their semantics.

run_distributed_pair.sh is the detached driver behind the paper-model Llama 3.1 8B reproduction: it runs two independent four-rank torchrun arms (W2 and W3 on separate GPU groups) against the full 4096/512/128, 20-epoch, 2000-Q/K-step budget, imports each arm's completed prefix, mirrors checkpoints while training, and then runs the RCO allocation/materialization and NLL comparison jobs. Its arguments are MODEL CORPUS OUTPUT MIRROR ORIGINAL_ARMS, and status.txt, driver.pid, and per-arm run.log/exit-code.txt expose progress.

bench_distributed_stage.py times complete MLP-stage updates against real 8B weight shapes. Measured on an MI350X with global batch 64 × 4096 tokens, microbatch 16, BF16 weights/activations/logits, device-cached targets and activation checkpointing (synthetic activations, RTN initialization):

Ranks W2 ms/update W3 ms/update
1 394.16 345.23
2 259.06 248.89
4 139.47 137.21

An eight-rank correctness run against an independent float64 oracle reports max absolute error 4.4e-16 (W2) and 2.7e-15 (W3) across losses, gradients, parameters, and optimizer state. These are update-timing and numerics results, not completed-model quality claims; the full 8B GSQ reproduction remains pending. Details: docs/experiments/gsq-paper-reproduction.md.

The same harness covers the paper's non-uniform budgets via rco_allocate.py/rco_materialize.py; see Non-uniform bit allocation (RCO) for usage and measured results.

Full recipe tables, per-document analysis, and statistical-power notes: docs/experiments/gsq-paper-reproduction.md and docs/experiments/gsq-paper-budget-1b-w3.md.

Pitfalls and edge cases

  • gsq and gsq_training cannot both be enabled on one config; staged and per-linear are separate paths.
  • GSQ requires enabled configs: a GSQConfig() default (or gsq set without enabled=True) is accepted but does nothing.
  • Refinement increases quantization time and allocates temporary/candidate tensors beyond max_candidate_bytes; relaxed adapters also allocate optimizer state.
  • The GPTQ staged shortcut runs inside quantize() before the ordinary looper; ordinary transforms and adapters are rejected, not silently applied. Passing calibration-free options or adapter arguments raises.
  • The public staged GPTQ shortcut now runs inside quant_blas_backend(deterministic=True), including calibration/Hessian construction, just like the ordinary GPTQ path. On ROCm this avoids an unpinned hipBLASLt path; the previous backend is restored after success or failure. This backend scope is separate from run_arm.py --deterministic and is not a cross-device bitwise-reproducibility guarantee.
  • A dynamic map on the staged path is a width assignment, not a general override: model.layers.<n> block names setting only bits. Per-projection overrides must go through the internal bits dicts instead, and any other dynamic shape raises.
  • FP8 is load-only and no longer has a GSQ adapter.
  • GPTQ local GSQ needs calibration activations, calibrated nn.Linear modules, and rejects tensor-parallel padded projections; data-independent fallback skips refinement rather than failing.
  • Staged GSQ validates resumable block checkpoints by capture metadata; checkpoint payloads are version-tagged, so resumes must match the producing configuration. Checkpoints additionally hash their packed predecessors, and gaps or changed predecessors are rejected before training; only an explicit resume_prefix_directory import may relax device, world size, target_cache, and activation_checkpointing.
  • An accepted config is not a quality promise: the README's measured gains are model- and data-specific, and the paper recipe is only partially reproduced here.

Source files

See also

  • GPTQ — the initializer and scalar export format GSQ refines.
  • AWQ, QQQ, Paro — other methods with GSQ adapters.
  • EXL3, GGUF — native formats supported by the separate reconstruction allocator.
  • QuantizeConfig Reference — gsq/gsq_training fields and dynamic per-layer overrides.
  • Quantization Lifecycle — where staged GSQ dispatches in quantize().
  • EoRA — a different, adapter-based accuracy-recovery approach.

Clone this wiki locally