Repository navigation
EXL3
🏠 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.
Compress weights into trellises instead of ordinary scalar integers. For: readers exploring low-bit model storage who can calibrate on NVIDIA CUDA or AMD ROCm, then deploy through an EXL3-aware runtime.
EXL3 combines a quantization algorithm with a trellis checkpoint layout. A trellis stores a compact sequence of states whose decoded values approximate the weights; nearby decisions share state instead of each weight carrying an independent integer. This is useful when you want to explore aggressive weight compression and can use the matching loader and runtime.
It is not a GPTQ checkpoint with a different backend. EXL3Config, FORMAT.EXL3, and the EXL3 runtime must agree. The implementation notes below are checked against 2aee8ddc2; support declarations are not benchmark or accuracy qualification.
| Your goal | Start here |
|---|---|
| Choose and understand | The decision table below; compare methods and dtypes |
| Use it | Quantize, save, and reload |
| Go deeper | Concepts · Runtime requirements · Troubleshooting |
| Choose this when… | Consider another path when… |
|---|---|
| You want trellis-based low-bit storage and will evaluate the resulting model | You need a familiar scalar checkpoint for a deployment engine: compare GPTQ and AWQ |
| You can collect calibration activations and run a CUDA/HIP trellis solver | You need direct weight-only packing without calibration: see GGUF |
| Your deployment accepts native EXL3, Torch reconstruction, or the explicit Apple Silicon MLX route | You are choosing a runtime solely by its name; check its hardware, dtype, and shape contract first |
- Install GPT-QModel and the GPU-enabled PyTorch/toolchain for NVIDIA CUDA or AMD ROCm. Public EXL3 quantization needs the vendored CUDA/HIP extension; a CPU or Apple Silicon inference route does not enable CPU/MLX quantization.
- Use a supported dense source model and representative calibration data. Input widths must be positive multiples of 128; generic quantization pads output widths to the next multiple of 128 and crops them at inference.
- Budget for calibration Hessians and tile workspaces, not just the final checkpoint. Check platform requirements before a large run.
- Start with
bits=3or choose a supported half-bit rate with themul1codebook.
Reading the diagram: The public quantization entry point requires CUDA/HIP and calibration. Torch/MLX inference does not enable CPU/MLX quantization through that entry point.
Text version of the workflow
- Per-layer, per-subset solve: Capture selected modules → Solve EXL3 trellises → Replay solved weights → Finalize EXL3 modules.
- Load an EXL3 artifact: Read EXL3 configuration → Rebuild packed modules → Run the selected runtime.
from gptqmodel import CalibrationConfig, GPTQModel
from gptqmodel.quantization import EXL3Config
qcfg = EXL3Config(
bits=3.0,
codebook="mcg",
out_scales="auto",
device="cuda:0", # NVIDIA CUDA example; see the AMD ROCm note below.
)
model = GPTQModel.load("/path/to/dense-model", quantize_config=qcfg)
# API demo only: replace these strings with a representative calibration corpus.
calibration = [
"This example document contains several complete sentences about the kinds "
"of questions and explanations that the model will encounter during deployment.",
"Use many real documents from the intended domain for an actual run, keeping "
"the calibration corpus separate from the data used to evaluate quality.",
]
model.quantize(CalibrationConfig(dataset=calibration, batch_size=1))
model.save("/path/to/exl3-model")The example illustrates the call shape. Use a representative calibration dataset and keep in mind that preparation removes samples with at most CalibrationConfig.min_length tokens (default 10). EXL3 requires a calibration dataset. A projection that sees zero tokens, such as an unselected MoE expert, is quantized using an identity proxy Hessian and EXL3's uncalibrated, RTN-equivalent trellis path. See Quantization Lifecycle for dataset preparation and sequencing.
For AMD ROCm, the public EXL3 guard in this source revision expects the PyTorch HIP execution spelling device="cuda:0"; this is an EXL3 entry-point limitation, not a declaration that NVIDIA CUDA and AMD ROCm are interchangeable. Use a ROCm PyTorch build and a working HIP EXL3 quantization extension. For inference, AUTO can select native HIP on eligible RDNA4 GPUs. See the public guard and backend resolver.
Before each subset captures, EXL3 binds a routed expert's Hessian accumulator to the device assigned by the MoE placement plan, if available. Otherwise, the expert index modulo the pool size picks the device. The fallback pool comes from explicit moe_vram_strategy_devices, the looper's resolved MoE pool after compute_device_filter, or the quantizer's device, in that order. The family-aware converter maps DEVICE.ROCM to PyTorch's HIP device spelling. Bare cuda selectors expand to process-visible ordinals when GPUs are available, and explicit ordinals are preserved. Partials are tracked by capture-source device and reduced in fixed device order. EXL3 capture · Hessian accumulation and reduction
The verified routed-expert gate and up projections in deepseek_v4, dots3_note, glm5_next, and glm_moe_dsa use the model-tree shared-input groups. Within an eligible capture subset, EXL3 collects one Hessian for the pair and both projections read the same accumulator state. Each expert has its own group.
from gptqmodel import GPTQModel, BACKEND
# AUTO selects native EXL3 on NVIDIA CUDA and on eligible ROCm RDNA4
# targets with a loadable extension or a HIP build toolchain.
model = GPTQModel.load("/path/to/exl3-model", device="cuda:0")
# Explicit native inference (on ROCm, gfx1200/gfx1201 only).
# model = GPTQModel.load(
# "/path/to/exl3-model", device="cuda:0", backend=BACKEND.EXL3_EXLLAMA_V3,
# )
# Explicit Torch fallback on CPU.
cpu_model = GPTQModel.load(
"/path/to/exl3-model", device="cpu", backend=BACKEND.EXL3_TORCH,
)
# Explicit MLX route on a supported Apple Silicon installation.
mlx_model = GPTQModel.load(
"/path/to/exl3-model", device="mps", backend=BACKEND.MLX,
)These are alternative loading examples, not instructions to keep multiple model copies resident. Standard generation usage is covered in Loading and Inference.
Reload the saved directory with the backend and activation dtype you intend to deploy. Generate a short sanity check using Loading and Inference, then compare held-out quality with the dense model in Evaluation. A small reconstruction proxy is not a language-model accuracy result.
Keep the complete checkpoint directory: packed tensors and tensor_storage metadata are required. Changing the backend does not convert EXL3 to GPTQ or VPTQ.
Let X be a real T × n matrix of calibration activation rows and W a real m × n linear weight matrix. With H = XᵀX / T, a useful layer-reconstruction objective is
Here Ŵ is the weight reconstructed from the packed trellis, m is the output width, and n is the input width. Errors along frequently used activation directions matter more than equally sized errors along unused directions.
EXL3 approximates this goal in a signed-Hadamard-transformed, regularized space. It searches legal trellis paths with tile/Viterbi kernels and uses block-LDL error compensation when the Hessian is usable; this is not an exact global minimizer of the equation above. Its reported proxy is measured in the regularized search space, not automatically in original source-weight or model-output space. See the quantizer and diagnostics.
| Identifier | Value | Meaning |
|---|---|---|
METHOD.EXL3 |
"exl3" |
Select the EXL3 quantization algorithm |
FORMAT.EXL3 |
"exl3" |
Serialize EXL3 trellises and their accompanying tensors |
EXL3Config |
Configuration class | EXL3-specific settings, plus inherited model/looper controls |
BACKEND.EXL3_EXLLAMA_V3 |
"exl3_exllama_v3" |
Native inference on NVIDIA CUDA and eligible AMD ROCm RDNA4 devices |
BACKEND.EXL3_TORCH |
"exl3_torch" |
Torch reconstruction and multiplication runtime |
BACKEND.MLX |
"mlx" |
Explicit Apple Silicon/Metal inference route |
Portions of gptqmodel/exllamav3/, the processor, and the runtime utilities are adapted from ExLlamaV3 by TurboDerp and contributors. GPT-QModel's EXL3 port adapts the original Q4NX codebook, encoder, and CUDA fragment decoder by AlexBrandes (Alex Brandes). Qubitium extended Q4NX to 3.5 bits per weight. ExLlamaV3 · Q4NX format and encoder · CUDA fragment decoder
EXL3 builds on the QTIP trellis design by Albert Tseng, Qingyao Sun, David Hou, and Christopher De Sa. QTIP paper · ExLlamaV3 quantization · Research credits
The native MLX kernel headers also identify the upstream EXL3 format and its MIT provenance. GPT-QModel supplies model traversal, calibration capture, module replacement, configuration, saving/loading, and additional Torch/MLX implementations. An EXL3 checkpoint should not be described as an ordinary GPTQ checkpoint that happens to use ExLlama kernels: its tensors and loader are different.
EXL3 does not store an integer code for every weight together with GPTQ-style group scales and zero points. It stores a packed trellis representation and input/output sign-scale tensors. Quantization works in a transformed weight space using randomized signs, block Hadamard transforms, regularization, and Hessian-aware error compensation. The decoder reconstructs codebook values from trellis states.
| Component | Purpose |
|---|---|
trellis |
Packed state information stored as torch.int16, with shape (stored_in_features // 16, stored_out_features // 16, int(16 * K)) at rate K bits per weight |
suh, svh
|
FP16 input/output sign-scale vectors used with Hadamard transforms |
su, sv
|
Legacy packed-sign alternatives; runtimes can unpack these to sign vectors |
mcg |
Optional marker for the mcg decoder family |
mul1 |
Optional marker for the mul1 decoder family |
q4nx |
Scalar int32 marker for the Q4NX decoder family |
r4nx |
Scalar int32 marker for the R4NX decoder family |
bias |
Optional linear bias |
The default EXL3 codebook is mcg. The mcg, mul1, q4nx, and r4nx decoder families use mutually exclusive marker tensors. A projection without a codebook marker uses 3inst. The Torch backend reads all five codebooks.
The block-128 Hadamard layout needs 128-aligned stored dimensions. Generic EXL3 quantization requires positive in_features % 128 == 0, zero-pads positive output widths to a multiple of 128, and crops runtime outputs back to the logical width. Low-level transform/MLX helpers still require aligned arrays supplied by their caller. Do not infer support for arbitrary convolutions or input padding from module-shape discovery; see the geometry contract.
The 3inst, mcg, and mul1 codebooks support integer rates from 1 through 8 bits per weight. Set EXL3Config(bits=2.5, codebook="mul1") to pack a projection at 2.5 bits per weight. The other native half-bit rates are 1.5 and 3.5, also with mul1. Each 16 × 16 tile alternates adjacent integer transition widths and stores 24, 40, or 56 int16 words at 1.5, 2.5, or 3.5 bits per weight, respectively.
The same rate limits apply to bits, head_bits, and those fields in dynamic rules. A rule can set its own codebook alongside its rate. If a rule can change the codebook, the quantizer validates head_bits against the effective codebook when it resolves the selected output head. Numeric strings are accepted, including "2.5" with mul1. Booleans, non-finite values and unsupported rate/codebook pairs raise ValueError. The normalized config, its JSON export, and runtime_bits use integers for whole rates and floats for half rates.
Half-bit mul1 quantization requires NVIDIA CUDA. For inference, use BACKEND.EXL3_EXLLAMA_V3 on NVIDIA CUDA or eligible ROCm RDNA4 devices. BACKEND.EXL3_TORCH is the portable option for CPU and other ROCm targets. MLX inference accepts integer widths. See the half-bit checkpoint layout.
Set explicit dynamic overrides to mix rates across modules. For example, keep a default of bits=4 and set {"bits": 2.5, "codebook": "mul1"} on selected projections. A half-bit bits setting specifies the packed rate for each eligible projection that inherits it. Total checkpoint size also includes scales, optional bias, metadata and unquantized weights.
For budget-driven selection, the separate format-aware RCO runner measures reconstruction error for K2/K3/K4, allocates one integer depth per definition-declared projection, then runs ordinary EXL3 quantization with the resulting dynamic map. Its shape-aware budget includes trellis storage, FP16 input/output scale vectors, and applicable codebook markers, but excludes biases and unquantized model state. This is reconstruction allocation, not staged GSQ or differentiable teacher-KL search, and does not bypass EXL3's native quantization/device requirements.
Q4NX stores 40, 48, or 56 int16 words per 16 × 16 tile at 2.5, 3.0, or 3.5 bits per weight, respectively. Its trellis starts with a zero prefix and yields four weights per state. The state widths are 22, 20, and 18 bits, respectively. The original implementation covers 2.5 and 3.0 bpw. The 3.5 bpw encoder searches all 16 overlap classes at each step. GPT-QModel port
EXL3Config(bits=2.5, codebook="q4nx") selects Q4NX quantization on NVIDIA CUDA. To mix codebooks in one checkpoint, set both fields in a matching dynamic rule, for example {"bits": 3.5, "codebook": "q4nx"} for selected projections. The saved quantize_config.json records the default codebook and the dynamic recipe, and tensor_storage describes each Q4NX projection's scalar int32 .q4nx tensor. The loader checks that the codebook marker keys match those in the safetensors shards and reports missing or unexpected markers before inference. Use BACKEND.EXL3_EXLLAMA_V3 on NVIDIA CUDA or eligible ROCm RDNA4 devices. Use BACKEND.EXL3_TORCH for portable inference, including on Apple Silicon. Rate validation · Checkpoint validation
R4NX is designed for AMD RDNA4. It uses the same packing scheme as Q4NX with its own state-to-weight mapping. Each 16 × 16 tile stores 40, 48, 56, or 64 int16 words at 2.5, 3.0, 3.5, or 4.0 bits per weight, respectively. The r4nx marker selects the decoder. Each state decodes to four weights from the signed bytes of a 32-bit multiply, scaled by 7/512. R4NX layout and decoder
Use EXL3Config(bits=4, codebook="r4nx", device="cuda:0") with a working HIP EXL3 extension on RDNA4. The quantizer uses a Torch Viterbi encoder and the extension's R4NX packer. To select R4NX for individual projections, set both fields in a matching dynamic rule, for example {"bits": 3.5, "codebook": "r4nx"}. On NVIDIA CUDA or eligible ROCm RDNA4 devices, BACKEND.EXL3_EXLLAMA_V3 reconstructs R4NX into a temporary weight for HGEMM. BACKEND.EXL3_TORCH is the portable option for CPU, Apple Silicon, and other ROCm targets. Quantizer and packer · Bundled runtime
| Operation/runtime | Requirements | Important behavior |
|---|---|---|
Public model.quantize() for EXL3 |
CUDA/HIP available; quantization device type cuda; backend AUTO or EXL3_EXLLAMA_V3
|
Q4NX and half-bit mul1 quantization require NVIDIA CUDA |
EXL3Processor low-level MLX branch |
Darwin arm64, importable mlx.core, target CPU or MPS |
Implemented internally, but the public EXL3 quantization guard above runs first |
ExllamaV3Linear |
NVIDIA CUDA or ROCm gfx1200/gfx1201, materialized packed tensors and EXL3 extension |
Lazily constructs the bundled runtime. AUTO checks extension availability on ROCm. |
ExllamaV3TorchLinear |
Torch operations supported by the selected device | Reconstructs for the current operation without retaining a dense weight cache |
| Native MLX inference | Apple Silicon/Metal, MLX and MLX-LM integration | Explicit BACKEND.MLX supports integer rates with 3inst, mcg, and mul1
|
The loader accepts only AUTO, EXL3_EXLLAMA_V3, EXL3_TORCH, or MLX for FORMAT.EXL3 after backend alias normalization. With GPU execution available, AUTO selects native EXL3 on NVIDIA CUDA or when every selected ROCm device passes the gfx120x check and the extension availability probe. On ROCm the probe accepts registered operators, an existing cached or configured binary, or a HIP JIT toolchain (hipcc and ninja) when no prebuilt library is explicitly configured. It does not compile the extension or guarantee that a later build succeeds. CDNA, gfx1250, and ROCm installations that fail the probe use EXL3_TORCH; other non-GPU targets also default to Torch.
Explicit EXL3_EXLLAMA_V3 checks the ROCm architecture without the AUTO availability probe. Select BACKEND.EXL3_TORCH to avoid the extension. AUTO does not select MLX for EXL3. See the HIP availability probe.
With native EXL3 on RDNA4 gfx1200 or gfx1201, whether selected by AUTO or explicitly, the bundled HIP runtime tries GEMV for 1–8 flattened rows when the packed rate and shape are eligible. Otherwise it can use packed wave32 WMMA GEMM for 1–512 rows, projection widths divisible by 128, and FP32 output from the inner kernel. The public wrapper requests FP32 output for both FP16 and BF16 activations on this path, then rescales, adds bias, and returns the activation dtype.
WMMA GEMM supports eligible integer rates for 3inst, mcg, and mul1, plus half-bit mul1. Q4NX can use eligible HIP GEMV but reconstructs for larger or unsupported calls. R4NX always reconstructs. Unsupported WMMA calls use temporary reconstruction with hipBLAS rather than changing the checkpoint. Bundled runtime · HIP GEMM dispatcher
On HIP, EXL3CUDAConfig(int8_gemv=...) (equivalently KernelConfig(exl3_int8_gemv=...) with the native backend) controls optional INT8-activation GEMV. The default 0 leaves it off; 1 enables residual INT8 for one row and 2 enables plain INT8 for one or two rows. This path requires mul1 at 2, 3, or 4 bpw and widths divisible by 128. When INT8 is ineligible, native HIP decode still tries FP16-operand GEMV when eligible. The fp16_gemv and fused_gemm CUDA tuning toggles do not control HIP dispatch. HIP INT8 gate
from gptqmodel import GPTQModel
from gptqmodel.backend import EXL3CUDAConfig
model = GPTQModel.load(
"/path/to/exl3-mul1-model", device="cuda:0", backend=EXL3CUDAConfig(int8_gemv=1),
)The tile encoder queries the current GPU's per-block opt-in shared-memory limit before launching. For K=2 on devices with at least 65,536 but fewer than 66,240 bytes, it automatically selects a compact layout using exactly 64 KiB. This enables 2-bit quantization on RDNA4 GPUs with 64 KiB per block without a new configuration flag; mcg, mul1, and 3inst use the same selection. GPUs with more shared memory keep the standard layout.
Unsupported layouts fail before launch with the required/available byte counts and a suggestion to use bits >= 3. Configuration acceptance of bits in [1, 8] does not guarantee that every bitrate fits a GPU.
EXL3's block_ldl() uses the shared allocation-failure classifier for both Cholesky factorization and inversion of its diagonal blocks. Explicit OOMs and solver workspace/handle failures such as CUSOLVER_STATUS_ALLOC_FAILED / HIPSOLVER_STATUS_ALLOC_FAILED can therefore retry the affected operation on CPU; inverted blocks are copied back to their original device. Non-allocation failures still propagate. This targeted recovery requires host memory and does not enable public CPU-only EXL3 quantization or guarantee recovery from tile-encoding OOMs. See the vendored solver.
KernelConfig.exl3_tile_batch defaults to None, which selects an automatic limit based on the codebook and encoding stage. A positive integer can lower that limit. Pass kernel={"exl3_tile_batch": 32} in EXL3Config to reduce scratch at the cost of more launches.
| Encoder stage | Automatic tile limit |
|---|---|
| Ordinary integer rate | 256 |
| Ordinary fractional rate | 128 |
| Q4NX final encoding at 2.5 or 3.0 bpw | 512 |
| Q4NX scale search at any rate, or final encoding at 3.5 bpw | 1,024 |
Q4NX keeps its Viterbi history in launch-local scratch. The automatic limits bound that history to 16 MiB at 512 tiles and 4 MiB at 1,024 tiles. Tile scheduling
Quantization workers now share one process-wide CUDA/HIP quantization stream per device, with a lock guarding stream creation. Work on that stream is ordered, and the existing per-device quantization lock still serializes the kernels. This avoids multiplying tile scratch and stranded allocator pools by the worker count.
Scratch remains keyed by device, K, stream, and tile-batch value. At a fixed K and batch, workers on one device reuse one scratch pair. The largest buffer is batch × 256 × (65536 >> K) int16 entries: batch 256 uses 512 MiB at K=4 or 2 GiB at K=2 per device for that buffer alone. Lower tile batches reduce scratch, not packed model storage or all other quantization workspaces. See quantization stream and tile scratch.
End-of-run cleanup now releases the process-wide per-stream tile scratch on both success and failure. ModuleLooper calls EXL3Processor.release_run_workspace(), which clears the tile-workspace registry; a completed run no longer leaves those cached tensors allocated for the rest of the process. Scratch is still reused during the run, and the tile-batch control above still governs peak workspace use. See the processor cleanup and workspace registry.
Native inference scratch is separate from the quantization tile registry above. Each native EXL3 call now owns its split-K INT32 lock array, HGEMM cuBLAS workspace, and batch-one Hadamard input buffer when that route needs them. These writable buffers are no longer shared per device or shape across concurrent streams. They are released after the consuming call, and the HGEMM path resets the cuBLAS workspace pointer before releasing its tensor. This fixes cross-stream corruption/deadlocks caused by shared scratch without retaining expanded weights or adding a cleanup API. See kernel scratch ownership.
gptqmodel/exllamav3/ext.py exposes exllamav3_runtime_available(), exllamav3_runtime_error(), and prewarm_exllamav3_extension(). The extension is named gptqmodel_exllamav3_ops; it is built from the vendored sources under gptqmodel_ext/exllamav3/ using Torch's extension machinery. A compatible GPU-enabled PyTorch installation, compiler/toolkit, and supported architecture are needed. Merely having the Python files is not enough.
The HIP build of the cooperative MoE kernel uses HIP's expf for CUDA's __expf call. This resolves the missing intrinsic when building the bundled EXL3 extension on ROCm. See the HIP compatibility header.
| Control | Purpose |
|---|---|
GPTQMODEL_EXT_VERBOSE |
Extension build verbosity |
GPTQMODEL_EXT_DEBUG |
Debug build controls |
GPTQMODEL_EXLLAMAV3_BUILD_ROOT |
Override extension build/cache root |
GPTQMODEL_EXLLAMAV3_FORCE_REBUILD |
Force rebuilding instead of reusing the build |
KernelConfig.exl3_tile_batch |
Positive integer to lower the automatic tile limit. Default None. |
TORCH_CUDA_ARCH_LIST |
CUDA architecture selection; when unset/empty, EXL3 derives a temporary value only around its JIT build |
Importing EXL3 no longer installs a process-wide architecture override. The build scope restores the previous value (or absence) after success or failure; a nonempty caller override is honored, and a different value installed concurrently is not overwritten during restoration. Derived capabilities are sorted numerically with +PTX on the highest target. Later Marlin/ExLlamaV2/AWQ JIT builds therefore do not inherit an EXL3-installed architecture list or miss their caches because of that leaked setting. See the scoped architecture helper.
The extension checks for required operations including had_paley, had_paley2, quantize_tiles, pack_trellis, unpack_trellis, pack_signs, reconstruct, had_r_128, hgemm, and bc_linear_exl3_run. Build/import failures should be diagnosed through the runtime error helper rather than assuming a model-format error. See Installation and Quickstart and Troubleshooting and FAQ.
Normal EXL3 quantization does not require pydantic. The memory-inspection helper imports it optionally inside list_gpu_tensors() rather than during utility-module import; the openai serving extra remains separate.
The following are the fields declared by EXL3Config itself. EXL3 inherits preprocessors from PreProcessorConfig, but rejects active weight smoothers. Shared controls such as device, dynamic, offload, and metadata ultimately come from BaseQuantizeConfig. See QuantizeConfig Reference. Keep the inherited rotation field unset: the loader accepts shared model-rotation metadata only for GPTQ/GPTQ_V2 checkpoints. EXL3's internal sign/Hadamard transforms are part of its own format, not that shared rotation workflow.
| Field | Declared type | Default | Behavior |
|---|---|---|---|
bits |
int | float |
3 |
Integer 1–8 with 3inst, mcg, or mul1. Additional rates are 1.5, 2.5, or 3.5 with mul1. Use 2.5, 3, or 3.5 with q4nx, and 2.5, 3, 3.5, or 4 with r4nx. |
method |
METHOD |
METHOD.EXL3 |
Only exl3 accepted |
format |
FORMAT |
FORMAT.EXL3 |
Only exl3 accepted |
group_size |
int |
-1 |
Forced to -1; not a GPTQ group-size setting |
desc_act |
Optional[bool] |
False |
Forced to False
|
sym |
bool |
True |
Forced to True
|
head_bits |
int | float | None |
None |
Output-head rate, validated against the effective codebook. Setting it implies head quantization when lm_head is omitted. |
lm_head |
bool | None |
None |
None follows head_bits. False opts out. True explicitly requests head quantization and requires untied weights. |
out_scales |
Optional[str] |
"auto" |
Controls output-scale decision passed to the quantizer |
codebook |
str |
"mcg" |
mcg, mul1, 3inst, q4nx, or r4nx, case/whitespace normalized |
tensor_storage |
Optional[Dict[str, Any]] |
None |
Per-module storage metadata; populated on save and required on load |
calibration |
Optional[Dict[str, int]] |
None |
Dictionary normalized to string keys and integer values; not the calibration dataset argument |
module_include |
Optional[List[str]] |
None |
Retired. Older checkpoints can load with this field, and saving omits it. |
A non-None module_include warns once per process and raises ValueError at EXL3 quantization setup. Express an allowlist with a dynamic -: rule that matches modules outside it. Use fully qualified module paths. EXL3 export preserves exact bits and head_bits rates and calibration/method provenance. It removes execution-only offload paths, placement and worker settings, and related lifecycle metadata.
EXL3Config.allowed_quant_methods() returns (METHOD.EXL3,); supported export formats are the EXL3 export-format tuple. Changing method or format does not convert the config into another method.
out_scales input |
Canonical config value | Quantizer argument |
|---|---|---|
"always", "true"
|
"always" |
True |
"never", "false"
|
"never" |
False |
"auto", "none"
|
"auto" |
None |
Python None
|
None |
None |
Other strings raise ValueError. These are normalized requests to the regularization stage; they are not a separate checkpoint scale format. The quantizer's regularization code makes the final output-scale decision, including handling exceptional zero-scale cases.
from gptqmodel.quantization import EXL3Config
qcfg = EXL3Config(
bits=3.0,
device="cuda:0",
head_bits=6.0,
dynamic={
r".*\.self_attn\.(q_proj|k_proj)$": {"bits": 4.0},
r".*\.mlp\.down_proj$": {"bits": 4.0, "out_scales": "always"},
},
)With head_bits set and lm_head omitted, an untied output head is eligible for quantization subject to dynamic exclusions. If the head shares its weight with the input embeddings, quantize() warns before calibration, keeps the shared weight, and records lm_head=False on save. The saved head_bits value records the requested rate. An explicit lm_head=False also skips the head. An explicit lm_head=True on a tied head raises NotImplementedError before calibration. Head resolution
If no dynamic rule matches the head, the shared looper can inject a bits=8 override with GPTQ-specific fields. EXL3 validates numeric values in group_size, sym, desc_act, and mse overrides before dropping those unused fields, so a non-finite numeric value such as NaN or infinity still raises. A matching head rule can set a different bits, head_bits, or codebook. For a codebook with restricted rates, give the head a matching rule with compatible rates to avoid the implicit 8-bit override. Config validation
clone_exllamav3_config_for_module(qcfg, module_full_name) resolves dynamic selection, returns None for a disabled module, and applies the eligible overrides to a copy of the base config. It uses a matching rule's head_bits for the head when supplied and validates the resulting rates. EXL3 config · Per-module selection
EXL3 honors the default auto_dtype_cast="auto_nf12" source-storage policy on eligible devices/shapes. Its preprocessor keeps eligible source projections packed through calibration forwards; quant_source restores the exact original dense bits immediately before the solver consumes a projection. This reduces source storage, not the EXL3 output bitrate. auto_dtype_cast="off" disables that source policy. Fully excluded layers stay dense. See NF12 eligibility and source restoration flow.
The processor constructor is:
def __init__(
self,
tokenizer,
qcfg: QuantizeConfig,
calibration: CalibrationConfig,
forward: Optional[ForwardConfig] = None,
lm_head_name: str = "lm_head",
):
...EXL3Processor subclasses LoopProcessor, reports the name "exl3", and requests forward capture, ForwardConfig.replay_after_process=True, and ForwardConfig.subset_early_stop=True.
The calibration dataset is fixed at construction. set_calibration_dataset() raises NotImplementedError rather than replacing a capture in progress.
| Stage | Implementation behavior |
|---|---|
| Module selection | Clone the EXL3 config for the module; honor dynamic exclusion |
| Capture setup | Construct a GPTQ capture task with GPTQConfig(bits=max(1, runtime_bits), group_size=-1, desc_act=False, sym=True, act_group_aware=False) and the selected device/pack dtype |
| Forward hooks | Feed activation batches into the capture task; the GPTQ object is used for activation/Hessian collection, not GPTQ weight export |
| Hessian preparation | Finalize the captured Hessian on the target device, or supply an identity proxy with sample count zero when the projection takes the fallback |
| Weight layout | Present the EXL3 quantizer with (in_features, out_features) weights; transpose/restore ordinary linear weights as needed |
| Quantization | Call native EXL3 with one device, a supported K for the effective codebook, sigma_reg=0.025, seed 787, and the output-scale policy |
| Replay preparation | Stage packed tensors to CPU through the module stream-state payload and install reconstructed weights for the current sequential replay |
| Submodule finalization | Collect EXL3 buffers and replace the dense module with create_exllamav3_module()
|
| Model finalization | Set quantized=True, method/format to EXL3, and qlinear_kernel=ExllamaV3Linear
|
The captured Hessian payload passed to the CUDA/HIP quantizer is marked single_use=True. A durable capture frontier can retain capture state for reuse during quantization. Sequential replay lets later subsets observe already-quantized earlier projections.
The inherited EXL3Config.fallback defaults to Fallback(strategy=FallbackStrategy.RTN, threshold="0.5%"). A projection also takes the uncalibrated path when its positive token count is strictly below the resolved threshold. Setting fallback=None disables that threshold. Zero-token projections still take the uncalibrated path. EXL3 uses its RTN-equivalent trellis grid and warns if a different fallback strategy was requested. See the fallback implementation.
The public EXL3 branch rejects adapter/EoRA generation, GPTAQ/native activation capture, and FOEM/native activation capture with NotImplementedError.
The CUDA/HIP quantizer applies the existing diagonal regularizer (sigma_reg=0.025 in EXL3Processor) before the signed-Hadamard congruence, computes that transform in FP64, restores symmetry by averaging with its transpose, then stores the result in FP32 for factorization. This preserves the intended conditioning of highly correlated activations without increasing damping or introducing adaptive damping. It requires temporary FP64 matrix storage; it does not turn the whole quantization pipeline into FP64.
Symmetry restoration now averages tile pairs with edge size 1024 instead of allocating another full square mean/difference matrix. Capture finalization also releases deferred per-device Hessian partials before the memory-heavy EXL3 solve. The square FP64 working matrix is still required; these lifetime changes preserve the symmetry calculation and introduce no new quantization option.
The low-level quantize_exl3() call writes a versioned quant_args["error_metrics"] dictionary. Its schema is "gptqmodel.exl3-trellis-error" and schema_version is 1. It records the selected quantizer path, Hessian sample count, regularization/transform/symmetry metadata, selected global scale, scale-search MSE, and reconstruction metrics. Reconstruction includes MSE, NMSE, relative Frobenius error, finite-value checks, 16×16 tile-SSE percentiles, and up to 16 worst tiles by default.
These metrics describe the regularized EXL3 search space, not source-weight reconstruction or activation-output error. The Hessian path reports Hessian-weighted relative error; the fallback reports unweighted reconstruction MSE. Do not compare those scalar proxy values as if they were the same loss. If Hessian metric evaluation runs out of memory, hessian_metric_status is "out_of_memory", the structured relative-error value is None, and the legacy returned proxy is -1.0, not a successful accuracy measurement. EXL3Processor validates the structured metrics and records them in completed projection checkpoints when enabled.
These are distinct completion boundaries, not a single generic resume file. The processor and looper now connect the stores to capture, replay, and final export. Advanced recovery requires matching run/model/calibration provenance; merely setting a directory does not establish a valid reusable run.
| Artifact | Selection and behavior |
|---|---|
| Completed projections |
meta["ds4rt_error_ledger"]["run"]["projection_checkpoint"] selects the ds4rt.exl3-projection-checkpoint-v1 contract and a persistent root. Requests bind source/capture/quantizer identity; atomic safetensors publication and validation permit reuse of completed work. |
| Capture frontiers |
KernelConfig.exl3_capture_frontier selects persistent raw Hessian/sample-count/route-evidence storage. Capture identity, tensor specs and payload hashes must agree on restore. |
| Calibration-batch progress |
KernelConfig.exl3_capture_batch_spool selects the EXL3CaptureBatchSpool root; KernelConfig.exl3_capture_batch_checkpoint_interval is a positive integer, default 1. It commits cumulative capture state at batch boundaries. Verified committed indices can be skipped after restart rather than replayed into the same Hessian twice. |
| Final inference export |
model.save() publishes packed tensors and tensor-storage metadata. Resume uses the separate capture and projection stores. |
Namespace-scoped frontier cleanup distinguishes base from mtp: committing a base output must not delete MTP work. Cleanup prunes incomplete publications and validates committed manifests on restart; corrupt scoped state fails closed. Keep durable working stores and native source files until quantization and export have finished.
Projection-store discovery ignores writer-owned interrupted publication files shaped like .<request-sha>.json.<random> or .<request-sha>.safetensors.<random> under the request's correct two-level hash prefix. EXL3ProjectionCheckpointStore.prune() reclaims them as removed_orphans; they never count as committed results or block reservation/recomputation after a crash. Unknown hidden files, wrong prefixes, symlinks and corrupt committed pairs still fail closed. Pruning is for the serialized store owner, not a cross-process lock: do not run it concurrently with another writer. See projection publication recovery.
Natural MoE routing is recorded separately from recovery. An explicitly authorized under-coverage policy (meta["ds4rt_zero_route_recovery"], or the bound family contract) can top up captures below 1,024 rows from ranked router candidates in the same fixed calibration selection, then use the declared normalized identity residual where needed. Recovery evidence does not pretend these were natural top-k routes and does not change the model's inference router. Model-specific family contracts govern the exact recipe.
The deepseek_v4, dots3_note, glm_moe_dsa, and glm5_next definitions opt into the shared learned-router top-up with zero_route_recovery = True. If the EXL3 coverage policy schedules recovery for a definition without that capability, quantization raises a route-coverage error. Route recovery source
During decoder-block replay, recovery collects candidate rows through the block's learned router. With a complete calibration-batch spool, recovery reuses recorded router inputs and candidate rankings without replaying the block. GLM-5.3's checkpoint MTP layer is identified as base for recovery and uses the same decoder-block path. Recovery implementation · GLM-5.3 block identity
EXL3 quantizes each projection on the device assigned by the looper and can reuse a completed projection from its checkpoint store. The following legacy meta keys have no effect:
-
ds4rt_error_ledger.run.remote_workers(nested underds4rt_error_ledgerandrun) ds4rt_error_ledger.run.projection_checkpoint_seedds4rt_inline_mixedds4rt_inline_mixed_by_namespace
Constructing or loading a config with these keys warns once per key per process. Serializing the config drops them. Use per-module dynamic bits to assign fixed rates to selected projections. See retired ds4rt switches.
The per-projection error journal has been removed. Setting GPTQMODEL_EXL3_ERROR_JOURNAL now logs a retirement warning. meta.ds4rt_error_ledger.family_join still supplies route-recovery provenance, and meta.ds4rt_error_ledger.run.projection_checkpoint still selects the projection store. Older completed projections remain reusable when they pass validation. Retired environment variables
For the remaining durable execution schemas, see:
-
exl3_projection_checkpoint.py,exl3_capture_frontier.py, andexl3_capture_batch_spool.py. - Projection diagnostics and router recovery.
The main lower-level entry point is:
def quantize_exl3(
weight: torch.Tensor,
H_data: dict,
quant_args: dict,
return_weight_q: bool,
progress_str: str | None = None,
verbose: bool = False,
swap_to_device: torch.device | None = None,
save_reg: str = None
):
...It returns reconstructed quantized weights when requested, a proxy error, and packed output tensors. The main stages are:
- Normalize the Hessian by sample count, inspect its diagonal, and choose fallback for unusable capture statistics.
- Apply diagonal regularization, random signs, and Hadamard transforms; compute a block LDL factor for Hessian-aware quantization when applicable.
- Regularize transformed weight ranges and choose whether to use output scales.
- Select a global scale with golden-section search over sampled tiles.
- Quantize tensor-core-layout tiles through trellis/Viterbi kernels, using LDLQ error compensation or the fallback path.
- Reconstruct for the processor's replay/error reporting, then pack the trellis and emit scales/signs and codebook markers.
The tile encoder uses 256 encoded states per tile. pack_trellis() converts a three-dimensional encoded int16 tensor with last dimension 256 into packed shape (shape[0], shape[1], 256 * K // 16). The runtime reads K back as trellis.shape[-1] // 16.
Workers share a per-device quantization stream and its tile workspace; adding workers no longer creates another quantization stream or scratch pair for the same device/K/batch. The quantizer also contains multi-GPU tile-distribution machinery, but EXL3Processor._build_quant_args() supplies a one-device list per module. Do not interpret those lower-level helpers as a promise that one module is automatically split across every visible GPU.
from gptqmodel import GPTQModel
from gptqmodel.backend import EXL3CUDAConfig
model = GPTQModel.load(checkpoint, backend=EXL3CUDAConfig(fp16_gemv=True, fused_gemm=True))
EXL3CUDAConfig field |
Default | Effect on eligible projections |
|---|---|---|
fp16_gemv |
False |
Allows FP16-operand GEMV for supported shapes with up to eight rows. Q4NX also tries eligible GEMV by default when fused_gemm=False. |
fused_gemm |
False |
Enables fused packed GEMM for ordinary integer-rate weights. Half-bit weights already select fused GEMM. For Q4NX, True disables dense prefill and requires fp16_gemv=True to consider GEMV. |
int8_gemv |
0 |
0 disables INT8 activation GEMV. 1 uses residual INT8 for eligible single-row mul1 calls. 2 uses plain INT8 for eligible one- or two-row mul1 calls. |
GEMV selection depends on the device, codebook, packed rate, and dimensions. Eligible non-Q4NX calls can use FP16-operand GEMV on Blackwell sm_120 and sm_121. Its output Hadamard now runs as a separate kernel on the same stream, after all GEMV output tiles have been written. Q4NX retains its separate Ampere/Ada GEMV gate, and INT8 GEMV has its own eligibility rules. Native dispatch reference
On Ampere and Ada (sm_89), Q4NX calls that request an FP32 projection, including the native FP16/BF16 wrapper, can use a register-decoding GEMV for one to eight rows when the projection fits the architecture’s dispatch limits. On Ada, the kernel also considers a narrow band of wide-output shapes for 2.5 and 3.5 bpw. Blackwell continues to use packed GEMM for Q4NX decode. Ada also selects Q4NX-specific packed GEMM tiling and split-K limits for eligible shapes. For prefill on Ampere, the default policy can decode a temporary FP16 weight matrix and run HGEMM with FP32 output. This path covers projections with 4–24 Mi weight elements and starts at 64 rows for up to 12 Mi elements, or 128 rows for larger projections. The expanded weights use up to 48 MiB of call-local scratch. Allocation failure falls back to packed GEMM. Set EXL3CUDAConfig(fused_gemm=True, fp16_gemv=False) to pin Q4NX to packed GEMM. CUDA dispatch
On Ada, tuned packed Q4NX GEMM uses a dedicated launch table for 2.5, 3.0, and 3.5 bpw. All 585 rate and shape cells were measured on an RTX 4090; the table supplies the tile and split-K choices without the old fixed Ada overrides. Other architectures retain their previous launch samples. Q4NX launch table · Tuning methodology
The CUDA Q4NX encoder uses rate-specific candidate scoring to reduce search time at 2.5, 3.0, and 3.5 bpw. It uses the same checkpoint layout and codebook. Q4NX encoder
The extension also exposes gptqmodel.exllamav3.ext.exllamav3_ext.exl3_moe_coop for integrations that already have routed expert IDs and weights. It supports packed gate, up and down projections on NVIDIA SM80+ and requires caller-owned scratch. See the routed decode operator contract.
| Implementation | Execution and storage |
|---|---|
gptqmodel/nn_modules/exllamav3.py — ExllamaV3Linear
|
Holds EXL3 buffers and a meta placeholder weight. FP16 and BF16 inputs on NVIDIA CUDA or supported HIP use native LinearEXL3 after the finiteness probe passes. FP32 inputs, materialized trellises off those devices, and FP16/BF16 inputs that fail the probe use a borrowed-buffer ExllamaV3TorchLinear helper. |
gptqmodel/exllamav3/modules/quant/exl3.py — LinearEXL3
|
On CUDA, uses BC_LinearEXL3 or reconstruct + Hadamard + HGEMM. R4NX uses reconstruction for all batch sizes. For 3inst, mcg, and mul1, the default reconstructs above 32 flattened rows. |
| ROCm inference | AUTO selects EXL3_EXLLAMA_V3 when every selected GPU is an eligible gfx120x target and the HIP extension passes the availability probe. Otherwise AUTO selects EXL3_TORCH. See native ROCm inference for kernel dispatch. |
gptqmodel/nn_modules/exllamav3_torch.py — ExllamaV3TorchLinear
|
Decodes the current trellis in bounded output chunks, applies block-128 Hadamard transforms, multiplies, adds bias, and casts to input dtype; no persistent dense weight cache |
gptqmodel/nn_modules/qlinear/mlx_exl3.py — MlxEXL3Linear
|
Native Metal row/matrix kernels over packed trellises, including codebook state decoding and optional output/bias fusion |
The EXL3 wrapper files are under nn_modules/, not nn_modules/qlinear/exllamav3.py or nn_modules/qlinear/exllamav3_torch.py in this revision.
The native wrapper restores unpacked Hadamard sign vectors suh/svh to FP16 after model-wide dtype/device moves, in post_init(), and before constructing its inner runtime. This prevents BF16 checkpoint loading from failing with suh is wrong datatype; packed su/sv remain int16.
For FP16 inputs on NVIDIA, the reconstruction path keeps the cuBLAS product, output Hadamard transform, and bias addition in FP32 before returning FP16. The packed GEMM also keeps split-K partials, output scales, and bias in FP32 through the final conversion. Reconstruction path · Packed dispatch
Native LinearEXL3 returns an empty output with its declared output width when the flattened batch has zero rows, without launching Hadamard/HGEMM work. The outer wrapper still crops padded output channels to the logical width. The low-level single/dual Hadamard wrappers also return before a zero-grid CUDA/HIP launch while retaining their existing dtype checks. Empty input does not relax the stored block-128 geometry contract.
Logical dimensions remain those of the model architecture even when EXL3 stores a padded output width for its 128-channel transform. Native and Torch wrappers validate storage geometry against the logical dimensions, compute with the stored width, and crop outputs back to out_features; the Torch wrapper also crops explicit dequantization results. Keep padded svh/trellis shapes and logical bias width consistent; malformed metadata raises rather than changing the model's projection size.
Generic EXL3 quantization now validates positive in_features % 128 == 0 before calibration; input channels are not automatically padded. Any positive output width is zero-padded in stored columns to the next multiple of 128, then cropped back to the logical width at runtime and when restoring a dense source. Before every subset forward and post-process replay, the looper refreshes deferred runtime weights for the whole layer, not just the current subset. This prevents earlier packed projections from reaching later forwards as META tensors. Restored dense weights are current-computation state, not a persistent inference cache. See runtime refresh and geometry.
For native padded outputs, the inner runtime receives a widened bias copy. In-place changes to the logical bias invalidate that copy through version tracking. A bias created under torch.inference_mode() is copied once outside inference mode so the first forward does not fail while reading a missing version counter; unchanged subsequent forwards reuse the inner runtime. This is bias-vector bookkeeping, not a retained dense-weight cache.
Runtime signatures also track ordinary in-place edits to packed buffers and metadata. Small inference-created suh, svh, su, sv, mcg, mul1, q4nx, and r4nx tensors are copied once to versioned tensors before handle construction so later edits invalidate derived sign/codebook state. The packed trellis is not duplicated for this normalization; call clear_weight_cache() after externally mutating an unversioned inference trellis in place.
The native FP16/BF16 wrapper bounds each input row before the FP16 input Hadamard. It checks both the raw input and its product with the checkpoint's suh scales. If either absolute maximum exceeds 65504 / sqrt(128), the row is divided by the smallest power of two that brings it within the bound; other rows keep a scale of one. The first nonempty call with finite bounds warms the module, so later calls compute scales on-device without a host finiteness check.
On eligible NVIDIA CUDA tensor-core GEMMs, the input Hadamard computes the bound and applies the row scale, and the GEMM epilogue undoes the scale and adds the unscaled checkpoint bias before rounding once. This avoids separate guard launches. BF16 with suh uses FP64 for the bound and rescale arithmetic so an FP32 exponent limit does not overflow the intermediate scale. The final cast still requires the result to fit the output dtype.
ROCm, R4NX, explicit GEMV policies, non-Q4NX inputs above 32 flattened rows, Q4NX without fused_gemm, and builds without the guarded GEMM keep the separate pre-scale and rescale path. That path requests an FP32 result from the native multiplication and uses the separate fused scaling operators when available, or their eager equivalents otherwise. There is no new user setting for the folded guard. Native wrapper · Guard dispatch
Native ExllamaV3Linear is also treated as graph-breaking for static-cache generation. The default skips auto-compilation but keeps the static cache available.
FP32 inputs and FP16/BF16 inputs that fail the initial probe use bounded Torch reconstruction/matmul, including non-contiguous views, and restore the input dtype. A failed probe is retried on the next eligible forward. The borrowed-buffer helper is not registered as a child module, so it adds no duplicate checkpoint keys. Cache clear and module-wide device/dtype moves discard derived helpers/handles; ordinary checkpoint-buffer updates are detected by their signatures before reuse. See activation dispatch.
When the wrapper's trellis is materialized off CUDA, every activation dtype takes that portable helper before native dispatch. This makes FP16 in-session inference work after quantization leaves packed layers on CPU. With the native wrapper, moving buffers and inputs to NVIDIA CUDA or supported RDNA4 restores eligible native dispatch; an absent/meta trellis still follows the existing validation path. Use EXL3_TORCH for portable CPU or ROCm loading.
Native and Torch handle construction, publication, and teardown share a per-module lock, preventing concurrent first forwards from receiving a transient missing handle. Copies recreate that lock and discard inherited runtime handles so they rebuild from packed buffers; packed checkpoint tensors are unchanged.
The extension reconstruction path allocates an inner FP16 weight for the consuming multiplication; get_inner_weight_tensor() does not retain it on the module. The Torch fallback also reconstructs for the current operation rather than caching a dense model. Its CPU arithmetic uses FP32, with a conditional oneDNN BF16 path when the CPU and problem size qualify. That path requires AVX512 BF16 and MKLDNN support, is enabled by default through KernelConfig.cpu_bf16x3_matmul, and uses a size threshold of either 1 << 19 weight elements or 1 << 23 multiply-accumulates. Output decoding is chunked in groups of 32 output tiles.
FP32 reconstruction does not mean that codebook rounding can be skipped. The Torch lookup table reproduces the native half-precision decoder law before widening to FP32: 3inst/mcg round the half-value sum like __hadd, and mul1 rounds once after the multiply-add like __hfma. This corrects Torch/native decoded-value discrepancies without changing packed trellises or requiring checkpoint conversion. tests/test_exl3_native_half_rounding.py checks all 65,536 states for each codebook against an independent scalar law, including signed-zero bits; it is a decoder-value contract, not a promise of bit-identical complete backend matmuls.
The portable Torch forward disables ambient autocast for both Hadamard transforms, the tiled projection, and the bias add. This prevents FP16 autocast from overflowing an intermediate Hadamard result before the projection. The forward restores the caller's autocast state and returns the activation input dtype. See the portable Torch forward.
The Torch backend creates its cached Hadamard matrices, permutations, and codebook tables outside inference mode. Warming up with generate() or torch.inference_mode() therefore leaves those constants usable by later forwards that compute input gradients, including in another model in the same process. See the Torch runtime cache contract.
ExllamaV3TorchLinear.optimize(backend="inductor", mode=None, fullgraph=False) is an explicit CPU compilation opt-in. A compiled-forward error falls back to eager execution. It should not be confused with a different checkpoint format or an unconditional compilation step during loading.
The lower-level native quantization signature is:
Developer API signatures (not a runnable example)
def exl3_quantize_weight_mlx(
weight,
hessian,
input_signs,
output_signs,
*,
sample_count: int,
bits: int,
codebook: str = "3inst",
force_output_scales=None,
sigma_reg: float = 0.025,
workspace_bytes: int = 256 << 20,
):
...Note that this low-level function's codebook="3inst" default differs from EXL3Config.codebook="mcg"; the processor passes its configured choice explicitly.
| Input/setting | Native MLX contract |
|---|---|
weight |
Nonempty rank-2 FP32 array in (in_features, out_features) layout; both dimensions divisible by 128 |
hessian |
FP32 square matrix matching the input-feature dimension |
input_signs |
FP32 (in_features, 1)
|
output_signs |
FP32 (1, out_features)
|
bits |
Integer 1 through 8; booleans rejected |
codebook |
3inst, mcg, or mul1
|
workspace_bytes |
Positive integer, default 256 << 20
|
The return tuple contains reconstructed weight, proxy error, packed trellis, FP16 input scales, FP16 output scales, fallback decision, selected global scale, and output-scale decision. The Torch bridge returns the reconstructed weight, a Python proxy-error value, and a dictionary of tensors; it seeds input/output signs on CPU and uses DLPack transfers.
| Module family | Responsibility |
|---|---|
mlx_exl3.py |
Viterbi tile encoding, state decode, trellis packing |
mlx_exl3_tiles.py |
Tensor-core tile layout transforms |
mlx_exl3_hadamard.py |
Block-128 Hadamard transforms |
mlx_exl3_hessian.py, mlx_exl3_block_ldl.py
|
Hessian finalization, transforms, block LDL |
mlx_exl3_rms.py, mlx_exl3_regularize.py
|
RMS/range regularization and scale selection |
mlx_exl3_gss.py |
Global-scale search |
mlx_exl3_ldlq.py, mlx_exl3_fallback.py
|
Hessian-aware or fallback tile quantization |
mlx_exl3_pipeline.py |
End-to-end orchestration and Torch bridge |
MlxEXL3Linear(in_features, out_features, bits, codebook="3inst", bias=False) requires positive input/output dimensions divisible by 128 and integer bitrates 1–8. Its activation inputs may be FP16, BF16, or FP32; the result is cast back to the activation dtype. gptqmodel/utils/mlx.py transfers packed trellises, scales, and codebook information and can decode legacy packed signs. MLX inference availability does not bypass the public quantization guard documented above.
gptqmodel/utils/exllamav3.py owns these operations:
| Function | Role |
|---|---|
_resolve_linear_shape(submodule) |
Resolve features from NamedModule state, nn.Linear, convolution/Transformers Conv1D, or feature attributes |
create_exllamav3_module(*, module_root, name, submodule, tensors, module_cls=ExllamaV3Linear) |
Build from packed tensors and replace the named module |
build_exllamav3_tensor_storage(model) |
Collect tensor_storage_entry() from EXL3 modules |
replace_exllamav3_placeholders(*, model, module_names, tensor_storage=None, module_cls=ExllamaV3Linear) |
Replace supported dense placeholders before loading tensor values |
On save, the writer rebuilds tensor_storage from the actual modules. Entries contain stored_tensors keyed by full tensor names with shape and torch_dtype, quant_format="exl3", exact bits_per_weight, and optional mcg_multiplier/mul1_multiplier. This metadata lets the loader allocate the correct packed buffers before loading checkpoint shards.
For lazy exports that pass through native tensors, the writer uses the loaded model to determine which source entries to republish, including entries reached through checkpoint aliases. See native EXL3 passthrough.
On load, a nonempty quantization_config.tensor_storage dictionary is mandatory. The loader chooses ExllamaV3TorchLinear placeholders for EXL3_TORCH or MLX and ExllamaV3Linear for the extension route. Keeping only a bits value and removing the tensor metadata is insufficient to recreate an EXL3 checkpoint.
The vendored util/ helpers provide architecture-list handling (arch_list.py), Hadamard support (hadamard.py), memory/tensor workspaces (memory.py, tensor.py), miscellaneous helpers (misc.py), and progress reporting (progress.py). These support the integration; they are not alternate public quantization methods.
EXL3 and VPTQ both use calibration/Hessian information and nonuniform weight representations, but they have separate configurations, processors, tensor layouts, and runtimes. VPTQ's implementation learns vector codebooks using weighted k-means and optionally residual codebooks; EXL3 uses its trellis/codebook decoder families. The EXL3 path does not call VPTQ's quantizer or interpret VPTQ index tensors. A VPTQ checkpoint is not an EXL3 checkpoint, and selecting an EXL3 backend is not a VPTQ conversion.
docs/exl3-mi350x-quant-lifecycle.md is a profiling record for a specific ROCm run. It explicitly excludes inference kernels. Its figures are not general throughput guarantees.
| Measured item | Recorded value |
|---|---|
| Accelerator | One MI350X, gfx950, 256 CUs |
| Model |
tiny-qwen2-base, hidden size 896, six layers, 42 quantized modules |
| Quantization | EXL3 4-bit, K=4, mcg
|
| Calibration | Eight samples, 136 tokens |
| Steady-state wall time | 7.97–8.02 seconds |
| Warm run | 14.6 seconds |
| Dominant GPU kernel |
quantize_tiles_kernel<4, 1>, 91.9% of profiled GPU time |
| Mean concurrent tile kernels in the trace | Approximately 1.155 |
The record explains why a latency-bound trellis kernel can leave a large GPU underoccupied, why isolated multi-stream launches scale better than the complete layer pipeline, and how sequential subsets/replay create synchronization barriers. Per-layer attention and MLP subsets have different numbers of independent chains. GPU-time sums include overlapping kernels and must not be equated with wall time. Optimization conclusions in that document concern scheduling, stream overlap, workspace, and occupancy for that workload—not EXL3 inference performance or model quality.
| Symptom or assumption | What to check |
|---|---|
Fractional bits/head_bits raises |
Use 1.5, 2.5, or 3.5 with mul1, or 2.5 or 3.5 with q4nx or r4nx. Check the effective codebook in matching dynamic rules. |
Setting group_size, desc_act, or sym changes nothing |
EXL3 forces -1, False, and True; these are not GPTQ tuning knobs here |
The output head stays dense with head_bits set |
Check for tied input embeddings, lm_head=False, and matching dynamic exclusions. |
| Head quantization fails on a tied-weight model | Untie the head weight first; the shared looper rejects tied head parameters |
| CPU/MPS EXL3 quantization fails despite MLX pipeline files | Public quantize() still requires CUDA/HIP in this revision |
| Tile encoder reports insufficient shared memory | Check required/available bytes. The automatic compact K=2 layout fits 64 KiB GPUs; other unsupported layouts require a higher bitrate such as bits >= 3
|
| CPU inference raises a CUDA/HIP error | Load with EXL3_TORCH, not the extension wrapper |
AUTO selects native EXL3 and the extension later fails to load or build |
On ROCm, the availability probe checks for registered operators, a library, or a HIP toolchain without compiling the extension. Load with EXL3_TORCH to use the portable backend. |
EXL3 tensors are on meta
|
Materialize checkpoint tensors before forward/post-initialization |
| Load fails before weights are read | Preserve nonempty tensor_storage metadata and valid EXL3 method/format |
| Missing calibration capture | Supply a dataset and ensure selected modules execute during capture |
| Native EXL3 inference is rejected on ROCm | Check that the selected GPU is gfx1200 or gfx1201 and that the HIP extension can load. Use EXL3_TORCH for other ROCm targets or to avoid the extension. |
| BF16 input is assumed to imply BF16 extension arithmetic | Native CUDA and HIP use FP16 operands after the finiteness probe passes. FP32 inputs and FP16/BF16 inputs that fail the probe use bounded Torch reconstruction. Output retains the input dtype. |
| Adapter, GPTAQ, or FOEM requested during EXL3 quantization | Unsupported in the public EXL3 processor branch |
| An upstream ExLlamaV3 artifact is assumed interchangeable solely by its name | Validate GPT-QModel's expected tensor layout and tensor_storage; format provenance alone is not a loader guarantee |
-
docs/exl3-numerical-diagnostics.md— conditioning and diagnostics flow; low-level helpers are not implicitly connected to capture/storage policies. -
gptqmodel/quantization/config.py— EXL3 enums, normalization, config, serialization, integer runtime width. -
gptqmodel/looper/exllamav3_processor.py— capture, per-module config, quantizer dispatch, replay and replacement. -
gptqmodel/looper/module_looper.py— shared head selection, injected dynamic defaults, and tied-head validation. -
gptqmodel/utils/exllamav3.py— module construction and tensor-storage metadata. -
gptqmodel/nn_modules/exllamav3.py— extension-backed Torch module. -
gptqmodel/nn_modules/exllamav3_torch.py— Torch runtime and CPU optimization. -
gptqmodel/exllamav3/ext.py— extension loading/building and runtime diagnostics. -
gptqmodel/exllamav3/modules/quant/exl3.py— vendored runtime dispatch. -
gptqmodel/exllamav3/modules/quant/exl3_lib/quantize.py— Hessian finalization, regularization, LDLQ, scale search, packing, streams. -
gptqmodel/exllamav3/util/{arch_list,hadamard,memory,misc,progress,tensor}.py— runtime/quantization support. -
gptqmodel_ext/exllamav3/— native extension sources. -
gptqmodel_ext/exllamav3/quant/quantize.cu— tile encoder, compact 2-bit layout, and per-device shared-memory guard. -
gptqmodel/quantization/mlx_exl3*.py— native MLX quantization stages listed above. -
gptqmodel/nn_modules/qlinear/mlx_exl3.py— Metal inference. -
gptqmodel/utils/mlx.py— MLX model transfer and packed payload handling. -
gptqmodel/models/base.py,loader.py,writer.py— public guards, processor selection, loading and saving. -
gptqmodel/quantization/vptq.py— separate VPTQ algorithm, for comparison. -
docs/exl3-mi350x-quant-lifecycle.md— MI350X measurement record.
Documentation home · Quickstart · Troubleshooting · Repository · PyPI
Public source 775013e41 declares package version 7.14.0. Individual pages identify their source revisions. Choose a method · Dtypes and formats. Maintained by ModelCloud.ai.
🧭 1 · Choose and understand
🚀 2 · Use it
- Installation and Quickstart
- Loading and Inference
- LeapQuant recurrent-state quantization
- Evaluation
- Serving
- Troubleshooting and FAQ
- Memory, Offload, Multi-GPU
- MLX / Apple Silicon
- Tenstorrent / Block Floats
- Hugging Face Integration
- Multimodal and MoE Models
🎛️ Methods and representations
Each guide: choose → examples → math / advanced
- GPTQ / GPTAQ / G2PTQ / ADMM-Q / RTN
- SINQ
- JointQ
- AWQ
- QQQ
- MACaQ / MXFP4
- EXL3
- CPTC
- VPTQ
- Tetra
- TWLA
- Paro
- FP8 and NVFP4
- NF12: lossless BF16 storage
- GGUF families
- BitsAndBytes: NF4 / FP4 / INT8
🧰 Refinement and execution
- GSQ refinement / allocation
- EoRA adapters
- Rotation, Smoothing, Norm Tuning
- Projection Fusion
- TurboQuant KV cache
🧠 3 · Theory and advanced reference