Skip to content

[BUG] Fresh dynamic configuration lookups remain stale after editing mutable typed overrides #4475

Closed

Description

@devin-ai-integration

Describe the bug

At 0b94d79c67, the cases below violate the stated supported contract. The validation scope for each case is explicit; source/dispatch proofs are not device numerical qualification.

Mutable typed dynamic overrides remain stale after in-place attribute edits

Severity: P2 — supported configuration resolution silently uses an obsolete setting; no GPU numerical claim

Contract and impact

A fresh resolution of a supported live dynamic override after an edit must agree with the value currently stored in that configuration. A previously issued immutable snapshot may stay old; a newly requested snapshot must not.

After the first lookup, editing a live MSEConfig leaf (for example norm or grid_budget) does not invalidate the tracked dictionary identity cache. New dynamic_get/resolve_module_config calls retain the deep-copied old value. GPTQ/QQQ consumers use these resolutions to construct per-module configuration. This proves silent configuration staleness, not a measured accuracy, latency or memory regression.

To reproduce / evidence

Construct GPTQConfig(dynamic={'^layer$': {'mse': MSEConfig(norm=2.0)}}), resolve 'layer' once, edit q.dynamic['^layer$']['mse'].norm = 4.0 in place, then request a fresh resolution. The same direct dictionary mutation and whole-object replacement controls invalidate correctly.

Public-package reproduction to run in a fully provisioned checkout (NOT executed as a package here):
from gptqmodel.quantization.config import GPTQConfig, MSEConfig
q = GPTQConfig(dynamic={'^layer$': {'mse': MSEConfig(norm=2.0)}})
print(q.dynamic_get('layer', 'mse').norm)  # warms cache: 2.0
q.dynamic['^layer$']['mse'].norm = 4.0
print(q.dynamic['^layer$']['mse'].norm)  # live: 4.0
print(q.dynamic_get('layer', 'mse').norm)  # stale: 2.0
print(q.resolve_module_config('layer').get('mse').norm)  # stale: 2.0

Actually executed: python reproduce.py HEAD and the same command with e55eff49c6cdbe78d67f35130cc5b502a7e44d21. The following complete portable version runs from the public checkout, uses exact AST definitions, and deliberately rejects any PCRE compilation. Save outside the repository as reproduce.py, then run python /path/reproduce.py <SHA>:

import ast
import copy
import hashlib
import json
import logging
import subprocess
import sys
import threading
import types
import weakref
from collections import OrderedDict
from collections.abc import Mapping
from dataclasses import asdict, dataclass, field, replace
from enum import Enum

REPO = '.'
rev = sys.argv[1] if len(sys.argv) > 1 else 'HEAD'
source = subprocess.check_output(['git', 'show', rev + ':gptqmodel/quantization/config.py'], cwd=REPO, text=True)
tree = ast.parse(source)

def assigned_names(n):
    targets = n.targets if isinstance(n, ast.Assign) else [n.target] if isinstance(n, ast.AnnAssign) else []
    return {t.id for t in targets if isinstance(t, ast.Name)}

names = {
    '_TrackedDict', '_TrackedList', '_track_dynamic_value', '_untrack_dynamic_value',
    '_BoundedLRUCache', 'MSEConfig', '_normalize_budget_bytes',
    '_get_dynamic_patterns', '_extract_literal_regex_pattern',
    '_resolve_dynamic_override', '_select_dynamic_value', 'dynamic_get',
    '_match_dynamic_rule', '_cached_dynamic_rule',
    'ResolvedModuleConfig', 'resolve_module_config_snapshot',
    '_normalize_mse', 'apply_scalar_module_overrides',
}
nodes = []
for n in tree.body:
    if isinstance(n, (ast.ClassDef, ast.FunctionDef)) and (n.name in names or n.name.startswith('_dynamic_')):
        nodes.append(n)
    elif isinstance(n, (ast.Assign, ast.AnnAssign)) and any(
        s.startswith(('_DYNAMIC_', '_MSE_BUDGET_')) or s == 'DYNAMIC_FIELD_SYNONYMS' for s in assigned_names(n)
    ):
        nodes.append(n)

def no_regex(*a, **kw):
    raise AssertionError('Probe must not exercise a substitute PCRE implementation')

env = dict(globals(), __name__='verified_config_nodes', log=logging.getLogger('probe'),
           pcre=types.SimpleNamespace(compile=no_regex))
