Repository navigation
GGUF
🏠 Home · 🧭 Choose a method · 🚀 Quickstart · 🧰 Help
On this page
Choose a block-quantized representation or load an existing .gguf model—without confusing the two workflows. For: readers importing GGUF artifacts or packing HF weights for GPT-QModel’s GGUF-aware runtimes.
GPT-QModel supports GGUF in two related but distinct forms:
-
GGML block-quantized linear weights in a GPT-QModel checkpoint, configured with
GGUFConfig, saved through the normal checkpoint writer, and executed by GGUF-aware Torch, native ggml, Triton, or MLX kernels. -
A
.ggufmodel file, resolved by the Hugging Face integration and imported either into a packed GPT-QModel runtime or into a dense Transformers model, subject to the loader restrictions below.
These are not interchangeable file formats. FORMAT.GGUF identifies the quantization family; it does not mean that model.save(...) writes a standalone llama.cpp model file. GGUF block compatibility, model-file compatibility, architecture support, and execution-kernel support are separate checks.
GGUF is a model-file container, not one dtype or one quantization algorithm. GGML tensor types such as Q4_0 and Q4_K define different number/block representations; GPT-QModel also uses METHOD.GGUF and FORMAT.GGUF for its packed-checkpoint family. The distinctions here are checked against 1f5f2ffdb. See Dtypes and formats for the broader map and llama.cpp for the model-file ecosystem.
| Your goal | Start here |
|---|---|
| Choose and understand | The route table below; compare methods and dtypes |
| Use it |
Pack an HF source · Export a standalone .gguf file · Load a .gguf file
|
| Go deeper | Configuration · Layout sizes · Backend arithmetic |
| Choose this when… | Use this route | Consider another path when… |
|---|---|---|
| You have dense HF weights and want no-calibration block packing |
GGUFConfig → quantize() → save()
|
You need activation-aware optimization: compare GPTQ, AWQ, or VPTQ |
You already have a .gguf file |
Pass the artifact to GPTQModel.load; check import eligibility and profile |
You assume every architecture/type combination stays packed; some imports become dense |
| You have a GPT-QModel GGUF checkpoint and need a single file for llama.cpp | Package it with GGUFPackageConfig |
The checkpoint uses an unsupported architecture, tokenizer, or packed layout |
- Follow Installation and Quickstart. The internal model-file reader needs no external
ggufpackage; other packing/native-runtime routes can need optional dependencies listed below. - For packing, provide a supported unquantized HF model. No calibration corpus is required. For import, select one unambiguous
.ggufartifact plus the model/config/tokenizer assets needed by the HF integration. - Pick an exact alias and runtime, not just “four-bit.”
q4_k_mmaps to uniformQ4_Khere; its suffix does not reproduce llama.cpp’s whole-model mixed-type preset. - NVIDIA CUDA, AMD ROCm, CPU ggml/Torch, and Apple Silicon MLX have different qtype/shape/toolchain requirements. The Triton backend’s explicit CUDA/ROCm declaration is not a promise for every vendor or architecture.
Reading the diagram: Packing needs no calibration. Single-file packaging starts from a saved checkpoint. Import depends on architecture, tensor type, processor and profile. Q1_0 auto/fast chooses dense import.
Text version of the workflow
- Create a GPTQModel checkpoint: Choose a GGUF subtype → Pack source matrices → Save checkpoint directory.
- Package a standalone .gguf file: Read a saved GGUF checkpoint → Write model-file metadata and payloads → Verify and publish the file.
- Eligible packed .gguf import: Check import eligibility → Install packed blocks → Execute block kernels.
- Dense HF .gguf import: Resolve the model file → Decode GGUF tensors → Run the dense model.
from gptqmodel import GPTQModel
from gptqmodel.quantization import GGUFConfig
from gptqmodel.utils.backend import BACKEND
config = GGUFConfig(bits="q4_k") # Exact block alias, not a whole-model preset.
model = GPTQModel.load("/models/source-hf", quantize_config=config)
model.quantize(backend=BACKEND.GGUF_TORCH)
model.save("/models/gguf-block-checkpoint")
loaded = GPTQModel.load(
"/models/gguf-block-checkpoint",
backend=BACKEND.GGUF_TORCH,
)The source directory must contain a supported, unquantized HF model. This weight-only lifecycle ignores any supplied calibration dataset: it performs no activation capture, Hessian solve, or calibration replay. Configured preprocessing is planned without forward passes; optional smoothing acts on weight blocks. Adapter/EoRA generation, GPTAQ, and FOEM are rejected in this lifecycle. GGUFTorchLinear.pack_original(...) ignores GPTQ scales, zeros, and g_idx, applies an optional smoother, pads the source width to a complete GGML block, and packs the source weight matrix.
The output is a GPT-QModel checkpoint directory, not a new llama.cpp .gguf artifact. Native C++ inference classes deliberately disable pack, pack_block, pack_gpu, and pack_original; use a packing-capable backend for quantization and select C++ at load time.
from gptqmodel import GPTQModel
# Supply the artifact itself as model_id_or_path.
model = GPTQModel.load("/models/bonsai/model.gguf", profile="low_memory")The public API rejects gguf_file=.... Pass the local file itself, or a local directory / Hub repository with a single unambiguous .gguf file. Automatic single-file inference requires exactly one GGUF and no dense checkpoint files recognized by the resolver. Repositories with several GGUF choices should be downloaded/selected explicitly; do not rely on an arbitrary first file.
The HF adapter resolves the file into its enclosing model location plus an internal gguf_file argument. Transformers still handles the model/config/tokenizer interpretation; the internal GGUF reader is not a universal model-architecture implementation.
GPT-QModel checks the selected GGUF before Transformers reads its config. This applies to local files and Hub downloads, in both the native packed and dense import paths. Invalid tensor bounds, overlapping tensors, unexpected extra data, nonzero alignment padding, or rejected chat templates in GGUF metadata stop the load. See checkpoint artifact checks.
For ports that use NativeConfig, the Transformers config reader derives model_type from the selected GGUF's metadata. This lets a supported GGUF-only checkpoint resolve its config class without a separate config.json. See the native config loader.
internal_gguf.inspect_quantized_checkpoint(...) currently recognizes a packed native-import candidate only when:
-
general.architectureisqwen3; - the recognized attention/MLP projection tensors have exactly one common supported quantization type;
- that type maps to a registered bits alias.
It also records whether output.weight uses that type, so the loader can configure lm_head. Native name mapping additionally requires Transformers' default tensor processor. Unsupported architectures, mixed projection types, or specialized tensor processors must not be assumed to retain packed weights through this path.
For a native packed candidate, the loader creates GGUF linear modules and copies the GGUF byte rows into qweight. It verifies packed shapes, dequantizes tensors that are not being installed as packed linear weights, and checks that required quantized modules were populated. The other HF import path produces dense weights through GGUF dequantization; it is not packed GGUF inference.
| Native import case | Behavior |
|---|---|
Q1_0, profile="auto"
|
Resolves to PROFILE.FAST; the source loader uses dense HF GGUF import |
Q1_0, profile="low_memory"
|
Packed/native-loader route rather than the fast dense route |
Native Q1_0 backend validation |
Allows AUTO, GGUF_TORCH, GGUF_TRITON, MLX; rejects native C++ backend selections |
Native Q2_0
|
AUTO becomes GGUF_TORCH; explicit backend must be GGUF_TORCH or MLX
|
These are model-file loader restrictions, separate from a class's generic bit-width capability table.
The repository's Prism/Bonsai guide documents inference-only support:
from gptqmodel import GPTQModel
model = GPTQModel.load("prism-ml/Bonsai-1.7B-gguf")
# To request the packed low-memory route instead:
# model = GPTQModel.load("prism-ml/Bonsai-1.7B-gguf", profile="low_memory")
tokens = model.generate(
"Who wrote Romeo and Juliet?",
max_new_tokens=128,
)[0]
print(model.tokenizer.decode(tokens, skip_special_tokens=True))Q1_0_g128 remains a compatibility alias for the official 128-element Q1_0 layout. The HF compatibility code supplies internal runtime/Prism hooks when the installed Transformers lacks them. This does not add Prism model quantization support.
New packed GGUF safetensors exports retain method="gguf" but publish quant_method="gptqmodel_gguf". Transformers reserves gguf for its standalone .gguf loader. GPT-QModel registers no quantizer for gptqmodel_gguf, so plain Transformers treats it as an unknown method and random-initializes the linear layers; the writer's hf_compat_warnings names GPTQModel.load at save time. Load these artifacts with GPTQModel.load or a compatible external runtime, not plain Transformers. Historical native configs carrying method="gguf", quant_method="gguf" still load in GPT-QModel. This naming change does not convert a safetensors artifact to a .gguf file.
| Direction | What the implementation provides |
|---|---|
| Dense HF → GGUF blocks |
GGUFConfig plus the weight-only lifecycle and normal GPT-QModel checkpoint writer |
.gguf → HF model/runtime |
HF integration with internal GGUF reader/dequantizers; packed native import only under the restrictions above |
| GGUF byte rows → Torch dense tensor |
internal_gguf.dequantize_to_torch(...) and linear-layer dequantize_weight()
|
| GGUF byte rows → MLX | Exact packed-layout transcoding for the supported subset, not quantizing already-dequantized weights again |
| GPT-QModel GGUF checkpoint → standalone llama.cpp file |
gptqmodel.package(GGUFPackageConfig(...)) repackages eligible safetensors checkpoints |
| Packed GGUF checkpoint → dense HF directory |
utils.model_dequant.dequantize_model rejects gguf/gptqmodel_gguf with NotImplementedError; layer-level decoding does not supply a whole-checkpoint dense converter |
Do not rename a safetensors file to .gguf, assume every llama.cpp architecture has an HF mapping, or assume quality-suffix presets and packed bytes alone supply tokenizer and architecture metadata.
The native bridge uses llama.cpp's ggml libraries through ctypes; it runs linear operations inside GPT-QModel, not llama.cpp's full tokenization, KV-cache, scheduler, or generation engine.
gptqmodel.package(config) writes a single runtime container from an existing checkpoint. Its supported configuration, GGUFPackageConfig, produces a standalone llama.cpp .gguf file without re-quantizing the weights.
Install the writer dependency with pip install 'gguf>=0.19.0' or use the GGUF extra. Pass an existing local safetensors checkpoint directory whose quantization config declares quant_method="gptqmodel_gguf" or the legacy quant_method="gguf". If starting with dense HF weights, quantize and save them with GGUFConfig first.
from gptqmodel import GGUFPackageConfig, package
out = package(
GGUFPackageConfig(
model_path="Qwen3-8B-gptqmodel-gguf",
out_path="Qwen3-8B.gguf",
)
)The function returns the written path as a pathlib.Path. The writer preserves each packed GGML block byte for byte, reorders whole output rows where required, and adds architecture and tokenizer metadata. It verifies tensor names, types, and logical shapes by reading the temporary file before publishing it.
-
Model layouts. Verified dense architectures are
qwen2,qwen3, andllama. Qwen2 requires query width equal to hidden width and Q/K/V biases. Qwen3 requires Q/K norms and forbids attention biases. Both forbid output-projection and MLP biases. Llama requires attention and MLP biases exactly when its config enables them. Omitted RoPE theta uses the family default. The writer rejects MoE checkpoints, padded packed rows, and unsupported tensor, attention, or RoPE layouts. Verified architecture rules -
Tokenizer. Use a fast BPE tokenizer with byte fallback disabled. GPT-QModel loads and normalizes the tokenizer through its package loader, using local files from
model_pathby default and with checkpoint-supplied code disabled. Settokenizer_pathto load from a separate local tokenizer directory. A loadedtokenizerobject takes precedence over both paths. The output includes the tokenizer's chat template when present. Setchat_templateto override it. Tokenizer loading source -
BOS and EOS. The writer derives
tokenizer.ggml.add_bos_tokenandtokenizer.ggml.add_eos_tokenfrom the tokenizer's actual output with and without special tokens, then checks its backend post-processor for any unresolved flag. This preserves Llama 3's BOS insertion in llama.cpp. Undetermined flags are omitted so llama.cpp can use its tokenizer defaults. Tokenizer metadata source -
Dense tensors.
dense_dtype="auto"preserves the source F16, BF16, or F32 encoding for dense matrices. To select an encoding, use"f16","bf16", or"f32". Norms and one-dimensional tensors such as biases use F32. -
Generation. Supported generation settings are mapped to
general.sampling.*.do_sample=Falsewrites zero temperature. Explicit sampling entries inmetadatatake precedence. -
Existing files.
overwrite=Falseis the default and raisesFileExistsErrorat an occupied path. Setoverwrite=Trueto replace the destination. The default publication path requires a filesystem with hard-link support.
See the packaging reference for the full architecture and failure rules and the public config for advanced options.
Reload with an explicit intended backend and dtype, inspect whether the import stayed packed, then evaluate held-out quality against the dense baseline using Evaluation. profile="low_memory" is an import choice, not evidence that every architecture has a packed path. Include temporary dequantization, activations, and KV cache in your runtime-memory estimate.
A successful load does not prove parity with llama.cpp: model-file metadata, tokenizer mapping, mixed-type recipes, and arithmetic differ. Native ggml may quantize activations for its dot products; compare that error separately from the stored weight representation.
A block shares metadata across several weight codes. For example, a Q4_0 block stores 32 four-bit codes qᵢ in 0…15 plus one FP16 scale d. Its decoded weights are
The scale may be signed; it is chosen by the packer, not a universal positive absolute-maximum scale. This block takes 16 code bytes plus 2 scale bytes, so its effective rate is 8 × 18 / 32 = 4.5 bits per weight—not exactly four. That calculation excludes padding, model metadata, and unquantized tensors.
For Q4_K, a 256-weight superblock also stores quantized subblock scale/minimum metadata. Conceptually a subblock decodes as ŵᵢ = s_g qᵢ − m_g, where g identifies the subblock and s_g, m_g are reconstructed from shared metadata. Other IQ, ternary, and float4 layouts have their own decoding laws: there is no single GGUF quantization objective or number system. See the layout registry and packers and reader/dequantizers.
| Concept | Value | Purpose |
|---|---|---|
| Quantization method |
METHOD.GGUF, value "gguf"
|
Selects GGUF weight-only quantization |
| Checkpoint family |
FORMAT.GGUF, value "gguf"
|
Selects compatible loaders and linear kernels |
| Public subtype | For example, "q_0", "q_k", "q_k_m", "iq_xs"
|
Combined with bits to identify a block representation |
| Full alias | For example, "q4_0", "q4_k_m", "iq2_xs"
|
Width plus subtype, accepted in bits or format
|
| Runtime specification | GGUFBits |
Structured width/version/variant/quality representation |
| Actual tensor type | For example, Q4_0, Q4_K
|
Determines block size, byte layout, and kernel dispatch |
GGUFConfig(bits=4, format="q_k_m"), GGUFConfig(bits=4, format="q4_k_m"), and GGUFConfig(bits="q4_k_m") normalize to the same runtime specification. The public config stores an integer width and a subtype string, not a GPTQ-style integer bit width alone.
A full alias in format carries its own width: bits=4, format="q8_0" raises ValueError instead of silently resolving to q4_0. If bits also names a full alias, both fields must resolve to the same subtype, not just the same width. The same agreement rule applies to per-module GGUF overrides and to bits paired with a quantization protocol's export.variant. See GGUF config resolution.
GGUF protocol compilation accepts one MAD smoothing operation in weight.prepare. Use {method: smooth.mad, k: 2.75, group_size_threshold: 128} or {method: smoother, smooth: {type: mad, k: 2.75, group_size_threshold: 128}}. Both numeric fields are optional and default to the values shown. Unknown keys are rejected, and supplying both outer k and a nested smooth raises an error.
The dataclass fields are:
bits: int
version: str
variant: str
quality: Optional[str] = None| Field | Validation |
|---|---|
bits |
Positive integer; GGUFConfig further restricts widths to 1, 2, 3, 4, 5, 6, 8
|
version |
q, iq, tq, mxfp, nvfp
|
variant |
Empty string, 0, 1, k, xxs, xs, s, m, nl
|
quality |
None, xs, s, m, l, g128
|
Individual component validation does not establish that a combination is supported. The alias registry and GGUFConfig combination validation are authoritative.
| API | Behavior |
|---|---|
GGUFBits.from_string(value: str) -> "GGUFBits" |
Strips surrounding whitespace, lowercases, replaces hyphens with underscores, and looks up a registered full alias |
GGUFBits.from_alias(value: str) -> "GGUFBits" |
Compatibility alias for from_string
|
to_string() -> str |
Full alias such as q4_k_m
|
serialize() -> str |
Same canonical full alias |
to_public_format() -> str |
Drops the width from the prefix: q4_k_m becomes q_k_m; width-in-name formats mxfp4 and nvfp4 remain unchanged |
__repr__() |
Constructor-style debug form, for example GGUFBits('q4_k_m')
|
QuantBits = GGUFBits remains a backward-compatible alias in the configuration module.
from gptqmodel.quantization import GGUFBits, GGUFConfig
spec = GGUFBits.from_string(" Q4-K-M ")
assert spec.to_string() == "q4_k_m"
assert spec.to_public_format() == "q_k_m"
config = GGUFConfig(bits=spec)
assert config.bits == 4
assert config.format == "q_k_m"
assert config.runtime_bits == specThe GGUF-specific dataclass declarations are:
bits: Union[int, str, GGUFBits] = field(default=4, metadata={"choices": [1, 2, 3, 4, 5, 6, 8]})
format: Optional[str] = field(default=None)
method: METHOD = field(default=METHOD.GGUF, init=False)
group_size: int = field(default=-1, init=False, repr=False)
desc_act: Optional[bool] = field(default=False, init=False, repr=False)
sym: bool = field(default=True, init=False, repr=False)These are field declarations, not the complete generated constructor: GGUFConfig also inherits preprocessing and base configuration fields. See QuantizeConfig Reference and Quantization Lifecycle.
| Parameter/property | Default | Meaning |
|---|---|---|
bits |
4 |
Integer, numeric string, full alias, or GGUFBits; normalized public value is an integer |
format |
None at construction |
Resolved to a public GGUF subtype; default with four bits is q_0
|
method |
METHOD.GGUF |
Fixed; not a constructor argument |
group_size |
-1 |
Fixed; GGUF block/subblock sizes belong to the tensor layout, not a GPTQ grouping option |
desc_act |
False |
Fixed; no GPTQ activation ordering |
sym |
True |
Fixed config convention; does not imply that every GGML block is mathematically symmetric |
runtime_bits |
Derived GGUFBits
|
Used by kernel selection and packing |
uses_weight_only_lifecycle() |
True |
Packs source weights directly rather than running GPTQ Hessian optimization |
supported_export_formats() |
(FORMAT.GGUF,) |
Supported checkpoint quantization family, not a .gguf file-writer promise |
format=None, the empty string, and the family token "gguf" request the width-specific default. Full aliases in format normalize to a subtype. A full alias in bits must agree with an explicit format; incompatible combinations raise ValueError.
Integer bits
|
Default full alias | Default public format
|
|---|---|---|
| 1 | q1_0 |
q_0 |
| 2 | q2_0 |
q_0 |
| 3 | q3_k |
q_k |
| 4 | q4_0 |
q_0 |
| 5 | q5_k_m |
q_k_m |
| 6 | q6_k |
q_k |
| 8 | q8_0 |
q_0 |
Dynamic rules normalize bits and format through the same resolver. For example:
config = GGUFConfig(
bits=4,
format="q_k_m",
dynamic={
r".*\.mlp\..*": {"bits": "q5_k_m", "format": "q_k_m"},
},
)A negative dynamic rule can exclude a module. Kernel/layout validation still applies separately to each selected module. An omitted dynamic format inherits the base subtype, even when bits contains a full alias; the inherited subtype and alias must agree. When changing representations, explicitly supply both bits and format to avoid a conflict or an unintended inherited layout.
Module construction and checkpoint reload resolve the width and subtype together, not just the numeric width. For example, {"bits": 4, "format": "q4_k"} creates Q4_K, not the width-four default Q4_0. A width-only override inherits the base subtype (q3_k plus {"bits": 4} becomes Q4_K); a format-only override inherits the base width (q4_0 plus {"format": "q_k"} becomes Q4_K). This keeps reloaded mixed-type modules consistent with the layout used during quantization.
The format-aware RCO runner can choose a GGML alias per projection under a packed-weight budget. Its generated dynamic entries include both bits and format; the result remains GPT-QModel's GGUF-family packed checkpoint, not a standalone .gguf file.
to_dict() serializes the public subtype and removes group_size, desc_act, and pack_dtype. It also strips runtime-only metadata such as weight-only/offload/packing/VRAM-management settings. The config is not a dump of every runtime attribute.
The following table combines the alias registry with _GGUF_TYPE_INFO. Bytes include block metadata. Effective bits per weight are 8 * bytes / elements, not just the nominal width in the name; these values exclude model-level metadata, non-quantized tensors, and padding.
| Accepted full alias(es) | Tensor layout | Elements/block | Bytes/block | Effective bits/weight |
|---|---|---|---|---|
q1_0, q1_0_g128
|
Q1_0 / compatibility name Q1_0_g128
|
128 | 18 | 1.125 |
q2_0 |
Q2_0 |
64 | 18 | 2.25 |
q4_0 |
Q4_0 |
32 | 18 | 4.5 |
q4_1 |
Q4_1 |
32 | 20 | 5 |
q5_0 |
Q5_0 |
32 | 22 | 5.5 |
q5_1 |
Q5_1 |
32 | 24 | 6 |
q8_0 |
Q8_0 |
32 | 34 | 8.5 |
q8_1 |
Q8_1 |
32 | 36 | 9 |
q2_k, q2_k_s, q2_k_m
|
Q2_K |
256 | 84 | 2.625 |
q3_k, q3_k_s, q3_k_m, q3_k_l
|
Q3_K |
256 | 110 | 3.4375 |
q4_k, q4_k_s, q4_k_m
|
Q4_K |
256 | 144 | 4.5 |
q5_k, q5_k_s, q5_k_m
|
Q5_K |
256 | 176 | 5.5 |
q6_k |
Q6_K |
256 | 210 | 6.5625 |
q8_k |
Q8_K |
256 | 292 | 9.125 |
iq1_s |
IQ1_S |
256 | 50 | 1.5625 |
iq1_m |
IQ1_M |
256 | 56 | 1.75 |
iq2_xxs |
IQ2_XXS |
256 | 66 | 2.0625 |
iq2_xs |
IQ2_XS |
256 | 74 | 2.3125 |
iq2_s |
IQ2_S |
256 | 82 | 2.5625 |
iq3_xxs |
IQ3_XXS |
256 | 98 | 3.0625 |
iq3_s |
IQ3_S |
256 | 110 | 3.4375 |
iq4_nl |
IQ4_NL |
32 | 18 | 4.5 |
iq4_xs |
IQ4_XS |
256 | 136 | 4.25 |
tq1_0 |
TQ1_0 |
256 | 54 | 1.6875 |
tq2_0 |
TQ2_0 |
256 | 66 | 2.0625 |
mxfp4 |
MXFP4 |
32 | 17 | 4.25 |
nvfp4 |
NVFP4 |
64 | 36 | 4.5 |
Quality suffixes such as _s, _m, and _l are preserved in the bit specification but map to the same base tensor layout here. They do not, by themselves, implement llama.cpp's whole-model mixed-type quantization recipes. GGUFConfig now warns for these K-quant aliases, including dynamic overrides: for example q4_k_m stores uniform Q4_K, not the llama.cpp mixed recipe. Use explicit dynamic rules for per-module choices. q5_k_s is correctly accounted as 5.5 bits/weight (uniform Q5_K), not 5.0.
Selected layout details:
| Type | Reconstruction/storage detail |
|---|---|
Q1_0 |
FP16 scale plus 128 sign bits; local packer uses mean absolute weight for the scale |
Q2_0 |
FP16 scale plus packed two-bit codes; local quantizer uses a ternary decision at normalized ±0.5 |
Q4_0 |
FP16 scale and 16 bytes of nibbles; reconstruction uses d * (code - 8)
|
Q4_K |
256-weight superblock; FP16 bases, packed subblock scales/minima, and four-bit codes; reconstruction is scale-times-code minus minimum |
Q5_K |
Related scale/minimum layout with an additional high-bit plane |
Q6_K |
Low four-bit and high two-bit planes, signed subblock scales, and an FP16 base; codes are centered by subtracting 32 |
Q8_0 |
FP16 scale plus 32 signed INT8 values |
Q8_1 |
FP16 scale d and auxiliary scale-sum d * sum(qs) plus 32 signed INT8 values |
Q8_K |
FP32 scale, 256 signed INT8 values, and 16 signed INT16 subblock sums |
MXFP4 / NVFP4
|
GGUF float4 layouts; not aliases for arbitrary FP4 checkpoints or BitsAndBytes FP4 |
The internal enum also recognizes unquantized/raw F32, F16, BF16, F64, and integer types. Enum recognition is not evidence that a type is a supported GGUFConfig quantization target.
The bundled Q8_0 packer rounds exact halfway values away from zero (for example, ±2.5 becomes ±3), matching ggml's rounding rule when the optional gguf package is absent. GGUF packing source
For GGUF formats with FP16 header fields, the packer checks the finished bytes before returning them. It validates block scales, any stored minimum or auxiliary scale-sum, and the split FP16 scale in IQ1_M. This covers the reference gguf, built-in NumPy, native ggml, and MLX packing routes. A non-finite field raises ValueError with the format, field, and block index. If the source weights need a wider scale, use GGUFConfig(bits="q8_k") with BACKEND.GGUF_TORCH. Q8_K stores its scale in FP32. Packed-header validator
Q8_1 packing raises ValueError with the block index and field name if either header value becomes non-finite when stored as FP16. The auxiliary scale-sum can overflow even with a finite scale. For example, a block of 32 values of 3,000 produces a scale near 23.62 and a scale-sum of 96,000. If the input range is fixed, choose a compatible subtype whose stored fields cover it, such as q8_0 or q8_k for that example. Q8_1 auxiliary-field range
| Path | Source-declared requirements and boundaries |
|---|---|
| Project Python requirement | >=3.11 |
| Project Transformers dependency |
transformers>=5.23.0,<5.24 in requirements.txt at the documented revision |
| GGUF extra |
pip install 'gptqmodel[gguf]'; declares gguf>=0.19.0 for standalone packaging, Transformers integration, and the MXFP4/NVFP4 type definitions. Also declares llama-cpp-python>=0.3.37 and Python-version-specific NumPy minimums. |
| Internal reader / documented Bonsai import | Uses the bundled GGUF reader |
| Native ggml CPU |
llama-cpp-python with loadable ggml-base and ggml-cpu libraries and required symbols |
| Native ggml CUDA | Additionally needs loadable ggml-cuda, available ggml CUDA devices, and a working CUDA build; installing a CPU-only wheel does not supply this |
| GGUF Triton | Installed Triton >=2.0.0; free-threaded/GIL-disabled Python requires Triton >=3.4.0; class advertises CUDA/ROCm devices on Linux/Windows |
| Triton package extra |
pip install 'gptqmodel[triton]'; current metadata requests triton>=3.8.0 on Python <3.15, a higher floor than the kernel's import-time compatibility check |
| MLX | Apple Silicon (Darwin, arm64), available Metal, mlx and mlx_lm; gptqmodel[mlx] declares mlx>=0.32.4, and mlx_lm>=0.32.2
|
The native bridge loads ggml shared libraries from llama-cpp-python. Version 0.3.37 bundles ggml 1.0.0, which provides a stable public C API. The external gguf package is optional and can still be used by the packer when installed. See package metadata and native library binding.
The portable Torch class advertises all device/platform families, but actual operators, dtypes, and optional dequantizers must be supported by the installed stack. GGUF_TRITON now declares and validates ROCm support, using generic/autotuned launches rather than NVIDIA capability specializations. The native GGUF_CPP_CUDA class remains a separate CUDA-only path; do not infer its HIP support from the Triton backend. See Installation and Quickstart and Inference Backends.
| Component | Role |
|---|---|
gguf.py::_quantize_gguf_tensor_numpy |
Repairs simple-block FP16 underflow and validates the stored FP16 header fields before returning the bytes |
gguf.py::_pack_gguf_tensor_numpy |
Tries an available external gguf quantizer, then built-in packers, then native ggml quantization |
gguf.py::_fallback_gguf_quantize |
Built-in Q1_0/compatibility, Q2_0, Q4_0, Q5_0, Q8_0, Q4_K, Q5_K, Q6_K, TQ1_0, TQ2_0, MXFP4, Q8_1, Q8_K packing |
gguf_cpp.py::_GGMLBridge.quantize_chunk |
Uses ggml_quantize_chunk; availability depends on installed ggml types/functions |
quantization/mlx_gguf.py::gguf_quantize_weight_mlx(weight, qtype: str) |
Metal packing into GGUF bytes for its explicit supported subset |
| utils/mlx_gguf_packing.py::repack_gguf_affine(qweight, qtype, in_features) | Converts existing GGUF codes/scales/minima into an equivalent packed affine representation |
| utils/mlx_gguf_packing.py::repack_gguf_float4(qweight, qtype, in_features) | Reorders MXFP4/NVFP4 nibbles and scale bytes into native MLX layouts |
| utils/internal_gguf.py | Internal enum/size registry, memory-mapped reader, quantization/dequantization adapter, native checkpoint inspection, minimal Qwen3 name mapping |
When packing a projection with a partial final Q1_0 or Q1_0_g128 block, the Torch packer fills the synthetic weight columns with that row's mean absolute weight over the real tail columns. The stored scale therefore reflects the real columns. Inference still pads the matching activation columns with zeros. See the sign-only tail packing test.
The NumPy packing route protects small nonzero blocks in Q2_0, Q4_0, Q4_1, Q5_0, Q5_1, Q8_0, Q8_1, IQ4_NL, TQ1_0, and TQ2_0. It clamps tiny nonzero scale magnitudes to the smallest positive FP16 subnormal (2**-24) before computing codes. Q4_1 and Q5_1 apply the same rule to the offset m. If the reference gguf or native ggml packer stores zero in an underflowed field, the shared packing step rebuilds the affected block from the source weights. In-range blocks keep their original bytes.
The NumPy route also protects sign-only Q1_0 and Q1_0_g128 blocks. These formats store the mean absolute weight as the FP16 scale d, so a sparse block can round that scale to zero even when its largest weight is representable. The built-in packer clamps a tiny nonzero mean to 2**-24 before the FP16 cast. If a packer emits d = 0 for a nonzero source block, the shared packing step rebuilds its scale and sign bits from the source weights. Each element then decodes to +d or -d according to its stored bit.
If an affected nonzero source block still decodes to all zeros, packing raises ValueError with the format and block index. Choose a format with a wider stored scale, such as Q8_K. Simple-block scale underflow
The built-in Q8_K packer preserves representable subnormal FP32 scales. If the usual reciprocal overflows for a tiny nonzero block, it computes the scale directly and derives the INT8 codes from the stored scale. Blocks with finite reciprocals keep ggml-style packing.
For built-in Q4_K, Q5_K, and Q6_K packing, a positive superblock base that would round to zero is stored as the smallest positive FP16 subnormal. The packer rebuilds the affected codes against the stored base instead of losing it to underflow. Neither change alters the byte layout. See the built-in packer.
The internal reader recognizes ggml 1.0's F8_E4M3 tensor type (ID 43). It stores one byte per element. The portable dequantizer interprets those bytes as torch.float8_e4m3fn and converts them to FP32. The Torch build must expose that dtype. This describes reading existing tensors. See type registry.
Recognized types are broader than the built-in packer. In particular, the built-in NumPy fallback does not pack every IQ/K format or NVFP4. Those cases may require external gguf/native ggml, or the separately supported Metal packer. An unsupported target on the NumPy/native route ultimately raises NotImplementedError; the Metal helper rejects unsupported types with ValueError. Neither route silently changes the quantization type.
If native ggml reports that a quantizer requires an importance matrix, the bridge supplies uniform importance values. That is a valid non-activation-aware fallback, not a calibration-derived importance matrix or a claim of parity with an importance-tuned llama.cpp quantization run.
The Metal packer accepts Q1_0, Q1_0_G128, Q2_0, Q4_0, Q4_K/_S/_M, Q5_K/_S/_M, Q6_K, TQ1_0, TQ2_0, MXFP4, NVFP4, and Q8_0 (case-normalized with upper()). It requires a nonempty rank-two FP16/BF16/FP32 matrix with complete blocks and returns evaluated mx.uint8 byte rows. This low-level function rejects unaligned widths; the higher-level Torch packer can pad them first.
On Darwin arm64 with mlx.core importable, GGUFTorchLinear._pack_weight_tensor(...) automatically selects this Metal packer when the padded weight has at least 2 * 1024 * 1024 elements. Smaller weights use the NumPy/native route. The dispatch does not first filter by tensor type and does not catch an unsupported-Metal-type error to retry another packer. Thus an alias accepted by GGUFConfig can still fail during large-layer packing on Apple Silicon even if an external/native quantizer could handle it elsewhere. Metal packing availability and exact MLX inference transfer support are separate checks.
GGUFReader(path, mode="r") memory-maps the file, validates magic 0x46554747, accepts file versions 2 and 3, reads scalar/string/array metadata, and exposes ReaderTensor byte/data views. Default alignment is 32 bytes; an explicit general.alignment must be a nonzero power of two. Duplicate fields/tensor names and rows not divisible by the quantization block size are rejected. GGUF_VERSION is 3. install_runtime() registers this module as gguf for the HF adapter; it is not the complete external package or a writer.
| Object | Shape/layout |
|---|---|
GGUFTorchLinear.qweight |
torch.uint8 rows: (out_features, padded_in_features // gguf_block_size * gguf_type_size)
|
GGUFTorchLinear.dequantize_weight(...) |
Contiguous (in_features, out_features) matrix, with input padding removed; this is the orientation for x @ weight, not nn.Linear.weight
|
internal_gguf.dequantize_to_torch(...) |
Reconstructs the supplied tensor data without the linear wrapper's final transpose or input-width crop |
The source signatures are:
Developer API signatures (not a runnable example)
# GGUFTorchLinear
def dequantize_weight(
self,
*,
device: torch.device | str | None = None,
dtype: torch.dtype | None = None,
) -> torch.Tensor:
...
# gptqmodel.utils.internal_gguf
def dequantize_to_torch(
data: np.ndarray,
qtype: GGMLQuantizationType,
*,
device: torch.device | str | None = None,
dtype: torch.dtype = torch.float32,
) -> torch.Tensor:
...The internal helper defaults to CPU/FP32. The linear wrapper resolves its target from the requested device/dtype and module state; on CPU it reconstructs in FP32 before the final output cast. These helpers explicitly materialize dense values for a consumer; calling one does not change the checkpoint into a dense model or authorize retaining an expanded inference cache.
| Backend enum / string | Class | Scope and restrictions |
|---|---|---|
GGUF_TORCH / gguf_torch
|
GGUFTorchLinear |
General GGUF reference/fallback; uint8 packed weights; optional chunked paths; advertises all devices/platforms |
GGUF_CPP_CPU / gguf_cpp_cpu
|
GGUFCppKernel |
CPU; uses native ggml for supported weight layouts, with a Torch fallback and an explicit override |
GGUF_CPP_CUDA / gguf_cpp_cuda
|
GGUFCudaKernel |
CUDA ggml graph/plan execution; requires matching native libraries; rejects Q8_1, Q8_K, TQ1_0, and TQ2_0
|
GGUF_TRITON / gguf_triton
|
GGUFTritonKernel |
CUDA/ROCm; only Q1_0/compatibility, Q4_K, Q5_K, Q6_K
|
MLX / mlx
|
GGUFMlxQuantLinear checkpoint holder; MlxGGUFLinear / MlxGGUFQ6KLinear runtime |
Apple Silicon/Metal; exact packed transfer subset and alignment constraints |
The Torch, C++ CPU/CUDA, and Triton classes accept FP16, BF16, and FP32 activations in their declarations. This does not imply identical internal precision: Triton converts non-FP16 activations to FP16 before computation, then restores the interface dtype. Biased Triton calls keep an FP32 output through bias addition; wide K-quant weights can also select FP32 reconstruction/dot products. See the arithmetic details below rather than inferring full BF16/FP32 compute from the returned dtype.
| Class | Advertised training support | Advertised adapters |
|---|---|---|
GGUFTorchLinear |
True |
Lora |
GGUFCppKernel, GGUFCudaKernel
|
False |
Lora |
GGUFTritonKernel |
False |
Lora |
GGUFMlxQuantLinear |
False |
None |
These declarations describe kernel validation contracts, not a general promise that every GGUF format supports every training workflow.
GGUFTorchLinear rounds input width up to the tensor block size, stores weights as byte rows, and pads activations for computation. Its portable forward reconstructs weights for the consuming matmul. Chunked fused paths reconstruct bounded blocks and accumulate their contributions rather than requiring a persistent dense weight cache. The packed input and its scale/index metadata may persist; a dequantized full-weight cache is not the intended storage model.
Fused Torch GGUF accumulation and its bias epilogue use FP32 before the final activation-dtype cast. CPU fused paths reconstruct chunks in FP32. Both chunked execution and the dense fallback reconstruct weights in FP32 for all BF16 qtypes, not only K-quants, to avoid premature weight rounding before cancellation.
Bias retains its source dtype at packing; empty load slots start in FP32. The shared model loader keeps GGUF bias in FP32 for FP16/BF16 checkpoint loads. CPU dense fallback with FP16/BF16 input and bias reconstructs and multiplies in FP32, disabling CPU autocast for the dot product so BF16 rounding cannot happen before a cancelling bias. Bias is added before the single output cast.
For FP16 activations, Q2_0, Q4_0, Q8_0, Q8_K, Q4_K, Q5_K, and Q6_K use packed scale/code bounds to decide when reconstruction must widen; other non-sign-only formats reconstruct in FP32 conservatively. Sign-only formats retain their ordinary FP16 route. Wide fallback keeps activation conversion, matmul, and bias inside the FP32 computation before restoring the input dtype. Q6_K combines integer code/scale factors before floating scaling to preserve zero codes and avoid intermediate range loss. These changes protect intermediate arithmetic, not outputs whose true values exceed the requested dtype's range. See the dense fallback precision guide.
Q8_K also widens when a sufficiently small FP32 scale and nonzero stored codes could lose weight information in FP16. This preserves small contributions that only become representable after the matmul; the final output still uses the activation dtype.
The K-scale overflow cache follows the packed qweight identity/version rather than a temporary blocks view and supports inference-created tensors without a version counter. Ordinary in-place updates or replacement invalidate its answers. After manually mutating an inference-mode tensor in place, call clear_weight_cache(). Fused inference is bypassed when gradients are enabled and the activation requires a gradient, even in evaluation mode; the differentiable dequantize/matmul path remains operation-local.
For explicit CUDA graph capture with GGUFTorchLinear, warm up the layer on its target device before capture. The layer supports capture for Q4_0, Q8_0, Q4_K, Q5_K, and Q6_K. The three K-quants reuse device-resident shift tables built during warmup, avoiding host-to-device copies inside the graph. Warm up again after clearing the weight cache. The other qtypes, including Q2_K and Q3_K, use host dequantization and cannot be captured. Query layer.supports_graph_capture() for the loaded qtype. Kernel capture declarations
The native GGUFCppKernel and GGUFCudaKernel report graph capture as unsupported for every qtype, including qtypes capturable through the Torch backend.
The Torch backend declares EAGER by default and INDUCTOR on CPU. Its CPU q4_k_m forward reaches Inductor in the CPU compile probe. This is separate from eager CUDA capture and does not enable automatic static-cache compilation. The native ggml backends still declare EAGER.
The default fused chunk plan is byte-budgeted rather than a fixed eight blocks: KernelConfig.gguf_fused_chunk_blocks=0 selects chunks using KernelConfig.gguf_fused_chunk_bytes (32 MiB). It budgets out_features * chunk_K * sizeof(float32), with at least one complete block; ordinary layers fitting the budget use a single chunk. A positive block count overrides the byte budget. This is a transient reconstructed-weight chunk target, not a cap on total process memory, activations, outputs, or all temporary allocations.
Torch fused dispatch uses static CPU/CUDA row and matrix-size gates, with no timing search or cached timing winner. It requires a quantized tensor type, no adapter, evaluation mode, and no enabled activation gradient. The fused route is selected when flattened rows are within the device's positive max_rows ceiling and in_features * out_features meets its minimum; setting that ceiling to zero disables it. Other calls use temporary dequantization plus matmul. This keeps the arithmetic independent of unrelated process load: the fused and dense reductions need not be bitwise identical. See static fused dispatch.
Performance still depends on rows, matrix widths, dtype, quantization type, threading, and installed kernels. Use scripts/benchmark_gguf_fused_thresholds.py for offline timing and output-drift comparisons before changing the gates.
GGUFCppKernel bypasses native CPU ggml matmul for a call when autograd is enabled and the activation requires gradients. The differentiable Torch path handles that call; later eligible no-grad calls can still use ggml. This is not native ggml backward support. See the CPU dispatch.
CPU native ggml quantized dot-product/SIMD paths can quantize the activation operand to a Q8 dot-product representation. This adds activation quantization error beyond GGUF weight quantization. Native ggml output therefore need not match x @ dequantized_weight.T with floating activations, even for identical packed weights. Treat that arithmetic difference separately from packer/dequantizer correctness; report weight-only reference error separately from native activation-quantized error. The actual SIMD implementation depends on the installed llama.cpp build and host hardware.
The native activation formats are Q8_0/Q8_1 for legacy layouts and Q8_K for K-quant layouts. GGML_NATIVE_MATMUL_ERROR_BOUND = 2e-2 remains a Gaussian-input regression tolerance, not an activation-independent error bound. That campaign measured roughly 4.9e-3..7.9e-3 relative L2 error on CPU and a worst CUDA case of 1.5e-2 against an exactly dequantized-weight FP64 oracle. The outlier-channel reproduction (16 of 4096 channels scaled by 100) reached roughly 3.3e-2..3.8e-2 relative error and 7.6e-2..8.4e-2 worst-row error on CPU. A Q8 block's shared scale and output cancellation prevent a universal relative-output bound. CUDA FP32/BF16 paths can add low-precision accumulation error. Choose BACKEND.GGUF_TORCH for floating-activation FP32 arithmetic matching the dequantized-weight reference to FP32 rounding, subject to the final output cast. See the activation-quantization evidence and path rule.
GGUFCppKernel now chooses native CPU matmul by capability rather than timing native and Torch on first use. Supported layouts default to native; if execution fails, the call falls back to Torch and remembers the failure for that (rows, dtype, qtype) key. An explicit native override bypasses that remembered choice but cannot enable excluded layouts. KernelConfig.gguf_cpp_native_matmul=False selects the Torch arithmetic path within this backend; choose BACKEND.GGUF_TORCH for an explicit weight-only backend. Native activation-Q8 arithmetic remains different from the floating-activation reference, so changing dispatch is a numerical choice as well as a performance choice.
GGUFCudaKernel returns an empty (..., out_features) tensor for zero flattened activation rows, including (0, K), (B, 0, K), and (0, S, K). It takes this path before device validation, packed-weight upload, or plan-cache construction, preserving input device/dtype and avoiding GGML plan has no scratch tensors for an unused MoE expert or empty batch slice. Nonempty calls retain the CUDA device requirement. See the CUDA forward.
For model loading, backend=GGUFCPPConfig(native_matmul=False) selects floating-activation CPU arithmetic within the C++ backend; import the class from gptqmodel.backend. native_matmul=True requests native arithmetic and None retains capability-based selection. For an individual CPU layer, GGUFCppKernel(..., exact_matmul=True) forces the floating-activation Torch path; False requests native, and None (default) defers to the layer's KernelConfig.gguf_cpp_native_matmul snapshot. The explicit constructor argument takes precedence, but neither control can enable excluded layouts. This is static configuration, not activation-value/outlier detection.
Q8_1 and Q8_K are special safety cases. They are valid stored layouts with built-in packing/dequantization, but upstream ggml does not expose the corresponding safe weight quantizers/vec-dot kernels used by this bridge. Native quantization excludes both to avoid GGML_ASSERT aborts. The native CPU matmul entry point rejects both to avoid missing-function-pointer failures, and the CPU dispatcher returns Torch even if native matmul is forced.
AUTO selection checks the concrete GGML tensor type, not only numeric bit width: a Q4_0 or Q5_0 request cannot select the fused Triton kernel merely because it is 4- or 5-bit. Quantization finalization retries compatible AUTO candidates per module, including mixed-layout dynamic overrides. Explicit BACKEND.GGUF_TRITON requests with unsupported layouts fail during selection instead of silently changing backend. Q5_0 also has a built-in NumPy pack/dequant path rather than requiring llama-cpp-python for that layout. See the selection and fallback contract.
The CUDA ggml backend rejects Q8_1, Q8_K, TQ1_0, and TQ2_0 at layer construction and again before graph creation, raising NotImplementedError rather than allowing a native process abort. AUTO can retry the Torch candidate after the construction-time rejection; explicitly choose BACKEND.GGUF_TORCH for these weights. This is a qtype restriction, not a blanket rejection of all 1/2-bit GGUF formats. The CPU backend supports TQ1_0/TQ2_0; its exclusion set is only Q8_1/Q8_K.
The internal gguf compatibility shim only registers when no real gguf package is installed or already loaded; it does not replace that package's architecture support. See the shim registration.
The native CPU bridge can wrap contiguous, nonempty, 32-byte-aligned CPU UINT8 packed weights directly instead of copying the entire packed matrix into a ggml buffer on every call. GGUFCppKernel.post_init() aligns an unaligned packed checkpoint view once. Missing optional pointer-wrapping symbols, an unsuitable buffer, or backend rejection uses the copied-weight bridge path. Activations, outputs, and graph scratch still need storage; this optimization does not change the native activation-Q8 arithmetic or make inference allocation-free. See CPU weight ownership.
Bridge initialization is locked; CPU execution also locks shared mutable ggml graph scratch. CUDA backend initialization, native forward/plan-cache operations, packed-weight replacement, cache clearing, and cleanup serialize under one process-wide reentrant lock, shared across every layer and CUDA device. ggml-cuda shares cuBLAS handles and memory pools across devices, so different GPUs cannot safely enter this bridge concurrently. Multi-GPU placement remains available, but native ggml-CUDA calls within a process serialize.
Each CUDA layer keeps one ggml packed-weight allocation shared across its batch-size/dtype execution plans. When qweight is on the execution device, the layer adopts a zero-copy Torch view of that same allocation rather than retaining a second Torch copy. state_dict(), saving, and the corrective bias epilogue read the same packed bytes; external views keep their backing allocation alive. Replacement or movement closes old plans before dropping the old weight owner. clear_weight_cache() closes plans but preserves an adopted allocation that is still the live qweight storage; in-place state loading already updates those shared bytes. No dense weight cache is retained.
Plan activations, outputs, and intermediates use offsets in one shared scratch arena per CUDA device rather than retaining separate backend buffers for every layer and row count. The arena grows for the largest plan; its generation invalidates stale plans before reuse. The arena is freed when the last native GGUF CUDA weight on that device is released, and the next forward that needs it allocates it again. Retained weights, including live zero-copy views, can keep the arena alive. This scratch is separate from packed-weight storage and Torch's allocator. CUDA BF16 input is converted to FP16 for the ggml operand. See shared scratch lifetime.
Both C++ wrappers finish bias before rounding to the caller dtype. On CPU, FP32 ggml output receives bias directly; if ggml returned FP16/BF16 and bias is present, the wrapper recomputes that biased case using temporary FP32-decoded weights and a wide matmul with autocast disabled, then casts once. On CUDA, every biased native call takes that corrective branch, even when ggml returned FP32: the native product can already have overflowed or lost cancellation precision before the bias. That corrective branch is no longer the native activation-Q8 dot arithmetic described above and can cost an extra computation. The CPU Torch fallback receives bias inside its own epilogue; native-versus-Torch timing no longer chooses the arithmetic path. Unbiased native execution remains unchanged. See the C++ bias epilogue.
The native-output correction rule depends only on device type, whether bias exists, and the native product dtype. It does not inspect activation values or call order. A zero-valued but present bias follows the same rule; on CPU with FP32 native output it does not by itself force an exact recomputation.
On Linux, if CPU alignment requires copying an unaligned file-backed packed tensor, the bridge can advise away whole clean source pages inside that tensor with MADV_DONTNEED after the copy. This lowers duplicate resident checkpoint memory without changing file contents or invalidating another holder's view: it can re-fault the pages. Heap/anonymous storage, private copy-on-write or swapped pages, and partial boundary pages are not discarded; unavailable mapping/page information leaves them alone. Already aligned mmap weights stay zero-copy. See mmap residency.
Triton fuses packed code decoding with matmul for the explicitly supported types and uses FP32 accumulators. Activation handling depends on the input dtype and whether bias is present:
| Input / bias | Computation and output |
|---|---|
| FP16, with or without bias | Ordinary fused route. Range-sensitive Q4_K/Q5_K/Q6_K metadata widens before weight reconstruction, selecting IEEE FP32 dot products when decoded weights could exceed FP16 range. Biased output stays FP32 through bias addition, then casts once to FP16. |
| BF16 or FP32, no bias | Normalize each activation row before FP16 staging, using a power-of-two scale for oversized rows and lifting tiny nonzero rows out of the FP16 underflow range. Store the dot output in FP32, restore the row scale in FP32, then cast to the original input dtype. |
| BF16 or FP32, with bias | Keep activations in FP32 and use IEEE FP32 dots; K-quant scale/minimum metadata also stays FP32 through weight reconstruction. Add bias before restoring the input dtype, avoiding a narrow weight reconstruction before a cancelling bias. |
Row scaling protects against converting a whole finite row to infinities or zeros; it does not make the unbiased FP16-staged route an exact FP32 GEMM. No route can represent a final result outside the requested output dtype. Empty activation batches and direct zero-row/zero-output-width launch helpers return correctly shaped empty outputs without launching a kernel. See the activation-range guide for the two wide-input paths and recorded device checks.
GGUFTritonKernel declares explicit CUDA graph capture for all five qtypes it can load: Q1_0, Q1_0_g128, Q4_K, Q5_K, and Q6_K. Unlike the Torch backend, it cannot load Q4_0 or Q8_0. Check layer.supports_graph_capture() on the loaded layer and warm up its inference path on the target device before capture, including after clearing the weight cache. Eager capture does not enable automatic static-cache compilation. See the capture and replay tests.
A newly built Triton cache records its producing stream and a readiness event. Outside graph capture, reuse from another stream waits while the build is incomplete and records the cached tensors on the consuming stream. It uses a snapshot of the tensor references taken when the cache was built, so another thread retiring the readiness event cannot invalidate the iteration. Calls on the builder stream use normal stream ordering. Once any stream observes completion, it removes the readiness event and the builder-stream reference; later forwards do no stream bookkeeping for cache readiness. After a warm forward, explicit torch.cuda.graph capture relies on graph startup synchronization and clears the readiness state without querying or waiting on the external event. This adds no dense weight cache. See cache readiness and capture coverage.
A concurrent cold start builds each Triton cache entry once per module. Callers that need the same entry reuse the first builder's published copy, keeping the packed metadata alive on consumer streams. Cache clearing coordinates with builds, and warm lookups after event retirement use the published entry directly. See the packed cache concurrency contract.
Caches retain compact derived scale/minimum metadata, not a dense floating matrix. The first cache build transposes packed storage once and exposes qweight with the same logical values through a transposed view. Packed code views for Q4_K, Q5_K, and Q6_K then read consecutive output features coalesced without keeping a second resident weight copy. The relayout temporarily needs one layer's extra packed buffer. state_dict() emits canonical contiguous GGUF bytes; checkpoint loading restores canonical storage before the next cache build. Ordinary FP16 metadata costs 32 bytes per 256-weight block, about 22%, 18%, or 15% of each format's packed bytes respectively. A wide-dot path or the scale-range guard selects FP32 cache metadata, doubling that metadata cost. Q1_0 sign bytes also remain views, while its SM80 specialization may retain derived UINT32 sign words. See the packed-cache memory contract and runtime layout implementation.
Before publishing that transposed qweight view, the first packed-weight relayout is serialized under a process-wide lock and, outside graph capture, waits for the calling CUDA/HIP stream's copy to finish. This protects concurrent cold builds from deriving persistent metadata from unfinished packed bytes, which could otherwise corrupt later outputs or produce NaNs. The host-side stream wait applies to the one-time relayout, not steady-state forwards; warm graph capture still follows the event rules above. See the publication order and cross-stream regression coverage.
Caches refresh on ordinary qweight mutation, replacement, checkpoint load, or device/dtype application; call clear_weight_cache() after unversioned inference-tensor mutation. Q1_0 has shape/capability-specific launch choices for CUDA capabilities (8, 0) and (8, 9), including packed-word and K=2048 decode specializations. Q4_K/Q5_K/Q6_K also have fixed SM 8.9 launches for selected decode and mid/prefill row bands; nonmatching shapes retain the autotuned path. On ROCm, CUDA capability probing returns None, so none of the SM80/SM89 choices apply. The ROCm class is eligible for AUTO at priority 45 (Torch is 15), subject to normal qtype/dtype/availability checks; BACKEND.GGUF_TORCH remains an explicit alternative. These specializations are not a claim that every GPU or shape has the same performance.
Exact transfer supports Q1_0/compatibility, Q2_0, Q4_0, Q8_0, Q4_K, Q5_K, Q6_K, TQ1_0, TQ2_0, MXFP4, and NVFP4. The holder requires 32-aligned input width, output width divisible by eight, complete unpadded source blocks, and no adapter. Its loader dtype declaration is FP16; runtime wrappers preserve the input activation dtype, including FP16/BF16 operation where supported.
| Source layout | MLX representation |
|---|---|
Q1_0 |
Two-bit packed affine codes, group 128, scale 2*d, bias -d
|
Q2_0 |
Two-bit affine, group 64 |
Q4_0 |
Four-bit affine, group 32, bias -8*d
|
Q8_0 |
Eight-bit affine after signed-to-unsigned code shift, group 32 |
Q4_K, Q5_K
|
Packed affine codes with group-32 scales/minima |
Q6_K |
Exact group-16 affine representation and a dedicated packed Metal execution option |
TQ1_0, TQ2_0
|
Two-bit affine representation with group-128 scales |
MXFP4, NVFP4
|
Native MLX float4 modes; groups 32 and 16 respectively |
MlxGGUFQ6KLinear uses a packed Q6_K kernel for decode and selected small BF16 prefill cases, and MlxGroup16Linear for other cases. MlxGGUFLinear wraps the general quantized linear and restores activation output dtype. Unsupported layouts or padding are not silently requantized to another type.
| Control | Default / effect |
|---|---|
KernelConfig.gguf_cpp_threads |
None: snapshot torch.get_num_threads() at module construction; explicit positive integer controls native CPU thread count |
KernelConfig.gguf_cpp_native_matmul |
None: capability-based native selection with remembered execution failures; False: Torch; True: request native except excluded types |
KernelConfig.gguf_fused_cuda_max_rows |
32 |
KernelConfig.gguf_fused_cuda_min_matrix_elements |
8388608 |
KernelConfig.gguf_fused_cpu_max_rows |
64 |
KernelConfig.gguf_fused_cpu_min_matrix_elements |
0 |
KernelConfig.gguf_fused_chunk_blocks |
0, must be non-negative; zero selects byte-budgeted chunks, positive values override the block count |
KernelConfig.gguf_fused_chunk_bytes |
33554432 bytes (32 MiB), must be positive; automatic chunk sizing still uses at least one complete block |
gguf_native_quantized_loader (RuntimeConfig / KernelConfig) |
True; permit native packed-checkpoint detection |
gguf_dequant_device (RuntimeConfig / KernelConfig) |
None; optional Torch cpu or cuda[:INDEX] conversion target. Invalid devices are rejected; unavailable accelerator targets raise when resolved |
gguf_dequant_chunk_bytes (RuntimeConfig / KernelConfig) |
268435456 bytes (256 MiB); positive integer FP32-output budget for a sign-only NumPy-facing conversion chunk, with at least one row. Not a total load-memory cap |
Prefer backend=GGUFTorchConfig(...), GGUFCPPConfig(...), or GGUFCUDAConfig(...) for model loading. GGUFCUDAConfig() has no tuning fields: all its matmuls use ggml-cuda, so Torch fused-forward gates do not apply. For the Torch/CPU configs, fused option names omit the gguf_ prefix (for example, fused_chunk_bytes=32 * 1024 * 1024); GGUFCPPConfig additionally exposes native_matmul=None and threads=None. Do not confuse these execution configs with quantization's GGUFConfig. Legacy kernel=... remains accepted with enum/string selectors; see typed configurations.
The former gguf_fused_autotune_warmup, gguf_fused_autotune_iters, and gguf_fused_autotune_margin fields, including their prefix-free typed equivalents, have been removed. GGUFTorchLinear.AUTOTUNE is False; changing autotune_enabled no longer changes this dispatch. Use the remaining row/matrix-size gates to select the crossover.
All GGUF modules snapshot their policy at construction, including native-matmul and CPU thread choices. At execution the C++ bridge sets the selected module's thread count while holding its shared CPU-backend lock; loading another model does not overwrite the first module's settings. These are API settings, not environment variables; see policy lifetime. None of these controls widens format or architecture coverage.
Pass the three load-policy fields above through runtime=RuntimeConfig(...) or the legacy kernel=KernelConfig(...) or mapping. Set gguf_native_quantized_loader=False to use Transformers' dense importer. The direct-to-Torch dense importer was removed. gguf_dequant_device and gguf_dequant_chunk_bytes control GPT-QModel's internal conversion, and Transformers' dense importer uses its own path.
The retired GPTQMODEL_INTERNAL_GGUF_QUANTIZED_LOADER, GPTQMODEL_INTERNAL_GGUF_TORCH_LOADER, GPTQMODEL_INTERNAL_GGUF_DEQUANT_DEVICE, and GPTQMODEL_INTERNAL_GGUF_DEQUANT_MAX_BYTES variables have no effect; each present name warns once with its replacement or removal. See the checkpoint load policy and HF import boundary.
Common mistakes:
- Selecting a backend by nominal width while ignoring the exact tensor type.
- Assuming a successfully parsed alias guarantees a built-in packer, native kernel, or packed model-file importer.
- Treating
group_size=-1as a single GGUF block spanning the entire row. - Comparing native activation-Q8 arithmetic to a floating-activation weight-only oracle without separating the errors.
- Expecting MLX to accept padded GGUF rows merely because Torch can pad them.
- Expecting
Q1_0default fast loading to have the same memory footprint as explicit low-memory packed loading. - Expecting dequantization to recover pre-quantization HF weights; it only reconstructs the stored quantized values.
Paths below are relative to the repository and link to the documented revision.
| Source | Responsibility |
|---|---|
| gptqmodel/quantization/config.py | Enums, aliases, GGUFBits, config normalization and serialization |
| gptqmodel/utils/backend.py | Backend and profile enums |
| gptqmodel/utils/internal_gguf.py | Internal reader, types, dequantization, native checkpoint inspection |
| gptqmodel/utils/mlx_gguf_packing.py | Exact MLX packed transcodes |
| gptqmodel/quantization/mlx_gguf.py | Metal GGUF packers |
| gptqmodel/nn_modules/qlinear/gguf.py | Layout registry, pack/dequantize logic, Torch linear |
| gptqmodel/nn_modules/qlinear/gguf_cpp.py | Native ggml SIMD/dequantization and CPU/CUDA graph execution |
| gptqmodel/nn_modules/qlinear/gguf_triton.py | Fused Triton inference |
| gptqmodel/nn_modules/qlinear/mlx_gguf.py | MLX runtime wrappers and packed Q6_K kernel |
| gptqmodel/nn_modules/qlinear/mlx.py | MLX source-layout capability validation |
| gptqmodel/utils/hf.py | Artifact discovery, public argument handling, Transformers compatibility |
| gptqmodel/models/loader.py | Native packed import, profiles, tensor mapping |
| gptqmodel/models/auto.py | Public load/export entry points |
| gptqmodel/utils/model_dequant.py | Checkpoint-based dense HF export and supported stored layouts |
| docs/prism-bonsai-gguf.md | Prism inference and Q1_0 compatibility |
| pyproject.toml, requirements.txt | Optional extras and dependency floors |
Documentation home · Quickstart · Troubleshooting · Repository · PyPI
Public source 775013e41 declares package version 7.14.0. Individual pages identify their source revisions. Choose a method · Dtypes and formats. Maintained by ModelCloud.ai.
🧭 1 · Choose and understand
🚀 2 · Use it
- Installation and Quickstart
- Loading and Inference
- LeapQuant recurrent-state quantization
- Evaluation
- Serving
- Troubleshooting and FAQ
- Memory, Offload, Multi-GPU
- MLX / Apple Silicon
- Tenstorrent / Block Floats
- Hugging Face Integration
- Multimodal and MoE Models
🎛️ Methods and representations
Each guide: choose → examples → math / advanced
- GPTQ / GPTAQ / G2PTQ / ADMM-Q / RTN
- SINQ
- JointQ
- AWQ
- QQQ
- MACaQ / MXFP4
- EXL3
- CPTC
- VPTQ
- Tetra
- TWLA
- Paro
- FP8 and NVFP4
- NF12: lossless BF16 storage
- GGUF families
- BitsAndBytes: NF4 / FP4 / INT8
🧰 Refinement and execution
- GSQ refinement / allocation
- EoRA adapters
- Rotation, Smoothing, Norm Tuning
- Projection Fusion
- TurboQuant KV cache
🧠 3 · Theory and advanced reference