Repository navigation
Loading and Inference
🏠 Home · 🧭 Choose a method · 🚀 Quickstart · 🧰 Help
On this page
- Overview
- 🧭 Choose the right loading intent
- 🚀 Use it: load, generate, then check the result
- Workflow at a glance
- Tokenizers and generation
- 🔬 Go deeper: loader contracts and runtime details
- Concepts
GPTQModel.load- Explicit loader entry points
- Post-quantization projection fusion
- How quantized-checkpoint detection works
- Nested checkpoints and source trust
- Checkpoint artifact checks
- GGUF identifier normalization
- RoPE configuration compatibility
- Loading adapters safely
- Concurrent loading and state validation
- Requirements and compatibility boundaries
- Environment variables and inference controls
- Pitfalls and troubleshooting
- Source files
- See also
Load the checkpoint you actually have, pick a compatible runtime, and generate text without starting a quantization job. For: application developers and anyone validating a saved model.
GPTQModel.load() is the public entry point for saved quantized checkpoints, dense inference/evaluation, and source models prepared for quantization. It inspects the checkpoint and dispatches to from_quantized() or from_pretrained(); these two paths have different device, tokenizer, adapter, and backend behavior. Supplying a QuantizeConfig does not itself quantize weights: quantization is a separate model.quantize(...) operation.
This reference describes source revision a4bfb7160. See Installation and Quickstart for installation and Quantization Lifecycle for source-model preparation and quantization.
| What you have | Use this when | Consider another path when |
|---|---|---|
| Saved quantized checkpoint |
GPTQModel.load(path) detects its saved configuration |
You want to change its bits or layout; a new config does not rewrite stored tensors |
| Dense model for inference/baseline | GPTQModel.load(path, quantize_config=None, device="accel:0") |
You intend to quantize; supply a method config before loading |
| Source model for quantization |
GPTQModel.load(path, quantize_config=...), then model.quantize(...)
|
You already have the final packed artifact |
| Published DeepSeek V4.1 Flash / Flash-1017 | Use its dedicated loader for indexed block-32 FP8/FP4 weights | You need padding, disk placement, adapters, or projection fusion |
| External engine | Select a compatible BACKEND.VLLM/SGLANG environment |
You need that engine's HTTP server; these adapters do not start it |
Prerequisites: install a matching Torch/runtime build, obtain checkpoint access, and check the saved format against the backend matrix. AUTO chooses among compatible installed implementations; it neither installs dependencies nor makes an unsupported model/shape/device valid. NVIDIA CUDA and AMD ROCm have distinct kernel contracts even though HIP uses Torch's cuda:N names.
from gptqmodel import GPTQModel
model = GPTQModel.load(
"ModelCloud/Llama-3.2-1B-Instruct-gptqmodel-4bit-vortex-v2.5",
device="cuda:0",
)
output_ids = model.generate(
"The capital city of France is",
max_new_tokens=32,
do_sample=False,
)
print(model.tokenizer.decode(output_ids[0], skip_special_tokens=True))Native causal-model generation normally returns prompt plus continuation. Slice by the tokenized prompt length when only the continuation is wanted. Do not assume the same return type for every external runtime; see Serving.
from gptqmodel import CalibrationConfig, GPTQModel, QuantizeConfig
model = GPTQModel.load(
"/path/to/source-model",
quantize_config=QuantizeConfig(bits=4, group_size=128),
)
# Quantize separately with a representative calibration dataset.
# model.quantize(CalibrationConfig(dataset=calibration_dataset), ...)If load() detects an already-quantized checkpoint, supplying a non-None quantize_config raises ValueError. Omit it to use the settings stored in the checkpoint, or pass an unquantized source to quantize. Recognized native FP8/NVFP4 formats can still enter the source/re-quantization path; AutoModuleDecoderConfig does not let an ordinary packed GPTQ/AWQ checkpoint bypass detection. Lazy source access preserves checkpoint-native names and conversion relationships through replay and export without eagerly dequantizing and caching the whole model. See native EXL3 export.
Use quantize_config=None to load an ordinary dense model for inference or evaluation. The architecture loads on CPU first, and GPT-QModel applies the requested placement. With neither device nor placement, dense loading uses accel:auto. A saved quantized checkpoint still follows the quantized loading path.
baseline = GPTQModel.load(
"/path/to/dense-source-model",
quantize_config=None,
device="accel:0",
)Use device="cpu" for a CPU baseline or pass a concrete accelerator to place the full model there. See placement options for sharding or offload.
Choose the activation dtype when loading. The first eager forward locks the input dtype of quantized linear kernels, including EXL3 and native-checkpoint TorchFP4Linear, and fused projections check the locks of their source modules. A later input with a different dtype raises RuntimeError. A cast that changes a locked parameter or buffer's dtype also raises. An explicit cast to a different activation dtype raises even when the stored operands already have the requested dtype. A device move that preserves tensor dtypes is allowed by the lock. A quantized linear returns the input dtype unless its documented role requires a wider output.
To change dtype after a forward, reload the model with the desired dtype or build a fresh module. If a whole-model cast raises, reload before continuing because modules visited earlier in the cast may already have changed dtype. Forward dtype contract
- Confirm which path loaded: dense, quantized native, or an external engine. Inspect the load logs and saved quantization config; a plausible reply is not evidence that the requested kernel ran.
- Use a short greedy prompt first. Native generation usually includes prompt tokens; SGLang returns text, and MLX has its own text-return contract.
- For an instruct model, apply its chat template explicitly. Compare exact prompt IDs against the dense baseline before diagnosing quality loss.
- Only then increase batch/context size or add adapters, fusion, or multi-GPU placement. Those features have separate compatibility and memory requirements.
Next: evaluate quality, serve an API, or plan memory and devices.
Public source for this guide: gptqmodel/models/auto.py · gptqmodel/models/loader.py · gptqmodel/models/base.py. Examples and declarations target revision a4bfb7160; source citations below use the same implementation revision.
Reading the diagram: Alternative intents, not sequential phases. Detected quantized inputs normally take from_quantized even when QuantizeConfig is supplied; native-float source exceptions are documented in the page.
Text version of the workflow
- Dense inference: Dense checkpoint → No QuantizeConfig → Apply placement → Native generation.
- Prepare quantization: Source checkpoint → Supply QuantizeConfig → from_pretrained → Ready to quantize.
- Saved quantized model: Recognized metadata → from_quantized → Initialize runtime → Runtime generation.
Ricursive Ripple (model_type="ricursive") uses the bundled model and tokenizer. The port uses Transformers 5.23 cache and mask APIs. Its model config controls MLP row chunking with mlp_chunk_size (default 2048, zero disables it), and logits_to_keep limits the projected positions during unlabeled generation. See Ricursive runtime behavior.
load_hf_tokenizer() selects the bundled tokenizer for ported checkpoints and uses Tokenicer for normalization. BaseQModel stores the Tokenicer wrapper on model.tokenizer. The underlying wrapped model's .tokenizer holds the tokenizer itself. See tokenizer normalization.
| Setting | Behavior |
|---|---|
| Supplied tokenizer |
GPTQModel.load(..., tokenizer=...) uses the supplied tokenizer on the standard source and quantized loaders and on DeepSeek V4.1 Flash. Pass a compatible PreTrainedTokenizerBase object, such as the result of AutoTokenizer.from_pretrained() for the original source model. Omitting tokenizer or passing None uses the checkpoint's tokenizer. The standard quantize() API also accepts tokenizer=.... |
tokenizer_trust_remote_code |
Separate tokenizer custom-code request in from_pretrained() or from_quantized(). It defaults to the original model-trust request, which load() passes explicitly. Executing checkpoint tokenizer Python also requires the checkpoint Python permission. |
| Pad/EOS metadata | Tokenicer uses the tokenizer's valid pad token or falls back to its EOS metadata, then aligns the model config's pad_token_id. The standard loader preserves a pad_token_id declared in the checkpoint's generation_config.json, including explicit null, even when you pass quantize_config=. If you explicitly supply a tokenizer with a pad ID, that ID takes precedence in the loaded generation config. |
| Chat template | Plain string generate() tokenizes text; it does not automatically turn it into a chat conversation. Apply the model's template explicitly. |
For models that require a text tokenizer, the standard loaders raise ValueError if the checkpoint has no usable tokenizer. This includes an effectively empty tokenizer that Transformers might construct from the model config alone. Restore the tokenizer assets for that checkpoint or pass the matching source tokenizer object when loading. Models such as Decision Transformer that consume named tensors can load without a tokenizer. Tokenizer validation · Loader
def generate(self, inputs=None, **kwargs):
...Generation normally runs under torch.inference_mode(). XLA devices and models with GPT-QModel CpuOffload or AlignDevicesHook(offload=True) use torch.no_grad(). This preserves version counters when offload hooks rematerialize layer tensors, so an ordinary forward can still follow generate(). If pad_token_id is omitted or None, the wrapper supplies the tokenizer's ID as a per-call argument when it has a tokenizer. Pass a concrete pad_token_id to override that argument. Dispatch differs by execution path:
| Input/path | Behavior |
|---|---|
| Native text string | Tokenizes with return_tensors="pt", padding=True, padding_side="left", normalizes the attention mask, and moves inputs to the model device. |
| Native list of strings | Batched tokenization with the same left-padding policy. |
| Tensor/token mapping | Normalizes supported higher-rank attention masks, then delegates to native generation. Unlike the text branch, it does not automatically move caller-provided tensors/mappings to the model device. |
| String without a tokenizer | Raises rather than guessing a tokenizer. |
Runtime with _runtime_generate
|
Delegates to the engine-specific generation adapter. Native Transformers' entire generation API is not guaranteed there. |
Native generation kwargs are passed to the underlying model. For external vLLM/SGLang, use supported sampling parameters and max_new_tokens, not Transformers' prompt-inclusive max_length. See Serving for the conversion tables and return types.
For a model already resident on one accelerator, dispatch omits redundant per-layer alignment hooks to avoid retaining GPU tensors through reference cycles. Place tensors on the execution device before a direct forward such as model.model(**inputs); do not rely on a hook to move CPU inputs. The string-based generate() path above still tokenizes and moves its inputs. Multi-device and offload maps retain placement hooks. See load-time memory ownership.
Use GPTQModel.load(..., state_quant=LeapQuantConfig()) to compress recurrent linear-attention state on native Kimi K3, dense Qwen3.5, and GLM-5.3 ports with eligible layers. Leave cache_implementation at the port's default and use unpadded input. See LeapQuant for configuration, supported ports, and cache limits.
For native Transformers generation, GPT-QModel checks the selected quantized linear kernels before delegating. If any kernel lacks SUPPORTS_COMPILE=True, the wrapper supplies disable_compile=True unless the caller selected a compile policy. This includes native EXL3 (ExllamaV3Linear): its runtime-handle path breaks the graph even though the class is not a BaseQuantLinear. Skipping auto-compilation avoids graph breaks that can slow decoding. cache_implementation="static" still selects a static cache; it does not require compilation.
| Caller choice | Behavior |
|---|---|
disable_compile=True or False
|
Preserved, including an explicit request to compile despite the kernel policy. |
Supplied generation_config with non-None disable_compile or compile_config
|
Its compile policy is preserved. |
compile_config=... without a supplied generation_config
|
Preserves the caller's compilation request. |
| No compile choice, at least one kernel opts out | Adds disable_compile=True; if a supplied generation config needs this default, a deep copy is changed, leaving the caller's object intact. |
Dense model, or all selected kernels have SUPPORTS_COMPILE=True
|
Leaves Transformers' compile policy unchanged. |
For an already loaded native model:
# Keep the static cache and explicitly request eager generation.
output = model.generate(
"Explain quantization briefly.",
cache_implementation="static",
disable_compile=True,
max_new_tokens=64,
)disable_compile=False explicitly permits Transformers compilation. TorchFP8Linear, AwqTorchLinear, BitsAndBytesLinear, and the portable MacaqLinear, QQQTorchLinear and VPTQLinear opt in. This does not change AUTO backend selection: native QQQ and VPTQ CUDA still opt out, as does MLX QQQ. Use BACKEND.QQQ_TORCH or BACKEND.VPTQ_TORCH to select the portable path explicitly. Marlin, ExLlamaV2, GPTQ Torch, and Paro retain the default opt-out. The policy also inspects kernels inside an optimized model's _orig_mod. An engine-bound _runtime_generate delegates before this native policy runs.
An opt-in requires both a zero-graph-break torch.compile(fullgraph=True) trace and faster measured compiled decoding on the claimed hardware. It is not a guarantee for every device or shape. Compiled FP8/AWQ reductions can change a greedy token relative to eager execution; use disable_compile=True when comparing against the eager baseline.
These generation controls are separate from QuantizeConfig(compile=...), which controls the Torch kernel's dequantization compiler. For compile levels and eager CUDA-graph capture declarations, see Kernel capabilities, the generation policy source, and the policy guide.
Explicit model.optimize(backend="inductor", mode=None, fullgraph=False) (also exposed through the deprecated model.compile(...) alias) compiles the quantized model's forward in place, so direct calls and native generate() enter it. model.compiled indicates that the compiled-forward wrapper was installed, not that lazy compilation has already succeeded. The first call pays compilation cost, repeated optimization does not stack wrappers, and supported deferred compiler failures fall back to eager. Unquantized models skip optimize().
optimize() prepares eligible eval-mode CPU int4pack layers before tracing. This avoids tracing the dense fallback just because no eager forward has run yet. See CPU int4pack compilation.
For attached LoRA adapters, optimize() aligns and locks the projection factors to the model dtype before tracing the first forward. An adapter already locked to a different dtype raises. See EoRA runtime loading.
The wrapper holds only a weak reference to the underlying model. After calls that trace new Dynamo frames, it collects reference cycles left by the trace without clearing the compiled-frame cache; cached calls do not trigger collection. Dropping the last model reference can therefore release its weights without a manual gc.collect(). PyTorch's allocator can still reserve the freed memory for reuse.
Each explicitly compiled forward uses the device of the first accelerator input, then the input embedding or the first accelerator parameter or buffer if needed. The caller's current device is restored even if the forward raises. This keeps Inductor's device defaults on the intended GPU during recompilation without changing tensor placement. The compiled TorchLinear dequantization path uses the same scope for direct kernel calls. See the compiled forward device scope.
With the default fullgraph=False, the compiled forward lets Dynamo handle compiler failures in the affected frame. It can run that frame eagerly without restarting earlier work that already updated the KV cache, recurrent state, or offload hooks. fullgraph=True does not enable this frame-level suppression. Ordinary model errors are not compile fallbacks. See the compile wrapper.
When Dynamo is already tracing a model forward, GPT-QModel's nested compile wrappers inline their original bodies without changing Dynamo configuration. This avoids a graph break that could fail static-cache generation with overwritten CUDA graph outputs, including with portable VPTQ. The compiled-forward proxy also skips reading Dynamo's global frame counter during an outer trace, so changes to that counter no longer force static-cache generation to retrace on every call.
With PyTorch's Dynamo trace predicate, trace-only behavior is local to the traced frame. An unrelated eager thread keeps its normal kernel caches and dispatch while another thread compiles. See concurrency.
Check the kernel's CPU compile level and limitations before requesting a full graph. The automatic generation policy above does not undo a forward explicitly compiled by optimize(): disable_compile=True disables Transformers' own auto-compilation, not that explicit forward replacement.
For the standard Transformers generation configuration, native loading no longer unconditionally forces generation_config.do_sample=True. An absent do_sample stays unset (greedy decoding by default), an explicit True stays enabled, and an explicit False is preserved when its sampling fields are consistent. Saving likewise does not add sampling merely to satisfy Transformers' strict configuration-save validation.
If Transformers' strict generation-config save check asks you to fix the configuration, the writer can use the config's to_json_file() serializer to write generation_config.json. If no fallback serializer exists, the original ValueError reaches the caller. Config writer
Re-saving a loaded quantized checkpoint preserves the live model's generation settings, including sampling parameters and an eos_token_id list defined only in generation_config.json. The writer deep-copies model.model.generation_config onto its checkpoint-facing save shell instead of using defaults derived from config.json; ordinary saves and EXL3 serialize the live model directly. This preserves caller changes without replacing the live generation-config object. See the generation-config round-trip contract and checkpoint saving.
There is a compatibility-repair exception: an explicit do_sample=False combined with a non-default sampling field is changed to True on load and by the post-save file sanitizer. The checked fields are temperature != 1.0, top_p != 1.0, any non-None min_p, typical_p != 1.0, epsilon_cutoff != 0.0, eta_cutoff != 0.0, and top_k != 50 when penalty_alpha is absent; None values do not trigger the comparisons. An absent do_sample is not repaired this way, even when sampling fields are present. For reproducible greedy native inference, pass do_sample=False explicitly to generate() rather than relying on a contradictory checkpoint. See the generation compatibility helpers and config writer.
messages = [{"role": "user", "content": "Explain weight-only quantization briefly."}]
inputs = model.tokenizer.apply_chat_template(
messages,
add_generation_prompt=True,
return_tensors="pt",
return_dict=True,
)
inputs = inputs.to(model.device)
output_ids = model.generate(**inputs, max_new_tokens=64, do_sample=False)
continuation = output_ids[0, inputs["input_ids"].shape[1]:]
print(model.tokenizer.decode(continuation, skip_special_tokens=True))The example requests a mapping with return_dict=True, preserving the attention mask and moving all input fields together. Without that option, tokenizer versions may return a tensor or a mapping. The native wrapper/server contain compatibility handling, but custom calling code should not assume .shape exists on every template result. For precise prompt comparisons, inspect the rendered template and token IDs before evaluating quantization quality.
BaseQModel.forward() delegates to the wrapped model. External runtimes are generation integrations, not a guarantee that native forward/logits APIs work on the engine object.
The sections below preserve the full dispatch, source-trust, placement, adapter, and compatibility reference. Start here only when adapting the practical path above.
| Concept | Meaning |
|---|---|
| Source model | A non-quantized model, or a supported native float-format model being used as the input to a new quantization run. Loaded through the model definition's from_pretrained(). |
| Saved quantized model | A checkpoint recognized from quantization metadata or a quantization configuration file. Loaded through from_quantized(). |
| Method | Quantization algorithm/family recorded in configuration, such as gptq, awq, or vptq. |
| Format | Saved tensor layout, such as gptq, gptq_v2, gptq_p, gemm, or gguf. It is not interchangeable with a backend name. |
| Backend | Native kernel selector or external execution engine; BACKEND.AUTO asks the selector to choose a compatible implementation. |
| Profile | A source-loading/GGUF loading policy, not a universal speed switch for every saved checkpoint. |
| Wrapper | A model-definition subclass of BaseQModel, containing the native model or external runtime, tokenizer, quantization configuration, and generation dispatch. |
The signature in gptqmodel/models/auto.py is:
@classmethod
def load(
cls,
model_id_or_path: Optional[str],
quantize_config: Optional[QuantizeConfig | Dict] = None,
placement=None,
device: Optional[Union[str, torch.device]] = None,
backend: Backend = BACKEND.AUTO,
profile: Union[str, int, PROFILE] = PROFILE.AUTO,
trust_remote_code: bool = False,
allow_remote_adapter: bool = False,
adapter_revision: Optional[str] = None,
adapter_sha256: Optional[str] = None,
fuse: bool = False,
p2p: Optional[Union[P2PConfig, Dict]] = None,
kernel: Optional[Union[KernelConfig, Dict]] = None,
module_tree: Optional[Union[str, List[Any], tuple]] = None,
runtime: Optional[RuntimeConfig] = None,
state_quant: Optional["LeapQuantConfig"] = None,
tokenizer: Optional[PreTrainedTokenizerBase] = None,
**kwargs,
):
...| Parameter | Default | Behavior |
|---|---|---|
model_id_or_path |
Required; annotated Optional[str]
|
Local model directory, Hub repository ID, or supported GGUF artifact path. Strings are stripped. The annotation does not make None a usable model identifier. |
quantize_config |
None |
QuantizeConfig or a dictionary converted with QuantizeConfig(**quantize_config). Used for source-model loading/re-quantization; raises ValueError on the normal already-quantized path. |
placement |
None |
A Placement, module-path dictionary, or root target string. See device placement. |
device |
None |
Requested device, forwarded to either loading path. Lists/tuples of one or more concrete accelerator ordinals constrain source quantization and default quantized layer-wise placement; singleton/duplicate sequences stay constrained, and integer ordinals use the active accelerator namespace. On the quantized path, a bare integer such as device=1 maps the whole model to that accelerator; an ordinal without an active accelerator raises. Concrete/abstract mixed sequences raise ValueError. Automatic quantization compute filtering requires quantize_config.device and compute_device_filter to be unset. See specific GPU selection. |
backend |
BACKEND.AUTO |
String, BACKEND member, or concrete BackendConfig such as MarlinConfig(fp32=False). Typed configurations select and tune a fixed backend. Explicit incompatible kernels/formats still fail validation. See typed backend configurations. |
profile |
PROFILE.AUTO |
Normalized through normalize_profile(), passed to source loading. It is not passed to the normal from_quantized() dispatch. |
trust_remote_code |
False |
Request to execute checkpoint Python where allowed. Package-owned ports take precedence. See the loader selection and permission rules. |
allow_remote_adapter |
False |
Explicit opt-in for a caller-selected remote adapter on a quantized model. Requires an adapter path, pinned commit, and weights digest; it is not a global permission for checkpoint metadata to fetch adapters. |
adapter_revision |
None |
Immutable 40-hex-character Hub commit for an explicitly selected remote adapter. Branches and tags are not accepted as pins. |
adapter_sha256 |
None |
64-hex-character SHA-256 digest of the remote adapter_model.safetensors. |
fuse |
False |
Explicit boolean opt-in for post-quantization projection fusion. A quantized wrapper applies it during initialization; a source wrapper records it for quantization finalization. Requires a qualified model definition; does not change backend selection. See Projection Fusion. |
p2p |
None |
P2PConfig or equivalent dictionary for multi-GPU peer-copy policy. With a target config it overrides quantize_config.p2p; otherwise that field supplies the policy. Quantized loads install the policy before peer setup. Also accepted by from_pretrained() and from_quantized(). See P2P configuration. |
kernel |
None |
Legacy KernelConfig or dictionary; accepted with enum/string selectors. Cannot combine with typed backend= or runtime=. Runtime-only. |
runtime |
None |
RuntimeConfig instance for shared quantizer, worker and host controls; overrides the quantization config's runtime when resolving without a legacy policy. Not a dictionary and not checkpoint metadata. |
module_tree |
None |
Explicit module-tree override; see Module plans. |
state_quant |
None |
LeapQuantConfig enables runtime recurrent-state compression on supported native ports. The policy is local to the loaded model and its new generation caches. |
tokenizer |
None |
Optional tokenizer object for the standard source or quantized loader. See Tokenizer ownership. |
**kwargs |
Empty | Passed to the selected loader after the public dispatcher's normalization. Examples include dtype, adapter on the quantized path, or engine initialization kwargs for an external backend. Not every kwarg is valid for every path. Use the explicit loader methods for a separate tokenizer_trust_remote_code override; load() already supplies that keyword internally. |
The initial config probe calls load_model_config() with the model identifier, resolved model trust, and config-selection options such as subfolder, revision, cache_dir, local_files_only, and token. The helper selects a package-owned config loader when one matches and otherwise delegates to Transformers' AutoConfig. For a private or gated Hub repository, pass token=... to GPTQModel.load() so the config probe and weight download can both authenticate. See the loader dispatch and config-selection options.
Native quantized loads reject unrecognized keyword arguments with TypeError and suggest a close match when available. They accept loader options such as attn_implementation and offload_dir, as well as options supported by the active snapshot downloader. On the Hugging Face Hub path, those include token, max_workers, local_dir, and endpoint. vLLM and SGLang pass engine-specific options to their runtime. See the accepted-key logic.
@classmethod
def from_pretrained(
cls,
model_id_or_path: str,
quantize_config: QuantizeConfig,
backend: Backend = BACKEND.AUTO,
profile: Union[str, int, PROFILE] = PROFILE.AUTO,
trust_remote_code: bool = False,
p2p: Optional[Union[P2PConfig, Dict]] = None,
kernel: Optional[Union[KernelConfig, Dict]] = None,
module_tree: Optional[Union[str, List[Any], tuple]] = None,
runtime: Optional[RuntimeConfig] = None,
**model_init_kwargs,
) -> BaseQModel:
...This public method normalizes GGUF arguments and the dtype alias, calls load_model_config(), resolves the model definition through check_and_get_model_definition(), and delegates to its loader. It can redirect to from_quantized() when metadata already identifies supported quantization.
That redirect preserves the caller's backend, adapter, placement, dtype/fusion kwargs, supplied tokenizer, tokenizer trust, and P2P policy. A target quantize_config cannot apply to an already quantized source and is not forwarded. A non-AUTO profile raises ValueError on this redirect rather than being silently ignored. Prefer load() or an explicit from_quantized() call for saved quantized checkpoints.
The public signature requires the quantize_config argument; pass None explicitly for dense loading without quantization preparation. The model-definition implementation in loader.py additionally exposes dtype="auto", placement=None, and device=None through its implementation signature. Its configuration/model-specific logic controls actual source-model construction. Dynamic per-module quantization produces a warning about HF Transformers support; vLLM/SGLang support discussed by that warning is still conditional on engine, model, format, and fused-module compatibility.
For a dense load, an explicit placement takes precedence. Otherwise a concrete device places the whole model, a device sequence splits the decoder across that pool, and an omitted device uses accel:auto.
@classmethod
def from_quantized(
cls,
model_id_or_path: Optional[str],
placement=None,
device: Optional[Union[str, int]] = None,
backend: Backend = BACKEND.AUTO,
adapter: Optional[Adapter | Dict] = None,
trust_remote_code: bool = False,
allow_remote_adapter: bool = False,
adapter_revision: Optional[str] = None,
adapter_sha256: Optional[str] = None,
p2p: Optional[Union[P2PConfig, Dict]] = None,
kernel: Optional[Union[KernelConfig, Dict]] = None,
module_tree: Optional[Union[str, List[Any], tuple]] = None,
runtime: Optional[RuntimeConfig] = None,
**kwargs,
) -> BaseQModel:
...Notice the public device annotation differs from load() and there is no explicit profile argument. The model-definition implementation also has dtype: [str | torch.dtype] = "auto". These are the source signatures, not an assertion that all annotation combinations are supported by every runtime.
The public method:
- Normalizes GGUF paths and
torch_dtype/dtypekwargs. - Separates tokenizer custom-code trust from model custom-code trust.
- Normalizes an adapter object/dictionary.
- Finds the appropriate registered model definition.
- Normalizes the backend and calls the model definition's
from_quantized().
The implementation in ModelLoader then resolves a local checkpoint directory, loads the saved QuantizeConfig, resolves manifest or explicit adapters, validates backend/format compatibility, loads the tokenizer, and constructs the model/runtime. Native paths instantiate quantized modules, load their tensors, perform format-specific conversion/post-initialization, and put the model in evaluation mode. External runtime paths create a runtime wrapper and attach generation dispatch instead of pretending that the engine is a Transformers module.
When you load a quantized checkpoint by Hub ID or directory, model.config.name_or_path records that identifier, including for the vLLM and SGLang adapters. The native quantized model also sets its underlying model's name_or_path. Use the wrapper's model_local_path for the resolved checkpoint directory.
For definitions that require a processor, loading first attempts to construct it. If that raises OSError or ValueError and the resolved quantized checkpoint directory has no processor metadata, loading logs a warning and proceeds with model.processor=None. Text inference remains available. The metadata check uses the selected subfolder and recognizes processor_config.json, preprocessor_config.json, video_preprocessor_config.json, and audio_preprocessor_config.json. If any of these files is present, processor errors propagate. Source-model loading still propagates processor errors. Processor loading
The native quantized loader rejects unsafe PyTorch .bin checkpoint loading. Use the supported safetensors checkpoint layout or a supported native GGUF path; renaming a .bin file does not make it safetensors. External engines retain their own checkpoint-reader constraints.
For packed GPTQ safetensors, the loader searches the canonical model basename before the legacy AutoGPTQ gptq_model-{bits}bit-{group_size}g basename. For each basename, it checks the sharded index before the single file. A legacy-only export still loads, but an older legacy file cannot take precedence over a fresh canonical save. See writer cleanup.
Before reading native quantized tensors, GPT-QModel checks that the checkpoint contains the required tensors for each selected kernel. A missing tensor raises ValueError with its key instead of leaving an uninitialized layer. See required checkpoint tensors.
During post-initialization, the loader checks each kernel's required payload for meta tensors. Resident layers initialize directly, including formats such as NF12, QQQ, VPTQ, and BitsAndBytes that have no GPTQ-style qweight buffer. For supported offloaded layers, the GPT-QModel offload hook materializes the payload for post_init() and releases it afterward. See kernel payload detection and offload.
Use device= for a whole-model target or a device pool. Use placement= to assign specific modules, request accelerator-memory balancing, or supply a weight budget.
| Input | What to expect |
|---|---|
device="accel:1" |
The second visible accelerator. You can also pass a concrete PyTorch device such as "cuda:1" or "cpu". |
device=("accel:0", "accel:1") |
Layer-wise loading across those devices. |
placement={"": "accel:0", "model.layers.[16:]": "accel:1"} |
Place the root on accelerator 0 and decoder blocks from index 16 onward on accelerator 1. Use paths from your model definition. |
placement="accel:auto" |
Balance over visible accelerators using free memory. Insufficient accelerator capacity raises. With no accelerator, use CPU. |
placement=Placement.budget({"accel:0": "20GiB", "cpu": "64GiB"}) |
Assign whole units against the listed weight budgets. The CPU tier offloads weights and executes those modules on the accelerator. Import Placement from gptqmodel.weight_loader. |
placement={"": "accel:0", "model.layers.[24:]": "disk>accel:0"}, offload_dir="/path/to/offload"
|
Store the selected blocks on disk and materialize their weights on accelerator 0 for execution. Use cpu>accel:0 to keep the backing weights in host memory. |
| Neither argument | Dense loading uses accel:auto. Native quantized loading builds its backend-aware layer-wise assignment. |
GPTQModel.load(), from_pretrained(), and from_quantized() reject the old device_map, max_memory, offload_folder, offload_state_dict, and offload_buffers keywords with TypeError. Use placement= for module and budget rules and offload_dir= for disk targets. See placement and offload behavior.
Explicit native backends must support the requested execution targets and offload mode. For host-offloaded weights, AUTO can skip kernels whose initialization needs accelerator-resident tensors. A one-device resident model can omit alignment hooks, so place input tensors on its execution device for direct forwards. See CPU and offload dispatch.
For source loading with a quantization configuration, QuantizeConfig.device selects the quantization compute device. Passing either loader device or placement alongside a configured QuantizeConfig.device raises AttributeError. Source weights are prepared on CPU or as a checkpoint-backed shell and moved for quantization.
The public backend enum is gptqmodel.utils.backend.BACKEND, re-exported by gptqmodel. Representative canonical values used by these loading paths are:
| Member | Value | Role |
|---|---|---|
AUTO |
auto |
Compatible native backend selection. |
GPTQ_TORCH |
gptq_torch |
Torch GPTQ implementation. |
GPTQ_TRITON |
gptq_triton |
Triton GPTQ implementation. |
MARLIN |
marlin |
Shared Marlin backend; method/format select GPTQ or AWQ. |
MACHETE |
machete |
Shared Hopper backend; method/format select GPTQ or AWQ. |
SWORDFISH |
swordfish |
Shared Blackwell backend; method/format select GPTQ or AWQ. |
ALLSPARK |
allspark |
Explicit W8A16 GPTQ/AWQ backend for supported CUDA or RDNA4 devices. |
GPTQ_BITBLAS |
gptq_bitblas |
BitBLAS GPTQ implementation. |
AWQ_TORCH |
awq_torch |
Torch AWQ implementation. |
FP8_TORCH |
fp8_torch |
Torch runtime for existing FP8 checkpoints (load-only); distinct from MLX. |
GGUF_TORCH |
gguf_torch |
Torch GGUF implementation. |
GGUF_TRITON |
gguf_triton |
Triton GGUF implementation. |
VPTQ_TORCH |
vptq_torch |
Torch VPTQ implementation. |
EXL3_TORCH |
exl3_torch |
Torch EXL3 implementation. |
VLLM |
vllm |
External vLLM runtime. |
SGLANG |
sglang |
External SGLang runtime. |
MLX |
mlx |
Checkpoint conversion into an MLX runtime, not Torch MPS execution. |
This is not the complete kernel/alias matrix; use Kernel Backends Reference for that reference. Hardware capability, bit width, group size, symmetry, activation ordering, dtype, and checkpoint layout affect compatibility. AUTO does not mean “Marlin on every machine.”
Model loading can impose narrower rules than a kernel class's declared formats. In particular, serialized Marlin/BitBLAS checkpoints select the matching method-specific backend on the local Torch path, with MLX handled separately. See format-specific loader branches before substituting a backend solely from the class tables.
All PROFILE enum values are:
class PROFILE(str, Enum):
AUTO = "auto"
FAST = "fast"
LOW_MEMORY = "low_memory"For native GGUF Q1_0 source loading, _resolve_native_gguf_profile() resolves AUTO to FAST; _should_use_dense_native_gguf_path() retains the dense HF import path for Q1_0 with FAST. Do not generalize that exception into a persistent dense-weight cache for quantized inference kernels. See GGUF.
Fusion is disabled by default. Use GPTQModel.load(..., fuse=True) or call
plan = model.fuse() on a quantized wrapper. Inspect plan.print() or
plan.to_dict() for eligibility and skip reasons; model.fuse(False) restores
separate execution and returns None. The explicit public loaders also forward
fuse through their keyword arguments to model-definition loaders.
This requires a definition-owned FusableConfig and compatible effective
quantization settings, native packed layout, and parent forward. Support for
ordinary inference does not imply fusion support. AUTO's selected native
backend is preserved. See Projection Fusion for qualified
models, overrides, runtime fallback, storage, and backend-specific limits.
GPTQModel.load() performs these operations before dispatch:
- When a quantization configuration is supplied, initiates best-effort quantization-related prewarming.
- Normalizes a GGUF artifact into a model root and internal filename, and strips a string identifier.
- Resolves model-code trust and normalizes configuration, backend, and profile inputs.
- Reads the selected model config with
load_model_config()for model directories and Hub IDs. A normalized absolute local path that is not a directory skips this initial probe. - Allows native float-format checkpoints to be treated as source models for re-quantization when that path is requested.
- Checks supported
config.quantization_configmetadata, then searches for standalone quantization configuration files locally or in the remote repository. - Calls
from_quantized()for a recognized checkpoint; otherwise callsfrom_pretrained().
This helper requires config.quantization_config to be a dictionary. It recognizes case-insensitive strings in quant_format, or in method with fallback to quant_method:
| Recognized method string |
METHOD member |
|---|---|
gptq |
METHOD.GPTQ |
gguf |
METHOD.GGUF |
fp8 |
METHOD.FP8 |
bitsandbytes |
METHOD.BITSANDBYTES |
awq |
METHOD.AWQ |
paro |
METHOD.PARO |
qqq |
METHOD.QQQ |
vptq |
METHOD.VPTQ |
exl3 |
METHOD.EXL3 |
tt-blockfloat |
METHOD.TT_BLOCKFLOAT |
The helper first checks _unsupported_quantization_metadata(). Unsupported activation-quantization or kv_cache_scheme metadata raises ValueError naming the actual feature rather than being silently treated as a dense model; a KV-cache scheme is not reported as activation quantization. Empty schemes and explicitly declared num_bits >= 16 are not precision reductions and do not trigger this guard. A nonempty scheme without a usable width is rejected conservatively. This guard is not a claim that every format from every producer with a recognized method label is loadable; ModelOpt runtime validation also checks for pre-quantized activation/K/V side scales. Use a compatible weight-only variant or a serving runtime that implements the declared cache scheme.
After a successful GPTQModel.load(...), the loader logs model storage, available device memory, and KV-cache estimates where the config is recognized. Use model.budget() for a snapshot and a context/batch plan, or model.kv_cache_estimate() for the cache estimate alone. A dtype override applies to the estimate. See KV-cache memory estimates.
Native block-float checkpoints use a dedicated from_quantized() route when local config.json declares quantization_config.quant_method="tt-blockfloat". The loader rebuilds packed linears, embeddings, and the tied head from the safetensors index on CPU and uses the checkpoint's declared dtype unless explicitly overridden. Omit device and placement, or pass device="cpu". Move model.model afterward to select eligible CUDA or ROCm emulation. See Tenstorrent storage and loading.
There are two related but different mechanisms:
| Stage | Files/metadata examined |
|---|---|
Public load() detection |
Supported quantization_config in the selected model config, or discovery of quantize_config.json / quant_config.json in the selected checkpoint. |
| Quantized loader's configuration reader |
QuantizeConfig.from_pretrained() checks quantize_config.json, then quant_config.json, then config.json; for the last file it reads its quantization_config member. |
quantize_config.json is the canonical filename (QUANT_CONFIG_FILENAME). Do not confuse it with quant_config.json, which is supported for compatibility, or invent a quantization_config.json requirement. If none of the three files exists, QuantizeConfig.from_pretrained() raises ValueError naming the checkpoint directory. If a file exists but its metadata is missing or malformed, parsing or validation can still fail.
For sidecar-only legacy checkpoints, GPTQModel.load() looks inside the requested subfolder; a sidecar at the root does not mark a nested dense checkpoint as quantized. On the Hub the probe also honors revision. With HF_HUB_OFFLINE=1, it checks the selected files in the local Hub cache instead of listing the remote repository. See the loader.
subfolder="nested/checkpoint" selects one repo-relative checkpoint directory. Model-definition detection, configuration, quantization metadata, weights, tokenizer, and checkpoint-relative adapter manifests resolve against the same subfolder and requested revision. The wrapper also uses the nested directory as its model_local_path, so processor and auxiliary-file lookups use the selected checkpoint rather than the repository root. The vLLM and SGLang runtime paths receive that directory too. This applies to downloaded Hub snapshots and local directories. Absolute paths, drive prefixes, backslashes, traversal segments, and existing symlink escapes are rejected.
With huggingface_hub 2.x, a filtered Hub snapshot can load by repo ID while offline or with local_files_only=True. If the Hub reports an incomplete snapshot, GPT-QModel accepts the cached directory when the selected checkpoint contains config.json. A filtered download can omit files such as the README and duplicate source weights. Cache the selected model's required weight, tokenizer, and processor files. If the cached checkpoint lacks its config, the Hub's incomplete-snapshot error is surfaced. See the snapshot resolver.
Package-owned ports take precedence over auto_map during model loading and reconstruction. Checkpoint Python requires explicit permission for supported fallback paths. Remote adapters use separate controls.
When save() rebuilds an export shell for a loaded quantized model, it rereads the config from the selected local checkpoint directory, including the nested directory if you passed subfolder. GGUF shell reads retain the selected filename. A missing or malformed selected config stops the save. Repair that config and retry. Checkpoint config selection
When a package definition owns a text model's config, the writer omits the source auto_map and checkpoint .py files from new exports. Definition-owned models that declare multimodal or processor requirements can retain the source metadata and files for external consumers. Export policy
Integrations using the writer mixin directly can supply the selected checkpoint as model_local_path when the wrapper's recorded checkpoint repository path is absent. See the writer.
Loader dtype aliases normalize "bfloat16" and "torch.bfloat16" to the same Torch dtype; invalid dtype names fail explicitly. Saved-model reconstruction and resaving use the checkpoint/model dtype, including quantized bias slots, rather than routing BF16/FP32 state through FP16 placeholders. This prevents range loss before weights or biases are copied. Explicit dtype conversion remains the caller's choice, subject to the selected kernel's supported dtypes.
Quantized loading preserves persistent floating quantization buffers when a model-dtype cast would lose values, including QQQ group/channel scales, EXL3 sign vectors, and Paro/MACaQ side state. Buffers declared activation-side by a module's MODEL_DTYPE_BUFFERS follow the requested model dtype; lossless widening may remain widened. Re-save shells restore stored buffer and dense floating Parameter dtypes exactly, including mixed-dtype norms, embeddings and unquantized heads/projections, while preserving tied parameter identity. Ordinary inference loads still cast dense parameters to the requested dtype. Repacking a CPU-transformed int4pack module uses its canonical checkpoint snapshot rather than its runtime layout; modified, non-exportable runtime state raises instead of producing an incompatible checkpoint. See checkpoint buffer preservation.
For AWQ GEMV, GEMV_FAST, and LLM_AWQ, AUTO resolves an inferred dtype to FP16 before source-model materialization/calibration or quantized loading. An explicit unsupported dtype such as BF16 raises early instead of being silently changed or failing during layer-0 finalization. Pass dtype=torch.float16, or use a GEMM-format checkpoint/config and a backend supporting BF16. Explicit backends are checked against their declared dtype support; this does not add hardware or format coverage. See AWQ layout selection.
The in-memory dequantize_model(model, dtype=None) helpers in qlinear/torch.py, torch_fused.py, and torch_aten_kernel.py now resolve dense weight/bias dtype independently of packed scale storage. An explicit dtype wins; otherwise non-quantized parameters and persistent buffers supply the compute dtype, preferring FP16/BF16 over incidental FP32 state. Only a model with no such floating state falls back to the quantized layer's bias, then scales, then FP16. This keeps BF16 models BF16 even when GPTQ scales are stored in FP16. Each helper requires its matching quantized-linear class, replaces those layers with nn.Linear modules on each source layer's packed-weight device, and does not cast surrounding modules; an explicit override must still match the caller's execution plan. This is separate from checkpoint-based gptqmodel.utils.model_dequant.dequantize_model() conversion; the former GPTQModel.export() API has been removed. See the dtype resolver and Torch helper.
GPT-QModel automatically checks artifacts from the selected local checkpoint directory or downloaded Hub snapshot. It stops loading when a check fails, including when an unused named chat template is rejected. These checks run with both values of trust_remote_code and remain active when GPTQ_BYPASS_SAFETY_CHECKS is set.
| Artifact | What GPT-QModel checks |
|---|---|
Selected .gguf file |
Tensor bounds, overlap, alignment padding and end of file, plus default and named chat templates in GGUF metadata. Inspection runs before Transformers reads the GGUF config, including on the dense import path. See loading a GGUF file. |
| Chat templates | Static inspection of chat_template.jinja, named templates under additional_chat_templates/, and templates in checkpoint JSON metadata. GPT-QModel also checks templates attached to loaded tokenizers and processors. |
| Safetensors weights | Checks root files and indexed shards, including nested shards, for safe paths, valid headers and data bounds before weight dispatch. Safetensors indexes must reference safetensors files. Resharding also checks each input shard before copying its data. |
| Legacy PyTorch weights | Dense loading and legacy conversion require weights_only=True. The native quantized loader retains its safetensors or supported GGUF policy. |
For a rejected artifact, compare the reported file with the original publisher's trusted revision. See troubleshooting a rejection and the artifact security reference.
normalize_model_id_or_path_for_hf_gguf() in gptqmodel/utils/hf.py is shared by the public entry points. It is distinct from quantization-method detection.
| Input situation | Result |
|---|---|
Explicit existing local .gguf file |
Resolves to its parent model root plus an internal artifact filename. |
| Directory/Hub repository with one unambiguous GGUF artifact | Can infer the artifact and carry the internal filename to HF configuration/model loading. |
| Multiple GGUF choices | Does not select an arbitrary quantization. Use an explicit local artifact path or a repository layout that identifies one artifact. |
| Repository also containing dense model weight artifacts | Single-GGUF inference is suppressed rather than silently replacing the dense checkpoint. |
Public non-None gguf_file=... kwarg |
Rejected with TypeError; provide the artifact/model identifier through the supported input path instead. |
Dense GGUF import uses the stock Transformers loader. See GGUF load controls for native packed detection and internal conversion.
HF configuration normalization preserves existing rope_parameters dictionaries keyed by layer/rope type rather than appending flat legacy rope_type or rope_theta scalars beside them. Type labels follow Transformers' resolution order: _rope_type_labels first, then layer_types. This covers hybrid layouts such as Dots3's sliding/full attention dictionaries and DeepSeek V4's main/compress dictionaries; a no-RoPE entry can remain None. Flat or missing legacy parameters still receive the applicable compatibility defaults. Do not flatten a valid per-type dictionary as a loading workaround. The implementation is gptqmodel/utils/hf.py::_normalize_rope_parameters_config_compat().
Runtime adapters are normalized by normalize_adapter() in gptqmodel/adapter/adapter.py. The registered serialized adapter name is lora; an existing Adapter instance is also accepted. Serialized A/B fields, if supplied, must be actual tensors, not arbitrary serialized executable objects.
File-backed adapter attachment honors PEFT target_modules and exclude_modules and checks that both A/B tensors exist. Partial adapters skip uncovered modules; eligible targeted dense linears also receive the correction. Unsupported embedding LoRA, DoRA, bias-training, modules_to_save, layer-replication, QALoRA/aLoRA, target-parameter, and CORDA features raise rather than silently changing the adapter's math. See EoRA runtime loading for exact matching and compatibility limits.
from gptqmodel import GPTQModel
model = GPTQModel.from_quantized(
"/path/to/quantized-checkpoint",
adapter={"name": "lora", "rank": None, "path": "/path/to/local-adapter"},
device="cuda:0",
)rank=None is populated from the loaded LoRA configuration's r. Every other supplied rank, including 0, must equal that r. Rank patterns can subsequently override the rank for individual modules. The loader reads adapter_config.json and adapter_model.safetensors, matches per-module LoRA A/B weights, and caches adapter config and tensors by source and pin while consuming their weights.
Dense attachments lock the adapter dtype to the module's weight dtype when loaded. Quantized linears lock it on the first eager forward. Choose dtype when loading. If you need a different dtype after the lock, reload the model with the adapter at the desired dtype. See EoRA runtime loading.
| Adapter source | Policy |
|---|---|
| Explicit local directory | Accepted without remote permissions. Do not pass remote pin options for a local adapter. |
| Adapter path in checkpoint configuration | Must resolve to an existing relative directory inside the checkpoint. Absolute paths, traversal, and directory symlinks are rejected; file symlinks have a narrow same-checkpoint HF cache-blob exception. |
| Explicit Hub adapter | Disabled by default; requires allow_remote_adapter=True, immutable revision, and safetensors SHA-256. |
| Explicit HTTPS URL | Only supported Hugging Face blob URLs are parsed; the URL revision must match the caller's immutable revision. Arbitrary HTTP/file URLs are not a supported adapter source. |
| Missing explicit remote path | Supplying remote permissions/pins without an explicit remote adapter is an error. |
An explicit remote adapter can be supplied through load(..., adapter=...) or directly through from_quantized():
model = GPTQModel.from_quantized(
"/path/to/quantized-checkpoint",
adapter={"name": "lora", "rank": None, "path": "owner/adapter-repo"},
allow_remote_adapter=True,
adapter_revision=immutable_commit, # 40 hexadecimal characters
adapter_sha256=weights_sha256, # 64 hexadecimal characters
)The variables must contain verified values for that adapter. Both pins are required; checksum mismatch fails loading. A checkpoint manifest cannot grant itself remote access. Remote-adapter options on a non-quantized load() branch raise ValueError. Model trust_remote_code=True does not replace any of these adapter checks.
See EoRA for generating quantization-error recovery adapters and Inference Backends for kernel-specific adapter support.
For native safetensors reloads, checkpoint tensors are copied to the devices resolved by WeightLoader. Reads use bounded byte ranges, and CPU tensors at their stored dtype can share their mapped windows. Targeted checkpoint reader
Eligible legacy-layout safetensors load directly from their original shards. With a resolved Placement and no disk targets, the loader maps checkpoint keys to runtime names and places tensors without writing renamed copies of the shards. Disk targets use the temporary key-conversion path when remapping is required. Packed FP8 buffers are restored from the original checkpoint. Checkpoint key conversion
When no definition-specific converter takes precedence, the Transformers source map leaves keys that already match a runtime parameter or buffer unchanged. It can apply multiple declared renames to an old key to reach a runtime name. For example, a DeepSeek-V4 checkpoint's runtime model.norm.weight stays intact, while its legacy attention norm can map through both the attention and norm renames. See checkpoint key layout.
GPTQModel.load() calls through the model-definition from_pretrained() and from_quantized() entry points are serialized by a process-wide reentrant lock. Save-side quantized-shell reconstruction, model dequantization, and Tenstorrent block-float from_config construction use the same lock. It does not serialize subsequent quantize() calls on already-loaded models or entire loads made directly through Transformers.
Eager calls through the GPT-QModel wrapper and compiled calls that reuse a cached graph can run concurrently. A call that may trace a graph takes the exclusive side of a separate model-global-state lock, so it may wait for an in-flight generate() or forward in the same process. This protects eager calls through model(...), model.forward(...), and model.generate(...) from PyTorch's process-wide tracing changes. It also applies to CPU BACKEND.GPTQ_TORCH when the kernel compiles weight decoding without an explicit model.optimize() call. Lazy compilation and concurrency
GPT-QModel's pass-through construction guard takes the same exclusive lock around Transformers' initialization contexts, including in direct Transformers calls. It serializes temporary default-dtype changes, class replacements, and class-wide suspension of tie_weights(). GPT-QModel takes the same lock to re-tie weights after checkpoint load, so that step waits for any concurrent suspension of tie_weights() to end. Compiled inference can overlap weight I/O, device placement, packing, and kernel post_init(). Loading a quantized model leaves other models' Dynamo caches intact. Construction guards and compile wrapper
Concurrent compilation and quantization. The exclusive guard covers changes and restores for process-wide TF32 precision, CPU oneDNN BF16x3 precision, and the worker pool's temporary Torch intra-op thread count. The package's gptqmodel.utils.torch.torch_compile() wrapper coordinates with this guard. A raw torch.compile trace that starts before the TF32 guard can restore the caller's precision while quantization is inside the guard. Let the raw trace finish before quantize(), or use the package wrapper. See the concurrency contract.
Load-time checks compare the process default dtype before and after loading under the exclusive guard, so another construction's temporary dtype does not cause a false failure. They raise RuntimeError if the settled default dtype changed, or if a checked materialized model retains meta floating parameters or violates its requested/uniform dtype. Intentional disk-offloaded CheckpointSource shells skip materialization/dtype checks; MLX objects without Torch parameters only receive the default-dtype check. Native source loading also runs the model definition's pre-load hook before construction. See the concurrent loading contract and loader.
Intentional FP32 parameters. assert_loaded_model_state() excludes FP32 parameters that match _keep_in_fp32_modules or _keep_in_fp32_modules_strict from its dtype check. It expands * to .* and searches the full parameter name with the resulting regex. The validator checks for meta parameters before applying the dtype exemption. See the state validator.
Native quantized reloads requested in FP16 or BF16 preserve checkpoint FP32 tensors that match _keep_in_fp32_modules_strict. This includes both parameters and buffers, such as the ERNIE router weight and the DeepSeek-V3 or GLM-4.x router correction bias. The Hunyuan MoE v1 router weight (mlp.gate.wg) and Zamba's Mamba parameter (A_log) are also declared strict FP32, including when loading a source model in either half dtype. See the checkpoint-loading helper, Hunyuan declaration, and Zamba declaration.
The lazy meta shell also marks matching floating-point parameters and buffers FP32 when built for FP16 or BF16. With source disk offload, CheckpointSource materializes them at the shell's FP32 dtype, preserving the original precision through quantization and re-save. See the shell builder.
Raw GPTQ state dicts carry their qzero convention in a persistent qzeros_format tensor, preserving v1/v2 round trips even after safetensors transport or plain-dict copying. The GPT-QModel checkpoint writer omits these marker tensors. Reload uses the saved checkpoint_format metadata. Partial loads without qzeros preserve the live layout. Transformed CPU GPTQ/AWQ int4pack layers emit their checkpoint snapshots. Kernel-private runtime payloads are marked 0 and cannot be loaded as checkpoints. See checkpoint interoperability. Optimized TorchLinear pickling drops its compiled dequantizer and restores eager execution on unpickle. GPT-QModel exports use safetensors.
Importing gptqmodel makes Transformers treat Accelerate as unavailable. Use GPTQModel.load for native per-expert MoE, dynamic and GPT-QModel-only checkpoints. Legacy quantized VL keys use the model's conversion map when the definition has no explicit converter. Packed GGUF safetensors intentionally identify their HF-facing method as gptqmodel_gguf and require a compatible loader. See Hugging Face Integration.
For MLX, generate() now accepts prompt/prompts/input_ids, max_new_tokens, sampling aliases, seed, explicit EOS IDs, and returned-text stop trimming. It returns one string or a list of strings, not Transformers token tensors, and does not interpret attention masks. See the generation adapter for exact precedence and defaults.
| Component | Declared requirement or boundary at this source revision |
|---|---|
| Python |
>=3.11 in pyproject.toml. Optional engines may impose stricter version constraints. |
| Tokenicer |
tokenicer>=0.0.21 in requirements.txt. Tokenizer normalization can change independently of quantized math. |
| Triton extra |
triton>=3.8.0 for Python <3.15. Installing it does not make a CUDA-only kernel run on every device. |
| CUDA/ROCm | Match the chosen kernel and PyTorch build. ROCm uses cuda devices in PyTorch, but has separate availability/capability checks. There is no single universal CUDA/ROCm minimum enforced by GPTQModel.load() itself. |
| MLX extra |
mlx>=0.32.4 and mlx_lm>=0.32.2. The MLX conversion and runtime path requires both packages. See MLX Apple Silicon. |
| vLLM/SGLang | Optional engines with their own dependency/hardware matrices and distinct accepted formats. Use a dedicated engine environment; see Serving. |
Select and tune an execution backend with GPTQModel.load(..., backend=MarlinConfig(fp32=False)), and supply shared controls with runtime=RuntimeConfig(max_packers=2). Import these classes from gptqmodel.backend or gptqmodel. All three public loaders accept both controls. When you later call model.quantize() with its default AUTO argument, it reuses the source-loading choice if the kernel supports packing. A retained inference backend such as Marlin triggers a warning and the method's default packer. An explicit backend at quantization time must support packing.
Legacy kernel=KernelConfig(...) or a dictionary remains supported with enum/string selectors. Combining legacy kernel= with typed backend= or runtime= raises ValueError. Quantized linears snapshot their own policy, so later loads do not retune existing modules; shared quantizer/host utilities still use a process fallback. Unset run policies reset to defaults. These settings are not checkpoint metadata. Retired kernel/thread environment switches have no effect; those in the migration registry warn once at import or a later load boundary with their API replacements. See typed configurations and policy lifetime.
utils/env.py contains the shared boolean parser, not a registry of all settings:
TRUTHFUL = {"1", "true", "yes", "on", "y"}
def env_flag(name: str, default: str | bool | None = "0") -> bool:
...Values are stripped and lowercased; an unset variable uses the supplied default (None means false). A variable present with an empty or unrecognized value is false. These remaining environment readers are separate from typed kernel policy.
| Variable | Default/interpretation | Scope |
|---|---|---|
GPTQMODEL_USE_MODELSCOPE |
False via env_flag
|
Selects the ModelScope-enabled Hub path. If requested without the package, raises with pip install modelscope; it is not a silent fallback. |
GPTQMODEL_PRINT_MODULE_TREE |
False | Opt-in module-tree printing in the loader. |
GPTQMODEL_POOL_PREWARM |
True via env_flag
|
Controls the best-effort device thread-pool prewarm initiated for source quantization loading. |
GPTQMODEL_LINEAR_PREWARM |
True via env_flag
|
Best-effort one-time background accelerator linear-library initialization. |
GPTQMODEL_QUANTIZE_PREWARM |
True via env_flag
|
Best-effort one-time quantization-payload prewarm. |
DEBUG |
False via env_flag
|
Package/importer debugging. |
GPTQMODEL_LOG_TIMES |
False via env_flag
|
Logger timing display. |
Quantized inference weights must remain quantized between uses. KernelConfig.torch_cache_weights and torch_lookahead are retired compatibility options: requesting them warns and leaves expanded-weight caching disabled. Dequantization temporaries are local to the current operation. Kernel-specific controls are documented in Kernel Backends Reference.
-
Already quantized versus source loading: inspect configuration metadata and filenames before assuming a caller-supplied
QuantizeConfigwill re-quantize a checkpoint. -
Placement differences:
load()forwardsdeviceandplacementto both branches. Quantization finalization can switch packed AWQ, QQQ, GGUF, and GPTQ layers to a kernel that supports their final device. GPTQ packed withBACKEND.TRITONcan switch toTorchLinearfor inference on the returned CPU model. See in-session finalization. -
Dtype aliases:
normalize_torch_dtype_kwarg()translates deprecatedtorch_dtypetodtype, warns, and rejects conflicting values. Prefer onedtypeargument. -
Unknown kwargs: passthrough is path-specific. An engine option is not automatically a Transformers option, and generation options belong to
generate(), notload(). -
Profile: the normal quantized
load()branch does not forward it. Set performance/memory expectations using the actual backend and checkpoint format. - Tokenizer and prompt quality: establish a non-quantized baseline with identical rendered prompts and input IDs before calling bad generation a quantization regression.
- Adapters: local paths, checkpoint-contained paths, and explicit remote adapters have intentionally different permissions.
- Hardware: a recognized method and a valid safetensors file are necessary but not sufficient for a specific kernel/device combination.
- Serving: the built-in HTTP shim has different limitations from native generation and external-engine servers; read Serving before exposing it.
| Path | Key implementation |
|---|---|
gptqmodel/models/auto.py |
Public load, from_pretrained, from_quantized; metadata detection; model-definition selection; trust/adapter forwarding. |
gptqmodel/models/loader.py |
ModelLoader implementations, device placement, configuration/tensor loading, external runtime routing, GGUF profile handling. |
gptqmodel/models/base.py |
Wrapper/tokenizer initialization, generate, forward, serving entry points. |
gptqmodel/quantization/config.py |
QuantizeConfig, METHOD, FORMAT, canonical/compatibility filenames. |
gptqmodel/utils/hf.py |
GGUF normalization, dtype aliases, trust resolution, Tokenicer construction, generation-config compatibility. |
gptqmodel/utils/artifact_security.py |
Static chat-template inspection, checkpoint shard validation, and the weights-only requirement. |
gptqmodel/utils/backend.py |
BACKEND, PROFILE, normalizers. |
gptqmodel/utils/importer.py |
Device normalization and kernel selection. |
gptqmodel/adapter/adapter.py |
Adapter normalization, LoRA application, adapter cache. |
gptqmodel/adapter/remote.py |
Checkpoint containment, explicit remote permission, immutable revision and digest checks. |
gptqmodel/utils/env.py |
Shared truth-value parser. |
gptqmodel/utils/modelscope.py, gptqmodel/utils/hub.py
|
Optional ModelScope selection and Hub routing. |
gptqmodel/utils/linalg_warmup.py, gptqmodel/__init__.py
|
Prewarm and worker controls. |
gptqmodel/nn_modules/qlinear/torch.py |
Torch inference switches and disabled legacy dense-cache compatibility shims. |
pyproject.toml, requirements.txt
|
Python and optional/core dependency declarations. |
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