Skip to content

refactor(api): quantize() takes a CalibrationConfig; drop the calibration kwargs (#4393) - #4724

Merged
Qubitium merged 1 commit into
mainfrom
refactor/calibration-config-api
Nov 17, 2026
Merged

Qubitium merged 1 commit into
mainfrom
refactor/calibration-config-api

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

quantize(), requantize() and GPTQModel.adapter.generate() now take every calibration choice in one frozen CalibrationConfig. It is the public class in gptqmodel/quantization/config.py, exported from gptqmodel and gptqmodel.quantization. The looper processors use the same class; the internal copy in looper/loop_processor.py is gone.

There is no backward compatibility. A bare dataset, any removed keyword, or an old positional call raises TypeError. A default run writes a checkpoint bitwise identical to main.

from gptqmodel import CalibrationConfig, GPTQConfig, GPTQModel

model = GPTQModel.load("Qwen/Qwen3-0.6B", GPTQConfig(bits=4, group_size=128))
model.quantize(CalibrationConfig(dataset=texts, batch_size=1))
def quantize(self, calibration: Optional[CalibrationConfig] = None, *,
             tokenizer=None, backend=BACKEND.AUTO, adapter=None,
             embed_quant_config=None, embed_quant_mode=None, checkpoint=None, fuse=None)
def requantize(self, calibration: CalibrationConfig, *, embed_quant_config=None, tokenizer=None,
               backend=BACKEND.AUTO, adapter=None, embed_quant_mode=None, norm=None)
GPTQModel.adapter.generate(adapter, model_id_or_path, quantized_model_id_or_path,
                           calibration: CalibrationConfig, *, tokenizer=None, ...)

The removed keywords are:

  • quantize() / requantize(): calibration_concat_size, calibration_sort, batch_size, calibration_data_min_length, calibration_concat_separator, calibration_exclude_attention_sinks, adapter_calibration_dataset.
  • adapter.generate(): calibration_dataset, calibration_dataset_concat_size, calibration_dataset_sort, batch_size, calibration_concat_separator.

API

field default validation (__post_init__)
dataset None not a str/bytes/CalibrationConfig; required unless the quantize config is weight-only
concat_size None None or a positive int (not bool); 0 is rejected, None disables packing
sort "desc" None, "asc", "desc" or "shuffle"
batch_size 1 positive int (not bool)
min_length 10 non-negative int (not bool)
concat_separator None None or str
exclude_attention_sinks False bool (attention-sink exclusion)
adapter_dataset None as dataset; requires a Lora adapter

The defaults are the previous quantize() keyword defaults. __post_init__ validates the types strictly (no bool passed as an int; exclude_attention_sinks must be a real bool, as in #4668). concat_size=0 used to mean "off" and is now rejected; use None.

Design decisions

  • tokenizer= stays a quantize() argument. It replaces the model's tokenizer (self.tokenizer). That tokenizer tokenizes the calibration text, but it is also what save() writes next to the checkpoint and what generate() uses, so it is model state, not calibration policy.
  • EoRA samples are a field (adapter_dataset), not a second config.
    • The EoRA pass has always reused the main pass's concat size, sort, separator, minimum length and batch size, and fell back to the main samples.
    • A second config would make callers repeat all of that.
    • The EoRA pass binds a copy with dataset=adapter_dataset or dataset and exclude_attention_sinks=False, matching the previous behaviour.
    • adapter_dataset without a Lora adapter now raises ValueError; it used to be silently ignored.
  • prepare_dataset is set only by CalibrationConfig.bind(). It is an init=False field. quantize() binds the model's preparer and rejects a config that is already bound.
    • LoopProcessor now forwards min_length itself, which replaces the functools.partial and BaseQModel._build_calibration_config.
    • The run plan's effective batch size is applied through bind().
  • Paths that cannot use a field reject it:
    • staged GSQ rejects adapter_dataset and exclude_attention_sinks;
    • norm tuning and post-quantization EoRA reject exclude_attention_sinks and adapter_dataset;
    • weight-only quantization warns that exclude_attention_sinks has no effect.
  • Provenance is unchanged. meta.calibration_exclude_attention_sinks: true is still written only when the option is on, now read from the dataclass.
  • Behaviour change: GPTQModel.adapter.generate() used to default to unsorted calibration. It now uses the shared default, sort="desc"; pass CalibrationConfig(sort=None) to keep input order.
  • Also included:

Flow

flowchart TD
    U["model.quantize(calibration, *, tokenizer, backend, adapter, ...)"] --> T{"calibration"}
    T -- "None" --> N["CalibrationConfig()"]
    T -- "not a CalibrationConfig<br/>(list, Dataset, ...)" --> X1["TypeError"]
    T -- "already bound<br/>(prepare_dataset set)" --> X2["ValueError"]
    T -- "CalibrationConfig" --> V["validated in __post_init__"]
    N --> P
    V --> P{"run plan"}
    P -- "staged GSQ" --> G["quantize_llama_gsq_public(calibration=...)<br/>adapter_dataset / exclude_attention_sinks rejected"]
    P -- "weight-only" --> W["_quantize_weight_only<br/>dataset ignored"]
    P -- "calibrated" --> D{"dataset is None"}
    D -- "yes" --> X3["ValueError: CalibrationConfig.dataset is required"]
    D -- "no" --> L{"adapter_dataset set<br/>without a Lora adapter"}
    L -- "yes" --> X4["ValueError"]
    L -- "no" --> B["_quantize_with_calibration<br/>calibration.bind(self.prepare_dataset,<br/>batch_size=run_plan.batch_size, adapter_dataset=None)"]
    B --> PR["every LoopProcessor<br/>prepare_dataset(concat_size, sort, batch_size,<br/>min_length, concat_separator)"]
    B --> E["EoRA: calibration_config.bind(..., dataset=adapter_dataset or dataset,<br/>exclude_attention_sinks=False)"]
    style X1 fill:#ffe8e8,stroke:#cc3333
    style X2 fill:#ffe8e8,stroke:#cc3333
    style X3 fill:#ffe8e8,stroke:#cc3333
    style X4 fill:#ffe8e8,stroke:#cc3333
Loading

prepare_dataset is a non-constructor field (init=False): only
CalibrationConfig.bind() sets it, and bind() re-validates the copy.
LoopProcessor.__init__ passes calibration_data_min_length=calibration.min_length
to the bound preparer itself, so the minimum length no longer travels through a
functools.partial.

Before and after

before (main at 2ed6a6e4f) after
quantize(calibration=None, calibration_concat_size=None, calibration_sort="desc", batch_size=1, tokenizer=None, backend=..., adapter=None, adapter_calibration_dataset=None, calibration_data_min_length=10, calibration_concat_separator=None, ..., calibration_exclude_attention_sinks=False) (gptqmodel/models/base.py:2095), every argument positional-or-keyword quantize(calibration: Optional[CalibrationConfig] = None, *, tokenizer, backend, adapter, embed_quant_config, embed_quant_mode, checkpoint, fuse) (gptqmodel/models/base.py:2095)
internal CalibrationConfig(dataset, prepare_dataset, concat_size, sort=None, concat_separator, batch_size, exclude_attention_sinks) (gptqmodel/looper/loop_processor.py:334) one public CalibrationConfig (gptqmodel/quantization/config.py:261) with min_length and adapter_dataset; prepare_dataset set by bind() (config.py:335)
BaseQModel._build_calibration_config(...) (base.py:2835) assembled it from seven arguments removed; calibration.bind(...) (base.py:2851)
partial(self.prepare_dataset, calibration_data_min_length=...) (base.py:2897) LoopProcessor forwards calibration.min_length (gptqmodel/looper/loop_processor.py:569)
EoRA config rebuilt from adapter_calibration_dataset (base.py:2945) calibration_config.bind(dataset=adapter_dataset or dataset, exclude_attention_sinks=False) (base.py:2895)
requantize(calibration, embed_quant_config, calibration_concat_size, ...) (base.py:2629) requantize(calibration: CalibrationConfig, *, ...) (base.py:2630)
GPTQModel.adapter.generate(..., calibration_dataset, calibration_dataset_concat_size, calibration_dataset_sort=None, batch_size, tokenizer, calibration_concat_separator) (gptqmodel/models/auto.py:1338) generate(adapter, model_id_or_path, quantized_model_id_or_path, calibration: CalibrationConfig, *, tokenizer, ...) (auto.py:1344)
quantize_llama_gsq_public(..., calibration_concat_size, calibration_sort, calibration_data_min_length, calibration_concat_separator, ...) (gptqmodel/looper/gsq_training_model.py:661) quantize_llama_gsq_public(wrapper, *, calibration, tokenizer, backend, unsupported)
a bare list, an old keyword, or an old positional (quantize(data, 2048)) was accepted TypeError (no alias, shim or deprecation path)

GPTQModel.adapter.generate() previously defaulted to unsorted calibration
(calibration_dataset_sort=None); it now uses the CalibrationConfig default
sort="desc". Pass CalibrationConfig(sort=None) for the input order.

Failure paths

  • quantize(["text"]), quantize(calibration=dataset), requantize(["text"], ...)
    and adapter.generate(..., ["text"]) raise TypeError naming
    CalibrationConfig.
  • Any removed keyword (calibration_concat_size, calibration_sort,
    batch_size, calibration_data_min_length, calibration_concat_separator,
    calibration_exclude_attention_sinks, adapter_calibration_dataset,
    calibration_dataset*) raises Python's TypeError: unexpected keyword argument. Every parameter after calibration is keyword-only, so an old
    positional call raises TypeError too.
  • A pre-bound config passed to quantize() raises ValueError: the model owns
    dataset preparation.
  • adapter_dataset without a Lora adapter raises ValueError before any
    layer is quantized (previously the samples were silently ignored).
  • Norm tuning (requantize(norm=...)) and post-quantization EoRA generation
    reject exclude_attention_sinks and adapter_dataset, which they cannot
    apply.

Reference page: docs/calibration-config.md, linked from the README quickstart.

Validation

All runs on CUDA (CUDA_VISIBLE_DEVICES=4, PCI bus order), HF_HUB_OFFLINE=1.

Bitwise check against main at 2ed6a6e4f. Qwen2.5-0.5B-Instruct, fp16, 64 nm-calibration rows, batch_size=1. main ran quantize(texts, batch_size=1); this branch ran quantize(CalibrationConfig(dataset=texts, batch_size=1)).

method tensors differing quantize_config.json
GPTQ 4-bit g128 794 0 identical (excluding meta.quantizer)
AWQ 4-bit g128 626 0 identical (excluding meta.quantizer)

Tests.

  • New tests/test_calibration_config.py: 54 passed. It covers:
    • field validation and the signatures of all three entry points;
    • TypeError for every removed keyword, for a bare list or Dataset, and for an old positional call;
    • a CPU tiny-Llama quantize() that records the exact prepare_dataset arguments;
    • sink provenance through save and reload;
    • EoRA adapter_dataset reaching only the adapter pass, and the no-Lora error;
    • weight-only quantize with no calibration.
  • tests/test_calibration_attention_sinks.py: 29 passed.
  • process_batch contract:
    • test_gptaq_foem_multigpu.py: 9 passed, 4 skipped (the skips need 2 GPUs). New cases cover signature parity across the three classes, GPTQ add_batch with batch_index against a float64 Hessian oracle, and the GPTAQ/FOEM return tuple.
    • test_gptq_hessian_pipeline.py: 16 passed.
    • test_moe_gptaq_foem.py: 6 passed.
    • test_gptq.py: 71 passed.
  • 48 calibration/looper/EoRA/GSQ/AWQ/GPTQ/QQQ/VPTQ/ParoQuant/EXL3 test files, including every file touched by the rebase: 1479 passed, 28 failed, 23 skipped.
    • All 28 failures fail identically on main 2ed6a6e4f:
      • test_fallback near-dead-scale: 24
      • test_gsq_method_adapters FP8 dtype: 2
      • test_dynamic::test_skip_module: 1
      • test_quant_and_eora: 1 (Hub dataset unavailable offline)
  • tests/models/test_llama3_2.py in fast mode (with EXCLUDE_ATTENTION_SINKS): 1 passed. It drops 512 BOS tokens from 92 batches, and the checkpoint records meta.calibration_exclude_attention_sinks: true.
  • Before this rebase (same change on the feat(calibration): exclude attention sinks in the shared calibration mask (#4393) #4663 base, against main 12c1273c2): a 303-file sweep gave main 5263 passed / 99 failed versus branch 5268 passed / 77 failed. Its only regressions were tests deleted by feat(calibration): exclude attention sinks in the shared calibration mask (#4393) #4663 itself or tests that hit GPU contention and pass when run serially.
  • Ruff is clean on every changed .py file, except five findings already on main (C408 and a rocm F821) in lines this PR does not touch.

Rebased onto 1826c23a6; the three newest main tests (test_awq_moe_root_capture_4697.py, test_awq_deepseek_v4_rotary_4695.py and the subprocess script in test_rocm_default_env.py) are converted to the new API and pass (10/10 for the two AWQ files).

Follow-up to #4663 (merged with its first commit only); this also lands the process_batch signature fix requested in the #4663 review (discussion_r4597507445).

🤖 Generated with Claude Code

…tion kwargs (#4393)

`quantize()`, `requantize()` and `GPTQModel.adapter.generate()` take every
calibration choice in one frozen `CalibrationConfig`, now the public class in
`gptqmodel/quantization/config.py` (exported from `gptqmodel` and
`gptqmodel.quantization`). The looper processors use the same class; the
internal copy in `looper/loop_processor.py` is gone. No backward-compatibility
path: a bare dataset, any removed keyword, or an old positional call raises
`TypeError`.

    quantize(self, calibration: Optional[CalibrationConfig] = None, *,
             tokenizer=None, backend=BACKEND.AUTO, adapter=None,
             embed_quant_config=None, embed_quant_mode=None,
             checkpoint=None, fuse=None)

- Fields and defaults (the previous quantize() defaults): dataset=None,
  concat_size=None, sort="desc", batch_size=1, min_length=10,
  concat_separator=None, exclude_attention_sinks=False, adapter_dataset=None.
  `__post_init__` validates types and values (sort in asc/desc/shuffle/None,
  positive ints, non-negative min_length, bool sink switch, no bare string).
- Removed kwargs: calibration_concat_size, calibration_sort, batch_size,
  calibration_data_min_length, calibration_concat_separator,
  calibration_exclude_attention_sinks, adapter_calibration_dataset (quantize/
  requantize) and calibration_dataset* / batch_size / calibration_concat_separator
  (adapter.generate). Everything after `calibration` is keyword-only.
- `adapter_dataset` is a field, not a second config: the EoRA pass has always
  reused the main pass's preparation policy and fell back to the main samples.
  It now fails closed without a Lora adapter instead of being ignored.
- `tokenizer=` stays a quantize() argument: it replaces the model tokenizer
  that save() writes and generate() uses, not only calibration tokenization.
- `prepare_dataset` is an init=False field set only by `CalibrationConfig.bind()`;
  `LoopProcessor` forwards `min_length` itself, replacing the functools.partial
  and `BaseQModel._build_calibration_config`. quantize() rejects a pre-bound
  config.
- Staged GSQ, norm tuning and post-quantization EoRA read the same object and
  reject the fields they cannot apply. Provenance (`meta.calibration_exclude_
  attention_sinks`) is unchanged, now sourced from the dataclass.
- adapter.generate() now defaults to sort="desc" like quantize() (was None).
- concat_size=0 is rejected; None disables packing (call sites updated).
- GPTQ/GPTAQ/FOEM `process_batch(inp, batch_index=None) -> Tuple[int,
  Optional[Tensor], device]` share one signature; GPTQ.add_batch forwards
  batch_index (code-quality review on #4663).
- Update every caller: package, scripts, optimize/, tests, README and docs;
  add docs/calibration-config.md (flow, before/after, failure paths).
- Test stubs for `ModuleLooper._set_processor_mask` accept the `padding_mask`
  argument the sink change added (forward-executor parallel/shared-KV and
  stage-module tests failed on it).

Tests: tests/test_calibration_config.py (validation, signatures, TypeError for
every removed kwarg and a bare dataset, tiny-Llama quantize that records the
exact prepare_dataset arguments, sink provenance through save/reload, EoRA
adapter samples, weight-only without calibration);
tests/test_gptaq_foem_multigpu.py (process_batch signature parity, GPTQ
add_batch Hessian vs float64 oracle).

Includes the GPTQ/GPTAQ/FOEM process_batch signature fix from the #4663 review (discussion_r4597507445).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Qubitium
Qubitium merged commit 4a871bf into main Nov 17, 2026
9 checks passed
@Qubitium
Qubitium deleted the refactor/calibration-config-api branch November 17, 2026 11:45
Qubitium added a commit that referenced this pull request Nov 17, 2026
…ntract refs (#4762) (#4791)

Fixes the four docs-vs-code items from #4762. Every corrected snippet was run
on CPU (`CUDA_VISIBLE_DEVICES=""`); no model was downloaded.

1. `docs/quantization-lifecycle-contracts.md` no longer builds a pre-bound
   `CalibrationConfig`. The processor example imports `CalibrationConfig` from
   `gptqmodel` (not `gptqmodel.looper.loop_processor`) and uses the post-#4724
   `CalibrationConfig(...).bind(model.prepare_dataset)` form, because
   `prepare_dataset` is `init=False` and passing it raises `TypeError`. The
   run-plan and `LoopPlan` examples now import the names they use, and
   `docs/calibration-config.md` imports `BACKEND` (it raised `NameError`).

2. Rotation is documented as the `QuantizeConfig.rotation` field, not a
   `quantize()` keyword, in `docs/quantization-features.md` (table row and
   Mermaid node) and `docs/rotation-model-support.md` (opening sentence and
   Mermaid node). `quantize()` has no `rotation` parameter, so the old call
   raised `TypeError`; the config form is the one `docs/gptq-w4a-gb10.md`
   already showed.

3. EoRA: `docs/eora/eora_generation.py` now sets `Lora(path=eora_path)`
   instead of joining `quant_path` and `eora_path`. `save()` writes the
   adapter to `adapter.path` (`models/writer.py:_eora_save`), so the old join
   produced `<quant>/<eora>` while the README's evaluation and inference steps
   read `<eora>`. Save and load now agree for both generation options. The
   inference snippet's trailing space in `Lora.path` is removed.

4. Contract `file:line` references: re-pointed 72 drifted citations across 40
   pages at the definition line the page names, and removed 2 stale
   `gptqmodel/utils/nf12.py` line refs (that file has 91 lines). Each new line
   was verified by opening the file, and each replaced citation was checked
   against the revision that introduced the doc line: where the old number
   named a `def`/`class`, it was that definition in that revision, so the new
   number is that symbol's definition today. Line ranges keep their span.
   Citations that already pointed at a correct usage line were left alone: the
   issue's heuristic flagged ~100 refs, and this change covers the ones whose
   named symbol moved, not the whole flagged set.

Guard: `tests/test_docs_contract_refs.py` imports every `gptqmodel` name used
by the doc blocks this change touches and resolves an explicit list of
contract citations (file exists, symbol defined within +-8 lines of the cited
line). It also pins the three API contracts above. It downloads nothing and
takes ~6 s. On unmodified `main` it fails 15 of 20 cases.

Tests:
  tests/test_docs_contract_refs.py: 20 passed
Qubitium added a commit that referenced this pull request Nov 17, 2026
… (#4919)

tests/test_excluded_device_warmup.py::test_quantize_never_claims_the_excluded_device
is the end-to-end gate for #4320/#4653, but its subprocess script still called
quantize() with batch_size= and calibration_data_min_length=, both removed by
#4724. Both parametrizations raised TypeError before measuring anything, so the
"excluded GPU stays unclaimed" guarantee had no working test. The test is
gpu/slow/integration and needs two devices, which is why CI never saw it.

The script now passes CalibrationConfig(dataset=..., batch_size=1, min_length=1).

tests/test_quantize_call_signature_4868.py is the CPU-only guard: it parses
every module under tests/ and the Python source held in its string constants
(where the broken call lived) and rejects any quantize() call that passes a
keyword removed by #4724. Two extra cases keep the scan honest - it must reach
the embedded gate script, and that script's quantize() must pass a
CalibrationConfig.

Red: 2 failed (TypeError) on the gate, 2 failed in the new guard.
Green: 2 passed on the gate, 17 passed for the file, 3 passed in the guard.

Co-authored-by: gptqmodel-agent <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant