Skip to content

fix(config): normalize EXL3 serialization and reject silent kwarg drops (#4052) - #4057

Merged
Qubitium merged 3 commits into
mainfrom
fix/issue-4052
Nov 14, 2026
Merged

Qubitium merged 3 commits into
mainfrom
fix/issue-4052

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Fixes #4052

TL;DR

Config construction and checkpoint reload now fail closed where they used to
drop user settings, and every concrete config class normalises the fields
to_dict() assumes are already Enum/dataclass instances. The net change is
6 files under gptqmodel/, 3 test files, 1 new reference page, and the README
link. EXL3Config(auto_dtype_cast="off") quantizes and saves end to end on
CUDA and ROCm; the same run crashed in writer.py before this change.

1. The problem

EXL3Config.__post_init__ bypassed BaseQuantizeConfig.__post_init__
(gptqmodel/quantization/config.py:6303 before this change), so
auto_dtype_cast stayed a str, telemetry stayed a dict, and mse
stayed a number. to_dict() then assumed normalised types
(config.py:4925 self.auto_dtype_cast.value, config.py:4897
asdict(self.telemetry)).

The factory path had the opposite failure mode: QuantizeConfig(...)
filtered kwargs down to the dispatched class's init fields with no error or
log (_filter_quantize_config_payload_for_target_cls), so typos and
method-incompatible fields vanished.

Old flow:

flowchart TD
    A["QuantizeConfig kwargs"] --> B["_resolve_quantize_config_class"]
    B --> C["_filter_quantize_config_payload_for_target_cls"]
    C -->|"unknown or foreign key"| D["silently dropped"]
    D --> E["concrete config __post_init__"]
    E -->|"EXL3 bypasses base"| F["raw str and dict fields"]
    F --> G["to_dict"]
    G -->|"EXL3"| H["AttributeError or TypeError"]
    classDef fail fill:#ffd6d6,stroke:#c00000,color:#000
    class D,H fail
Loading

Before/after mechanisms:

Area Before After
Factory kwargs _filter_quantize_config_payload_for_target_cls dropped unknown and foreign keys silently _validate_quantize_config_factory_kwargs raises for unknown keys and warns for foreign known fields (config.py:4012)
EXL3 fields EXL3Config.__post_init__ bypassed base normalisation calls _normalize_serialization_fields (config.py:6401)
Serialization helper duplicated in BaseQuantizeConfig.__post_init__ shared helper (config.py:4429)
Bool fields bool() accepted the string "False" as True _validate_bool_fields raises TypeError (config.py:4452)
Calibration examples isinstance(example, dict) rejected BatchEncoding (calibration.py:352) isinstance(example, Mapping) (calibration.py:356)
Device placement explicit device replaced by device_map without a check (loader.py:1735) _normalize_requested_device_map (loader.py:569) checks agreement and maps HF strings
static_groups written to meta, absent from the reload map mapped in from_quant_config (config.py:4831)

2. The new flow

flowchart TD
    A["QuantizeConfig kwargs"] --> B["_normalize_quantize_config_constructor_kwargs"]
    B --> C["_resolve_quantize_config_class"]
    C --> D["_validate_quantize_config_factory_kwargs"]
    D -->|"unknown key"| E["TypeError with close-match hint"]
    D -->|"known field not accepted by target"| F["WARN and drop"]
    D -->|"accepted"| G["_prepare_target_quantize_config_kwargs"]
    G --> H["concrete config __post_init__"]
    H --> I["_normalize_serialization_fields"]
    I --> J["to_dict"]
    classDef fail fill:#ffd6d6,stroke:#c00000,color:#000
    class E fail
Loading

from_quant_config is unchanged and stays lenient: it still logs and ignores
unknown keys so old checkpoints load. The strict check lives only on the
QuantizeConfig(...) factory and GPTQModel.load(..., quantize_config=dict).

EXL3 now runs the shared normalisation directly:

flowchart LR
    A["EXL3Config __post_init__"] --> B["_normalize_preprocessor_state"]
    B --> C["_normalize_serialization_fields"]
    C --> D["AutoDtypeCast"]
    C --> E["TelemetryConfig"]
    C --> F["MSEConfig"]
    D --> G["to_dict"]
    E --> G
    F --> G
Loading

Device and device_map:

flowchart TD
    A["from_quantized device and device_map"] --> B["_normalize_requested_device_map"]
    B -->|"device_map is cpu or cuda:N string"| C["map to empty-key device map"]
    B -->|"accelerate keyword"| D["keep keyword string"]
    B --> E{"device also set?"}
    E -->|"yes"| F["_validate_device_and_device_map_agree"]
    F -->|"family mismatch"| G["ValueError"]
    F -->|"families agree"| H["use device_map"]
    E -->|"no"| H
    classDef fail fill:#ffd6d6,stroke:#c00000,color:#000
    class G fail
Loading

The reference page with the same diagrams and the failure contract is
docs/config-serialization.md, linked from README.md next to the concrete
config classes.

3. Before/after repro

Config items (CPU, PYTHONPATH=$PWD):

# before
EXL3Config(auto_dtype_cast='off').to_dict()
  -> AttributeError: 'str' object has no attribute 'value'
EXL3Config(auto_dtype_cast='bogus')
  -> accepted
EXL3 default to_dict -> from_quant_config -> to_dict
  -> TypeError: asdict() should be called on dataclass instances
QuantizeConfig(bits=4, damp_percnt=0.1)
  -> GPTQConfig, no error, damp_percent stayed 0.05
QuantizeConfig(method='awq', static_groups=True, gptaq=...)
  -> AWQConfig, both fields vanished
[tokenizer(text)]
  -> ValueError: unsupported calibration example type BatchEncoding
device='cpu', device_map={'': 'cuda:0'}
  -> cpu request silently replaced
device_map='cpu'
  -> ValueError: If passing a string for device_map ...
static_groups written to meta
  -> reloaded as False
GPTQConfig(desc_act='False').desc_act
  -> True
# after
EXL3Config(auto_dtype_cast='off').to_dict()
  -> {'auto_dtype_cast': 'off', ...}
EXL3Config(auto_dtype_cast='bogus')
  -> ValueError: auto_dtype_cast must be 'auto_nf12' or 'off'
EXL3 to_dict -> from_quant_config -> to_dict
  -> identical payload
QuantizeConfig(bits=4, damp_percnt=0.1)
  -> TypeError: ... `damp_percnt` (did you mean `damp_percent`?)
QuantizeConfig(method='awq', static_groups=True, gptaq=...)
  -> WARN: AWQConfig does not accept ['gptaq', 'static_groups']
[tokenizer(text)]
  -> accepted
device='cpu', device_map={'': 'cuda:0'}
  -> ValueError: device selects cpu but device_map selects cuda
device_map='cpu'
  -> {'': 'cpu'}
static_groups written to meta
  -> reloaded as True
GPTQConfig(desc_act='False')
  -> TypeError: desc_act must be a bool or None

End-to-end EXL3 (bits=2, auto_dtype_cast="off", tiny Llama with
128-wide projections):

# before (main @ 39cd57a85, CUDA 4090)
quantized
Traceback ...
  File ".../gptqmodel/models/writer.py", line 2039, in save_quantized
AttributeError: 'str' object has no attribute 'value'

# after (CUDA 4090 and R9700)
quantized
saved ['config.json', 'model.safetensors', 'quantize_config.json', ...]
saved auto_dtype_cast: off telemetry: {'device': False}

4. Tests and validation

New/updated tests:

  • tests/qcfg/test_config_serialization.py — every concrete config normalises
    auto_dtype_cast/telemetry/mse; EXL3 round-trip; static_groups reload;
    bool fields reject strings and ints.
  • tests/qcfg/test_config_dispatch.py — unknown factory kwarg raises with a
    suggestion; foreign known fields warn; from_quant_config stays lenient.
  • tests/test_calibration_mapping_input.py — BatchEncoding calibration rows.
  • tests/test_loader.py — HF device_map strings, invalid/offload strings,
    and device/device_map agreement and conflict.

Exact commands and measured results:

# CUDA venv, post-merge branch
PYTHONPATH=$PWD /opt/venvs/cu130t/bin/python -m pytest -q \
  tests/qcfg tests/test_calibration_padding_mask.py \
  tests/test_calibration_truncation.py tests/test_calibration_windows.py \
  tests/test_loader.py tests/test_calibration_mapping_input.py
# 139 passed, 1 warning

# ROCm venv, post-merge branch
HIP_VISIBLE_DEVICES=1 PYTHONPATH=$PWD /opt/venvs/rocm101t/bin/python -m pytest -q \
  tests/qcfg tests/test_calibration_padding_mask.py \
  tests/test_calibration_truncation.py tests/test_calibration_windows.py \
  tests/test_loader.py tests/test_calibration_mapping_input.py
# 139 passed, 1 warning

# Fail-before, same four new/updated files on origin/main @ 451d304cb
# 20 failed, 42 passed
# Pass-after on the branch
# 62 passed

ruff check gptqmodel docs/eora tests setup.py
# All checks passed!

Hardware:

  • CUDA: NVIDIA RTX 4090, GPU-1ece7ec2-d88d-9284-93c8-d2578d90ad7e,
    torch 2.16.0.dev+cu130, Py3.14t.
  • ROCm: AMD Radeon AI PRO R9700, HIP_VISIBLE_DEVICES=1,
    torch 2.16.0.dev+rocm10.1, Py3.14t.
  • The RTX 5090 was not used. nvidia-smi --query-compute-apps showed the
    assigned 4090 free before the timing/GPU runs.

5. Risk and limitations

  • QuantizeConfig(**config.to_dict()) is preserved for every concrete config
    tested; RTN to_dict still dispatches to GPTQConfig because RTN is a
    weight-only mode without a top-level method marker. That predates this PR and
    is not changed here.
  • QuantizeConfig(method='gptq', format='gemm') still auto-selects AWQ with a
    warning, and GPTQModel.load(quantized_path, quantize_config=X) still
    ignores X; both are separate dispatch contracts listed as follow-up in the
    docs page.
  • The strict factory check is intentionally not applied to
    from_quant_config, so legacy checkpoint JSON with unknown keys keeps
    loading.

…ps (#4052)

- Run the base serialization normalization for EXL3Config so auto_dtype_cast,
  telemetry, and mse survive to_dict/from_quant_config round trips.
- Validate QuantizeConfig factory kwargs: unknown keys raise with a suggestion,
  known fields for another method warn instead of vanishing, and
  from_quant_config stays lenient for legacy checkpoints.
- Accept Mapping calibration examples such as BatchEncoding.
- Honor HF device_map string shorthand and reject device/device_map conflicts.
- Reload static_groups from checkpoint meta and reject non-bool bool fields.
- Document the flow in docs/config-serialization.md and link it from README.
@Qubitium
Qubitium merged commit 50dce35 into main Nov 14, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/issue-4052 branch November 14, 2026 19:35
Qubitium added a commit that referenced this pull request Nov 17, 2026
#4693)

Two config paths still accepted input that silently changed, or failed to
change, what got quantized. #4052/#4057 covered the top-level kwargs and eight
base bool fields; both gaps below are the remainder.

**Bool fields.** `_validate_bool_fields` checked a hand-maintained list of eight
names. Every other bool field was coerced with `bool(...)` (so `"False"` became
`True`) or stored as a truthy string. Derive the set from the dataclass
annotations instead, so a field cannot be added without being validated.
`Optional[bool]` keeps `None` as the documented "use the default" value.
`MacaqConfig` forces `sym=True` before `super().__post_init__()`, so it now
validates the caller's input first; otherwise the forced value is all the
validator ever saw.

**`dynamic` rules.** `_normalize_dynamic_layer_config` checked only the `bits`
and `group_size` values, never that the keys were known. A misspelled override
(`{"bit": 8, "group_sise": 32}`) was accepted, had no effect, and was written
into the checkpoint, so the saved mixed-precision layout differed from the one
requested. Reject unknown keys against the union of every known config class's
fields plus the legacy aliases (`fmt`, and the opaque `nested` passthrough), so
a checkpoint carrying another backend's field still loads. Reuse the difflib
close-match hint from the top-level kwargs check. Also compile each pattern at
construction: a bad regex used to survive until the first module match.

Closes #4668.
Qubitium added a commit that referenced this pull request Nov 17, 2026
) (#4698)

`BaseQModel.save(..., **kwargs)` forwarded `**kwargs` only on the non-quantized
branch. For a quantized model — the normal case — every extra keyword was
discarded without an error or a log line, so a typo of a real parameter and an
HF option such as `push_to_hub=True` both reported success and did nothing.

Raise `TypeError` for any leftover keyword on the quantized branch, with the
same difflib close-match hint `QuantizeConfig` uses for unknown kwargs (#4057):
`max_shard_sise` now points at `max_shard_size`.

The module-replacement writer (`save_quantized_embeddings`) also dropped two of
`save()`'s own named parameters. It writes a weight-only replacement checkpoint
and has no adapter or split support, so `eora_path`/`split_by` are now rejected
there explicitly instead of being ignored.

This is the save-side counterpart of #4052/#4057.

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

Labels

None yet

Projects

None yet

1 participant