module = types.ModuleType(env['__name__'])
sys.modules[env['__name__']] = module
module.__dict__.update(env)
env = module.__dict__
exec(compile('from __future__ import annotations\n' + ast.unparse(ast.Module(body=nodes, type_ignores=[])), rev, 'exec'), env)

results = []
for kind in ['plain-object', 'tracked-object', 'tracked-replace', 'tracked-dict']:
    value = {'norm': 2.0} if kind == 'tracked-dict' else env['MSEConfig'](norm=2.0)
    dynamic = {'^layer$': {'mse': value}}
    if kind != 'plain-object':
        dynamic = env['_track_dynamic_value'](dynamic, None)
    cfg = types.SimpleNamespace(dynamic=dynamic)
    first = env['dynamic_get'](dynamic, 'layer', 'mse')
    old = env['resolve_module_config_snapshot'](cfg, 'layer') if 'resolve_module_config_snapshot' in env else None
    before = getattr(dynamic, '_mutation_version', None)
    if kind == 'tracked-replace':
        dynamic['^layer$']['mse'] = env['MSEConfig'](norm=4.0)
    elif kind == 'tracked-dict':
        dynamic['^layer$']['mse']['norm'] = 4.0
    else:
        dynamic['^layer$']['mse'].norm = 4.0
    actual = env['dynamic_get'](dynamic, 'layer', 'mse')
    new = env['resolve_module_config_snapshot'](cfg, 'layer').get('mse') if old else None
    def norm(v):
        return v.get('norm') if isinstance(v, dict) else getattr(v, 'norm', None)
    results.append(dict(kind=kind, first=norm(first), live=norm(dynamic['^layer$']['mse']),
        newly_resolved=norm(actual), snapshot=norm(new), version=[before,getattr(dynamic,'_mutation_version',None)]))
print(json.dumps(dict(revision=rev, scope='exact AST definitions; no package import or tensor execution', results=results), indent=2))

Observed and expected behavior

Observed at HEAD: plain dict + typed object => first 2, live 4, fresh dynamic_get 4, fresh snapshot 4. Tracked dict + typed object => first 2, live 4, fresh dynamic_get 2, fresh snapshot 2, mutation version 0 -> 0. Tracked whole-object replacement => fresh 4, version 0 -> 1. Tracked nested dict norm edit => fresh 4, version 0 -> 1. At MSEConfig introduction the same dynamic_get outcomes and versions occur; ResolvedModuleConfig did not yet exist. Expected fresh typed-leaf resolution: 4. Old snapshots intentionally staying 2 are not the defect.

Public source and history

BaseQuantizeConfig.setattr wraps dynamic dictionaries:

