From d85f81fd8f1bbfbb7a9fe2ddc5bdab4fddca88f8 Mon Sep 17 00:00:00 2001 From: Qubitium Date: Fri, 6 Nov 2026 15:36:19 -0800 Subject: [PATCH 1/7] fix(models): resolve module roles from explicit model trees --- gptqmodel/looper/awq_processor.py | 9 +- gptqmodel/looper/exllamav3_processor.py | 4 +- gptqmodel/looper/gsq_training_awq.py | 22 +- gptqmodel/looper/gsq_training_capture.py | 8 +- gptqmodel/looper/gsq_training_model.py | 9 +- gptqmodel/looper/module_looper.py | 35 +- gptqmodel/looper/stage_subset.py | 14 +- gptqmodel/looper/weight_only_looper.py | 23 +- gptqmodel/models/auto.py | 3 +- gptqmodel/models/base.py | 101 ++++-- .../models/definitions/hunyuan_v1_moe.py | 1 - gptqmodel/models/definitions/k2_horizon.py | 1 - gptqmodel/models/loader.py | 58 +++- gptqmodel/models/module_plan.py | 311 ++++++++++++++++++ gptqmodel/models/moe_lifecycle.py | 75 ++++- gptqmodel/models/writer.py | 26 +- gptqmodel/quantization/awq/utils/utils.py | 8 +- gptqmodel/quantization/gsq_training.py | 81 +++-- gptqmodel/quantization/gsq_training_affine.py | 14 +- gptqmodel/quantization/rotation/rotation.py | 126 +++++-- gptqmodel/utils/model.py | 53 ++- tests/module_tree/test_auto_detect.py | 2 +- .../module_tree/test_explicit_module_plan.py | 125 +++++++ .../module_tree/test_module_tree_variants.py | 44 +-- tests/test_afmoe_support.py | 8 +- tests/test_awq_weight_mean.py | 2 +- 26 files changed, 944 insertions(+), 219 deletions(-) create mode 100644 gptqmodel/models/module_plan.py create mode 100644 tests/module_tree/test_explicit_module_plan.py diff --git a/gptqmodel/looper/awq_processor.py b/gptqmodel/looper/awq_processor.py index e1ca2734c4..a268bab785 100644 --- a/gptqmodel/looper/awq_processor.py +++ b/gptqmodel/looper/awq_processor.py @@ -1583,7 +1583,14 @@ def unwrap(m): if staged_gsq is not None and staged_gsq.enabled: from .gsq_training_awq import capture_awq_staged_teacher - staged_teacher = capture_awq_staged_teacher(self, layer_module_ref, named_childs, fallback_names) + plan = getattr(self.gptq_model, "module_plan", None) + projections = tuple( + name for name, named in named_childs.items() + if plan is None or plan.roles(name) + ) + staged_teacher = capture_awq_staged_teacher( + self, layer_module_ref, named_childs, fallback_names, projections=projections, + ) if self.apply_clip: clip_list = self._search_best_clip( diff --git a/gptqmodel/looper/exllamav3_processor.py b/gptqmodel/looper/exllamav3_processor.py index aece0753f3..baa7a63a23 100644 --- a/gptqmodel/looper/exllamav3_processor.py +++ b/gptqmodel/looper/exllamav3_processor.py @@ -180,9 +180,7 @@ def tmp(module, inp: Tuple[torch.Tensor, ...], out: torch.Tensor): def _is_lm_head(self, module: NamedModule) -> bool: """Returns whether the named module corresponds to the model lm_head.""" - if module.full_name == self.lm_head_name: - return True - return module.full_name.endswith(f".{self.lm_head_name}") + return module.full_name == self.lm_head_name or module.name == self.lm_head_name def _target_bits(self, module: NamedModule, module_qcfg: EXL3Config) -> int: """Chooses lm_head-specific bitwidth overrides when configured.""" diff --git a/gptqmodel/looper/gsq_training_awq.py b/gptqmodel/looper/gsq_training_awq.py index 4dff4b8307..b194a85e93 100644 --- a/gptqmodel/looper/gsq_training_awq.py +++ b/gptqmodel/looper/gsq_training_awq.py @@ -14,10 +14,11 @@ 'mlp.gate_proj', 'mlp.up_proj', 'mlp.down_proj') -def capture_awq_staged_teacher(processor, layer, modules, fallback_names): +def capture_awq_staged_teacher(processor, layer, modules, fallback_names, projections=None): """Capture the scaled, pre-clipping teacher before AWQ overwrites weights.""" - if set(modules) != set(PROJECTIONS) or fallback_names: - raise ValueError('Staged AWQ GSQ requires all seven Llama projections without fallback') + expected = tuple(projections or PROJECTIONS) + if set(modules) != set(expected) or fallback_names: + raise ValueError('Staged AWQ GSQ requires every declared projection without fallback') if any(module.state.get('tp_pad_info') for module in modules.values()): raise ValueError('Staged AWQ GSQ does not support tensor-parallel padding') if layer.self_attn.config._attn_implementation != 'eager': @@ -46,12 +47,23 @@ def refine_awq_staged_layer(processor, teacher_capture, modules, *, layer_index) groups = torch.arange(weight.shape[1], device=device)//processor.qcfg.group_size codes = affine_codes(weight, scales, zeros, groups, 4, packing='awq_gemm', scale_dtype=scales.dtype) initializers[name] = (codes, scales, zeros) + projections = tuple(modules) _, records = fit_llama_stages(teacher, initializers, batches, bits=4, group_size=processor.qcfg.group_size, affine_initializers=True, - reinitialize_mlp=False, **options) + reinitialize_mlp=False, projections=projections, **options) payloads = {} + plan = getattr(processor.gptq_model, "module_plan", None) + attention_parents = {spec.parent for spec in plan.specs if "q" in spec.roles} if plan else () + mlp_parents = {spec.parent for spec in plan.specs if "gate" in spec.roles} if plan else () + + def stage_for(name): + if name in records: + return name + parent = name.rsplit(".", 1)[0] if "." in name else "" + return "attention" if parent in attention_parents else "mlp" if parent in mlp_parents else name + for name, named in modules.items(): - stage = name if name in records else ('attention' if name.startswith('self_attn.') else 'mlp') + stage = stage_for(name) key = 'weight' if stage == name else name+'.weight' record = records[stage] linear = processor.resolve_quant_source_module(named) diff --git a/gptqmodel/looper/gsq_training_capture.py b/gptqmodel/looper/gsq_training_capture.py index 5709e9180d..ed1d6797b6 100644 --- a/gptqmodel/looper/gsq_training_capture.py +++ b/gptqmodel/looper/gsq_training_capture.py @@ -274,7 +274,8 @@ def clone(value): def quantize_llama_gsq_capture(layer, cache, *, bits, group_size, gsq=None, pack=True, device=None, initialization_cache=None, validation_cache=None, distributed=None, - target_cache='none', activation_checkpointing=False): + target_cache='none', activation_checkpointing=False, + projections=None, attention_projections=None, mlp_projections=None): """Train/export a shared captured block even when its caller uses inference mode. The shared looper still owns installing the result and replaying it before @@ -294,7 +295,10 @@ def quantize_llama_gsq_capture(layer, cache, *, bits, group_size, gsq=None, pack gsq=gsq, pack=pack, initialization_batches=initialization_batches, validation_batches=validation_batches, distributed=distributed, - target_cache=target_cache, activation_checkpointing=activation_checkpointing) + target_cache=target_cache, activation_checkpointing=activation_checkpointing, + projections=projections, + attention_projections=attention_projections, + mlp_projections=mlp_projections) def capture_llama_gsq_inputs( diff --git a/gptqmodel/looper/gsq_training_model.py b/gptqmodel/looper/gsq_training_model.py index 95dc3530ee..7dbad187de 100644 --- a/gptqmodel/looper/gsq_training_model.py +++ b/gptqmodel/looper/gsq_training_model.py @@ -10,6 +10,7 @@ import torch +from ..quantization.gsq_training import LLAMA_STAGED_PROJECTIONS as STAGED_PROJECTIONS from ..quantization.gsq_training_config import GSQTrainingConfig from .gsq_training_capture import advance_llama_gsq_inputs, capture_llama_gsq_inputs, quantize_llama_gsq_capture @@ -154,7 +155,7 @@ def quantize_llama_gsq_model(model, documents, *, bits, group_size, gsq=None, la initialization_documents=None, validation_documents=None, checkpoint_directory=None, distributed=None, target_cache='none', activation_checkpointing=False, - resume_prefix_directory=None, reuse_capture=False): + resume_prefix_directory=None, reuse_capture=False, projections=None): """Quantize selected dense decoder blocks in place and replay the packed prefix. Defaults select every decoder block. This runtime entry point does not write @@ -227,6 +228,7 @@ def quantize_llama_gsq_model(model, documents, *, bits, group_size, gsq=None, la raise ValueError('Staged model quantization requires nonempty validation documents') if validation_documents is not None and not gsq.enabled: raise ValueError('Validation documents require enabled staged GSQ') + names = tuple(projections or STAGED_PROJECTIONS) layers = model.model.layers indices = list(range(len(layers))) if layer_indices is None else list(layer_indices) if (not indices or any(isinstance(i, bool) or not isinstance(i, int) or not 0 <= i < len(layers) for i in indices) @@ -236,8 +238,6 @@ def quantize_llama_gsq_model(model, documents, *, bits, group_size, gsq=None, la if len(devices) != 1 or next(iter(devices)).type == 'meta': raise ValueError('Staged model quantization currently requires one materialized model device') device = next(iter(devices)) - names = ('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') for index in indices: for name in names: module = layers[index].get_submodule(name) @@ -441,7 +441,8 @@ def capture_validation(index=index, capture_options=capture_options, initialization_cache=initialization_cache, validation_cache=validation_cache, distributed=distributed, target_cache=target_cache, - activation_checkpointing=activation_checkpointing) + activation_checkpointing=activation_checkpointing, + projections=names) finally: if not reuse_capture: for captured in (cache, initialization_cache, validation_cache): diff --git a/gptqmodel/looper/module_looper.py b/gptqmodel/looper/module_looper.py index a382b0f5be..8d8ceb1872 100644 --- a/gptqmodel/looper/module_looper.py +++ b/gptqmodel/looper/module_looper.py @@ -916,42 +916,23 @@ def _collect_row_counts(self, layer_inputs: Optional[List[List[torch.Tensor]]]) return counts def _extract_moe_group_key(self, module_name: Optional[str]) -> Optional[str]: - """Collapse expert module names into a stable MoE routing group key.""" + """Collapse expert module names using the definition's declared experts.""" if not module_name: return None - if ".experts." in module_name: - prefix, remainder = module_name.split(".experts.", 1) - expert_id = remainder.split(".", 1)[0] - if expert_id: - return f"{prefix}.experts.{expert_id}" + plan = getattr(self.gptq_model, "module_plan", None) + if plan is None: return None - - if ".shared_experts." in module_name: - prefix, _ = module_name.split(".shared_experts.", 1) - return f"{prefix}.shared_experts" - - if ".shared_expert." in module_name: - prefix, _ = module_name.split(".shared_expert.", 1) - return f"{prefix}.shared_expert" - - return None + return plan.expert_root(module_name) def _is_attention_module_name(self, module_name: str) -> bool: - """Heuristically detect attention modules from their qualified name.""" + """Return whether the declared tree marks this path as attention.""" - if not module_name: + plan = getattr(self.gptq_model, "module_plan", None) + if plan is None or not module_name: return False - - lowered = module_name.lower() - if ".attn" in lowered or "attn." in lowered: - return True - if ".attention" in lowered or "attention." in lowered: - return True - if lowered.endswith("attn") or lowered.endswith("attention"): - return True - return False + return "q" in plan.roles(module_name) or "k" in plan.roles(module_name) or "v" in plan.roles(module_name) def _should_use_moe_lifecycle( self, diff --git a/gptqmodel/looper/stage_subset.py b/gptqmodel/looper/stage_subset.py index f5a83b9f6a..e75e2cf36d 100644 --- a/gptqmodel/looper/stage_subset.py +++ b/gptqmodel/looper/stage_subset.py @@ -327,14 +327,17 @@ def _collect_layer_candidate_names( def _collect_assignable_moe_group_keys( moe_groups: Dict[str, List[str]], + plan, ) -> List[str]: """Return expert families that should stay co-located on one device.""" assignable_group_keys: List[str] = [] for group_key, module_names in moe_groups.items(): - suffixes = {name.rsplit(".", 1)[-1] for name in module_names} - # Some MoE families route pairs like gate/up or w1/w3 together. - if {"gate_proj", "up_proj"}.issubset(suffixes) or {"w1", "w3"}.issubset(suffixes): + if plan is None: + assignable_group_keys.append(group_key) + continue + roles = {role for name in module_names for role in plan.roles(name)} + if {"gate", "up"}.issubset(roles): assignable_group_keys.append(group_key) return assignable_group_keys @@ -489,7 +492,10 @@ def build_subset_plan( forward_device_map[module_name] = target_device if moe_strategy_active and moe_groups and moe_devices: - assignable_group_keys = _collect_assignable_moe_group_keys(moe_groups) + assignable_group_keys = _collect_assignable_moe_group_keys( + moe_groups, + getattr(looper.gptq_model, "module_plan", None), + ) if assignable_group_keys: if looper._moe_vram_strategy == VramStrategy.BALANCED and len(moe_devices) > 1: for group_index, group_key in enumerate(assignable_group_keys): diff --git a/gptqmodel/looper/weight_only_looper.py b/gptqmodel/looper/weight_only_looper.py index 8a9361bb72..41561886d3 100644 --- a/gptqmodel/looper/weight_only_looper.py +++ b/gptqmodel/looper/weight_only_looper.py @@ -216,26 +216,23 @@ def _resolve_strategy_device_pools(self) -> None: self._dense_vram_strategy_explicit = bool(dense_strategy_devices) or self._dense_vram_strategy != VramStrategy.EXCLUSIVE self._moe_vram_strategy_explicit = bool(moe_strategy_devices) or self._moe_vram_strategy != VramStrategy.EXCLUSIVE - @staticmethod - def _extract_moe_group_key(module_name: Optional[str]) -> Optional[str]: + def _extract_moe_group_key(self, module_name: Optional[str]) -> Optional[str]: """Return the expert family key used to co-locate gate/up/down modules.""" - if not module_name or ".experts." not in module_name: - return None - prefix, remainder = module_name.split(".experts.", 1) - expert_id = remainder.split(".", 1)[0] - if not expert_id: - return None - return f"{prefix}.experts.{expert_id}" + plan = getattr(self.gptq_model, "module_plan", None) + return plan.expert_root(module_name) if plan is not None and module_name else None - @staticmethod - def _collect_assignable_moe_group_keys(moe_groups: Dict[str, List[str]]) -> List[str]: + def _collect_assignable_moe_group_keys(self, moe_groups: Dict[str, List[str]]) -> List[str]: """Return expert families that should stay co-located on one device.""" assignable_group_keys: List[str] = [] for group_key, module_names in moe_groups.items(): - suffixes = {name.rsplit(".", 1)[-1] for name in module_names} - if {"gate_proj", "up_proj"}.issubset(suffixes) or {"w1", "w3"}.issubset(suffixes): + plan = getattr(self.gptq_model, "module_plan", None) + if plan is None: + assignable_group_keys.append(group_key) + continue + roles = {role for name in module_names for role in plan.roles(name)} + if {"gate", "up"}.issubset(roles): assignable_group_keys.append(group_key) return assignable_group_keys diff --git a/gptqmodel/models/auto.py b/gptqmodel/models/auto.py index e5d7295bab..6fb503a994 100644 --- a/gptqmodel/models/auto.py +++ b/gptqmodel/models/auto.py @@ -581,7 +581,8 @@ def check_and_get_model_definition(model_dir, trust_remote_code=False, **config_ config = AutoConfig.from_pretrained(model_dir, trust_remote_code=trust_remote_code, **config_load_kwargs) model_type = config.model_type.lower() - # if model_type is not supported, use BaseQModel, will use auto_detect_module_tree to generate module tree + # Unsupported model types use BaseQModel and fail closed unless the caller + # supplies an explicit model definition/module tree. if model_type not in SUPPORTED_MODELS: return BaseQModel diff --git a/gptqmodel/models/base.py b/gptqmodel/models/base.py index 72e03a2754..e4e6a0f113 100644 --- a/gptqmodel/models/base.py +++ b/gptqmodel/models/base.py @@ -106,6 +106,7 @@ normalize_device, ) from .loader import ModelLoader, _setup_rotation_online_had +from .module_plan import ModulePlan from .shared_input import SharedInputPlan, build_shared_input_plan from .writer import ModelWriter @@ -436,8 +437,6 @@ class BaseQModel(nn.Module): # `WeightRenaming` entries; legacy runtime->checkpoint dicts are still accepted. HF_CONVERSION_MAP_REVERSED: Optional[Any] = None - moe_expert_module_name_prefixes = [".expert"] - ATTENTION_MASKS_DTYPE = torch.bool # default to bool ATTENTION_MASKS_REQUIRED_FOR_INPUT: bool = False @@ -484,12 +483,16 @@ def __init__( # If module_tree is still None after auto-detection, raise an error indicating unsupported model type if effective_tree is None: - raise ValueError(f"Unsupport model_type {model.config.model_type}, and failed to auto-detect module tree for model {model}") + raise ValueError( + f"Unsupported model_type {model.config.model_type}: no explicit module_tree is registered. " + "Add a model definition instead of relying on name-based auto-detection." + ) # Keep the selected tree stable for the lifetime of this instance; # class definitions remain reusable by later instances. self.effective_module_tree = _freeze_module_tree(effective_tree) self.module_tree = self.effective_module_tree + self.module_plan = ModulePlan.from_tree(self.effective_module_tree) # record configuration early so model lifecycle hooks can rely on them @@ -521,6 +524,11 @@ def __init__( if dynamic_cache_prepared else dynamic_override_cache_stats(getattr(quantize_config, "dynamic", None)) ) self.model = self.after_model_load(model, load_quantized_model=load_quantized_model) + hooks = getattr(self, "moe_lifecycle_hooks", None) + if hooks is not None: + hooks = copy.copy(hooks) + self.moe_lifecycle_hooks = hooks + hooks.module_plan = self.module_plan if (getattr(quantize_config, "dynamic", None) and hasattr(self.model, "named_modules") and (not dynamic_cache_prepared or self.model is not model @@ -596,18 +604,15 @@ def __init__( def _resolve_effective_module_tree(cls, model, quantize_config, detector=None): """Resolve a model tree before a loader needs to plan against it.""" quant_method = getattr(quantize_config, "method", None) if quantize_config else None - effective_tree = copy.deepcopy(cls.module_tree) + effective_tree = copy.deepcopy(getattr(model, "gptqmodel_effective_module_tree", None)) + if effective_tree is None: + effective_tree = copy.deepcopy(cls.module_tree) if quant_method is not None: override = (getattr(cls, "module_tree_overrides", None) or {}).get(quant_method) if override is not None and effective_tree is not None: log.info(f"Module Tree: overridden by METHOD.{quant_method.upper()}") effective_tree = apply_module_tree_override(effective_tree, override) - if effective_tree is None: - if detector is None: - detector = cls.__new__(cls) - effective_tree = detector._auto_detect_module_tree(model, quant_method) - return copy.deepcopy(effective_tree) @classmethod @@ -828,21 +833,30 @@ def is_moe_module(cls, module_path: str) -> bool: Returns: True if any parent in the path is marked with :moe flag """ - moe_modules = cls.get_moe_modules() - - # Check if any MoE module is a prefix of this path - for moe_module in moe_modules: - # Handle layer index in path (e.g., "model.layers.0.mlp" should match "mlp") - if f".{moe_module}" in module_path or module_path.endswith(moe_module): - return True - # Also check for patterns like "mlp.experts.5" matching "mlp.experts" - path_parts = module_path.split(".") - for i in range(len(path_parts)): - partial_path = ".".join(path_parts[i:]) - if partial_path.startswith(moe_module + ".") or partial_path == moe_module: - return True - - return False + if not isinstance(module_path, str) or not module_path: + return False + + layers = cls.extract_layers_node() + relative = None + for layer_path in layers: + prefix = f"{layer_path}." + if module_path.startswith(prefix): + relative = module_path[len(prefix):] + break + container_name = layer_path.rsplit(".", 1)[-1] + shorthand = f"{container_name}." + if module_path.startswith(shorthand): + layer_index, separator, remainder = module_path[len(shorthand):].partition(".") + if separator and layer_index.isdigit(): + relative = remainder + break + if relative is None: + return False + + first, separator, remainder = relative.partition(".") + if separator and first.isdigit(): + relative = remainder + return ModulePlan.from_tree(_module_tree_for_class(cls)).is_moe(relative) @classmethod def get_moe_module_name(cls) -> Optional[List[str]]: @@ -1131,8 +1145,7 @@ def expert_count(module_name: str) -> int: # Currently, only need to add `capture_only_modules` to `['mlp.experts.#.gate_proj', 'mlp.experts.#.up_proj']` # or ['mlp.shared_expert.gate_proj', 'mlp.shared_expert.up_proj', 'mlp.experts.#.gate_proj', 'mlp.experts.#.up_proj'] # or ['mlp.shared_experts.gate_proj', 'mlp.shared_experts.up_proj', 'mlp.experts.#.gate_proj', 'mlp.experts.#.up_proj'] - add_capture_only_module = len(names) == (4 if any("shared_expert" in n for n in names) else 2) - if add_capture_only_module and capture_only_modules: + if capture_only_modules and any(EXPERT_INDEX_PLACEHOLDER in n for n in names): # Extend all elements in capture_only_modules moe_simple[-1].extend(capture_only_modules) else: @@ -1658,6 +1671,7 @@ def quantize( } self.model = fuse_layer_norms(model=self.model, pre_lm_head_norm_module_name=self.pre_lm_head_norm_module, + plan=self.module_plan, **module_name_args) # MPS does not support float64. @@ -1669,7 +1683,9 @@ def quantize( if rotation_device is not None and rotation_device.type == "mps": rotation_device = CPU self.model, _ = rotate_model(model=self.model, rotate_mode=self.quantize_config.rotation, - device=rotation_device, **module_name_args) + device=rotation_device, plan=self.module_plan, + embedding_name=self.get_input_embeddings_name(), + **module_name_args) if self.quantize_config.rotation: backend = normalize_backend(backend, quant_method=self.quantize_config.method) @@ -1753,7 +1769,12 @@ def quantize( if timer is not None: timer.flush() - _setup_rotation_online_had(self.model, self.quantize_config.rotation) + _setup_rotation_online_had( + self.model, + self.quantize_config.rotation, + module_plan=self.module_plan, + layer_prefixes=self.extract_layers_node(), + ) if self.quantize_config.dynamic: log_dynamic_override_cache_stats(dynamic_cache_stats_before, dynamic=self.quantize_config.dynamic) return result @@ -3769,7 +3790,8 @@ def awq_input_feature_aggregation(cls, module_name: str) -> Optional[Dict[str, A if not isinstance(module_name, str): return None - for moe_root in cls.get_moe_module_name() or []: + plan = getattr(cls, "module_plan", None) or ModulePlan.from_tree(_module_tree_for_class(cls)) + for moe_root in (spec.template for spec in plan.moe_roots()) or cls.get_moe_module_name() or []: if module_name == moe_root: return { "mode": "token_rows", @@ -3860,9 +3882,19 @@ def _module_kwargs_for_feature(feature_name: str | None): _try_update_last_module(candidate_name) continue - is_moe_block = any(any(k in name for k in self.moe_expert_module_name_prefixes) for name in block) - is_moe_down_block = is_moe_block and any("down" in name for name in block) - is_moe_gate_up_block = is_moe_block and any("gate" in name for name in block) and any("up" in name for name in block) + plan = getattr(self, "module_plan", None) or ModulePlan.from_tree(_module_tree_for_class(type(self))) + block_roles = { + name: plan.roles(strip_non_quantize_flags(name)) + for name in block + } + is_moe_block = any( + plan.is_expert(strip_non_quantize_flags(name)) + for name in block + ) + is_moe_down_block = is_moe_block and any("down" in roles for roles in block_roles.values()) + is_moe_gate_up_block = is_moe_block and any( + "gate" in roles or "up" in roles for roles in block_roles.values() + ) if is_moe_down_block and last_module is not None and last_module_name is not None: # mlp.experts.0.down_proj target_suffix = last_module_name.split(".")[-1] @@ -3960,7 +3992,8 @@ def _module_kwargs_for_feature(feature_name: str | None): # as the effective boundary for the expert segment in this block. gate_up_proj_indices = [ i for i, name in enumerate(block) - if any(k in name for k in self.moe_expert_module_name_prefixes) and ("gate" in name or "up" in name) + if plan.is_expert(strip_non_quantize_flags(name)) + and ({"gate", "up"} & set(block_roles[name])) ] # Use the last one if any exist @@ -3968,7 +4001,7 @@ def _module_kwargs_for_feature(feature_name: str | None): last_up_proj_index = gate_up_proj_indices[-1] candidate_name = strip_non_quantize_flags(block[last_up_proj_index]) - assert "gate" in candidate_name or "up" in candidate_name + assert {"gate", "up"} & set(block_roles[block[last_up_proj_index]]) else: candidate_name = strip_non_quantize_flags(block[-1]) _try_update_last_module(candidate_name) diff --git a/gptqmodel/models/definitions/hunyuan_v1_moe.py b/gptqmodel/models/definitions/hunyuan_v1_moe.py index 55eed49a64..bf92e44fce 100644 --- a/gptqmodel/models/definitions/hunyuan_v1_moe.py +++ b/gptqmodel/models/definitions/hunyuan_v1_moe.py @@ -16,7 +16,6 @@ class HunYuanMoEV1QModel(BaseQModel): awq_scale_optimize_shape_dependent_modules = ["self_attn.o_proj"] moe_lifecycle_hooks = GateUpDownMoELifecycleHooks() - moe_lifecycle_hooks.shared_expert_block_names = ["shared_mlp"] module_tree = [ "model", diff --git a/gptqmodel/models/definitions/k2_horizon.py b/gptqmodel/models/definitions/k2_horizon.py index 1117fd26cd..cbd1aa3135 100644 --- a/gptqmodel/models/definitions/k2_horizon.py +++ b/gptqmodel/models/definitions/k2_horizon.py @@ -129,7 +129,6 @@ class K2HorizonQModel(BaseQModel): } pre_lm_head_norm_module = "model.norm" - moe_expert_module_name_prefixes = [".expert", ".v_experts."] moe_lifecycle_hooks = K2HorizonMoELifecycleHooks() module_tree = [ diff --git a/gptqmodel/models/loader.py b/gptqmodel/models/loader.py index 412e5e9f1f..fdb03a0a73 100644 --- a/gptqmodel/models/loader.py +++ b/gptqmodel/models/loader.py @@ -102,7 +102,7 @@ simple_dispatch_model, validate_checkpoint_qweights, ) -from ._const import DEVICE, HAS_NPU, normalize_device +from ._const import DEVICE, EXPERT_INDEX_PLACEHOLDER, HAS_NPU, normalize_device log = setup_logger() @@ -649,7 +649,7 @@ def _set_paged_attention_safe_cuda_graphs(model) -> None: cb_config.use_cuda_graph = (False, False) -def _setup_rotation_online_had(model, rotation: Optional[str]) -> None: +def _setup_rotation_online_had(model, rotation: Optional[str], module_plan=None, layer_prefixes=None) -> None: """Attach online Hadamard transform state to QuantLinear modules for rotation inference. Rotation (QuaRot/SpinQuant/Hadamard) fuses an orthogonal ``Q`` and an exact @@ -673,7 +673,21 @@ def _setup_rotation_online_had(model, rotation: Optional[str]) -> None: if not isinstance(module, BaseQuantLinear): continue - if name.endswith("mlp.down_proj"): + relative = None + if module_plan is not None: + for prefix in layer_prefixes or (): + if name.startswith(f"{prefix}."): + relative = name[len(prefix) + 1:] + break + if relative is not None: + _, separator, remainder = relative.partition(".") + relative = remainder if separator and _.isdigit() else relative + is_down_projection = ( + "down" in module_plan.roles(relative) + if module_plan is not None and relative is not None + else name.endswith("mlp.down_proj") + ) + if is_down_projection: intermediate_size = module.in_features had_K, K = get_hadK(intermediate_size) module.online_full_had = True @@ -1879,8 +1893,9 @@ def from_quantized( effective_module_tree = cls._resolve_effective_module_tree(model, qcfg) if effective_module_tree is None: raise ValueError( - f"Unsupport model_type {config.model_type}, and failed to auto-detect module tree for model {model}" + f"Unsupported model_type {config.model_type}: no explicit module_tree is registered." ) + model.gptqmodel_effective_module_tree = copy.deepcopy(effective_module_tree) with cls._module_tree_context(effective_module_tree): extract_layers_node = cls.extract_layers_node() @@ -1923,9 +1938,31 @@ def from_quantized( if qcfg.lm_head and name == cls.lm_head: continue - if not any(name.startswith(prefix) for prefix in extract_layers_node) or any(name.startswith(ignore_module) for ignore_module in ignore_modules) or all( - not name.endswith(ignore_module) for sublist in simple_layer_modules for ignore_module in sublist - ): + layer_prefix = next( + (f"{prefix}." for prefix in extract_layers_node if name.startswith(f"{prefix}.")), + None, + ) + relative = name[len(layer_prefix):] if layer_prefix is not None else None + if relative is not None: + layer_index, separator, remainder = relative.partition(".") + relative = remainder if separator and layer_index.isdigit() else relative + declared = { + item.split(":", 1)[0] + for sublist in simple_layer_modules + for item in sublist + } + relative_match = ( + relative is not None + and any( + relative == leaf + or (relative.startswith(f"{leaf}.") and EXPERT_INDEX_PLACEHOLDER in leaf) + for leaf in declared + ) + ) + if layer_prefix is None or any( + name == ignore_module or name.startswith(f"{ignore_module}.") + for ignore_module in ignore_modules + ) or not relative_match: # log non-lm-head quantized modules only if name is not cls.lm_head: log.info(f"The layer {name} is not quantized.") @@ -2387,7 +2424,12 @@ def assign(mod, device_id): ) if backend == BACKEND.MLX: instance._runtime_generate = partial(mlx_generate, tokenizer=tokenizer) - _setup_rotation_online_had(instance.model, qcfg.rotation) + _setup_rotation_online_had( + instance.model, + qcfg.rotation, + module_plan=getattr(instance, "module_plan", None), + layer_prefixes=instance.extract_layers_node(), + ) _set_paged_attention_safe_cuda_graphs(instance.model) if qcfg.dynamic: log_dynamic_override_cache_stats(instance._dynamic_cache_stats_before, dynamic=qcfg.dynamic) diff --git a/gptqmodel/models/module_plan.py b/gptqmodel/models/module_plan.py new file mode 100644 index 0000000000..0ab18076f9 --- /dev/null +++ b/gptqmodel/models/module_plan.py @@ -0,0 +1,311 @@ +# SPDX-FileCopyrightText: 2026 ModelCloud.ai +# SPDX-License-Identifier: Apache-2.0 + +"""Immutable module inventory derived from a model definition's ``module_tree``. + +Quantization code must never rediscover module roles by inspecting live names. +The definition tree already declares decoder boundaries, aliases, MoE roots, +expert placeholders, projection order, and exclusion/capture flags. This module +turns that declaration into exact, layer-relative paths and role queries. + +Only template paths declared by the definition are matched. Expert placeholders +are expanded only at explicit ``#`` nodes, and no query accepts a name merely +because it shares a prefix or suffix with a declared path. +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple + +from ._const import EXPERT_INDEX_PLACEHOLDER as _EXPERT_PLACEHOLDER + + +_PLACEHOLDER_RE = re.escape(_EXPERT_PLACEHOLDER) +_NOT_QUANTIZE = "!" +_CAPTURE_ONLY = "?" + +PROJECTION_ROLE_FLAGS = { + "q": "q", + "k": "k", + "v": "v", + "o": "o", + "gate": "gate", + "up": "up", + "down": "down", +} + +PROJECTION_ROLE_NAMES = { + "q_proj": ("q",), + "k_proj": ("k",), + "v_proj": ("v",), + "o_proj": ("o",), + "gate_proj": ("gate",), + "up_proj": ("up",), + "down_proj": ("down",), + "w1": ("gate",), + "w3": ("up",), + "w2": ("down",), + "gate_up_proj": ("gate", "up"), +} + + +def _split_spec(token: str) -> Tuple[str, List[str]]: + parts = token.split(":") + aliases = [alias for alias in parts[0].split("|") if alias] + name = aliases[0] if aliases else parts[0] + return name, [part for part in parts[1:] if part] + + +def _join(parent: str, child: str) -> str: + if not child: + return parent + return f"{parent}.{child}" if parent else child + + +def _iter_variants(module_tree: Any) -> List[List[Any]]: + if not isinstance(module_tree, (list, tuple)): + return [] + if module_tree and all(isinstance(item, (list, tuple)) for item in module_tree): + return [list(item) for item in module_tree] + return [list(module_tree)] + + +@dataclass(frozen=True) +class ModuleSpec: + """One declared module path plus the flags that define its role.""" + + template: str + flags: Tuple[str, ...] = () + + @property + def name(self) -> str: + return self.template.rsplit(".", 1)[-1] + + @property + def parent(self) -> str: + return self.template.rsplit(".", 1)[0] if "." in self.template else "" + + @property + def is_moe(self) -> bool: + return "moe" in self.flags + + @property + def is_expert_placeholder(self) -> bool: + return _EXPERT_PLACEHOLDER in self.template + + @property + def is_root_leaf(self) -> bool: + return self.template == self.name + + @property + def quantize(self) -> bool: + return not any(flag in (_NOT_QUANTIZE, _CAPTURE_ONLY) for flag in self.flags) + + @property + def capture_only(self) -> bool: + return _CAPTURE_ONLY in self.flags + + @property + def roles(self) -> Tuple[str, ...]: + explicit = tuple(PROJECTION_ROLE_FLAGS[flag] for flag in self.flags if flag in PROJECTION_ROLE_FLAGS) + if explicit: + return explicit + return PROJECTION_ROLE_NAMES.get(self.name, ()) + + @property + def pattern(self) -> re.Pattern[str]: + escaped = re.escape(self.template) + return re.compile("^" + escaped.replace(_PLACEHOLDER_RE, r"\d+") + "$") + + def matches(self, path: str) -> bool: + return bool(self.pattern.match(path)) + + +def collect_module_specs(module_tree: Any) -> Dict[str, ModuleSpec]: + """Collect every path declared under a tree's decoder ``#`` boundary.""" + + specs: Dict[str, ModuleSpec] = {} + + def record(template: str, flags: Sequence[str]) -> None: + current = specs.get(template) + merged = tuple(dict.fromkeys((*(current.flags if current else ()), *flags))) + specs[template] = ModuleSpec(template=template, flags=merged) + + def walk(node: Any, parent: str) -> None: + if isinstance(node, dict): + for key, value in node.items(): + if not isinstance(key, str): + continue + name, flags = _split_spec(key) + child = _join(parent, _EXPERT_PLACEHOLDER if name == "#" else name) + record(child, flags) + walk(value, child) + return + if isinstance(node, (tuple, list)): + for item in node: + if isinstance(item, dict): + walk(item, parent) + continue + if not isinstance(item, str): + continue + name, flags = _split_spec(item) + child = parent if name == "#" or parent == name or parent.endswith(f".{name}") else _join(parent, name) + record(child, flags) + + for variant in _iter_variants(module_tree): + try: + boundary = variant.index("#") + except ValueError: + continue + mapping = next((item for item in variant[boundary + 1:] if isinstance(item, dict)), None) + if mapping is not None: + walk(mapping, "") + return specs + + +class ModulePlan: + """Layer-relative inventory and role queries for one effective model tree.""" + + def __init__(self, specs: Mapping[str, ModuleSpec]): + self._specs = dict(specs) + self._by_parent: Dict[str, List[ModuleSpec]] = {} + for spec in self._specs.values(): + self._by_parent.setdefault(spec.parent, []).append(spec) + + @classmethod + def from_tree(cls, module_tree: Any) -> "ModulePlan": + return cls(collect_module_specs(module_tree)) + + @property + def specs(self) -> Tuple[ModuleSpec, ...]: + return tuple(self._specs.values()) + + def find(self, path: str) -> Optional[ModuleSpec]: + spec = self._specs.get(path) + if spec is not None: + return spec + return next((candidate for candidate in self._specs.values() if candidate.matches(path)), None) + + def is_moe(self, path: str) -> bool: + spec = self.find(path) + if spec is None: + return False + if spec.is_moe: + return True + return any(_path_has_segment(spec.template, moe.template) for moe in self.moe_roots()) + + def roles(self, path: str) -> Tuple[str, ...]: + spec = self.find(path) + return () if spec is None else spec.roles + + def is_expert(self, path: str) -> bool: + if not isinstance(path, str) or not path: + return False + for container in self.expert_containers(): + prefix = container.split(f".{_EXPERT_PLACEHOLDER}", 1)[0] + if not path.startswith(f"{prefix}."): + continue + remainder = path[len(prefix) + 1:] + parts = remainder.split(".") + if parts and parts[0].isdigit(): + return True + return False + + def moe_roots(self) -> Tuple[ModuleSpec, ...]: + return tuple(spec for spec in self._specs.values() if spec.is_moe) + + def expert_containers(self) -> Tuple[str, ...]: + containers = { + spec.template.rsplit(f".{_EXPERT_PLACEHOLDER}", 1)[0] + for spec in self._specs.values() + if spec.is_expert_placeholder + } + return tuple(sorted(containers)) + + def shared_expert_containers(self) -> Tuple[str, ...]: + """Return declared non-routed projection containers beneath a MoE root. + + This is inferred from tree structure, not names: any direct projection + family under the MoE root that is not the routed-expert placeholder is + a shared/parallel expert family (for example ``shared_experts`` or + ``shared_mlp``). Router gates have no projection roles and are excluded. + """ + expert_containers = set(self.expert_containers()) + containers = set() + for moe in self.moe_roots(): + for spec in self._specs.values(): + if spec.parent == moe.template or not spec.roles: + continue + if not _path_has_segment(spec.template, moe.template): + continue + container = spec.parent + if container in expert_containers or _EXPERT_PLACEHOLDER in container: + continue + containers.add(container) + return tuple(sorted(containers)) + + def role_paths_in_parent(self, parent: str, role: str) -> Tuple[str, ...]: + """Return concrete paths for one role under a concrete parent path.""" + matched = [] + for spec in self._by_parent.get(parent, ()): + if role in spec.roles: + matched.append(spec.template) + return tuple(matched) + + def child_roles(self, parent: str, role: str) -> Tuple[str, ...]: + """Return direct child names that carry ``role`` under a declared parent.""" + return tuple( + spec.template.rsplit(".", 1)[-1] if "." in spec.template else spec.template + for spec in self._by_parent.get(parent, ()) + if role in spec.roles + ) + + def direct_child(self, parent: str, name: str) -> bool: + return any(leaf.template == f"{parent}.{name}" for leaf in self._by_parent.get(parent, ())) + + def concrete_paths(self, template_parent: str, concrete_parent: str) -> Tuple[str, ...]: + """Swap a declared parent template for its concrete, expanded parent path.""" + paths = [] + for spec in self._by_parent.get(template_parent, ()): + leaf = spec.template.rsplit(".", 1)[-1] if "." in spec.template else spec.template + paths.append(_join(concrete_parent, leaf)) + return tuple(paths) + + def shared_container_leaf(self, moe_root: str) -> Optional[str]: + for container in self.shared_expert_containers(): + if container == moe_root or container.startswith(f"{moe_root}."): + relative = container[len(moe_root) + 1:] if container != moe_root else "" + if relative: + return relative.split(".", 1)[0] + return None + + def expert_container_leaf(self, moe_root: str) -> Optional[str]: + for container in self.expert_containers(): + if container == moe_root or container.startswith(f"{moe_root}."): + relative = container[len(moe_root) + 1:] if container != moe_root else "" + if relative: + return relative.split(".", 1)[0] + return None + + def expert_root(self, path: str) -> Optional[str]: + """Return the expert family path containing a concrete expert leaf.""" + for container in self.expert_containers(): + prefix = container.split(f".{_EXPERT_PLACEHOLDER}", 1)[0] + if not _path_has_segment(path, prefix): + continue + remainder = path[len(prefix) + 1:] + parts = remainder.split(".") + if parts and parts[0].isdigit(): + return f"{prefix}.{parts[0]}" + return None + + def same_moe_family(self, left: str, right: str) -> bool: + """Return whether two expert leaves belong to the same expanded expert.""" + left_root, right_root = self.expert_root(left), self.expert_root(right) + return left_root is not None and left_root == right_root + + +def _path_has_segment(path: str, parent: str) -> bool: + return path == parent or path.startswith(f"{parent}.") diff --git a/gptqmodel/models/moe_lifecycle.py b/gptqmodel/models/moe_lifecycle.py index 9bb2c36eec..8f8e0553fa 100644 --- a/gptqmodel/models/moe_lifecycle.py +++ b/gptqmodel/models/moe_lifecycle.py @@ -10,7 +10,7 @@ customization of MoE forward passes and routing logic during quantization. """ -from typing import Any, Dict, Optional +from typing import TYPE_CHECKING, Any, Dict, Optional import torch import torch.nn as nn @@ -24,6 +24,33 @@ log = setup_logger() +if TYPE_CHECKING: + from .module_plan import ModulePlan + + +def _module_plan(model_class) -> Optional["ModulePlan"]: + """Return the exact tree plan for a live wrapper or definition class.""" + if model_class is None: + return None + plan = getattr(model_class, "module_plan", None) + if plan is not None: + return plan + module_tree = getattr(model_class, "module_tree", None) + if module_tree is None: + return None + from .module_plan import ModulePlan + return ModulePlan.from_tree(module_tree) + + +def _bind_hooks_plan(hooks, model_class): + """Bind a definition's tree plan to its lifecycle hook object.""" + if hooks is None or model_class is None: + return + plan = _module_plan(model_class) + if plan is not None: + hooks.module_plan = plan + + def _get_module_by_relative_path(parent: nn.Module, relative_path: str) -> Optional[nn.Module]: """ Get a submodule from a parent module by relative path. @@ -70,11 +97,11 @@ class MoELifecycleHooks: Main use case: Forward whole calibration dataset to all experts instead of only routed ones. """ - # List of possible expert block names that models can override - expert_block_names = ['experts'] - - # List of possible shared expert block names that models can override - shared_expert_block_names = ['shared_experts', 'shared_expert'] + # Legacy overrides for definitions whose tree predates explicit MoE + # container paths. New definitions should tag ``experts``/``shared_*`` + # leaves so the module plan can resolve them exactly. + expert_block_names = () + shared_expert_block_names = () def get_moe_block(self, layer_module: nn.Module, model_class: type) -> Optional[nn.Module]: """ @@ -99,7 +126,11 @@ def get_moe_block(self, layer_module: nn.Module, model_class: type) -> Optional[ return None # Get the module by name - moe_block = getattr(layer_module, moe_module_name[0], None) + moe_block = layer_module + for part in moe_module_name[0].split("."): + moe_block = getattr(moe_block, part, None) + if moe_block is None: + return None return moe_block @@ -131,7 +162,15 @@ def get_experts_module(self, moe_block: nn.Module, model_class: type) -> Optiona Example: Returns moe_block.experts if it exists """ - # Use the helper to get the attribute name + plan = getattr(self, "module_plan", None) or _module_plan(model_class) + if plan is not None: + for root in plan.moe_roots(): + container = plan.expert_container_leaf(root.template) + if container and hasattr(moe_block, container): + return getattr(moe_block, container) + return None + + # Legacy hooks without a tree plan may explicitly declare container names. name = self.get_experts_module_name(moe_block) if name: experts_module = getattr(moe_block, name) @@ -154,7 +193,15 @@ def get_experts_module_name(self, moe_block: nn.Module) -> Optional[str]: if name: experts = getattr(moe_block, name) """ - # Try expert container attribute names from the class attribute + plan = getattr(self, "module_plan", None) + if plan is not None: + for root in plan.moe_roots(): + container = plan.expert_container_leaf(root.template) + if container and hasattr(moe_block, container): + return container + return None + + # Legacy hooks without a tree plan may explicitly declare container names. for name in self.expert_block_names: if hasattr(moe_block, name): return name @@ -175,7 +222,15 @@ def get_shared_experts_module_name(self, moe_block: nn.Module) -> Optional[str]: if name: shared_experts = getattr(moe_block, name) """ - # Try shared expert container attribute names from the class attribute + plan = getattr(self, "module_plan", None) or _module_plan(self) + if plan is not None: + for root in plan.moe_roots(): + container = plan.shared_container_leaf(root.template) + if container and hasattr(moe_block, container): + return container + return None + + # Legacy hooks without a tree plan may explicitly declare container names. for name in self.shared_expert_block_names: if hasattr(moe_block, name): return name diff --git a/gptqmodel/models/writer.py b/gptqmodel/models/writer.py index d9fa189a67..3f6d26cae2 100644 --- a/gptqmodel/models/writer.py +++ b/gptqmodel/models/writer.py @@ -65,7 +65,7 @@ from ..utils.structure import alias_all_from_turtle_if_meta, alias_from_turtle_for_submodule from ..utils.torch import torch_empty_cache from ..version import __version__ -from ._const import DEFAULT_MAX_SHARD_SIZE, DEVICE +from ._const import DEFAULT_MAX_SHARD_SIZE, DEVICE, EXPERT_INDEX_PLACEHOLDER log = setup_logger() @@ -1319,9 +1319,27 @@ def get_model_with_quantize(self, qcfg, model_id_or_path): if qcfg.lm_head and name == self.lm_head: continue - if any(name.startswith(ignore_module) for ignore_module in ignore_modules) or all( - not name.endswith(ignore_module) for sublist in self.simple_layer_modules(config, qcfg) for ignore_module in sublist - ): + declared = { + item.split(":", 1)[0] + for sublist in self.simple_layer_modules(config, qcfg) + for item in sublist + } + layer_prefix = next( + (f"{prefix}." for prefix in self.extract_layers_node() if name.startswith(f"{prefix}.")), + None, + ) + relative = name[len(layer_prefix):] if layer_prefix is not None else None + if relative is not None: + layer_index, separator, remainder = relative.partition(".") + relative = remainder if separator and layer_index.isdigit() else relative + relative_match = relative is not None and any( + relative == leaf or (relative.startswith(f"{leaf}.") and EXPERT_INDEX_PLACEHOLDER in leaf) + for leaf in declared + ) + if any( + name == ignore_module or name.startswith(f"{ignore_module}.") + for ignore_module in ignore_modules + ) or not relative_match: # log non-lm-head quantizerd modules only if name is not self.lm_head: log.info(f"The layer {name} is not quantized.") diff --git a/gptqmodel/quantization/awq/utils/utils.py b/gptqmodel/quantization/awq/utils/utils.py index 8f3c08b932..634e7895c4 100644 --- a/gptqmodel/quantization/awq/utils/utils.py +++ b/gptqmodel/quantization/awq/utils/utils.py @@ -8,6 +8,8 @@ import accelerate import torch +from ....utils.model import get_module_by_name_suffix + ipex_available = importlib.util.find_spec("intel_extension_for_pytorch") is not None try: @@ -17,12 +19,6 @@ -def get_module_by_name_suffix(model, module_name: str): - for name, module in model.named_modules(): - if name.endswith(module_name): - return module - - def simple_dispatch_model(model, device_map): from accelerate.hooks import AlignDevicesHook, add_hook_to_module diff --git a/gptqmodel/quantization/gsq_training.py b/gptqmodel/quantization/gsq_training.py index 3d3306e66b..7a08841a3a 100644 --- a/gptqmodel/quantization/gsq_training.py +++ b/gptqmodel/quantization/gsq_training.py @@ -154,9 +154,11 @@ def resolve_projection_bits(bits, projections=LLAMA_STAGED_PROJECTIONS): Non-uniform bit allocation (the output of a budget-constrained search such as RCO) is only actionable if a single block can be exported at different - widths per projection, so this accepts either a single width applied to all - seven Llama projections or an explicit mapping. Every requested projection - must be known and every width must be on the staged scalar grid. + widths per projection, so this accepts either a single width applied to the + supplied projections or an explicit mapping. Every requested projection + must be known and every width must be on the staged scalar grid. The default + preserves the Llama seven-projection public contract; model-driven callers + pass the declared inventory from ``module_tree``. """ if isinstance(bits, dict): unknown = set(bits)-set(projections) @@ -857,8 +859,10 @@ def fit_llama_stages(layer, initializers, batches, *, bits, group_size, epochs, qk_steps=2000, qk_damp_percent=.01, reinitialize_mlp=True, initializer='gptq', batch_size=1, microbatch_size=1, affine_initializers=False, initialization_batches=None, validation_batches=None, distributed=None, - target_cache='none', activation_checkpointing=False, **training): - """Fit a Llama block in author stage order from supplied scalar initializers. + target_cache='none', activation_checkpointing=False, + projections=None, attention_projections=None, mlp_projections=None, + **training): + """Fit a dense decoder block in the staged GSQ author order. Batches are (hidden_states, attention_kwargs) pairs without padding. Caller owns GPTQ initialization, disjoint data preparation, packing and evaluation. @@ -898,10 +902,25 @@ def fit_llama_stages(layer, initializers, batches, *, bits, group_size, epochs, has_attention_mask = any(kwargs.get('attention_mask') is not None for _, kwargs in source) if len(lengths) != 1 or has_attention_mask: raise ValueError('SDPA staged GSQ requires equal-length documents without explicit attention masks') - names = ('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') + if projections is None and attention_projections is None and mlp_projections is None: + names = LLAMA_STAGED_PROJECTIONS + attention_projections = names[:4] + mlp_projections = names[4:] + else: + names = tuple(projections or LLAMA_STAGED_PROJECTIONS) + if attention_projections is None: + attention_projections = names[:4] + if mlp_projections is None: + mlp_projections = names[len(attention_projections):] + attention_projections = tuple(attention_projections) + mlp_projections = tuple(mlp_projections) + if not attention_projections or not mlp_projections: + raise ValueError('Staged GSQ requires nonempty attention and MLP projection groups') + grouped = tuple(attention_projections) + tuple(mlp_projections) + if set(grouped) != set(names): + raise ValueError('Staged GSQ projection groups must partition the declared inventory exactly') if set(initializers) != set(names) or not batches: - raise ValueError('Dense-decoder GSQ requires all seven projection initializers and nonempty batches') + raise ValueError('Dense-decoder GSQ requires an initializer for every declared projection and nonempty batches') width = resolve_projection_bits(bits, names) initializers = dict(initializers) initialization_batches = batches if initialization_batches is None else initialization_batches @@ -922,9 +941,9 @@ def quantizer(name): from .gsq_training_affine import GSQAffineTrainingModule return GSQAffineTrainingModule(codes, scales, zeros, group_size, bits=nbits, noise=noise, - logits_dtype=torch.float32 if name in names[:2] else weight.dtype) + logits_dtype=torch.float32 if name in attention_projections[:2] else weight.dtype) return GSQScalarTrainingModule(weight, scales, group_size, bits=nbits, noise=noise, - logits_dtype=torch.float32 if name in names[:2] else weight.dtype) + logits_dtype=torch.float32 if name in attention_projections[:2] else weight.dtype) def run(stage_name, stage, selected, stage_batches, teacher=None, validation_stage_batches=None): quantizers = {name+'.weight': quantizer(name) for name in selected} @@ -994,7 +1013,7 @@ def train_qk(): qk_inputs, damp_percent=qk_damp_percent, device=device, transform=fitted.input_layernorm, ) results = {} - for name in names[:2]: + for name in attention_projections[:2]: projection = fitted.get_submodule(name) quant = quantizer(name) qk_option_names = ( @@ -1050,24 +1069,24 @@ def prepare_stage_batches(source): # reconstruction target. Its student uses fitted Q/K and learns V/O. dense_attention = { f'{name}.weight': layer.get_submodule(name).weight.detach() - for name in names[:4] + for name in attention_projections } - run('attention', LlamaGSQAttentionStage(fitted), names[2:4], staged_batches, + run('attention', LlamaGSQAttentionStage(fitted), attention_projections[2:], staged_batches, teacher=dense_attention, validation_stage_batches=validation_stage_batches) mlp_metadata = None if reinitialize_mlp: def refresh_mlp(): return initialize_llama_gptq(fitted, initialization_batches, - bits={name: width[name] for name in names[4:]}, + bits={name: width[name] for name in mlp_projections}, group_size=group_size, damp_percent=qk_damp_percent, - projections=names[4:], initializer=initializer) + projections=mlp_projections, initializer=initializer) refreshed, mlp_metadata = (refresh_mlp() if distributed is None else distributed.primary_call(refresh_mlp)) initializers.update(refreshed) # The block target also uses original dense attention and dense MLP; # the student uses fitted attention and learns the three MLP projections. - run('mlp', fitted, names[4:], staged_batches, teacher=dense_attention, + run('mlp', fitted, mlp_projections, staged_batches, teacher=dense_attention, validation_stage_batches=validation_stage_batches) records['mlp']['initializer_timing'] = 'after_attention' if reinitialize_mlp else 'before_attention' records['mlp']['initializer_metadata'] = mlp_metadata @@ -1093,8 +1112,7 @@ def initialize_llama_gptq(layer, batches, *, bits, group_size, damp_percent=.01, raise ValueError('Unknown staged GPTQ initializer') working = copy.deepcopy(layer).eval() tasks, handles = {}, [] - names = ('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') + names = LLAMA_STAGED_PROJECTIONS if projections is not None: if not projections or not set(projections).issubset(names): raise ValueError('Unsupported Llama GPTQ projection subset') @@ -1278,7 +1296,7 @@ def objective(_batch, weights): decay='constant', optimizer=optimizer) -def pack_llama_staged_block(fitted, records, *, bits, group_size): +def pack_llama_staged_block(fitted, records, *, bits, group_size, projections=None, attention_projections=None): """Export a fitted Llama block to portable Torch GPTQ modules on CPU. This is a block export helper, not a complete checkpoint writer. Scale @@ -1292,12 +1310,12 @@ def pack_llama_staged_block(fitted, records, *, bits, group_size): from ..utils.backend import BACKEND exported = copy.deepcopy(fitted).cpu() - names = ('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') + names = tuple(projections or LLAMA_STAGED_PROJECTIONS) + attention = tuple(attention_projections or names[:4]) width = resolve_projection_bits(bits, names) for name in names: nbits = width[name] - stage = name if name in records else ('attention' if name.startswith('self_attn.') else 'mlp') + stage = name if name in records else ('attention' if name in attention else 'mlp') key = 'weight' if stage == name else name+'.weight' scales = records[stage]['scales'][key].detach().cpu() if not torch.isfinite(scales).all() or (scales == 0).any(): @@ -1315,7 +1333,8 @@ def pack_llama_staged_block(fitted, records, *, bits, group_size): def quantize_llama_gsq_block(layer, batches, *, bits, group_size, gsq=None, pack=True, initialization_batches=None, validation_batches=None, distributed=None, - target_cache='none', activation_checkpointing=False): + target_cache='none', activation_checkpointing=False, + projections=None, attention_projections=None, mlp_projections=None): """Quantize one captured Llama block, optionally train GSQ, then export. The default performs ordinary GPTQ initialization. Enabled staged GSQ has @@ -1333,7 +1352,8 @@ def quantize_llama_gsq_block(layer, batches, *, bits, group_size, gsq=None, pack if not isinstance(gsq, GSQTrainingConfig): raise TypeError('Staged GSQ requires GSQTrainingConfig, a dictionary or None') effective = gsq.to_dict() - width = resolve_projection_bits(bits) + declared = tuple(projections or LLAMA_STAGED_PROJECTIONS) + width = resolve_projection_bits(bits, declared) if isinstance(group_size, bool) or not isinstance(group_size, int) or group_size <= 0: raise ValueError('Staged scalar GSQ requires a positive contiguous group size') if not isinstance(pack, bool): @@ -1342,7 +1362,7 @@ def quantize_llama_gsq_block(layer, batches, *, bits, group_size, gsq=None, pack def initialize(): return initialize_llama_gptq(layer, initialization_batches, bits=width, group_size=group_size, damp_percent=gsq.damp_percent, - initializer=gsq.initializer) + initializer=gsq.initializer, projections=declared) initializers, metadata = initialize() if distributed is None else distributed.primary_call(initialize) if gsq.enabled: @@ -1350,6 +1370,9 @@ def initialize(): initialization_batches=initialization_batches, validation_batches=validation_batches, distributed=distributed, target_cache=target_cache, activation_checkpointing=activation_checkpointing, + projections=declared, + attention_projections=attention_projections, + mlp_projections=mlp_projections, **gsq.training_kwargs()) else: fitted = copy.deepcopy(layer).eval() @@ -1357,7 +1380,13 @@ def initialize(): for name, (weight, _) in initializers.items(): fitted.get_submodule(name).weight.copy_(weight) records = {name: {'scales': {'weight': scales}} for name, (_, scales) in initializers.items()} - exported = pack_llama_staged_block(fitted, records, bits=width, group_size=group_size) if pack else fitted + if pack: + exported = pack_llama_staged_block( + fitted, records, bits=width, group_size=group_size, projections=declared, + attention_projections=attention_projections, + ) + else: + exported = fitted return exported, {'gsq_training': effective, 'bits': bits, 'group_size': group_size, 'projection_bits': width, 'packed': pack, 'deterministic_algorithms': torch.are_deterministic_algorithms_enabled(), diff --git a/gptqmodel/quantization/gsq_training_affine.py b/gptqmodel/quantization/gsq_training_affine.py index aef0322fdd..043c02eb12 100644 --- a/gptqmodel/quantization/gsq_training_affine.py +++ b/gptqmodel/quantization/gsq_training_affine.py @@ -96,8 +96,9 @@ def prepare_affine_export(codes, scales, zeros, group_index, *, bits, packing, s return {'weight': weight, 'scales': scales, 'zeros': zeros, 'g_idx': groups, 'codes': codes} -def pack_llama_affine_stages(fitted, records, *, group_size, scale_dtype=torch.float16): - """Pack all seven fitted affine projections through the CPU AWQ GEMM path. +def pack_llama_affine_stages(fitted, records, *, group_size, scale_dtype=torch.float16, + projections=None, attention_projections=None): + """Pack fitted affine projections through the CPU AWQ GEMM path. Caller owns transformed teacher capture, AWQ initialization and replay. The supplied fitted block and records are never modified. @@ -107,10 +108,13 @@ def pack_llama_affine_stages(fitted, records, *, group_size, scale_dtype=torch.f from ..nn_modules.qlinear.torch_awq import AwqTorchLinear exported = copy.deepcopy(fitted).cpu() - names = ('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') + names = tuple(projections or ( + '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', + )) + attention = tuple(attention_projections or names[:4]) for name in names: - stage = name if name in records else ('attention' if name.startswith('self_attn.') else 'mlp') + stage = name if name in records else ('attention' if name in attention else 'mlp') key = 'weight' if stage == name else name+'.weight' record = records[stage] linear = exported.get_submodule(name) diff --git a/gptqmodel/quantization/rotation/rotation.py b/gptqmodel/quantization/rotation/rotation.py index 7e15b40de0..d655372eb4 100644 --- a/gptqmodel/quantization/rotation/rotation.py +++ b/gptqmodel/quantization/rotation/rotation.py @@ -9,6 +9,7 @@ import torch from transformers import PreTrainedModel +from ...models.module_plan import ModulePlan from ...utils.logger import setup_logger from ...utils.model import get_module_by_name_prefix from ...utils.torch import torch_empty_cache @@ -47,25 +48,74 @@ def reset_ln(ln): ln.weight.data = torch.ones_like(W_norm) -def fuse_layer_norms(model: PreTrainedModel, pre_lm_head_norm_module_name: str, layers_node: str, lm_head_name: str): +def _relative_roles(plan: ModulePlan, parent: str, role: str) -> list[str]: + return list(plan.child_roles(parent, role)) + + +def _resolve_role(layer, plan: ModulePlan, parent: str, role: str): + names = _relative_roles(plan, parent, role) + if len(names) != 1: + raise ValueError(f"Rotation requires exactly one `:{role}` projection under {parent or ''}, found {names}") + path = f"{parent}.{names[0]}" if parent else names[0] + try: + return layer.get_submodule(path) + except AttributeError as exc: + raise ValueError(f"Rotation declared `:{role}` module is missing: {path}") from exc + + +def _default_rotation_plan() -> ModulePlan: + return ModulePlan.from_tree([ + "model", "layers", "#", + { + "input_layernorm": ("input_layernorm:!:norm",), + "self_attn": ("q_proj:0:q", "k_proj:0:k", "v_proj:0:v", "o_proj:1:o"), + "post_attention_layernorm": ("post_attention_layernorm:!:norm",), + "mlp": ("gate_proj:0:gate", "up_proj:0:up", "down_proj:1:down"), + }, + ]) + + +def _rotation_parents(plan: ModulePlan): + attn_parents = { + spec.parent for spec in plan.specs + if "q" in spec.roles and spec.parent and "." not in spec.parent + } + mlp_parents = { + spec.parent for spec in plan.specs + if "gate" in spec.roles and spec.parent and "." not in spec.parent + } + if len(attn_parents) != 1 or len(mlp_parents) != 1: + raise ValueError("Rotation requires one declared attention parent and one MLP parent in module_tree") + return next(iter(attn_parents)), next(iter(mlp_parents)) + + +def fuse_layer_norms(model: PreTrainedModel, pre_lm_head_norm_module_name: str, layers_node: str, lm_head_name: str, + plan: ModulePlan = None): layers , _ = get_module_by_name_prefix(model, layers_node) + plan = plan or _default_rotation_plan() + norm_roles = plan.child_roles("", "norm") + if len(norm_roles) != 2: + raise ValueError(f"Rotation requires two declared layer norms, found {list(norm_roles)}") + input_norm, post_norm = norm_roles + attn_parent, mlp_parent = _rotation_parents(plan) # Fuse the linear operations in Layernorm into the adjacent linear blocks. for layer in layers: # fuse the input layernorms into the linear layers fuse_ln_linear( - layer.post_attention_layernorm, [layer.mlp.up_proj, layer.mlp.gate_proj] + layer.get_submodule(post_norm), + [_resolve_role(layer, plan, mlp_parent, "up"), _resolve_role(layer, plan, mlp_parent, "gate")], ) fuse_ln_linear( - layer.input_layernorm, + layer.get_submodule(input_norm), [ - layer.self_attn.q_proj, - layer.self_attn.k_proj, - layer.self_attn.v_proj, + _resolve_role(layer, plan, attn_parent, "q"), + _resolve_role(layer, plan, attn_parent, "k"), + _resolve_role(layer, plan, attn_parent, "v"), ], ) - reset_ln(layer.post_attention_layernorm) - reset_ln(layer.input_layernorm) + reset_ln(layer.get_submodule(post_norm)) + reset_ln(layer.get_submodule(input_norm)) pre_head_layernorm, _ = get_module_by_name_prefix(model, pre_lm_head_norm_module_name) lm_head, _ = get_module_by_name_prefix(model, lm_head_name) @@ -104,29 +154,37 @@ def get_orthogonal_matrix(size, mode, device): raise ValueError(f"Unknown mode {mode}") -def get_embeddings(model) -> list[torch.nn.Module]: - return [model.model.embed_tokens] +def get_embeddings(model, embedding_name: str = None) -> list[torch.nn.Module]: + if embedding_name is not None: + return [model.get_submodule(embedding_name)] + getter = getattr(model, "get_input_embeddings", None) + return [getter()] if callable(getter) else [model.model.embed_tokens] -def rotate_embeddings(model, Q, device) -> None: +def rotate_embeddings(model, Q, device, embedding_name: str = None) -> None: # Rotate the embeddings. - for W in get_embeddings(model): + for W in get_embeddings(model, embedding_name=embedding_name): dtype = W.weight.data.dtype W_ = W.weight.data.to(device=device, dtype=torch.float64) W.weight.data = torch.matmul(W_, Q).to(device="cpu", dtype=dtype) -def rotate_attention_inputs(layer, Q, device) -> None: +def rotate_attention_inputs(layer, Q, device, plan: ModulePlan = None, attn_parent: str = None) -> None: # Rotate the WQ, WK and WV matrices of the self-attention layer. - for W in [layer.self_attn.q_proj, layer.self_attn.k_proj, layer.self_attn.v_proj]: + if plan is None or attn_parent is None: + raise ValueError("Rotation requires an explicit attention parent from module_tree") + inputs = [_resolve_role(layer, plan, attn_parent, role) for role in ("q", "k", "v")] + for W in inputs: dtype = W.weight.dtype W_ = W.weight.to(device=device, dtype=torch.float64) W.weight.data = torch.matmul(W_, Q).to(device="cpu", dtype=dtype) -def rotate_attention_output(layer, Q, device) -> None: +def rotate_attention_output(layer, Q, device, plan: ModulePlan = None, attn_parent: str = None) -> None: # Rotate output matrix of the self-attention layer. - W = layer.self_attn.o_proj + if plan is None or attn_parent is None: + raise ValueError("Rotation requires an explicit attention parent from module_tree") + W = _resolve_role(layer, plan, attn_parent, "o") dtype = W.weight.data.dtype W_ = W.weight.data.to(device=device, dtype=torch.float64) W.weight.data = torch.matmul(Q.T, W_).to(device="cpu", dtype=dtype) @@ -135,18 +193,22 @@ def rotate_attention_output(layer, Q, device) -> None: W.bias.data = torch.matmul(Q.T, b).to(device="cpu", dtype=dtype) -def rotate_mlp_input(layer, Q, device): +def rotate_mlp_input(layer, Q, device, plan: ModulePlan = None, mlp_parent: str = None): # Rotate the MLP input weights. - mlp_inputs = [layer.mlp.up_proj, layer.mlp.gate_proj] + if plan is None or mlp_parent is None: + raise ValueError("Rotation requires an explicit MLP parent from module_tree") + mlp_inputs = [_resolve_role(layer, plan, mlp_parent, role) for role in ("up", "gate")] for W in mlp_inputs: dtype = W.weight.dtype W_ = W.weight.data.to(device=device, dtype=torch.float64) W.weight.data = torch.matmul(W_, Q).to(device="cpu", dtype=dtype) -def rotate_mlp_output(layer, Q, device): +def rotate_mlp_output(layer, Q, device, plan: ModulePlan = None, mlp_parent: str = None): # Rotate the MLP output weights and bias. - W = layer.mlp.down_proj + if plan is None or mlp_parent is None: + raise ValueError("Rotation requires an explicit MLP parent from module_tree") + W = _resolve_role(layer, plan, mlp_parent, "down") dtype = W.weight.data.dtype W_ = W.weight.data.to(device=device, dtype=torch.float64) W.weight.data = torch.matmul(Q.T, W_).to(device="cpu", dtype=dtype) @@ -175,9 +237,11 @@ def rotate_head(model, Q, device, lm_head_name) -> None: W.weight.data = torch.matmul(W_, Q).to(device="cpu", dtype=dtype) -def rotate_ov_proj(layer, head_num, head_dim): - v_proj = layer.self_attn.v_proj - o_proj = layer.self_attn.o_proj +def rotate_ov_proj(layer, head_num, head_dim, plan: ModulePlan = None, attn_parent: str = None): + if plan is None or attn_parent is None: + raise ValueError("Rotation requires an explicit attention parent from module_tree") + v_proj = _resolve_role(layer, plan, attn_parent, "v") + o_proj = _resolve_role(layer, plan, attn_parent, "o") apply_exact_had_to_linear(v_proj, had_dim=head_dim, output=True) # apply_exact_had_to_linear(o_proj, had_dim=-1, output=False) apply_exact_had_to_linear(o_proj, had_dim=head_dim, output=False) @@ -185,7 +249,7 @@ def rotate_ov_proj(layer, head_num, head_dim): @torch.inference_mode() def rotate_model(model: PreTrainedModel, rotate_mode: str, device: torch.device, lm_head_name: str, - layers_node: str, Q=None): + layers_node: str, Q=None, plan: ModulePlan = None, embedding_name: str = None): Q = ( get_orthogonal_matrix( model.config.hidden_size, rotate_mode, device @@ -198,14 +262,16 @@ def rotate_model(model: PreTrainedModel, rotate_mode: str, device: torch.device, model_dim = config.hidden_size head_dim = model_dim // num_heads - rotate_embeddings(model, Q, device) + rotate_embeddings(model, Q, device, embedding_name=embedding_name) rotate_head(model, Q, device, lm_head_name) torch_empty_cache() layers , _ = get_module_by_name_prefix(model, layers_node) + plan = plan or _default_rotation_plan() + attn_parent, mlp_parent = _rotation_parents(plan) for idx, layer in enumerate(log.pb(layers).title("Rotating")): - rotate_attention_inputs(layer, Q, device) - rotate_attention_output(layer, Q, device) - rotate_mlp_input(layer, Q, device) - rotate_mlp_output(layer, Q, device) - rotate_ov_proj(layer, num_heads, head_dim) + rotate_attention_inputs(layer, Q, device, plan=plan, attn_parent=attn_parent) + rotate_attention_output(layer, Q, device, plan=plan, attn_parent=attn_parent) + rotate_mlp_input(layer, Q, device, plan=plan, mlp_parent=mlp_parent) + rotate_mlp_output(layer, Q, device, plan=plan, mlp_parent=mlp_parent) + rotate_ov_proj(layer, num_heads, head_dim, plan=plan, attn_parent=attn_parent) return model, Q diff --git a/gptqmodel/utils/model.py b/gptqmodel/utils/model.py index e1822a5dd3..3d8d87f1a8 100644 --- a/gptqmodel/utils/model.py +++ b/gptqmodel/utils/model.py @@ -321,11 +321,31 @@ def get_module_by_name(module, child_name): def get_module_by_name_prefix(model, module_name: Union[List[str], str]): + """Resolve the first path that is exactly ``prefix`` or a dotted descendant. + + A plain ``startswith`` test treats ``mlp_extra`` as ``mlp`` and can silently + select a sibling instead of the declared module. Prefer an exact path, then + reject ambiguous descendant matches instead of choosing among them. + """ module_name_list = module_name if isinstance(module_name, list) else [module_name] - for name, module in model.named_modules(): - for prefix in module_name_list: - if name.startswith(prefix): - return module, prefix + modules = dict(model.named_modules()) + for prefix in module_name_list: + if isinstance(prefix, str) and prefix in modules: + return modules[prefix], prefix + for prefix in module_name_list: + if not isinstance(prefix, str) or not prefix: + continue + matches = [ + (name, module) + for name, module in modules.items() + if name.startswith(f"{prefix}.") + ] + if len(matches) == 1: + return matches[0][1], prefix + if len(matches) > 1: + raise ValueError( + f"Ambiguous module prefix {prefix!r}: matches {[name for name, _ in matches[:8]]}" + ) return None, "" @@ -439,9 +459,28 @@ def get_layer_name(layer_names: Union[List[str], str, None], layer_index: int) - def get_module_by_name_suffix(model, module_name: str): - for name, module in model.named_modules(): - if name.endswith(module_name): - return module + """Resolve a path suffix at a dotted segment boundary. + + Exact paths win. Multiple suffix matches are an error: returning the first + one makes device placement and quantization depend on module registration + order. + """ + modules = dict(model.named_modules()) + exact = modules.get(module_name) + if exact is not None: + return exact + matches = [ + (name, module) + for name, module in modules.items() + if name.endswith(f".{module_name}") + ] + if len(matches) == 1: + return matches[0][1] + if len(matches) > 1: + raise ValueError( + f"Ambiguous module suffix {module_name!r}: matches {[name for name, _ in matches[:8]]}" + ) + return None def get_module(module, key): """Get module from model by key name. diff --git a/tests/module_tree/test_auto_detect.py b/tests/module_tree/test_auto_detect.py index 39179a726e..a3d1fe6a56 100644 --- a/tests/module_tree/test_auto_detect.py +++ b/tests/module_tree/test_auto_detect.py @@ -33,7 +33,7 @@ def __init__(self): class TestAutoDetectModuleTree(unittest.TestCase): - def test_layers_with_parents(self): + def test_diagnostic_tree_detection_remains_available(self): model = DummyModel() base = BaseQModel.__new__(BaseQModel) tree = base._auto_detect_module_tree(model, quant_method="gptq") diff --git a/tests/module_tree/test_explicit_module_plan.py b/tests/module_tree/test_explicit_module_plan.py new file mode 100644 index 0000000000..195f96cb8b --- /dev/null +++ b/tests/module_tree/test_explicit_module_plan.py @@ -0,0 +1,125 @@ +# SPDX-FileCopyrightText: 2026 ModelCloud.ai +# SPDX-License-Identifier: Apache-2.0 + +import torch.nn as nn + +from gptqmodel.models.base import BaseQModel +from gptqmodel.models.module_plan import ModulePlan +from gptqmodel.utils.model import get_module_by_name_prefix, get_module_by_name_suffix + + +class _ToyModel(nn.Module): + def __init__(self): + super().__init__() + self.model = nn.Module() + self.model.layers = nn.ModuleList([nn.Module()]) + layer = self.model.layers[0] + layer.mlp = nn.Module() + layer.mlp.gate_proj = nn.Linear(2, 2) + layer.mlp.up_proj = nn.Linear(2, 2) + layer.mlp.down_proj = nn.Linear(2, 2) + layer.mlp_extra = nn.Linear(2, 2) + + +def test_prefix_resolution_rejects_sibling_prefix(): + model = _ToyModel() + module, matched = get_module_by_name_prefix(model, "model.layers.0.mlp") + assert module is model.model.layers[0].mlp + assert matched == "model.layers.0.mlp" + + +def test_prefix_resolution_prefers_the_exact_container(): + root = nn.Module() + root.a = nn.Module() + root.a.one = nn.Linear(1, 1) + root.a.two = nn.Linear(1, 1) + module, matched = get_module_by_name_prefix(root, "a") + assert module is root.a + assert matched == "a" + + +def test_prefix_resolution_does_not_match_similarly_named_siblings(): + model = _ToyModel() + module, _ = get_module_by_name_prefix(model, "model.layers.0.mlp") + assert module is model.model.layers[0].mlp + module, _ = get_module_by_name_prefix(model, "model.layers.0.mlp.extra") + assert module is None + + +def test_suffix_resolution_requires_segment_boundary(): + root = nn.Module() + root.alpha = nn.Module() + root.alpha.proj = nn.Linear(1, 1) + assert get_module_by_name_suffix(root, "proj") is root.alpha.proj + assert get_module_by_name_suffix(root, "alpha.pro") is None + + +def test_module_plan_resolves_roles_without_live_name_heuristics(): + plan = ModulePlan.from_tree([ + "model", + "layers", + "#", + { + "self_attn": ("q_proj:0", "k_proj:0", "v_proj:0", "o_proj:1"), + "mlp:moe": { + "experts": {"#": ("gate_proj:0", "up_proj:0", "down_proj:1")}, + "shared_mlp": ("gate_proj:0", "up_proj:0", "down_proj:1"), + }, + }, + ]) + assert plan.roles("mlp.experts.0.gate_proj") == ("gate",) + assert plan.roles("mlp.experts.0.up_proj") == ("up",) + assert plan.roles("mlp.experts.0.down_proj") == ("down",) + assert plan.is_moe("mlp.experts.0.gate_proj") + assert not plan.is_moe("mlp_extra.gate_proj") + assert plan.expert_container_leaf("mlp") == "experts" + assert plan.shared_container_leaf("mlp") == "shared_mlp" + + +def test_module_plan_shared_containers_do_not_depend_on_expert_spelling(): + plan = ModulePlan.from_tree([ + "model", "layers", "#", + { + "mlp:moe": { + "experts": {"#": ("w1:0:gate", "w3:0:up", "w2:1:down")}, + "parallel_branch": ("w1:0:gate", "w3:0:up", "w2:1:down"), + }, + }, + ]) + assert plan.shared_expert_containers() == ("mlp.parallel_branch",) + assert plan.shared_container_leaf("mlp") == "parallel_branch" + + +def test_module_plan_uses_explicit_projection_tags_for_renamed_leaves(): + plan = ModulePlan.from_tree([ + "model", "layers", "#", + {"mlp:moe": {"experts": {"#": ("w1:0:gate", "w3:0:up", "w2:1:down")}}}, + ]) + assert plan.roles("mlp.experts.3.w1") == ("gate",) + assert plan.roles("mlp.experts.3.w3") == ("up",) + assert plan.roles("mlp.experts.3.w2") == ("down",) + + +def test_is_moe_module_uses_tree_relative_paths_only(): + class ToyDefinition(BaseQModel): + module_tree = [ + "model", "layers", "#", + {"mlp:moe": {"experts": {"#": ("gate_proj:0",)}}}, + ] + + assert ToyDefinition.is_moe_module("model.layers.2.mlp.experts.0.gate_proj") + assert ToyDefinition.is_moe_module("model.layers.2.mlp") + assert not ToyDefinition.is_moe_module("model.layers.2.mlp_extra") + + +def test_unsupported_tree_fails_closed_without_auto_detection(): + class UndefinedTree(BaseQModel): + module_tree = None + + class Config: + model_type = "not_registered" + + class Model: + config = Config() + + assert UndefinedTree._resolve_effective_module_tree(Model(), object()) is None diff --git a/tests/module_tree/test_module_tree_variants.py b/tests/module_tree/test_module_tree_variants.py index 19a35c59e8..05c04d06b7 100644 --- a/tests/module_tree/test_module_tree_variants.py +++ b/tests/module_tree/test_module_tree_variants.py @@ -13,6 +13,10 @@ from gptqmodel.utils.model import get_layers_with_prefixes +def _layer_paths(model_cls): + return model_cls.extract_layers_node() + + class _BranchALayer(nn.Module): def __init__(self): super().__init__() @@ -93,14 +97,11 @@ class _LegacyPipePrefixQModel(BaseQModel): class _AutoDetectedTreeQModel(BaseQModel): - """Tiny unknown-architecture definition used to verify instance isolation.""" + """Tiny definition used to verify explicit per-instance tree isolation.""" module_tree = None shared_input_verified_model_types = frozenset({"unknown"}) - def _auto_detect_module_tree(self, model, quant_method): - return model.config.selected_tree - def _configure_modelopt_runtime(self): pass @@ -134,13 +135,14 @@ def _init_tree_qmodel(qmodel_cls, selected_tree, method=METHOD.GPTQ): model.model = nn.Module() model.model.layers = nn.ModuleList([nn.Module()]) qcfg = SimpleNamespace(method=method, adapter=None) + model.gptqmodel_effective_module_tree = selected_tree return qmodel_cls(model, quantized=False, quantize_config=qcfg) def test_single_module_tree_expands_layer_path_base_modules_and_layer_modules(): model = _VariantTreeModel() - assert _SingleTreeQModel.extract_layers_node() == ["model.A_module.layers"] + assert ["model.A_module.layers"] == _layer_paths(_SingleTreeQModel) assert _SingleTreeQModel.get_base_modules(model) == [ "model.shared", "model.B_module", @@ -164,7 +166,7 @@ def test_module_tree_variant_normalization_accepts_single_and_multiple_trees(): def test_variant_module_tree_expands_layer_paths_and_base_modules(): model = _VariantTreeModel() - assert _VariantTreeQModel.extract_layers_node() == [ + assert _layer_paths(_VariantTreeQModel) == [ "model.A_module.layers", "model.B_module.layers", ] @@ -178,7 +180,7 @@ def test_variant_module_tree_expands_layer_paths_and_base_modules(): def test_variant_module_tree_merges_branch_specific_layer_modules(): model = _VariantTreeModel() - layers, layer_names = get_layers_with_prefixes(model, _VariantTreeQModel.extract_layers_node()) + layers, layer_names = get_layers_with_prefixes(model, _layer_paths(_VariantTreeQModel)) assert len(layers) == 2 assert layer_names == [ @@ -194,7 +196,7 @@ def test_variant_module_tree_merges_branch_specific_layer_modules(): def test_pipe_separated_module_tree_prefix_is_not_expanded(): - assert _LegacyPipePrefixQModel.extract_layers_node() == [ + assert _layer_paths(_LegacyPipePrefixQModel) == [ "model.A_module|B_module.layers", ] @@ -211,8 +213,8 @@ def test_effective_module_tree_is_instance_local_and_deeply_immutable(order): assert _AutoDetectedTreeQModel.module_tree is None expected_paths = {"a": "model.layers", "b": "other.blocks"} expected_modules = {"a": [["mlp.a"]], "b": [["mixer.proj.b"]]} - assert first.extract_layers_node() == [expected_paths[first_key]] - assert second.extract_layers_node() == [expected_paths[second_key]] + assert _layer_paths(first) == [expected_paths[first_key]] + assert _layer_paths(second) == [expected_paths[second_key]] assert first.simple_layer_modules(first.model.config, SimpleNamespace(dynamic=None)) == expected_modules[first_key] assert second.full_layer_modules(second.model.config) == expected_modules[second_key] assert first.effective_module_tree[0] == trees[first_key][0] @@ -222,7 +224,7 @@ def test_effective_module_tree_is_instance_local_and_deeply_immutable(order): pass else: raise AssertionError("effective_module_tree must be deeply immutable") - assert first.extract_layers_node() == [expected_paths[first_key]] + assert _layer_paths(first) == [expected_paths[first_key]] def test_effective_frozen_tree_preserves_shared_input_tags(): @@ -260,15 +262,15 @@ def test_effective_tree_context_only_binds_its_model_class(): tree_b = ["alternate", "layers", "#", {"mlp": ("up_proj:0",)}] with _AutoDetectedTreeQModel._module_tree_context(tree_a): - assert _AutoDetectedTreeQModel.extract_layers_node() == ["other.blocks"] - assert _SingleTreeQModel.extract_layers_node() == ["model.A_module.layers"] + assert ["other.blocks"] == _layer_paths(_AutoDetectedTreeQModel) + assert ["model.A_module.layers"] == _layer_paths(_SingleTreeQModel) with _AutoDetectedTreeQModel._module_tree_context(tree_b): - assert _AutoDetectedTreeQModel.extract_layers_node() == ["alternate.layers"] - assert _SingleTreeQModel.extract_layers_node() == ["model.A_module.layers"] - assert _AutoDetectedTreeQModel.extract_layers_node() == ["other.blocks"] + assert ["alternate.layers"] == _layer_paths(_AutoDetectedTreeQModel) + assert ["model.A_module.layers"] == _layer_paths(_SingleTreeQModel) + assert ["other.blocks"] == _layer_paths(_AutoDetectedTreeQModel) -def test_fresh_quantized_load_planning_binds_auto_detected_tree(): +def test_fresh_quantized_load_planning_requires_an_explicit_tree(): selected_tree = [ "model", "layers", @@ -281,11 +283,11 @@ def test_fresh_quantized_load_planning_binds_auto_detected_tree(): model.model.layers = nn.ModuleList([_BranchALayer()]) qcfg = SimpleNamespace(method=METHOD.GPTQ, dynamic=None, adapter=None) + assert _AutoDetectedTreeQModel._resolve_effective_module_tree(model, qcfg) is None + model.gptqmodel_effective_module_tree = selected_tree effective_tree = _AutoDetectedTreeQModel._resolve_effective_module_tree(model, qcfg) - - assert _AutoDetectedTreeQModel.module_tree is None with _AutoDetectedTreeQModel._module_tree_context(effective_tree): - assert _AutoDetectedTreeQModel.extract_layers_node() == ["model.layers"] + assert ["model.layers"] == _layer_paths(_AutoDetectedTreeQModel) assert _AutoDetectedTreeQModel.simple_layer_modules(model.config, qcfg) == [ ["self_attn.q_proj"], ["self_attn.o_proj"], @@ -299,7 +301,7 @@ def test_fresh_quantized_load_planning_binds_auto_detected_tree(): quantize_config=qcfg, effective_module_tree=effective_tree, ) - assert instance.extract_layers_node() == ["model.layers"] + assert ["model.layers"] == _layer_paths(instance) def test_module_tree_method_override_is_copy_on_write_for_dense_moe_tree(): diff --git a/tests/test_afmoe_support.py b/tests/test_afmoe_support.py index d079982c12..36cfa598d3 100644 --- a/tests/test_afmoe_support.py +++ b/tests/test_afmoe_support.py @@ -70,7 +70,7 @@ def test_afmoe_simple_layer_modules_cover_attention_and_mlp(): assert AfMoeQModel.layer_modules_strict is False hooks = AfMoeQModel.moe_lifecycle_hooks assert isinstance(hooks, GateUpDownMoELifecycleHooks) - # Lifecycle hooks look names up with hasattr(moe_block, name), so the - # default bare attribute names must be used rather than module-tree keys. - assert hooks.expert_block_names == ["experts"] - assert hooks.shared_expert_block_names == ["shared_experts", "shared_expert"] + # Container names now come from the model definition's tree, not a static + # candidate list. AFMoE declares the routed and shared expert containers. + assert hooks.expert_block_names == () + assert hooks.shared_expert_block_names == () diff --git a/tests/test_awq_weight_mean.py b/tests/test_awq_weight_mean.py index f4acc79482..195bc81d04 100644 --- a/tests/test_awq_weight_mean.py +++ b/tests/test_awq_weight_mean.py @@ -342,7 +342,7 @@ def test_public_moe_model_policies_enable_pointwise_roots_and_children(): (MixtralQModel, "mlp", "mlp.experts.0.gate_proj"), (Qwen3MoeQModel, "mlp", "mlp.experts.0.gate_proj"), (Qwen3NextGPTQ, "mlp", "mlp.shared_expert.down_proj"), - (MiniMaxM2GPTQ, "block_sparse_moe", "block_sparse_moe.experts.0.w1"), + (MiniMaxM2GPTQ, "mlp", "mlp.experts.0.gate_proj"), ] for model_cls, root_name, child_name in cases: From 9c702045d30761139446036cd3d574395a301c1d Mon Sep 17 00:00:00 2001 From: Qubitium Date: Fri, 6 Nov 2026 16:55:10 -0800 Subject: [PATCH 2/7] docs: require diagrams for major logic-flow changes Add $gptqmodel-logic-flow-diagrams skill, wire it into AGENTS.md and the PR template, and commit the resolved model-tree flow as a reference page. - .agents/skills/gptqmodel-logic-flow-diagrams: when the rule applies, required artifacts (new-flow diagram, before/after evidence, docs page), accuracy rules, Mermaid authoring rules for GitHub rendering, and a review checklist. - AGENTS.md: repo-wide instruction to apply the skill before opening a PR. - .github/PULL_REQUEST_TEMPLATE.md: reviewable checklist for the same gate. - docs/model-tree-resolution.md: the PR #3565 flow, diagrams and contracts, kept for future reference. - README.md: link the new page from the quantization support section. --- .../gptqmodel-logic-flow-diagrams/SKILL.md | 191 ++++++++++++ .../agents/openai.yaml | 4 + .github/PULL_REQUEST_TEMPLATE.md | 18 ++ AGENTS.md | 22 ++ README.md | 2 + docs/model-tree-resolution.md | 294 ++++++++++++++++++ 6 files changed, 531 insertions(+) create mode 100644 .agents/skills/gptqmodel-logic-flow-diagrams/SKILL.md create mode 100644 .agents/skills/gptqmodel-logic-flow-diagrams/agents/openai.yaml create mode 100644 docs/model-tree-resolution.md diff --git a/.agents/skills/gptqmodel-logic-flow-diagrams/SKILL.md b/.agents/skills/gptqmodel-logic-flow-diagrams/SKILL.md new file mode 100644 index 0000000000..be62c1f3d3 --- /dev/null +++ b/.agents/skills/gptqmodel-logic-flow-diagrams/SKILL.md @@ -0,0 +1,191 @@ +--- +name: gptqmodel-logic-flow-diagrams +description: Require Mermaid diagrams and before/after tables for major logic-flow changes, both in the PR description and in a committed docs/ reference page. Use when a change alters control flow, resolution/selection order, dispatch, data or tensor lifecycle, or removes or replaces a decision mechanism. +--- + +# Logic-flow diagrams for major changes + +A change that moves *decision-making* is not fully reviewed until a reader can +see the old flow, the new flow, and the boundary between them without opening +the diff. This skill defines the minimum documentation bar for those changes and +where it lives. + +## When this skill applies + +Apply it when a change does any of the following: + +- Alters **control flow**: new/removed stages, reordered phases, new early + exits, new failure paths, changed fallbacks. +- Replaces a **decision mechanism**: heuristics replaced by declared metadata, + name matching replaced by explicit tags/paths, a config key changing which + code path runs, a plugin/registry becoming authoritative. +- Changes **resolution or selection order**: device placement, backend + selection, kernel dispatch, layer/module resolution, checkpoint resume order. +- Changes **data or tensor lifecycle**: what is materialized, cached, freed, + offloaded, repacked, or persisted across stages. +- Moves work **between processes, devices, or stages**: multi-GPU split, + lazy-load/materialize boundaries, disk offload, streaming. +- Introduces a **fail-closed** or **fail-open** contract change: previously + guessed, now raises; previously raised, now defaults. + +Not required for: localized bug fixes, numerical tweaks inside one function, +doc-only changes, or dependency bumps. When unsure, ask: *"would a competent +reviewer need a diagram to be confident the flow is right?"* If yes, apply it. + +## Requirements (minimum) + +For every qualifying PR, produce **all three**: + +1. **Flow diagram(s)** of the new logic in the PR description. +2. **Before/after comparison** — either a second diagram of the old flow or a + table mapping each old mechanism to its replacement, with `file:line` + pointers where the old logic lived. +3. **A committed reference page** under `docs/` that keeps the same diagrams + for future readers (see [Where the docs page goes](#where-the-docs-page-goes)). + +Diagrams are the floor, not the ceiling. Add whichever of these actually +explain the change: + +| Artifact | Use for | +| --- | --- | +| Mermaid flowchart | control flow, decision trees, dispatch, fallbacks | +| Mermaid sequence diagram | multi-actor flow: caller → loader → looper → kernel | +| Mermaid state diagram | lifecycle, resume/restart, failure and retry states | +| Mermaid `classDiagram` / ER | new core types, ownership, data model | +| Before/after table | 1:1 replacement of mechanisms or semantics | +| Change inventory table | file → add/delete counts → one-line purpose | +| Measured numbers table | what the bug cost or what the fix changed, with units | +| Declaration/token syntax block | new metadata grammar readers must write | + +Every diagram must carry information that prose would take a paragraph to say. +If a diagram restates one sentence, drop it. + +## Accuracy rules (non-negotiable) + +- Diagrams describe **code that exists in the PR**, not the intended design. + Re-read the diff before drawing; do not draw from the commit message. +- Name real symbols: `ModulePlan.from_tree`, `_resolve_effective_module_tree`, + `plan.expert_root()`. Placeholders like `do_stuff()` are not acceptable. +- Mark **failure and ambiguity paths** explicitly, visually distinct from the + success path (e.g. red fill). Silent fallbacks are the usual root cause of + the bug being fixed — show where they were removed. +- Show **where a decision is made** and what it is made from. "Resolves role" + is too vague; "resolves role from declared `:q` tag" is the point. +- Quantitative claims need a source: measured, counted from the diff, or + explicitly labelled as an estimate. Never invent pass counts. +- Do not include aspirational or follow-up flows as if implemented. Put those + in a clearly separated "Not in scope / follow-up" section. + +## PR description structure + +Use this skeleton for qualifying PRs; drop sections that genuinely do not apply. + +```markdown +## TL;DR +What changed, the net diff size, and the one-line architectural consequence. + +## 1. The problem +Diagram of the OLD flow + table of the mechanisms being removed, with file:line. + +## 2. The new flow +End-to-end diagram from entry point to the components that consume the result. + +## 3. New core (if any) +Diagram of the new abstraction: how it is built, what it exposes. +Syntax/token table if the change introduces new metadata. + +## 4. Per-subsystem detail +One small diagram per non-obvious decision; before/after where it helps. + +## 5. Failure and ambiguity contract +State diagram + table: situation → before → after. + +## 6. Change inventory +Table: area, file, ± lines, purpose. + +## 7. Tests / guarantees +Table: test name → the invariant it pins. + +## 8. Validation +Exact commands and measured results. + +## 9. Reviewer notes +Trade-offs, deliberate scope limits, open questions. +``` + +## Mermaid authoring rules (GitHub-rendered) + +These avoid the failures that actually happen on GitHub: + +- **Never wrap a ```` ```mermaid ```` fence in a raw HTML block** (`
`, + ``). GitHub does not parse markdown inside raw HTML, so the fence + renders as literal text. Use plain block elements or line breaks instead. +- Keep labels short and use `
` for line breaks inside a label. Avoid + `` tags inside labels; plain text is safer across renderers. +- Avoid `{` and `}` in label text — Mermaid parses them as shape syntax. + Write `specs map`, not `specs{}`. +- Prefer `flowchart TD/LR` over `graph`. Use `stateDiagram-v2` only for real + state machines, and give states `state "label" as ID` when the label has + spaces or punctuation. +- Quote any label containing `.`, `(`, `)`, `:`, `/`, `#`, or an arrow. +- Validate before publishing: confirm fences are balanced and every block + starts with a known diagram type. A quick local check: + ```bash + python - <<'PY' + import re, pathlib + text = pathlib.Path("PR_BODY.md").read_text() + blocks = re.findall(r"```mermaid\n(.*?)```", text, re.S) + print(len(blocks), "blocks", text.count("```"), "fences") + for i, b in enumerate(blocks): + print(i, b.strip().splitlines()[0]) + PY + ``` +- After the PR is opened, re-read the live body from the API and confirm the + block count survived: `body.count("```mermaid")`. + +## Where the docs page goes + +Commit the reference page next to the subject it describes, not in a new +parallel tree: + +| Change subject | Location | +| --- | --- | +| Model/definition resolution, module trees | `docs/model-tree-resolution.md` | +| Loader, writer, checkpoint, packing | `docs/.md` (existing file if present) | +| Device placement, multi-GPU | `docs/multi_gpu_quantization.md` | +| Quantization math, kernels, formats | existing `docs/` page for the method | +| Looper stages, resume | `docs/looper-checkpoint-redesign.md` | + +Rules for the page: + +- Title it for the mechanism, not the PR: *"Model tree resolution"*, not + *"PR 3565"*. +- Open with **what the flow is and why it is shaped that way**, then the + diagrams, then the contracts (fail-closed rules, extension points). +- Keep diagrams in sync with the code. If a later PR changes the flow, update + the page in the same PR — a stale diagram is worse than none. +- Link the page from `README.md` where related features are discussed, so it is + discoverable rather than orphaned. +- Reference the introducing PR number in one line so readers can find the + rationale, but do not write the page as a changelog. + +## Review checklist + +- [ ] Change qualifies (control flow, decision mechanism, lifecycle, or + ordering), or the PR states why diagrams are not needed. +- [ ] New-flow diagram with real symbol names, from entry point to consumers. +- [ ] Old mechanism shown or tabulated with `file:line` evidence. +- [ ] Failure/ambiguity paths visible and visually distinct. +- [ ] Numbers are measured or explicitly labelled as estimates. +- [ ] Follow-up work separated from implemented behavior. +- [ ] `docs/` reference page committed and linked from `README.md`. +- [ ] Mermaid blocks balanced, no raw-HTML wrapping, no `{}` in labels. +- [ ] Live PR body re-read after publishing to confirm rendering input. + +## Reference example + +PR #3565 (`fix(models): resolve module roles from explicit model trees`) is the +worked example: ten diagrams covering the removed name heuristics, the +resolve/freeze/compile path, the new `ModulePlan` queries, per-subsystem +resolution, lookup ambiguity handling, and the fail-closed contract. Its +distilled reference page is `docs/model-tree-resolution.md`. diff --git a/.agents/skills/gptqmodel-logic-flow-diagrams/agents/openai.yaml b/.agents/skills/gptqmodel-logic-flow-diagrams/agents/openai.yaml new file mode 100644 index 0000000000..c10359fe5a --- /dev/null +++ b/.agents/skills/gptqmodel-logic-flow-diagrams/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "GPT-QModel Logic Flow Diagrams" + short_description: "Diagram major logic-flow changes in PR and docs" + default_prompt: "Use $gptqmodel-logic-flow-diagrams to document this logic-flow change with before/after diagrams and a committed docs/ reference page." diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 40db963f4b..3d6475d8af 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -20,6 +20,24 @@ Paste the exact test commands and results here: ```bash ``` +## Logic Flow Documentation + +Required for changes that alter control flow, replace a decision mechanism +(for example name matching replaced by declared metadata), change resolution or +selection order, change data or tensor lifecycle, or introduce a fail-closed +contract. See `$gptqmodel-logic-flow-diagrams` in +`.agents/skills/gptqmodel-logic-flow-diagrams/SKILL.md`. + +- [ ] This change does not alter a major logic flow, or the required diagrams + and docs page are included below. +- [ ] New-flow Mermaid diagram(s) describe the shipped code using real symbol names. +- [ ] The removed/replaced mechanism is shown or tabulated with `file:line` evidence. +- [ ] Failure and ambiguity paths are marked and visually distinct from success. +- [ ] A reference page under `docs/` repeats the diagrams, titled for the + mechanism, and is linked from `README.md`. + +Diagram summary (or "not applicable" with one sentence of justification): + ## Review Requirements AI-assisted code is welcome. The PR must still be reviewed before it is opened as ready for review. diff --git a/AGENTS.md b/AGENTS.md index a0c82495ed..d1e9a84fff 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -61,3 +61,25 @@ For tokenizer initialization, tokenization normalization, special-token compatib GPT-QModel depends on [ModelCloud/Tokenicer](https://github.com/ModelCloud/Tokenicer). Put reusable corrective tokenizer and chat-template normalization in Tokenicer, add relevant tests, increment its version, run its complete test suite, then commit, push, and open a Tokenicer pull request. Do not leave model-loader patches in GPT-QModel merely to avoid fixing the dependency. Establish a non-quantized baseline before treating bad generation or evaluation scores as a quantization regression. Compare exact rendered prompts and input IDs as well as aggregate scores. + +## Logic-flow change documentation + +For any change that alters control flow, replaces a decision mechanism (for +example name matching replaced by declared metadata), changes resolution or +selection order, changes data or tensor lifecycle, or introduces a fail-closed +contract, read and follow `$gptqmodel-logic-flow-diagrams` in +`.agents/skills/gptqmodel-logic-flow-diagrams/SKILL.md` before opening the pull +request. + +Such a change is not reviewable from the diff alone. The pull request +description must contain, at minimum, a Mermaid diagram of the new flow drawn +from the shipped code, a before/after view of the mechanism being removed with +`file:line` evidence, and an explicitly marked failure/ambiguity path. The same +diagrams must be committed as a reference page under `docs/`, titled for the +mechanism rather than the pull request, and linked from `README.md` where the +related feature is described. + +Diagrams must use real symbol names and measured numbers. Do not draw intended +design, estimate test results, or include follow-up work as if implemented. Keep +diagrams in sync with the code: a later change to the same flow updates the page +in the same pull request. diff --git a/README.md b/README.md index 44a3058b2d..262abd5a47 100644 --- a/README.md +++ b/README.md @@ -106,6 +106,8 @@ save, reload, and validate a model. It also maps advanced features to their guid Every quantization method shares a common lifecycle—calibrate, quantize, validate, save, load, and serve—while retaining method-specific controls where they matter. New methods and kernels plug into that lifecycle instead of creating another disconnected toolchain. +Module roles—attention projections, MLP projections, MoE experts and shared experts, and quantizable leaves—are resolved from each architecture's declared module tree, not from runtime module names. See **[model tree resolution](docs/model-tree-resolution.md)** for the resolution flow, the declaration syntax, and the fail-closed contracts. + | Feature | GPT-QModel | Transformers | vLLM | SGLang | Lora Training | |---------------------------|------------|---|---|---|---------------| | GPTQ | ✅ | ✅ | ✅ | ✅ | ✅ | diff --git a/docs/model-tree-resolution.md b/docs/model-tree-resolution.md new file mode 100644 index 0000000000..b59739b89b --- /dev/null +++ b/docs/model-tree-resolution.md @@ -0,0 +1,294 @@ +# Model tree resolution + +How GPT-QModel decides what each module *is*: its role (`q`/`k`/`v`/`o`, +`gate`/`up`/`down`), whether it belongs to a MoE block, which expert family it +belongs to, and whether it should be quantized at all. + +The short version: **the architecture's declared `module_tree` is authoritative; +runtime module names are not consulted.** Introduced in PR #3565. + +## Why it is shaped this way + +Before this change the answer to "what is this module?" was derived from the +*string* of the live module name: + +```mermaid +flowchart LR + subgraph OLD["BEFORE — runtime name guessing"] + direction TB + N["module full name
model.layers.7.mlp.experts.3.w1"] --> H1{"'.expert' in name?"} + N --> H2{"'.experts.' in name?"} + N --> H3{"endswith('mlp.down_proj')?"} + N --> H4{"'.attn' in name?"} + N --> H5{"endswith(declared)?"} + H1 --> R1["is MoE"] + H2 --> R2["group key"] + H3 --> R3["rotation target"] + H4 --> R4["attention"] + H5 --> R5["quantizable"] + end + style OLD fill:#fff1f0,stroke:#d4380d + style H1 fill:#ffe7ba + style H2 fill:#ffe7ba + style H3 fill:#ffe7ba + style H4 fill:#ffe7ba + style H5 fill:#ffe7ba +``` + +Each of those rules fails *silently*: no exception, just the wrong grouping or +the wrong quantization. A model that renames `gate_proj` to `w1`, exposes +`shared_mlp` instead of `shared_experts`, or adds an extra attention projection +was mis-classified by construction. + +The repository already declared the structure of every supported architecture in +`module_tree` — decoder boundaries (`#`), leaf order, aliases, `:moe` markers, +and `!`/`?` exclusion flags. That declaration only drove layer extraction; role +logic re-guessed the rest. This design makes the declaration the single source of +truth and compiles it once per model instance. + +## Resolution flow + +```mermaid +flowchart TD + M["model loaded
AutoModel / checkpoint"] --> RES["_resolve_effective_module_tree()"] + RES -->|1| INJ["model.gptqmodel_effective_module_tree
explicit injection"] + RES -->|2| CLS["cls.module_tree
registered definition"] + INJ --> OVR + CLS --> OVR["apply module_tree_overrides()
per-method: gptq / awq / exl3"] + OVR -->|None| ERR["ValueError:
no explicit module_tree registered
fail closed"] + OVR -->|tree| FRZ["_freeze_module_tree()
deep immutable"] + FRZ --> ATTR["self.effective_module_tree = frozen
self.module_tree = effective"] + ATTR --> PLAN["ModulePlan.from_tree(effective)
compiled once"] + PLAN --> USE["module_plan
used by every subsystem"] + PLAN --> HOOK["moe_lifecycle_hooks.module_plan
per-instance copy"] + PLAN --> MDL["model.gptqmodel_effective_module_tree
handed to loader"] + style PLAN fill:#d9f7be,stroke:#237804,stroke-width:2px + style ERR fill:#ffa39e,stroke:#a8071a + style FRZ fill:#e6f7ff +``` + +Three properties matter here: + +- **One tree per instance.** The tree is deep-frozen and stored on the instance, + so a class definition can be reused by later instances without dispatch state + leaking between them. +- **Compiled once.** `ModulePlan` is built at construction, not re-derived per + module lookup. +- **Fails closed.** If no definition and no injection exist, loading raises + instead of guessing a structure. + +## `ModulePlan` + +`gptqmodel/models/module_plan.py` turns the declaration into an immutable +inventory of `ModuleSpec(template, flags)` plus role and MoE queries. + +```mermaid +flowchart LR + T["module_tree
['model','layers','#',...]"] --> B["find decoder boundary
variant.index('#')"] + B --> W["walk()
dict → keys / list → leaves"] + W --> S["ModuleSpec
template + flags"] + S --> IDX["specs map
template → spec"] + S --> PAR["_by_parent map
parent → specs"] + IDX --> Q["queries"] + PAR --> Q + Q --> Q1["roles / child_roles"] + Q --> Q2["is_moe / moe_roots"] + Q --> Q3["expert_containers"] + Q --> Q4["shared_expert_containers"] + Q --> Q5["expert_root / same_moe_family"] + Q --> Q6["is_expert / concrete_paths"] + style S fill:#d9f7be,stroke:#237804 +``` + +### Declaration syntax + +``` +"mlp:moe" ^ ^ + │ │ │ └── flags: moe root + │ └── leaf/container name + └── the declared path segment +``` + +| Token form | Meaning | Produced role | +| --- | --- | --- | +| `q_proj:0:q` | slot `0`, role `q` | `q` | +| `w1:0:gate` | explicit tag wins over the name | `gate` | +| `mlp:moe` | MoE root marker | `moe` | +| `x:!` / `x:?` | not quantized / capture-only | `quantize = False` | +| `experts.#` | routed-expert expansion | `{expert_index}` → `\d+` | +| `gate_up_proj` | fused projection | `("gate","up")` | + +### Matching is exact + +Templates compile to an anchored regular expression (`^…$`) with `#` replaced by +`\d+`. There is no `startswith`, `endswith`, or `in` fallback: + +```mermaid +flowchart LR + A["lookup: mlp.experts.3.w1"] --> E{"exact template?"} + E -->|yes| H["spec"] + E -->|no| R{"anchored regex
^mlp\.experts\.\d+\.w3$"} + R -->|match| H + R -->|no| NONE["None →
caller treats as undeclared"] + style NONE fill:#fff1f0,stroke:#a8071a +``` + +Because the pattern is anchored and placeholder-aware, `mlp_extra.gate_proj` +can never match the declared `mlp` branch, while `mlp.experts.3.gate_proj` +matches the declared `mlp.experts.#.gate_proj` template. + +### Shared experts without an allow-list + +`shared_expert_containers()` finds shared/parallel expert branches +**structurally**: a direct projection family under a MoE root that is not the +routed `#` container and carries no router-only role. Definitions therefore do +not need to spell `shared_experts`, `shared_expert`, or `shared_mlp`; declaring +the branch is enough. + +## What each subsystem asks + +```mermaid +flowchart TD + PLAN["ModulePlan"] --> BASE["models/base.py
is_moe_module() · AWQ roles
stage-block classification"] + PLAN --> MOE["models/moe_lifecycle.py
expert / shared containers
dotted MoE roots"] + PLAN --> IOL["models/loader.py · writer.py
declared-path quantizability
rotation down-proj"] + PLAN --> ROT["rotation/rotation.py
:norm :q :k :v :o :gate :up :down"] + PLAN --> LOOP["looper/module_looper.py
expert_root() group keys
role-based attention"] + PLAN --> SUB["looper/stage_subset.py
weight_only_looper.py
gate+up in roles
co-location"] + PLAN --> GSQ["quantization/gsq_training*.py
declared projection inventory
attention/MLP partition"] + style PLAN fill:#d9f7be,stroke:#237804,stroke-width:2px +``` + +### MoE membership and grouping + +```mermaid +flowchart LR + P["model.layers.9.mlp.experts.5.w2"] --> REL["strip layer prefix → layer-relative
mlp.experts.5.w2"] + REL --> PL["plan.roles() → ('down',)"] + REL --> EX["plan.expert_root() →
mlp.experts.5"] + EX --> GRP["device co-location group"] + REL --> MOEQ["plan.is_moe() → walks moe_roots()"] + style EX fill:#d9f7be +``` + +The expert family key used for device co-location is the declared family path, so +`gate`/`up`/`down` of one expert stay together on one device regardless of what +the projections are named. + +### Quantizability (loader and writer) + +```mermaid +flowchart TD + N["named module
model.layers.3.mlp.up_proj"] --> LP{"declared layer prefix?"} + LP -->|no| SKIP["skip: not quantized"] + LP -->|yes| REL["relative = mlp.up_proj"] + REL --> DEC{"relative declared, or
expanded expert leaf?"} + DEC -->|yes| Q["quantize"] + DEC -->|no| SKIP + style Q fill:#d9f7be,stroke:#237804 + style SKIP fill:#ffa39e +``` + +### Rotation + +Rotation needs the two layer norms, one attention parent, and one MLP parent. +It reads them from declared `:norm` and projection roles rather than assuming a +Llama layout: + +```mermaid +flowchart TD + R["rotate_model(plan=self.module_plan)"] --> N1["plan.child_roles('', 'norm')
→ exactly 2 norms"] + R --> P1["_rotation_parents(plan)
attention parent + MLP parent"] + P1 --> Q1["_resolve_role(layer, plan, parent, 'q'|'k'|'v'|'o')"] + P1 --> Q2["_resolve_role(layer, plan, parent, 'gate'|'up'|'down')"] + N1 --> F["fuse → reset"] + Q1 --> F + Q2 --> F + F --> EMB["get_embeddings()
get_input_embeddings() / embedding_name"] + R -.->|no plan| DEF["_default_rotation_plan()
Llama defaults for public callers"] + style DEF fill:#e6f7ff + style P1 fill:#d9f7be +``` + +`_resolve_role` requires exactly one match and raises with the offending path, so +a definition with two `:q` projections fails loudly instead of silently picking +one. + +## Ambiguity in name lookup + +Two helpers in `utils/model.py` used to return the first match in module +registration order. They now prefer an exact path and raise on multiple matches: + +```mermaid +flowchart LR + subgraph A["get_module_by_name_prefix"] + A1["exact path in named_modules?"] -->|yes| AOK["return"] + A1 -->|no| A2["dotted descendants"] + A2 -->|1| AOK + A2 -->|>1| AERR["ValueError:
Ambiguous module prefix"] + A2 -->|0| ANONE["None"] + end + subgraph B["get_module_by_name_suffix"] + B1["exact path?"] -->|yes| BOK["return"] + B1 -->|no| B2["ends with '.' + suffix"] + B2 -->|1| BOK + B2 -->|>1| BERR["ValueError:
Ambiguous module suffix"] + B2 -->|0| BNONE["None"] + end + style AERR fill:#ffa39e + style BERR fill:#ffa39e +``` + +## Contracts + +```mermaid +flowchart TD + S["resolve effective tree"] --> I{"model.gptqmodel_effective_module_tree?"} + I -->|yes| F["freeze deep-immutable"] + I -->|no| C{"cls.module_tree?"} + C -->|yes| O["apply module_tree_overrides()"] + C -->|no| X["ValueError:
register a model definition"] + O --> F + F --> P["ModulePlan.from_tree()"] + P --> R["load / quantize / rotate"] + style X fill:#ffa39e,stroke:#a8071a + style P fill:#d9f7be,stroke:#237804 +``` + +| Situation | Behavior | +| --- | --- | +| Unknown `model_type`, no definition | `ValueError`; never auto-guesses a tree | +| Ambiguous `:q` / `:k` / … role | `ValueError` naming the candidate paths | +| Ambiguous prefix or suffix lookup | `ValueError` naming the candidates | +| Path not declared in the tree | treated as undeclared: not quantized, no role | +| Custom architecture | inject `model.gptqmodel_effective_module_tree` | +| Per-method difference | `module_tree_overrides[method]` on the definition | + +## Extension points + +- **New architecture:** add a model definition with an explicit `module_tree`. + Never add a new name heuristic to make an architecture work. +- **Per-method divergence:** use `module_tree_overrides` keyed by quantization + method instead of branching on names inside shared code. +- **Custom/injected models:** attach `gptqmodel_effective_module_tree` to the + model object before loading. +- **Diagnostics only:** `_auto_detect_module_tree()` still exists to inspect an + unknown model, but it is deliberately not on the loading path. + +## Known limitation + +`ModuleSpec.roles` falls back to a small name-to-role map (`q_proj`, +`k_proj`, `v_proj`, `o_proj`, `gate_proj`, `up_proj`, `down_proj`, `w1`, `w2`, +`w3`, `gate_up_proj`) when a declared leaf carries no explicit role tag. The +fallback applies at *declaration time*, not against live module names, so it +cannot select the wrong sibling — but it is still a naming convention. Fully +tagging every definition would allow the map to be deleted. + +## Related tests + +| Test file | What it pins | +| --- | --- | +| `tests/module_tree/test_explicit_module_plan.py` | roles, shared containers, renamed leaves, sibling rejection, fail-closed | +| `tests/module_tree/test_module_tree_variants.py` | tree variants produce identical declared paths | +| `tests/module_tree/test_auto_detect.py` | auto-detection stays diagnostic-only | +| `tests/test_afmoe_support.py`, `tests/test_k2_horizon_support.py` | real MoE definitions resolve without name overrides | From ba460abef7694dd8a2f4162735fd71700a96a5b6 Mon Sep 17 00:00:00 2001 From: Qubitium Date: Fri, 6 Nov 2026 17:21:07 -0800 Subject: [PATCH 3/7] test(models): verify flash tree weight coverage --- AGENTS.md | 20 + docs/model-tree-resolution.md | 44 ++ gptqmodel/models/definitions/deepseek_v4.py | 25 +- gptqmodel/models/definitions/glm5_next.py | 14 + gptqmodel/models/definitions/qwen3_5.py | 2 +- gptqmodel/models/definitions/ricursive.py | 4 +- .../test_flash_model_tree_consumption.py | 647 ++++++++++++++++++ tests/module_tree/test_model_alignment.py | 6 +- tests/test_ricursive_support.py | 4 +- 9 files changed, 753 insertions(+), 13 deletions(-) create mode 100644 tests/module_tree/test_flash_model_tree_consumption.py diff --git a/AGENTS.md b/AGENTS.md index d1e9a84fff..7ab46f6f1d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -83,3 +83,23 @@ Diagrams must use real symbol names and measured numbers. Do not draw intended design, estimate test results, or include follow-up work as if implemented. Keep diagrams in sync with the code: a later change to the same flow updates the page in the same pull request. + +## Model-definition weight coverage + +`module_tree` is the oracle for checkpoint-owned weights, including +non-quantized weights. Derive coverage from `state_dict()` (parameters and +persistent buffers), not from `named_modules()`, `named_parameters()`, or +`named_buffers()` alone: runtime-created non-persistent buffers are not +checkpoint weights and must not become definition obligations. + +For every decoder-layer `state_dict()` entry: + +- The deepest owning module must resolve through `ModulePlan.find()`. +- A quantized owner must be declared by `simple_layer_modules()`. +- A non-quantized owner must carry an explicit `:!` or `:?` tag. + +Add real-model regression coverage for new or changed definitions. The Flash +family reference is +`tests/module_tree/test_flash_model_tree_consumption.py`; it builds the actual +meta model and checks quantizable paths, weight owners, roles, MoE hooks, and +looper consumers. diff --git a/docs/model-tree-resolution.md b/docs/model-tree-resolution.md index b59739b89b..f495cbb54d 100644 --- a/docs/model-tree-resolution.md +++ b/docs/model-tree-resolution.md @@ -189,6 +189,49 @@ flowchart TD style SKIP fill:#ffa39e ``` +### Checkpoint weight coverage + +The tree is also the oracle for every checkpoint-owned weight inside a decoder +layer, not only for modules that the current quantization pipeline replaces. +This prevents a non-quantized projection, router, hyper-connection, compressor, +or norm from disappearing between the model definition and the live model. + +```mermaid +flowchart TD + SD["layer.state_dict()
parameters + persistent buffers"] --> OWN["deepest owning module
for each entry"] + OWN --> FIND["plan.find(owner)"] + FIND -->|None| FAIL["test failure:
undeclared weight owner"] + FIND -->|spec| Q{"owner in
simple_layer_modules?"} + Q -->|yes| DECL["quantized by declaration"] + Q -->|no| TAG{"spec.quantize == False?"} + TAG -->|yes| EXCLUDED["explicit :! / :? exclusion"] + TAG -->|no| FAIL2["test failure:
untagged non-quantized weight"] + style FAIL fill:#ffa39e,stroke:#a8071a + style FAIL2 fill:#ffa39e,stroke:#a8071a + style EXCLUDED fill:#d9f7be,stroke:#237804 +``` + +`state_dict()` is the source of truth for this check. Non-persistent buffers +created at runtime are excluded by Torch and are not model-definition +obligations. The owning-module rule also covers direct parameters and buffers on +containers, such as Qwen `linear_attn.A_log`, DeepSeek `self_attn.sinks`, and +Ripple `self_attn.value_res_lambda`. + +Measured Flash-family coverage at this revision: + +| Model family | Decoder layers | Quantizable specs | Unique weight owners | +| --- | ---: | ---: | ---: | +| Qwen3.5 / Qwen3.8 | 32 | 10 | 19 | +| GLM-5.3-Flash | 45 | 873 | 37 | +| MiniMax-M3.1-Flash | 60 | 394 | 20 | +| DeepSeek-V4-Flash | 43 | 775 | 29 | +| Ripple | 5 (fixture) | 8 | 15 | + +DeepSeek-V4.1-Flash is not included: its checkpoint declares +`model_type=deepseek_v41`, but Transformers 5.22.2 and its main branch expose no +native `deepseek_v41` config or model class. The test activates automatically +when upstream support lands instead of relabeling V4-Flash as V4.1. + ### Rotation Rotation needs the two layer norms, one attention parent, and one MLP parent. @@ -292,3 +335,4 @@ tagging every definition would allow the map to be deleted. | `tests/module_tree/test_module_tree_variants.py` | tree variants produce identical declared paths | | `tests/module_tree/test_auto_detect.py` | auto-detection stays diagnostic-only | | `tests/test_afmoe_support.py`, `tests/test_k2_horizon_support.py` | real MoE definitions resolve without name overrides | +| `tests/module_tree/test_flash_model_tree_consumption.py` | real Flash-family meta models: quantizable specs, every checkpoint weight owner, roles, MoE hooks, looper helpers, Ripple custom code | diff --git a/gptqmodel/models/definitions/deepseek_v4.py b/gptqmodel/models/definitions/deepseek_v4.py index 36d4785909..c2e54f7ca0 100644 --- a/gptqmodel/models/definitions/deepseek_v4.py +++ b/gptqmodel/models/definitions/deepseek_v4.py @@ -14,20 +14,33 @@ class DeepSeekV4QModel(DeepSeekV3QModel): "layers", "#", { + "attn_hc:!": ("input_norm:!",), "input_layernorm": ("input_layernorm:!",), - "self_attn": ( + # `sinks` is a direct parameter on the attention container. + "self_attn:!": ( "q_a_norm:!", - "q_a_proj:0", + "q_a_proj:0:q", "q_b_norm:!", - "q_b_proj:0:in=q_a", + "q_b_proj:0:q:in=q_a", "o_a_proj:!", - "o_b_proj:1", + "o_b_proj:1:o", "kv_norm:!", - "kv_proj:2", + "kv_proj:2:k:v", + "compressor:!", + "compressor.kv_norm:!", + "compressor.kv_proj:!", + "compressor.gate_proj:!", + "compressor.indexer:!", + "compressor.indexer.kv_norm:!", + "compressor.indexer.kv_proj:!", + "compressor.indexer.q_b_proj:!", + "compressor.indexer.gate_proj:!", + "compressor.indexer.scorer.weights_proj:!", ), + "ffn_hc:!": ("input_norm:!",), "post_attention_layernorm": ("post_attention_layernorm:!",), "mlp:moe": { - "gate": ("gate:!",), + "gate": ("gate:!", "e_score_correction_bias:!", "tid2eid:!"), "experts": { "#": ("gate_proj:0", "up_proj:0", "down_proj:1"), }, diff --git a/gptqmodel/models/definitions/glm5_next.py b/gptqmodel/models/definitions/glm5_next.py index 388ce8d671..5ccc8ccc3a 100644 --- a/gptqmodel/models/definitions/glm5_next.py +++ b/gptqmodel/models/definitions/glm5_next.py @@ -38,22 +38,36 @@ class Glm5NextQModel(BaseQModel): "layers", "#", { + "attn_hc:!": ("input_norm:!",), "input_layernorm": ("input_layernorm:!",), "self_attn": ( # KDA (linear-attention) layers. + "b_proj:!", + "conv1d:!", + "forget_gate:!", + "forget_gate.f_a_proj:!", + "forget_gate.f_b_proj:!", + "g_a_proj:!", + "g_b_proj:!", + "o_norm:!", "q_proj:0:q", "k_proj:0:k", "v_proj:0:v", # DSA layers. The low-rank input and sparse indexer stay dense. "q_a_proj:!", + "q_a_layernorm:!", "kv_a_proj_with_mqa:!", + "kv_a_layernorm:!", + "indexer:!", "indexer.wq_b:!", "indexer.wk:!", + "indexer.k_norm:!", "indexer.weights_proj:!", "q_b_proj:0:q:in=q_a", "kv_b_proj:0:k:v:in=kv_a", "o_proj:1", ), + "ffn_hc:!": ("input_norm:!",), "post_attention_layernorm": ("post_attention_layernorm:!",), "mlp:moe": { # Dense fallback used by the first three decoder layers. diff --git a/gptqmodel/models/definitions/qwen3_5.py b/gptqmodel/models/definitions/qwen3_5.py index dabaf24b59..4b65f0ec8d 100644 --- a/gptqmodel/models/definitions/qwen3_5.py +++ b/gptqmodel/models/definitions/qwen3_5.py @@ -37,7 +37,7 @@ class Qwen3_5QModel(LlamaQModel): { "input_layernorm": ("input_layernorm:!",), "self_attn": ("q_norm:!", "q_proj:0:in=x", "k_norm:!", "k_proj:0:in=x", "v_proj:0:in=x", "o_proj:1"), - "linear_attn": ( + "linear_attn:!": ( "norm:!", "conv1d:!", "in_proj_qkv:0:in=x", diff --git a/gptqmodel/models/definitions/ricursive.py b/gptqmodel/models/definitions/ricursive.py index e91d33800d..656b38b585 100644 --- a/gptqmodel/models/definitions/ricursive.py +++ b/gptqmodel/models/definitions/ricursive.py @@ -37,7 +37,9 @@ class RicursiveQModel(BaseQModel): "#", { "input_layernorm": ("input_layernorm:!:norm",), - "self_attn": ( + # `value_res_lambda` is a direct parameter on the attention + # container when value residuals are enabled. + "self_attn:!": ( "q_norm:!:norm", "k_norm:!:norm", # `q_proj`, `k_proj` and `g_proj` all read the raw hidden states. `v_proj` diff --git a/tests/module_tree/test_flash_model_tree_consumption.py b/tests/module_tree/test_flash_model_tree_consumption.py new file mode 100644 index 0000000000..8a9ec405d9 --- /dev/null +++ b/tests/module_tree/test_flash_model_tree_consumption.py @@ -0,0 +1,647 @@ +# SPDX-FileCopyrightText: 2026 ModelCloud.ai +# SPDX-License-Identifier: Apache-2.0 + +"""End-to-end module-tree contract tests for current Flash model families. + +These tests build the actual Transformers model shells on the ``meta`` device, +run the registered Defuser conversion, and then exercise the same tree consumers +used by quantization: ``simple_layer_modules``, ``ModulePlan``, the MoE lifecycle +hooks, and the module looper helpers. + +The DeepSeek-V4.1-Flash checkpoint declares ``model_type=deepseek_v41``. The +current Transformers release has no ``deepseek_v41`` config/model class, so a +true model test is impossible until upstream lands. ``deepseek_v4`` is kept as +the supported V4-Flash control, and the V4.1 test activates automatically once +the upstream config exists. +""" + +from __future__ import annotations + +import copy +import re +from dataclasses import dataclass +from types import SimpleNamespace + +import pytest +import torch +import transformers +from transformers.models.auto.configuration_auto import CONFIG_MAPPING + +from gptqmodel.looper.module_looper import ModuleLooper +from gptqmodel.models._const import EXPERT_INDEX_PLACEHOLDER +from gptqmodel.models.auto import MODEL_MAP +from gptqmodel.models.base import BaseQModel +from gptqmodel.models.definitions.deepseek_v4 import DeepSeekV4QModel +from gptqmodel.models.definitions.glm5_next import Glm5NextQModel +from gptqmodel.models.definitions.minimax_m3_vl import MiniMaxM3VLGPTQ +from gptqmodel.models.definitions.qwen3_5 import Qwen3_5QModel +from gptqmodel.models.definitions.ricursive import RicursiveQModel +from gptqmodel.models.loader import _convert_model_with_defuser +from gptqmodel.models.module_plan import ModulePlan +from gptqmodel.utils.model import find_modules, get_layers_with_prefixes +from tests.test_ricursive_support import _build_tiny_fixture, _reference_dir + + +QC = SimpleNamespace(dynamic=None) + + +@dataclass(frozen=True) +class FlashCase: + model_type: str + checkpoint: str + definition: type[BaseQModel] + config_class: str + layers_node: str + layer_count: int + spec_count: int + weight_owner_count: int + moe: bool + dense_layer: int | None + moe_layer: int | None + key_modules: tuple[str, ...] + roles: tuple[tuple[str, tuple[str, ...]], ...] + nonquantized: tuple[str, ...] + + +CASES = { + "qwen3_5": FlashCase( + model_type="qwen3_5", + checkpoint="Qwen/Qwen3.8-27B", + definition=Qwen3_5QModel, + config_class="Qwen3_5Config", + layers_node="model.language_model.layers", + layer_count=32, + spec_count=10, + weight_owner_count=19, + moe=False, + dense_layer=0, + moe_layer=None, + key_modules=( + "linear_attn.in_proj_qkv", + "linear_attn.out_proj", + "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", + ), + roles=( + ("self_attn.q_proj", ("q",)), + ("self_attn.k_proj", ("k",)), + ("self_attn.v_proj", ("v",)), + ("self_attn.o_proj", ("o",)), + ("mlp.gate_proj", ("gate",)), + ("mlp.up_proj", ("up",)), + ("mlp.down_proj", ("down",)), + ), + nonquantized=( + "input_layernorm", + "self_attn.q_norm", + "self_attn.k_norm", + "linear_attn.norm", + "linear_attn.conv1d", + "linear_attn", + "linear_attn.in_proj_b", + "linear_attn.in_proj_a", + "post_attention_layernorm", + ), + ), + "glm5_next": FlashCase( + model_type="glm5_next", + checkpoint="zai-org/GLM-5.3-Flash", + definition=Glm5NextQModel, + config_class="Glm5NextConfig", + layers_node="model.language_model.layers", + layer_count=45, + spec_count=873, + weight_owner_count=37, + moe=True, + dense_layer=0, + moe_layer=3, + key_modules=( + "self_attn.q_proj", + "self_attn.q_a_proj", + "self_attn.q_b_proj", + "self_attn.kv_b_proj", + "self_attn.o_proj", + "mlp.experts.0.gate_proj", + "mlp.experts.287.down_proj", + "mlp.shared_experts.gate_proj", + "mlp.shared_experts.up_proj", + "mlp.shared_experts.down_proj", + ), + roles=( + ("self_attn.q_proj", ("q",)), + ("self_attn.k_proj", ("k",)), + ("self_attn.v_proj", ("v",)), + ("self_attn.q_b_proj", ("q",)), + ("self_attn.kv_b_proj", ("k", "v")), + ("self_attn.o_proj", ("o",)), + ("mlp.experts.0.gate_proj", ("gate",)), + ("mlp.experts.0.up_proj", ("up",)), + ("mlp.experts.0.down_proj", ("down",)), + ("mlp.shared_experts.gate_proj", ("gate",)), + ), + nonquantized=( + "input_layernorm", + "self_attn.q_a_proj", + "self_attn.kv_a_proj_with_mqa", + "self_attn.indexer.wq_b", + "self_attn.indexer.wk", + "self_attn.indexer.weights_proj", + "self_attn.indexer", + "self_attn.indexer.k_norm", + "self_attn.b_proj", + "self_attn.conv1d", + "self_attn.forget_gate", + "self_attn.forget_gate.f_a_proj", + "self_attn.forget_gate.f_b_proj", + "self_attn.g_a_proj", + "self_attn.g_b_proj", + "self_attn.kv_a_layernorm", + "self_attn.o_norm", + "self_attn.q_a_layernorm", + "post_attention_layernorm", + "attn_hc", + "attn_hc.input_norm", + "ffn_hc", + "ffn_hc.input_norm", + "mlp.gate", + "mlp.shared_experts.gate_proj", + "mlp.shared_experts.up_proj", + "mlp.shared_experts.down_proj", + ), + ), + "minimax_m3_vl": FlashCase( + model_type="minimax_m3_vl", + checkpoint="MiniMaxAI/MiniMax-M3.1-Flash", + definition=MiniMaxM3VLGPTQ, + config_class="MiniMaxM3VLConfig", + layers_node="model.language_model.layers", + layer_count=60, + spec_count=394, + weight_owner_count=20, + moe=True, + dense_layer=3, + moe_layer=0, + key_modules=( + "self_attn.q_proj", + "self_attn.k_proj", + "self_attn.v_proj", + "self_attn.o_proj", + "self_attn.indexer.q_proj", + "self_attn.indexer.k_proj", + "mlp.experts.0.gate_proj", + "mlp.experts.127.down_proj", + "mlp.shared_experts.gate_up_proj", + "mlp.shared_experts.down_proj", + ), + roles=( + ("self_attn.q_proj", ("q",)), + ("self_attn.k_proj", ("k",)), + ("self_attn.v_proj", ("v",)), + ("self_attn.o_proj", ("o",)), + ("self_attn.indexer.q_proj", ("q",)), + ("self_attn.indexer.k_proj", ("k",)), + ("mlp.experts.0.gate_proj", ("gate",)), + ("mlp.experts.0.up_proj", ("up",)), + ("mlp.experts.0.down_proj", ("down",)), + ("mlp.shared_experts.gate_up_proj", ("gate", "up")), + ), + nonquantized=( + "input_layernorm", + "self_attn.q_norm", + "self_attn.k_norm", + "self_attn.indexer.q_norm", + "self_attn.indexer.k_norm", + "post_attention_layernorm", + "mlp.gate", + ), + ), + "deepseek_v4": FlashCase( + model_type="deepseek_v4", + checkpoint="deepseek-ai/DeepSeek-V4-Flash", + definition=DeepSeekV4QModel, + config_class="DeepseekV4Config", + layers_node="model.layers", + layer_count=43, + spec_count=775, + weight_owner_count=29, + moe=True, + dense_layer=None, + moe_layer=0, + key_modules=( + "self_attn.q_a_proj", + "self_attn.q_b_proj", + "self_attn.kv_proj", + "self_attn.o_b_proj", + "mlp.experts.0.gate_proj", + "mlp.experts.255.down_proj", + "mlp.shared_experts.gate_proj", + "mlp.shared_experts.up_proj", + "mlp.shared_experts.down_proj", + ), + roles=( + ("self_attn.q_a_proj", ("q",)), + ("self_attn.q_b_proj", ("q",)), + ("self_attn.kv_proj", ("k", "v")), + ("self_attn.o_b_proj", ("o",)), + ("mlp.experts.0.gate_proj", ("gate",)), + ("mlp.experts.0.up_proj", ("up",)), + ("mlp.experts.0.down_proj", ("down",)), + ("mlp.shared_experts.gate_proj", ("gate",)), + ), + nonquantized=( + "input_layernorm", + "self_attn.q_a_norm", + "self_attn.q_b_norm", + "self_attn.o_a_proj", + "self_attn.kv_norm", + "post_attention_layernorm", + "attn_hc", + "attn_hc.input_norm", + "ffn_hc", + "ffn_hc.input_norm", + "self_attn", + "self_attn.compressor", + "self_attn.compressor.kv_norm", + "self_attn.compressor.kv_proj", + "self_attn.compressor.gate_proj", + "self_attn.compressor.indexer", + "self_attn.compressor.indexer.kv_norm", + "self_attn.compressor.indexer.kv_proj", + "self_attn.compressor.indexer.q_b_proj", + "self_attn.compressor.indexer.gate_proj", + "self_attn.compressor.indexer.scorer.weights_proj", + "mlp.gate", + "mlp.gate.e_score_correction_bias", + "mlp.gate.tid2eid", + ), + ), +} + + +def _mix_minimax_layers(config) -> None: + """Exercise both attention branches and both MLP branches in one config.""" + + text_config = config.text_config + text_config.layer_types = [ + "minimax_m3_sparse" if index % 2 == 0 else "full_attention" + for index in range(text_config.num_hidden_layers) + ] + text_config.mlp_layer_types = [ + "dense" if index % 4 == 3 else "sparse" + for index in range(text_config.num_hidden_layers) + ] + + +CONFIG_OVERRIDES = { + "minimax_m3_vl": _mix_minimax_layers, +} + + +def _quantizable_specs(definition: type[BaseQModel], config) -> tuple[str, ...]: + blocks = definition.simple_layer_modules( + model_config=config, + quantize_config=QC, + ) + return tuple(sorted({name.split(":", 1)[0] for block in blocks for name in block})) + + +def _missing_specs(specs: tuple[str, ...], resolved: set[str]) -> list[str]: + missing = [] + for spec in specs: + pattern = re.compile( + "^" + re.escape(spec).replace(re.escape(EXPERT_INDEX_PLACEHOLDER), r"\d+") + "$" + ) + if not any(pattern.match(name) for name in resolved): + missing.append(spec) + return missing + + +def _resolved_modules(layers) -> set[str]: + resolved = set() + for layer in layers: + resolved.update(find_modules(layer)) + return resolved + + +def _weight_owners(layer) -> set[str]: + """Return modules that own checkpoint state entries (weights/buffers). + + This intentionally reads ``state_dict()`` rather than ``named_parameters()`` + or ``named_buffers()``. Runtime-generated non-persistent buffers are not + checkpoint weights and must not become model-definition obligations. + """ + + modules = {name for name, _ in layer.named_modules() if name} + owners = set() + for weight_path in layer.state_dict(): + owner = max( + ( + name + for name in modules + if weight_path.startswith(f"{name}.") + and "." not in weight_path[len(name) + 1:] + ), + key=len, + default="", + ) + assert owner, f"state entry {weight_path!r} is not owned by a module" + owners.add(owner) + return owners + + +def _normalize_owner(owner: str) -> str: + return re.sub(r"(?<=\.)\d+(?=\.|$)", "#", owner) + + +def _build_meta_case(case: FlashCase) -> SimpleNamespace: + config = transformers.AutoConfig.for_model(case.model_type) + override = CONFIG_OVERRIDES.get(case.model_type) + if override is not None: + override(config) + + definition = MODEL_MAP[case.model_type] + with torch.device("meta"): + model = definition.loader.from_config(config) + + _convert_model_with_defuser(definition, model, cleanup_original=False) + layers, layer_names = get_layers_with_prefixes(model, definition.extract_layers_node()) + assert layers, f"{case.model_type}: no decoder layers resolved" + + return SimpleNamespace( + config=config, + definition=definition, + model=model, + layers=layers, + layer_names=layer_names, + specs=_quantizable_specs(definition, config), + resolved=_resolved_modules(layers), + plan=ModulePlan.from_tree(definition.module_tree), + ) + + +@pytest.fixture(scope="module", params=tuple(CASES.values()), ids=lambda case: case.model_type) +def flash_case(request): + return _build_meta_case(request.param) + + +def test_flash_definitions_build_real_meta_models(flash_case): + case = next(item for item in CASES.values() if item.definition is flash_case.definition) + + assert MODEL_MAP[case.model_type] is case.definition + assert type(flash_case.config).__name__ == case.config_class + assert flash_case.definition.extract_layers_node() == [case.layers_node] + + text_config = getattr(flash_case.config, "text_config", flash_case.config) + assert text_config.num_hidden_layers == case.layer_count + assert len(flash_case.layers) == case.layer_count + assert flash_case.layer_names[0] == f"{case.layers_node}.0" + assert flash_case.layer_names[-1] == f"{case.layers_node}.{case.layer_count - 1}" + assert len(flash_case.specs) == case.spec_count + + +def test_every_flash_quantizable_spec_resolves_on_the_real_model(flash_case): + case = next(item for item in CASES.values() if item.definition is flash_case.definition) + + assert not _missing_specs(flash_case.specs, flash_case.resolved), ( + f"{case.model_type}: quantizable module-tree entries matched no decoder " + f"layer: {_missing_specs(flash_case.specs, flash_case.resolved)[:12]}" + ) + assert set(case.key_modules) <= flash_case.resolved + + +def test_flash_tree_marks_nonquantized_modules_as_dense(flash_case): + case = next(item for item in CASES.values() if item.definition is flash_case.definition) + simple = { + name.split(":", 1)[0] + for block in flash_case.definition.simple_layer_modules(flash_case.config, QC) + for name in block + } + full = { + name.split(":", 1)[0] + for block in flash_case.definition.full_layer_modules( + model_config=flash_case.config, + include_capture_only=True, + ) + for name in block + } + + assert set(case.nonquantized) <= full + assert set(case.nonquantized).isdisjoint(simple) + + +def test_every_checkpoint_weight_owner_is_declared_with_the_right_tag(flash_case): + case = next(item for item in CASES.values() if item.definition is flash_case.definition) + quantized_patterns = [ + re.compile("^" + re.escape(spec).replace(re.escape(EXPERT_INDEX_PLACEHOLDER), r"\d+") + "$") + for spec in flash_case.specs + ] + owners = set() + for layer in flash_case.layers: + owners.update(_weight_owners(layer)) + + normalized_owners = {_normalize_owner(owner) for owner in owners} + assert len(normalized_owners) == case.weight_owner_count + + for owner in owners: + spec = flash_case.plan.find(owner) + assert spec is not None, ( + f"{case.model_type}: checkpoint weights owned by undeclared module {owner!r}" + ) + is_quantized = any(pattern.match(owner) for pattern in quantized_patterns) + if not is_quantized: + assert not spec.quantize, ( + f"{case.model_type}: non-quantized weight owner {owner!r} must carry " + f"an explicit `:!`/`:?` tag" + ) + + +def test_flash_module_plan_resolves_roles_and_moe_families(flash_case): + case = next(item for item in CASES.values() if item.definition is flash_case.definition) + plan = flash_case.plan + + for path, expected_roles in case.roles: + assert plan.roles(path) == expected_roles, path + + if case.moe: + assert tuple(spec.template for spec in plan.moe_roots()) == ("mlp",) + assert plan.expert_container_leaf("mlp") == "experts" + assert plan.shared_container_leaf("mlp") == "shared_experts" + assert plan.is_expert("mlp.experts.0.gate_proj") + assert plan.expert_root("mlp.experts.17.down_proj") == "mlp.experts.17" + assert plan.same_moe_family( + "mlp.experts.17.gate_proj", + "mlp.experts.17.down_proj", + ) + assert not plan.same_moe_family( + "mlp.experts.17.gate_proj", + "mlp.experts.18.down_proj", + ) + assert plan.is_moe("mlp.experts.17.gate_proj") + else: + assert plan.moe_roots() == () + assert plan.expert_containers() == () + assert plan.shared_expert_containers() == () + assert not plan.is_moe("mlp.down_proj") + + +def test_flash_is_moe_module_uses_exact_tree_paths(flash_case): + case = next(item for item in CASES.values() if item.definition is flash_case.definition) + definition = case.definition + first_layer = flash_case.layer_names[0] + + if case.moe: + assert definition.is_moe_module(f"{first_layer}.mlp") + assert definition.is_moe_module(f"{first_layer}.mlp.experts.0.gate_proj") + assert definition.is_moe_module("layers.0.mlp.experts.0.gate_proj") + assert not definition.is_moe_module(f"{first_layer}.self_attn.q_proj") + else: + assert not definition.is_moe_module(f"{first_layer}.mlp") + assert not definition.is_moe_module(f"{first_layer}.mlp.down_proj") + + +def test_flash_moe_hooks_follow_the_declared_containers(flash_case): + case = next(item for item in CASES.values() if item.definition is flash_case.definition) + hooks = getattr(case.definition, "moe_lifecycle_hooks", None) + if hooks is None: + assert not case.moe + return + + hooks = copy.copy(hooks) + hooks.module_plan = flash_case.plan + + moe_layer = flash_case.layers[case.moe_layer] + moe_block = hooks.get_moe_block(moe_layer, case.definition) + assert moe_block is not None + assert hooks.get_experts_module_name(moe_block) == "experts" + assert hooks.get_shared_experts_module_name(moe_block) == "shared_experts" + assert hooks.get_experts_module(moe_block, case.definition) is not None + assert hooks.get_shared_experts_module(moe_block, case.definition) is not None + + if case.dense_layer is not None: + dense_layer = flash_case.layers[case.dense_layer] + dense_block = hooks.get_moe_block(dense_layer, case.definition) + assert dense_block is not None + assert hooks.get_experts_module(dense_block, case.definition) is None + assert hooks.get_shared_experts_module(dense_block, case.definition) is None + + +def test_flash_looper_consumers_use_the_module_plan(flash_case): + case = next(item for item in CASES.values() if item.definition is flash_case.definition) + looper = ModuleLooper.__new__(ModuleLooper) + looper.gptq_model = SimpleNamespace(module_plan=flash_case.plan) + + for path, roles in case.roles: + assert looper._is_attention_module_name(path) == bool({"q", "k", "v"} & set(roles)), path + + if case.moe: + assert looper._extract_moe_group_key("mlp.experts.17.gate_proj") == "mlp.experts.17" + assert looper._extract_moe_group_key("mlp.shared_experts.gate_proj") is None + else: + assert looper._extract_moe_group_key("mlp.down_proj") is None + + +def test_ricursive_ripple_real_custom_model_matches_declared_tree(tmp_path): + ref_dir = _reference_dir() + if ref_dir is None: + pytest.skip("Ripple custom code unavailable (set GPTQMODEL_RIPPLE_REF to run offline)") + + model_dir = tmp_path / "ripple" + _build_tiny_fixture(ref_dir, model_dir) + + from transformers import AutoModelForCausalLM + + model = AutoModelForCausalLM.from_pretrained(str(model_dir), trust_remote_code=True).eval() + layers, layer_names = get_layers_with_prefixes(model, RicursiveQModel.extract_layers_node()) + assert len(layers) == 5 + assert layer_names[0] == "model.layers.0" + + specs = _quantizable_specs(RicursiveQModel, model.config) + resolved = _resolved_modules(layers) + assert not _missing_specs(specs, resolved) + + plan = ModulePlan.from_tree(RicursiveQModel.module_tree) + assert plan.moe_roots() == () + assert plan.expert_containers() == () + assert plan.roles("self_attn.q_proj") == ("q",) + assert plan.roles("self_attn.k_proj") == ("k",) + assert plan.roles("self_attn.v_proj") == ("v",) + assert plan.roles("self_attn.o_proj") == ("o",) + assert plan.roles("self_attn.g_proj") == () + assert plan.roles("mlp.gate_proj") == ("gate",) + assert plan.roles("mlp.up_proj") == ("up",) + assert plan.roles("mlp.down_proj") == ("down",) + + owners = set() + for layer in layers: + owners.update(_weight_owners(layer)) + assert {_normalize_owner(owner) for owner in owners} == { + "input_layernorm", + "mlp.down_proj", + "mlp.gate_proj", + "mlp.up_proj", + "post_attention_layernorm", + "post_feedforward_layernorm", + "pre_feedforward_layernorm", + "self_attn", + "self_attn.g_proj", + "self_attn.k_norm", + "self_attn.k_proj", + "self_attn.o_proj", + "self_attn.q_norm", + "self_attn.q_proj", + "self_attn.v_proj", + } + assert all(plan.find(owner) is not None for owner in owners) + assert not plan.find("self_attn").quantize + + assert not RicursiveQModel.is_moe_module("mlp.down_proj") + assert not RicursiveQModel.is_moe_module("model.layers.0.mlp.down_proj") + + looper = ModuleLooper.__new__(ModuleLooper) + looper.gptq_model = SimpleNamespace(module_plan=plan) + assert looper._is_attention_module_name("self_attn.q_proj") + assert looper._is_attention_module_name("self_attn.k_proj") + assert looper._is_attention_module_name("self_attn.v_proj") + assert not looper._is_attention_module_name("self_attn.g_proj") + assert not looper._is_attention_module_name("self_attn.o_proj") + assert looper._extract_moe_group_key("mlp.down_proj") is None + + +def test_deepseek_v41_flash_model_tree_when_upstream_support_lands(): + """Build V4.1 against its real checkpoint only once Transformers supports it. + + The checkpoint ``deepseek-ai/DeepSeek-V4.1-Flash`` declares + ``model_type=deepseek_v41``. Transformers 5.22.2 (the version used by this + suite) and its main branch contain only ``deepseek_v4``, so there is no + native config or model class to build. Keeping this test conditional means + it becomes real V4.1 coverage as soon as the upstream class and the + GPTQModel definition are added, instead of silently testing V4-Flash under a + V4.1 label. + """ + + if "deepseek_v41" not in CONFIG_MAPPING: + pytest.skip( + "Transformers has no deepseek_v41 config/model implementation; " + "DeepSeek-V4.1-Flash cannot be built as a true model yet" + ) + if "deepseek_v41" not in MODEL_MAP: + pytest.fail( + "Transformers now exposes deepseek_v41 but GPTQModel has no " + "DeepSeek-V4.1 definition; add the definition and tree tests" + ) + + config = transformers.AutoConfig.for_model("deepseek_v41") + definition = MODEL_MAP["deepseek_v41"] + with torch.device("meta"): + model = definition.loader.from_config(config) + _convert_model_with_defuser(definition, model, cleanup_original=False) + layers, _ = get_layers_with_prefixes(model, definition.extract_layers_node()) + assert layers + + specs = _quantizable_specs(definition, config) + assert not _missing_specs(specs, _resolved_modules(layers)) diff --git a/tests/module_tree/test_model_alignment.py b/tests/module_tree/test_model_alignment.py index 97222544ee..6f446c0b9d 100644 --- a/tests/module_tree/test_model_alignment.py +++ b/tests/module_tree/test_model_alignment.py @@ -245,9 +245,9 @@ def test_qwen3_5_linear_attention_module_tree(self): self.assertTrue(hasattr(decoder_layer.linear_attn, "conv1d")) self.assertTrue(hasattr(decoder_layer.linear_attn, "in_proj_b")) self.assertTrue(hasattr(decoder_layer.linear_attn, "in_proj_a")) - self.assertIn("conv1d:!", Qwen3_5QModel.module_tree[-1]["linear_attn"]) - self.assertIn("in_proj_b:!:1", Qwen3_5QModel.module_tree[-1]["linear_attn"]) - self.assertIn("in_proj_a:!:1", Qwen3_5QModel.module_tree[-1]["linear_attn"]) + self.assertIn("conv1d:!", Qwen3_5QModel.module_tree[-1]["linear_attn:!"]) + self.assertIn("in_proj_b:!:1", Qwen3_5QModel.module_tree[-1]["linear_attn:!"]) + self.assertIn("in_proj_a:!:1", Qwen3_5QModel.module_tree[-1]["linear_attn:!"]) class TestQwen3_5MoeModuleTree(ModelTest): diff --git a/tests/test_ricursive_support.py b/tests/test_ricursive_support.py index 08cc615684..97ef1ec6cf 100644 --- a/tests/test_ricursive_support.py +++ b/tests/test_ricursive_support.py @@ -81,14 +81,14 @@ def test_ricursive_module_tree_covers_perinorm_and_gated_attention(): assert set(layer) == { "input_layernorm", - "self_attn", + "self_attn:!", "post_attention_layernorm", "pre_feedforward_layernorm", "mlp", "post_feedforward_layernorm", } - attn = layer["self_attn"] + attn = layer["self_attn:!"] # Per-head Q/K RMSNorm must stay dense. assert "q_norm:!:norm" in attn assert "k_norm:!:norm" in attn From 587ffe738ada8a35f728b6c0bd9c2f9507fc2bee Mon Sep 17 00:00:00 2001 From: Qubitium Date: Fri, 6 Nov 2026 17:32:19 -0800 Subject: [PATCH 4/7] feat(models): expose inspectable module plans --- docs/model-tree-resolution.md | 31 ++- gptqmodel/__init__.py | 2 +- gptqmodel/looper/awq_processor.py | 3 +- gptqmodel/looper/gsq_training_awq.py | 3 +- gptqmodel/looper/module_looper.py | 5 +- gptqmodel/looper/stage_subset.py | 3 +- gptqmodel/looper/weight_only_looper.py | 5 +- gptqmodel/models/__init__.py | 1 + gptqmodel/models/base.py | 30 ++- gptqmodel/models/loader.py | 2 +- gptqmodel/models/module_plan.py | 244 +++++++++++++++++- .../module_tree/test_explicit_module_plan.py | 101 ++++++++ .../test_flash_model_tree_consumption.py | 4 +- 13 files changed, 414 insertions(+), 20 deletions(-) diff --git a/docs/model-tree-resolution.md b/docs/model-tree-resolution.md index f495cbb54d..6cd8ac9b52 100644 --- a/docs/model-tree-resolution.md +++ b/docs/model-tree-resolution.md @@ -100,6 +100,35 @@ flowchart LR style S fill:#d9f7be,stroke:#237804 ``` +### Inspection API + +The compiled plan is attached to every model instance and is retrieved through +one public method: + +```python +plan = model.module_plan() + +plan.print() # TUI tree, ANSI auto-detected +plan.print(color=False) # plain log-safe output +plan.print(max_depth=2) # cap very large trees +text = plan.render(color=False) +payload = plan.to_dict() # JSON-friendly extraction/debug data +json_text = plan.to_json() +summary = plan.summary() +``` + +`ModulePlan` and `ModuleSpec` are exported from both `gptqmodel` and +`gptqmodel.models`. `model.module_plan()` raises if called before the model has a +compiled plan; it never guesses or recompiles a tree. + +The tree renderer marks: + +- `[quantize]` — declared as a quantization leaf. +- `[excluded]` / `[capture-only]` — non-quantized declarations. +- `[moe]`, `[expert-container]`, `[shared-expert]`, `[expert]` — MoE structure. +- `[roles=q]`, `[in=x]`, `[group=0]` — projection roles, shared input, and group. +- `[container]` — structural parent, not itself a quantization target. + ### Declaration syntax ``` @@ -240,7 +269,7 @@ Llama layout: ```mermaid flowchart TD - R["rotate_model(plan=self.module_plan)"] --> N1["plan.child_roles('', 'norm')
→ exactly 2 norms"] + R["rotate_model(plan=self.module_plan())"] --> N1["plan.child_roles('', 'norm')
→ exactly 2 norms"] R --> P1["_rotation_parents(plan)
attention parent + MLP parent"] P1 --> Q1["_resolve_role(layer, plan, parent, 'q'|'k'|'v'|'o')"] P1 --> Q2["_resolve_role(layer, plan, parent, 'gate'|'up'|'down')"] diff --git a/gptqmodel/__init__.py b/gptqmodel/__init__.py index 86a4a56b30..9844461594 100644 --- a/gptqmodel/__init__.py +++ b/gptqmodel/__init__.py @@ -341,7 +341,7 @@ def exllama_set_max_input_length(model, max_input_length: int): from . import extension from .looper.checkpoint import CheckpointStopped from .looper.checkpoint_store import CheckpointConfig -from .models import GPTQModel, get_best_device +from .models import GPTQModel, ModulePlan, ModuleSpec, get_best_device from .models.auto import ASCII_LOGO, TRANSFORMERS_VERSION from .quantization import ( AWQConfig, diff --git a/gptqmodel/looper/awq_processor.py b/gptqmodel/looper/awq_processor.py index a268bab785..6aff2f6364 100644 --- a/gptqmodel/looper/awq_processor.py +++ b/gptqmodel/looper/awq_processor.py @@ -20,6 +20,7 @@ from ..looper.named_module import NamedModule from ..models import BaseQModel from ..models._const import DEVICE, SUPPORTS_MODULE_TYPES +from ..models.module_plan import _model_module_plan from ..models.writer import ( PROCESS_LOG_LAYER, PROCESS_LOG_MODULE, @@ -1583,7 +1584,7 @@ def unwrap(m): if staged_gsq is not None and staged_gsq.enabled: from .gsq_training_awq import capture_awq_staged_teacher - plan = getattr(self.gptq_model, "module_plan", None) + plan = _model_module_plan(self.gptq_model) projections = tuple( name for name, named in named_childs.items() if plan is None or plan.roles(name) diff --git a/gptqmodel/looper/gsq_training_awq.py b/gptqmodel/looper/gsq_training_awq.py index b194a85e93..bb959ee368 100644 --- a/gptqmodel/looper/gsq_training_awq.py +++ b/gptqmodel/looper/gsq_training_awq.py @@ -7,6 +7,7 @@ import torch +from ..models.module_plan import _model_module_plan from .gsq_training_capture import prepare_llama_gsq_capture @@ -52,7 +53,7 @@ def refine_awq_staged_layer(processor, teacher_capture, modules, *, layer_index) group_size=processor.qcfg.group_size, affine_initializers=True, reinitialize_mlp=False, projections=projections, **options) payloads = {} - plan = getattr(processor.gptq_model, "module_plan", None) + plan = _model_module_plan(processor.gptq_model) attention_parents = {spec.parent for spec in plan.specs if "q" in spec.roles} if plan else () mlp_parents = {spec.parent for spec in plan.specs if "gate" in spec.roles} if plan else () diff --git a/gptqmodel/looper/module_looper.py b/gptqmodel/looper/module_looper.py index 8d8ceb1872..b42a41d0d2 100644 --- a/gptqmodel/looper/module_looper.py +++ b/gptqmodel/looper/module_looper.py @@ -35,6 +35,7 @@ from ..models import BaseQModel from ..models._const import SUPPORTS_MODULE_TYPES from ..models.base import CAPTURE_ONLY_FLAG +from ..models.module_plan import _model_module_plan from ..nn_modules.hooked_linear import HookedLinear from ..quantization.config import ( METHOD, @@ -921,7 +922,7 @@ def _extract_moe_group_key(self, module_name: Optional[str]) -> Optional[str]: if not module_name: return None - plan = getattr(self.gptq_model, "module_plan", None) + plan = _model_module_plan(self.gptq_model) if plan is None: return None return plan.expert_root(module_name) @@ -929,7 +930,7 @@ def _extract_moe_group_key(self, module_name: Optional[str]) -> Optional[str]: def _is_attention_module_name(self, module_name: str) -> bool: """Return whether the declared tree marks this path as attention.""" - plan = getattr(self.gptq_model, "module_plan", None) + plan = _model_module_plan(self.gptq_model) if plan is None or not module_name: return False return "q" in plan.roles(module_name) or "k" in plan.roles(module_name) or "v" in plan.roles(module_name) diff --git a/gptqmodel/looper/stage_subset.py b/gptqmodel/looper/stage_subset.py index e75e2cf36d..9e0a7b20ce 100644 --- a/gptqmodel/looper/stage_subset.py +++ b/gptqmodel/looper/stage_subset.py @@ -29,6 +29,7 @@ from ..looper.loop_processor import LoopProcessor from ..looper.named_module import NamedModule from ..models._const import META +from ..models.module_plan import _model_module_plan from ..quantization.config import ExpertsRoutingBypass, GcMode, VramStrategy, normalize_bypass_batch_size from ..utils.device import get_device from ..utils.device_telemetry import emit_device_telemetry @@ -494,7 +495,7 @@ def build_subset_plan( if moe_strategy_active and moe_groups and moe_devices: assignable_group_keys = _collect_assignable_moe_group_keys( moe_groups, - getattr(looper.gptq_model, "module_plan", None), + _model_module_plan(looper.gptq_model), ) if assignable_group_keys: if looper._moe_vram_strategy == VramStrategy.BALANCED and len(moe_devices) > 1: diff --git a/gptqmodel/looper/weight_only_looper.py b/gptqmodel/looper/weight_only_looper.py index 41561886d3..1d4c3b3e2a 100644 --- a/gptqmodel/looper/weight_only_looper.py +++ b/gptqmodel/looper/weight_only_looper.py @@ -31,6 +31,7 @@ from ..looper.weight_only_processor import WeightOnlyProcessor from ..models import BaseQModel from ..models._const import CPU, SUPPORTS_MODULE_TYPES +from ..models.module_plan import _model_module_plan from ..nn_modules.converter import MODULE_CONVERTER_MAP from ..quantization.config import ( BitsAndBytesConfig, @@ -219,7 +220,7 @@ def _resolve_strategy_device_pools(self) -> None: def _extract_moe_group_key(self, module_name: Optional[str]) -> Optional[str]: """Return the expert family key used to co-locate gate/up/down modules.""" - plan = getattr(self.gptq_model, "module_plan", None) + plan = _model_module_plan(self.gptq_model) return plan.expert_root(module_name) if plan is not None and module_name else None def _collect_assignable_moe_group_keys(self, moe_groups: Dict[str, List[str]]) -> List[str]: @@ -227,7 +228,7 @@ def _collect_assignable_moe_group_keys(self, moe_groups: Dict[str, List[str]]) - assignable_group_keys: List[str] = [] for group_key, module_names in moe_groups.items(): - plan = getattr(self.gptq_model, "module_plan", None) + plan = _model_module_plan(self.gptq_model) if plan is None: assignable_group_keys.append(group_key) continue diff --git a/gptqmodel/models/__init__.py b/gptqmodel/models/__init__.py index 0d3419ce25..22192b4f87 100644 --- a/gptqmodel/models/__init__.py +++ b/gptqmodel/models/__init__.py @@ -7,3 +7,4 @@ from .auto import MODEL_MAP, GPTQModel from .base import BaseQModel from .definitions import * +from .module_plan import ModulePlan, ModuleSpec diff --git a/gptqmodel/models/base.py b/gptqmodel/models/base.py index e4e6a0f113..077c5fa546 100644 --- a/gptqmodel/models/base.py +++ b/gptqmodel/models/base.py @@ -492,7 +492,7 @@ def __init__( # class definitions remain reusable by later instances. self.effective_module_tree = _freeze_module_tree(effective_tree) self.module_tree = self.effective_module_tree - self.module_plan = ModulePlan.from_tree(self.effective_module_tree) + self._module_plan = ModulePlan.from_tree(self.effective_module_tree) # record configuration early so model lifecycle hooks can rely on them @@ -528,7 +528,7 @@ def __init__( if hooks is not None: hooks = copy.copy(hooks) self.moe_lifecycle_hooks = hooks - hooks.module_plan = self.module_plan + hooks.module_plan = self._module_plan if (getattr(quantize_config, "dynamic", None) and hasattr(self.model, "named_modules") and (not dynamic_cache_prepared or self.model is not model @@ -652,6 +652,20 @@ def invoke_with_effective_tree(*args, **kwargs): invoke_with_effective_tree.__gptqmodel_tree_bound__ = True return invoke_with_effective_tree + def module_plan(self) -> ModulePlan: + """Return the immutable module plan compiled for this model instance.""" + + try: + plan = object.__getattribute__(self, "_module_plan") + except AttributeError: + plan = None + if not isinstance(plan, ModulePlan): + raise RuntimeError( + f"{type(self).__name__}: module plan is not compiled yet; " + "construct the quantized model before inspecting it" + ) + return plan + @classmethod def extract_layers_node(cls): """ @@ -1671,7 +1685,7 @@ def quantize( } self.model = fuse_layer_norms(model=self.model, pre_lm_head_norm_module_name=self.pre_lm_head_norm_module, - plan=self.module_plan, + plan=self._module_plan, **module_name_args) # MPS does not support float64. @@ -1683,7 +1697,7 @@ def quantize( if rotation_device is not None and rotation_device.type == "mps": rotation_device = CPU self.model, _ = rotate_model(model=self.model, rotate_mode=self.quantize_config.rotation, - device=rotation_device, plan=self.module_plan, + device=rotation_device, plan=self._module_plan, embedding_name=self.get_input_embeddings_name(), **module_name_args) @@ -1772,7 +1786,7 @@ def quantize( _setup_rotation_online_had( self.model, self.quantize_config.rotation, - module_plan=self.module_plan, + module_plan=self._module_plan, layer_prefixes=self.extract_layers_node(), ) if self.quantize_config.dynamic: @@ -3790,7 +3804,7 @@ def awq_input_feature_aggregation(cls, module_name: str) -> Optional[Dict[str, A if not isinstance(module_name, str): return None - plan = getattr(cls, "module_plan", None) or ModulePlan.from_tree(_module_tree_for_class(cls)) + plan = ModulePlan.from_tree(_module_tree_for_class(cls)) for moe_root in (spec.template for spec in plan.moe_roots()) or cls.get_moe_module_name() or []: if module_name == moe_root: return { @@ -3882,7 +3896,9 @@ def _module_kwargs_for_feature(feature_name: str | None): _try_update_last_module(candidate_name) continue - plan = getattr(self, "module_plan", None) or ModulePlan.from_tree(_module_tree_for_class(type(self))) + plan = getattr(self, "_module_plan", None) or ModulePlan.from_tree( + _module_tree_for_class(type(self)) + ) block_roles = { name: plan.roles(strip_non_quantize_flags(name)) for name in block diff --git a/gptqmodel/models/loader.py b/gptqmodel/models/loader.py index fdb03a0a73..b859ca1dfd 100644 --- a/gptqmodel/models/loader.py +++ b/gptqmodel/models/loader.py @@ -2427,7 +2427,7 @@ def assign(mod, device_id): _setup_rotation_online_had( instance.model, qcfg.rotation, - module_plan=getattr(instance, "module_plan", None), + module_plan=instance.module_plan(), layer_prefixes=instance.extract_layers_node(), ) _set_paged_attention_safe_cuda_graphs(instance.model) diff --git a/gptqmodel/models/module_plan.py b/gptqmodel/models/module_plan.py index 0ab18076f9..3394f2e8b4 100644 --- a/gptqmodel/models/module_plan.py +++ b/gptqmodel/models/module_plan.py @@ -15,10 +15,13 @@ from __future__ import annotations +import json import re -from dataclasses import dataclass +import sys +from dataclasses import dataclass, field from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple +from ..utils.colors import ANSIColor, color_text from ._const import EXPERT_INDEX_PLACEHOLDER as _EXPERT_PLACEHOLDER @@ -123,6 +126,14 @@ def matches(self, path: str) -> bool: return bool(self.pattern.match(path)) +@dataclass +class _PlanNode: + name: str + path: str + spec: Optional[ModuleSpec] = None + children: Dict[str, "_PlanNode"] = field(default_factory=dict) + + def collect_module_specs(module_tree: Any) -> Dict[str, ModuleSpec]: """Collect every path declared under a tree's decoder ``#`` boundary.""" @@ -165,6 +176,25 @@ def walk(node: Any, parent: str) -> None: return specs +def _model_module_plan(model: Any) -> Optional["ModulePlan"]: + """Resolve a live model's plan for internal consumers. + + The public accessor is ``model.module_plan()``. Partial models used by + focused unit tests may not have a compiled plan; those callers receive + ``None`` and retain their existing fallback behavior. + """ + + accessor = getattr(model, "module_plan", None) + if callable(accessor): + try: + return accessor() + except RuntimeError: + return None + if isinstance(accessor, ModulePlan): + return accessor + return getattr(model, "_module_plan", None) + + class ModulePlan: """Layer-relative inventory and role queries for one effective model tree.""" @@ -182,6 +212,218 @@ def from_tree(cls, module_tree: Any) -> "ModulePlan": def specs(self) -> Tuple[ModuleSpec, ...]: return tuple(self._specs.values()) + def summary(self) -> Dict[str, Any]: + """Return a compact, JSON-friendly inventory summary.""" + + quantized = sum(1 for spec in self._specs.values() if spec.quantize) + capture_only = sum(1 for spec in self._specs.values() if spec.capture_only) + return { + "spec_count": len(self._specs), + "quantized_count": quantized, + "excluded_count": len(self._specs) - quantized - capture_only, + "capture_only_count": capture_only, + "moe_roots": [spec.template for spec in self.moe_roots()], + "expert_containers": list(self.expert_containers()), + "shared_expert_containers": list(self.shared_expert_containers()), + } + + def to_dict(self) -> Dict[str, Any]: + """Return the compiled plan as a JSON-serializable debug structure.""" + + containers = self._container_templates() + return { + "summary": self.summary(), + "specs": [ + { + "template": spec.template, + "parent": spec.parent, + "flags": list(spec.flags), + "roles": list(spec.roles), + "quantize": spec.quantize, + "capture_only": spec.capture_only, + "moe": spec.is_moe, + "container": spec.template in containers, + "expert_placeholder": spec.is_expert_placeholder, + } + for spec in self._specs.values() + ], + } + + def to_json(self, *, indent: int = 2) -> str: + """Serialize ``to_dict()`` for logs, bug reports, or extraction tools.""" + + return json.dumps(self.to_dict(), indent=indent) + + def print(self, *, file: Any = None, **render_kwargs) -> None: + """Print the rendered plan. This is the debug/TUI entry point.""" + + print(self.render(**render_kwargs), file=file) + + def render( + self, + *, + color: Optional[bool] = None, + max_depth: Optional[int] = None, + show_summary: bool = True, + ) -> str: + """Render the plan as a TUI-friendly tree. + + ``color=None`` auto-detects a terminal. Pass ``color=False`` for logs + and tests, or ``color=True`` in a TUI that wants ANSI styling. + """ + + if color is None: + color = sys.stdout.isatty() + + summary = self.summary() + lines = [] + if show_summary: + lines.append( + "ModulePlan: " + f"{summary['spec_count']} specs | " + f"{summary['quantized_count']} quantized | " + f"{summary['excluded_count']} excluded | " + f"{summary['capture_only_count']} capture-only" + ) + roots = ", ".join(summary["moe_roots"]) or "-" + expert_containers = ", ".join(summary["expert_containers"]) or "-" + shared_containers = ", ".join(summary["shared_expert_containers"]) or "-" + lines.append(f"MoE roots: {roots}") + lines.append(f"Experts: {expert_containers}") + lines.append(f"Shared experts: {shared_containers}") + lines.append("") + + root = self._build_render_tree() + for index, child in enumerate(root.children.values()): + self._render_node( + child, + lines=lines, + prefix="", + is_last=index == len(root.children) - 1, + depth=1, + color=color, + max_depth=max_depth, + ) + return "\n".join(lines) + + def __str__(self) -> str: + return self.render() + + def __repr__(self) -> str: + summary = self.summary() + return ( + f"ModulePlan(specs={summary['spec_count']}, " + f"quantized={summary['quantized_count']}, " + f"excluded={summary['excluded_count']}, " + f"moe_roots={summary['moe_roots']})" + ) + + def _build_render_tree(self) -> _PlanNode: + root = _PlanNode(name="", path="") + for spec in self._specs.values(): + node = root + path = [] + for segment in spec.template.split("."): + path.append(segment) + child_path = ".".join(path) + node = node.children.setdefault(segment, _PlanNode(name=segment, path=child_path)) + node.spec = spec + return root + + def _container_templates(self) -> set[str]: + parents = {spec.parent for spec in self._specs.values() if spec.parent} + return { + spec.template + for spec in self._specs.values() + if any(parent == spec.template or parent.startswith(f"{spec.template}.") for parent in parents) + } + + def _render_node( + self, + node: _PlanNode, + *, + lines: List[str], + prefix: str, + is_last: bool, + depth: int, + color: bool, + max_depth: Optional[int], + ) -> None: + connector = "└─ " if is_last else "├─ " + lines.append(f"{prefix}{connector}{self._format_node(node, color=color)}") + child_prefix = f"{prefix}{' ' if is_last else '│ '}" + + if max_depth is not None and depth >= max_depth and node.children: + remaining = self._descendant_count(node) + ellipsis = "└─ " if len(node.children) > 0 else "" + lines.append(f"{child_prefix}{ellipsis}… {remaining} descendant path(s)") + return + + children = list(node.children.values()) + for index, child in enumerate(children): + self._render_node( + child, + lines=lines, + prefix=child_prefix, + is_last=index == len(children) - 1, + depth=depth + 1, + color=color, + max_depth=max_depth, + ) + + def _format_node(self, node: _PlanNode, *, color: bool) -> str: + label = "{expert_index}" if node.name == _EXPERT_PLACEHOLDER else node.name + badges = [] + spec = node.spec + + if spec is None: + badges.append(self._badge("container", "\033[90m", color=color)) + else: + is_container = bool(node.children) + if spec.is_moe: + badges.append(self._badge("moe", ANSIColor.ORANGE, color=color)) + if is_container: + badges.append(self._badge("container", "\033[90m", color=color)) + if not spec.quantize: + badges.append(self._badge("excluded", ANSIColor.YELLOW, color=color)) + elif spec.capture_only: + badges.append(self._badge("capture-only", ANSIColor.CYAN, color=color)) + elif spec.quantize: + badges.append(self._badge("quantize", ANSIColor.BRIGHT_GREEN, color=color)) + else: + badges.append(self._badge("excluded", ANSIColor.YELLOW, color=color)) + + for flag in spec.flags: + if flag.isdigit(): + badges.append(self._badge(f"group={flag}", ANSIColor.ORANGE, color=color)) + elif flag.startswith("in="): + badges.append(self._badge(flag, ANSIColor.CYAN, color=color)) + elif flag == "norm": + badges.append(self._badge("norm", ANSIColor.CYAN, color=color)) + + if spec.roles: + badges.append( + self._badge(f"roles={','.join(spec.roles)}", ANSIColor.CYAN, color=color) + ) + + if node.path in self.expert_containers(): + badges.append(self._badge("expert-container", ANSIColor.ORANGE, color=color)) + if node.path in self.shared_expert_containers(): + badges.append(self._badge("shared-expert", ANSIColor.ORANGE, color=color)) + if node.name == _EXPERT_PLACEHOLDER: + badges.append(self._badge("expert", ANSIColor.ORANGE, color=color)) + + name = color_text(label, ANSIColor.CYAN) if color else label + return f"{name} {' '.join(badges)}" if badges else name + + @staticmethod + def _badge(label: str, color_code: Any, *, color: bool) -> str: + text = f"[{label}]" + return color_text(text, color_code) if color else text + + def _descendant_count(self, node: _PlanNode) -> int: + return sum(1 + self._descendant_count(child) for child in node.children.values()) + def find(self, path: str) -> Optional[ModuleSpec]: spec = self._specs.get(path) if spec is not None: diff --git a/tests/module_tree/test_explicit_module_plan.py b/tests/module_tree/test_explicit_module_plan.py index 195f96cb8b..166d97b12c 100644 --- a/tests/module_tree/test_explicit_module_plan.py +++ b/tests/module_tree/test_explicit_module_plan.py @@ -1,6 +1,10 @@ # SPDX-FileCopyrightText: 2026 ModelCloud.ai # SPDX-License-Identifier: Apache-2.0 +import io +import json + +import pytest import torch.nn as nn from gptqmodel.models.base import BaseQModel @@ -123,3 +127,100 @@ class Model: config = Config() assert UndefinedTree._resolve_effective_module_tree(Model(), object()) is None + + +def _render_plan() -> ModulePlan: + return ModulePlan.from_tree([ + "model", "layers", "#", + { + "self_attn:!": ( + "q_proj:0:q:in=x", + "k_proj:0:k:in=x", + "v_proj:0:v", + "o_proj:1:o", + ), + "mlp:moe": { + "gate": ("gate:!",), + "experts": {"#": ("gate_proj:0:gate", "up_proj:0:up", "down_proj:1:down")}, + "shared_experts": ( + "gate_proj:0:gate", + "up_proj:0:up", + "down_proj:1:down", + ), + }, + }, + ]) + + +def test_module_plan_renders_a_tui_tree(): + plan = _render_plan() + + rendered = plan.render(color=False) + assert "ModulePlan: 16 specs | 14 quantized | 2 excluded | 0 capture-only" in rendered + assert "MoE roots: mlp" in rendered + assert "├─ self_attn [container] [excluded]" in rendered + assert "q_proj [quantize] [group=0] [in=x] [roles=q]" in rendered + assert "{expert_index} [container] [expert]" in rendered + assert "shared_experts [container] [shared-expert]" in rendered + assert "… 4 descendant path(s)" in plan.render(color=False, max_depth=1, show_summary=False) + + +def test_module_plan_print_and_extraction_payload(): + plan = _render_plan() + + output = io.StringIO() + plan.print(file=output, color=False) + assert output.getvalue() == plan.render(color=False) + "\n" + + payload = plan.to_dict() + assert payload["summary"] == { + "spec_count": 16, + "quantized_count": 14, + "excluded_count": 2, + "capture_only_count": 0, + "moe_roots": ["mlp"], + "expert_containers": ["mlp.experts"], + "shared_expert_containers": ["mlp.shared_experts"], + } + q_proj = next(spec for spec in payload["specs"] if spec["template"] == "self_attn.q_proj") + assert q_proj == { + "template": "self_attn.q_proj", + "parent": "self_attn", + "flags": ["0", "q", "in=x"], + "roles": ["q"], + "quantize": True, + "capture_only": False, + "moe": False, + "container": False, + "expert_placeholder": False, + } + experts = next(spec for spec in payload["specs"] if spec["template"] == "mlp.experts") + assert experts["container"] is True + assert json.loads(plan.to_json()) == payload + + +def test_model_plan_returns_the_compiled_plan(capsys): + plan = _render_plan() + model = object.__new__(BaseQModel) + model._module_plan = plan + + assert model.module_plan() is plan + model.module_plan().print(color=False) + assert "ModulePlan: 16 specs" in capsys.readouterr().out + + +def test_module_plan_is_exported_from_public_package_roots(): + from gptqmodel import ModulePlan as public_module_plan + from gptqmodel.models import ModulePlan as models_module_plan + from gptqmodel.models import ModuleSpec as models_module_spec + + assert public_module_plan is ModulePlan + assert models_module_plan is ModulePlan + assert models_module_spec is not None + + +def test_model_plan_fails_loudly_without_a_compiled_plan(): + model = object.__new__(BaseQModel) + + with pytest.raises(RuntimeError, match="module plan is not compiled yet"): + model.module_plan() diff --git a/tests/module_tree/test_flash_model_tree_consumption.py b/tests/module_tree/test_flash_model_tree_consumption.py index 8a9ec405d9..3ca97161da 100644 --- a/tests/module_tree/test_flash_model_tree_consumption.py +++ b/tests/module_tree/test_flash_model_tree_consumption.py @@ -533,7 +533,7 @@ def test_flash_moe_hooks_follow_the_declared_containers(flash_case): def test_flash_looper_consumers_use_the_module_plan(flash_case): case = next(item for item in CASES.values() if item.definition is flash_case.definition) looper = ModuleLooper.__new__(ModuleLooper) - looper.gptq_model = SimpleNamespace(module_plan=flash_case.plan) + looper.gptq_model = SimpleNamespace(module_plan=lambda: flash_case.plan) for path, roles in case.roles: assert looper._is_attention_module_name(path) == bool({"q", "k", "v"} & set(roles)), path @@ -603,7 +603,7 @@ def test_ricursive_ripple_real_custom_model_matches_declared_tree(tmp_path): assert not RicursiveQModel.is_moe_module("model.layers.0.mlp.down_proj") looper = ModuleLooper.__new__(ModuleLooper) - looper.gptq_model = SimpleNamespace(module_plan=plan) + looper.gptq_model = SimpleNamespace(module_plan=lambda: plan) assert looper._is_attention_module_name("self_attn.q_proj") assert looper._is_attention_module_name("self_attn.k_proj") assert looper._is_attention_module_name("self_attn.v_proj") From 2d0ecbd4f5a1e887c511b2a63d92ad0eafbd43c9 Mon Sep 17 00:00:00 2001 From: Qubitium Date: Fri, 6 Nov 2026 17:34:24 -0800 Subject: [PATCH 5/7] refactor(models): route plan consumers through accessor --- docs/model-tree-resolution.md | 3 ++- gptqmodel/models/base.py | 15 ++++++++------- gptqmodel/models/module_plan.py | 4 +--- tests/module_tree/test_explicit_module_plan.py | 15 ++++++++++++++- 4 files changed, 25 insertions(+), 12 deletions(-) diff --git a/docs/model-tree-resolution.md b/docs/model-tree-resolution.md index 6cd8ac9b52..da46a243bf 100644 --- a/docs/model-tree-resolution.md +++ b/docs/model-tree-resolution.md @@ -119,7 +119,8 @@ summary = plan.summary() `ModulePlan` and `ModuleSpec` are exported from both `gptqmodel` and `gptqmodel.models`. `model.module_plan()` raises if called before the model has a -compiled plan; it never guesses or recompiles a tree. +compiled plan; it never guesses or recompiles a tree. All internal consumers +resolve the plan through this accessor rather than reading the backing field. The tree renderer marks: diff --git a/gptqmodel/models/base.py b/gptqmodel/models/base.py index 077c5fa546..5059ec9854 100644 --- a/gptqmodel/models/base.py +++ b/gptqmodel/models/base.py @@ -528,7 +528,7 @@ def __init__( if hooks is not None: hooks = copy.copy(hooks) self.moe_lifecycle_hooks = hooks - hooks.module_plan = self._module_plan + hooks.module_plan = self.module_plan() if (getattr(quantize_config, "dynamic", None) and hasattr(self.model, "named_modules") and (not dynamic_cache_prepared or self.model is not model @@ -1685,7 +1685,7 @@ def quantize( } self.model = fuse_layer_norms(model=self.model, pre_lm_head_norm_module_name=self.pre_lm_head_norm_module, - plan=self._module_plan, + plan=self.module_plan(), **module_name_args) # MPS does not support float64. @@ -1697,7 +1697,7 @@ def quantize( if rotation_device is not None and rotation_device.type == "mps": rotation_device = CPU self.model, _ = rotate_model(model=self.model, rotate_mode=self.quantize_config.rotation, - device=rotation_device, plan=self._module_plan, + device=rotation_device, plan=self.module_plan(), embedding_name=self.get_input_embeddings_name(), **module_name_args) @@ -1786,7 +1786,7 @@ def quantize( _setup_rotation_online_had( self.model, self.quantize_config.rotation, - module_plan=self._module_plan, + module_plan=self.module_plan(), layer_prefixes=self.extract_layers_node(), ) if self.quantize_config.dynamic: @@ -3896,9 +3896,10 @@ def _module_kwargs_for_feature(feature_name: str | None): _try_update_last_module(candidate_name) continue - plan = getattr(self, "_module_plan", None) or ModulePlan.from_tree( - _module_tree_for_class(type(self)) - ) + try: + plan = self.module_plan() + except RuntimeError: + plan = ModulePlan.from_tree(_module_tree_for_class(type(self))) block_roles = { name: plan.roles(strip_non_quantize_flags(name)) for name in block diff --git a/gptqmodel/models/module_plan.py b/gptqmodel/models/module_plan.py index 3394f2e8b4..51c1c5e832 100644 --- a/gptqmodel/models/module_plan.py +++ b/gptqmodel/models/module_plan.py @@ -190,9 +190,7 @@ def _model_module_plan(model: Any) -> Optional["ModulePlan"]: return accessor() except RuntimeError: return None - if isinstance(accessor, ModulePlan): - return accessor - return getattr(model, "_module_plan", None) + return None class ModulePlan: diff --git a/tests/module_tree/test_explicit_module_plan.py b/tests/module_tree/test_explicit_module_plan.py index 166d97b12c..9598ed1460 100644 --- a/tests/module_tree/test_explicit_module_plan.py +++ b/tests/module_tree/test_explicit_module_plan.py @@ -8,7 +8,7 @@ import torch.nn as nn from gptqmodel.models.base import BaseQModel -from gptqmodel.models.module_plan import ModulePlan +from gptqmodel.models.module_plan import ModulePlan, _model_module_plan from gptqmodel.utils.model import get_module_by_name_prefix, get_module_by_name_suffix @@ -224,3 +224,16 @@ def test_model_plan_fails_loudly_without_a_compiled_plan(): with pytest.raises(RuntimeError, match="module plan is not compiled yet"): model.module_plan() + + +def test_internal_consumers_resolve_the_plan_through_the_public_method(): + plan = _render_plan() + + class _Model: + _module_plan = object() + + def module_plan(self): + return plan + + assert _model_module_plan(_Model()) is plan + assert _model_module_plan(object()) is None From c9b38ccbfeb79015102e297e9c98913c39815133 Mon Sep 17 00:00:00 2001 From: Qubitium Date: Sat, 7 Nov 2026 02:10:24 +0000 Subject: [PATCH 6/7] fix(models): enforce declared expert paths and fixed expert indices --- docs/model-tree-resolution.md | 18 ++++++ gptqmodel/models/module_plan.py | 19 ++++++- gptqmodel/models/moe_lifecycle.py | 23 +++++++- .../module_tree/test_explicit_module_plan.py | 57 +++++++++++++++++++ 4 files changed, 111 insertions(+), 6 deletions(-) diff --git a/docs/model-tree-resolution.md b/docs/model-tree-resolution.md index da46a243bf..0a5b93278b 100644 --- a/docs/model-tree-resolution.md +++ b/docs/model-tree-resolution.md @@ -175,6 +175,24 @@ routed `#` container and carries no router-only role. Definitions therefore do not need to spell `shared_experts`, `shared_expert`, or `shared_mlp`; declaring the branch is enough. +An explicitly numbered expert also belongs to the routed container. For example, +Hymba declares `moe.experts.0` instead of a `#` placeholder. Its projection +children make `moe.experts` an expert container, and the numbered branch is not +classified as a shared expert. Expert-family queries still require the full +path to be declared in the tree. + +```mermaid +flowchart TD + ROOT["declared MoE root"] --> CHILD{"declared child structure"} + CHILD -->|"# placeholder"| ROUTED["expert_containers()"] + CHILD -->|"numeric child with projection leaves"| ROUTED + CHILD -->|"other projection family"| SHARED["shared_expert_containers()"] + ROUTED --> FIND{"ModulePlan.find(path)"} + FIND -->|"declared"| GROUP["is_expert() / expert_root()"] + FIND -->|"undeclared"| REJECT["False / None"] + style REJECT fill:#ffa39e,stroke:#a8071a +``` + ## What each subsystem asks ```mermaid diff --git a/gptqmodel/models/module_plan.py b/gptqmodel/models/module_plan.py index 51c1c5e832..fbcf376518 100644 --- a/gptqmodel/models/module_plan.py +++ b/gptqmodel/models/module_plan.py @@ -441,7 +441,7 @@ def roles(self, path: str) -> Tuple[str, ...]: return () if spec is None else spec.roles def is_expert(self, path: str) -> bool: - if not isinstance(path, str) or not path: + if not isinstance(path, str) or not path or self.find(path) is None: return False for container in self.expert_containers(): prefix = container.split(f".{_EXPERT_PLACEHOLDER}", 1)[0] @@ -462,6 +462,17 @@ def expert_containers(self) -> Tuple[str, ...]: for spec in self._specs.values() if spec.is_expert_placeholder } + # A fixed numeric index under a MoE root is an expert too. Hymba, for + # example, declares only `moe.experts.0` rather than a `#` placeholder. + moe_roots = tuple(spec.template for spec in self.moe_roots()) + projection_parents = {spec.parent for spec in self._specs.values() if spec.roles} + for spec in self._specs.values(): + if not spec.name.isdigit() or not any( + _path_has_segment(spec.template, root) for root in moe_roots + ): + continue + if spec.template in projection_parents: + containers.add(spec.parent) return tuple(sorted(containers)) def shared_expert_containers(self) -> Tuple[str, ...]: @@ -472,7 +483,7 @@ def shared_expert_containers(self) -> Tuple[str, ...]: a shared/parallel expert family (for example ``shared_experts`` or ``shared_mlp``). Router gates have no projection roles and are excluded. """ - expert_containers = set(self.expert_containers()) + expert_containers = self.expert_containers() containers = set() for moe in self.moe_roots(): for spec in self._specs.values(): @@ -481,7 +492,7 @@ def shared_expert_containers(self) -> Tuple[str, ...]: if not _path_has_segment(spec.template, moe.template): continue container = spec.parent - if container in expert_containers or _EXPERT_PLACEHOLDER in container: + if any(_path_has_segment(container, expert) for expert in expert_containers): continue containers.add(container) return tuple(sorted(containers)) @@ -531,6 +542,8 @@ def expert_container_leaf(self, moe_root: str) -> Optional[str]: def expert_root(self, path: str) -> Optional[str]: """Return the expert family path containing a concrete expert leaf.""" + if not isinstance(path, str) or self.find(path) is None: + return None for container in self.expert_containers(): prefix = container.split(f".{_EXPERT_PLACEHOLDER}", 1)[0] if not _path_has_segment(path, prefix): diff --git a/gptqmodel/models/moe_lifecycle.py b/gptqmodel/models/moe_lifecycle.py index 8f8e0553fa..64da82ad81 100644 --- a/gptqmodel/models/moe_lifecycle.py +++ b/gptqmodel/models/moe_lifecycle.py @@ -32,13 +32,22 @@ def _module_plan(model_class) -> Optional["ModulePlan"]: """Return the exact tree plan for a live wrapper or definition class.""" if model_class is None: return None + from .module_plan import ModulePlan + plan = getattr(model_class, "module_plan", None) - if plan is not None: + if isinstance(plan, ModulePlan): return plan + if callable(plan) and not isinstance(model_class, type): + try: + resolved = plan() + except RuntimeError: + pass + else: + if isinstance(resolved, ModulePlan): + return resolved module_tree = getattr(model_class, "module_tree", None) if module_tree is None: return None - from .module_plan import ModulePlan return ModulePlan.from_tree(module_tree) @@ -250,7 +259,15 @@ def get_shared_experts_module(self, moe_block: nn.Module, model_class: type) -> Example: Returns moe_block.shared_experts or moe_block.shared_expert if either exists """ - # Use the helper to get the attribute name + plan = getattr(self, "module_plan", None) or _module_plan(model_class) + if plan is not None: + for root in plan.moe_roots(): + container = plan.shared_container_leaf(root.template) + if container and hasattr(moe_block, container): + return getattr(moe_block, container) + return None + + # Legacy hooks without a tree plan may explicitly declare a name. name = self.get_shared_experts_module_name(moe_block) if name: shared_experts_module = getattr(moe_block, name) diff --git a/tests/module_tree/test_explicit_module_plan.py b/tests/module_tree/test_explicit_module_plan.py index 9598ed1460..b3732e65ed 100644 --- a/tests/module_tree/test_explicit_module_plan.py +++ b/tests/module_tree/test_explicit_module_plan.py @@ -8,7 +8,10 @@ import torch.nn as nn from gptqmodel.models.base import BaseQModel +from gptqmodel.models.definitions.hymba import HymbaQModel from gptqmodel.models.module_plan import ModulePlan, _model_module_plan +from gptqmodel.models.moe_lifecycle import MoELifecycleHooks +from gptqmodel.models.moe_lifecycle import _module_plan as _hook_module_plan from gptqmodel.utils.model import get_module_by_name_prefix, get_module_by_name_suffix @@ -80,6 +83,60 @@ def test_module_plan_resolves_roles_without_live_name_heuristics(): assert plan.shared_container_leaf("mlp") == "shared_mlp" +def test_expert_queries_reject_undeclared_descendants(): + plan = ModulePlan.from_tree([ + "model", "layers", "#", + {"mlp:moe": {"experts": {"#": ("gate_proj:0",)}}}, + ]) + assert plan.is_expert("mlp.experts.3.gate_proj") + assert plan.expert_root("mlp.experts.3.gate_proj") == "mlp.experts.3" + assert plan.find("mlp.experts.3.undeclared") is None + assert not plan.is_expert("mlp.experts.3.undeclared") + assert plan.expert_root("mlp.experts.3.undeclared") is None + + +def test_fixed_index_expert_definition_is_not_a_shared_expert(): + plan = ModulePlan.from_tree(HymbaQModel.module_tree) + assert plan.expert_containers() == ("moe.experts",) + assert plan.shared_expert_containers() == () + assert plan.expert_container_leaf("moe") == "experts" + assert plan.is_expert("moe.experts.0.gate_proj") + assert plan.expert_root("moe.experts.0.down_proj") == "moe.experts.0" + assert not plan.is_expert("moe.experts.1.gate_proj") + + block = nn.Module() + block.experts = nn.ModuleList([nn.Linear(2, 2)]) + assert MoELifecycleHooks().get_experts_module(block, HymbaQModel) is block.experts + + +def test_unbound_moe_hook_compiles_definition_plan_instead_of_using_method(): + class ToyDefinition(BaseQModel): + module_tree = [ + "model", "layers", "#", + {"mlp:moe": { + "experts": {"#": ("gate_proj:0",)}, + "shared_experts": ("gate_proj:0",), + }}, + ] + + block = nn.Module() + block.experts = nn.ModuleList([nn.Linear(2, 2)]) + block.shared_experts = nn.Module() + block.shared_experts.gate_proj = nn.Linear(2, 2) + hooks = MoELifecycleHooks() + assert isinstance(_hook_module_plan(ToyDefinition), ModulePlan) + assert hooks.get_experts_module(block, ToyDefinition) is block.experts + assert hooks.get_shared_experts_module(block, ToyDefinition) is block.shared_experts + + compiled = ModulePlan.from_tree(ToyDefinition.module_tree) + + class LiveModel: + def module_plan(self): + return compiled + + assert _hook_module_plan(LiveModel()) is compiled + + def test_module_plan_shared_containers_do_not_depend_on_expert_spelling(): plan = ModulePlan.from_tree([ "model", "layers", "#", From f1a0b119e0b97058b17528c0d2de52ff138476ca Mon Sep 17 00:00:00 2001 From: Qubitium Date: Sat, 7 Nov 2026 02:30:53 +0000 Subject: [PATCH 7/7] test(models): require module plan contracts for every registered model --- .../gptqmodel-model-plan-tests/SKILL.md | 48 + .github/PULL_REQUEST_TEMPLATE.md | 15 + AGENTS.md | 21 +- docs/model-tree-resolution.md | 38 + gptqmodel/models/loader.py | 4 +- gptqmodel/quantization/rotation/rotation.py | 2 +- .../fixtures/registered_module_plans.json | 2461 +++++++++++++++++ .../test_registered_module_plans.py | 115 + tests/test_rotation_persistence.py | 40 + 9 files changed, 2735 insertions(+), 9 deletions(-) create mode 100644 .agents/skills/gptqmodel-model-plan-tests/SKILL.md create mode 100644 tests/module_tree/fixtures/registered_module_plans.json create mode 100644 tests/module_tree/test_registered_module_plans.py diff --git a/.agents/skills/gptqmodel-model-plan-tests/SKILL.md b/.agents/skills/gptqmodel-model-plan-tests/SKILL.md new file mode 100644 index 0000000000..45c92fa1f9 --- /dev/null +++ b/.agents/skills/gptqmodel-model-plan-tests/SKILL.md @@ -0,0 +1,48 @@ +--- +name: gptqmodel-model-plan-tests +description: Add and validate module-plan unit tests when registering a model type, changing a model definition, or changing module-tree consumption in GPTQModel. +--- + +# Model support requires module-plan tests + +Every new `MODEL_MAP` entry, including an alias, must add an explicit case to +`tests/module_tree/fixtures/registered_module_plans.json` and a model-specific +module-plan unit test under `tests/module_tree/`. Changes to a definition's +paths, tags, variants, or method overrides must update its tests in the same PR. +The always-run registry contract fails for an unlisted model or method case. + +Use `tests/module_tree/test_registered_module_plans.py` for the fast compiler +and consumer contract. Its inventory pins decoder prefixes and ordered blocks +from the independent quantization subset planner. Review expectation changes +against the architecture; do not blindly refresh snapshots from `ModulePlan`. +Cover each model-type alias, layout variant, and quantization-method override. + +For model-specific coverage, build the real model class with a tiny config on +CPU or meta, run the normal Defuser conversion where required, and obtain the +plan through `model.module_plan()` when testing a loaded wrapper. Verify: + +- Declared quantizable paths resolve on the real decoder layers, including + dense/MoE and hybrid attention branches used by the model. +- Checkpoint-owned weight owners resolve through `plan.find()` and carry + quantization, exclusion, or capture tags. Include non-quantized weights. +- Declared roles and routed/shared expert families reach the actual consumers, + including looper grouping and lifecycle hooks where applicable. +- Similar prefixes/suffixes and undeclared descendants are rejected. + +`state_dict()` is a useful architecture fixture for parameters and persistent +buffers. For an actual checkpoint audit, use checkpoint keys and declared +conversion mappings to distinguish checkpoint weights from tensors created +after loading; runtime-only tensors do not create model-definition obligations. +Do not substitute a tree-generated fake model for real model validation. + +The Flash-family reference is +`tests/module_tree/test_flash_model_tree_consumption.py`. A missing optional +remote implementation may skip its real-model test with a precise reason, +but must still run the registry contract. Do not blanket-skip exceptions or +report a skipped case as validated. Unsupported registry sentinels such as +original `dbrx` require an explicit rejection test, not positive coverage. + +Run the registry contract, the new model-specific test, and affected consumer +tests. Record the exact commands, pass/skip counts, dependency limitations, +and model-test nodes in the PR. New model support is not complete with only an +E2E generation test or a registry entry. diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 3d6475d8af..4bddfdc8f8 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -20,6 +20,21 @@ Paste the exact test commands and results here: ```bash ``` +## Model Support / Module Plan + +Required for new model support, model-type aliases, and definition changes. +See `.agents/skills/gptqmodel-model-plan-tests/SKILL.md`. + +- [ ] Every new `MODEL_MAP` entry has an explicit registry plan case. +- [ ] A new model-specific module-plan unit test builds the real model class + and verifies declared paths, checkpoint weight ownership/tags, roles, + and applicable consumers, including layout variants and method overrides. +- [ ] Runtime-created tensors are distinguished from checkpoint-owned weights. +- [ ] Registry and model-specific tests passed; any dependency skips and their + precise coverage limits are listed below. + +Model test node IDs and results (or "not applicable"): + ## Logic Flow Documentation Required for changes that alter control flow, replace a decision mechanism diff --git a/AGENTS.md b/AGENTS.md index 7ab46f6f1d..3ae803c5a8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -86,13 +86,22 @@ in the same pull request. ## Model-definition weight coverage -`module_tree` is the oracle for checkpoint-owned weights, including -non-quantized weights. Derive coverage from `state_dict()` (parameters and -persistent buffers), not from `named_modules()`, `named_parameters()`, or -`named_buffers()` alone: runtime-created non-persistent buffers are not -checkpoint weights and must not become definition obligations. +For every new model type or alias in `MODEL_MAP`, and every change to a model +definition or module-plan consumer, follow +`.agents/skills/gptqmodel-model-plan-tests/SKILL.md`. New model support must add +an explicit registry plan case and a model-specific module-plan unit test in +the same PR. Cover its layout variants and method overrides. The registry +contract runs without an opt-in flag and must not skip supported definitions. -For every decoder-layer `state_dict()` entry: +`module_tree` is the oracle for checkpoint-owned weights, including +non-quantized weights. Use `state_dict()` (parameters and persistent buffers) +for model architecture fixtures, not `named_modules()`, `named_parameters()`, +or `named_buffers()` alone. For an actual checkpoint audit, verify ownership +against checkpoint keys and declared conversion mappings: tensors created +after loading must not become definition obligations solely because they +appear in a runtime `state_dict()`. + +For every checkpoint-owned decoder-layer entry: - The deepest owning module must resolve through `ModulePlan.find()`. - A quantized owner must be declared by `simple_layer_modules()`. diff --git a/docs/model-tree-resolution.md b/docs/model-tree-resolution.md index 0a5b93278b..34512086d3 100644 --- a/docs/model-tree-resolution.md +++ b/docs/model-tree-resolution.md @@ -195,6 +195,11 @@ flowchart TD ## What each subsystem asks +Rotation reads normalization membership from explicit `norm` flags; projection +roles remain `q/k/v/o/gate/up/down`. A supplied plan also makes online Hadamard +setup reject paths outside the declared decoder layers. The public helper's +legacy default applies only when no plan is supplied. + ```mermaid flowchart TD PLAN["ModulePlan"] --> BASE["models/base.py
is_moe_module() · AWQ roles
stage-block classification"] @@ -223,6 +228,39 @@ The expert family key used for device co-location is the declared family path, s `gate`/`up`/`down` of one expert stay together on one device regardless of what the projections are named. +## Registry-wide module-plan unit tests + +`tests/module_tree/test_registered_module_plans.py` runs for every `MODEL_MAP` +entry without an opt-in flag, including aliases and each method override. The +committed `fixtures/registered_module_plans.json` records reviewed decoder +prefixes and ordered quantization/capture/exclusion blocks. A new registered +model without an explicit case fails the suite. + +The tested registry contains 198 model-type entries, 173 definition classes, +and 175 definition/method cases. Original `dbrx` is a documented unsupported +sentinel and receives a rejection test; `dbrx_converted` receives a positive +contract test. This suite validates definitions and compiler/consumer agreement. +Real model layout and checkpoint weight ownership are verified separately by +model-specific tests such as `test_flash_model_tree_consumption.py`. + +```mermaid +flowchart TD + REG["MODEL_MAP entry"] --> CASE{"explicit inventory case?"} + CASE -->|"missing"| FAIL["test failure: add model-plan case"] + CASE -->|"present"| TREE["definition and method override"] + TREE --> PLAN["ModulePlan.from_tree()"] + TREE --> SUB["build_layer_modules() / shared-input metadata"] + PLAN --> CHECK["compare paths, flags, norms, MoE and exact lookup"] + SUB --> CHECK + CHECK --> USE["ModuleLooper / WeightOnlyLooper via module_plan()"] + TREE --> REAL["separate real-model tests: actual layout and checkpoint owners"] + style FAIL fill:#ffa39e,stroke:#a8071a +``` + +New support must add both an explicit registry case and a real-model module-plan +unit test. This requirement is maintained in `AGENTS.md`, +`.agents/skills/gptqmodel-model-plan-tests/SKILL.md`, and the PR template. + ### Quantizability (loader and writer) ```mermaid diff --git a/gptqmodel/models/loader.py b/gptqmodel/models/loader.py index b859ca1dfd..d058fa04f7 100644 --- a/gptqmodel/models/loader.py +++ b/gptqmodel/models/loader.py @@ -683,8 +683,8 @@ def _setup_rotation_online_had(model, rotation: Optional[str], module_plan=None, _, separator, remainder = relative.partition(".") relative = remainder if separator and _.isdigit() else relative is_down_projection = ( - "down" in module_plan.roles(relative) - if module_plan is not None and relative is not None + relative is not None and "down" in module_plan.roles(relative) + if module_plan is not None else name.endswith("mlp.down_proj") ) if is_down_projection: diff --git a/gptqmodel/quantization/rotation/rotation.py b/gptqmodel/quantization/rotation/rotation.py index d655372eb4..f9f1b11083 100644 --- a/gptqmodel/quantization/rotation/rotation.py +++ b/gptqmodel/quantization/rotation/rotation.py @@ -93,7 +93,7 @@ def fuse_layer_norms(model: PreTrainedModel, pre_lm_head_norm_module_name: str, plan: ModulePlan = None): layers , _ = get_module_by_name_prefix(model, layers_node) plan = plan or _default_rotation_plan() - norm_roles = plan.child_roles("", "norm") + norm_roles = tuple(spec.name for spec in plan.specs if not spec.parent and "norm" in spec.flags) if len(norm_roles) != 2: raise ValueError(f"Rotation requires two declared layer norms, found {list(norm_roles)}") input_norm, post_norm = norm_roles diff --git a/tests/module_tree/fixtures/registered_module_plans.json b/tests/module_tree/fixtures/registered_module_plans.json new file mode 100644 index 0000000000..cfe4c4bd50 --- /dev/null +++ b/tests/module_tree/fixtures/registered_module_plans.json @@ -0,0 +1,2461 @@ +{ + "models": { + "afmoe": "AfMoeQModel", + "agnes": "AgnesQModel", + "apertus": "ApertusQModel", + "apertus1p5": "Apertus1p5QModel", + "apertus1p5_text": "Apertus1p5TextQModel", + "axk2": "AXK2QModel", + "baichuan": "BaiChuanQModel", + "bailing_hybrid": "BailingMoeQModel", + "bailing_moe": "BailingMoeQModel", + "bloom": "BloomQModel", + "brumby": "BrumbyQModel", + "chatglm": "ChatGLMQModel", + "codegen": "CodeGenQModel", + "cohere": "LlamaQModel", + "cohere2": "LlamaQModel", + "cohere2_moe": "Cohere2MoeQModel", + "cohere_compass": "CohereCompassQModel", + "dbrx": "DbrxQModel", + "dbrx_converted": "DbrxConvertedQModel", + "deci": "DeciLMQModel", + "deepseek_ocr2": "DeepSeekOCR2QModel", + "deepseek_v2": "DeepSeekV2QModel", + "deepseek_v3": "DeepSeekV3QModel", + "deepseek_v32": "DeepSeekV32QModel", + "deepseek_v4": "DeepSeekV4QModel", + "deepseek_vl": "DeepSeekVLQModel", + "deepseek_vl_v2": "DeepSeekVLV2QModel", + "diffusion_gemma": "DiffusionGemmaQModel", + "dots1": "Dots1QModel", + "dream": "DreamQModel", + "ernie4_5": "Ernie4_5QModel", + "ernie4_5_moe": "Ernie4_5_MoeQModel", + "ernie4_5_moe_vl": "Ernie4_5_VLMoeQModel", + "ernie4_5_vl_moe": "Ernie4_5_VLMoeQModel", + "exaone": "ExaOneQModel", + "exaone4": "Exaone4QModel", + "exaone4_5": "Exaone4_5QModel", + "exaone4_5_text": "Exaone4QModel", + "falcon": "RwgQModel", + "falcon_h1": "FalconH1QModel", + "falcon_mamba": "FalconMambaQModel", + "flint": "FlintQModel", + "gemma": "LlamaQModel", + "gemma2": "Gemma2QModel", + "gemma3": "Gemma3ForConditionalGenerationGPTQ", + "gemma3_text": "Gemma3QModel", + "gemma3n": "Gemma3nForConditionalGenerationGPTQ", + "gemma3n_text": "Gemma3nTextQModel", + "gemma4": "Gemma4ForConditionalGenerationGPTQ", + "gemma4_text": "Gemma4TextQModel", + "gemma4_unified": "Gemma4UnifiedForConditionalGenerationGPTQ", + "gemma4_unified_text": "Gemma4UnifiedTextQModel", + "glm": "GlmQModel", + "glm4": "GlmQModel", + "glm4_moe": "GLM4MoEGPTQ", + "glm4_moe_lite": "Glm4MoeLiteQModel", + "glm4v": "Glm4vGPTQ", + "glm4v_moe": "Glm4vMoeQModel", + "glm4v_moe_text": "Glm4vMoeTextQModel", + "glm5_next": "Glm5NextQModel", + "glm_moe_dsa": "GlmMoeDsaQModel", + "glm_ocr": "GlmOCRGPTQ", + "glmasr": "GlmASRGPTQ", + "gpt2": "GPT2QModel", + "gpt_bigcode": "GptBigCodeQModel", + "gpt_neo": "GptNeoQModel", + "gpt_neox": "GPTNeoXQModel", + "gpt_oss": "GPTOSSGPTQ", + "gpt_pangu": "PanguAlphaQModel", + "gptj": "GptJQModel", + "granite": "LlamaQModel", + "granitemoe": "GraniteMoeQModel", + "granitemoehybrid": "GraniteMoeHybridQModel", + "grinmoe": "GrinMoeQModel", + "helium": "LlamaQModel", + "hrm_text": "HrmTextQModel", + "hunyuan_v1_dense": "HunYuanDenseV1QModel", + "hunyuan_v1_moe": "HunYuanMoEV1QModel", + "hunyuan_vl": "HunYuanVLQModel", + "hy_v3": "HYV3QModel", + "hymba": "HymbaQModel", + "inkling_mm_model": "InklingMMQModel", + "instella": "InstellaQModel", + "intern_s2_preview": "InternS2PreviewQModel", + "internlm": "InternLMQModel", + "internlm2": "InternLM2QModel", + "interns1": "InternS1QModel", + "internvl": "InternVLQModel", + "internvl_chat": "InternVLChatQModel", + "jamba": "JambaQModel", + "k2_horizon": "K2HorizonQModel", + "kimi_k2": "DeepSeekV3QModel", + "kimi_k25": "KimiK25QModel", + "klear": "KlearQModel", + "laguna": "LagunaQModel", + "lfm2": "LFM2QModel", + "lfm2_moe": "LFM2MoeQModel", + "lfm2_vl": "LFM2VLQModel", + "lfm3": "LFM3QModel", + "lfm3_omni": "LFM3OmniQModel", + "lfm3_vl": "LFM3VLQModel", + "llada2_moe": "LLaDA2MoeQModel", + "llama": "LlamaQModel", + "llama4": "Llama4QModel", + "llama4_text": "Llama4TextQModel", + "llava": "LlavaQModel", + "llava_qwen2": "LlavaQwen2QModel", + "locateanything": "LocateAnythingQModel", + "longcat_flash": "LongCatFlashQModel", + "longllama": "LlamaQModel", + "mage_vl": "MageVLQModel", + "marin": "Qwen3QModel", + "mimo": "MimoQModel", + "mimo_v2": "MimoV2QModel", + "minicpm": "MiniCPMGPTQ", + "minicpm3": "MiniCpm3QModel", + "minicpmo": "MiniCPMOQModel", + "minicpmv": "MiniCPMVQModel", + "minicpmv4_6": "MiniCPMV4_6QModel", + "minimax": "MiniMaxQModel", + "minimax_m2": "MiniMaxM2GPTQ", + "minimax_m3_vl": "MiniMaxM3VLGPTQ", + "ministral3": "Ministral3GPTQ", + "mistral": "LlamaQModel", + "mistral3": "Mistral3GPTQ", + "mixtral": "MixtralQModel", + "mllama": "MLlamaQModel", + "mllama_text_model": "MLlamaTextQModel", + "mobilellm": "MobileLLMQModel", + "moss": "MossQModel", + "mpt": "MptQModel", + "muse_glimmer": "MuseGlimmerQModel", + "nanbeige": "NanbeigeQModel", + "nemotron-nas": "DeciLMQModel", + "nemotron_h": "NemotronHQModel", + "nemotron_h_puzzle": "NemotronHPuzzleQModel", + "nemotron_labs_diffusion": "NemotronLabsDiffusionQModel", + "nemotronh_nano_omni_reasoning_v3": "NemotronOmniQModel", + "olmo": "LlamaQModel", + "olmo2": "LlamaQModel", + "olmo3": "Olmo3QModel", + "olmoe": "OlmoeQModel", + "openvla": "OpenVLAQModel", + "opt": "OptQModel", + "ouro": "OuroQModel", + "ovis": "OvisQModel", + "ovis2": "Ovis2QModel", + "ovis2_5": "Ovis2_5QModel", + "ovis2_6_moe": "Ovis2_6_MoeQModel", + "ovis2_6_next": "Ovis2_6_NextQModel", + "phi": "PhiQModel", + "phi3": "Phi3QModel", + "phi4mm": "Phi4MMGPTQ", + "phimoe": "PhiMoEGPTQForCausalLM", + "qwen": "QwenQModel", + "qwen2": "Qwen2QModel", + "qwen2_5_omni": "Qwen2_5_OmniGPTQ", + "qwen2_5_vl": "Qwen2_5_VLQModel", + "qwen2_5_vl_text": "Qwen2_5_VLQModel", + "qwen2_audio": "Qwen2AudioGPTQ", + "qwen2_moe": "Qwen2MoeQModel", + "qwen2_vl": "Qwen2VLQModel", + "qwen2_vl_text": "Qwen2VLQModel", + "qwen3": "Qwen3QModel", + "qwen3_5": "Qwen3_5QModel", + "qwen3_5_moe": "Qwen3_5_MoeQModel", + "qwen3_5_moe_text": "Qwen3_5_MoeTextQModel", + "qwen3_5_text": "Qwen3_5TextQModel", + "qwen3_moe": "Qwen3MoeQModel", + "qwen3_next": "Qwen3NextGPTQ", + "qwen3_omni_moe": "Qwen3OmniMoeGPTQ", + "qwen3_vl": "Qwen3_VLQModel", + "qwen3_vl_moe": "Qwen3_VL_MoeQModel", + "qwen4_exp": "Qwen4ExpQModel", + "qwen4_exp_text": "Qwen4ExpTextQModel", + "qwen_drive": "QwenDriveQModel", + "raon1_mini": "Raon1MiniQModel", + "refinedWeb": "RwgQModel", + "refinedWebModel": "RwgQModel", + "ricursive": "RicursiveQModel", + "seed_oss": "LlamaQModel", + "smollm3": "LlamaQModel", + "smolvlm": "SmolVLMQModel", + "solar_open": "SolarOpenQModel", + "solar_open2": "SolarOpen2QModel", + "spark2_5": "Spark2_5QModel", + "stablelm": "LlamaQModel", + "stablelm_epoch": "LlamaQModel", + "starcoder2": "Starcoder2QModel", + "telechat": "TeleChat2QModel", + "unlimited-ocr": "UnlimitedOCRQModel", + "voxtral": "VoxtralGPTQ", + "xing4_0": "Xing4_0QModel", + "xverse": "XverseQModel", + "yi": "LlamaQModel", + "zamba": "ZambaQModel", + "zamba2": "Zamba2QModel", + "zdtaichu5_0": "ZDTaichu5QModel" + }, + "cases": { + "AfMoeQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj", "self_attn.gate_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp:?"], + ["mlp.router.gate:!"], + ["mlp.shared_experts.gate_proj", "mlp.shared_experts.up_proj", "mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj", "mlp.gate_proj", "mlp.up_proj"], + ["mlp.shared_experts.down_proj", "mlp.experts.{expert_index}.down_proj", "mlp.down_proj"] + ] + }, + "AgnesQModel/gptq": { + "layers": ["model.language_model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["delta_attn.norm:!", "delta_attn.conv1d:!", "delta_attn.in_proj_qkv"], + ["delta_attn.in_proj_z", "delta_attn.in_proj_b:!", "delta_attn.in_proj_a:!"], + ["delta_attn.out_proj"], + ["global_attn.q_norm:!", "global_attn.q_proj", "global_attn.k_norm:!", "global_attn.k_proj", "global_attn.v_proj"], + ["global_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"], + ["mlp.parallel_ffn.gate_proj", "mlp.parallel_ffn.up_proj"], + ["mlp.parallel_ffn.down_proj"] + ] + }, + "ApertusQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "Apertus1p5QModel/gptq": { + "layers": ["model.language_model.layers"], + "blocks": [ + ["attention_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj", "self_attn.q_norm:!", "self_attn.k_norm:!"], + ["self_attn.o_proj"], + ["feedforward_layernorm:!"], + ["mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "Apertus1p5TextQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "AXK2QModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_a_proj", "self_attn.kv_a_proj_with_mqa"], + ["self_attn.q_gate_proj", "self_attn.kv_b_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"], + ["mlp.gate:!", "mlp.gate.e_score_correction_bias:!"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"], + ["mlp.shared_experts.gate_proj", "mlp.shared_experts.up_proj"], + ["mlp.shared_experts.down_proj"] + ] + }, + "BaiChuanQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.W_pack"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "BailingMoeQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj", "self_attn.g_proj", "self_attn.kv_a_proj_with_mqa", "self_attn.forget_gate.f_proj", "self_attn.b_proj"], + ["self_attn.o_proj", "self_attn.kv_b_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate:!"], + ["mlp.shared_experts.gate_proj", "mlp.shared_experts.up_proj", "mlp.shared_experts.down_proj"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "BloomQModel/gptq": { + "layers": ["transformer.h"], + "blocks": [ + ["input_layernorm:!"], + ["self_attention.query_key_value"], + ["self_attention.dense"], + ["post_attention_layernorm:!"], + ["mlp.dense_h_to_4h"], + ["mlp.dense_4h_to_h"] + ] + }, + "BrumbyQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj", "self_attn.g_proj:!", "self_attn.q_norm:!", "self_attn.k_norm:!"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "ChatGLMQModel/gptq": { + "layers": ["transformer.encoder.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attention.query_key_value"], + ["self_attention.dense"], + ["post_attention_layernorm:!"], + ["mlp.dense_h_to_4h"], + ["mlp.dense_4h_to_h"] + ] + }, + "CodeGenQModel/gptq": { + "layers": ["transformer.h"], + "blocks": [ + ["attn.qkv_proj"], + ["attn.out_proj"], + ["mlp.fc_in"], + ["mlp.fc_out"] + ] + }, + "LlamaQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "Cohere2MoeQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["mlp.gate:!"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "CohereCompassQModel/gptq": { + "layers": ["model.language_model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["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"] + ] + }, + "DbrxQModel/gptq": { + "layers": [], + "blocks": [ + ] + }, + "DbrxConvertedQModel/gptq": { + "layers": ["transformer.blocks"], + "blocks": [ + ["norm_attn_norm.attn.q_proj", "norm_attn_norm.attn.k_proj", "norm_attn_norm.attn.v_proj"], + ["norm_attn_norm.attn.out_proj"], + ["ffn.experts.mlp.{expert_index}.w1", "ffn.experts.mlp.{expert_index}.v1"], + ["ffn.experts.mlp.{expert_index}.w2"] + ] + }, + "DeciLMQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "DeepSeekOCR2QModel/gptq": { + "layers": ["model.language_model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"], + ["mlp.gate:!"], + ["mlp.shared_experts.gate_proj", "mlp.shared_experts.up_proj"], + ["mlp.shared_experts.down_proj"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"] + ] + }, + "DeepSeekV2QModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_a_proj", "self_attn.q_b_proj", "self_attn.q_proj", "self_attn.kv_a_proj_with_mqa", "self_attn.kv_b_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"], + ["mlp.shared_experts.gate_proj", "mlp.shared_experts.up_proj"], + ["mlp.shared_experts.down_proj"] + ] + }, + "DeepSeekV3QModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.q_a_proj", "self_attn.kv_a_proj_with_mqa"], + ["self_attn.q_b_proj", "self_attn.kv_b_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"], + ["mlp.shared_experts.gate_proj", "mlp.shared_experts.up_proj"], + ["mlp.shared_experts.down_proj"] + ] + }, + "DeepSeekV32QModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_a_proj", "self_attn.kv_a_proj_with_mqa", "self_attn.indexer.wk", "self_attn.indexer.weights_proj:!"], + ["self_attn.q_b_proj", "self_attn.kv_b_proj", "self_attn.indexer.wq_b"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"], + ["mlp.gate:!", "mlp.gate.e_score_correction_bias:!"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"], + ["mlp.shared_experts.gate_proj", "mlp.shared_experts.up_proj"], + ["mlp.shared_experts.down_proj"] + ] + }, + "DeepSeekV4QModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["attn_hc:!"], + ["attn_hc.input_norm:!"], + ["input_layernorm:!"], + ["self_attn:!"], + ["self_attn.q_a_norm:!", "self_attn.q_a_proj", "self_attn.q_b_norm:!", "self_attn.q_b_proj", "self_attn.o_a_proj:!", "self_attn.kv_norm:!", "self_attn.compressor:!", "self_attn.compressor.kv_norm:!", "self_attn.compressor.kv_proj:!", "self_attn.compressor.gate_proj:!", "self_attn.compressor.indexer:!", "self_attn.compressor.indexer.kv_norm:!", "self_attn.compressor.indexer.kv_proj:!", "self_attn.compressor.indexer.q_b_proj:!", "self_attn.compressor.indexer.gate_proj:!", "self_attn.compressor.indexer.scorer.weights_proj:!"], + ["self_attn.o_b_proj"], + ["self_attn.kv_proj"], + ["ffn_hc:!"], + ["ffn_hc.input_norm:!"], + ["post_attention_layernorm:!"], + ["mlp.gate:!", "mlp.gate.e_score_correction_bias:!", "mlp.gate.tid2eid:!"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"], + ["mlp.shared_experts.gate_proj", "mlp.shared_experts.up_proj"], + ["mlp.shared_experts.down_proj"] + ] + }, + "DeepSeekVLQModel/gptq": { + "layers": ["model.language_model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "DeepSeekVLV2QModel/gptq": { + "layers": ["language.model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_a_proj", "self_attn.q_b_proj", "self_attn.q_proj", "self_attn.kv_a_proj_with_mqa", "self_attn.kv_b_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"], + ["mlp.shared_experts.gate_proj", "mlp.shared_experts.up_proj"], + ["mlp.shared_experts.down_proj"] + ] + }, + "DiffusionGemmaQModel/gptq": { + "layers": ["model.encoder.language_model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_norm:!", "self_attn.q_proj", "self_attn.k_norm:!", "self_attn.k_proj", "self_attn.v_norm:!", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["pre_feedforward_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"], + ["post_feedforward_layernorm_1:!"], + ["pre_feedforward_layernorm_2:!"], + ["router.proj:!"], + ["experts.{expert_index}.gate_proj", "experts.{expert_index}.up_proj"], + ["experts.{expert_index}.down_proj"], + ["post_feedforward_layernorm_2:!"], + ["post_feedforward_layernorm:!"] + ] + }, + "Dots1QModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_norm:!", "self_attn.k_norm:!", "self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"], + ["mlp.shared_experts.gate_proj", "mlp.shared_experts.up_proj"], + ["mlp.shared_experts.down_proj"] + ] + }, + "DreamQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "Ernie4_5QModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "Ernie4_5_MoeQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj"], + ["mlp.up_proj"], + ["mlp.down_proj"], + ["mlp.gate:!"], + ["mlp.shared_experts.gate_proj"], + ["mlp.shared_experts.up_proj"], + ["mlp.shared_experts.down_proj"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"] + ] + }, + "Ernie4_5_VLMoeQModel/gptq": { + "layers": ["model.language_model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj"], + ["mlp.up_proj"], + ["mlp.down_proj"], + ["mlp.shared_experts.gate_proj"], + ["mlp.shared_experts.up_proj"], + ["mlp.shared_experts.down_proj"], + ["mlp.text_moe.gate:!"], + ["mlp.text_moe.experts.{expert_index}.gate_proj", "mlp.text_moe.experts.{expert_index}.up_proj"], + ["mlp.text_moe.experts.{expert_index}.down_proj"], + ["mlp.vision_moe.gate:!"], + ["mlp.vision_moe.experts.{expert_index}.gate_proj", "mlp.vision_moe.experts.{expert_index}.up_proj"], + ["mlp.vision_moe.experts.{expert_index}.down_proj"] + ] + }, + "ExaOneQModel/gptq": { + "layers": ["transformer.h"], + "blocks": [ + ["ln_1:!"], + ["attn.attention.q_proj", "attn.attention.k_proj", "attn.attention.v_proj"], + ["attn.attention.out_proj"], + ["ln_2:!"], + ["mlp.c_fc_0", "mlp.c_fc_1"], + ["mlp.c_proj"] + ] + }, + "Exaone4QModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj", "self_attn.q_norm:!", "self_attn.k_norm:!"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"], + ["post_feedforward_layernorm:!"] + ] + }, + "Exaone4_5QModel/gptq": { + "layers": ["model.language_model.layers", "language_model.layers"], + "blocks": [ + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj", "self_attn.q_norm:!", "self_attn.k_norm:!"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"], + ["post_feedforward_layernorm:!"] + ] + }, + "RwgQModel/gptq": { + "layers": ["transformer.h"], + "blocks": [ + ["ln_1:!"], + ["self_attention.query_key_value"], + ["self_attention.dense"], + ["ln_2:!"], + ["mlp.dense_h_to_4h"], + ["mlp.dense_4h_to_h"] + ] + }, + "FalconH1QModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["mamba.in_proj"], + ["mamba.out_proj"], + ["feed_forward.gate_proj", "feed_forward.up_proj"], + ["feed_forward.down_proj"] + ] + }, + "FalconMambaQModel/gptq": { + "layers": ["backbone.layers"], + "blocks": [ + ["norm:!"], + ["mixer.in_proj", "mixer.x_proj"], + ["mixer.out_proj"] + ] + }, + "FlintQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_norm:!", "self_attn.k_norm:!", "self_attn.softmax_offset:!", "self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"], + ["mlp.gate:!"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"], + ["mlp.shared_expert.gate_proj", "mlp.shared_expert.up_proj"], + ["mlp.shared_expert.down_proj"] + ] + }, + "Gemma2QModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "Gemma3ForConditionalGenerationGPTQ/gptq": { + "layers": ["model.language_model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "Gemma3QModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "Gemma3nForConditionalGenerationGPTQ/gptq": { + "layers": ["model.language_model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_norm:!", "self_attn.q_proj", "self_attn.k_norm:!", "self_attn.k_proj", "self_attn.v_norm:!", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["pre_feedforward_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"], + ["post_feedforward_layernorm:!"], + ["per_layer_input_gate"], + ["post_per_layer_input_norm:!"], + ["per_layer_projection"] + ] + }, + "Gemma3nTextQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_norm:!", "self_attn.q_proj", "self_attn.k_norm:!", "self_attn.k_proj", "self_attn.v_norm:!", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["pre_feedforward_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"], + ["post_feedforward_layernorm:!"], + ["per_layer_input_gate"], + ["post_per_layer_input_norm:!"], + ["per_layer_projection"] + ] + }, + "Gemma4ForConditionalGenerationGPTQ/gptq": { + "layers": ["model.language_model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_norm:!", "self_attn.q_proj", "self_attn.k_norm:!", "self_attn.k_proj", "self_attn.v_norm:!", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["pre_feedforward_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"], + ["post_feedforward_layernorm:!"], + ["per_layer_input_gate"], + ["post_per_layer_input_norm:!"], + ["per_layer_projection"] + ] + }, + "Gemma4TextQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_norm:!", "self_attn.q_proj", "self_attn.k_norm:!", "self_attn.k_proj", "self_attn.v_norm:!", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["pre_feedforward_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"], + ["post_feedforward_layernorm:!"], + ["per_layer_input_gate"], + ["post_per_layer_input_norm:!"], + ["per_layer_projection"] + ] + }, + "Gemma4UnifiedForConditionalGenerationGPTQ/gptq": { + "layers": ["model.language_model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_norm:!", "self_attn.q_proj", "self_attn.k_norm:!", "self_attn.k_proj", "self_attn.v_norm:!", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["pre_feedforward_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"], + ["post_feedforward_layernorm:!"] + ] + }, + "Gemma4UnifiedTextQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_norm:!", "self_attn.q_proj", "self_attn.k_norm:!", "self_attn.k_proj", "self_attn.v_norm:!", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["pre_feedforward_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"], + ["post_feedforward_layernorm:!"] + ] + }, + "GlmQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "GLM4MoEGPTQ/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.q_norm:!", "self_attn.k_proj", "self_attn.k_norm:!", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate:!"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"], + ["mlp.shared_experts.gate_proj"], + ["mlp.shared_experts.up_proj"], + ["mlp.shared_experts.down_proj"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "Glm4MoeLiteQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.q_a_proj", "self_attn.kv_a_proj_with_mqa"], + ["self_attn.q_b_proj", "self_attn.kv_b_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp:?"], + ["mlp.gate:!"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj", "mlp.shared_experts.gate_proj", "mlp.shared_experts.up_proj"], + ["mlp.experts.{expert_index}.down_proj", "mlp.shared_experts.down_proj"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "Glm4vGPTQ/gptq": { + "layers": ["model.language_model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "Glm4vMoeQModel/gptq": { + "layers": ["model.language_model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate:!"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"], + ["mlp.shared_experts.gate_proj"], + ["mlp.shared_experts.up_proj"], + ["mlp.shared_experts.down_proj"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "Glm4vMoeTextQModel/gptq": { + "layers": ["layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate:!"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"], + ["mlp.shared_experts.gate_proj"], + ["mlp.shared_experts.up_proj"], + ["mlp.shared_experts.down_proj"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "Glm5NextQModel/gptq": { + "layers": ["model.language_model.layers"], + "blocks": [ + ["attn_hc:!"], + ["attn_hc.input_norm:!"], + ["input_layernorm:!"], + ["self_attn.b_proj:!", "self_attn.conv1d:!", "self_attn.forget_gate:!", "self_attn.forget_gate.f_a_proj:!", "self_attn.forget_gate.f_b_proj:!", "self_attn.g_a_proj:!", "self_attn.g_b_proj:!", "self_attn.o_norm:!", "self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj", "self_attn.q_a_proj:!", "self_attn.q_a_layernorm:!", "self_attn.kv_a_proj_with_mqa:!", "self_attn.kv_a_layernorm:!", "self_attn.indexer:!", "self_attn.indexer.wq_b:!", "self_attn.indexer.wk:!", "self_attn.indexer.k_norm:!", "self_attn.indexer.weights_proj:!", "self_attn.q_b_proj", "self_attn.kv_b_proj"], + ["self_attn.o_proj"], + ["ffn_hc:!"], + ["ffn_hc.input_norm:!"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"], + ["mlp.gate:!", "mlp.gate.e_score_correction_bias:!"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"], + ["mlp.shared_experts.gate_proj:!", "mlp.shared_experts.up_proj:!", "mlp.shared_experts.down_proj:!"] + ] + }, + "GlmMoeDsaQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.q_a_proj", "self_attn.kv_a_proj_with_mqa", "self_attn.indexer.wk"], + ["self_attn.q_b_proj", "self_attn.kv_b_proj", "self_attn.indexer.wq_b"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate:!"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"], + ["mlp.shared_experts.gate_proj", "mlp.shared_experts.up_proj"], + ["mlp.shared_experts.down_proj"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "GlmOCRGPTQ/gptq": { + "layers": ["model.language_model.layers", "language_model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "GlmASRGPTQ/gptq": { + "layers": ["language_model.model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "GPT2QModel/gptq": { + "layers": ["transformer.h"], + "blocks": [ + ["ln_1:!"], + ["attn.c_attn"], + ["attn.c_proj"], + ["ln_2:!"], + ["mlp.c_fc"], + ["mlp.c_proj"] + ] + }, + "GptBigCodeQModel/gptq": { + "layers": ["transformer.h"], + "blocks": [ + ["ln_1:!"], + ["attn.c_attn"], + ["attn.c_proj"], + ["ln_2:!"], + ["mlp.c_fc"], + ["mlp.c_proj"] + ] + }, + "GptNeoQModel/gptq": { + "layers": ["transformer.h"], + "blocks": [ + ["ln_1:!"], + ["attn.attention.q_proj", "attn.attention.k_proj", "attn.attention.v_proj"], + ["attn.attention.out_proj"], + ["ln_2:!"], + ["mlp.c_fc"], + ["mlp.c_proj"] + ] + }, + "GPTNeoXQModel/gptq": { + "layers": ["gpt_neox.layers"], + "blocks": [ + ["input_layernorm:!"], + ["attention.query_key_value"], + ["attention.dense"], + ["post_attention_layernorm:!"], + ["mlp.dense_h_to_4h"], + ["mlp.dense_4h_to_h"] + ] + }, + "GPTOSSGPTQ/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"] + ] + }, + "PanguAlphaQModel/gptq": { + "layers": ["transformer.h"], + "blocks": [ + ["ln_1:!"], + ["attn.q_proj", "attn.k_proj", "attn.v_proj"], + ["attn.c_proj"], + ["ln_2:!"], + ["mlp.c_fc"], + ["mlp.c_proj"] + ] + }, + "GptJQModel/gptq": { + "layers": ["transformer.h"], + "blocks": [ + ["ln_1:!"], + ["attn.q_proj", "attn.k_proj", "attn.v_proj"], + ["attn.out_proj"], + ["mlp.fc_in"], + ["mlp.fc_out"] + ] + }, + "GraniteMoeQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["block_sparse_moe:?"], + ["block_sparse_moe.experts.{expert_index}.gate_proj", "block_sparse_moe.experts.{expert_index}.up_proj"], + ["block_sparse_moe.experts.{expert_index}.down_proj"] + ] + }, + "GraniteMoeHybridQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["mamba.in_proj"], + ["mamba.out_proj"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["block_sparse_moe:?"], + ["block_sparse_moe.experts.{expert_index}.gate_proj", "block_sparse_moe.experts.{expert_index}.up_proj"], + ["block_sparse_moe.experts.{expert_index}.down_proj"], + ["shared_mlp.input_linear"], + ["shared_mlp.output_linear"] + ] + }, + "GrinMoeQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["block_sparse_moe.experts.{expert_index}.w1", "block_sparse_moe.experts.{expert_index}.w3"], + ["block_sparse_moe.experts.{expert_index}.w2"] + ] + }, + "HrmTextQModel/gptq": { + "layers": ["model.L_module.layers", "model.H_module.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj", "self_attn.gate_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "HunYuanDenseV1QModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.query_layernorm:!", "self_attn.q_proj", "self_attn.key_layernorm:!", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "HunYuanMoEV1QModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj", "self_attn.query_layernorm:!", "self_attn.key_layernorm:!"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp:?"], + ["mlp.gate:!"], + ["mlp.shared_mlp.gate_proj", "mlp.shared_mlp.up_proj"], + ["mlp.shared_mlp.down_proj"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"] + ] + }, + "HunYuanVLQModel/gptq": { + "layers": ["model.language_model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.query_layernorm:!", "self_attn.q_proj", "self_attn.key_layernorm:!", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "HYV3QModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_norm:!", "self_attn.k_norm:!", "self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate:!"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"], + ["mlp.shared_experts.gate_proj", "mlp.shared_experts.up_proj"], + ["mlp.shared_experts.down_proj"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "HymbaQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["mamba.in_proj"], + ["mamba.out_proj"], + ["post_attention_layernorm:!"], + ["moe.experts.0.gate_proj", "moe.experts.0.up_proj"], + ["moe.experts.0.down_proj"] + ] + }, + "InklingMMQModel/gptq": { + "layers": ["model.language_model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj", "self_attn.r_proj", "self_attn.q_norm:!", "self_attn.k_norm:!"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"], + ["mlp.gate:!"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"] + ] + }, + "InstellaQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "InternS2PreviewQModel/gptq": { + "layers": ["model.language_model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_norm:!", "self_attn.q_proj", "self_attn.k_norm:!", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["linear_attn.norm:!", "linear_attn.conv1d:!", "linear_attn.in_proj_qkv"], + ["linear_attn.in_proj_z", "linear_attn.in_proj_b:!", "linear_attn.in_proj_a:!"], + ["linear_attn.out_proj"], + ["post_attention_layernorm:!"], + ["mlp:?"], + ["mlp.gate:!"], + ["mlp.shared_expert_gate:!"], + ["mlp.shared_expert.gate_proj", "mlp.shared_expert.up_proj", "mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.shared_expert.down_proj", "mlp.experts.{expert_index}.down_proj"] + ] + }, + "InternLMQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "InternLM2QModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["attention_norm:!"], + ["attention.wqkv", "attention.wo"], + ["ffn_norm:!"], + ["feed_forward.w1", "feed_forward.w3"], + ["feed_forward.w2"] + ] + }, + "InternS1QModel/gptq": { + "layers": ["model.language_model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_norm:!", "self_attn.q_proj", "self_attn.k_norm:!", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "InternVLQModel/gptq": { + "layers": ["model.language_model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "InternVLChatQModel/gptq": { + "layers": ["language_model.model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_norm:!", "self_attn.k_norm:!", "self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "JambaQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["mamba.in_proj"], + ["mamba.out_proj"], + ["pre_ff_layernorm:!"], + ["feed_forward.gate_proj", "feed_forward.up_proj"], + ["feed_forward.down_proj"] + ] + }, + "K2HorizonQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_norm:!"], + ["self_attn.k_norm:!"], + ["self_attn.q_proj"], + ["self_attn.k_proj"], + ["self_attn.v_proj"], + ["self_attn.gate_proj"], + ["self_attn.v_router:!"], + ["self_attn.v_experts.{expert_index}"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate:!"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"], + ["mlp.shared_experts.gate_proj", "mlp.shared_experts.up_proj"], + ["mlp.shared_experts.down_proj"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "KimiK25QModel/gptq": { + "layers": ["language_model.model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.q_a_proj", "self_attn.kv_a_proj_with_mqa"], + ["self_attn.q_b_proj", "self_attn.kv_b_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"], + ["mlp.shared_experts.gate_proj", "mlp.shared_experts.up_proj"], + ["mlp.shared_experts.down_proj"] + ] + }, + "KlearQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.shared_experts.gate_proj", "mlp.shared_experts.up_proj"], + ["mlp.shared_experts.down_proj"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"] + ] + }, + "LagunaQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_norm:!", "self_attn.k_norm:!", "self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj", "self_attn.g_proj:!"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.shared_experts.gate_proj", "mlp.shared_experts.up_proj"], + ["mlp.shared_experts.down_proj"], + ["mlp.shared_expert.gate_proj", "mlp.shared_expert.up_proj"], + ["mlp.shared_expert.down_proj"], + ["mlp.gate:!"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "LFM2QModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["operator_norm:!"], + ["conv.in_proj", "conv.out_proj"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.out_proj"], + ["ffn_norm:!"], + ["feed_forward.w1", "feed_forward.w3"], + ["feed_forward.w2"] + ] + }, + "LFM2MoeQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["operator_norm:!"], + ["conv.in_proj", "conv.out_proj"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["ffn_norm:!"], + ["feed_forward.gate:!"], + ["feed_forward.w1", "feed_forward.w3"], + ["feed_forward.w2"], + ["feed_forward.experts.{expert_index}.w1", "feed_forward.experts.{expert_index}.w3"], + ["feed_forward.experts.{expert_index}.w2"] + ] + }, + "LFM2VLQModel/gptq": { + "layers": ["model.language_model.layers"], + "blocks": [ + ["operator_norm:!"], + ["conv.in_proj"], + ["conv.out_proj"], + ["self_attn.q_proj", "self_attn.q_layernorm:!", "self_attn.k_proj", "self_attn.k_layernorm:!", "self_attn.v_proj"], + ["self_attn.out_proj"], + ["ffn_norm:!"], + ["feed_forward.w1", "feed_forward.w3"], + ["feed_forward.w2"] + ] + }, + "LFM3QModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["operator_norm:!"], + ["post_operator_norm:!"], + ["conv.in_proj"], + ["conv.out_proj"], + ["self_attn.q_proj", "self_attn.q_norm:!", "self_attn.k_proj", "self_attn.k_norm:!", "self_attn.v_proj", "self_attn.gate_proj:!"], + ["self_attn.o_proj"], + ["ffn_norm:!"], + ["post_ffn_norm:!"], + ["feed_forward.w1", "feed_forward.w3"], + ["feed_forward.w2"] + ] + }, + "LFM3OmniQModel/gptq": { + "layers": ["model.language_model.layers"], + "blocks": [ + ["operator_norm:!"], + ["post_operator_norm:!"], + ["conv.in_proj"], + ["conv.out_proj"], + ["self_attn.q_proj", "self_attn.q_norm:!", "self_attn.k_proj", "self_attn.k_norm:!", "self_attn.v_proj", "self_attn.gate_proj:!"], + ["self_attn.o_proj"], + ["ffn_norm:!"], + ["post_ffn_norm:!"], + ["feed_forward.w1", "feed_forward.w3"], + ["feed_forward.w2"] + ] + }, + "LFM3VLQModel/gptq": { + "layers": ["model.language_model.layers"], + "blocks": [ + ["operator_norm:!"], + ["post_operator_norm:!"], + ["conv.in_proj"], + ["conv.out_proj"], + ["self_attn.q_proj", "self_attn.q_norm:!", "self_attn.k_proj", "self_attn.k_norm:!", "self_attn.v_proj", "self_attn.gate_proj:!"], + ["self_attn.o_proj"], + ["ffn_norm:!"], + ["post_ffn_norm:!"], + ["feed_forward.w1", "feed_forward.w3"], + ["feed_forward.w2"] + ] + }, + "LLaDA2MoeQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["attention.query_key_value", "attention.query_layernorm:!", "attention.key_layernorm:!"], + ["attention.dense"], + ["post_attention_layernorm:!"], + ["mlp:?"], + ["mlp.gate:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"], + ["mlp.shared_experts.gate_proj", "mlp.shared_experts.up_proj"], + ["mlp.shared_experts.down_proj"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"] + ] + }, + "Llama4QModel/gptq": { + "layers": ["language_model.model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["feed_forward.router:!"], + ["feed_forward.experts.{expert_index}.gate_proj", "feed_forward.experts.{expert_index}.up_proj", "feed_forward.shared_expert.gate_proj", "feed_forward.shared_expert.up_proj"], + ["feed_forward.experts.{expert_index}.down_proj", "feed_forward.shared_expert.down_proj"] + ] + }, + "Llama4TextQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["feed_forward.router:!"], + ["feed_forward.experts.{expert_index}.gate_proj", "feed_forward.experts.{expert_index}.up_proj", "feed_forward.shared_expert.gate_proj", "feed_forward.shared_expert.up_proj"], + ["feed_forward.experts.{expert_index}.down_proj", "feed_forward.shared_expert.down_proj"] + ] + }, + "LlavaQModel/gptq": { + "layers": ["model.language_model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "LlavaQwen2QModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "LocateAnythingQModel/gptq": { + "layers": ["language_model.model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "LongCatFlashQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.0.q_a_proj", "self_attn.0.q_b_proj", "self_attn.0.kv_a_proj_with_mqa", "self_attn.0.kv_b_proj"], + ["self_attn.0.o_proj"], + ["self_attn.1.q_a_proj", "self_attn.1.q_b_proj", "self_attn.1.kv_a_proj_with_mqa", "self_attn.1.kv_b_proj"], + ["self_attn.1.o_proj"], + ["post_attention_layernorm:!"], + ["mlps.0.gate_proj", "mlps.0.up_proj"], + ["mlps.0.down_proj"], + ["mlps.1.gate_proj", "mlps.1.up_proj"], + ["mlps.1.down_proj"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"] + ] + }, + "MageVLQModel/gptq": { + "layers": ["model.language_model.layers", "language_model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj", "self_attn.q_norm:!", "self_attn.k_norm:!"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "Qwen3QModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_norm:!", "self_attn.k_norm:!", "self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "MimoQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "MimoV2QModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.qkv_proj", "self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp:?"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"], + ["mlp.gate:!"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"] + ] + }, + "MiniCPMGPTQ/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj"], + ["self_attn.k_proj"], + ["self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj", "mlp.down_proj"] + ] + }, + "MiniCpm3QModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_a_proj", "self_attn.kv_a_proj_with_mqa"], + ["self_attn.q_b_proj", "self_attn.kv_b_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "MiniCPMOQModel/gptq": { + "layers": ["llm.model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj"], + ["self_attn.k_proj"], + ["self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj", "mlp.down_proj"] + ] + }, + "MiniCPMVQModel/gptq": { + "layers": ["llm.model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj"], + ["self_attn.k_proj"], + ["self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj", "mlp.down_proj"] + ] + }, + "MiniCPMV4_6QModel/gptq": { + "layers": ["model.language_model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_norm:!", "self_attn.q_proj", "self_attn.k_norm:!", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["linear_attn.norm:!", "linear_attn.conv1d:!", "linear_attn.in_proj_qkv"], + ["linear_attn.in_proj_z", "linear_attn.in_proj_b:!", "linear_attn.in_proj_a:!"], + ["linear_attn.out_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "MiniMaxQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj", "self_attn.qkv_proj"], + ["self_attn.o_proj", "self_attn.out_proj", "self_attn.output_gate"], + ["post_attention_layernorm:!"], + ["mlp.gate:!"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"] + ] + }, + "MiniMaxM2GPTQ/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.q_norm:!", "self_attn.k_proj", "self_attn.k_norm:!", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate:!"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"] + ] + }, + "MiniMaxM3VLGPTQ/gptq": { + "layers": ["model.language_model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.q_norm:!", "self_attn.k_proj", "self_attn.k_norm:!", "self_attn.v_proj", "self_attn.indexer.q_proj", "self_attn.indexer.q_norm:!", "self_attn.indexer.k_proj", "self_attn.indexer.k_norm:!"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_up_proj"], + ["mlp.down_proj"], + ["mlp.gate:!", "mlp.gate.e_score_correction_bias:!"], + ["mlp.shared_experts.gate_up_proj"], + ["mlp.shared_experts.down_proj"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"] + ] + }, + "Ministral3GPTQ/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "Mistral3GPTQ/gptq": { + "layers": ["model.language_model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "MixtralQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp:?"], + ["mlp.gate:!"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"] + ] + }, + "MLlamaQModel/gptq": { + "layers": ["model.language_model.layers", "language_model.model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "MLlamaTextQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "MobileLLMQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "MossQModel/gptq": { + "layers": ["transformer.h"], + "blocks": [ + ["ln_1:!"], + ["attn.qkv_proj"], + ["attn.out_proj"], + ["mlp.fc_in"], + ["mlp.fc_out"] + ] + }, + "MptQModel/gptq": { + "layers": ["transformer.blocks"], + "blocks": [ + ["attn.Wqkv"], + ["attn.out_proj"], + ["ffn.up_proj"], + ["ffn.down_proj"] + ] + }, + "MuseGlimmerQModel/gptq": { + "layers": ["model.language_model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj", "self_attn.gate_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["pre_feedforward_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"], + ["post_feedforward_layernorm:!"] + ] + }, + "NanbeigeQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "NemotronHQModel/gptq": { + "layers": ["backbone.layers"], + "blocks": [ + ["norm:!"], + ["mixer.q_proj", "mixer.k_proj", "mixer.v_proj"], + ["mixer.o_proj"], + ["mixer.in_proj", "mixer.out_proj"], + ["mixer.gate_proj", "mixer.up_proj"], + ["mixer.down_proj"] + ] + }, + "NemotronHPuzzleQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["norm:!"], + ["mixer.q_proj", "mixer.k_proj", "mixer.v_proj", "mixer.in_proj"], + ["mixer.o_proj", "mixer.out_proj"], + ["mixer.fc1_latent_proj"], + ["mixer.experts.{expert_index}.up_proj"], + ["mixer.experts.{expert_index}.down_proj"], + ["mixer.fc2_latent_proj"], + ["mixer.shared_experts.up_proj"], + ["mixer.shared_experts.down_proj"] + ] + }, + "NemotronLabsDiffusionQModel/gptq": { + "layers": ["encoder.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "NemotronOmniQModel/gptq": { + "layers": ["language_model.backbone.layers"], + "blocks": [ + ["norm:!"], + ["mixer.q_proj", "mixer.k_proj", "mixer.v_proj"], + ["mixer.o_proj"], + ["mixer.in_proj", "mixer.out_proj"], + ["mixer.gate_proj", "mixer.up_proj"], + ["mixer.down_proj"] + ] + }, + "Olmo3QModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["self_attn.q_proj", "self_attn.q_norm:!", "self_attn.k_proj", "self_attn.k_norm:!", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"], + ["post_feedforward_layernorm:!"] + ] + }, + "OlmoeQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj", "self_attn.q_norm:!", "self_attn.k_norm:!"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate:!"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"] + ] + }, + "OpenVLAQModel/gptq": { + "layers": ["language_model.model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "OptQModel/gptq": { + "layers": ["model.decoder.layers"], + "blocks": [ + ["final_layer_norm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.out_proj"], + ["fc1"], + ["fc2"] + ] + }, + "OuroQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["input_layernorm_2:!"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"], + ["post_attention_layernorm_2:!"] + ] + }, + "OvisQModel/gptq": { + "layers": ["llm.model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "Ovis2QModel/gptq": { + "layers": ["model.language_model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "Ovis2_5QModel/gptq": { + "layers": ["llm.model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "Ovis2_6_MoeQModel/gptq": { + "layers": ["llm.model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_norm:!", "self_attn.k_norm:!", "self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp:?"], + ["mlp.gate:!"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"] + ] + }, + "Ovis2_6_NextQModel/gptq": { + "layers": ["llm.model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_norm:!", "self_attn.k_norm:!", "self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["linear_attn.norm:!", "linear_attn.conv1d:!", "linear_attn.in_proj_qkvz", "linear_attn.in_proj_ba:!"], + ["linear_attn.out_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate:!"], + ["mlp.shared_expert_gate:!"], + ["mlp.shared_expert.gate_proj", "mlp.shared_expert.up_proj", "mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.shared_expert.down_proj", "mlp.experts.{expert_index}.down_proj"] + ] + }, + "Ovis2_6_NextQModel/awq": { + "layers": ["llm.model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_norm:!", "self_attn.k_norm:!", "self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["linear_attn.norm:!", "linear_attn.conv1d:!", "linear_attn.in_proj_qkvz", "linear_attn.in_proj_ba:!"], + ["linear_attn.out_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate"], + ["mlp.shared_expert_gate:!"], + ["mlp.shared_expert.gate_proj", "mlp.shared_expert.up_proj", "mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.shared_expert.down_proj", "mlp.experts.{expert_index}.down_proj"] + ] + }, + "PhiQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj"], + ["self_attn.k_proj"], + ["self_attn.v_proj"], + ["self_attn.dense"], + ["post_attention_layernorm:!"], + ["mlp.fc1"], + ["mlp.fc2"] + ] + }, + "Phi3QModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["self_attn.qkv_proj"], + ["self_attn.o_proj"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "Phi4MMGPTQ/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.qkv_proj.base_layer"], + ["self_attn.o_proj.base_layer"], + ["post_attention_layernorm:!"], + ["mlp.gate_up_proj.base_layer"], + ["mlp.down_proj.base_layer"] + ] + }, + "PhiMoEGPTQForCausalLM/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp:?"], + ["mlp.router:!"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"] + ] + }, + "QwenQModel/gptq": { + "layers": ["transformer.h"], + "blocks": [ + ["ln_1:!"], + ["attn.c_attn"], + ["attn.c_proj"], + ["ln_2:!"], + ["mlp.w1", "mlp.w2"], + ["mlp.c_proj"] + ] + }, + "Qwen2QModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "Qwen2_5_OmniGPTQ/gptq": { + "layers": ["thinker.model.layers", "thinker.model.language_model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "Qwen2_5_VLQModel/gptq": { + "layers": ["model.language_model.layers", "language_model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "Qwen2AudioGPTQ/gptq": { + "layers": ["model.language_model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "Qwen2MoeQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp:?"], + ["mlp.gate:!"], + ["mlp.shared_expert_gate:!"], + ["mlp.shared_expert.gate_proj", "mlp.shared_expert.up_proj", "mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.shared_expert.down_proj", "mlp.experts.{expert_index}.down_proj"] + ] + }, + "Qwen2VLQModel/gptq": { + "layers": ["model.language_model.layers", "language_model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "Qwen3_5QModel/gptq": { + "layers": ["model.language_model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_norm:!", "self_attn.q_proj", "self_attn.k_norm:!", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["linear_attn:!"], + ["linear_attn.norm:!", "linear_attn.conv1d:!", "linear_attn.in_proj_qkv"], + ["linear_attn.in_proj_z", "linear_attn.in_proj_b:!", "linear_attn.in_proj_a:!"], + ["linear_attn.out_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "Qwen3_5_MoeQModel/gptq": { + "layers": ["model.language_model.layers", "language_model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_norm:!", "self_attn.q_proj", "self_attn.k_norm:!", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["linear_attn.norm:!", "linear_attn.conv1d:!", "linear_attn.in_proj_qkv"], + ["linear_attn.in_proj_z", "linear_attn.in_proj_b:!", "linear_attn.in_proj_a:!"], + ["linear_attn.out_proj"], + ["post_attention_layernorm:!"], + ["mlp:?"], + ["mlp.gate:!"], + ["mlp.shared_expert_gate:!"], + ["mlp.shared_expert.gate_proj", "mlp.shared_expert.up_proj", "mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.shared_expert.down_proj", "mlp.experts.{expert_index}.down_proj"] + ] + }, + "Qwen3_5_MoeTextQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_norm:!", "self_attn.q_proj", "self_attn.k_norm:!", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["linear_attn.norm:!", "linear_attn.conv1d:!", "linear_attn.in_proj_qkv"], + ["linear_attn.in_proj_z", "linear_attn.in_proj_b:!", "linear_attn.in_proj_a:!"], + ["linear_attn.out_proj"], + ["post_attention_layernorm:!"], + ["mlp:?"], + ["mlp.gate:!"], + ["mlp.shared_expert_gate:!"], + ["mlp.shared_expert.gate_proj", "mlp.shared_expert.up_proj", "mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.shared_expert.down_proj", "mlp.experts.{expert_index}.down_proj"] + ] + }, + "Qwen3_5TextQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_norm:!", "self_attn.q_proj", "self_attn.k_norm:!", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["linear_attn.norm:!", "linear_attn.conv1d:!", "linear_attn.in_proj_qkv"], + ["linear_attn.in_proj_z", "linear_attn.in_proj_b:!", "linear_attn.in_proj_a:!"], + ["linear_attn.out_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "Qwen3MoeQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_norm:!", "self_attn.k_norm:!", "self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp:?"], + ["mlp.gate:!"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"] + ] + }, + "Qwen3NextGPTQ/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_norm:!", "self_attn.k_norm:!", "self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["linear_attn.norm:!", "linear_attn.conv1d:!", "linear_attn.in_proj_qkvz", "linear_attn.in_proj_ba:!"], + ["linear_attn.out_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate:!"], + ["mlp.shared_expert_gate:!"], + ["mlp.shared_expert.gate_proj", "mlp.shared_expert.up_proj", "mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.shared_expert.down_proj", "mlp.experts.{expert_index}.down_proj"] + ] + }, + "Qwen3NextGPTQ/awq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_norm:!", "self_attn.k_norm:!", "self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["linear_attn.norm:!", "linear_attn.conv1d:!", "linear_attn.in_proj_qkvz", "linear_attn.in_proj_ba:!"], + ["linear_attn.out_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate"], + ["mlp.shared_expert_gate:!"], + ["mlp.shared_expert.gate_proj", "mlp.shared_expert.up_proj", "mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.shared_expert.down_proj", "mlp.experts.{expert_index}.down_proj"] + ] + }, + "Qwen3OmniMoeGPTQ/gptq": { + "layers": ["thinker.model.layers", "thinker.model.language_model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_norm:!", "self_attn.k_norm:!", "self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate:!"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"] + ] + }, + "Qwen3_VLQModel/gptq": { + "layers": ["model.language_model.layers", "language_model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj", "self_attn.q_norm:!", "self_attn.k_norm:!"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "Qwen3_VL_MoeQModel/gptq": { + "layers": ["model.language_model.layers", "language_model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj", "self_attn.q_norm:!", "self_attn.k_norm:!"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate:!"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"] + ] + }, + "Qwen4ExpQModel/gptq": { + "layers": ["model.language_model.layers"], + "blocks": [ + ["self_attn.indexer.index_qk_proj:!", "self_attn.indexer.q_layernorm:!", "self_attn.indexer.k_layernorm:!", "self_attn.q_proj", "self_attn.q_norm:!", "self_attn.k_proj", "self_attn.k_norm:!", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["linear_attn.conv1d:!", "linear_attn.in_proj_qkv", "linear_attn.norm:!"], + ["linear_attn.in_proj_z", "linear_attn.in_proj_b:!", "linear_attn.in_proj_a:!"], + ["linear_attn.out_proj"], + ["mlp.shared_expert.gate_proj", "mlp.shared_expert.up_proj"], + ["mlp.shared_expert.down_proj"], + ["mlp.gate:!"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"], + ["mlp.shared_expert_gate:!"] + ] + }, + "Qwen4ExpTextQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["self_attn.indexer.index_qk_proj:!", "self_attn.indexer.q_layernorm:!", "self_attn.indexer.k_layernorm:!", "self_attn.q_proj", "self_attn.q_norm:!", "self_attn.k_proj", "self_attn.k_norm:!", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["linear_attn.conv1d:!", "linear_attn.in_proj_qkv", "linear_attn.norm:!"], + ["linear_attn.in_proj_z", "linear_attn.in_proj_b:!", "linear_attn.in_proj_a:!"], + ["linear_attn.out_proj"], + ["mlp.shared_expert.gate_proj", "mlp.shared_expert.up_proj"], + ["mlp.shared_expert.down_proj"], + ["mlp.gate:!"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"], + ["mlp.shared_expert_gate:!"] + ] + }, + "QwenDriveQModel/gptq": { + "layers": ["vlm.model.language_model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_norm:!", "self_attn.q_proj", "self_attn.k_norm:!", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["linear_attn.norm:!", "linear_attn.conv1d:!", "linear_attn.in_proj_qkv"], + ["linear_attn.in_proj_z", "linear_attn.in_proj_b:!", "linear_attn.in_proj_a:!"], + ["linear_attn.out_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "Raon1MiniQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj", "self_attn.f_a_proj", "self_attn.b_proj", "self_attn.rda_w_proj", "self_attn.g_proj", "self_attn.q_a_proj", "self_attn.kv_a_proj_with_mqa"], + ["self_attn.f_b_proj", "self_attn.q_b_proj", "self_attn.kv_b_proj"], + ["self_attn.o_proj"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"], + ["mlp.shared_experts.gate_proj", "mlp.shared_experts.up_proj"], + ["mlp.shared_experts.down_proj"], + ["moe.gate:!", "moe.gate.e_score_correction_bias:!"], + ["moe.experts.{expert_index}.gate_proj", "moe.experts.{expert_index}.up_proj"], + ["moe.experts.{expert_index}.down_proj"], + ["moe.shared_experts.gate_proj", "moe.shared_experts.up_proj"], + ["moe.shared_experts.down_proj"] + ] + }, + "RicursiveQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn:!"], + ["self_attn.q_norm:!", "self_attn.k_norm:!", "self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj", "self_attn.g_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["pre_feedforward_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"], + ["post_feedforward_layernorm:!"] + ] + }, + "SmolVLMQModel/gptq": { + "layers": ["model.text_model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "SolarOpenQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate:!"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"], + ["mlp.shared_experts.gate_proj", "mlp.shared_experts.up_proj"], + ["mlp.shared_experts.down_proj"] + ] + }, + "SolarOpen2QModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.q_norm:!", "self_attn.k_proj", "self_attn.k_norm:!", "self_attn.v_proj", "self_attn.g_proj", "self_attn.o_norm:!"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj", "mlp.shared_experts.gate_proj", "mlp.shared_experts.up_proj"], + ["mlp.down_proj", "mlp.shared_experts.down_proj"], + ["mlp.gate:!"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"] + ] + }, + "Spark2_5QModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_k_v_proj", "self_attn.g_proj:!"], + ["self_attn.out_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "Starcoder2QModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.c_fc"], + ["mlp.c_proj"] + ] + }, + "TeleChat2QModel/gptq": { + "layers": ["transformer.h"], + "blocks": [ + ["input_layernorm:!"], + ["self_attention.dense"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "UnlimitedOCRQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"], + ["mlp.gate:!"], + ["mlp.shared_experts.gate_proj", "mlp.shared_experts.up_proj"], + ["mlp.shared_experts.down_proj"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"] + ] + }, + "VoxtralGPTQ/gptq": { + "layers": ["language_model.model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "Xing4_0QModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["attn_hc:!"], + ["attn_hc.input_norm:!", "attn_hc.hc_fn:!", "attn_hc.hc_base:!", "attn_hc.hc_scale:!"], + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.q_a_proj", "self_attn.kv_a_proj_with_mqa", "self_attn.q_a_layernorm:!", "self_attn.kv_a_layernorm:!"], + ["self_attn.q_b_proj", "self_attn.kv_b_proj"], + ["self_attn.o_proj"], + ["ffn_hc:!"], + ["ffn_hc.input_norm:!", "ffn_hc.hc_fn:!", "ffn_hc.hc_base:!", "ffn_hc.hc_scale:!"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"], + ["mlp.gate:!", "mlp.gate.e_score_correction_bias:!"], + ["mlp.experts.{expert_index}.gate_proj", "mlp.experts.{expert_index}.up_proj"], + ["mlp.experts.{expert_index}.down_proj"], + ["mlp.shared_experts.gate_proj", "mlp.shared_experts.up_proj"], + ["mlp.shared_experts.down_proj"] + ] + }, + "XverseQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + }, + "ZambaQModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["mamba.in_proj"], + ["mamba.out_proj"], + ["linear"], + ["mamba_decoder.input_layernorm:!"], + ["mamba_decoder.mamba.in_proj"], + ["mamba_decoder.mamba.out_proj"] + ] + }, + "Zamba2QModel/gptq": { + "layers": ["model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["mamba.in_proj"], + ["mamba.out_proj"], + ["linear"], + ["mamba_decoder.input_layernorm:!"], + ["mamba_decoder.mamba.in_proj"], + ["mamba_decoder.mamba.out_proj"] + ] + }, + "ZDTaichu5QModel/gptq": { + "layers": ["language_model.model.layers"], + "blocks": [ + ["input_layernorm:!"], + ["self_attn.q_norm:!", "self_attn.q_proj", "self_attn.k_norm:!", "self_attn.k_proj", "self_attn.v_proj"], + ["self_attn.o_proj"], + ["linear_attn.norm:!", "linear_attn.conv1d:!", "linear_attn.in_proj_qkv"], + ["linear_attn.in_proj_z", "linear_attn.in_proj_b:!", "linear_attn.in_proj_a:!"], + ["linear_attn.out_proj"], + ["post_attention_layernorm:!"], + ["mlp.gate_proj", "mlp.up_proj"], + ["mlp.down_proj"] + ] + } + } +} diff --git a/tests/module_tree/test_registered_module_plans.py b/tests/module_tree/test_registered_module_plans.py new file mode 100644 index 0000000000..d7da9c1ac6 --- /dev/null +++ b/tests/module_tree/test_registered_module_plans.py @@ -0,0 +1,115 @@ +# SPDX-FileCopyrightText: 2026 ModelCloud.ai +# SPDX-License-Identifier: Apache-2.0 + +"""Always-run plan contracts for every MODEL_MAP entry, including aliases. + +The checked-in inventory pins the independent quantization subset planner's +ordered blocks. These are definition/compiler unit tests, not a claim that +every remote checkpoint has been instantiated. Real model layout and weight +ownership tests complement this suite (see test_flash_model_tree_consumption). +""" + +import json +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from gptqmodel.looper.module_looper import ModuleLooper +from gptqmodel.looper.weight_only_looper import WeightOnlyLooper +from gptqmodel.models._const import EXPERT_INDEX_PLACEHOLDER +from gptqmodel.models.auto import MODEL_MAP +from gptqmodel.models.module_plan import ModulePlan +from gptqmodel.models.shared_input import collect_leaf_specs + + +INVENTORY = json.loads((Path(__file__).parent / "fixtures/registered_module_plans.json").read_text()) + + +def _methods(definition): + return sorted({"gptq", *(getattr(method, "value", method) for method in (definition.module_tree_overrides or {}))}) + + +def test_every_registered_model_has_an_explicit_plan_case(): + missing = set(MODEL_MAP) - INVENTORY["models"].keys() + assert not missing, f"Add module-plan unit test cases for new model support: {sorted(missing)}" + for model_type, definition in MODEL_MAP.items(): + assert INVENTORY["models"][model_type] == definition.__name__ + for method in _methods(definition): + assert f"{definition.__name__}/{method}" in INVENTORY["cases"] + + +@pytest.mark.parametrize("model_type", sorted(MODEL_MAP)) +def test_registered_model_plan_matches_quantization_consumers(model_type): + definition = MODEL_MAP[model_type] + for method in _methods(definition): + expected = INVENTORY["cases"][f"{definition.__name__}/{method}"] + tree = definition._resolve_effective_module_tree( + SimpleNamespace(), SimpleNamespace(method=method), + ) + if model_type == "dbrx": + # Registry sentinel: original DBRX explicitly requires conversion. + assert tree is None + assert expected == {"layers": [], "blocks": []} + model = SimpleNamespace(config=SimpleNamespace(model_type=model_type)) + with pytest.raises(ValueError, match="no explicit module_tree"): + definition(model=model, quantized=False, quantize_config=None) + continue + + assert tree is not None + with definition._module_tree_context(tree): + assert definition.extract_layers_node() == expected["layers"] + blocks = definition.build_layer_modules(tree, include_capture_only=True) + assert blocks == expected["blocks"], "Review changed paths/order/flags and update the explicit case" + + plan = ModulePlan.from_tree(tree) + assert plan.specs + with definition._module_tree_context(tree): + for name in definition.get_norm_modules(): + assert "norm" in plan.find(name).flags + roots = definition.get_moe_module_name() or [] + assert {spec.template for spec in plan.moe_roots()} == set(roots) + # The shared-input planner has a separate metadata parser. A disagreement + # here can silently route capture or reuse Hessians for the wrong input. + for leaf in collect_leaf_specs(tree).values(): + spec = plan.find(leaf.template) + assert spec is not None + assert spec.quantize == leaf.quantize + if leaf.input_tag is not None: + assert f"in={leaf.input_tag}" in spec.flags + wrapper = SimpleNamespace(module_plan=lambda: plan) + looper = ModuleLooper.__new__(ModuleLooper) + looper.gptq_model = wrapper + weight_only = WeightOnlyLooper.__new__(WeightOnlyLooper) + weight_only.gptq_model = wrapper + + for block in expected["blocks"]: + for entry in block: + path = entry.replace(":!", "").replace(":?", "") + concrete = path.replace(EXPERT_INDEX_PLACEHOLDER, "7") + spec = plan.find(concrete) + assert spec is not None, (model_type, method, entry) + assert spec.quantize == (":!" not in entry and ":?" not in entry) + assert spec.capture_only == (":?" in entry) + assert plan.find(concrete + ".undeclared") is None + assert not plan.is_expert(concrete + ".undeclared") + assert looper._extract_moe_group_key(concrete + ".undeclared") is None + if EXPERT_INDEX_PLACEHOLDER in path: + prefix = path.split(EXPERT_INDEX_PLACEHOLDER, 1)[0] + expected_root = prefix + "7" + assert plan.is_expert(concrete) + assert looper._extract_moe_group_key(concrete) == expected_root + assert weight_only._extract_moe_group_key(concrete) == expected_root + + # Each layout variant must compile on its own as well as in the union. + for variant in definition._iter_module_tree_variants(tree): + variant_plan = ModulePlan.from_tree(variant) + assert variant_plan.specs + for block in definition.build_layer_modules(variant, include_capture_only=True): + for entry in block: + concrete = entry.replace(":!", "").replace(":?", "").replace(EXPERT_INDEX_PLACEHOLDER, "7") + assert variant_plan.find(concrete) is not None + + payload = json.loads(plan.to_json()) + assert len(payload["specs"]) == len(plan.specs) + assert "ModulePlan:" in plan.render(color=False, max_depth=2) diff --git a/tests/test_rotation_persistence.py b/tests/test_rotation_persistence.py index 24a40b4955..870736f289 100644 --- a/tests/test_rotation_persistence.py +++ b/tests/test_rotation_persistence.py @@ -9,6 +9,34 @@ from gptqmodel.quantization.config import QuantizeConfig +@pytest.mark.parametrize("use_definition_plan", [True, False]) +def test_declared_norm_fusion_preserves_real_llama_forward(use_definition_plan): + from transformers import LlamaConfig, LlamaForCausalLM + + from gptqmodel.models.definitions.llama import LlamaQModel + from gptqmodel.models.module_plan import ModulePlan + from gptqmodel.quantization.rotation.rotation import fuse_layer_norms + + torch.manual_seed(42) + model = LlamaForCausalLM(LlamaConfig( + hidden_size=32, intermediate_size=64, num_attention_heads=4, + num_key_value_heads=2, num_hidden_layers=1, vocab_size=64, + tie_word_embeddings=False, + )).double().eval() + layer = model.model.layers[0] + with torch.no_grad(): + for norm in (layer.input_layernorm, layer.post_attention_layernorm, model.model.norm): + norm.weight.uniform_(0.5, 1.5) + tokens = torch.tensor([[1, 4, 9, 12]]) + expected = model(tokens).logits.clone() + plan = ModulePlan.from_tree(LlamaQModel.module_tree) if use_definition_plan else None + fuse_layer_norms(model, "model.norm", "model.layers", "lm_head", plan=plan) + actual = model(tokens).logits + torch.testing.assert_close(actual, expected, atol=1e-6, rtol=1e-6) + for norm in (layer.input_layernorm, layer.post_attention_layernorm, model.model.norm): + assert torch.equal(norm.weight, torch.ones_like(norm.weight)) + + def test_quantize_config_rotation_roundtrip(): cfg = QuantizeConfig(bits=4, group_size=128, rotation="hadamard") d = cfg.to_dict() @@ -54,6 +82,18 @@ def __init__(self, intermediate_size, hidden_size): self.layers = torch.nn.ModuleList([_DummyLayer(intermediate_size, hidden_size)]) +def test_rotation_with_plan_ignores_undeclared_suffix_matches(): + from gptqmodel.models.module_plan import ModulePlan + + model = _DummyModel(128, 32) + model.extra = torch.nn.Module() + model.extra.mlp = _DummyMlp(128, 32) + plan = ModulePlan.from_tree(["layers", "#", {"mlp": ("down_proj:down",)}]) + _setup_rotation_online_had(model, "hadamard", module_plan=plan, layer_prefixes=["layers"]) + assert model.layers[0].mlp.down_proj.online_full_had + assert not model.extra.mlp.down_proj.online_full_had + + def test_setup_rotation_online_had_pow2_intermediate(): model = _DummyModel(8192, 4096) _setup_rotation_online_had(model, "hadamard")