Repository navigation
Model Definitions and Module Tree
🏠 Home · 🧭 Choose a method · 🚀 Quickstart · 🧰 Help
On this page
- 🧭 Start with the plan, then the implementation
- Current module-plan guide
- Overview
- Workflow at a glance
- Concepts
- Traversal and derived plans
- Shared-input metadata and Hessian reuse
- Loading and dispatch
- Device and module constants
- Saving and checkpoint preservation
- Usage and adding an architecture
- Granite SWA definitions
- OLMo Hybrid definition
- Registry reference
- Pitfalls and edge cases
- Source files
- See also
Learn how GPT-QModel maps checkpoint architectures to explicit weight-owning module declarations. This page is for contributors adding an architecture and readers debugging a missing, incorrectly grouped, or wrongly quantized module.
| Reading depth | Read | Use it to… |
|---|---|---|
| Choose / understand | Current module-plan guide and Overview | Separate wrapper, tree, plan, and live modules |
| Practical usage | Inspect a plan and adding an architecture | Find the owning declaration and its required tests |
| Theory / advanced | Traversal and derived plans, loading, and saving | Understand consumers and lifecycle boundaries |
Before you start: obtain the GPT-QModel wrapper, not just the underlying Transformers model, and identify the checkpoint's model_type. Registry membership is not whole-checkpoint coverage. Decoder declarations include checkpoint-owned non-quantized weights; embeddings, vision towers, and auxiliary modules outside decoder regions need separate auditing.
The retained reference cites the implementation it was written against. Compare version-sensitive behavior with the target source and module-plan tests.
Next: use Module Plans for API recipes and tags, or Supported Models for registry lookup.
Module Plans: API, Tags, and New Models documents the explicit module-plan implementation merged in PR #3565, including model.module_plan(), terminal/JSON output, all tags, checkpoint-owned weight coverage, and the required registry plus real-model tests. DeepSeek V4.1 Flash provides a verified checkpoint inventory and its support limits.
The reference below includes the merged module-plan implementation: normal loading requires an explicit definition or injected tree, and model.module_plan() exposes the selected instance's decoder-relative inventory. Declarations include non-quantized checkpoint-owned decoder weights, while runtime-created caches are outside that obligation.
Projection Fusion, introduced in PR #3567, consumes the same plan for opt-in post-quantization QKV and gate/up execution. BaseQModel.fusable defaults to None: a matching, validated FusableConfig is required. plan = model.fuse() applies execution and returns an inspectable planner; model.fuse(False) restores separate execution. The qualification matrix, native backend contracts, dynamic-setting checks, and runtime skip reasons are separate from ordinary model support.
A model definition tells GPT-QModel how a Hugging Face model is organized, which modules may be quantized, the order in which their activations must be collected, and which model-specific loading and replay hooks are necessary. Definitions are Python subclasses of BaseQModel in gptqmodel/models/definitions/; MODEL_MAP in gptqmodel/models/auto.py selects one using the checkpoint configuration's model_type.
This page describes the source at revision ab7e28314164be048a34f93b79cd9a2388fa77ef. Architecture names and Transformers layouts change between releases; inspect the definition shipped with the installed GPT-QModel version, not just a checkpoint's marketing name.
The current declaration is named module_tree. There is no BaseQModel.layers_modules_tree declaration in this revision. Similarly, “base modules” and “layer modules” describe computed plans: use get_base_modules(), build_layer_modules(), simple_layer_modules(), and full_layer_modules(), rather than assigning old base_modules or layer_modules lists.
Reading the diagram: The lanes are separate views of one definition. A full-plan entry is not automatically a quantization target; skipped weights remain dense.
Text version of the workflow
- Quantization target view: Select definition → Resolve effective tree → Build simple plan → Process target subsets.
- Capture and planning view: Use the same tree → Build full plan → Prepare capture.
BaseQModel subclasses torch.nn.Module, owns the underlying Transformers model as self.model, and delegates unresolved attributes to that model through __getattr__. forward() delegates to the wrapped model unless a definition overrides it. The class is decorated at the bottom of base.py by factory functions, not Python mixin inheritance:
BaseQModel = ModelLoader(ModelWriter(BaseQModel))ModelLoader installs from_pretrained() and from_quantized(); ModelWriter installs saving methods. GPTQModel itself is a dispatch facade: GPTQModel() raises an error. Load a model using its class methods.
def __init__(
self,
model: PreTrainedModel,
quantized: bool,
quantize_config: Optional[BaseQuantizeConfig],
tokenizer: Optional[PreTrainedTokenizerBase] = None,
qlinear_kernel: nn.Module = None,
load_quantized_model: bool = False,
trust_remote_code: bool = False,
model_local_path: str = None,
turtle_model: Optional[LazyTurtle] = None,
effective_module_tree: Optional[Any] = None,
):Source: gptqmodel/models/base.py.
Important definition attributes and their base-class defaults:
| Attribute | Base default | Contract |
|---|---|---|
module_tree |
None |
Root path, layer-container delimiter, and layer-relative module mapping; may contain multiple complete variants. |
module_tree_overrides |
None |
Mapping from METHOD to a tree override applied for that quantization method. |
lm_head |
"lm_head" |
Output-head path. Quantizing the head is separately controlled by the quantization configuration. |
pre_lm_head_norm_module |
None |
Final normalization applied to cached inputs before head quantization; a path string or ordered list of alternative paths. A nonempty declaration that cannot be resolved raises ValueError. |
rotary_embedding |
None |
Optional architecture-specific rotary embedding path. |
layer_modules_strict |
True |
Require planned modules to exist; heterogeneous/optional-layer definitions may set False. Unresolved quantization specs are tracked across layers and reported at run exit. |
awq_scale_optimize_shape_dependent_modules |
None |
Optional module names whose AWQ scale search needs architecture-specific shape handling. |
awq_preserve_explicit_position_embeddings |
False |
Opt-in preservation of explicit position embeddings for AWQ. |
shared_input_verified_model_types |
empty frozenset
|
Model types whose explicit input-sharing declarations are verified; not inherited for verification purposes. |
loader |
AutoModelForCausalLM |
HF auto-loader used to construct/load the architecture. |
defuser_generic_experts |
False |
Native Kimi-Linear and MiMo-V2-Flash opt into generic expert defusion when no Defuser registry entry expands their fused 3-D expert weights. |
require_pkgs |
None |
Package/version requirements checked by check_versions(). |
require_dtype |
None |
Override automatic/user dtype selection when required by the definition. |
require_fast_init |
True |
Passed as _fast_init during source-model loading. |
require_load_processor |
False |
Load and retain an AutoProcessor on the wrapper. |
require_load_tokenizer |
True |
Load the tokenizer on source and quantized loads; definitions without the attribute also take the text path. Decision Transformer sets False and retains tokenizer=None. |
calibration_inputs |
"token_ids" |
Shared preparation input contract: token/text normalization by default, or "tensor_kwargs" for already-batched named tensors. Unknown values raise ValueError. |
CAPTURE_DERIVE_POSITION_IDS |
None |
Auto-detect whether capture should supply 2-D text positions from a compatible mask. Use False to leave positions to the model or True to allow derivation when automatic detection cannot see the capability. Explicit input positions are preserved. |
require_monkeypatch |
False |
Invoke the definition's monkey_patch() during wrapper initialization. |
dynamic_expert_index |
None |
Config attribute containing the fallback expert count. |
dynamic_expert_indices |
None |
Layer-relative expert-prefix to config-field mapping for multiple expert families. |
supported_dense_vram_strategies, supported_moe_vram_strategies
|
[VramStrategy.EXCLUSIVE, VramStrategy.BALANCED] |
Supported placement strategies. |
support_batch_quantize |
True |
Setting False makes quantization force batch_size=1. |
write_shared_kv_cache |
False |
Let a layer publish KV state needed by later replay layers. |
support_offload_to_disk |
True |
Definitions can disable the lazy/offloaded source path. |
supports_desc_act |
[True, False] |
Allowed activation-order settings; a definition can restrict them. |
info |
{} |
Definition notes; the loader prints an optional "notes" entry. |
modality |
[MODALITY.TEXT] |
Metadata, not the quantization target selector. |
ATTENTION_MASKS_DTYPE |
torch.bool |
Calibration mask dtype; e.g. Omni adapters use integer masks. |
ATTENTION_MASKS_REQUIRED_FOR_INPUT |
False |
Require masks during input capture. |
INPUT_EMBEDDING_EXTRA_ARGS |
None |
When truthy, the base capture hook calls model.generate() with these extra arguments instead of model(..., use_cache=...). |
modules_with_direct_meta_tensors |
[] |
Paths owning direct meta parameters/buffers, materialized outside normal traversal. direct_meta_modules=[] is the compatibility alias. |
HF_CONVERSION_MAP_REVERSED |
None |
Runtime-to-checkpoint renaming/conversion rules for lazy materialization. |
hf_conversion_model_type_alias |
None |
Reuse another model type's inferred HF conversion rules. |
defuser_module_paths |
None |
Explicit nested roots to defuse when experts do not live at the top-level model root. |
turtle_materialize_tie_weights |
True |
Whether ordinary turtle materialization re-ties weights. |
out_of_model_tensors |
None |
Extra checkpoint files or tensor prefixes to preserve on save. |
quant_override_files |
{} |
Definition-specific files written after quantized save. |
This is the actual Llama declaration from definitions/llama.py:
module_tree = [
"model",
"layers",
"#",
{
"input_layernorm": ("input_layernorm:!:norm",),
"self_attn": ("q_proj:0:q:in=x", "k_proj:0:k:in=x", "v_proj:0:v:in=x", "o_proj:1:o"),
"post_attention_layernorm": ("post_attention_layernorm:!:norm",),
"mlp": ("gate_proj:0:gate:in=x", "up_proj:0:up:in=x", "down_proj:1:down"),
}
]The prefix before the top-level "#" identifies the repeated decoder layer container, here model.layers. The mapping after it contains paths relative to one decoder layer. Insertion order and subset markers describe forward execution/calibration ordering. Do not alphabetically sort a definition.
| Syntax | Meaning | Example / caution |
|---|---|---|
Top-level "#"
|
Separates root/layer-container path from the layer mapping. |
["model", "layers", "#", {...}]. |
| Nested dictionaries | Extend a relative module path. |
{"mlp": {"experts": {...}}}. |
| Leaf tuple/list | Ordered child module specifications. |
"self_attn": ("q_proj:0", "o_proj:1"). |
:<integer> |
Subset/group identifier; first flag satisfying str.isdigit() is used, default 0. |
q_proj:0, k_proj:0, v_proj:0 share a calculation block; o_proj:1 follows. Numeric groups are scoped/offset by nesting, not global layer IDs. |
:! |
Keep a non-quantized entry in the full plan. | Norms, routers, selected convolutions. It is filtered from the simple quantization plan. |
:? |
Capture-only entry; not a quantized weight target. |
mlp:moe:? lets capture/scaling inspect a parent MoE input. Parent inclusion is opt-in via include_capture_only=True. |
:moe |
Mark a MoE root/family for lifecycle discovery. |
mlp:moe. It does not itself enumerate or quantize experts. |
:norm |
Identify a norm eligible for the separate norm-tuning path. |
input_layernorm:!:norm; linear quantization still excludes it. |
:postnorm |
A norm that executes after a linear and must not become its AWQ predecessor. | Post-projection Q/K norms remain plan-owned but are excluded as scale sources. |
:nosrc |
A norm or projection that must not supply an AWQ scale source. | Keep its declared weight ownership and quantization policy while disabling unsafe folds across residual, activation, convolution, or mixed-state computation. |
:q, :k, :v, :o, :gate, :up, :down
|
Explicit projection roles for module-plan consumers. |
query:0:q works without the name q_proj; kv_b_proj:0:k:v has two roles. Explicit roles override conventional leaf-name roles. |
:in=<tag> |
Assert sibling modules consume identical activations. |
gate_proj:0:in=x, up_proj:0:in=x; not implied by numeric grouping. |
runtime|checkpoint |
Ordered aliases; first name is the runtime shell path. | Mixtral's mlp|block_sparse_moe and gate_proj|w1. Later names assist checkpoint lookup, not extra quantization targets. |
Nested "#"
|
Expert-index placeholder. |
"experts": {"#": (...)} becomes experts.{expert_index}.*, then concrete expert paths. |
Empty nested key ""
|
Use the current parent path without adding a segment. | Supports dense and sparse MLP alternatives in the same tree. |
AWQ source declarations must follow native producer/consumer relationships. Matching widths or observing every declared target during replay does not establish that the source produced those inputs or that all consumers were declared. Current definitions use :nosrc for unsafe sources in Falcon Mamba, MOSS, Qwen, Gemma3n, AXK2/GLM DSA, LongCat Flash, and Inkling, while preserving supported plain quantization. Shared consumers in CohereCompass and GraniteMoE SWA are grouped together; a replay boundary that covers only part of that group uses configured fallback, or raises with fallback=None. Intentional no-group policies remain plain quantization even when fallback is disabled. Bloom also checks its live residual mode before enabling norm folds. See AWQ scaling and architecture policies and the source relationship guide.
Leaf names that repeat the parent's final component refer to the parent itself; e.g. "input_layernorm": ("input_layernorm:!",) does not produce input_layernorm.input_layernorm. Subset offsets advance past the largest resolved nested group rather than summing nested widths; producer-before-consumer ordering is preserved across shallow nested dictionaries. See ordering contract.
Flags on a dictionary parent describe that parent entry; they are not recursive exclusions of all descendants. For example, "mlp:moe:?" can capture the MoE input while its explicitly declared expert projections remain quantizable. Mark individual router/norm leaves :! when those weights must stay dense.
module_tree can be a list of complete trees, as in Mllama's current model.language_model.layers and legacy language_model.model.layers layouts. extract_layers_node() returns each distinct layer-container path in first-seen order. build_layer_modules() combines variants and deduplicates identical blocks without changing their order.
_resolve_effective_module_tree() first deep-copies an explicitly injected model.gptqmodel_effective_module_tree, falling back to the class declaration, then applies a method override when present. It does not invoke autodetection. apply_module_tree_override() merges on a copy, never the class-owned tree. Initialization freezes the result recursively into effective_module_tree, keeps self.module_tree as its compatibility alias, and compiles one ModulePlan. Mutating the effective mapping raises TypeError; repeated model.module_plan() calls return the same plan.
ModulePlan.find() accepts only declared decoder-relative paths or concrete numeric indices at declared expert placeholders, not arbitrary prefix/suffix matches or tensor names. Explicit projection flags take precedence; otherwise conventional declared leaf names such as q_proj, w1, w3, and w2 provide roles. A live module's name alone does not add it to the plan. See the tag reference for the complete role vocabulary and matching rules.
Class-level planning calls use the static declaration; calls through an instance use its selected tree. __getattribute__ wraps the tree-sensitive class methods in a ContextVar binding, and the quantized loader uses _module_tree_context() while planning before wrapper construction. One instance's method override must not affect another model instance.
The current definitions repair decoder coverage without adding new MODEL_MAP aliases:
| Model/layout | Corrected declaration or conversion |
|---|---|
| Voxtral | Decoder layers resolve under model.language_model.layers, not language_model.model.layers. |
| Ling/Bailing | The bundled port covers the hybrid self_attn and attention branches. Ling-2.6-flash adds q_a_proj, kv_a_proj_with_mqa, g_proj, q_b_proj, and kv_b_proj alongside query_key_value/dense. |
| Llama 4 | Interleaved dense MLP gate/up/down projections are covered alongside routed/shared experts; the text wrapper uses top-level lm_head. |
| Gemma 4 text/composite MoE | Generic expert conversion expands fused experts; routed projections are declared, while router/scales and MoE norms stay explicitly unquantized. Dense variants treat absent expert counts as zero. |
| Nemotron-H / Nemotron Omni MoE | Both definitions share NEMOTRON_H_LAYER_MODULES, mounted at model.layers and language_model.model.layers respectively. n_routed_experts drives expert expansion; shared and routed up/down projections are declared, with latent-MoE fc1_latent_proj before the experts and fc2_latent_proj afterward. The top-k router and SSM convolution remain explicitly non-quantized. |
| DeepSeek-V2 | When top-k probability normalization is enabled for multiple experts, the router normalizes the selected probabilities before applying routed_scaling_factor. See the router implementation. |
| DeepSeek-VL2 | Non-MLA (use_mla=False, including tiny) attention declares k_proj and v_proj alongside q_proj/o_proj; MLA retains its low-rank projection path. |
| Qwen4-Exp text/composite | Optional ple, attn_hyper_connection, and mlp_hyper_connection subtrees carry explicit :! exclusions so their checkpoint-owned transforms remain dense. |
| Remote-code Phi-3 longrope |
after_defuser_conversion() splits a remaining Phi3MLP.gate_up_proj into gate/up linears when native Defuser class matching did not apply. |
| Native GLM-4V |
after_defuser_conversion() also splits a remaining Glm4vTextMLP.gate_up_proj. It preserves weight/bias dtype and device, binds the split gate/up/down forward, and removes the fused linear before strict plan resolution. Already-split modules are unchanged; malformed widths are not guessed into a valid plan. This is a layout repair, not a new AWQ qualification claim. |
| Zamba / Zamba2 | Shared transformer subtrees remain explicitly excluded (shared_transf:! / shared_transformer:!), not silently omitted from coverage. |
Checkpoint-owned short convolutions are explicitly retained for hybrid Bailing, Falcon-H1, Jamba, native Kimi-Linear, Nemotron-H, and Zamba-family layouts; Jamba's dt_proj and GRIN-MoE's router gate are retained too. Final norm paths are declared for Falcon-H1, HRM-Text, Nemotron-H, PhiMoE, and Zamba/Zamba2. These are plan/coverage corrections, not evidence that every listed layout has completed AWQ safety qualification.
Ling-2.6-flash uses attention.* even with model_type="bailing_hybrid". In that branch, query_key_value, q_a_proj, kv_a_proj_with_mqa, and g_proj are subset 0; q_b_proj/kv_b_proj are subset 1; dense is subset 2. The checkpoint-owned query_layernorm, key_layernorm, g_norm, q_a_layernorm, and kv_a_layernorm remain explicitly unquantized (:!). layer_modules_strict=False resolves the projections each layer actually owns. The bundled port uses the checkpoint config to select the layout. See the Bailing definition, and MLA coverage tests.
Nemotron Omni previously had a mixer-only declaration that omitted routed/shared experts, the router, and the SSM convolution; quantization could report success while undeclared expert weights stayed in BF16. The shared declaration covers those leaves in both wrappers. Dense, shared-expert, and routed-expert up_proj entries carry :nosrc: their down_proj(relu2(up_proj(x))) computation cannot fold an output scale through the squared-ReLU activation. Nemotron-H's native MoE mixer skips scale folding. Its other mixer types can use the generic planner. See the AWQ policies. See the shared declaration and Nemotron plan/fold tests.
When Nemotron Omni materializes a layer lazily, its checkpoint mapping resolves the bundled model's language_model.model.* paths to the original language_model.backbone.* tensor names. See the checkpoint mapping.
Sequential quantization follows producer/consumer order. DeepSeek-VL2 and each LongCat Flash MLA block place q_a/kv_a before q_b/kv_b, then o_proj; LongCat's two sub-blocks run in self_attn.0 → mlps.0 → self_attn.1 → mlps.1 order. Bailing and native Kimi-Linear put o_proj after their latent/gated attention producers. LFM2-MoE convolution separates in_proj from the later out_proj, and Nemotron-H/Omni separates SSM in_proj from out_proj. These ordering and leaf-coverage fixes do not establish new AWQ scale-fold relationships. See the subset-order regressions and additional leaf coverage.
The registry leaf-coverage test inventories supported module leaves and direct 2-D/3-D expert owners in actual meta-model layouts after conversion, rather than checking only paths already declared in the tree. Exact plan hits or explicit :!/:? ancestor exclusions satisfy this test; uncovered leaves or zero resolved decoder layers fail. Remote-only configs may skip with a reason, so a skipped registry case is not real-checkpoint validation. See leaf coverage and Phi-3 conversion and its model-specific regression cases.
The shared resolver normalizes pre_lm_head_norm_module to an ordered, deduplicated list of nonempty strings (tuples are accepted too). Exact get_submodule() matches take precedence across all candidates; prefix matching is attempted only if no exact candidate resolves. The head-input hook uses the first resolved module, and norm-tuning discovery uses the same resolver. None leaves the final norm unset; invalid declarations raise TypeError, and an unresolved nonempty declaration raises rather than silently skipping the norm or passing None into pre_quantize().
Definitions accommodate these text-decoder layouts:
| Definition | Ordered final-norm candidates |
|---|---|
| Qwen3-VL base |
model.language_model.norm, language_model.norm, model.norm, norm
|
| Mistral3, GLM4V, Voxtral |
model.language_model.norm, model.norm
|
| Ovis2 |
model.language_model.norm, model.language_model.model.norm
|
| GLM-ASR |
language_model.norm, language_model.model.norm
|
| Ernie 4.5 VL MoE |
model.language_model.norm, language_model.norm, model.norm
|
See tests/test_pre_lm_head_norm_resolution.py for layout regressions. These candidates do not change which vision/audio towers are quantized.
@classmethod
def full_layer_modules(cls, model_config=None, is_awq_quantize: bool = False, include_capture_only: bool = False):Source: gptqmodel/models/base.py.
@classmethod
def simple_layer_modules(cls, model_config, quantize_config, is_awq_quantize: bool = False, include_capture_only: bool = False):Source: gptqmodel/models/base.py.
@classmethod
def shared_input_plan(
cls,
model_config=None,
quantize_config=None,
is_awq_quantize: bool = False,
) -> SharedInputPlan:Source: gptqmodel/models/base.py.
| API | Result and purpose |
|---|---|
module_plan() |
Inspect the instance's compiled ModulePlan: declared owners, projection roles, MoE/expert membership, terminal rendering, and JSON export. This is distinct from the expanded subset and shared-input plans below. |
extract_layers_node() |
List of candidate repeated-layer paths. Definitions may override it for HF layout alternatives. |
build_layer_modules(tree, include_capture_only=False) |
Ordered layer-relative blocks with non-quantized markers preserved; expert templates are not expanded here. |
full_layer_modules(model_config=None, is_awq_quantize=False, include_capture_only=False) |
Build blocks and expand expert indices if config/cardinality are available; retain non-quantized entries. MoE expansion handles capture-only blocks specially, as described below. Used by scaling/capture/planning. |
simple_layer_modules(model_config, quantize_config, is_awq_quantize=False, include_capture_only=False) |
Build/expand, remove :!/:? entries and empty blocks, then remove modules excluded by dynamic matching. This is the quantizable plan. |
get_base_modules(model) |
Walk ancestor roots before the layer container, collecting sibling child modules while excluding every declared continuation path. Returns module paths, not module objects. |
get_modules_with_direct_meta_tensors(model) |
Return configured module paths and automatically detect module-tree prefixes that directly own meta parameters or buffers. get_direct_meta_modules() delegates here. |
generate_layers_modules_tree_simple(node) |
Produce a simplified display/helper representation; not the authoritative quantization planner. |
get_moe_modules() / get_moe_module_name()
|
Discover :moe paths / layer-level MoE-root names. |
get_norm_modules() |
Collect :norm metadata for the norm-tuning machinery. |
For Llama, simple_layer_modules() yields these relative calculation blocks:
[
["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"],
["self_attn.o_proj"],
["mlp.gate_proj", "mlp.up_proj"],
["mlp.down_proj"],
]The full plan additionally retains input_layernorm:! and post_attention_layernorm:! blocks. get_base_modules() is about non-layer siblings needed for execution/materialization; being a base module does not mean it is quantized. Custom multimodal definitions often extend/replace this method to include vision towers/projectors outside the language-model ancestry.
This recursive helper removes parsed flags from strings and keys, choosing the first alias. For a dictionary value that is a tuple/list of strings, it drops that parent entry if every child has ! or ?. If only some children are flagged, it keeps the block and strips flags from all its children; it does not selectively remove the skipped child. It does not expand experts, resolve dynamic rules, check a live model, or construct execution subsets. Its top-level list recursion tests list, whereas the effective runtime tree is frozen to tuples: use a mutable tree copy when requesting this presentation form. Do not use its output to decide which weights to replace.
build_moe_modules_if_need() expands {expert_index} when a definition supplies dynamic_expert_index and a model config is present. The fallback count comes from text_config, otherwise thinker_config.text_config, otherwise ffn_config when it declares the requested count field, otherwise the root config. This covers converted DBRX's nested ffn_config.moe_num_experts without shadowing another architecture's top-level count. dynamic_expert_indices can select a count by the longest matching expert prefix; absent/malformed mapped fields fall back to the legacy count.
A present non-scalar count, such as a per-modality list, resolves to None: unresolved expert placeholders remain in the plan and produce a warning/coverage miss, rather than crashing range() or guessing one family's count. The looper leaves routing override disabled when the model-wide count is unresolved. A missing legacy count attribute still raises AttributeError.
ERNIE 4.5 VL MoE declares dynamic_expert_index="moe_num_experts", expanding both mlp.text_moe.experts and mlp.vision_moe.experts. Its non-strict tree permits dense/sparse layer variants, while explicit gate:! and moe_statics:! leaves preserve both modality routers and their score-correction bias. Converted DBRX expands ffn.experts.mlp and explicitly excludes norm_attn_norm.norm_1, norm_attn_norm.norm_2, and ffn.router.layer. See model-specific expert coverage.
Non-AWQ expansion is projection-major within a block: all expert gate_proj paths, then all up_proj paths, etc. Entries without {expert_index} are emitted once, even in a mixed expert/shared/dense block, not repeated per routed expert. AWQ expansion preserves non-expert segments in forward order and expands expert segments expert-major where family cardinalities match. During MoE expansion, an all-capture-only block is removed from its original position (leaving an empty block); AWQ may attach its entries to a qualifying expert input block. Therefore, include_capture_only=True does not guarantee that a MoE parent remains in its own block in the full plan. Do not independently reorder shared experts and routed experts: replay depends on the declared order.
LayerModuleCoverageTracker records per-spec hit/miss layer sets in both the calibration and weight-only loopers. Quantization and EoRA-generation entry points report coverage in finally, including exceptional exits. A spec with zero matches produces a Quantization coverage warning that it was NOT quantized; numeric path segments normalize to .# so expanded experts share one report entry. Specs present in only some layers produce an informational hybrid/optional summary, with per-spec counts at DEBUG level. This is a module-resolution diagnostic, not proof that every routed expert received calibration tokens or that an interrupted run completed. Strict definitions still raise on a missing module; intentionally excluded/capture-only entries belong in :!/:? declarations rather than stale quantization specs.
gptqmodel/models/shared_input.py derives immutable LeafSpec, SharedInputGroup, and SharedInputPlan objects. GPTQ Hessian collection depends on input activations, so verified modules consuming the same input can avoid duplicate collection.
- The default is one group per quantizable module. A common numeric subset is not proof of shared input.
-
:in=xshares only among leaves with the same immediate parent and tag.self_attn:in=xandmlp:in=xremain independent; each expanded expert has its own parent. - Non-quantized and capture-only leaves do not join groups.
- A leaf repeated across tree variants must have identical subset/input/skip metadata; conflicts raise
ValueError. - The concrete definition must list the checkpoint's
model_typein its ownshared_input_verified_model_types. Inheriting a Llama tree or mapping another alias to Llama does not automatically enable reuse for that alias. - Metadata may span subsets, but runtime deduplication is within a subset: each subset elects its own leader.
dedup_followers/dedup_countreflect only same-subset reuse.
probe_shared_inputs(layer, plan, forward) installs pre-hooks, copies captured tensors to CPU, runs the supplied forward under inference mode, removes hooks, and checks call counts, shape, dtype, and exact tensor equality. Its report distinguishes mismatches, unverified groups, undeclared sharing, and missing_modules. ok is a strict alias of fully_verified, not “no mismatch among the experts that happened to run.” Cover unrouted experts deliberately before declaring a model type verified. See tests/module_tree/test_shared_input_cpu_forward.py for the real-forward verification gate.
RicursiveQModel registers model_type="ricursive" for Ripple and uses package-owned config, modeling and tokenizer classes. Its model.layers.# tree includes attention q/k/v/g/o projections, per-head Q/K norms, four decoder norms (input, post-attention, pre-feedforward, post-feedforward), and MLP gate/up/down projections. Norm leaves remain non-quantized full-plan entries tagged for separate norm tuning (:!:norm), not packed linear targets. Full versus sliding attention does not change the quantization target set.
Attention q/k/g declare in=x; v does not. With value residuals enabled, v_proj consumes a blend of the first-layer and current hidden states, so sharing its Hessian with q/k/g would be incorrect. As for any definition, declarations alone do not enable shared-input reuse without the verification allowlist.
The port uses the Transformers 5.23 cache and mask APIs for full and sliding attention. output_attentions=True computes diagnostic attention probabilities separately and keeps SDPA's output for the forward pass. See the Ripple implementation.
mlp_chunk_size is a Ripple model config field with a default of 2048 rows. Set it to zero to disable MLP row chunking. For unlabeled calls, a positive logits_to_keep limits how many trailing hidden states reach the LM head. Labeled calls compute the full causal-LM loss and trim only the returned logits. See the Ripple config and local-port tests.
@classmethod
def load(
cls,
model_id_or_path: Optional[str],
quantize_config: Optional[QuantizeConfig | Dict] = None,
device_map: Optional[Union[str, Dict[str, Union[str, int]]]] = None,
device: Optional[Union[str, torch.device]] = None,
backend: Union[str, 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,
**kwargs,
):Source: gptqmodel/models/auto.py.
load() normalizes model IDs/GGUF references, config dictionaries, backend/profile values, and trust settings. It checks supported embedded quantization metadata or quantization config files to choose source-model versus quantized loading. With a new quantization config, recognized native FP8/NVFP4 sources are treated as inputs for new quantization rather than automatically as finished inference checkpoints. Remote-adapter options are rejected on the source-model branch.
| Entry point | Use |
|---|---|
GPTQModel.load(...) |
Automatic source/quantized dispatch. A dictionary quantize_config is converted to QuantizeConfig. |
GPTQModel.from_pretrained(model_id_or_path, quantize_config, backend=BACKEND.AUTO, profile=PROFILE.AUTO, trust_remote_code=False, p2p=None, **model_init_kwargs) |
Select a definition and prepare a source model; already-supported quantized configurations may redirect to from_quantized(). |
GPTQModel.from_quantized(model_id_or_path, device_map=None, device=None, backend=BACKEND.AUTO, adapter=None, trust_remote_code=False, allow_remote_adapter=False, adapter_revision=None, adapter_sha256=None, p2p=None, **kwargs) |
Select a definition and load a quantized checkpoint/runtime. |
check_and_get_model_definition(model_dir, trust_remote_code=False, **config_load_kwargs) |
Use load_model_config to select the config class, then resolve model_type case-insensitively. Unknown types fall back to BaseQModel. |
The table abbreviates type annotations; the copied load() declaration above is the complete public dispatch signature. Do not confuse its device and device_map arguments with quantization worker pools.
gptqmodel/models/loader.py resolves/downloads the local model path, loads and normalizes HF config, registers Defuser fused-block replacements, chooses dtype/device, loads the tokenizer through the HF/Tokenicer integration, and checks definition requirements. Its source-loader entry point calls torch._dynamo.disable() because quantization is not intended to run through Dynamo/compiled graph capture. A user attn_implementation other than "auto" is propagated to nested configs by the attention override helper.
With a quantization config, the source model is prepared on CPU (or as a meta shell), not eagerly placed on the quantization accelerator. Set QuantizeConfig.device for quantization; passing a separate loader device or device_map while that field is set raises AttributeError.
offload_to_disk=True is the config default; offload_to_disk_path=None is replaced by a managed temporary directory when needed. The lazy path builds a shell with build_shell_model(), converts fused structures through Defuser, and calls LazyTurtle.maybe_create() with the tree, runtime/checkpoint mapping, config, and target shell. LazyTurtle lives in gptqmodel/utils/structure.py, not a lazy_turtle.py module.
The checkpoint source retains an index rather than constructing a second full dense CPU model. It reads requested tensors from local safetensors shards; supported pickle checkpoint extensions (.bin, .pt, .pth, .ckpt) are converted once into temporary safetensors. maybe_create() requires a local directory and returns None if construction fails; the offload loader treats a missing lazy source as an error.
The quantization offload loader warns once per process when one checkpoint shard spans multiple layers, because those layers cause repeated shard reads. This is advisory, not an inference-load restriction. Use gptqmodel.reshard() to produce per-layer safetensors while preserving tensor payload bytes.
shell_module_materialize() serializes access with the wrapper's RLock, supports an explicit module_path, and delegates ordinary materialization to the turtle alias helpers. The turtle uses runtime/checkpoint aliases and reversed HF conversion rules, handles requested subtrees, honors placement exclusions, and can re-tie weights. Modules owning direct meta tensors have a separate materialization entry point. The loader also detects bare parameters and buffers on decoder-tree prefixes, such as Hymba's model.memory_tokens, so lazy calibration can materialize them before the first forward. Native encoded sources also have distinct forward and quantization-source decoding paths; do not copy packed source bytes into dense shell parameters.
Definitions with support_offload_to_disk=False disable this path. A recognized meta-shell build failure can fall back to direct CPU HF loading without a turtle; unrelated runtime errors propagate. MiMo mixed sources explicitly reject that fallback because it cannot preserve their source layout. Without a quantization config, the loader uses the ordinary HF loading branch (with device_map or "auto"), subject to native GGUF/profile redirects.
The quantized path restores the checkpoint quantization config, validates backend/format/device compatibility, creates an HF architecture, defuses where needed, and resolves the effective tree before planning replacements. It finds all candidate modules, excludes base modules and ordinary heads, matches declared layer-relative simple-plan paths rather than arbitrary suffixes, and consults should_quantize_module(). Quantized embedding endpoints and explicitly quantized heads have separate handling. The checkpoint is then loaded into the appropriate runtime modules and wrapped with quantized=True.
External runtimes and specialized formats branch within this loader; the tree does not guarantee a particular inference kernel. See Loading and Inference, Inference Backends, and Kernel Backends Reference.
An unregistered model_type selects BaseQModel, but no longer gains a tree inferred from live module names. If neither a class declaration nor an explicitly injected gptqmodel_effective_module_tree supplies a tree, normal loading raises ValueError stating that no explicit module_tree is registered. Add and test a definition rather than relying on the old AutoCompat behavior.
BaseQModel._auto_detect_module_tree() remains a diagnostic helper, not a fallback called by _resolve_effective_module_tree(). It cannot establish checkpoint ownership, heterogeneous-layer coverage, safe sharing, router exclusions, replay kwargs, or modality boundaries. Follow Add and validate a new model.
Path lookup is also boundary-aware: get_module_by_name_prefix() and get_module_by_name_suffix() prefer exact paths, then accept only dotted descendants/suffixes. More than one fallback match raises ValueError, rather than selecting whichever module was registered first; mlp_extra is not a match for the prefix mlp.
gptqmodel/models/_const.py supplies shared device-family identifiers, not a per-kernel compatibility matrix:
| Enum | Members and serialized values |
|---|---|
DEVICE |
ALL="all", CPU="cpu", CUDA="cuda", XPU="xpu", NPU="npu", MPS="mps", ROCM="rocm". |
PLATFORM |
ALL="all", LINUX="linux", WIN32="win32", DARWIN="darwin". |
| Constant / helper | Contract |
|---|---|
CPU, META
|
torch.device("cpu"), torch.device("meta"). Meta represents a shell without materialized tensor storage. |
CUDA, CUDA_0, XPU, XPU_0, MPS
|
Devices cuda, cuda:0, xpu, xpu:0, and mps. |
NPU, NPU_0
|
Try npu/npu:0; fall back to CPU if Torch cannot construct the device. This does not make CPU an actual NPU. |
ROCM |
torch.device("cuda:0"); PyTorch HIP shares the CUDA device namespace. |
SUPPORTS_MODULE_TYPES |
[nn.Embedding, nn.Linear, nn.Conv1d, nn.Conv2d, transformers.Conv1D]; individual algorithms/kernels apply further restrictions. |
EXPERT_INDEX_PLACEHOLDER |
"{expert_index}". |
DEFAULT_MAX_SHARD_SIZE |
"4GB". |
DEVICE.type, DEVICE.index
|
ROCm reports type "cuda"; CUDA/ROCm/XPU/NPU have default index 0, other enum members return None. |
DEVICE.to_torch_device() |
Make a concrete device using that type/default index. ALL is a selector, not a concrete Torch device to materialize. |
DEVICE.to_device_map() |
Return {"": self}, substituting DEVICE.CUDA for ROCm. |
normalize_device(type_value) |
Normalize a string, enum, integer, or torch.device to a device family, discarding a string's explicit index. Integer input selects the available family in CUDA/XPU/NPU/MPS/CPU order; it is not a preserved device ordinal. |
get_best_device(backend=BACKEND.AUTO) |
Choose CUDA_0, XPU_0, NPU_0, MPS, then CPU by availability. The function does not choose an inference kernel. |
For backend-specific CUDA architecture, ROCm, operating-system, and dtype limitations, use Kernel Backends Reference. The ordinary architecture/loader path here is Torch-based. The Apple Silicon GPTQModel.quantize_mlx() entry point in auto.py instead lazily delegates to gptqmodel.quantization.mlx_native.quantize_mlx; that implementation loads/saves through mlx_lm.utils and selects native MLX GPTQ or MLX-LM AWQ without constructing this Torch wrapper.
def save(
self,
save_dir: str,
safetensors_metadata: Optional[Dict[str, str]] = None,
max_shard_size: Optional[Union[int, str]] = DEFAULT_MAX_SHARD_SIZE,
meta_quantizer: Optional[str] = None,
eora_path: Optional[str] = None,
split_by: Optional[str] = None,
**kwargs,
):Source: gptqmodel/models/base.py.
save() dispatches on self.quantized. Ordinary quantized models use save_quantized(); a model flagged _model_free_weight_only_replacements_only uses save_quantized_embeddings(). Unquantized wrappers delegate to the underlying Transformers model's save_pretrained().
save() parameter |
Default | Behavior |
|---|---|---|
save_dir |
Required | Output directory, created by the quantized writer. |
safetensors_metadata |
None |
Dictionary whose keys/values are normalized to strings; writer sets format="pt". |
max_shard_size |
"4GB" |
Integer bytes or size string; KB/MB/GB/TB/PB are decimal, KiB/MiB/GiB/TiB/PiB and bare K/M/G/T/P are binary. None disables the size limit. |
meta_quantizer |
None |
Optional additional name:version quantizer fingerprint; invalid formats are warned about. |
eora_path |
None |
Optional adapter output override; otherwise the configured adapter path is used. |
split_by |
None |
Only ordinary safetensors output is enabled in this revision. Empty/"none" strings normalize to None; "layer" and all other modes raise ValueError. |
The default maximum shard size is DEFAULT_MAX_SHARD_SIZE = "4GB". Size-based sharding is separate from layer splitting. Although writer.py contains a layer-grouped streaming implementation, SUPPORTED_SPLIT_BY = {None} disables that mode in this revision. The parser's error message still mentions 'layer'; it does not reflect the enabled set. The specialized free-weight-only writer has a narrower option set than the ordinary quantized writer.
For a layer-wise layout, first save an ordinary safetensors checkpoint, then call the separate reshard() API. Its default PER_LAYER_WITH_SINGLE_GLOBAL layout does not enable split_by="layer" in this writer.
The quantized save flow in writer.py:
- Require
self.quantized, normalizeout_of_model_tensors, and collect extra prefix tensors as sources. - Save
quant_log.csvwhen logs are present, record quantizer/config metadata, and derive the export configuration. Already-loaded quantized models can be reconstructed into a save-compatible representation; EXL3 has dedicated tensor-storage handling. - Attach
config.quantization_config, save model/generation configuration using an empty state dictionary, and savequantize_config.json. Runtime attention implementation fields are temporarily stripped and restored. Dynamic rule order is preserved in the serialized model config. - For shell/turtle models, restore remaining meta layers/parameters from the source while avoiding overwriting quantized modules with their original dense weights. Gather a state dictionary that can read offloaded storage.
- Stream ordinary safetensors shards, write an index when multiple files are produced, and clean stale ordinary weight files. Layer-grouped output is currently disabled by the split-mode parser. Kernels without shard support disable the requested sharding. Metadata values are normalized to strings and
format="pt"is set. - Save EoRA adapters if configured; copy requested passthrough tensor files; copy remote Python files when trusted remote code is in use; save tokenizer and then processor.
-
BaseQModel.save()writes definition-levelquant_override_filesafter the quantized writer returns.
The processor is intentionally saved after the tokenizer, because its multimodal chat template must not be overwritten by a text-only tokenizer template. Extra tensor prefixes are merged into the main weight stream/index; explicitly copied safetensors files are copied without modifying that index. Use prefixes when tensors must participate in the indexed model weights.
The wrapper's save_pretrained() makes the same writer selection and warns when it redirects a quantized model. The module-replacement writer preserves packed endpoints and writes live generation settings for generative models rather than only copying the source checkpoint's generation configuration.
Inkling 2 Mini rebuilds a skipped layer's packed expert container from its original payload. Every leaf must have the same quantization signature, including format, bit width, block size, and storage dtypes. Re-quantized layers stay per projection. A mixed layer is rejected before any re-fusion tensor is created. See the checkpoint re-fusion contract.
For eligible lazy EXL3 sources, the writer can publish packed replacements alongside untouched native checkpoint entries under their original names, without materializing the rest of the shell. It validates a unique authoritative source mapping (or an explicit fused-replacement contract), removes the complete replaced native module prefix including obsolete scales, and checks packed tensor census and native/packed collisions. Ambiguous conversion mappings do not silently opt into passthrough. Source shards must remain readable through export.
The writer scopes native passthrough to the loaded model. It keeps entries whose owning module exists or whose source key resolves from a runtime parameter or persistent buffer through checkpoint aliases. This can omit layers above a reduced num_hidden_layers and uninstantiated next-token heads from the source index. Retained entries keep their original bytes and dtype. If ownership cannot be determined, all passthrough candidates are kept. See passthrough ownership scope.
Definition-owned save-state overlays support disjoint auxiliary state such as MTP modules. Prefix/suffix/removal declarations and tensor-storage coverage are validated before combining state; overlays are not permission to overwrite unrelated checkpoint entries. out_of_model_tensors selectors now support prefixes, suffixes and exact tensor names. Every selected tensor declared by the source safetensors index must be readable; a missing/corrupt shard raises instead of silently dropping indexed multimodal/MTP state. Absent optional prefixes remain optional.
The GLM-5.3 (Glm5NextQModel) checkpoint-only MTP layer also declares enorm, hnorm, eh_proj, and shared_head.norm as non-quantized owners. These source-representation envelope tensors must survive export even though they are absent from target layers; the non-strict tree permits that difference. See GLM MTP ownership.
Source: gptqmodel/models/writer.py. See native model replay boundaries.
from types import SimpleNamespace
from gptqmodel import QuantizeConfig
from gptqmodel.models.auto import MODEL_MAP
definition = MODEL_MAP["llama"]
print(definition.extract_layers_node())
print(definition.simple_layer_modules(
SimpleNamespace(model_type="llama"), QuantizeConfig(bits=4, group_size=128)
))- Inspect the actual HF configuration, runtime module names, checkpoint keys, and forward implementation. Identify every repeated layer type, dense/sparse alternative, embedding/output endpoint, and special nonpersistent buffer.
- Add a class under
gptqmodel/models/definitions/, inheriting the nearest compatible definition orBaseQModel. Supply the correct loader and explicitmodule_tree, in forward order. Set non-strict matching only when optional/heterogeneous paths justify it. - Mark routers/norms/skipped projections with
:!; declare capture-only parents only where replay/scaling needs them. For MoE supply expert counts, expert placeholders,:moe, appropriate lifecycle hooks, and nested Defuser roots if necessary. - Add the import/export in
definitions/__init__.pyand import the class inauto.py; add each exact supportedmodel_typetoMODEL_MAPinauto.py.SUPPORTED_MODELSis derived from this map, not a second manually maintained list. Version-dependent definitions use explicit import/registration gates. - Handle HF/checkpoint naming differences through aliases or
HF_CONVERSION_MAP_REVERSED; prefer declarative reversed renamings over ad hoc materialization patches. Account for direct-meta buffers, tied weights, and out-of-model tensor prefixes. - Implement only the hooks needed for capture and replay. The default
should_quantize_layer()andshould_quantize_module()returnTrue; override both when a layer subclass must remain dense during calibration and checkpoint reconstruction. - Validate the tree with tiny real forwards and the existing module-tree tests, then test loading, first-layer capture, quantization, saving, and reloading. Include omitted/dense modules in save/reload checks, not just successfully quantized linears.
- Add
:in=metadata only after actual-forward validation and list every verifiedmodel_typeon the concrete class. Update project model documentation when registering support.
For a new model that is genuinely forward/layout compatible with Llama, a minimal starting point is inheritance rather than copying its parser logic. The following names are placeholders, not existing registry entries:
# gptqmodel/models/definitions/new_architecture.py
from .llama import LlamaQModel
class NewArchitectureQModel(LlamaQModel):
shared_input_verified_model_types = frozenset()# gptqmodel/models/definitions/__init__.py
from .new_architecture import NewArchitectureQModel
# gptqmodel/models/auto.py (after importing the definition)
MODEL_MAP["actual_config_model_type"] = NewArchitectureQModelReplace the inherited tree/loader/hooks when the actual architecture differs. Empty verification keeps sharing disabled until real-forward tests establish its safety; it does not prevent ordinary quantization.
Useful hook points:
| Hook | Default / intended customization |
|---|---|
before_model_load(self, model_local_path, load_quantized_model) |
No-op; invoked before HF source construction. |
after_model_load(self, model, load_quantized_model) |
Return the model; model-specific structural/config adjustments. |
pre_quantize_generate_hook_start() / pre_quantize_generate_hook_end()
|
Materialize capture prerequisites and release/offload them afterward. Base start is a no-op. |
prepare_dataset(...) |
Base text calibration normalization; multimodal adapters may build processor outputs instead. |
move_input_capture_example(...), finalize_input_capture_example(...)
|
Move/normalize examples before initial capture. |
run_input_capture(...) |
Base calls model(...), or model.generate(...) when INPUT_EMBEDDING_EXTRA_ARGS is truthy. Overrides can prepare embeddings and call the first language layer directly; capture still stops at its pre-hook. |
capture_first_layer_positional_inputs(...) |
Base captures hidden_states kwarg or first positional argument. |
capture_first_layer_input_kwargs(...) |
Base leaves captured kwargs unchanged. |
prepare_layer_replay_kwargs(...) |
Base returns additional inputs unchanged; override for layer-specific masks/rotary/state. |
update_layer_replay_kwargs_from_output(...) |
Base returns layer-input kwargs unchanged; override for cross-layer replay state. |
_model_module_tree(model, quantize_config, detector=None) |
Class hook that selects a declared tree for the model's configuration before method-specific overrides apply. Defaults to the class's module_tree. |
pre_quantize(module, module_path=None) / post_quantize(module)
|
Materialization/device handling around layer processing. The looper passes the dotted module_path when known so lazy loading can look up the layer without scanning the model. Overrides of pre_quantize should accept and forward this keyword. |
lm_head_pre_quantize_generate_hook(inputs) |
Apply the configured final norm before head quantization. |
Initial input capture calls the model-specific release hook and removes its first-layer pre-hook on every exit, including a failing start hook or calibration forward. A cleanup failure is reported without replacing the original capture error; if capture succeeded, a release failure propagates. ERNIE VL releases embeddings, rotary state, the vision tower, and the resampler by attribute name: CPU when disk offload is disabled, disk offload when enabled. For partially materialized meta shells, it moves only real leaves to CPU and leaves meta leaves untouched. All four independent releases are attempted even if one fails. See the capture cleanup lifecycle.
granite_swa selects GraniteSWAQModel, a Llama-derived class with an explicit module tree. Its model.layers.# attention projections and mlp.{gate,up,down}_proj are quantizable; self_attn:! declares ownership of the direct self_attn.sinks parameter without quantizing it. Final norm is model.norm. The sparse sibling uses the same explicit non-quantized attention-container ownership, so sinks resolve through ModulePlan.find() rather than remaining undeclared checkpoint state.
granitemoe_swa selects GraniteMoeSWAQModel. Defuser >=0.0.30 exposes packed routed experts as block_sparse_moe.experts.{expert_index}.{gate_proj,up_proj,down_proj} before module-plan resolution. The definition uses dynamic_expert_index="num_local_experts", GateUpDownMoELifecycleHooks, and layer_modules_strict=False. shared_mlp.input_linear / output_linear are also quantizable; block_sparse_moe.router and layer norms are explicitly excluded. Attention sinks remain source parameters rather than quantized leaves.
Both definitions set fusable=None: ordinary quantization support does not admit opt-in projection fusion, whose current executor does not model their per-layer full/sliding-window dispatch and post-attention sink scaling. See Supported Models, the sparse definition, and the real-model module-plan tests.
olmo_hybrid selects OlmoHybridQModel. Its model.layers.# stack alternates gated-DeltaNet linear_attn and full self_attn blocks; layer_modules_strict=False skips paths absent from each block shape. Both shapes quantize Q/K/V/O projections and mlp.{gate,up,down}_proj; DeltaNet additionally quantizes g_proj.
The linear_attn:! container owns dense A_log and dt_bias. Its a_proj, b_proj, conv1d, and o_norm remain unquantized, as do full-attention Q/K norms and decoder norms. pre_lm_head_norm_module="model.norm" names the final norm. The fusion contract qualifies full-attention QKV and MLP gate/up; the DeltaNet parent is excluded by its native forward semantics. See Supported Models and the real-model plan test.
decision_transformer selects DecisionTransformerQModel with a bundled model loader, require_load_tokenizer=False, and calibration_inputs="tensor_kwargs". Its encoder.h.# GPT-2 decoder attention/MLP projections are quantizable; native root embed_*/predict_* heads are explicitly materialized for lazy loading. See tensor-input calibration. The support addition qualifies GPTQ, not AWQ or projection fusion.
sensenova_loop selects SenseNovaLoopQModel, with a bundled Qwen3.5-derived model, processor loading, and physical decoder path model.language_model.layers.#. LoopedLayerCaptureMixin captures every native forward visit for calibration, while the saved model reuses one quantized copy per physical layer. mhc_attn/mhc_ffn routers are excluded from quantization and must remain FP32; inherited out-of-model preservation retains mtp.* tensors. Its explicit fusable=None withholds projection fusion pending native-forward qualification. See the model entry.
For llama4 and llama4_text, the effective module tree checks the decoder config (including nested text_config). When moe_layers covers every decoder layer, as in Scout, it removes the absent dense feed_forward fallback. Interleaved dense/MoE layouts retain it, and strict module validation remains enabled. This avoids requiring nonexistent dense projections on an all-MoE checkpoint. See the Llama-4 definition.
The following table lists the MODEL_MAP registrations. Several model types intentionally share a definition. A registry entry identifies the model definition. Consult the method and backend pages for supported combinations.
check_and_get_model_definition() uses exact/case-folded lookup, so historical RefinedWeb/RefinedWebModel capitalization now resolves. Both unlimited_ocr (the real configuration spelling) and legacy unlimited-ocr map to UnlimitedOCRQModel. The standard kimi_linear layout selects KimiLinearNativeQModel for ordinary calibration. Only configurations with use_attn_residuals=True or non-None attn_res_block_size retain the legacy K3/Linear bounded-runner requirement; kimi_k3 remains bounded. See supported Kimi layouts and bounded native-source calibration.
Every MODEL_MAP definition now declares a loader: a LocalModelLoader (gptqmodel/models/local.py) naming package-owned config_class, model_class and optional processor_class/tokenizer_class under gptqmodel/models/ports/, including models Transformers implements natively (for example Qwen3QModel.loader = Qwen3Loader()). The loader never reads checkpoint auto_map. Ports target the Transformers 5.23 ABI, import no transformers.models.* and carry no backward-compatibility code; tests/test_model_port_policy.py enforces this. See the port policy.
Other load-time handling includes class-name/config.architectures checkpoint-conversion lookup after model-type lookup, Nemotron-H's model.layers root, and reconstruction of non-persistent buffers after lazy loading. LFM2-MoE declares attention out_proj and defused gate_proj/up_proj/down_proj experts while its dense MLP keeps w1/w3/w2. GLM-ASR uses AutoModelForMultimodalLM, model.language_model.layers and a top-level lm_head. DeepSeek-V4 materializes target layers eagerly for GPTQ/AWQ/RTN while preserving EXL3's packed boundary. HRM-Text captures real recurrent invocations rather than replaying a flattened stack once. See calibration lifecycle.
OLMo (olmo) and Helium (helium) reuse LlamaQModel: model.layers.# contains self_attn.{q,k,v,o}_proj and mlp.{gate,up,down}_proj, with final norm model.norm. Neither alias is in that class's shared_input_verified_model_types allowlist in this revision; registration does not opt them into shared-input Hessian reuse. Original OLMo has parameter-free norms, so selecting them for norm tuning fails the trainable-gain requirement. See tests/test_olmo_helium_support.py for the registry, layout, and norm contracts.
Gemma 2, Gemma 3 text/multimodal, and OLMo 2 have explicit decoder trees so checkpoint-owned normalization weights resolve through ModulePlan.find() while staying unquantized. Gemma 2 declares its pre/post-feed-forward norms; Gemma 3 additionally declares per-head Q/K norms, and its multimodal definition reuses the text decoder leaves. olmo2 now maps to Olmo2QModel, with Q/K norms and post-attention/post-feed-forward norms but no pre-attention input_layernorm. It declares shared-input verification for olmo2 and final norm model.norm. Attention and MLP projection groups remain quantizable. The Gemma/OLMo family coverage test checks real meta-model weight owners and plan consumers.
- Never quantize every
Linearmerely because it exists. The tree, dynamic rules, per-layer/module hooks, and embedding/head rules jointly determine replacement. - A layer-relative suffix is not a checkpoint key. Runtime aliases and HF conversion rules must agree with Defuser's shell layout.
- A class declaration is shared across instances. Do not mutate it inside a loader or method-specific path; use the effective-tree mechanism.
- Group IDs describe execution, not equal inputs. Incorrect sharing can silently reuse the wrong Hessian.
- Extra model-type aliases need their own shared-input verification even if the same class/tree is reused.
- Alternative layer paths are complete tree variants or explicit resolver overrides, not additional strings inserted into one prefix.
- Lazy capture can execute vision/audio/projector modules outside the decoder tree. These must be materialized even though their weights remain dense.
- A skip during calibration alone is insufficient: quantized loading and saving must also honor it. Mllama's cross-attention hooks demonstrate the two-sided contract.
- Device constants express available families, not a kernel compatibility guarantee.
_const.py's CUDA helper checks for at least one device with compute capability >= 6.0; individual kernels can require newer architectures. ROCm uses PyTorch'scudadevice namespace.
-
gptqmodel/models/base.py— definition contract, tree parsing/overrides, effective-tree isolation, traversal, capture/replay hooks, materialization, save dispatch. -
gptqmodel/models/auto.py—GPTQModel,MODEL_MAP, conditional registrations, automatic source/quantized dispatch. -
gptqmodel/models/definitions/__init__.pyandgptqmodel/models/definitions/*.py— definition registry imports and architecture declarations. -
gptqmodel/models/loader.py— HF source/quantized loaders, requirement checks, Defuser integration, lazy source setup, runtime replacement. -
gptqmodel/models/writer.py— quantized configuration/weight streaming, sharding, extra tensors, tokenizer/processor packaging. -
gptqmodel/models/shared_input.py— metadata collection, grouping, verification probes. -
gptqmodel/models/definitions/ricursive.py,gptqmodel/models/ports/ricursive/,tests/test_ricursive_local_port.py— Ripple targets, bundled model and regression coverage. -
tests/test_pre_lm_head_norm_resolution.py— ordered final-norm candidate and multimodal layout regressions. -
gptqmodel/models/moe_lifecycle.py— expert replay/lifecycle interfaces. -
gptqmodel/models/_const.py— device/platform enums, supported module types, expert placeholder, shard default. -
gptqmodel/utils/structure.py—LazyTurtleand checkpoint-backed tensor materialization. -
gptqmodel/quantization/config.py— quantization methods, dynamic exclusions, MoE/configuration types. -
gptqmodel/quantization/mlx_native.py— separate MLX quantization entry point and native GPTQ/MLX-LM AWQ dispatch. -
gptqmodel/looper/stage_inputs_capture.py,gptqmodel/looper/stage_subset.py,gptqmodel/looper/module_looper.py— consumers of the definition and replay plans. -
tests/module_tree/— automatic detection, variants, subset order, MoE metadata, and shared-input tests.
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
- 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 / RTN
- 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