Repository navigation
ParoQuant
🏠 Home · 🧭 Choose a method · 🚀 Quickstart · 🧰 Help
On this page
Learn a better coordinate system before storing four-bit weights. For: readers willing to spend calibration-time optimization on rotations and scales, then deploy a checkpoint whose runtime preserves those transforms.
Paro quantizes linear weights in a learned, pairwise-rotated coordinate system. Calibration optimizes Givens-rotation angles and channel scales, then fine-tunes weights and quantizer parameters against floating-point reconstruction targets. Inference rotates activations and multiplies them by packed, transformed-domain weights.
The method is METHOD.PARO ("paro"); its checkpoint format is FORMAT.PARO ("paro"). It is not an ordinary AWQ checkpoint, even though its integer weights use AWQ packing: the rotations and channel scales are part of the model and must be loaded with the weights.
Migrating from ParoQuant: new checkpoints publish method, quant_method, and format as "paro". The config loader still accepts legacy "paroquant" method/format metadata and normalizes it to Paro; this is checkpoint compatibility, not an alias for every old Python identifier. Use ParoConfig for quantization, BACKEND.PARO_CUDA / BACKEND.PARO_TRITON (or BACKEND.PARO, the CUDA alias) for inference, and ParoCUDAConfig / ParoTritonConfig from gptqmodel.backend for typed backend settings. Kernel/runtime settings now use the paro_* prefix, and source modules live under paro rather than paroquant. This page retains its original URL so existing links keep working.
Configuration and backend distinctions on this page are checked against 0c280a465. The method originates in ParoQuant research and the Z-Lab implementation. A declared backend is not a quality or speed qualification for every accelerator.
| Your goal | Start here |
|---|---|
| Choose and understand | The decision table below; compare methods and dtypes |
| Use it | Quantize, save, and reload |
| Go deeper | Concepts · Optimization and runtime reference · Troubleshooting |
| Choose this when… | Consider another path when… |
|---|---|
| You want to learn pairwise rotations and channel scales from calibration outputs | You want a simpler scalar checkpoint without a learned runtime transform: compare GPTQ and AWQ |
| You can afford two train-style optimization stages and measure held-out quality | You need direct weight-only packing with no activation capture: see GGUF |
| Your runtime loads Paro weights and rotation side tensors | Your engine only accepts ordinary AWQ/GPTQ; matching INT4 packing alone is insufficient |
- Install GPT-QModel, use a supported source model, and prepare representative calibration data. The Llama example may require accepting the model license and authenticating with Hugging Face.
- Plan for four-bit,
sym=Trueexport. Groups must divide the input width and have even width; packed output width must be divisible by eight. Native NVIDIA CUDA and MLX add narrower shape requirements. - Start with
opt_scope="module"so the unit of optimization is clear. Broader scopes use whole-layer targets and have different activation-memory costs, not simply more parallelism. - Pick the runtime for your actual hardware. Native NVIDIA CUDA, explicit AMD ROCm Triton, portable fallbacks, and Apple Silicon MLX are distinct paths; see Backend reference.
Reading the diagram: Independent optimization and execution concerns. Grouped scopes use layer replay objectives; zero epochs skip updates, not export. Packing is not a resume checkpoint.
Text version of the workflow
- Module-scope optimization: Capture activation rows → Learn angles and scales → Fine-tune quantization → Pack runtime state.
- Packed inference: Scale input channels → Apply learned rotations → Evaluate packed weights → Restore output shape.
Use representative calibration text or the supported tokenized calibration inputs described in Quantization lifecycle. This example deliberately supplies the important choices rather than relying on unrelated base-configuration defaults:
from datashoal.hf_compat import load_dataset
from gptqmodel import CalibrationConfig, GPTQModel
from gptqmodel.quantization import ParoConfig
dataset = load_dataset(
"allenai/c4",
data_files="en/c4-train.00001-of-01024.json.gz",
local_only=False,
split="train",
streaming=True,
)
calibration = [row["text"] for row in dataset.take(128)]
qcfg = ParoConfig(
bits=4,
group_size=128,
device="cuda:0", # NVIDIA CUDA example.
sym=True,
krot=8,
opt_scope="module",
opt_quantizer_impl="reference",
)
model = GPTQModel.load("meta-llama/Llama-3.2-1B", quantize_config=qcfg)
model.quantize(CalibrationConfig(dataset=calibration, batch_size=1))
model.save("llama-paro")from gptqmodel import BACKEND, GPTQModel
model = GPTQModel.load(
"llama-paro", device="cuda:0", backend=BACKEND.PARO_CUDA,
)
tokens = model.generate("Capital of France is", max_new_tokens=32)[0]
print(model.tokenizer.decode(tokens))On ROCm, AUTO prefers the Triton runtime when it passes the backend checks. To select it explicitly on NVIDIA CUDA or ROCm, request BACKEND.PARO_TRITON. See the backend reference for group, dtype, and platform requirements. On supported Apple Silicon systems, use the MLX backend described in MLX on Apple Silicon. The opt_stage_impl, opt_pair_impl, and opt_quantizer_impl fields choose calibration implementations independently of the inference backend.
Reload through GPTQModel.load, generate a sanity check, and compare held-out quality with the dense source in Evaluation. The sample count above is an API recipe, not a guarantee of adequate coverage. Preserve pairs, theta, channel_scales, and the Paro config alongside the packed weights.
If optimization exceeds memory, keep module scope first and distinguish calibration-forward batches from optimizer row minibatches. Then consult the scope guide below before increasing scope or enabling activation checkpointing. Neither lower optimizer loss nor successful serialization proves compatibility with another inference engine.
For every group of input channels, a rotation stage divides channels into disjoint pairs. For one pair with values a, b and angle θ, the reference implementation computes:
Stages are applied in order. The inverse reverses stage order and negates the angles. Pair indices are local to each group, not global feature indices. Groups must have even width, and the input width must be divisible by that width. group_size=-1 is normalized to the complete input width.
krot is the number of stages. opt_pair_ratio determines the number of active disjoint pairs per group; unused channels are filled with dummy pairs whose angles stay zero. The fast schedule uses randomized permutations of a round-robin pairing template; the reference schedule uses its separate pair-selection/alignment implementation. These are selectable implementations, not a guarantee of identical random schedules.
Let R denote the combined orthogonal row-vector rotation and D the diagonal matrix of bounded, learned channel scales. For row-vector activations X and weights W in (out_features, in_features) order, the optimizer forms:
Without quantization, XᵣWᵣᵀ = XWᵀ. With transformed-domain pseudo-quantization Q, the replayed linear is:
The equivalent weight in the original input coordinate system is Q(Wᵣ) Rᵀ D⁻¹. The processor uses this pseudo-weight during calibration replay, but packs Q(W_r) for runtime. The saved channel_scales are the reciprocal runtime scales D⁻¹, not the unconstrained optimization parameter channel_scales_opt.
_RoundSTE rounds in the forward pass and passes its gradient through unchanged. _ClampSTE clamps forward values but also passes gradients through. Consequently, optimization can update weights, angles, channel scales, and learned quantizer parameters despite rounding and clipping.
Two quantizer implementations must be distinguished:
opt_quantizer_impl |
Internal transformed-weight quantizer |
|---|---|
"reference" (configuration default) |
_quantizer_sym_for_impl returns False: affine quantization with a floating zero-point parameter. |
"fast" |
Preserves sym; with the required sym=True, uses signed symmetric quantization. |
The public Paro configuration requires sym=True; setting sym=False is not how to select the affine reference path. Four-bit symmetric quantization uses signed codes from -8 to 7, then exports an unsigned packed representation with zero point 8. Affine quantization uses unsigned codes from 0 to 15. Quantizer scales are bounded to [1e-5, 1e5]; these bounds are separate from the configurable channel-scale bounds.
For module scope, let Y_fp = X W₀ᵀ + b be the frozen floating-point target for calibration rows X, where W₀ is the original weight. Let W̃ be the optimization weight, D the positive bounded channel-scale matrix, and R the learned pairwise rotation. With transformed-domain pseudo-quantizer Q_φ, the prediction is
The stage runners minimize mean smooth-L1 reconstruction error. For residual entries eⱼ = Ŷⱼ − Y_fp,ⱼ and M compared output elements, the default loss is
The rotation stage updates angles/scales with a pseudo-quantizer; the fine-tuning stage holds the rotation parameters fixed and updates weights/quantizer parameters. STE supplies surrogate gradients through rounding/clipping, so this is not exact differentiation of an integer optimization problem. Grouped scopes compare replayed layer outputs instead of independent linear outputs. See the module optimizer and grouped runners.
opt_scope |
Objective and orchestration | Gradient checkpointing with opt_gradient_checkpointing=None
|
|---|---|---|
"module" |
Each linear independently reconstructs its own floating-point output. | Off. |
"compute_block" |
Optimize selected linears together inside a replayed layer against preserved layer outputs. | Off. |
"layer" |
Optimize the selected linears of an entire layer together against preserved layer outputs. | On. |
Compute-block buckets are attn_qkv (q_proj, k_proj, v_proj), attn_o (o_proj), mlp_gate_up (gate_proj, up_proj), and mlp_down (down_proj). Other names receive individual single:<module_name> buckets. These names are implementation buckets, not additional opt_scope values.
Set opt_scope on ParoConfig. With "module", a dynamic rule can override optimizer fields such as opt_batch_size, opt_rotation_lr, or opt_finetune_epochs for one projection. With "compute_block" or "layer", set shared optimizer and training controls on ParoConfig because the group uses one optimizer and dataset. A rule that tries to set a shared control or change opt_scope raises ValueError. Grouped scopes still honor per-module settings such as krot, opt_pair_ratio, opt_seed, and channel-scale clamps.
opt_gradient_checkpointing trades recomputation for activation memory during optimization. It does not save progress for resuming a run, and neither a best-state snapshot nor model.save() is a quantization continuation checkpoint. See Quantization Lifecycle for the separate continuation API.
from gptqmodel.quantization import ParoConfig
qcfg = ParoConfig(
bits=4,
group_size=128,
sym=True,
opt_scope="layer",
opt_gradient_checkpointing=True,
opt_best_state_dtype="bf16",
)A lower-precision best-state snapshot reduces snapshot storage but rounds the state that will be restored. It does not change the packed bit width. opt_train_samples and opt_validation_samples count flattened activation/token rows, not dataset records. In module scope, opt_batch_size splits these rows into optimization minibatches independently of CalibrationConfig.batch_size. The accuracy-tuned default is 64 rows. Larger minibatches reduce optimizer steps per epoch without dropping rows; validate quantization quality if you raise it for speed.
Paro samples oversized per-module captures as each calibration batch arrives. It flattens each nonempty capture into token rows before joining batches, so a shorter sequence or a change in how many tokens reach a routed expert no longer discards every capture after the first. The assembled per-module features are capped at opt_train_samples + opt_validation_samples rows (2,112 with the defaults). Grouped optimization also keeps separate replay context, so this cap applies to the captured module features. Paro capture source
Grouped scopes retain complete cached layer-forward batches. Training uses the smallest nonempty prefix meeting the training-row budget; validation uses the smallest nonempty suffix meeting the validation-row budget. These selections can exceed the budgets and can overlap. Grouped runners do not split batches using opt_batch_size: their optimizer steps follow the captured forward batches, so the calibration forward batch size and sequence length directly affect optimization memory.
All scopes, including the default opt_scope="module" on Torch and MLX, multiply the configured rotation, weight, and quantizer learning rates by max(1, opt_batch_size / 64). At or below 64 the configured rates are unchanged.
Per-module dynamic rules can set a coverage threshold, for example {"fallback": "1.0%"}. The coverage check reads the resolved threshold for each module, and the packed Paro layer uses the same resolved krot and kernel as the module's quantization recipe. A field set to None in a rule inherits its top-level value. Paro processor
On the Torch path, Paro compares each module's captured token rows with fallback.threshold before sampling for the optimizer. The default is "0.5%" of calibration tokens; a number sets an absolute row count. The comparison is strict: a module that reaches the threshold does not trigger this fallback. For example, with Fallback(threshold=64), 63 captured rows trigger fallback and 64 do not.
Below the threshold, Paro skips learned rotation and fine-tuning for that module and packs round-to-nearest weights with identity rotations in the usual Paro format. It uses RTN regardless of the configured fallback strategy. This applies to all opt_scope values: in "compute_block" and "layer" scopes, modules that meet the threshold remain in the group optimization. Set fallback=None to disable the coverage check and make missing activations an error. See the processor source.
ParoConfig is defined in gptqmodel/quantization/config.py and inherits the shared preprocessor/quantization configuration. See QuantizeConfig reference for shared fields such as bits, group_size, dynamic, device selection, and offload settings. The following are the fields declared specifically by ParoConfig.
| Field | Declared type | Default | Meaning / validation |
|---|---|---|---|
method |
METHOD |
METHOD.PARO |
Paro method. |
format |
FORMAT |
FORMAT.PARO |
Only Paro export format; ParoConfig.__post_init__ rewrites another recognized format to this value. |
krot |
int |
8 |
Positive rotation-stage count. |
opt_rotation_epochs |
int |
10 |
Non-negative rotation/channel-scale stage epochs. |
opt_finetune_epochs |
int |
10 |
Non-negative weight/quantizer stage epochs. |
opt_train_samples |
int |
2048 |
Positive training-row budget. |
opt_validation_samples |
int |
64 |
Positive validation-row budget. |
opt_batch_size |
int |
64 |
Positive row minibatch size in module scope; affects learning-rate scaling in every scope, but does not split grouped batches. |
opt_rotation_lr |
float |
0.05 |
Positive angle and channel-scale learning rate. |
opt_weight_lr |
float |
1e-5 |
Positive weight learning rate. |
opt_quantizer_lr |
float |
1e-6 |
Positive learned-quantizer learning rate. |
opt_pair_ratio |
float |
0.5 |
Must satisfy 0 < value <= 0.5. |
opt_seed |
int |
0 |
Base seed for deterministic module-specific schedules. |
opt_scope |
str |
"module" |
"module", "compute_block", "layer". |
opt_train_on_noisy_inputs |
bool |
False |
Grouped scopes may train on propagated quantized/noisy inputs against clean floating-point targets. Not enabled for module scope. |
| Field | Declared type | Default | Meaning / validation |
|---|---|---|---|
opt_optimizer |
str |
"adamw" |
"adamw", "adam", or "sgd". |
opt_weight_decay |
float |
0.01 |
Non-negative. |
opt_betas |
Tuple[float, float] |
(0.9, 0.95) |
Two Adam-family coefficients, each in [0, 1). |
opt_eps |
float |
1e-10 |
Positive Adam-family epsilon. |
opt_amsgrad |
bool |
False |
Adam-family AMSGrad option. |
opt_sgd_momentum |
float |
0.0 |
Non-negative SGD momentum. |
opt_sgd_dampening |
float |
0.0 |
Non-negative SGD dampening. |
opt_sgd_nesterov |
bool |
False |
Requires positive momentum and zero dampening. |
| Field | Declared type | Default | Meaning / effective behavior |
|---|---|---|---|
opt_fused_rotation |
bool |
True |
Request native fused rotations when eligible. Not a guarantee that every scope/device uses them. |
opt_gradient_checkpointing |
Optional[bool] |
None |
Scope-dependent resolution above; explicit booleans override it. |
opt_stage_cudagraph |
bool |
True |
Request eligible CUDA-graph stage execution. Full-model module processing explicitly disables per-linear stage graphs to avoid private-pool memory growth. |
opt_amp |
Optional[bool] |
None |
AMP policy for module, compute_block, and layer optimization. None enables AMP on NVIDIA CUDA and leaves it off on ROCm. True requests AMP on PyTorch cuda devices, including ROCm. False disables it on all devices. |
opt_best_state_dtype |
Union[str, torch.dtype] |
"fp32" |
Normalized to "fp16", "bf16", or "fp32" for best-state snapshots. |
opt_stage_impl |
str |
"fast" |
"fast" or "reference" for the standalone/module optimizer stage runner. Grouped processing has its own runners. |
opt_pair_impl |
str |
"fast" |
"fast" or "reference" pair generation. |
opt_quantizer_impl |
str |
"reference" |
"fast" or "reference"; also changes internal quantizer symmetry as explained above. |
opt_channel_scale_clamp_min |
float |
1e-2 |
Positive lower bound for learned channel scales. |
opt_channel_scale_clamp_max |
float |
1e2 |
Positive upper bound; must exceed the lower bound. |
quant_linear_init_kwargs() returns {"krot": self.krot}. Configuration serialization records the Paro optimization controls in metadata; beta values serialize as a list. PARO_EXPORT_FORMATS contains only FORMAT.PARO. Dynamic format overrides are still required to resolve to FORMAT.PARO.
optimize_paro_linear in gptqmodel/quantization/paro/optimization.py:
- Validates symmetry and group size; flattens/subsamples captured activation rows. Oversized input streams are sampled using rounded, evenly spaced indices.
- Makes FP32 optimization weights, activations, and floating-point targets with
F.linear. - Uses a prefix for training and a suffix for validation. With insufficient rows, the two can overlap; this is not an automatically disjoint held-out dataset.
- Creates pair metadata, zero angles, unit channel scales, and a mask for dummy rotations.
- Optimizes only channel scales and angles during the rotation stage.
- Initializes
GroupLinearQuantizerfrom the transformed weight. - Optimizes weights and quantizer parameters during fine-tuning, leaving the rotation parameters inactive.
- Exports pseudo-weights, packing weights, quantization parameters, rotation metadata, and losses.
Stage runners use smooth-L1 reconstruction loss, cosine learning-rate decay toward base_lr / 20, per-epoch validation, and restoration of the best validation state. Dummy angles are reset after updates. Zero epochs skip updates, not necessarily quantization/export work.
The return contract is ParoOptimizationResult: pseudo_weight, pack_weight, q_scales, q_zeros, pairs, theta, channel_scales, train_loss, val_loss, and used_identity. Missing activation rows can produce an identity-rotation quantized result, rather than an unquantized layer; processor-level fallback policy determines whether missing features are accepted.
The low-level asymmetric GroupLinearQuantizer includes zero in each fitted range, rounds a legal zero point, and refits the scale against each side's available codes. This prevents constant or one-sided groups from collapsing under a clamped zero point. FP16/BF16 weights use FP32 range/grid arithmetic and FP32 quantizer parameters; pseudo-quantized outputs retain the weight dtype. Scales are bounded to [1e-5, 1e5] both during pseudo-quantization and in pack_params(), so exported scales match the effective learned grid. A tiny opposite-sign endpoint can still round to zero, and the scale bounds can still saturate extreme values. These numerical fixes do not expand the public backend's sym=True support. See optimization details.
The exact optimizer entry-point signature is:
Developer API signatures (not a runnable example)
def optimize_paro_linear(
*,
weight: torch.Tensor,
bias: Optional[torch.Tensor],
inputs: torch.Tensor,
bits: int,
group_size: int,
sym: bool,
krot: int,
pair_ratio: float,
train_rows: int,
val_rows: int,
batch_size: int,
rotation_epochs: int,
finetune_epochs: int,
rotation_lr: float,
weight_lr: float,
quantizer_lr: float,
seed: int,
optimizer_name: str = "adamw",
optimizer_weight_decay: float = 0.01,
optimizer_betas: tuple[float, float] = (0.9, 0.95),
optimizer_eps: float = 1e-10,
optimizer_amsgrad: bool = False,
sgd_momentum: float = 0.0,
sgd_dampening: float = 0.0,
sgd_nesterov: bool = False,
fused_rotation: Optional[bool] = None,
stage_cudagraph: Optional[bool] = None,
stage_impl: Literal["fast", "reference"] = "fast",
pair_impl: Literal["fast", "reference"] = "fast",
quantizer_impl: Literal["fast", "reference"] = "fast",
gradient_checkpointing: bool = False,
best_state_dtype: Optional[str | torch.dtype] = "fp32",
use_amp: Optional[bool] = None,
scale_clamp_min: float = PARO_OPT_SCALE_CLAMP_MIN_DEFAULT,
scale_clamp_max: float = PARO_OPT_SCALE_CLAMP_MAX_DEFAULT,
) -> ParoOptimizationResult:
...Notice that this low-level function defaults quantizer_impl to "fast", whereas ParoConfig.opt_quantizer_impl defaults to "reference". The processor passes the configuration explicitly.
The reference and fast quantizers cap scale clamp bounds at the scale dtype's finite maximum. For FP16 scales that maximum is 65504. They also bound the chosen symmetric or affine codes before reconstruction so an endpoint outside the source weight dtype's range stays off the replay grid. Paro quantizer implementation
ParoProcessor in gptqmodel/looper/paro_processor.py registers modules, captures their input activations to CPU, tracks subset completion, then quantizes a layer after its capture is complete. It rejects calibration-dataset replacement and requires an initial calibration dataset.
For grouped scopes it preserves layer inputs, kwargs, and clean targets. Replay removes past-key-value caches, disables use_cache, rebuilds position/rotary metadata, and normalizes inference-born tensors so autograd can use them. Compute-block optimization uses layer copies. The dense whole-layer path also trains on a separate FP32 copy, streams CPU-owned replay shards, snapshots the best state on CPU, and uses eager attention on the copy. The trained values are written back in the live weights' dtype. This path applies to recognized dense projection groups, while other layer groups use the general grouped optimizer. Paro processor
Deferred grouped replay resolves the module-tree branch that owns each layer and snapshots that branch's masks and position IDs with the layer state. Both grouped-dataset construction and replay-batch construction use this context, so vision/audio branches do not inherit the first text branch's positions or mask; absent entries remain None.
Layer scope disables fused rotation in its optimizer wrappers.
Module seeds are derived with BLAKE2b from the base seed, layer index, and a name key. Module scope uses the full module name; grouped scopes use the terminal archetype. This is stronger isolation than simply giving every layer the same seed.
Transformers Conv1D projections (such as GPT-2's attention projections) enter module optimization as [out, in] and are written back in their native [in, out] layout before packing. Packing installs ParoLinear, packs the transformed pseudo-quantized weight, copies pairs, theta, and runtime channel_scales, then calls post_init. Finalization marks the model quantized and sets METHOD.PARO. Optional original-versus-quantized residuals can feed a subsequent EoRA processor.
| Source | Role | Requirements / behavior |
|---|---|---|
optimization.py |
Torch round/clamp STE, affine custom-autograd node, group quantizer, optional compiled training quantization | Reference/fallback arithmetic and orchestration. |
modules/triton/affine_ste.py |
Fused affine pseudo-quantization | Optional Triton; selects CUDA or HIP libdevice; ties-to-even rounding and round-to-nearest division. Defaults to a Torch elementwise backward; optional Triton backward still performs group reductions with Torch. |
modules/triton/sym_ste.py |
Fused symmetric pseudo-quantization | Optional Triton; fused forward and Torch backward reductions. |
utils/paro.py |
Native fused rotation and custom backward | Optional JIT extension; supports input, angle, and channel-scale gradients when dispatched through the autograd wrapper. |
KernelConfig.paro_affine_ste_triton and KernelConfig.paro_sym_ste_triton default to enabled. KernelConfig.paro_affine_ste_triton_backward defaults to disabled. Availability probes and wrapper eligibility checks determine whether these accelerators actually run; they are distinct from the inference Triton GEMM kernels.
For a successfully packed four-bit module, let I = in_features, O = out_features, and G be the normalized group size (I for group_size=-1). The AWQ INT4 packer requires O divisible by 8. ParoLinear declares that same alignment for backend selection and rejects incompatible direct construction before packing; every inference path shares this storage constraint.
| Tensor | Meaning / shape |
|---|---|
qweight |
AWQ-layout INT32-packed four-bit transformed weights, (I, O // 8). |
qzeros |
INT32-packed group zero points, (I // G, O // 8). |
scales |
FP16/BF16 group dequantization scales, (I // G, O). |
pairs |
INT16 pair schedule, (krot, in_features). |
theta |
Rotation angles, (krot, in_features // 2). |
channel_scales |
Runtime activation scaling, (1, in_features). |
bias |
Optional floating-point linear bias, (O,). |
Identity state has zero angles and unit channel scales. A loader that only knows AWQ weight packing but ignores these extra tensors does not implement Paro inference.
| Backend / class | Declared support | Execution |
|---|---|---|
BACKEND.PARO_CUDA / ParoLinear
|
4 bits; sym=True; groups -1, 16, 32, 64, 128; INT32 packing; FP16/BF16 inputs; Lora; class declares all devices/platforms |
Rotation followed by eligible AWQ CUDA GEMM, CPU AVX512, CPU ATen, or temporary dense fallback. The backend name does not mean every call uses a CUDA kernel. |
BACKEND.PARO_TRITON / ParoTritonLinear
|
CUDA and ROCm device types; Linux/Windows; Triton >=2.0.0, or >=3.4.0 with GIL disabled; inherits four-bit/symmetry/dtype/adapter declarations |
Autotunes decode-fused, prefill-fused, and temporary-dequantize-plus-matmul plans. Low-level GEMM helpers accept groups 32, 64, 128 or full width; group 16 is inherited at class level but not supported by those helpers. |
BACKEND.MLX / MlxParoLinear
|
MLX/Metal implementation for Apple Silicon | MLX quantized matmul after staged or fused Metal rotation; returns the activation dtype. See MLX on Apple Silicon for loader requirements. |
On ROCm, AUTO prefers PARO_TRITON when it passes validation, ahead of the portable ParoLinear dense fallback. On NVIDIA CUDA, PARO_CUDA remains the first choice. You can request BACKEND.PARO_TRITON explicitly on either supported GPU family. The Triton GEMM has separate Ada (RTX 4090 / SM 8.9) and RDNA4 launch tables, with decode/medium/prefill row bands. See the hardware tuning contract and backend selection code.
ParoLinear.forward flattens leading activation dimensions, rotates inputs, evaluates the quantized projection, applies an optional adapter to the original unrotated input, and restores the output shape. Dense dequantization is temporary; it is not a persistent dense-weight cache.
For explicit GPU graph capture of the portable dense forward, warm up on the target device before capture. The AWQ unpacker creates and caches its shift offsets on-device, eliminating the host-to-device copy that previously prevented capture on this path.
ParoLinear.clear_weight_cache() clears packed-weight and rotation-derived state and recomputes whether theta/channel_scales describe an identity rotation. After manually editing unversioned inference-mode rotation tensors, call it before forwarding so an old identity shortcut cannot skip the new rotation. Meta/offloaded rotation buffers disable the shortcut until a materialized load or move clears the cache again. State loading and device/dtype moves use the same invalidation path.
The identity shortcut requires both theta and channel_scales to be frozen. Trainable rotations run even under torch.no_grad(), so evaluation sees optimizer updates rather than a cached identity; with gradients enabled they also preserve parameter gradients at identity.
Triton decode/prefill kernels add bias in their FP32 accumulator before the final output conversion; dense execution uses the shared wide matmul/bias helper. If rotated inputs or bias require gradients, plan selection and execution force the differentiable dense route, preserving input/rotation and bias gradients rather than choosing an inference-only fused kernel. See numeric epilogues and input gradients.
The native NVIDIA AWQ route has a narrower contract than packed storage: four-bit weights, G % 32 == 0, O % 64 == 0, and O % G == 0; BF16 additionally requires compute capability >=8.0 on the selected device. ROCm does not enter this CUDA extension. Unsupported shapes/devices fall through to another eligible route instead of triggering native assertions. Split-K partials and dense reductions stay FP32 through bias addition, then cast once to the input dtype, avoiding FP16 overflow before cancellation.
Eligible native NVIDIA inference switches from split-K AWQ GEMM to call-local weight reconstruction and cuBLAS at a projection-specific row count. The cutoff accounts for aspect ratio, total weight size, and narrow output widths. It is clamped to 768–4,096 flattened rows and is 1,342 rows for a 4,096 × 4,096 projection. This is a shape heuristic tuned on SM 8.9, not a runtime benchmark. The fused CUDA rotation and the Triton prefill kernel use 64-bit row offsets for large activations and outputs. See native prefill dispatch and the fused rotation code.
When gradients are enabled and the input, theta, or channel_scales requires gradients, the module uses the autograd-aware rotation. On CUDA, a gradient-bearing rotated input takes the differentiable dense matmul path rather than the native AWQ GEMM; ParoTriton likewise selects its differentiable path when needed. No-grad inference still uses the eligible packed kernels. See the module training path.
CPU execution keeps one live packed layout per layer: AVX512 or ATen int4pack. The live qweight/qzeros buffers hold that layout; checkpoint words are reconstructed through a verified inverse for state_dict() and saving. Switching layouts, moving device/dtype, entering training, eager dense fallback, or loading state restores checkpoint layout first. A traced dense fallback instead reads the saved checkpoint operands without rewriting the live buffers. clear_weight_cache() invalidates derived rotation/legacy caches while retaining an authoritative live CPU layout. Scales and bias retain their checkpoint dtype; the AVX512 call widens them to FP32 temporarily. See CPU layout ownership.
For biased CPU ATen execution, int4pack returns an FP32 product so bias is added before output narrowing. Triton decode/prefill forwards the module's snapshotted fp32_accum setting into GEMM rather than reading a later process-global value; standalone GEMM helpers retain the global fallback when no setting is supplied.
Non-identity CPU rotations can trace with Inductor. Model- and layer-level optimize() prepare eligible eval-mode AVX512 or ATen layouts before tracing. A direct cold fullgraph=True trace skips layout setup and uses a traceable fallback if no packed path qualifies. Warm up eagerly or use optimize() to prepare the packed path before tracing. A prepared ATen layout supports biased FP16 or BF16 calls when the activation dtype matches the prepared layout. Explicit CPU compilation remains opt-in. See CPU kernel compilation limits.
On supported NVIDIA setups, a non-identity ParoTritonLinear layer can trace with torch.compile(fullgraph=True) and run with CUDA graphs. The fused rotation exposes tensor metadata to tracing, and compiled calls use cached or default launch plans without timing kernels or reading the tuning cache from disk. optimize() prewarms the fused rotation extension where eligible. Automatic Transformers static-cache generation compilation stays disabled for this kernel. See compiled inference and CUDA graphs.
CPU layout conversion detaches retained scales, bias, theta, pairs, and channel_scales from non-resizable checkpoint-backed storage, preventing these views from keeping a safetensors shard mapped after weight repacking; ordinary allocated tensors are not copied. AVX512 and ATen capture their packed operands under the transform/state-dict lock, then run GEMM outside that process-wide lock. Independent CPU projections can therefore overlap instead of serializing their products. A concurrent save can rebind module buffers without invalidating the captured operands; failure restoration reacquires the lock. This does not promise safe simultaneous arbitrary weight mutation or alter packed formats.
The Triton dequantizer normalizes strided qweight, scales, and qzeros to contiguous operands; fused GEMM does the same for its activation input and packed operands. This fixes logical-value decoding for transposed or padded-storage views without changing the checkpoint layout, group-size checks, or retained packed-weight storage.
ParoTritonLinear.forward now also packs the flattened activation before rotation, fixing strided decode views such as hidden_states[:, -1:, :] that otherwise failed the fused rotation's contiguity check. GPT-QModel no longer registers quant_method="paro" as generic HF GPTQ; use the native loader so rotations and learned side state are restored rather than entering an incompatible homogeneous GPTQ path.
utils/paro.py offers reference Torch rotations and a vectorized CPU rotation. The native extension is built from gptqmodel_ext/paro/rotation.cu through the shared JIT loader. Its fused rotation eligibility is narrower than the Python API: group size 128, krot 1 or 8, and eligible CUDA tensors. Unsupported cases fall back to Torch. Building the native extension requires the relevant Torch extension toolchain; merely installing Triton does not build it.
For FP16 and BF16 inputs, the reference and vectorized Torch rotations and the fused native CUDA rotation keep channel scaling and all Givens stages in FP32, then round once to the input dtype. The fused CUDA path uses an FP32 shared-memory workspace between stages. This avoids FP16 intermediate overflow and per-stage BF16 rounding. Torch rotation · CUDA rotation
def apply_paro_rotation(
x: torch.Tensor,
pairs: torch.Tensor,
theta: torch.Tensor,
scales: Optional[torch.Tensor] = None,
group_size: int = 128,
) -> torch.Tensor:
...Use apply_paro_rotation_autograd for its custom fused-backward dispatch; the reference and vectorized helpers expose the same argument structure. Rotation launch selection has process-local and optional disk caches keyed by runtime/hardware identity. These caches store launch decisions, not expanded weights.
The fused rotation backward orders shared-memory readback before the next rotation rewrites those columns, removing an intermittent gradient race. Angle-gradient reduction uses fixed four-row partials folded in ascending order, so its result is independent of the selected cta_m/row_pad launch plan. The native pair-gradient, standalone angle-gradient, and Torch fallback use the corrected input-side expression sum(g_i * x_j - g_j * x_i) after sweeping both values and gradients back through the rotation; no extra sine/cosine factors remain. This corrects training at nonzero angles. The standalone grad_theta fallback still uses atomic accumulation for batches over 32 rows and is not bitwise reproducible there. See fused backward details.
| Control | Default | Purpose |
|---|---|---|
KernelConfig.paro_cache_runtime_dtype |
False |
Retain runtime-typed scales/bias rather than repeatedly converting them. |
KernelConfig.paro_auto_cache_bf16_runtime_dtype |
True |
Enable that behavior automatically for BF16 compute. |
KernelConfig.paro_cache_rotation_dtype |
False |
Cache typed angle and channel-scale metadata. |
KernelConfig.paro_auto_cache_bf16_rotation_dtype |
True |
Enable typed rotation metadata caching for BF16. |
KernelConfig.paro_cpu_avx512 |
True |
Permit the eligible BF16 CPU AVX512 path. |
KernelConfig.paro_rotate_autotune |
True |
Autotune the native rotation launch when no valid explicit launch override is supplied. |
KernelConfig.paro_rotate_cta_m |
None |
None or an integer from 4, 8, 16; other values raise. |
KernelConfig.paro_rotate_row_pad |
None |
None, 0 or 2; other values raise. |
KernelConfig.paro_autotune_cache |
True |
Enable disk persistence of rotation launch decisions. |
GPTQMODEL_PARO_BUILD_ROOT |
torch_extensions/paro under the GPT-QModel cache root, or paro under $GPTQMODEL_TORCH_EXTENSIONS_DIR when set |
Override the native extension build root. Cache root and override order |
GPTQMODEL_PARO_FORCE_REBUILD |
False |
Request native extension rebuilding through the shared loader. |
GPTQMODEL_EXT_VERBOSE |
False |
Enable shared JIT-extension build verbosity. |
Runtime dtype settings come from KernelConfig at module construction; explicit constructor arguments with corresponding names override these settings. The CPU rotation path also reuses typed rotation metadata directly. Metadata caches are not dequantized weight caches. The disk launch-cache root is GPTQMODEL_CACHE_DIR, otherwise $XDG_CACHE_HOME/gptqmodel, otherwise ~/.cache/gptqmodel; files live under paro/rotation_launch/. Use the rotation cache/extension clearing helpers in utils/paro.py when deliberately changing tuning or build state within one process.
Native fused-rotation autotune timing counts and speedup thresholds are internal constants in gptqmodel_ext/paro/rotation.cu. The former GPTQMODEL_PARO_ROTATE_AUTOTUNE_* timing environment variables are no longer read. Select native rotation search/launch behavior with KernelConfig.paro_rotate_autotune, paro_rotate_cta_m, and paro_rotate_row_pad; the separate Triton GEMM tuning fields below retain their own meaning.
The typed rotation cache creates its angle and channel-scale tensors outside inference mode, including when a BF16 generate() call warms it. A later gradient-enabled forward can reuse those tensors for rotation backward. See the rotation runtime cache.
The low-level GEMM unpacks INT4 tiles, subtracts zero points, multiplies by group scales, and accumulates the dot product. Decode uses blocks (M, N, K)=(4, 128, 32), four warps, and two stages; prefill uses (32, 128, 32), eight warps, and four stages. KernelConfig.fp32_accum defaults to enabled.
| Control | Default | Meaning |
|---|---|---|
KernelConfig.paro_triton_autotune |
True |
Boolean enabling eligible plan tuning. |
KernelConfig.paro_triton_autotune_warmup |
2 |
Non-negative warmup count. |
KernelConfig.paro_triton_autotune_iters |
4 |
Timed iterations, at least one. |
KernelConfig.paro_triton_autotune_margin |
0.05 |
Non-negative tuning margin. |
KernelConfig.paro_triton_decode_max_rows |
8 |
Decode-row threshold, at least one. |
These typed kernel-policy settings are captured when the runtime module is constructed. Set them through kernel=... before loading/building the module; changing environment variables has no effect. A module's clear_autotune() clears its plan decisions. The plan cache is per module and keyed only by "decode" or "prefill", not by the exact activation shape; the first tuned workload of each kind determines later calls until the cache is cleared.
Paro's public quantization run now requests the deterministic rocBLAS scope on ROCm for the whole run, including its rotation-optimization GEMMs, although Paro does not accumulate a Hessian. Per-module seeds derived from opt_seed alone were insufficient when hipBLASLt selected different kernels across processes. This trades faster hipBLASLt FP16/BF16 GEMMs for reproducible seeded checkpoints on the same qualified stack. Explicit KernelConfig(rocm_quant_blas="hipblaslt") opts out of the pin and can give different checkpoints across processes; see the shared policy and timeout limits. This policy does not establish cross-device bitwise equality or add an inference backend.
Torch uses the cuda device type for ROCm too. The standalone optimizer explicitly disables stage CUDA graphs on ROCm and defaults AMP off there. This is separate from the grouped runners' device-type-based AMP behavior. Triton training kernels import HIP libdevice on HIP builds; the inference class validates torch.cuda.is_available() rather than establishing compatibility with every AMD architecture. Do not infer a hardware-support guarantee from a shared device-type name.
The MLX optimizer is available only on Darwin/arm64 with mlx.core importable. ParoProcessor selects it for nonempty CPU/MPS module-scope calibration when opt_stage_impl="fast" and gradient checkpointing is off. It implements the two stages with MLX autodiff and bridges tensors through DLPack. Grouped scopes are not this native MLX optimization path.
| MLX source | Responsibility |
|---|---|
quantization/mlx_paro_optimize.py |
Availability, differentiable rotations/STE, AdamW/Adam/SGD, stage loop, Torch result bridge. |
quantization/mlx_paro_rotation.py |
Forward/inverse Metal rotation, validated local pair permutations; standalone primitive returns FP32. Groups 16, 32, 64, 128. |
quantization/mlx_paro_quant.py |
Metal transformed-weight pseudo-quantization; primitive supports bits 2..8, distinct from the four-bit export runtime. |
quantization/mlx_paro.py |
Native symmetric four-bit AWQ-layout packing; validates finite positive scales, finite weights, code range, and output width divisible by 32. |
nn_modules/qlinear/mlx_paro.py |
Runtime staged/fused Metal activation rotations and quantized matmul. Uses FP32 intermediates and restores the input dtype. |
The MLX runtime uses fused rotations for BF16 or multiple stages when the group is at most 128; eligible single-stage FP16 execution may use the staged kernel.
The MLX export packer forms 8 * scale and the affine code expression in FP32 before ties-to-even rounding, matching the Torch AWQ packer. This avoids both FP16 zero-offset overflow and low-precision division moving threshold-neighbor values onto the wrong integer code. Stored scale dtypes and the packed four-bit layout are unchanged; finite positive stored scales and legal code ranges are still required. See MLX packing contracts.
gptqmodel/utils/paro_benchmark.py provides dense baselines, prefix-layer/single-module/selected-module dynamic masks, quantize-save-reload evaluation, module/region timing tables, and CUDA-versus-Triton-versus-dense kernel comparisons. Kernel measurements capture real module inputs and report maximum/mean absolute differences as well as latency. Evaluation helpers are imported from tests/eval.py, so this is checkout tooling, not a self-contained installed-package benchmark.
Its model/calibration defaults are checkout-specific. Supply your own accessible model and calibration paths before running it. The utility's default row counts and evaluation suite are benchmark choices, not additional public quantizer defaults. See Evaluation for model-quality measurement.
The benchmark's fused_opt_rotation choice is forwarded to ParoConfig.opt_fused_rotation through make_paro_config(..., opt_fused_rotation=True). Results report the effective choice: layer-scope optimization records fused_opt_rotation=False because that scope forces portable rotations even when fusion was requested. The flag requests an eligible path; it does not prove every module used a native fused kernel.
ParoConfig.gsq adds a Gumbel-Softmax refinement pass to Paro's module optimization (gsq_paro.refine_paro_export). It requires bits 4, opt_scope "module", and opt_train_on_noisy_inputs False. See GSQ.
- Keep
sym=Trueand use the Paro format. Do not relabel the checkpoint as AWQ. - The optimizer's generic pseudo-quantizer can handle more bit widths than the current four-bit inference/export backend. Helper acceptance is not end-to-end format support.
- Valid group sizes must also divide the actual module width and satisfy the selected kernel's restrictions. Automatic padding is not advertised by the Paro runtime classes.
- Calibration rows are required for meaningful learned rotations. Identity fallback is not successful rotation optimization; disable fallback when missing activations should be an error.
- Module scope reconstructs linears; grouped scopes reconstruct a whole-layer output. Their losses and memory costs are not interchangeable measurements.
- Validation prefixes/suffixes can overlap when data is insufficient. Supply enough calibration rows if a disjoint holdout matters.
- More stages increase rotation metadata and work; they do not expand the fused native kernel's supported
krotset. - CUDA graphs and AMP are scope- and platform-dependent, even when enabled in configuration.
- Changing
opt_quantizer_implchanges quantization arithmetic, not just speed. - Keep rotation buffers with the checkpoint and preserve
krotwhen constructing runtime modules.
Paths below are relative to the repository:
-
gptqmodel/quantization/config.py— configuration, method/format values, metadata. -
gptqmodel/quantization/paro/optimization.py— optimization, STE, pairing, result contract. -
gptqmodel/quantization/paro/modules/triton/affine_ste.py— affine STE acceleration. -
gptqmodel/quantization/paro/modules/triton/sym_ste.py— symmetric STE acceleration. -
gptqmodel/quantization/paro/modules/triton/gemm.py— inference dequantization/GEMM. -
gptqmodel/looper/paro_processor.py— capture, scope orchestration, packing. -
gptqmodel/nn_modules/qlinear/paro.py— shared runtime. -
gptqmodel/nn_modules/qlinear/paro_triton.py— Triton plan dispatch. -
gptqmodel/nn_modules/qlinear/torch_awq.py,gptqmodel/quantization/awq/utils/packing_utils.py— inherited packing and four-bit layout constraints. -
gptqmodel/utils/paro.py— rotations, JIT/autotuning, autograd. -
gptqmodel/utils/cpp.py— shared JIT build-root, rebuild, and verbosity policy. -
gptqmodel/utils/paro_benchmark.py— development benchmarks. -
gptqmodel_ext/paro/rotation.cu— native rotation extension. -
gptqmodel/quantization/mlx_paro.py— MLX packing. -
gptqmodel/quantization/mlx_paro_optimize.py— MLX optimizer. -
gptqmodel/quantization/mlx_paro_quant.py— MLX pseudo-quantization. -
gptqmodel/quantization/mlx_paro_rotation.py— MLX weight rotation. -
gptqmodel/nn_modules/qlinear/mlx_paro.py— MLX runtime. -
gptqmodel/models/base.py— quantization processor selection. -
docs/paro.md— scope-specific checkpointing notes.
Documentation home · Quickstart · Troubleshooting · Repository · PyPI
Public source 780f1bbfc declares package version 7.15.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
- FITQ
- 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