Skip to content

fix(quantization): validate embedding quant config before replay (#5124) - #5136

Merged
Qubitium merged 1 commit into
mainfrom
fix/5124-embed-quant-config-validation
Nov 18, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/5124-embed-quant-config-validation

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

Fixes #5124.

QuantizeEmbedConfig was a plain @dataclass with no __post_init__, and
BaseQModel._normalize_embed_quant_config returned a passed instance unchanged
(gptqmodel/models/base.py:2884-2901 at e2f9676c6). The loopers then compare
the stored mode against enum members (in (QuantizeEmbed.INPUT, ...)) and test
embed_only for truthiness. A value that matched no branch therefore started a
full calibration replay, quantized nothing, and returned a normal result dict
with no warning.

This PR validates the config where it is constructed and again where it enters
quantize()/requantize(), so a bad mode or a non-bool embed_only fails
before dataset preparation, offload, or any layer replay.

Net diff: +96/−2 in gptqmodel/ (one validator, one __post_init__, one
re-validation call), plus tests and the mechanism page. No API removal.

Root cause and reproduced behaviour

Cached Qwen/Qwen2.5-0.5B-Instruct-GPTQ-Int4, CUDA, four short calibration
rows, pre-fix e2f9676c6:

call observed
requantize(..., QuantizeEmbedConfig(embed_quant_mode="inptu")) returned {"gptq": [...]} in 3.6 s; embed_tokens stayed Embedding; nothing quantized
requantize(..., QuantizeEmbedConfig(embed_quant_mode="input")) returned in 6.2 s; embed_tokens became TorchQuantEmbeddings
requantize(..., QuantizeEmbedConfig(embed_quant_mode=None)) ValueError: layer module item 'self_attn.q_proj' not found in model after 0.9 s
QuantizeEmbedConfig(embed_only="False") stored as the truthy string; stage_layer.py:1051 (embed_only is not False) and weight_only_looper.py:1083 (bool(...) and self.embed_only) treated it as True

The removed decision mechanism, with file:line evidence:

consumer pre-fix behaviour
gptqmodel/looper/module_looper.py:2023-2029 is not None enters the embedding block, but a typo builds no requested_endpoints
gptqmodel/looper/module_looper.py:2168-2169, 2222 in (...) is False, while replay_all_layers = embed_quant_mode is not None is True
gptqmodel/looper/stage_layer.py:575-576 both endpoint flags False
gptqmodel/looper/weight_only_looper.py:842-848 both endpoint flags False
gptqmodel/looper/stage_layer.py:1051 embed_only is not False accepts a truthy non-bool
gptqmodel/looper/weight_only_looper.py:1083 bool(embedding_targets) and self.embed_only accepts a truthy non-bool

What Changed

  • gptqmodel/quantization/config.py: add _normalize_embed_quant_mode(), which
    coerces through QuantizeEmbed(value) and raises ValueError naming the
    field and the valid values ('input', 'output', 'both') for anything
    else, including None. Add QuantizeEmbedConfig.__post_init__ using that
    helper and the existing _require_bool_value ([BUG] Config validation still silently accepts bad input (#4052 incomplete): 20+ bool fields take "False" as True (mock_quantization="False" runs the mock solver), and typo'd keys in dynamic overrides are ignored and persisted #4668) for embed_only, plus
    validate() for re-validation.
  • gptqmodel/models/base.py: _normalize_embed_quant_config calls
    embed_quant_config.validate() instead of returning the instance unchanged.
    Both quantize() (base.py:2387) and requantize() (base.py:2921) call
    the normalizer before any calibration or layer work.
  • tests/test_embed_quant_api.py: construction/coercion/rejection tests, mutated
    instances through both entry points with quantize() /
    _quantize_with_calibration replaced by failing spies, and a cached-checkpoint
    CUDA case.
  • docs/embedding-quantization-config.md: mechanism page with the new flow, the
    removed flow, and the failure/ambiguity paths; linked from README.md and
    docs/README.md.

The other QuantizeEmbedConfig field is embed_only; both fields are covered.
No neighbouring teacher/dtype/calibration fields exist on this dataclass, so
nothing else was in scope.

Logic Flow Documentation

  • 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.
  • docs/embedding-quantization-config.md repeats the diagrams, is titled for
    the mechanism, and is linked from README.md.

New flow

flowchart TD
    A["quantize(embed_quant_config=...)<br/>requantize(embed_quant_config=...)"] --> B["_normalize_embed_quant_config<br/>base.py:2884"]
    B --> C{"both embed_quant_config<br/>and embed_quant_mode set"}
    C -- "yes" --> X1["ValueError: pass only one"]
    C -- "no" --> D{"embed_quant_config type"}
    D -- "QuantizeEmbed member" --> E["QuantizeEmbedConfig(embed_quant_mode=member)"]
    D -- "QuantizeEmbedConfig" --> F["embed_quant_config.validate()"]
    D -- "other" --> X2["TypeError"]
    D -- "None with embed_quant_mode" --> G{"embed_quant_mode is QuantizeEmbed"}
    G -- "no" --> X3["TypeError"]
    G -- "yes" --> E
    E --> H["__post_init__<br/>config.py:269"]
    F --> H
    H --> I{"QuantizeEmbed(embed_quant_mode)"}
    I -- "unknown or None" --> X4["ValueError: mode must be<br/>input, output or both"]
    I -- "known" --> J{"type(embed_only) is bool"}
    J -- "no" --> X5["TypeError: embed_only<br/>must be a bool"]
    J -- "yes" --> K["validated QuantizeEmbedConfig"]
    K --> L["ModuleLooper / WeightOnlyLooper<br/>endpoint selection and replay"]
    L --> M["replay_all_layers = mode is not None<br/>module_looper.py:2222"]
    L --> N["mode in INPUT, BOTH / OUTPUT, BOTH<br/>module_looper.py:2168, stage_layer.py:575,<br/>weight_only_looper.py:842"]
    style X1 fill:#ffe8e8,stroke:#cc3333
    style X2 fill:#ffe8e8,stroke:#cc3333
    style X3 fill:#ffe8e8,stroke:#cc3333
    style X4 fill:#ffe8e8,stroke:#cc3333
    style X5 fill:#ffe8e8,stroke:#cc3333
Loading

Removed mechanism

flowchart TD
    A["QuantizeEmbedConfig(embed_quant_mode=value)<br/>plain dataclass, no validation"] --> B["_normalize_embed_quant_config<br/>base.py:2884-2901 returns instance unchanged"]
    B --> C["ModuleLooper.embed_quant_mode = value<br/>module_looper.py:254"]
    C --> D{"value in INPUT, BOTH<br/>or OUTPUT, BOTH"}
    D -- "known" --> E["quantize the requested endpoint"]
    D -- "typo, whitespace, Both" --> F["requested_endpoints stays empty<br/>module_looper.py:2023-2029"]
    F --> G["replay_all_layers = value is not None<br/>module_looper.py:2222"]
    G --> H["stage_layer.py:575-576 both False<br/>weight_only_looper.py:842-848 both False"]
    H --> I["replay every layer, quantize nothing,<br/>return a normal result dict"]
    C --> J{"value is None"}
    J -- "yes" --> K["embedding block skipped<br/>is not None guards"]
    K --> L["planner fails later with<br/>layer module item self_attn.q_proj not found"]
    C --> M["embed_only is not False<br/>stage_layer.py:1051"]
    M --> N["embed_only truthiness<br/>weight_only_looper.py:1083"]
    style I fill:#ffe8e8,stroke:#cc3333
    style L fill:#ffe8e8,stroke:#cc3333
    style N fill:#ffe8e8,stroke:#cc3333
Loading

Failure and ambiguity paths

stateDiagram-v2
    [*] --> Constructed
    Constructed --> Validated: QuantizeEmbedConfig.__post_init__
    Validated --> Rejected: unknown mode or non-bool embed_only
    Validated --> Normalized: quantize() / requantize()
    Normalized --> Rejected: validate() sees a mutated field
    Normalized --> Replaying: looper selects endpoints
    Replaying --> [*]
    Rejected --> [*]
    state "Rejected (ValueError / TypeError before any layer work)" as Rejected
Loading

Tests

  • Unit tests executed and passed.
  • New simple/fast unit tests added.

Red/green evidence (same test file; source reverted with git stash for the red
run):

# red: e2f9676c6 source, new tests only
CUDA_VISIBLE_DEVICES=3 PYTHONPATH=$PWD HF_HUB_OFFLINE=1 python -m pytest \
  tests/test_embed_quant_api.py -q -k "not real_checkpoint"
# 19 failed, 20 passed  (every new test failed; the quantize() spy proved the
# bad mode reached _quantize_with_calibration before the fix)

# green: this branch
CUDA_VISIBLE_DEVICES=3 PYTHONPATH=$PWD HF_HUB_OFFLINE=1 python -m pytest \
  tests/test_embed_quant_api.py -q -k "not real_checkpoint"
# 39 passed, 1 deselected

CUDA_VISIBLE_DEVICES=3 PYTHONPATH=$PWD HF_HUB_OFFLINE=1 python -m pytest \
  tests/test_embed_quant_api.py -q -k "real_checkpoint" -rs
# 1 passed, 39 deselected  (cached Qwen2.5-0.5B-Instruct-GPTQ-Int4, CUDA)

CUDA_VISIBLE_DEVICES=3 PYTHONPATH=$PWD HF_HUB_OFFLINE=1 python -m pytest \
  tests/test_embed_quant_api.py tests/test_weight_only_looper.py \
  tests/test_stage_modules.py tests/qcfg/test_config_validation_4668.py \
  tests/test_calibration_config.py -q
# 200 passed

CUDA_VISIBLE_DEVICES=3 PYTHONPATH=$PWD HF_HUB_OFFLINE=1 python -m pytest \
  tests/test_host_memory_trim_4990.py tests/test_norm_lifecycle.py \
  tests/test_norm_requant.py tests/test_requant_embed_lm_head.py -q -rs
# 50 passed

CUDA_VISIBLE_DEVICES=3 PYTHONPATH=$PWD HF_HUB_OFFLINE=1 python -m pytest tests/qcfg -q
# 183 passed

ruff check gptqmodel/quantization/config.py gptqmodel/models/base.py tests/test_embed_quant_api.py
# All checks passed!

Post-fix behaviour on the same cached checkpoint:

QuantizeEmbedConfig(embed_quant_mode="inptu")
  -> ValueError: QuantizeEmbedConfig: `embed_quant_mode` must be one of
     'input', 'output', 'both' (a QuantizeEmbed value), got 'inptu'.
QuantizeEmbedConfig(embed_quant_mode=None)      -> same ValueError, got None
QuantizeEmbedConfig(embed_only="False")
  -> TypeError: QuantizeEmbedConfig: `embed_only` must be a bool, got str ('False').
valid "input" requantize -> 7.5 s, embed_tokens: Embedding -> TorchQuantEmbeddings
mutated config through requantize() -> ValueError after 0.00 s, quantize() never called

Skip / limitation: tests/test_requant_embed_lm_head_e2e.py was not used as
evidence. It requires /monster/data/model/Qwen2.5-0.5B-Instruct-gptq-4bit and
downloads allenai/ai2_arc; under HF_HUB_OFFLINE=1 it fails in datasets
with ConnectionError, before touching embedding config validation.

Model Support / Module Plan

Not applicable: no model, alias, module plan, fusion or AWQ change.

Review Requirements

Kernel Accuracy Requirements

Not applicable: no kernel or numerical change.

Notes

  • validate() re-runs __post_init__, so a caller that mutates a config after
    construction is rejected at the entry point rather than silently ignored.
  • The compatibility embed_quant_mode= keyword still requires a
    QuantizeEmbed member; a bare string there keeps raising TypeError (use
    QuantizeEmbedConfig(embed_quant_mode="input")).
  • Out of scope: QuantizeEmbedConfig is not serialized into checkpoints, so no
    migration is needed for existing files.

QuantizeEmbedConfig was a bare dataclass, and _normalize_embed_quant_config
returned a passed instance unchanged. A misspelled embed_quant_mode matched
none of the looper branches, so the run replayed calibration over every layer,
quantized nothing, and returned a normal result dict. embed_quant_mode=None
failed later with an unrelated missing-layer error, and embed_only="False"
was truthy.

Add __post_init__ that coerces embed_quant_mode through QuantizeEmbed
(raising ValueError listing the valid values) and validates embed_only with
the #4668 _require_bool_value helper. Re-validate a passed instance at both
entry points so a mutated config is rejected before dataset preparation,
offload, or any layer replay.

Adds tests/test_embed_quant_api.py regressions (CPU construction and both
entry points, plus a cached-checkpoint CUDA case) and the mechanism page
docs/embedding-quantization-config.md linked from README.md.
@Qubitium
Qubitium force-pushed the fix/5124-embed-quant-config-validation branch from 21e96de to aafca0a Compare November 18, 2026 05:45
@Qubitium
Qubitium marked this pull request as ready for review November 18, 2026 05:58
@Qubitium
Qubitium merged commit a4506d6 into main Nov 18, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/5124-embed-quant-config-validation branch November 18, 2026 05:58
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