# Wrap assignment as well as construction so later ``config.dynamic =``
# edits receive the same mutation tracking as the initial value.
if name == "dynamic" and value is not None and isinstance(value, dict) and not isinstance(value, _TrackedDict):
value = _track_dynamic_value(value, None)
super().__setattr__(name, value)
; typed MSE leaf:
class MSEConfig:
"""MSE shrink-grid search controls used at calibration.
``norm`` is the exponent of the ``|deq(x)-x|^norm`` objective; ``0``
disables the search. The GPTQ/QQQ MSE shrink grid and the AWQ clip grid
evaluate candidates in batched chunks; the budget fields bound each
chunk's workspace in bytes (ints) or postfixed strings (``"256M"``,
``"1G"``). They are chunk-sizing targets, not limits on total process
memory: the AWQ path sizes several scratch buffers independently, and a
single candidate or minimum product tile can exceed the target.
``None`` selects a device-derived default (16 MiB on CPU, 256 MiB on GPU);
``0`` forces single-candidate chunking (and one-token product tiles for
AWQ). When the active caching allocator pins ``max_split_size_mb``, the AWQ
clip budget is additionally capped just below that size so its scratch
segments stay splittable; that cap only changes chunk sizes, never the
selected bounds. These settings only affect calibration-time scratch, never
the stored quantized weights.
"""
norm: float = field(
default=0.0,
metadata={"help": "Exponent of the MSE objective; 0 disables the shrink-grid search"},
)
grid_budget: Optional[Union[int, str]] = field(
default=None,
metadata={"help": "Workspace budget per candidate chunk for the GPTQ/QQQ MSE shrink grid (bytes, or '256M'/'1G')"},
)
clip_grid_budget: Optional[Union[int, str]] = field(
default=None,
metadata={"help": "Workspace budget per scratch buffer for the AWQ clip grid (bytes, or '256M'/'1G')"},
)
def __post_init__(self):
if not isinstance(self.norm, (int, float)) or isinstance(self.norm, bool):
raise ValueError("MSEConfig: `norm` must be a number.")
self.norm = float(self.norm)
self.grid_budget = _normalize_budget_bytes(self.grid_budget, "grid_budget")
self.clip_grid_budget = _normalize_budget_bytes(self.clip_grid_budget, "clip_grid_budget")
def __bool__(self):
return self.norm > 0.0
@staticmethod
def resolve_budget_bytes(budget: Optional[int], device: torch.device) -> int:
"""Resolve a byte budget; ``None`` uses the device default."""
if budget is None:
budget = (16 if device.type == "cpu" else 256) << 20
return budget
def grid_budget_bytes(self, device: torch.device) -> int:
return self.resolve_budget_bytes(self.grid_budget, device)
def clip_grid_budget_bytes(self, device: torch.device) -> int:
return self.resolve_budget_bytes(self.clip_grid_budget, device)
; wrapper leaves dataclasses untracked:
def _track_dynamic_value(value, root):
# Preserve the user's container shape while sharing one mutation counter
# across every mutable descendant.
if isinstance(value, dict):
tracked = _TrackedDict(_root=root)
root = tracked._root
for key, item in value.items():
dict.__setitem__(tracked, key, _track_dynamic_value(item, root))
if root is tracked:
tracked._reorder_exclusions_first()
return tracked
if isinstance(value, (list, tuple)):
tracked = _TrackedList(_root=root)
root = tracked._root
for item in value:
list.append(tracked, _track_dynamic_value(item, root))
return tracked if isinstance(value, list) else tuple(tracked)
return value
; tracked identity/version shortcut:
def _dynamic_cache_key(dynamic):
if isinstance(dynamic, _TrackedDict):
with dynamic._root._dynamic_lock:
identity_key = id(dynamic)
version = dynamic._root._mutation_version
with _DYNAMIC_CACHE_LOCK:
record = _DYNAMIC_IDENTITY_CACHE.get(identity_key)
if record is not None and record[0]() is dynamic and record[1] == version:
# Identity and version checks keep this acceleration safe.
return record[2]
fingerprint = _dynamic_fingerprint(dynamic)
_DYNAMIC_IDENTITY_CACHE[identity_key] = (weakref.ref(dynamic), version, fingerprint)
return fingerprint
# Untracked mappings are still correct; they simply pay fingerprint cost
# because arbitrary in-place mutations cannot expose a safe O(1) token.
return _dynamic_fingerprint(dynamic)
; deep-copied cached patterns:
def _get_dynamic_patterns(dynamic: Dict[str, Dict[str, Any]]):
"""Return a stable compiled matching plan for this dynamic mapping."""
with _dynamic_lock_for(dynamic):
cache_key = _dynamic_cache_key(dynamic)
with _DYNAMIC_CACHE_LOCK:
patterns = _DYNAMIC_PATTERN_CACHE.get(cache_key)
exact_lookup = _DYNAMIC_EXACT_LOOKUP_CACHE.get(cache_key)
all_exact = _DYNAMIC_ALL_EXACT_CACHE.get(cache_key)
regex_patterns = _DYNAMIC_REGEX_PATTERN_CACHE.get(cache_key)
if (patterns is not None and exact_lookup is not None
and all_exact is not None and regex_patterns is not None):
return exact_lookup, all_exact, regex_patterns
patterns = []
exact_lookup = {}
regex_patterns = []
all_exact = True
if dynamic is not None:
for index, (pattern, overrides) in enumerate(dynamic.items()):
# Cache entries own snapshots, so later edits cannot change them.
override_snapshot = copy.deepcopy(dict(overrides))
is_negative = pattern.startswith("-:")
raw = pattern[2:] if pattern.startswith(("-:", "+:")) else pattern
exact_literal = _extract_literal_regex_pattern(raw)
if exact_literal is None:
all_exact = False
try:
compiled = pcre.compile(raw)
except Exception as exc:
raise ValueError(f"QuantizeConfig: invalid dynamic pattern `{pattern}`") from exc
regex_patterns.append((index, is_negative, compiled, override_snapshot))
else:
compiled = None
if exact_literal not in exact_lookup:
exact_lookup[exact_literal] = (
index,
False if is_negative else override_snapshot,
)
patterns.append((is_negative, compiled, override_snapshot, exact_literal, index))
_DYNAMIC_PATTERN_CACHE[cache_key] = patterns
_DYNAMIC_EXACT_LOOKUP_CACHE[cache_key] = exact_lookup
_DYNAMIC_ALL_EXACT_CACHE[cache_key] = all_exact
_DYNAMIC_REGEX_PATTERN_CACHE[cache_key] = regex_patterns
return exact_lookup, all_exact, regex_patterns
; public resolution path:
def dynamic_get(
self,
layer_name: str,
key: str = None,
default: Union[int, bool, float] = None,
sub_key: str = None,
) -> Union[Dict, int, bool, float]:
return dynamic_get(self.dynamic, layer_name, key, default, sub_key)
def has_dynamic_exclusions(self) -> bool:
"""Return True when a `-:` rule leaves at least one module unquantized."""
return any(
isinstance(pattern, str) and pattern.startswith("-:")
for pattern in (self.dynamic or ())
)
def external_module_inclusions(self) -> Optional[Tuple[str, ...]]:
"""Return Optimum's `modules_in_block_to_quantize` inclusion list.
`None` means the checkpoint did not declare one and every module in the
model tree is eligible. A non-empty tuple restricts quantization to
modules whose block-relative name ends with one of the entries.
"""
inclusions = getattr(self, "_external_module_inclusions", None)
return tuple(inclusions) if inclusions else None
def resolve_module_config(self, module_name: str) -> ResolvedModuleConfig:
"""Snapshot the resolved dynamic rule for one quantizable module."""
return resolve_module_config_snapshot(self, module_name)
; typed MSE normalization and scalar override application:
def _normalize_mse(
mse: Optional[Union[MSEConfig, Dict[str, Any], int, float]],
base: Optional[MSEConfig] = None,
) -> MSEConfig:
"""Normalize a ``mse`` config value into an ``MSEConfig``.
A bare number is the legacy ``mse`` exponent: it becomes ``norm`` and, when
``base`` is given (e.g. a per-layer dynamic override), keeps the base's
workspace budgets. Dicts merge onto ``base`` field-wise.
"""
if mse is None:
return base if base is not None else MSEConfig()
if isinstance(mse, MSEConfig):
return mse
if isinstance(mse, dict):
payload = asdict(base) if base is not None else {}
return MSEConfig(**{**payload, **mse})
if isinstance(mse, (int, float)) and not isinstance(mse, bool):
if base is not None:
return replace(base, norm=float(mse))
return MSEConfig(norm=float(mse))
raise ValueError("QuantizeConfig: `mse` must be a MSEConfig, dict, number, or None.")
def apply_scalar_module_overrides(config: "BaseQuantizeConfig", resolved_cfg: ResolvedModuleConfig) -> None:
"""Apply the shared GPTQ/QQQ per-module fields to a cloned config."""
if resolved_cfg.excluded:
raise ValueError(f"Cannot apply excluded module config: {resolved_cfg.module_name}")
if resolved_cfg.source_pattern is None:
return
for field_name in ("bits", "sym", "group_size", "damp_percent", "static_groups"):
setattr(config, field_name, resolved_cfg.get(field_name, getattr(config, field_name)))
config.mse = _normalize_mse(resolved_cfg.get("mse", None), base=config.mse)
desc_act = resolved_cfg.get("desc_act", None)
if desc_act is not None:
config.desc_act = desc_act
act_group_aware = resolved_cfg.get("act_group_aware", None)
if act_group_aware is not None:
config.act_group_aware = act_group_aware
config._resolve_activation_ordering(desc_act, act_group_aware)
; GPTQ caller resolves before cloning/applying:
def clone_gptq_config_for_module(
qcfg: QuantizeConfig,
module_full_name: str,
*,
fallback=None,
resolved_cfg: Optional[ResolvedModuleConfig] = None,
) -> Optional[QuantizeConfig]:
"""Clones and applies per-module GPTQ dynamic overrides, or skips the module."""
resolved_cfg = resolved_cfg or qcfg.resolve_module_config(module_full_name)
if resolved_cfg.excluded:
return None
qcfg_clone = copy.deepcopy(qcfg)
apply_scalar_module_overrides(qcfg_clone, resolved_cfg)
# The processor-level fallback is the *default* for this run: a per-module
# `dynamic` override outranks it. Applying it after the override (as this
and
def preprocess(self, module: NamedModule, fallback=None, **kwargs):
"""Builds the per-module GPTQ/GPTAQ/FOEM task after applying dynamic overrides."""
resolved_cfg = self.qcfg.resolve_module_config(module.full_name)
qcfg_clone = clone_gptq_config_for_module(
self.qcfg,
module.full_name,
fallback=fallback,
resolved_cfg=resolved_cfg,
)
if qcfg_clone is None:
return
bind_resolved_module_config(module, resolved_cfg)
# store last used qcfg_dynamic
self.qcfg_dynamic = qcfg_clone
. LoopProcessor retains the supplied qcfg:
self.tokenizer = tokenizer
self.qcfg = qcfg
self.qcfg_dynamic = None # cloned and dynamic filtered
. Thus a stale fresh resolution can reach a later per-module quantization config; numerical effect was not measured.

e55eff4 / #3436 adds the accepted mutable MSEConfig representation on 2026-10-24. At introduction

def _track_dynamic_value(value, root):
# Preserve the user's container shape while sharing one mutation counter
# across every mutable descendant.
if isinstance(value, dict):
tracked = _TrackedDict(_root=root)
root = tracked._root
for key, item in value.items():
dict.__setitem__(tracked, key, _track_dynamic_value(item, root))
return tracked
if isinstance(value, (list, tuple)):
tracked = _TrackedList(_root=root)
root = tracked._root
for item in value:
list.append(tracked, _track_dynamic_value(item, root))
return tracked if isinstance(value, list) else tuple(tracked)
return value
still tracks only dict/list/tuple descendants, and
def _dynamic_cache_key(dynamic):
if isinstance(dynamic, _TrackedDict):
with dynamic._root._dynamic_lock:
identity_key = id(dynamic)
version = dynamic._root._mutation_version
with _DYNAMIC_CACHE_LOCK:
record = _DYNAMIC_IDENTITY_CACHE.get(identity_key)
if record is not None and record[0]() is dynamic and record[1] == version:
# Identity and version checks keep this acceleration safe.
return record[2]
fingerprint = _dynamic_fingerprint(dynamic)
_DYNAMIC_IDENTITY_CACHE[identity_key] = (weakref.ref(dynamic), version, fingerprint)
return fingerprint
# Untracked mappings are still correct; they simply pay fingerprint cost
# because arbitrary in-place mutations cannot expose a safe O(1) token.
return _dynamic_fingerprint(dynamic)
shortcuts on the unchanged root version. The same exact norm=2 -> norm=4 tracked typed-leaf case already fails at that commit. Earlier 34223e6 / #3101 establishes a mutable-container cache mechanism but predates the MSEConfig supported input; it is not an effective fix for this typed-leaf invariant.

