Repository navigation
Quantization Lifecycle
🏠 Home · 🧭 Choose a method · 🚀 Quickstart · 🧰 Help
On this page
- Overview
- 🧭 Choose the path before you load
- 🚀 Use it: prepare → quantize → save
- Workflow at a glance
- 🔬 Go deeper: orchestration and ownership
- Concepts and ownership
- Public entry point
- CalibrationConfig: data and policy
- End-to-end call graph
- 1. Entry validation and preparation
- 2. Calibration data ingestion
- 3.
ModuleLoopersetup and initial input capture - 4. Layer planning and execution:
stage_layer.py - 5. Subset planning, coverage, and processing:
stage_subset.py - 6. Cached forward replay:
forward_executor.py - 7. Preprocessing, dense sources, and linear runtime modes
- 8. Finalization, offload, and garbage collection
- 9. Checkpoints and continuation/resume
- 10. Weight-only lifecycle
- 11. Native and dequantization passes
- Errors, edge cases, and operational guidance
- Source files
- See also
Understand what happens between loading dense weights and saving a reusable quantized checkpoint, so you can plan calibration, memory, and recovery. For: recipe authors and engineers debugging a quantization run.
BaseQModel.quantize() converts a loaded source model into a model whose selected modules contain packed quantized weights. It is not one model-wide weight conversion: the calibration path captures the decoder's initial inputs, replays layers in model-defined calculation groups, collects algorithm-specific statistics, solves each selected module, replays the reconstructed weights, and finally packs and optionally offloads the replacements.
There are two distinct execution paths:
| Path | Selection | Orchestrator | Calibration forwards |
|---|---|---|---|
| Calibration-based |
quantize_config.uses_weight_only_lifecycle() returns False
|
ModuleLooper |
Input capture, subset statistics, and post-process replay as required by the processors |
| Weight-only | That method returns True
|
WeightOnlyLooper with WeightOnlyProcessor
|
None; conversion uses the source weights directly |
This page follows the implementation at source revision 1d58e66db. Internal hooks, checkpoint schemas, and supported combinations are revision-sensitive. The processor reference is Looper Processors; configuration fields are described more broadly in QuantizeConfig Reference.
| Choice | Choose this when | What you pay for / when to reconsider |
|---|---|---|
GPTQ: GPTQConfig(...)
|
You want calibration-statistic-guided weight error compensation | Representative inputs, Hessian/solver memory, and layer replay; not a quality guarantee |
GPTAQ: GPTQConfig(gptaq=GPTAQConfig(...))
|
You want GPTQ with correction informed by pristine-versus-quantized inputs | Extra pristine-input work and storage; excluded from resumable checkpoints in this source |
RTN: RTNConfig(...)
|
You need calibration-free weight rounding and a simpler conversion lifecycle | No GPTQ calibration compensation; evaluate its quality separately even with the same GPTQ export format |
| Other method | Your target number system/runtime requires it | Check requires_calibration_dataset() and uses_weight_only_lifecycle() instead of guessing from bit width |
These are recipes/lifecycles, not three interchangeable storage dtypes. RTN can write a GPTQ-family layout without running the GPTQ solver. GPTQ W4A16 is still calibration-based even though activations remain floating point at inference. See GPTQ for algorithm intuition/math and Choosing a Method and Dtype for broader trade-offs.
Before running: use a registered dense model, a compatible backend/device, and a bounded representative calibration corpus. A quantization run may need substantially more memory than the final packed checkpoint. Keep original source files, temporary offload, resume state, and final export in separate locations.
from gptqmodel import CalibrationConfig, GPTQModel, QuantizeConfig
config = QuantizeConfig(
bits=4,
group_size=128,
device="cuda:0",
offload_to_disk=True,
offload_to_disk_path="./quant-work/offload",
)
model = GPTQModel.load("MODEL_REPO_OR_LOCAL_PATH", config, dtype="bfloat16")
# API demo only: replace these two tiny strings with a representative corpus.
calibration = [
"A representative calibration passage with enough tokens to pass length filtering.",
"Another representative passage covering the language and tasks used by the model.",
]
quantization_log = model.quantize(CalibrationConfig(dataset=calibration, batch_size=1, sort="desc"))
model.save("./quantized-model")The small list illustrates the API, not a calibration-quality recommendation. LoopProcessor warns when the supplied dataset has fewer than 256 items or the prepared average input length is below 256; these are warnings, not minimum-size validation gates.
from gptqmodel import GPTAQConfig, GPTQConfig, RTNConfig
# Pick ONE before loading a fresh source model:
gptq = GPTQConfig(bits=4, group_size=128)
gptaq = GPTQConfig(bits=4, group_size=128, gptaq=GPTAQConfig(alpha=0.25))
rtn = RTNConfig(bits=4, group_size=128)For RTN, load the fresh source with rtn and call model.quantize(calibration=None); the weight-only orchestrator does not capture calibration forwards. For GPTQ/GPTAQ, supply the actual calibration corpus. model.quantize(...) mutates the wrapper and returns logs. On success, the wrapped Torch model and newly packed layers are in evaluation mode, so immediate inference uses the evaluation path used after reload. Save with model.save(...), then reload the saved artifact for quality and runtime checks.
When you leave the dense source dtype on auto and set quantize_config.device, the loader uses that device family for dtype selection, subject to model and backend dtype requirements. This applies even when the host has an accelerator and the requested quantization device is CPU. See the source loader.
| Boundary | What you have | What you do not have yet |
|---|---|---|
GPTQModel.load(..., quantize_config=...) |
Prepared source model and selected recipe | Quantized weights |
| Capture/solve/replay | Statistics and temporary reconstructed weights used for subsequent calibration | A final exported model; InputCache is not a generation KV cache |
| Finalize/pack | Packed modules plus optional temporary offload backing | A durable inference checkpoint unless saved |
model.save(...) |
Final inference artifact with config/tokenizer and packed payload | Proof of accuracy or serving-engine compatibility |
CheckpointConfig boundary |
Supported continuation state and referenced working files | An inference export, or permission to change run identity |
Next: evaluate the saved checkpoint, understand memory pressure, or inspect resume restrictions.
Public source for this guide: gptqmodel/models/base.py · gptqmodel/quantization/config.py · gptqmodel/looper/module_looper.py · gptqmodel/looper/weight_only_looper.py. Examples and declarations target revision 1d58e66db; source citations below use the same implementation revision.
Reading the diagram: The lanes are alternatives. A later save() exports the model; it is not a quantization resume checkpoint.
Text version of the workflow
- Calibration-based: Prepare calibration → Capture first inputs → Quantize layer subsets → Finalize model.
- Weight-only: Select conversion → Walk weight targets → Convert and pack → Finalize model.
Follow the numbered stages for the calibration path, then the separate weight-only path. The same source model can require different workspaces and replay depending on the chosen method; a packed bit width alone cannot predict peak memory.
| Object | Owns | Does not mean |
|---|---|---|
BaseQModel |
Model definition, source-weight materialization, config, tokenizer, model-specific preparation/replay hooks, selected packing kernel | An individual quantization algorithm |
ModuleLooper |
Layer/subset order, processor chain, forward executor, device assignment, finalizer scheduling, extension boundaries | A global choice of the numerical algorithm independent of the config |
LoopProcessor |
Per-algorithm tasks, calibration cache, hooks, results, logs, packing/finalization | One instance per linear; an instance serves many modules |
NamedModule |
Stable relative/full names, layer index, module dtype, shared per-module state, synchronized access and stream-transfer helpers | A separate persistent copy of all model weights |
InputCache |
Positional layer inputs and batch-aligned replay metadata | A generation KV cache |
SubsetPlan |
Resolved execution policy for a calculation group or chunk | A checkpoint or a user configuration object |
DeviceAssignmentState |
Continuation of the quantization scheduler's device cursor and assignments | Automatic remapping onto another GPU topology |
LoopExtensions |
Synchronous start/boundary callbacks | A background event bus or a serialization format |
Three different products must be distinguished:
- Reconstructed weights are floating-point tensors produced by a quantizer. They are temporarily assigned to a dense module so later calibration replay sees the quantization error.
-
Packed modules are replacements created in
submodule_finalize(). Their persistent representation is method/backend-specific: packed codes and scales, codebooks, EXL3 tensors, or other supported quantized layouts. -
Saved inference models are produced separately by
model.save(...). Neither a temporary offload directory nor a resumable quantization checkpoint is an inference export directory.
The callable signature in gptqmodel/models/base.py is reproduced below, with source comments omitted:
def quantize(
self,
calibration: Optional[CalibrationConfig] = None,
*,
tokenizer: Optional[PreTrainedTokenizerBase] = None,
backend: Optional[Backend] = BACKEND.AUTO,
adapter: Adapter = None,
embed_quant_config: Optional[Union[QuantizeEmbedConfig, QuantizeEmbed]] = None,
embed_quant_mode: Optional[QuantizeEmbed] = None,
checkpoint: Optional["CheckpointConfig"] = None,
fuse: Optional[bool] = None,
measure_weight_error: bool = False,
) -> Dict[str, List[Dict[str, str]]]:
...| Argument | Default | Lifecycle effect |
|---|---|---|
calibration |
None |
An unbound CalibrationConfig. Leave it unset for weight-only runs or MoEQuant EBSS with default preparation. Other calibrated runs require a dataset. |
tokenizer |
None |
A supplied PreTrainedTokenizerBase replaces the wrapper tokenizer through Tokenicer.load; other types are rejected |
backend |
BACKEND.AUTO |
Normalized together with method, format, activation mode, and device before validating/selecting the packing kernel |
adapter |
None |
Replaces quantize_config.adapter when supplied; a Lora requests EoRA processing |
embed_quant_config |
None |
Normalized embedding conversion request; also accepts a QuantizeEmbed value. Fresh runs support only OUTPUT with an untied head, subject to the method and head layout. |
embed_quant_mode |
None |
Compatibility alternative; cannot be supplied together with embed_quant_config
|
checkpoint |
None |
Must be a CheckpointConfig; activates additional support validation, store lease, signal handling, and boundary persistence |
fuse |
None |
Inherit the wrapper's fusion opt-in. True requests qualified post-quantization QKV/gate-up fusion; False disables it. A requested definition contract is validated before calibration. Not a QuantizeConfig field; see Projection Fusion. |
measure_weight_error |
False |
Opt into per-module weight reconstruction MAE for direct-pack GGUF, BitsAndBytes, NF12, and CPTC. Logging only; does not change packed weights. |
The return value is the looper's mapping from processor labels to log-row lists. The annotation describes string-valued rows, but actual rows can contain additional numeric/structured diagnostic values. Treat the return as quantization diagnostics, not as the packed model; the model is mutated in place.
CalibrationConfig is the public frozen dataclass in gptqmodel/quantization/config.py, exported from both gptqmodel and gptqmodel.quantization. Use it for quantize(), requantize(), and GPTQModel.adapter.generate(). The looper processors consume this same class.
from gptqmodel import CalibrationConfig
calibration = CalibrationConfig(
dataset=calibration_texts,
concat_size=2048,
sort="desc",
batch_size=1,
min_length=10,
concat_separator=None,
exclude_attention_sinks=False,
)
model.quantize(calibration)| Field | Default | Contract |
|---|---|---|
dataset |
None |
Collection or iterable of supported samples. Required for calibrated runs except EBSS, which requires this field to be unset. A bare str, bytes, or another CalibrationConfig raises TypeError. |
concat_size |
None |
Optional positive integer window length. None disables packing; 0 is rejected |
sort |
"desc" |
"asc", "desc", "shuffle", or None to retain input order |
batch_size |
1 |
Positive integer or the exact string "auto". Model definitions can force the effective batch size to one; staged GPTQ GSQ prepares single-document rows |
min_length |
10 |
Nonnegative integer; ordinary text preparation removes rows with this many or fewer non-padding tokens |
concat_separator |
None |
Optional string inserted between samples in the same window, only if at least one token from the next sample also fits; None is an empty separator |
exclude_attention_sinks |
False |
Strict bool; excludes every attended BOS from supported statistics while preserving forward execution. See method restrictions |
adapter_dataset |
None |
Optional EoRA samples with the same preparation policy; None reuses dataset. A bare string/bytes/config is rejected; separate adapter samples require a Lora adapter |
Integer fields reject booleans and floats. Construction validates the policy; the model still validates dataset contents and method-specific restrictions. prepare_dataset is an internal non-constructor field set by bind(), which returns a validated copy. Pass an unbound config to quantize(); a pre-bound object raises ValueError. To change the frozen policy, construct another config or use dataclasses.replace().
CalibrationConfig(dataset=calibration, batch_size="auto") opts into automatic sizing for standard calibrated model.quantize(), norm tuning with model.requantize(norm=...), and standalone model.adapter.generate(). It chooses a power of two up to 16, capped by the normalized example count, using 25% of reported free device memory as its activation budget. The estimate uses floating-point element size and the text decoder's width and layer count when the model exposes it through get_text_config(). It uses a batch of one when either decoder dimension is unavailable or the device does not report free memory, as on CPU.
The estimator counts normalized rows, including for DataFrames and columnar mappings. It uses concat_size when set. Otherwise it checks pretokenized lengths along the last sequence axis and samples up to four plain-text and four chat rows, choosing candidates by character count. Chat samples go through the calibration chat-template path before token counting. If no length can be measured it assumes 512 tokens. Staged GPTQ GSQ still prepares single-document rows. See the batch estimator and model entry points.
tokenizer= remains a keyword-only model argument: it replaces the tokenizer used for calibration, generation, and saving. EoRA binds a copy of the same policy to its selected samples with sink exclusion disabled. Norm tuning rejects sink exclusion and separate adapter samples; staged GPTQ GSQ also rejects both fields. Weight-only methods can call model.quantize() with no config; a supplied dataset is ignored.
Bare datasets, removed calibration keywords, and old positional arguments after calibration now raise TypeError; there is no compatibility alias. All remaining quantize() / requantize() options are keyword-only. The defaults preserve the former quantize() preparation policy, except that disabling concatenation must use None rather than 0.
| Former argument | Current location |
|---|---|
Dataset passed directly to quantize(data) / requantize(data, ...)
|
CalibrationConfig(dataset=data) as calibration
|
calibration_concat_size |
CalibrationConfig.concat_size |
calibration_sort |
CalibrationConfig.sort |
batch_size |
CalibrationConfig.batch_size |
calibration_data_min_length |
CalibrationConfig.min_length |
calibration_concat_separator |
CalibrationConfig.concat_separator |
calibration_exclude_attention_sinks |
CalibrationConfig.exclude_attention_sinks |
adapter_calibration_dataset |
CalibrationConfig.adapter_dataset |
Adapter generation: calibration_dataset, calibration_dataset_concat_size, calibration_dataset_sort
|
calibration=CalibrationConfig(dataset=..., concat_size=..., sort=...) |
Adapter generation now defaults to sort="desc" through CalibrationConfig; use sort=None to preserve its former unsorted default. The lower-level dataset helper retains its calibration_dataset_* / calibration_data_min_length parameter names; those are not accepted public model-call keywords. See the source migration guide.
Both loopers publish the first nonempty log in run-plan order whose processor owns the quantization log (owns_quant_log=True) on model.quant_log, without a quantizer-name allow-list. Auxiliary EoRA rows describe adapter fitting and opt out, so they neither duplicate module rows in quant_log.csv nor replace quantization statistics. If no owning processor recorded rows, an existing model log is preserved (or initialized empty when absent), including during standalone adapter generation. model.save() can therefore emit quant_log.csv for methods beyond GPTQ/QQQ/AWQ, provided their primary processors recorded per-module rows. This model-level CSV is separate from the returned per-processor diagnostics and retained diagnostic files; see processor log ownership.
After successful finalization, both calibration and weight-only paths print Quantize summary: with layer/module counts, elapsed duration, and, when supported, peak VRAM ... GiB (per-device max). This is the largest peak allocation among GPUs actually used by the run, not a sum or necessarily the current GPU. The summary follows after_quantize() and requested fusion/runtime installation; failed finalization does not print a success summary. Internal processor-label logs are normalized into layer/module counts before reporting.
Fusion remains disabled unless explicitly requested through loading,
quantize(..., fuse=True), or model.fuse(). Finalization applies a requested
plan after successful quantization. To obtain an inspectable plan afterward,
use plan = model.fuse(); quantize() does not return it. An unqualified
definition raises, while a qualified plan can contain only skipped groups.
BaseQModel.quantize(...)
normalize embedding arguments; validate config/checkpoint/model state
normalize method/format/backend; validate/select qlinear kernel
optional tokenizer replacement, adapter override, rotation
quant_blas_backend()
uses_weight_only_lifecycle() == False
_quantize_with_calibration(...)
construct processors (optional Native / ModulePreProcessor / primary / Eora)
optional DEVICE_THREAD_POOL.no_auto_gc()
optional checkpoint_session(...)
ModuleLooper(...).loop(...)
tf32_high_precision_guard -> _loop_impl (inference_mode)
prepare/reuse processor calibration datasets
StageInputsCapture.cache_inputs -> InputCache
release raw datasets; optional base-module disk offload
build LoopPlan -> extensions.start(LoopContext)
run_layer_stage(...)
pre_quantize / materialize / resolve NamedModules
for each processor and calculation subset:
preprocess -> skip filtering -> build SubsetPlan
run_subset_stage(...)
register capture hooks
ForwardExecutor.run -> serial or parallel -> run_single
validate coverage / choose fallback / prune when policy requires
DEVICE_THREAD_POOL -> processor.process(...)
optional post-process forward replay -> receive_layer_inputs
reverse processor submodule_finalize -> optional disk offload
extensions.publish(LoopStep, finalizer futures)
wait device/stream pools and finalizer watcher threads
reverse processor.finalize -> return processor logs
uses_weight_only_lifecycle() == True
_quantize_weight_only(...)
WeightOnlyProcessor -> WeightOnlyLooper.loop(...)
resolve/materialize modules -> quantize_module -> submodule_finalize
publish boundaries -> finalize -> return logs
after_quantize(); rehome_quantized_kernel(); optional W4A runtime stream installation
flush region timer; set up online rotation; report dynamic-cache statistics
return logs
The graph separates the initial model-entry capture forward, subset capture forwards, and post-process replay forwards. Initial capture delegates to the definition's run_input_capture(); the ordinary single-stack path stops at the first decoder layer's pre-hook. Concurrent multi-branch trees instead continue until every branch's first layer has been captured. The base hook calls the model (or generate() when INPUT_EMBEDDING_EXTRA_ARGS is truthy), while multimodal definitions may prepare embeddings and call the first language layer directly. These forwards serve different purposes and can have different device-placement and output-retention policies.
quantize() first normalizes the embedding arguments and requires a non-None BaseQuantizeConfig. It then checks the retired resume environment variable, validates a supplied checkpoint request, rejects ordinary re-quantization of an already-quantized model, resets optional region timing, and checks the quantization-method blacklist.
Backend validation happens before the looper:
| Case | Entry behavior |
|---|---|
quantize(backend=BACKEND.AUTO) after source loading with an explicit backend |
Reuses the retained backend if it supports packing. If the packing selector rejects it or cannot select a packer, GPT-QModel logs a warning and uses the method's default packer. An explicit inference-only backend passed directly to quantize() still fails packing validation. |
FORMAT.MARLIN as a quantization output format |
Rejected; use FORMAT.GPTQ, with inference kernel selection handled separately |
AWQ GEMV_FAST / LLM_AWQ export |
pack_dtype is set to torch.int16
|
| Automatic AWQ GEMM packing | Uses the native AWQ_GEMM packer for calibrated 4-bit NVIDIA CUDA runs and AWQ_TORCH for other supported widths, devices, and weight-only exports. See AWQ packer selection. |
| NPU AWQ with a non-GEMM format in the automatic selection branch | Rejected with an explanation requiring FORMAT.GEMM
|
| QQQ automatic selection | Portable BACKEND.QQQ_TORCH on CPU/NPU; otherwise BACKEND.QQQ
|
| VPTQ / Paro automatic selection |
BACKEND.VPTQ_TORCH / BACKEND.PARO_CUDA
|
| BitsAndBytes automatic selection | BACKEND.BITSANDBYTES |
EXL3 public quantize()
|
Only BACKEND.AUTO or BACKEND.EXL3_EXLLAMA_V3; requires torch.cuda.is_available() and a cuda quantization device, including HIP through PyTorch's CUDA API |
| BitBLAS format | Requires a usable BitBLAS runtime. If the availability probe fails, the error includes compatibility guidance and any recorded probe detail. The installation extra was withdrawn. |
For non-EXL3 methods, select_quant_linear(..., pack=True) validates the proposed combination and selects self.qlinear_kernel. A processor can still have a specialized finalization class, such as QQQ, VPTQ, Paro, or EXL3; packing backend and numerical quantizer are related but not interchangeable concepts.
If rotation is requested, the entry implementation limits model definitions to Llama/Qwen2, unties word embeddings when necessary, fuses norms, and rotates the model. MPS rotation uses CPU because MPS lacks float64 support. The accepted rotation backends are GPTQ_TORCH, GPTQ_TRITON, GPTQ_W4AFP8, and GPTQ_W4A_NVFP4; AUTO resolves to GPTQ_TORCH in this branch. See Rotation, Smoothing and Norm Tuning.
Config normalization disables offload_to_disk when rotation is enabled because the rotation path is incompatible with disk offload. The general offload default below does not override that normalization; rotation is also unsupported by checkpointed quantization.
The wrapper warns about partial dynamic rules for module units that inference engines fuse. It runs quantization under quant_blas_backend(); on ROCm this scopes the quantization-specific BLAS override rather than changing the user's inference policy.
The preparation chain is:
prepare_calibration_dataset_once(calibration)
calibration.prepare_dataset(...)
BaseQModel.prepare_dataset(...) or a model-specific override
prepare_calibration_dataset(...) for text
prepare_vlm_calibration_dataset(...) for definitions opting into shared conversation preparation
The text preparation path accepts token dictionaries, strings, token-ID lists, supported Hugging Face dataset types, and finite generators. It also accepts a single mapping or a columnar mapping, including a batched tokenizer BatchEncoding. It unpacks input_ids, text, and messages columns into examples. Recognized columns must have matching row counts. Select a split such as dataset["train"] before passing a Hugging Face DatasetDict. Definitions that set conversation_calibration = True use a shared helper that routes pre-tokenized rows back to the text path. See multimodal preparation for conversation formats and model-specific restrictions. Prefer explicit dictionaries when supplying already-tokenized data:
from gptqmodel import CalibrationConfig
calibration = [
{"input_ids": token_ids, "attention_mask": [1] * len(token_ids)}
for token_ids in tokenized_examples
]
model.quantize(CalibrationConfig(dataset=calibration))The shared helper also converts DataFrame-like tables to column mappings before iteration, so a pandas frame calibrates on its row contents rather than the literal column label "text". NumPy-formatted Hugging Face slices with ragged one-dimensional object-array token columns and mappings containing pandas Series are split positionally into rows, including Series with a non-default index. Object-array IDs/masks are unwrapped before tensor validation; this does not allow non-integer token IDs. Numeric one-dimensional token vectors still mean one token row. Recognized column lengths must agree. Qwen3-VL's dedicated adapter rejects top-level mappings and DataFrames; pass an iterable of individual samples there. See input normalization.
tokenized_examples must contain representative, valid integer token-ID sequences. Boolean, floating-point, complex, scalar, zero-row, and rank-greater-than-two input_ids are rejected. Zero-token rows (for example, "" encoded by a tokenizer without BOS, [], or [[]]) are dropped as too short rather than aborting an otherwise usable dataset. Empty Python containers normalize to integer storage for this check; explicitly floating-point tensors remain invalid even when empty. The helper validates row lengths and attention-mask compatibility, supplies masks where needed, handles text/message tokenization through the configured tokenizer, and trims rows against the resolved model positional limit. A bare string is rejected as a dataset. Empty datasets are rejected.
Masks normalize to per-token keep flags before counting or filtering. Supported forms include ordinary 1D/2D keep masks and 3D/4D causal grids, including additive grids: the query axis is collapsed with any, retaining a key token that at least one query can attend to. Mask shape must match the IDs after normalization. Chat-template text and concatenation separators are tokenized with add_special_tokens=False to avoid adding a second BOS; ordinary raw-text samples keep the tokenizer's normal special-token behavior.
Dataset preparation and layer replay share the same mask classifier. An entirely zero floating-point mask, or an entirely zero numeric mask of rank three or higher, keeps every token as an unpadded additive mask. An entirely zero 2D integer mask still denotes padding. This keeps PanGu-alpha's unpadded extended mask from discarding every row during calibration replay. See attention-mask classification.
When a row contains non-None input_ids, the supplied IDs and optional attention_mask take precedence over both text and messages. This also applies to columnar mappings such as dataset[:], preserving the caller's truncation, special-token, and chat-template choices from Dataset.map(tokenizer, ...). The source columns are not re-tokenized, and an informational log counts rows where they were ignored. If IDs are absent or None, the existing messages-first, then text processing remains in effect. See the shared calibration helper.
Processing order matters:
- Normalize and tokenize samples; validate token/mask structure.
- Remove all-padding rows. Without concatenation, trim over-budget rows after removing masked padding, using
tokenizer.truncation_side(defaultright), independently of padding side: left keeps the real-token tail, right keeps the prefix. Other pre-padded rows lose contiguous padding at either edge before sorting and batching; rows with interior mask zeros are left intact by this edge-strip step. Re-pad ragged non-batch-quantization items ontokenizer.padding_sidewhen needed. - Without concatenation, remove individual rows with less than or equal to
CalibrationConfig.min_lengthnon-padding tokens (default10); padded width or a longer neighboring row cannot make a short row pass. - With
CalibrationConfig.concat_sizeset, pack source rows into fixed-size windows, stripping source padding and inserting separators before minimum-length filtering. A separator that would fill or overflow the remaining space closes the window without being appended. Do not truncate long source documents to the model position budget or discard short utterances before packing. Drop any window with at mostmin_lengthattended tokens before padding it. If packing leaves no usable windows, make sureconcat_size > min_lengthwithout exceeding the model's resolved positional limit. - Sort ascending/descending by length, shuffle, or preserve order. The accepted sort values are
"asc","desc","shuffle", andNone; other values raise. - Batch/collate according to
batch_sizeand the model's batch-quantization support.
quantize() binds the model's preparer through CalibrationConfig.bind(). The preparation helper forwards CalibrationConfig.min_length (default 10) as calibration_data_min_length. The shared conversation path compares that value with the prepared batch's input_ids width. For direct calls to BaseQModel.prepare_dataset(), calibration_data_min_length=None keeps the text helper's 10-token threshold and leaves shared conversation batches unfiltered by length. Calibration preparation flow
Trimming and dropped-padding counts are logged. Padding alone must not consume the position budget or survive as a zero-statistics calibration sample. See calibration row trimming and multimodal preparation for the separate conversation adapter contract.
Columnar token inputs also accept general nested Sequence values, including Hugging Face datasets.Column, rather than requiring a Python list or tuple. Size warnings count rows in the primary column, not the mapping's number of keys. For a Hugging Face datasets.Dataset, pandas DataFrame, or columnar mapping, the numeric attention_mask convention is resolved across the column. If another row establishes the 0/1 convention, an all-zero floating row stays all-padding after the split rather than being reinterpreted as an additive mask. Use boolean or integer masks to make binary intent explicit when no row contains a 1.
Concatenation strips pad positions before packing windows even when the row did not need length trimming. Every emitted partial window, including an early flush or the final tail, is padded to concat_size on the tokenizer's padding side. Padding uses pad_token_id, then eos_token_id, then 0, with a zero attention mask at those positions. Calibration preparation source.
LoopProcessor computes num_batches and total_calibration_tokens from prepared batches; token counting uses attention masks when available. Batch indices are stored in thread-local state during forward replay so capture order can remain deterministic even with multiple forward workers. Each processor has a cache; processors that return False from verify_calibration_dataset(index) can reuse the preceding processor's cache. Raw prepared datasets are released once initial input capture is complete.
Hugging Face Dataset inputs are read through a Python-row view (with_format(None)) so pandas, Arrow, NumPy, or Torch display formatting does not change accepted calibration content; the caller's dataset format is unchanged. Formatted slices passed directly also work for messages: NumPy object-array or pandas DataFrame rows are normalized to plain Python containers before chat templating. In columnar inputs, tools and documents stay with their conversation. Arrow table slices normalize through to_pydict(). Model-specific VLM paths retain their own preparation contracts.
Before rendering a messages conversation, shared preparation recursively removes None-valued mapping entries such as unused tool_calls keys and tool argument names injected by Arrow's shared schema. Explicit null values in argument mappings are removed too, since they cannot be distinguished from padding. content: None, null list entries, and JSON strings used for tool arguments are preserved. The caller's rows are not changed.
When a messages row carries non-None tools or documents, shared preparation normalizes those payloads before calling the chat formatter. It accepts JSON-encoded objects and lists, removes null-valued mapping entries introduced by Arrow schema unification, and preserves null elements in lists. A single tool definition is wrapped in a list. The normalization leaves the caller's rows intact and apply_chat_template still uses add_generation_prompt=False. Legacy formatters that reject keyword arguments retry with messages only. Other formatter failures with these extras warn once and retry without them. Explicit non-None input_ids still take precedence. See the calibration input parser.
Initial capture derives position_ids from a nonempty 2-D attention mask when the model forward accepts them and the example does not already provide them: real tokens use cumsum(mask)-1, masked positions use 1. This prevents left padding from shifting GPT-2/GPT-Neo learned absolute positions; an unpadded row retains its ordinary positions. Models without a compatible argument are left unchanged.
By default, capture skips that text-position derivation if a module exposes compute_3d_position_ids, get_rope_index, or compute_mrope_position_ids. The model can then compute its own multimodal RoPE positions. Definitions can override that detection with CAPTURE_DERIVE_POSITION_IDS (default None); the override does not replace an explicit position_ids input. See the capture implementation.
DecisionTransformerQModel opts into calibration_inputs="tensor_kwargs" and loads without a tokenizer. Pass a nonempty mapping, or a sequence of mappings, whose values are tensors with their own batch dimension, for example states, actions, rewards, returns_to_go, timesteps, and an optional attention_mask matching the model forward. Preparation detaches tensors without tokenization or shape changes; each row is one batch and batch_size other than 1 is logged and ignored.
Before the calibration forward, floating inputs are cast to the dtype of the model's first floating-point parameter, when available. FP32 states and actions can therefore be supplied for BF16 models. Integer tensors such as timestep IDs retain their dtype.
Token-length sorting, minimum-length filtering, and padding collation do not apply. CalibrationConfig.concat_size is rejected for this path. Empty mappings/datasets, non-tensor values, and scalar tensors raise ValueError. Token-input models do not gain this behavior automatically. Only decoder attention/MLP weights are quantized; the RL heads remain native. See the definition and source guide.
LoopProcessor accepts calibration without len(). The shared helper materializes finite iterables, and an unsized result from a model-specific preparation override is also materialized so it can be replayed for each layer. This is not bounded-memory streaming: bound a streaming dataset or generator before passing it. Empty prepared inputs still raise; size warnings for unsized inputs run after preparation.
quantize(), requantize(norm=...), and standalone model.adapter.generate() materialize finite one-shot iterators before automatic batch sizing or dataset preparation. This lets the estimator and processors read the same rows. For quantization with separate EoRA samples, both CalibrationConfig.dataset and CalibrationConfig.adapter_dataset are handled this way. Re-iterable inputs such as Hugging Face IterableDataset can still be materialized during preparation.
The separate iter_calibration_windows(tokenizer, text, seqlen=256, nsamples=32, ...) helper samples the full tokenized corpus. For multiple windows it spaces starts across 0..total_tokens-seqlen, including both the prefix and tail; one window stays anchored at zero. Short corpora can still overlap or repeat windows, with warnings. This is different from the utils/data.py evaluation loader, which explicitly rejects streaming IterableDataset inputs; see Evaluation.
If the bound preparer filters out every row, prepare_calibration_dataset_once() raises ValueError. If the length filter removed every row, lower CalibrationConfig.min_length or provide longer calibration samples.
At the public entry point, calibration=None becomes CalibrationConfig(). A calibrated run needs usable samples. With MoEQuant EBSS, quantize() generates the dataset from materialized model weights before rotation and ordinary dataset preparation. EBSS rejects a supplied dataset. Empty or fully filtered data fails preparation. Check actual per-module captured coverage, especially for routed experts.
The constructor installs the shared ForwardExecutor, device pools and module-device assignment state, MoE policies, optional subset callbacks, extension dispatcher, and tracking for outstanding finalizer watcher threads. Model definitions supply the layer path and ordered module-tree calculation groups; they are not inferred solely from module-class names.
loop() enters the TF32 high-precision guard and calls _loop_impl() under torch.inference_mode(). The implementation preserves the model's config.use_cache value and disables cache while quantizing. It resolves the decoder layers and their dotted names, prepares embedding/lm-head defaults, and calls StageInputsCapture.cache_inputs(...) for processors needing an initial calibration cache.
For an ordinary single-stack tree, the stage installs a forward pre-hook on the first decoder layer. For each calibration batch, the ordinary model forward reaches that hook, which saves the layer's positional input list, attention mask, position IDs, extra keyword arguments, and model-specific capture data. It raises the intentional stop-forward sentinel so the remainder of the model need not execute merely to obtain the first decoder input.
Mask and position capture binds the decoder's actual forward signature, covering positional arguments as well as keywords. This preserves GPT-2's positional causal mask under eager attention and padding mask under SDPA during later layer replay. The same argument binding applies to multi-branch and looped first-layer capture. See positional replay mask capture.
Concurrent multi-branch trees install a hook on each branch's first layer, retaining branch-owned caches in InputCache.branch_first_layer_inputs. Capture stops once all branch hooks have fired; it must execute enough of the model to reach every branch rather than stopping at the first decoder. Every branch must be reached for every calibration batch; an unreachable branch raises ValueError naming the branch and batch. During replay, _branch_replay_cache() selects the owning branch for every layer, including checkpoint catch-up replay: masks, positions, and extra kwargs always come from that branch. Only its first layer restarts from captured hidden inputs; later layers consume the preceding quantized layer's output. This prevents later vision layers from inheriting a text branch's attention mask or losing their own cu_seqlens. See parallel module trees.
Hybrid Transformers models replay each decoder with its own layer-type kwargs. Capture uses Transformers' registered mask-builder table for full, sliding-window, and chunked attention and retains per-type rotary tuples where needed. Capture can read the original padding mask from mappings such as a multimodal processor's BatchFeature. Layer execution selects the current layer type for both calibration and post-process replay, preserving padding and local-window semantics. See the layer-type capture code.
Recurrent/convolution layers also resolve their own replay type, including block_type and nested mamba mixer metadata. GPTQ keeps a captured None recurrent mask. AWQ packed token-row replay instead supplies a planar [1, retained_tokens] keep mask, never an attention-only additive grid; it does not isolate recurrent state between packed documents. See AWQ replay constraints.
Inherited replay-mask implementations are honored through super() without recursive redispatch; the raw two-dimensional padding mask remains available to build every layer type. AWQ resolves typed rotary state through a nested self_attn as well as layer-level attributes. Tokenizer outputs may be any Mapping, including BatchEncoding, and retain their supplied attention_mask instead of replacing it with all ones.
Multimodal wrappers also preserve state normally applied by the outer model loop: Qwen3-VL/Omni DeepStack visual residuals and Gemma-3's image-block-aware full/sliding mask dictionary. Padded Qwen-VL/Mllama capture builds the appropriate 4-D first-layer mask; all-one masks can still use None. See multimodal replay.
HRM-Text captures every invocation of each recurrent L/H layer in a real full-model forward, rather than pretending the flattened stack runs once. This materializes the whole recurrent model for capture; it is not the ordinary first-layer-only low-memory path. The per-layer cache covers H_cycles * L_cycles L-stack invocations and H_cycles H-stack invocations.
SenseNova-Loop and Inkling 2 Mini use full-forward capture through LoopedLayerCaptureMixin. Capture runs one native full-model forward per prepared batch with the KV cache disabled. Replay uses every captured visit for layers inside the loop and the actual post-loop inputs for later layers. The full model is materialized on the capture device, and each physical layer is quantized once. Inkling 2 Mini also preserves the attention residual bank and any loop messages passed to each invocation. See the looped capture source, SenseNova-Loop model entry, and Inkling 2 Mini calibration notes.
The first layer's checkpoint path is resolved in this order:
- Caller-supplied
layer_names[0]. - A legacy
full_nameattribute. - Discovery by identity in
model.named_modules().
A disagreement between the first two is logged; the caller's dotted path wins. A class name may label progress but is not used as a checkpoint prefix. The resolved path is passed to shell_module_materialize(..., module_path=...), which is essential for lazy source models. If the first layer has a deferred floatx source, capture can leave it lazy because the pre-hook runs before its packed weights are consumed.
Capture normally stages the first layer on CPU and stores cached calibration inputs on CPU. calibration_data_device can instead select a device or "balanced", which distributes cache storage across available forward devices, applying compute_device_filter where applicable. Storage placement is distinct from the device used by a later layer forward or quantization task.
@dataclass
class InputCache:
layer_inputs: List[List[torch.Tensor]]
layer_input_kwargs: List[Dict[str, torch.Tensor]]
position_ids: List[Optional[torch.Tensor]]
attention_masks: List[torch.Tensor]
src_inputs: Optional[List[List[torch.Tensor]]] = NoneWhen src_inputs is None, __post_init__() creates a shallow list copy of layer_inputs, or an empty list if no inputs exist. It does not clone every tensor. module_kwargs() returns position_ids and attention_masks; the latter is the cache's plural field name, not necessarily a layer's forward keyword. The executor translates the relevant per-batch metadata into the actual call.
Capture stores one position_ids slot per batch. When the first decoder layer receives no explicit IDs, capture stores None and replay omits the argument for that batch. This keeps explicit positions attached to their original batches when a calibration set mixes text and vision rows. Replay also treats missing trailing slots in older continuation checkpoints as None. Capture · Replay
Processors access this data through a thread-safe cache wrapper. receive_layer_inputs(...) replaces the inputs that feed the next layer after authoritative output replay.
After capture, the looper releases calibration datasets, optionally offloads base modules, prewarms Paro when present, and builds layer-module lists. With true_sequential=False, calculation groups are flattened rather than preserving sequential subset dependencies. This changes which quantized predecessors later statistics observe; it is not merely a scheduling optimization.
The looper builds an immutable LoopPlan containing the actual steps (input embeddings, transformer layers, and eligible output-embedding/lm-head steps). extensions.start(LoopContext(...)) runs before planned steps and returns the starting execution cursor for continuation.
For each layer, run_layer_stage(...) performs the model-specific preparation/materialization and module conversion, resolves concrete quantizable modules, creates NamedModule wrappers, and iterates processors in chain order. Full dotted names allow dynamic configuration, source loading, result storage, replacement, and device assignment to refer to the same object consistently.
For each processor it:
- Runs
preprocess()to create tasks or annotate state. - Applies
is_skipped()and model/dynamic eligibility. - Resolves subsets and their device/forward plans.
- Calls
run_subset_stage()for each subset or expert chunk. - Replays outputs after processing when
processor.lifecycle.forward.replay_after_processrequires it. - Updates the processor input cache for the next layer.
All consumers that need a dense/reconstructed module run before its base quantizer packs it. Per-module finalization follows the processor chain in reverse, allowing EoRA to preserve its adapter before the quantizer restores the base reconstructed weights and replaces the dense module.
Embedding and lm_head steps have their own eligibility checks. An explicit lm_head=True raises NotImplementedError on a tied output head. When EXL3Config(head_bits=...) requests head quantization implicitly, a tied head triggers a warning before calibration and stays shared. Tying is checked using actual parameters or, for a lazy head on meta, checkpoint tensor availability and resolved tied-weight metadata. A materialized head with independent weights remains eligible even if a nested text config advertises tying. See EXL3 output-head selection and Model Definitions and Module Tree.
SubsetPlan records the resolved module set, subset position, forward mode, replay policy, batching/chunks, row-count expectations, MoE group information, device assignments, and restoration policy for temporary forward-device overrides. It is a regular dataclass, not a Python-enforced immutable object; planning establishes decisions before workers run.
| Plan property | Meaning |
|---|---|
need_forward_outputs |
True when the pass executes forward and does not obtain authoritative outputs from replay-after-process |
subset_forward_serial |
Whether forward_mode == "serial"
|
batching_enabled |
Whether the plan contains more than one module chunk |
calibration_coverage_policy |
Policy controlling validation, fallback, pruning, and dynamic-exclusion recording |
run_subset_stage() has separate branches for chunked MoE work, ordinary forward-plus-process work, and no-forward processing. The inner pass registers module hooks, optionally enables shared-input capture or MoE-root capture, and executes cached batches through ForwardExecutor. Hooks are removed after capture rather than being retained on the exported inference graph.
Subset early-stop waits until every hooked member has captured input in the current calibration batch, regardless of declaration order. Each data-parallel worker tracks its own pending members, and the layer pre-hook resets the tracking and stop flags on the running replica before each batch. One replica cannot complete another replica's subset. Falcon-H1's up_proj can execute before gate_proj, and Ling hybrid attention's b_proj before g_proj, without starving sibling calibration hooks. If a member never fires, capture runs through the forward rather than stopping at the declared-last member; the existing coverage policy then applies. See subset capture.
Coverage is algorithm/policy-dependent. A routed expert may receive few or no tokens. The code can permit the configured fallback, remove uncovered targets, and record dynamic exclusions when the resolved coverage policy calls for those actions; it does not unconditionally quantize every unobserved expert with valid Hessian statistics. has_captured_input_ids() is the processor's coverage probe even when the underlying stored data is activations rather than literal input IDs.
The default Fallback configuration uses FallbackStrategy.RTN and threshold "0.5%". Per-module fallback choices are passed into processors. Fallback is not universal: EXL3 explicitly checks that its Hessian exists and that it captured positive samples, and Paro has its own missing-feature handling.
After capture/coverage resolution, the looper assigns/reconciles module and task devices and submits processor.process(...) to DEVICE_THREAD_POOL. The worker receives the subset mapping, previous processed subset, and subset indices where applicable. Results are collected in a deterministic order even though worker completion may be concurrent. Stage cleanup synchronizes devices or flushes allocator caches according to the selected policy.
ForwardExecutor.run(...) chooses serial execution when forced, when auto_forward_data_parallel=False, or when there is only one usable forward device. Otherwise it uses the parallel implementation to distribute cached batches across forward-device replicas.
For one cached batch, run_single(...):
- Sets the processor's thread-local batch index.
- Moves positional inputs, masks, position IDs, and nested kwargs to the execution device.
- Supplies
use_cache=Falseand letsprepare_layer_replay_kwargsadapt the call to the model definition. - Executes the layer/module and handles shared KV/reuse state required by the model.
- Extracts the primary output when output collection is requested.
- Clears active attention-mask and batch-index state on exit.
Serial and data-parallel replay both determine once per batch which samples have usable calibration tokens and whether the batch contains attention padding. Routed-expert hooks check the padding-only mask, so excluding attention sinks alone keeps valid routed rows, including all-zero activations. The worker clears the masks and derived flags when the batch ends. See calibration mask binding.
Not every subset forward needs to retain outputs. A statistics-capture pass may early-stop once its last necessary hook fires; authoritative next-layer outputs can instead come from the full replay after process(). Processors needing pristine layer IO, notably grouped Paro optimization, request that context explicitly.
For cross-layer KV reuse (for example Hymba), shared_kv_cache_dict is keyed by (layer_index, batch_idx). Each consuming batch reads only its own predecessor-layer K/V, in both serial and data-parallel execution. Post-quantization replay overwrites the FP capture's entry so the K/V agrees with the quantized hidden states passed onward. After a layer finishes, all predecessor-layer batch slots are evicted, bounding the cache to adjacent layers rather than growing with model depth. A missing predecessor entry is not replaced with another batch's data; the model's own validation can fail the run. This is calibration scratch, not an inference KV cache or checkpoint payload. See shared KV cache.
Early-stopped batches retain empty positional output slots instead of shifting later batches onto the wrong masks, positions, or replay kwargs; the empty slot is not forwarded as a real batch. Quantization worker entry points establish inference mode on the worker thread itself and drain submitted futures before propagating a failure.
After authoritative replay, obsolete activation references and prior-layer shared KV entries are released instead of surviving through later layers. MoE Hessian capture preserves the original batch keep-mask and drops padded token rows before expert statistics, including routing-bypass padding; this is separate from which experts are selected. AWQ shares unmasked sibling captures safely under inference mode and defaults every module to bounded token-row aggregation, so variable sequence lengths do not require a MoE-specific override. Memory lifetime · padding and capture sharing.
Forward data parallelism and quantization-module distribution are different mechanisms. Replicating a layer for forwarding can increase VRAM and startup cost; more visible GPUs do not guarantee a faster run.
| Configuration field | Default at this revision | Role |
|---|---|---|
device |
Method/config-dependent | Quantization execution device; backend validation uses the resolved value |
compute_device_filter |
None |
Filters candidate compute devices; an empty result is not treated as a request to disable all computation |
calibration_data_device |
None |
Initial calibration-cache storage; supports "balanced"
|
auto_forward_data_parallel |
True |
Permits cached-batch data parallel forwarding |
dense_vram_strategy |
VramStrategy.EXCLUSIVE |
Dense/serial-path module placement |
dense_vram_strategy_devices |
None |
Optional dense device pool |
moe_vram_strategy |
VramStrategy.EXCLUSIVE |
Expert-family placement |
moe_vram_strategy_devices |
None |
Optional expert device pool |
For balanced MoE quantization, use logical indices relative to CUDA_VISIBLE_DEVICES. The dense and MoE pools are separate, and expert families remain together. Actual free-threaded parallel MoE eligibility also depends on the Python runtime: PYTHON_GIL=0 requires a free-threaded build and a genuinely disabled GIL. It cannot convert a regular build into one. Paro is restricted to single-device quantization by the looper at this revision.
DeviceAssignmentState in execution_state.py is shared by the calibration and weight-only orchestrators. It serializes a version-1 mapping containing next_device and module_devices. Restore rejects a negative/non-integer cursor, invalid names, and devices outside the current quantization pool plus CPU. This state preserves future scheduling as well as already assigned modules.
For pool examples see Memory Offload and Multi-GPU.
ModulePreProcessor is a no-forward LoopProcessor inserted when quantize_config.preprocessors is nonempty. Its preprocess() records an ordered preprocessor_pipeline and specialized state:
| Preprocessor | Recorded state | Consumer |
|---|---|---|
AutoModuleDecoderConfig |
auto_module_decoder, decode/passthrough policies, optional native floatx runtime plan |
Model materialization/source hand-off |
TensorParallelPadderConfig |
tp_pad_info with pad_cols, target_multiple, and original_columns
|
Quantizers and adapter/dequantization handling |
SmootherConfig |
Serialized entry in the ordered pipeline | Quantization/source preprocessing machinery |
The TP target multiple is the least common multiple of (2, 4, 8) and a positive group_size when present. The planner annotates; its process() is a no-op. Source decoding is deferred until quantization hand-off rather than being repeated during post-quantization W4 replay. Processor-specific source lookup can use quant_source_module rather than treating every live forward wrapper as an ordinary dense source.
BaseQuantizeConfig.auto_dtype_cast defaults to AutoDtypeCast.AUTO_NF12 ("auto_nf12"); set it to AutoDtypeCast.OFF or "off" to retain dense sources. This policy is separate from the ordered preprocessor pipeline and the requested output quantization method/format.
For an eligible aligned BF16 source (or FP16 matrix with an exact BF16 round trip) on NVIDIA SM80+ or supported RDNA4 HIP, forward-role shell_module_materialize() installs a packed source replacement. ModuleLooper restores the exact source dtype/bits on the quantization device immediately before processing and rebinds the task to that source. Linears use canonical NF12; selected embeddings use its row-major lookup layout. Unsupported cases stay dense; selected native floatx forwards take precedence, and NF12-method runs bypass this policy.
Packed source buffers are released after restoration unless GPTQ + EoRA still needs them for the FP32 w - wq difference. That path uses fused widening decode/subtract when available and releases the packed source after the difference (including fallback/cleanup paths). EoRA's later forward captures statistics from the quantized module rather than replacing it with a freshly packed source. HookedLinear replacements preserve calibration hooks and W4A/rotation replay semantics. See NF12 source storage for exact eligibility, diagnostics, arithmetic caveats, and source links.
linear_mode.py defines:
class LinearMode(str, Enum):
INFERENCE = "inference"
TRAIN = "train"This is a runtime mode for fused Torch linear implementations, not a selector between ModuleLooper and WeightOnlyLooper. In torch_fused.py and torch_fused_awq.py, an initially unset mode becomes INFERENCE only when the module is not training, the input does not require gradients, and TORCH_HAS_FUSED_OPS is true. Otherwise it becomes TRAIN, using the corresponding dequantize-and-matmul path. The branch checks the input's requires_grad, not the global torch.is_grad_enabled() flag, and is selected only while linear_mode is None. Do not infer lifecycle scheduling or checkpoint support from this enum.
When TorchFusedAwqLinear switches from training to evaluation via eval(), it clears LinearMode.TRAIN so the next eligible forward can use fused INT4 again. Switching a fused layer to training restores the checkpoint layout for the dequantized training path. AWQ mode handling
Failure cleanup also covers errors before a looper starts: processor-chain construction, calibration validation, checkpoint-context entry, or looper construction. Calibrated quantization, weight-only quantization, and standalone EoRA release already-built processors independently without replacing the original error. Device-SMI handles open lazily on the first metric query, so an unused processor starts no sampler threads. This releases per-run resources; it does not roll back partially quantized weights or make a failed attempt resumable without a supported checkpoint.
When calibration quantization is cancelled or fails mid-layer, ModuleLooper attempts to return the active decoder layer or embedding/head endpoint to its pre-stage device (CPU for a lazy meta shell), including parameters and buffers. Both loopers also try to switch completed packed layers to layout-compatible kernels for the device left by cleanup. These steps are best-effort and preserve the original exception; they do not undo partial quantization or make a failed run saveable. See placement cleanup and offload lifetime and the continuation-checkpoint restrictions below.
Both loopers wait for submitted work before attempting repair on cancellation or failure, including errors in final restoration, and release run-wide scratch on exit. The calibration looper also clears any remaining subset capture hooks on the in-flight layer. Both loopers attempt to repair parameter and buffer version counters so a later grad-enabled forward can use tensors materialized during quantization. Secondary repair failures are logged without replacing the original exception. Cancelled-run cleanup
If EXL3 has already packed a projection but its live weight is still on meta, interrupted-run recovery attempts to install the staged packed module without retaining a dense copy. This also covers offload_to_disk=False. For lazy source parameters, checkpoint materialization fills a replacement before attaching it to the module, so an interruption during the copy leaves a meta placeholder that recovery can retry rather than exposing uninitialized weights.
process() completing does not imply that packing or disk writes are complete. stage_layer.py queues per-module finalizers; these call submodule_finalize(), install packed replacements, and perform method-eligible offload. Finalizer exceptions request loop termination and must be surfaced before claiming a safe checkpoint.
Finalizers that build a packed replacement install it only after packing succeeds. If packing is interrupted, the original projection is still in the model tree. Failure cleanup unwraps remaining float capture wrappers so an ordinary forward can run through layers that contain both successfully packed and float projections.
| Field | Source default | Effect |
|---|---|---|
offload_to_disk |
True |
Enables quantization-time offload of base/completed modules |
offload_to_disk_path |
None |
Auto-created temporary directory when disk offload is enabled and no path is supplied |
gc_mode |
GcMode.INTERVAL |
Normal periodic thread-pool GC policy |
wait_for_submodule_finalizers |
False |
True explicitly waits for per-layer finalization before the next layer; False permits overlap unless a forced-synchronous condition applies |
The enum is:
class GcMode(str, Enum):
INTERVAL = "interval"
ON_STAGE_END = "on_stage_end"ON_STAGE_END enters DEVICE_THREAD_POOL.no_auto_gc() at the model entry wrapper and requests explicit cache cleanup at stage boundaries. It is not a tensor offload mode and does not make live tensors disappear. Disk offload lowers live tensor residency but the accelerator allocator may still retain freed pools until cache cleanup.
Even with wait_for_submodule_finalizers=False, the layer stage drains finalizers synchronously when W4A activation modes are active, when more than one non-CPU quantization accelerator is active, or when Paro participates. Otherwise it may use a SubmoduleFinalizeWatcher thread so packing/offload overlaps the next layer. The looper tracks these threads and waits for them before overall completion. Certain synchronous finalization cases also release the accelerator cache to limit allocator growth.
At a successful layer boundary, after any packing and offload finalizers complete, the layer stage asks glibc to return unused host heap pages to the OS. This can reduce retained host memory from AWQ calibration features and CPU packing. It also runs for layers with no finalizer tasks. Platforms without glibc's malloc_trim skip the trim. Layer cleanup · Host heap helper
For the GPTQ/QQQ/AWQ/Paro paths, finalized modules are eligible for forced disk offload as file-backed CPU tensors. Keep their backing files while using the live model. This stage's processor-type guard does not include EXL3 or VPTQ; do not assume identical per-module offload behavior for every algorithm. A missing path in the guarded offload branch produces a warning and skips that write rather than inventing a destination. Ordinary config initialization normally supplies a path automatically.
The generated directory uses a gptqmodel_ prefix and is owned by the config's shared temporary-directory object. A failed optional Humming import no longer retains the quantization run through its traceback, so it can release temporary offload files when the model and config are released. See the Humming import handler. Set an explicit path when you need operational control over storage lifetime. Do not remove offload files while live model hooks, finalizers, checkpoint attempts, or saving still depend on them.
On successful calibration-loop completion, the looper waits for DEVICE_THREAD_POOL, dangling watcher threads, and the stream-device pool; collects processor logs; finalizes processors in reverse; and restores config.use_cache. The public entry then runs after_quantize(), calls rehome_quantized_kernel(), installs the applicable W4A runtime stream, flushes timers, and sets up online rotation. model.save() remains a separate operation.
For AWQ, QQQ, and GGUF methods, finalization checks that packed layers can execute on their final device, commonly CPU. If their packing kernel is accelerator-only, AUTO selects a compatible kernel for the same method/format/device and reuses the packed buffers and hooks. Existing device-compatible modules remain unchanged. If a layout has no suitable implementation, or a dynamic module cannot be switched safely, finalization raises with guidance to reload the saved checkpoint on the intended device or use a portable Torch backend. Weight-only runs also materialize still-meta base modules such as embeddings and norms from the source checkpoint before returning. These steps enable in-session inference after quantization without replacing quantized payloads with dense source weights; offload bundles must remain available. See offload lifetime.
GPTQ quantized with BACKEND.TRITON can also run inference immediately after quantization when its packed layers finish on CPU. Finalization switches those layers to TorchLinear via BACKEND.GPTQ_TORCH and reuses the GPTQ packed buffers. W4A activation modes (w4afp8 and w4a_nvfp4) retain their CUDA-specific kernels. See the in-session model contract.
For requantize(embed_quant_config=...), kernel selection uses the recorded placement of the loaded model before replay. For example, an AWQ checkpoint loaded with Marlin on CUDA keeps that kernel when the original CUDA placement is restored. If a kernel cannot run on the recorded device, only modules still in checkpoint layout can switch to a compatible reader. A kernel-private layout that cannot run there raises before replay with guidance to reload on a supported device. Requantize placement
keep_processor_logs=True preserves per-processor files under logs/ by default. Construct the quantization config with keep_processor_logs=False to remove those files during successful base processor finalization; failed runs retain partial logs for diagnosis. The in-memory diagnostic rows returned by quantize() are separate from this file-retention setting.
Extensions are an internal orchestration interface. Both loopers accept extensions=() in their constructors; public quantize() has no general-purpose extensions argument. The checkpoint wrapper is one caller that supplies an extension.
ModuleLooper raises TypeError if the model sets quantization_layer_boundary_checkpoint to a non-None value. Custom looper integrations should pass a LoopExtension through extensions. Restore state in on_start(context) and return a LoopPlan cursor. In on_boundary(boundary), call boundary.quiesce() before committing the step. See the migration mapping.
| API | Contract |
|---|---|
LoopStep(kind, index, name) |
Frozen execution identity; its index need not be a decoder-layer index |
LoopPlan(steps) |
Requires an exact tuple of unique steps; after(step) returns the following cursor |
LoopContext(plan, model, processors, shared_state, execution=None) |
Frozen context passed to start callbacks; execution implements pool identity and scheduler continuation |
Optional extension.on_start(context)
|
Install continuation before planned execution; return None or an integer cursor from 0 through the plan length |
extension.on_boundary(boundary) |
Observe a completed step before the next step mutates execution state |
boundary.quiesce() |
Wait for every preceding future, then return their results or propagate a worker failure |
LoopExtensions.start(context) |
Validates returned cursors and rejects conflicting non-None cursors from different extensions |
LoopExtensions.publish(step, futures=()) |
Dispatches callbacks synchronously and retains unfinished, failed, or cancelled futures for later quiescence |
Boundaries are borrowed only during the callback and belong to the orchestration thread. Calling quiesce() later or from a worker raises RuntimeError. It waits for all futures before raising a failed future's exception so recovery cannot run while other finalizers are still mutating the model. Extensions must quiesce before treating a layer's outputs or packed/offloaded state as durable. extension.py itself knows nothing about tensors, storage formats, or checkpoint policy.
Checkpointing captures quantization execution, not an arbitrary Python process or an exported inference model. validate_checkpoint_support() requires:
| Requirement | Current restriction |
|---|---|
| Model type |
llama, qwen2, or qwen3_moe, as listed in CHECKPOINT_MODEL_TYPES
|
| Layer order | true_sequential=True |
| Disk backing | offload_to_disk=True |
| Source | Local model.safetensors or model.safetensors.index.json plus referenced shards and config.json
|
| Disallowed config features | GPTAQ, FOEM, rotation, lm_head quantization, and embedding quantization. Ordered dynamic overrides/exclusions are supported when the configuration is identical on resume. |
| Adapter | No adapter or an exact Lora instance; EXL3 additionally rejects adapter/EoRA generation |
| Thread | Quantization must run on the main thread for scoped signal handling |
| Placement serialization | CPU and CUDA device tags; ROCm uses PyTorch's cuda namespace; no general MPS/XPU/NPU continuation adapter |
Qwen2 continuation covers sources with tied or untied word embeddings. The remaining restrictions above still apply; support for qwen2 does not admit other Qwen model types automatically. An unsupported model type raises an error naming the supported set and the requested type.
Dynamic per-module settings are resolved once when the module is scheduled; the winning rule, packing fields, kernel, and method-specific options are recorded with the completed packed module. This includes BitsAndBytes block/compression settings. Resume restores those per-module values instead of applying global defaults again; runtime coverage exclusions remain dense and are restored as exclusions. Keep the original rule order and calibration inputs unchanged across attempts. See the resolved module / checkpoint contracts.
QuantizationCheckpointAdapter.bind() checks the processors' declared lifecycle roles through checkpoint_chain_supported(). It accepts one PRIMARY processor, optionally followed by one SECONDARY processor. Current declarations include:
| Chain | Notes |
|---|---|
(GPTQProcessor,) or (GPTQProcessor, EoraProcessor)
|
Standard GPTQ, not GPTAQ/FOEM |
(AWQProcessor,) or (AWQProcessor, EoraProcessor)
|
Preserves scaling mutations as well as packed modules |
(QQQProcessor,) or (QQQProcessor, EoraProcessor)
|
Preserves QQQ packed schema |
(ParoProcessor,) or (ParoProcessor, EoraProcessor)
|
Preserves Paro rotation/runtime options |
(MacaqProcessor,) or (MacaqProcessor, EoraProcessor)
|
Preserves MACaQ packed transform state |
(WeightOnlyProcessor,) |
Shares the boundary/state-adapter protocol |
(EXL3Processor,) |
Added when the configured method is EXL3 |
VPTQ, NativeProcessor, DequantizeProcessor, and ModulePreProcessor do not declare a supported checkpoint role. Chains containing them fail admission. A config being valid for ordinary quantization is not evidence that it supports checkpointing; the model/config restrictions and supported packed-module constructors still apply. See the role predicate and adapter admission.
@dataclass(frozen=True)
class CheckpointConfig:
path: str | Path = "auto"
resume: str = "auto"
interval: str = "layer:1"
module_results: bool = False
keep_last: int = 2
strict_device_check: bool = TrueThe class also keeps an internal, non-init _resolved_path field so an automatic root resolves once across retries.
| Field | Accepted values / behavior |
|---|---|
path |
Nonempty string/path; "auto" resolves to the config's offload root. An explicit path is preferable for restarting with newly loaded config/model objects |
resume |
"auto": restore if a generation exists; "required": fail if none exists; "never": require a directory without published checkpoints |
interval |
"layer:<positive integer>" or "subset:<positive integer>". Default "layer:1" publishes at each completed layer. "subset:<n>" counts both module-group and layer steps toward its publication interval. |
keep_last |
Integer at least 2; retains fallback generations |
strict_device_check |
Boolean, default True; False removes only physical UUID/serial from identity comparison, not topology/capability/pool requirements |
module_results |
Boolean, default False. Requires interval="subset:1". Plain GPTQ saves eligible module results as processing finishes. |
Subset checkpointing requires a single processor that supports subset boundaries, such as plain GPTQ or weight-only RTN. With interval="subset:1", a restart restores completed module groups in the interrupted layer and resumes at the first unfinished group. Each subset commit writes the full continuation, so finer recovery increases disk writes.
With module_results=True, plain GPTQ replays the unfinished group's forward to recapture its Hessians. It reuses a saved result when the run identity, module name, input weight and Hessian match, then solves the remaining modules. Weight-only RTN resumes from the last committed subset boundary. Subset steps · Result matching
from gptqmodel import CalibrationConfig, CheckpointConfig, CheckpointStopped, GPTQModel, QuantizeConfig
# Use a supported llama, qwen2, or qwen3_moe source without the excluded features.
config = QuantizeConfig(
bits=4,
group_size=128,
device="cuda:0",
true_sequential=True,
offload_to_disk=True,
offload_to_disk_path="./quant-work/offload",
)
model = GPTQModel.load("LOCAL_SOURCE_MODEL", config, dtype="bfloat16")
checkpoint = CheckpointConfig(
path="./quant-work/checkpoints",
resume="auto",
interval="layer:1",
keep_last=2,
)
try:
model.quantize(CalibrationConfig(dataset=calibration_dataset), checkpoint=checkpoint)
except CheckpointStopped:
# A cooperative SIGINT/SIGTERM stop committed a safe boundary.
pass
else:
model.save("./quantized-model")Resume by loading the same local source model and supplying the same calibration/configuration and checkpoint root. The code still constructs the execution plan and initial capture needed to validate identity before installing continuation. A checkpoint is not permission to substitute a different calibration corpus or skip source availability.
When resume replaces the initial replay cache with the saved frontier, it releases the discarded capture rather than keeping both frontiers resident.
For disk-backed replay inputs, the scheduler reads batch presence and CPU placement from manifest metadata. It opens and verifies the shard when the scheduled batch is read for replay, not again just to decide where it will run. See the replay scheduler and input cache.
| File | Responsibility |
|---|---|
extension.py |
Immutable execution steps, start context, borrowed boundaries, finalizer quiescence |
checkpoint.py |
CheckpointExtension: interval policy, restore cursor, cooperative stop, capture/commit orchestration |
gptq_checkpoint.py |
Model/processor support validation, session lease/signal wrapper, identity and quantization-state adapter |
checkpoint_store.py |
CheckpointConfig, writer lock, immutable objects, manifests, atomic CURRENT, validation/retention/collection |
checkpoint_devices.py |
Visible-device identity and optional UUID/serial projection |
checkpoint_modules.py |
Explicit packed-module schemas and constructors; no dynamic import driven by checkpoint data |
continuation.py |
Safe tensor/value encoding and device-aware decoding |
execution_state.py |
Shared scheduler continuation |
checkpoint_session() takes an exclusive writer lease for the root, creates an attempt-* directory for that run's new offload files, and leaves QuantizeConfig.offload_to_disk_path unchanged. Subsequent models sharing the config still resolve CheckpointConfig(path="auto") from the configured root, not a previous run's attempt directory. It temporarily replaces SIGINT/SIGTERM handlers with a stop request and restores previous handlers on exit. The lower-level extension itself does not install global signal handlers. The lease encloses setup, execution, and worker cleanup so a failed attempt cannot race another writer.
At a due boundary, including the final planned step or a requested stop:
-
LoopBoundary.quiesce()waits for all preceding finalizer futures and propagates failures. - The adapter captures processor caches/logs/results/statistics, shared state, packed module specs/artifacts, materialized dense parameters/buffers and aliases, device scheduler state, and Torch/CUDA/Python/NumPy RNG states.
-
ContinuationCodec.dump_file()writes the tensor data and JSON value tree into a private staged safetensors file. - The store streams the file into a content-addressed SHA-256 object and writes a manifest referencing all required artifacts, including earlier completed layers.
- An fsynced atomic replacement of
CURRENTpublishes the new generation. - The adapter updates committed artifact locations; unreachable objects are collected after publication.
- If stopping was requested,
CheckpointStoppedis raised only after the safe generation is committed.
During a writer lease, the store reuses SHA-256 verification for packed objects whose file metadata is unchanged. This avoids rereading all earlier modules at each checkpoint boundary. A fresh resume verifies the objects it reads again, and changes to a cached object trigger re-verification. See the checkpoint store.
An interrupted write is not recovered by scanning for the newest-looking file. Only generations named in CURRENT are candidates. The store tries the newest complete published generation and can fall back to retained complete generations when a newer one is corrupt. Identity mismatch fails closed; it is not treated as ordinary corruption to be silently bypassed. A post-publication cleanup failure logs a warning rather than turning a durable commit into a failed transaction.
Packed-module checkpoint bundles record the actual bias_dtype when a bias tensor exists. Restore recreates FP16/BF16/FP32 bias storage before schema comparison instead of assuming the kernel's FP16 placeholder. Older bundles without that field retain the constructor default; invalid recorded bias dtypes raise CheckpointError.
Current resumable checkpoints record a versioned descriptor of the packed tensor names, shapes and dtypes for each module. Resume checks the descriptor against the kernel's supported layouts and the safetensors bundle header before installing the module or its offload index. A mismatch raises CheckpointError. Version 7 continuations use this descriptor, and version 6 remains readable through the legacy layout checks. Packed tensor validation · Continuation adapter
Packed-module continuation metadata also records scales_dtype when the stored scales tensor uses a dtype other than FP16. This lets AWQ GEMM resume a checkpoint containing BF16 scales by allocating the matching buffer before the tensor schema check. FP16 scales omit the field and use the constructor's default on restore. See the packed-module restore source.
The adapter hashes actual source configuration/shards and initial processor caches, not merely model IDs or calibration filenames. Its identity includes algorithm configuration (including runtime/method-specific fields), processor chain, packed kernel, runtime Torch/Transformers versions, execution plan, and device topology. Offload-path/temporary-directory/telemetry fields are excluded from quantization identity so attempt-private storage can change without changing the numerical configuration.
Source hashing reads the actual configuration and shard contents from a local Hugging Face Hub cache snapshot, including files linked to the repository's blobs directory. For Xet-backed files it also accepts the standard two-hop chain from the snapshot through the repository's blob entry to the cache-wide blobs store. Both layouts support creating and resuming quantization checkpoints directly from the snapshot. Paths must be valid relative checkpoint paths. Unsupported links, including a direct snapshot link to the cache-wide store, raise CheckpointError. See source identity and path checks.
Strict topology compares visible GPU ordering, UUIDs, serials when available, names, capabilities, selected pools, and device counts. If any execution pool uses CUDA, topology capture inspects every visible CUDA device, not only devices selected for work, and requires each device's PyTorch properties to expose a UUID. This also matters on ROCm, which uses the CUDA API: successful ordinary quantization does not guarantee that the runtime exposes checkpoint-compatible UUIDs. strict_device_check=False removes physical UUID/serial fields from identity comparison only after topology capture; it does not bypass UUID availability, implement device remapping, or promise bit-exact results on different hardware.
The quantization adapter writes continuation version 7 and keeps adapter_version at 6 in the manifest identity so version 6 checkpoints can still resume. The continuation codec uses version 2. The store and scheduler continuation each use version 1. Quantization checkpoint adapter
Supported values are finite scalar values, dense materialized strided CPU/CUDA tensors, supported torch.device metadata, exact InputCache instances, dictionaries with string/integer/boolean keys, lists, and tuples. The codec rejects cyclic structures, unsupported objects/devices/layouts, and nonfinite scalar values. It does not pickle Python objects or deserialize executable code.
The codec stages device tensors on CPU and records their original device tags. It can write CPU tensors directly and copies overlapping storage views as needed for safetensors. Repeated references to the same tensor object share one payload entry and restore to the same object.
Manifest verification streams the continuation's SHA-256 check. Resume opens the verified file directly with safetensors, materializes each payload tensor once, and checks restored shape, dtype, bytes, and device. The adapter also validates packed-module and dense state, including aliases, and restores scheduler and RNG state. A checkpoint directory is coupled to the execution identity. Continuation codec · Checkpoint store
Packed reconstruction also has explicit method-specific metadata in checkpoint_modules.py:
| Packed module case | Additional schema information |
|---|---|
General BaseQuantLinear
|
Input/output dimensions, serialized bits, group size, activation ordering, symmetry, bias presence |
| EXL3 |
kind="exl3", output dtype, and each saved buffer's shape/dtype |
| Paro |
kind="paro" and rotation/runtime-dtype options |
| QQQ accelerator kernel |
kind="qqq" and whether group scales exist |
| BitsAndBytes | Compute dtype; 4-bit quantization-state buffer shape, which depends on serialized values rather than dimensions alone |
| GPTQ/AWQ BitBLAS | Compute dtype from the kernel's quantization config |
| NF12 | Data-dependent escape_rows, restoring the saved (escape_rows, 8) escape-table shape before schema validation |
| MACaQ | Actual compute_dtype used for BH and pre_scale, which can differ from the source config dtype |
NF12 escape tables with nonzero rows and MACaQ runs whose transform dtype differs from the source config can therefore resume without a packed-schema mismatch. These are continuation-bundle metadata fields, not new quantization options; the model, processor-chain, and execution-identity restrictions above still apply.
The constructors are explicit code, not import paths supplied by checkpoint data. The storage layer uses filelock; continuation/artifact serialization uses safetensors. Filesystem fsync and atomic replacement are part of publication: the store does not silently promise host-crash durability on a filesystem that cannot satisfy those operations.
RTNConfig, SINQConfig, GGUFConfig, BitsAndBytesConfig, NF12Config, and CPTCConfig select the weight-only lifecycle for ordinary conversion. FP8 is load-only; quantize() rejects FP8Config before calibration. This lifecycle rejects LoRA/EoRA, GPTAQ, and FOEM, and uses one WeightOnlyProcessor plus a WeightOnlyLooper. It ignores a supplied calibration dataset except when CPTC enables YAQA.
WeightOnlyLooper.loop():
- Validates the concrete supported config type and optional embedding targets.
- Disables
use_cache, resolves layers, and materializes direct meta-backed source tensors as needed. - Optionally offloads base modules and builds sequential/flattened module groups.
- Creates an optional local
ModulePreProcessorfor configured source/padding plans. - Starts boundary extensions with a layer/lm-head
LoopPlan. - Applies per-layer preparation/conversion; resolves named modules and dynamic exclusions before scheduling.
- Calls
quantize_module()with a per-module config clone and assigned device, thensubmodule_finalize()and optional offload. - Publishes completed layer boundaries, restores cache behavior in
finally, marks the model quantized, and returns logs.
RTN computes reconstructed weights plus q_scales, q_zeros, and q_g_idx, then uses the selected packer. SINQ fits the affine grid after weight-tile normalization and adds an input-column scale to the packed state. GGUF, BitsAndBytes, NF12, and CPTC call pack_original(...) on the dense source. Their log records measured pack time in seconds and loss=n/a by default. Requesting measure_weight_error=True reconstructs each dense weight after packing to log MAE.
GGUF and BitsAndBytes encode on CPU. NF12 can stage an eligible CPU tensor inside its native accelerator encoder. For all three, quantization keeps CPU-resident dense weights on the host and materializes lazy source layers on CPU, avoiding an extra accelerator copy of the dense layer. The assigned device still guides backend selection and the packed-weight handoff. RTN stages weights on its assigned quantization device. Source staging · Weight-only looper
CPTC encodes batches of weight blocks on the assigned quantization device and keeps the packed result on CPU during finalization. With YAQA enabled, the weight-only entry point prepares the required dataset and collects both curvature sketches on the dense model before creating the processor. The same looper then uses those sketches during direct packing.
The weight-only embedding fast path currently supports RTN only; boundary extensions with embedding targets are rejected. On a fresh model, quantize() raises NotImplementedError before calibration for QuantizeEmbed.INPUT, QuantizeEmbed.BOTH, or QuantizeEmbed.OUTPUT with tied input/output weights. An untied output head remains eligible, subject to the method and supported head type. embed_only disables disk offload and marks the result for replacement-only saving. Dynamically excluded trailing layers can be skipped without materializing unnecessary quantization work.
Load a quantized checkpoint and use requantize(embed_quant_mode=...) for input or both endpoints. Replacements return to their original devices and the rest of the model returns to its recorded placement. Quantized input embeddings emit the model's compute dtype, such as BF16, independently of the stored scale dtype. Reloaded embeddings also use the model dtype. When saving a GPTQ-native checkpoint with a packed output head, the writer records lm_head=True even if the loaded quantization config did not set it. A fresh calibrated OUTPUT run with embed_only=True also records dynamic exclusions for each decoder tree so the export reloads with a dense decoder. Endpoint support matrix · Fresh quantization metadata · Checkpoint writer
For dispatched models, calibration capture respects resident GPT-QModel hooks' execution devices. Placement restoration uses the device of the packed tensor payload and skips the qzeros_format layout marker, which can remain on CPU even when the weights are on an accelerator. A packed replacement for a CPU-offloaded output head stays in the existing offload chain. Capture placement · Endpoint restoration · CPU-offload placement
With G2PTQ, token-ID embedding tables use plain GPTQ during endpoint requantization. An eligible linear output head keeps G2PTQ replay and uses KL by default.
When output-head requantization needs a pre-head norm already parked on disk, it restores that norm from its offload bundle onto the staging device before calibration. This also works when requantizing a loaded checkpoint without a lazy source model. Pre-quantization materialization
NativeProcessor is prepended for GPTAQ or positive-alpha FOEM. For each layer, it merges the module subsets into one capture plan and forwards the cached calibration batches through that plan, rather than repeating collection for each subset. This is not one forward for the entire dataset or model. It places the captured unquantized module inputs in shared module state as native_inp, tagging per-sample entries with their calibration batch index. GPTAQ/FOEM pair native and replay inputs by that index even if parallel batches finish out of order; missing keyed inputs raise rather than pairing with an unrelated batch. Its staging device comes from the GPTAQ/FOEM config ("auto" uses DEVICE_1; "cpu" uses CPU). Later processing consumes these pristine inputs before finalization releases them. It does not emit a packed linear.
quantize() prepares the main calibration batches once for the processor chain, so CalibrationConfig(sort="shuffle") gives native capture and quantization the same shuffled order. EoRA reuses that order unless an adapter_dataset supplies separate batches.
GPTAQ and FOEM accumulate Hessian and native-delta statistics separately on each contributing device, then reduce weighted partials in stable device order before quantization. GPTAQ weights by its batch-request count; FOEM weights by token count. This corrects multi-device calibration without adding a config option.
DequantizeProcessor is not selected by ordinary quantize() method dispatch. BaseQModel._eora_generate() composes it before EoraProcessor, using a mapping of existing quantized modules. It removes each mapped module, optimizes it, dequantizes/transposes its weight to the working device, handles TP padding, and stages wq plus the float32 difference w_wq_diff. It does not by itself export a newly dense model. Its finalizer drops temporary original/reconstructed weight state after consumers finish. See EoRA and Looper Processors.
| Failure or observation | Where / cause | Action |
|---|---|---|
| Missing/invalid quantize config | Public entry requires BaseQuantizeConfig
|
Load with a supported quantization config |
| Already quantized model | Ordinary quantize() rejects it unless an embedding request applies |
Use the explicit supported conversion/requantization workflow; do not call the ordinary path blindly |
| Missing calibration | Calibration lifecycle chosen with calibration=None
|
Supply data or intentionally select a weight-only config |
| Empty/invalid calibration | Processor/helper length, shape, mask, tokenizer, or type validation | Check prepared data and ensure length filtering leaves usable examples |
| Short calibration samples disappear or the minimum seems ineffective | Ordinary preparation removes each row with non-padding token count <= the forwarded minimum; model adapters can differ | Inspect prepared token lengths, masks, and model-specific preparation; see minimum-length forwarding |
| Stop-forward exception during capture | The internal sentinel intentionally aborts the unused model tail | Do not catch/suppress arbitrary forward errors as if they were this sentinel |
| Missing/weak expert coverage | Routing sent few/no calibration tokens to an expert | Inspect coverage, routing policy, fallback, and dynamic exclusions; improve representative calibration |
| EXL3 missing Hessian/no samples | Processor validates capture before solving | Fix capture/coverage; ordinary fallback is not a blanket substitute |
| Device/Hessian assertion | Scheduled weight/task/current-device context differs | Investigate pool selection and custom model hooks; do not move tensors behind the looper's assignment state |
| OOM despite disk offload | Current Hessians, inputs, replicas, optimization state, and unfinished finalizers remain live | Reduce batches/replicas/expert chunks; consider synchronous finalizers and stage-end GC; inspect host memory as well as VRAM |
| Finalizer failure | Packing/offload worker raised | Treat the run as incomplete; only a committed quiescent checkpoint is a durable resume point |
GPTQMODEL_RESUME=1 |
Raises ValueError at quantization entry |
Unset it and use CheckpointConfig in a new checkpoint directory |
| Checkpoint unsupported feature/chain | Entry support validator or adapter allowlist | Use the supported subset; do not assume ordinary quantization support implies resume support |
| Checkpoint identity mismatch | Source/config/calibration/runtime/kernel/topology/plan changed | Recreate the exact execution identity or use a new root; do not edit manifests to bypass validation |
| Another writer owns root | Nonblocking exclusive file lock | Ensure the old run has stopped and released its lease; do not launch concurrent writers |
resume="required" with no generation |
No published checkpoint | Select the correct root or start intentionally with "auto"/"never"
|
resume="never" with published generation |
Fresh-run policy protects existing work | Use a new directory |
| Corrupt retained checkpoints | No complete published candidate survives validation | Restore storage from backup or restart in a new root |
| More GPUs but no speedup | Subset barriers, GIL, replication overhead, method restrictions, or kernel occupancy | Profile end-to-end; visibility and worker count alone do not establish useful parallelism |
docs/exl3-mi350x-quant-lifecycle.md is a historical MI350X/gfx950 measurement record, explicitly not a current implementation specification. Its single-device timing/occupancy results are not universal defaults or throughput promises. In particular, merging sequential subsets can change quantized outputs: preserve numerical semantics when tuning scheduling.
All paths below are relative to the repository root. The source tree is available at the revision linked in the overview.
| Path | Main responsibility |
|---|---|
gptqmodel/models/base.py |
quantize, dataset delegation, processor selection, weight-only branch, model hooks, adapter-generation composition |
gptqmodel/utils/calibration.py |
Calibration normalization, validation, filtering, concatenation, sorting, batching |
gptqmodel/quantization/config.py |
Lifecycle selection, execution/memory defaults, fallback, preprocessors |
gptqmodel/looper/module_looper.py |
Calibration orchestration, device pools, named modules, final waits |
gptqmodel/looper/stage_inputs_capture.py |
First-layer capture and lazy module-path materialization |
gptqmodel/looper/stage_layer.py |
Layer/processor/subset flow, replay, finalizers, offload, boundaries |
gptqmodel/looper/stage_subset.py |
Resolved subset plans, coverage, MoE chunks, capture and worker dispatch |
gptqmodel/looper/forward_executor.py |
Serial/parallel cached forward execution |
gptqmodel/looper/input_cache.py |
Batch-aligned replay cache schema |
gptqmodel/looper/named_module.py |
Stable module identity, synchronized state, stream-to-CPU helpers |
gptqmodel/looper/execution_state.py |
Device scheduler continuation |
gptqmodel/looper/loop_processor.py |
Processor policy, state, logging, continuation, hooks |
gptqmodel/looper/module_preprocessor.py |
Ordered source/TP/smoothing plan annotations |
gptqmodel/looper/linear_mode.py |
Fused-linear runtime mode enum |
gptqmodel/nn_modules/qlinear/torch_fused.py, torch_fused_awq.py
|
Consumers of LinearMode
|
gptqmodel/looper/extension.py |
Execution plans, contexts, borrowed boundaries, extension dispatch |
gptqmodel/looper/checkpoint.py, checkpoint_store.py, checkpoint_devices.py, checkpoint_modules.py
|
Boundary persistence, transactional objects, topology, packed schemas |
gptqmodel/looper/gptq_checkpoint.py, continuation.py
|
Quantization adapter, identity, session wrapper, safe continuation encoding |
gptqmodel/looper/weight_only_looper.py, weight_only_processor.py
|
Calibration-free quantization and packing |
gptqmodel/looper/native_processor.py, dequantize_processor.py
|
Pristine-input capture and adapter-generation reconstruction |
gptqmodel/utils/offload.py, gptqmodel/utils/model.py
|
Disk offload, graph replacement, packer dispatch |
docs/looper-checkpoint-redesign.md |
Checkpoint design and validation record; implementation restrictions remain authoritative |
docs/multi_gpu_quantization.md |
Logical GPU pools and free-threaded MoE configuration |
docs/exl3-mi350x-quant-lifecycle.md |
Historical quantization-lifecycle profiling, not an API contract |
Documentation home · Quickstart · Troubleshooting · Repository · PyPI
Public source 8d42d0c29 declares package version 7.12.4. 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
- Paro
- FP8 and NVFP4
- NF12: lossless BF16 storage
- GGUF families
- BitsAndBytes: NF4 / FP4 / INT8
🧰 Refinement and execution
🧠 3 · Theory and advanced reference