Repository navigation
refactor(api): quantize() takes a CalibrationConfig; drop the calibration kwargs (#4393) - #4724
Merged
Merged
Conversation
…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]>
8 tasks done
This was referenced Nov 17, 2026
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
This was referenced Nov 17, 2026
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]>
This was referenced Nov 18, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
quantize(),requantize()andGPTQModel.adapter.generate()now take every calibration choice in one frozenCalibrationConfig. It is the public class ingptqmodel/quantization/config.py, exported fromgptqmodelandgptqmodel.quantization. The looper processors use the same class; the internal copy inlooper/loop_processor.pyis 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 tomain.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
__post_init__)datasetNonestr/bytes/CalibrationConfig; required unless the quantize config is weight-onlyconcat_sizeNoneNoneor a positiveint(notbool);0is rejected,Nonedisables packingsort"desc"None,"asc","desc"or"shuffle"batch_size1int(notbool)min_length10int(notbool)concat_separatorNoneNoneorstrexclude_attention_sinksFalsebool(attention-sink exclusion)adapter_datasetNonedataset; requires aLoraadapterThe defaults are the previous
quantize()keyword defaults.__post_init__validates the types strictly (noboolpassed as an int;exclude_attention_sinksmust be a realbool, as in #4668).concat_size=0used to mean "off" and is now rejected; useNone.Design decisions
tokenizer=stays aquantize()argument. It replaces the model's tokenizer (self.tokenizer). That tokenizer tokenizes the calibration text, but it is also whatsave()writes next to the checkpoint and whatgenerate()uses, so it is model state, not calibration policy.adapter_dataset), not a second config.dataset=adapter_dataset or datasetandexclude_attention_sinks=False, matching the previous behaviour.adapter_datasetwithout aLoraadapter now raisesValueError; it used to be silently ignored.prepare_datasetis set only byCalibrationConfig.bind(). It is aninit=Falsefield.quantize()binds the model's preparer and rejects a config that is already bound.LoopProcessornow forwardsmin_lengthitself, which replaces thefunctools.partialandBaseQModel._build_calibration_config.bind().adapter_datasetandexclude_attention_sinks;exclude_attention_sinksandadapter_dataset;exclude_attention_sinkshas no effect.meta.calibration_exclude_attention_sinks: trueis still written only when the option is on, now read from the dataclass.GPTQModel.adapter.generate()used to default to unsorted calibration. It now uses the shared default,sort="desc"; passCalibrationConfig(sort=None)to keep input order.process_batchsignature fix from the feat(calibration): exclude attention sinks in the shared calibration mask (#4393) #4663 review (discussion_r4597507445). All three are nowprocess_batch(inp: Tensor, batch_index: Optional[int] = None) -> Tuple[int, Optional[Tensor], device]. GPTAQ and FOEM return(tokens, None, device)because their Hessian stays in the per-device partial, andGPTQ.add_batchforwardsbatch_indexat both call sites.ModuleLooper._set_processor_masknow accept thepadding_maskargument added in feat(calibration): exclude attention sinks in the shared calibration mask (#4393) #4663. Onmainthey fail 7 tests intest_stage_modules.pyand the forward-executor parallel/shared-KV tests; on this branch those three files pass 61/61.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:#cc3333prepare_datasetis a non-constructor field (init=False): onlyCalibrationConfig.bind()sets it, andbind()re-validates the copy.LoopProcessor.__init__passescalibration_data_min_length=calibration.min_lengthto the bound preparer itself, so the minimum length no longer travels through a
functools.partial.Before and after
mainat2ed6a6e4f)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-keywordquantize(calibration: Optional[CalibrationConfig] = None, *, tokenizer, backend, adapter, embed_quant_config, embed_quant_mode, checkpoint, fuse)(gptqmodel/models/base.py:2095)CalibrationConfig(dataset, prepare_dataset, concat_size, sort=None, concat_separator, batch_size, exclude_attention_sinks)(gptqmodel/looper/loop_processor.py:334)CalibrationConfig(gptqmodel/quantization/config.py:261) withmin_lengthandadapter_dataset;prepare_datasetset bybind()(config.py:335)BaseQModel._build_calibration_config(...)(base.py:2835) assembled it from seven argumentscalibration.bind(...)(base.py:2851)partial(self.prepare_dataset, calibration_data_min_length=...)(base.py:2897)LoopProcessorforwardscalibration.min_length(gptqmodel/looper/loop_processor.py:569)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)quantize(data, 2048)) was acceptedTypeError(no alias, shim or deprecation path)GPTQModel.adapter.generate()previously defaulted to unsorted calibration(
calibration_dataset_sort=None); it now uses theCalibrationConfigdefaultsort="desc". PassCalibrationConfig(sort=None)for the input order.Failure paths
quantize(["text"]),quantize(calibration=dataset),requantize(["text"], ...)and
adapter.generate(..., ["text"])raiseTypeErrornamingCalibrationConfig.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'sTypeError: unexpected keyword argument. Every parameter aftercalibrationis keyword-only, so an oldpositional call raises
TypeErrortoo.quantize()raisesValueError: the model ownsdataset preparation.
adapter_datasetwithout aLoraadapter raisesValueErrorbefore anylayer is quantized (previously the samples were silently ignored).
requantize(norm=...)) and post-quantization EoRA generationreject
exclude_attention_sinksandadapter_dataset, which they cannotapply.
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
mainat2ed6a6e4f. Qwen2.5-0.5B-Instruct, fp16, 64nm-calibrationrows,batch_size=1.mainranquantize(texts, batch_size=1); this branch ranquantize(CalibrationConfig(dataset=texts, batch_size=1)).quantize_config.jsonmeta.quantizer)meta.quantizer)Tests.
tests/test_calibration_config.py: 54 passed. It covers:TypeErrorfor every removed keyword, for a bare list or Dataset, and for an old positional call;quantize()that records the exactprepare_datasetarguments;adapter_datasetreaching only the adapter pass, and the no-Lora error;tests/test_calibration_attention_sinks.py: 29 passed.process_batchcontract:test_gptaq_foem_multigpu.py: 9 passed, 4 skipped (the skips need 2 GPUs). New cases cover signature parity across the three classes, GPTQadd_batchwithbatch_indexagainst 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.main2ed6a6e4f:test_fallbacknear-dead-scale: 24test_gsq_method_adaptersFP8 dtype: 2test_dynamic::test_skip_module: 1test_quant_and_eora: 1 (Hub dataset unavailable offline)tests/models/test_llama3_2.pyin fast mode (withEXCLUDE_ATTENTION_SINKS): 1 passed. It drops 512 BOS tokens from 92 batches, and the checkpoint recordsmeta.calibration_exclude_attention_sinks: true.main12c1273c2): 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..pyfile, except five findings already onmain(C408 and arocmF821) 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.pyand the subprocess script intest_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_batchsignature fix requested in the #4663 review (discussion_r4597507445).🤖 Generated with Claude Code