Existing reports

Related but distinct: #3440 is destructive serializer mutation (fixed), #4201 is serialization of typed objects/factory metadata, and #3101 is earlier cache/module-tree isolation. Public all-state issue searches repo:ModelCloud/GPTQModel is:issue "MSEConfig" "stale", "MSEConfig" "mutation", and "dataclass" "cache" each returned zero. The broader "dynamic" "stale" search returned six differently titled integration/AWQ reports. No exact duplicate identified in those focused searches; differently worded or unindexed duplicates remain possible. No publication was attempted.

Software / device info and validation limits

Ubuntu/Linux CPython 3.10.12, stdlib-only exact AST definitions extracted by git show from pinned public sources. The anchored ^layer$ key uses shipped exact-literal matching; no regex substitute was exercised. The BaseQuantizeConfig constructor and real processor/model did not execute. Their reachability is a source proof. Torch, Transformers, PCRE and pytest are absent; no full-package import, GPU, GIL=0, disk roundtrip or quantization arithmetic was tested. No claim is made for every other typed leaf; MSEConfig alone is demonstrated.

Model / datasets

The evidence uses tiny synthetic tensors or local fixtures derived from the public tests; no private model or dataset is required. Device execution that remains untested is stated above.

Activity

  1. added
    bug
    on Nov 16, 2026
  2. Qubitium commented on Nov 17, 2026

    @Qubitium
    Collaborator

    Claimed by an AI agent. Will reproduce on CPU, fix, add a focused regression test, and open a PR.

  3. Qubitium commented on Nov 17, 2026

    @Qubitium
    Collaborator

    Claimed by an AI agent. Will reproduce on CPU where possible, fix, add a focused regression test, and open a PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions