Skip to content

PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度

Optimize diffusion calibration step sampling (#2265)

Wang, Changce90add61e93
diff --git a/auto_round/autoround.py b/auto_round/autoround.py
index 12c3dda97..6b96ceff4 100644
--- a/auto_round/autoround.py
+++ b/auto_round/autoround.py
@@ -353,6 +353,7 @@ _ENTRY_KWARG_OWNERS = {
"quant_nontext_module": "mllm",
"guidance_scale": "diffusion",
"num_inference_steps": "diffusion",
+ "calib_num_inference_steps": "diffusion",
"generator_seed": "diffusion",
}
diff --git a/auto_round/calibration/diffusion.py b/auto_round/calibration/diffusion.py
index c60a08279..29fca0141 100644
--- a/auto_round/calibration/diffusion.py
+++ b/auto_round/calibration/diffusion.py
@@ -57,8 +57,9 @@ class DiffusionCalibrator(LLMCalibrator):
super().__init__(compressor)
self.pipe = compressor.pipe
self.guidance_scale = compressor.guidance_scale
- self.num_inference_steps = compressor.num_inference_steps
+ self.calib_num_inference_steps = compressor.calib_num_inference_steps
self.generator_seed = compressor.generator_seed # make sure pass
+ self.pipeline_call_kwargs = dict(getattr(compressor, "pipeline_call_kwargs", {}) or {})
def _wrap_block_forward(self, forward_fn):
"""Wrap positional-arg block forward into kwargs form for diffusion blocks."""
@@ -95,7 +96,8 @@ class DiffusionCalibrator(LLMCalibrator):
def calib(self, nsamples: int, bs: int) -> None:
"""Drive the diffusion pipeline so block-forward hooks fire.
- Verbatim port of the legacy ``DiffusionMixin.calib``.
+ The pipeline asks its scheduler to build a native schedule with
+ ``calib_num_inference_steps`` denoising steps.
"""
from auto_round.compressors.diffusion.dataset import get_diffusion_dataloader
@@ -106,8 +108,8 @@ class DiffusionCalibrator(LLMCalibrator):
)
logger.warning(
- "Diffusion model will catch nsamples * num_inference_steps inputs, "
- "you can reduce nsamples or num_inference_steps if OOM or take too much time."
+ "Diffusion model will catch nsamples * calib_num_inference_steps inputs, "
+ "you can reduce nsamples or calib_num_inference_steps if OOM or take too much time."
)
requires_image = self._requires_calibration_image()
if isinstance(self.dataset, str):
@@ -141,7 +143,6 @@ class DiffusionCalibrator(LLMCalibrator):
low_gpu_mem_usage=self.low_gpu_mem_usage,
)
pipeline_fn = getattr(pipe, "_autoround_pipeline_fn", None)
-
with tqdm(range(1, total + 1), desc="cache block inputs") as pbar:
for batch in self.dataloader:
if len(batch) == 2:
@@ -155,45 +156,29 @@ class DiffusionCalibrator(LLMCalibrator):
)
if isinstance(prompts, tuple):
prompts = list(prompts)
- try:
- generator = (
- None
- if self.generator_seed is None
- else torch.Generator(device=pipe.device).manual_seed(self.generator_seed)
- )
- if requires_image:
- if image_inputs is None:
- raise ValueError(
- "I2V calibration requires images. Use the default coco2014 dataset or provide an "
- "'image' column in a local TSV."
- )
- image = self._load_calibration_images(image_inputs)
- pipe(
- image,
- prompt=prompts,
- guidance_scale=self.guidance_scale,
- num_inference_steps=self.num_inference_steps,
- generator=generator,
- )
- elif pipeline_fn is not None:
- pipeline_fn(
- pipe,
- prompts,
- guidance_scale=self.guidance_scale,
- num_inference_steps=self.num_inference_steps,
- generator=generator,
- )
- else:
- pipe(
- prompts,
- guidance_scale=self.guidance_scale,
- num_inference_steps=self.num_inference_steps,
- generator=generator,
+ generator = (
+ None
+ if self.generator_seed is None
+ else torch.Generator(device=pipe.device).manual_seed(self.generator_seed)
+ )
+ call_kwargs = dict(self.pipeline_call_kwargs)
+ call_kwargs.update(
+ guidance_scale=self.guidance_scale,
+ num_inference_steps=self.calib_num_inference_steps,
+ generator=generator,
+ )
+ if requires_image:
+ if image_inputs is None:
+ raise ValueError(
+ "I2V calibration requires images. Use the default coco2014 dataset or provide an "
+ "'image' column in a local TSV."
)
- except NotImplementedError:
- pass
- except Exception as error:
- raise error
+ image = self._load_calibration_images(image_inputs)
+ pipe(image, prompt=prompts, **call_kwargs)
+ elif pipeline_fn is not None:
+ pipeline_fn(pipe, prompts, **call_kwargs)
+ else:
+ pipe(prompts, **call_kwargs)
step = len(prompts)
total_cnt += step
pbar.update(step)
@@ -212,8 +197,8 @@ class DiffusionCalibrator(LLMCalibrator):
)
if total_cnt < self.batch_size:
raise ValueError(
- f"valid samples is less than batch_size({self.batch_size}),"
- " please adjust c.batch_size or seqlen."
+ f"valid sample count is less than batch_size ({self.batch_size}); "
+ "please reduce batch_size or provide more calibration samples."
)
max_len = (total_cnt // self.batch_size) * self.batch_size
for k, v in self.inputs.items():
diff --git a/auto_round/cli/main.py b/auto_round/cli/main.py
index 0c6be246b..75c76a278 100644
--- a/auto_round/cli/main.py
+++ b/auto_round/cli/main.py
@@ -97,6 +97,7 @@ def _build_entry_model_type_kwargs(args) -> dict:
"template": args.template,
"guidance_scale": args.guidance_scale,
"num_inference_steps": args.num_inference_steps,
+ "calib_num_inference_steps": args.calib_num_inference_steps,
"generator_seed": args.generator_seed,
}
diff --git a/auto_round/cli/parser.py b/auto_round/cli/parser.py
index def9707d7..dbab03181 100644
--- a/auto_round/cli/parser.py
+++ b/auto_round/cli/parser.py
@@ -284,7 +284,16 @@ def build_quantize_parser(*, prog: str = "auto_round quantize") -> argparse.Argu
)
diff.add_argument("--guidance_scale", default=7.5, type=float, help="Classifier-free guidance scale.")
diff.add_argument(
- "--num_inference_steps", default=50, type=int, help="Number of denoising steps for diffusion evaluation."
+ "--calib_num_inference_steps",
+ default=8,
+ type=int,
+ help="Number of denoising steps used to collect diffusion quantization calibration inputs.",
+ )
+ diff.add_argument(
+ "--num_inference_steps",
+ default=50,
+ type=int,
+ help="Number of denoising steps for diffusion generation/evaluation.",
)
diff.add_argument("--generator_seed", default=None, type=int, help="Random seed used for diffusion generation.")
diff --git a/auto_round/compressors/diffusion/README.md b/auto_round/compressors/diffusion/README.md
index d44cc467a..4d2dcc388 100644
--- a/auto_round/compressors/diffusion/README.md
+++ b/auto_round/compressors/diffusion/README.md
@@ -23,7 +23,7 @@ autoround = AutoRound(
"black-forest-labs/FLUX.1-dev",
scheme="MXFP8",
dataset="coco2014",
- num_inference_steps=10,
+ calib_num_inference_steps=8,
guidance_scale=7.5,
generator_seed=None,
batch_size=1,
@@ -36,7 +36,10 @@ autoround.quantize_and_save(output_dir, format="fake", inplace=True)
```
- `dataset`: the dataset for quantization training. Currently supports `coco2014` and user customized `.tsv` files.
-- `num_inference_steps`: the reference number of denoising steps.
+- `calib_num_inference_steps`: the number of inference steps requested when the scheduler builds its native
+ short calibration schedule. Higher-order schedulers may expand these into more internal timesteps.
+- `num_inference_steps`: the number of denoising steps used for diffusion generation/evaluation; it does not
+ control the calibration schedule.
- `guidance_scale`: controls how much the image generation process follows the text prompt.
- `generator_seed`: a seed that controls the initial noise from which an image is generated.
@@ -53,6 +56,7 @@ auto-round \
--format fake \
--batch_size 1 \
--dataset coco2014 \
+ --calib_num_inference_steps 8 \
--output_dir ./tmp_autoround
```
diff --git a/auto_round/compressors/diffusion/dataset.py b/auto_round/compressors/diffusion/dataset.py
index 33da29c3b..f30a4203f 100644
--- a/auto_round/compressors/diffusion/dataset.py
+++ b/auto_round/compressors/diffusion/dataset.py
@@ -275,6 +275,7 @@ def get_diffusion_dataloader(dataset="coco2014", bs=1, seed=42, nsamples=128, im
Returns:
DataLoader: The DataLoader for the calibrated datasets.
"""
+ requested_dataset = dataset
if dataset in COCO_URL:
logger.info(f"use dataset {dataset}, loading calibration data...")
dataframe = _load_coco_dataframe(dataset, nsamples, image_required)
@@ -292,6 +293,20 @@ def get_diffusion_dataloader(dataset="coco2014", bs=1, seed=42, nsamples=128, im
dataset = DIFFUSION_DATASET["local"](dataset, nsamples)
else:
raise ValueError("Only support coco2014/audiocaps dataset or loading local tsv/csv file now.")
+
+ if (
+ image_required
+ and isinstance(requested_dataset, str)
+ and requested_dataset not in COCO_URL
+ and getattr(dataset, "image_paths", None) is None
+ ):
+ logger.warning(
+ f"Dataset {requested_dataset!r} does not provide images required for I2V calibration; "
+ "falling back to coco2014."
+ )
+ dataframe = _load_coco_dataframe("coco2014", nsamples, image_required=True)
+ dataset = DIFFUSION_DATASET["local"]("coco2014", nsamples, dataframe=dataframe)
+
set_seed(seed)
dataloader_params = {"batch_size": bs, "shuffle": True}
diff --git a/auto_round/compressors/diffusion_mixin.py b/auto_round/compressors/diffusion_mixin.py
index 72cde7649..f5e542ef8 100644
--- a/auto_round/compressors/diffusion_mixin.py
+++ b/auto_round/compressors/diffusion_mixin.py
@@ -11,19 +11,16 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
-import inspect
import json
import os
from typing import Any, Optional, Union
import torch
-from tqdm import tqdm
from auto_round.logger import logger
from auto_round.utils import clear_memory
from auto_round.utils.device import (
dispatch_model_block_wise,
- dispatch_model_by_all_available_devices,
get_major_device,
)
from auto_round.utils.device_manager import device_manager, is_auto_device_mapping
@@ -44,7 +41,8 @@ class DiffusionMixin:
Diffusion-specific parameters:
guidance_scale: Control how much image generation follows text prompt
- num_inference_steps: Reference number of denoising steps
+ num_inference_steps: Number of denoising steps for diffusion generation or evaluation
+ calib_num_inference_steps: Number of denoising steps used to collect calibration inputs
generator_seed: Seed for initial noise generation
Design note:
@@ -59,12 +57,19 @@ class DiffusionMixin:
*args,
guidance_scale: float = 7.5,
num_inference_steps: int = 50,
+ calib_num_inference_steps: int = 8,
generator_seed: Optional[int] = None,
**kwargs,
) -> None:
+ if num_inference_steps < 1:
+ raise ValueError("num_inference_steps must be a positive integer.")
+ if calib_num_inference_steps < 1:
+ raise ValueError("calib_num_inference_steps must be a positive integer.")
+
# Store diffusion-specific attributes
self.guidance_scale = guidance_scale
self.num_inference_steps = num_inference_steps
+ self.calib_num_inference_steps = calib_num_inference_steps
self.generator_seed = generator_seed
self.pipeline_call_kwargs = dict(kwargs.pop("pipeline_call_kwargs", {}) or {})
@@ -147,9 +152,8 @@ class DiffusionMixin:
"""Select the diffusion calibration strategy.
``DiffusionCalibrator`` lives at
- :mod:`auto_round.calibration.diffusion` and owns what used to be
- ``DiffusionMixin.calib`` / ``_get_block_forward_func`` /
- ``_should_stop_cache_forward``.
+ :mod:`auto_round.calibration.diffusion` and owns diffusion-specific
+ calibration input collection.
"""
return "diffusion"
@@ -206,118 +210,6 @@ class DiffusionMixin:
target_device = get_major_device(device_map)
pipe.to(target_device)
- @torch.no_grad()
- def calib(self, nsamples: int, bs: int) -> None:
- """Perform diffusion-specific calibration for quantization.
-
- Override parent's calib method to use diffusion dataset loading logic.
- The diffusion pipeline is read from ``self.model_context.pipe``.
- """
- from auto_round.compressors.diffusion.dataset import get_diffusion_dataloader
-
- pipe = self.model_context.pipe
- if pipe is None:
- raise ValueError(
- "Diffusion pipeline not found in model_context. " "Ensure the model was loaded as a diffusion model."
- )
-
- logger.warning(
- "Diffusion model will catch nsamples * num_inference_steps inputs, "
- "you can reduce nsamples or num_inference_steps if OOM or take too much time."
- )
- if isinstance(self.dataset, str):
- dataset = self.dataset.replace(" ", "")
- self.dataloader, self.batch_size = get_diffusion_dataloader(
- dataset=dataset,
- bs=self.batch_size,
- seed=self.seed,
- nsamples=self.calibration_context.nsamples,
- )
- else:
- self.dataloader = self.dataset
- total_cnt = 0
-
- total = nsamples if not hasattr(self.dataloader, "len") else min(nsamples, len(self.dataloader))
-
- # NOTE: we intentionally skip the sequential offloading check here (the guard that
- # exits when pipe is already dispatched). In new-arch diffusion, the pipe may
- # already be dispatched to multi-device in a prior calib call. The dispatch
- # state is preserved across calls, so re-dispatching or moving is unnecessary and
- # would break the existing placement.
- if pipe.device != self.model.device:
- pipe.to(self.model.device)
- if (
- hasattr(self.model, "hf_device_map")
- and len(self.model.hf_device_map) > 1
- and torch.device(self.model.device).type in ["cuda", "xpu"]
- ):
- logger.warning(
- "Diffusion model is activated sequential model offloading. "
- "Pipe may already be dispatched from a prior calib call. "
- "Skipping re-dispatch to avoid breaking the existing placement."
- )
-
- device_map = getattr(self.compress_context, "device_map", None)
- device_list = getattr(self.compress_context, "device_list", [])
- # Skip dispatch for secondary transformers
- if (
- not getattr(self, "_inputs_cached", False)
- and device_map is not None
- and is_auto_device_mapping(device_map)
- and len(device_list) > 1
- ):
- pipe_transformer = getattr(pipe, "transformer", None)
- if self.model_context.model is not pipe_transformer:
- pass # secondary transformer — skip pipeline dispatch
- else:
- pipe = dispatch_model_by_all_available_devices(pipe, device_map)
-
- with tqdm(range(1, total + 1), desc="cache block inputs") as pbar:
- for ids, prompts in self.dataloader:
- if isinstance(prompts, tuple):
- prompts = list(prompts)
- pipe_kwargs = self._build_pipeline_call_kwargs(pipe, prompts)
- try:
- if self._requires_calibration_image() or "prompt" in pipe_kwargs:
- # I2V pipeline: 'image' is the first positional arg, so pass
- # 'prompt' as keyword to avoid "multiple values for argument 'image'".
- pipe(**pipe_kwargs)
- else:
- pipe(prompts, **pipe_kwargs)
- except NotImplementedError:
- pass
- except Exception as error:
- raise error
- step = len(prompts)
- total_cnt += step
- pbar.update(step)
- if total_cnt >= nsamples:
- break
- if total_cnt == 0:
- logger.error(
- f"no data has been cached, please provide more data with sequence length >={self.seqlen} in the "
- f"dataset or decease the sequence length"
- )
- exit(-1)
- elif total_cnt < nsamples:
- logger.warning(
- f"Insufficient number of samples collected may affect the quantization. "
- f"target samples count is {nsamples}, while valid samples count is {total_cnt}"
- )
- if total_cnt < self.batch_size:
- raise ValueError(
- f"valid samples is less than batch_size({self.batch_size}),"
- " please adjust self.batch_size or seqlen."
- )
- max_len = (total_cnt // self.batch_size) * self.batch_size
- for k, v in self.inputs.items():
- for key in v:
- if isinstance(v[key], list) and len(v[key]) == total_cnt:
- self.inputs[k][key] = v[key][:max_len]
-
- # torch.cuda.empty_cache()
-
- # TODO move to calibration wenhuach
def try_cache_inter_data_gpucpu(self, *args, **kwargs) -> Any:
"""Skip re-caching when DiffusionMixin.quantize has already populated self.inputs.
@@ -399,14 +291,14 @@ class DiffusionMixin:
# Dual-transformer path: quantize all transformers sequentially
logger.info("Detected multi-transformer diffusion pipeline, quantizing all transformers")
- # Ensure at least 2 inference steps so both transformers are exercised during calibration
- orig_steps = getattr(self, "num_inference_steps", None) or 50
+ # Ensure at least 2 calibration inference steps so both transformers are exercised.
+ orig_steps = getattr(self, "calib_num_inference_steps", None) or 8
if orig_steps < 2:
logger.warning(
- f"num_inference_steps={orig_steps} is too low for dual-transformer "
+ f"calib_num_inference_steps={orig_steps} is too low for dual-transformer "
f"quantization — increasing to 2 so all transformers receive calibration data."
)
- self.num_inference_steps = 2
+ self.calib_num_inference_steps = 2
# Disable low_cpu_mem_usage so quantized models stay in memory during multi-transformer
# quantization.
@@ -498,7 +390,7 @@ class DiffusionMixin:
self._quantized_transformers = quantized_extras
self.compress_context.low_cpu_mem_usage = orig_low_cpu
self.compress_context.is_immediate_saving = orig_immediate_saving
- self.num_inference_steps = orig_steps
+ self.calib_num_inference_steps = orig_steps
return self.model_context.model, self.layer_config
diff --git a/auto_round/compressors/orchestrator.py b/auto_round/compressors/orchestrator.py
index f1a4215f5..243492de4 100644
--- a/auto_round/compressors/orchestrator.py
+++ b/auto_round/compressors/orchestrator.py
@@ -100,9 +100,9 @@ class CompressionOrchestrator(BaseOrchestrator):
def post_init(self) -> None:
"""Run base post-init then attach the registered calibrator strategy.
- Subclasses (MLLM/Diffusion) override ``calib`` directly on the
- CompressionOrchestrator; the calibrator owns ``try_cache_inter_data_gpucpu`` /
- ``cache_inter_data`` orchestration plus the LLM ``calib`` body.
+ Model-type mixins select the calibrator kind; the calibrator owns
+ ``try_cache_inter_data_gpucpu`` / ``cache_inter_data`` orchestration
+ plus the model-specific ``calib`` body.
"""
if self._post_init_done:
return
diff --git a/docs/svdquant_details.md b/docs/svdquant_details.md
index f1cb6da05..404a49a49 100644
--- a/docs/svdquant_details.md
+++ b/docs/svdquant_details.md
@@ -119,8 +119,9 @@ Smooth search and additional residual iterations are opt-in:
```
For diffusion calibration, `--nsamples` controls prompts and
-`--num_inference_steps` controls denoising steps. Start small before running a
-full quality configuration.
+`--calib_num_inference_steps` controls the number of inference steps requested when the scheduler builds its
+native short calibration schedule. Higher-order schedulers may expand these into more internal timesteps.
+Start small before running a full quality configuration.
## Processing flow
diff --git a/docs/svdquant_details_CN.md b/docs/svdquant_details_CN.md
index ffd4c51e9..4f45f0e62 100644
--- a/docs/svdquant_details_CN.md
+++ b/docs/svdquant_details_CN.md
@@ -115,7 +115,9 @@ Smooth 搜索和更多 residual iterations 默认不开启,可按需添加:
```
Diffusion calibration 中,`--nsamples` 控制 prompt 数量,
-`--num_inference_steps` 控制去噪步数。建议先用小配置跑通端到端流程,再运行完整质量配置。
+`--calib_num_inference_steps` 控制 scheduler 构建原生短校准 schedule 时请求的推理步数;高阶
+scheduler 可能将其展开为更多内部 timestep。
+建议先用小配置跑通端到端流程,再运行完整质量配置。
## 处理流程
diff --git a/test/e2e/test_cpu/test_diffusion_quantize_e2e.py b/test/e2e/test_cpu/test_diffusion_quantize_e2e.py
index eef72b244..126cf3252 100644
--- a/test/e2e/test_cpu/test_diffusion_quantize_e2e.py
+++ b/test/e2e/test_cpu/test_diffusion_quantize_e2e.py
@@ -45,7 +45,7 @@ import torch
# Matrix
# ---------------------------------------------------------------------------
-# (hf_id, scheme, min_ram_gib, num_inference_steps, guidance_scale)
+# (hf_id, scheme, min_ram_gib, calib_num_inference_steps, guidance_scale)
DIFFUSION_CASES = [
# FLUX.1-dev - the canonical diffusion quant target.
(
@@ -107,7 +107,7 @@ def _require_ram(min_gib: int) -> None:
pytest.skip(f"only {avail:.1f} GiB free RAM, need {min_gib} GiB for this diffusion case")
-def _quantize_diffusion(model_id: str, scheme: str, output_dir: str, num_inference_steps: int) -> None:
+def _quantize_diffusion(model_id: str, scheme: str, output_dir: str, calib_num_inference_steps: int) -> None:
"""Quantize a diffusion model with ``auto-round`` and write to ``output_dir``."""
from test.helpers import get_model_path
@@ -122,7 +122,7 @@ def _quantize_diffusion(model_id: str, scheme: str, output_dir: str, num_inferen
scheme=scheme,
iters=0, # diffusion paths are typically RTN
disable_opt_rtn=(scheme not in ("W4A16",)),
- num_inference_steps=num_inference_steps,
+ calib_num_inference_steps=calib_num_inference_steps,
)
ar.quantize_and_save(output_dir)
@@ -181,7 +181,7 @@ class TestDiffusionQuantizeE2E:
# ---- 1. quantize + save ----
t0 = time.perf_counter()
- _quantize_diffusion(model_id, scheme, save_dir, num_inference_steps=num_steps)
+ _quantize_diffusion(model_id, scheme, save_dir, calib_num_inference_steps=num_steps)
quant_time = time.perf_counter() - t0
# Sanity: the saved pipeline must contain the expected files.
@@ -253,7 +253,7 @@ class TestDiffusionLoadOnly:
_require_ram(20)
save_dir = str(tmp_path / "diffusion_load_only")
- _quantize_diffusion(model_id, scheme, save_dir, num_inference_steps=2)
+ _quantize_diffusion(model_id, scheme, save_dir, calib_num_inference_steps=2)
from diffusers import AutoPipelineForText2Image
diff --git a/test/unit/common/calibration/test_diffusion.py b/test/unit/common/calibration/test_diffusion.py
index d42667708..3a6de3177 100644
--- a/test/unit/common/calibration/test_diffusion.py
+++ b/test/unit/common/calibration/test_diffusion.py
@@ -85,8 +85,10 @@ class TestDiffusionCalibrator:
low_gpu_mem_usage=False,
has_variable_block_shape=False,
guidance_scale=7.5,
- num_inference_steps=1,
+ calib_num_inference_steps=4,
+ num_inference_steps=20,
generator_seed=None,
+ pipeline_call_kwargs={},
pipe=pipe,
model=model,
model_context=SimpleNamespace(
@@ -239,6 +241,7 @@ class TestDiffusionCalibrator:
calibrator.dataset = [("id0", ["p1", "p2"])]
calibrator.pipe = FakePipeline(fn=lambda *args, **kwargs: None)
calibrator.pipe._autoround_pipeline_fn = pipeline_fn
+ calibrator.pipeline_call_kwargs = {"audio_end_in_s": 3.0}
calibrator._requires_calibration_image = lambda: False
with patch("auto_round.calibration.diffusion.tqdm", FakeTqdm):
@@ -247,9 +250,11 @@ class TestDiffusionCalibrator:
assert len(calls) == 1
assert calls[0][1] == ["p1", "p2"]
assert calls[0][2]["guidance_scale"] == pytest.approx(7.5)
+ assert calls[0][2]["num_inference_steps"] == 4
assert calls[0][2]["generator"] is None
+ assert calls[0][2]["audio_end_in_s"] == pytest.approx(3.0)
- def test_calib_falls_back_to_pipe_when_no_pipeline_fn(self, calibrator):
+ def test_calib_calls_pipe_with_calibration_kwargs(self, calibrator):
calls = []
def fake_pipe(prompts, **kwargs):
@@ -257,6 +262,7 @@ class TestDiffusionCalibrator:
calibrator.dataset = [("id0", ["p1", "p2"])]
calibrator.pipe = FakePipeline(fn=fake_pipe)
+ calibrator.pipeline_call_kwargs = {"height": 512, "width": 768, "num_inference_steps": 999}
calibrator._requires_calibration_image = lambda: False
with patch("auto_round.calibration.diffusion.tqdm", FakeTqdm):
@@ -264,6 +270,9 @@ class TestDiffusionCalibrator:
assert len(calls) == 1
assert calls[0][0] == ["p1", "p2"]
+ assert calls[0][1]["num_inference_steps"] == 4
+ assert calls[0][1]["height"] == 512
+ assert calls[0][1]["width"] == 768
def test_calib_passes_image_when_required(self, calibrator):
seen_images = []
@@ -277,7 +286,7 @@ class TestDiffusionCalibrator:
assert seen_images[0] is calibration_image
- def test_calib_not_implemented_error_is_swallowed(self, calibrator):
+ def test_calib_not_implemented_error_propagates(self, calibrator):
def failing_pipe(*args, **kwargs):
raise NotImplementedError("unsupported op")
@@ -286,9 +295,8 @@ class TestDiffusionCalibrator:
calibrator._requires_calibration_image = lambda: False
with patch("auto_round.calibration.diffusion.tqdm", FakeTqdm):
- calibrator.calib(nsamples=1, bs=1)
-
- assert calibrator.inputs == {}
+ with pytest.raises(NotImplementedError, match="unsupported op"):
+ calibrator.calib(nsamples=1, bs=1)
def test_calib_other_exceptions_propagate(self, calibrator):
def failing_pipe(*args, **kwargs):
@@ -350,5 +358,5 @@ class TestDiffusionCalibrator:
calibrator._requires_calibration_image = lambda: False
with patch("auto_round.calibration.diffusion.tqdm", FakeTqdm):
- with pytest.raises(ValueError, match="valid samples is less than batch_size"):
+ with pytest.raises(ValueError, match="valid sample count is less than batch_size"):
calibrator.calib(nsamples=3, bs=2)
diff --git a/test/unit/common/compressors/test_diffusion_mixin.py b/test/unit/common/compressors/test_diffusion_mixin.py
index eea0ec9bf..b0edac3e2 100644
--- a/test/unit/common/compressors/test_diffusion_mixin.py
+++ b/test/unit/common/compressors/test_diffusion_mixin.py
@@ -11,6 +11,7 @@ import inspect
from types import SimpleNamespace
from unittest.mock import MagicMock
+import pytest
import torch
from auto_round.compressors.diffusion_mixin import DiffusionMixin
@@ -25,8 +26,40 @@ class TestDiffusionMixinProperties:
params = {k: v.default for k, v in sig.parameters.items() if v.default is not inspect.Parameter.empty}
assert params.get("guidance_scale") == 7.5
assert params.get("num_inference_steps") == 50
+ assert params.get("calib_num_inference_steps") == 8
assert params.get("generator_seed") is None
+ def test_generation_and_calibration_steps_are_independent(self):
+ class Parent:
+ def __init__(self, *args, **kwargs):
+ self.model_context = SimpleNamespace(pipe=None, model=None)
+
+ class MockCompressor(DiffusionMixin, Parent):
+ pass
+
+ comp = MockCompressor(num_inference_steps=20, calib_num_inference_steps=7)
+
+ assert comp.num_inference_steps == 20
+ assert comp.calib_num_inference_steps == 7
+
+ @pytest.mark.parametrize(
+ ("kwargs", "match"),
+ [
+ ({"calib_num_inference_steps": 0}, "calib_num_inference_steps"),
+ ({"num_inference_steps": 0}, "num_inference_steps"),
+ ],
+ )
+ def test_rejects_non_positive_inference_steps(self, kwargs, match):
+ class Parent:
+ def __init__(self, *args, **kwargs):
+ self.model_context = SimpleNamespace(pipe=None, model=None)
+
+ class MockCompressor(DiffusionMixin, Parent):
+ pass
+
+ with pytest.raises(ValueError, match=match):
+ MockCompressor(**kwargs)
+
def test_get_calibrator_kind_returns_diffusion(self):
# Create a minimal mock class
class MockCompressor(DiffusionMixin):
diff --git a/test/unit/common/core/test_entry_normalization.py b/test/unit/common/core/test_entry_normalization.py
index 63d7acd61..350260a2e 100644
--- a/test/unit/common/core/test_entry_normalization.py
+++ b/test/unit/common/core/test_entry_normalization.py
@@ -18,13 +18,22 @@ def test_split_entry_kwargs_partitions_owned_fields():
processor = object()
grouped = _split_entry_kwargs(
- {"dataset": ["sample"], "scale_dtype": "fp32", "processor": processor, "model_free": False}
+ {
+ "dataset": ["sample"],
+ "scale_dtype": "fp32",
+ "processor": processor,
+ "model_free": False,
+ "num_inference_steps": 20,
+ "calib_num_inference_steps": 8,
+ }
)
assert grouped["base"]["dataset"] == ["sample"]
assert grouped["compressor"]["scale_dtype"] == "fp32"
assert grouped["mllm"]["processor"] is processor
assert grouped["route"]["model_free"] is False
+ assert grouped["diffusion"]["num_inference_steps"] == 20
+ assert grouped["diffusion"]["calib_num_inference_steps"] == 8
def test_split_entry_kwargs_ignores_unknown_fields(monkeypatch):
diff --git a/test/unit/common/models/test_audio_model.py b/test/unit/common/models/test_audio_model.py
index a70136963..19524d736 100644
--- a/test/unit/common/models/test_audio_model.py
+++ b/test/unit/common/models/test_audio_model.py
@@ -356,7 +356,7 @@ class TestStableAudioQuantization:
nsamples=1,
iters=0,
disable_opt_rtn=True,
- num_inference_steps=2,
+ calib_num_inference_steps=2,
device_map=device,
enable_torch_compile=True,
)
diff --git a/test/unit/common/utils/test_cli_usage.py b/test/unit/common/utils/test_cli_usage.py
index 3803c0dc4..fbc0f2935 100644
--- a/test/unit/common/utils/test_cli_usage.py
+++ b/test/unit/common/utils/test_cli_usage.py
@@ -218,6 +218,24 @@ class TestAutoRoundCmd:
assert args.layer_config == layer_cfg
+def test_diffusion_quantize_cli_keeps_inference_steps_separate():
+ from auto_round.cli.parser import build_quantize_parser
+
+ args = build_quantize_parser().parse_args(
+ [
+ "--model",
+ "dummy-model",
+ "--calib_num_inference_steps",
+ "6",
+ "--num_inference_steps",
+ "12",
+ ]
+ )
+
+ assert args.calib_num_inference_steps == 6
+ assert args.num_inference_steps == 12
+
+
def test_run_rtn_uses_zero_shot_recipe(monkeypatch):
from auto_round.cli import main as cli_main
diff --git a/test/unit/test_cpu/models/test_diffusion.py b/test/unit/test_cpu/models/test_diffusion.py
index e0fa62a3c..f27602ba5 100644
--- a/test/unit/test_cpu/models/test_diffusion.py
+++ b/test/unit/test_cpu/models/test_diffusion.py
@@ -149,7 +149,7 @@ def test_flux_saving(setup_flux):
tokenizer=None,
scheme="W4A16",
iters=0,
- num_inference_steps=2,
+ calib_num_inference_steps=2,
disable_opt_rtn=True,
)
autoround.quantize_and_save(output_dir)
@@ -166,7 +166,7 @@ def test_flux(setup_flux):
tokenizer=None,
scheme="MXFP4",
iters=0,
- num_inference_steps=2,
+ calib_num_inference_steps=2,
disable_opt_rtn=True, # We change the logic, for opt-rtn, we always do calibration which is slow on cpu
)
# skip model saving since it takes much time
@@ -181,7 +181,7 @@ def test_flux(setup_flux):
# tokenizer=None,
# scheme="NVFP4",
# iters=1,
-# num_inference_steps=2,
+# calib_num_inference_steps=2,
# nsamples=2,
# dataset="coco2014",
# )
diff --git a/test/unit/test_cuda/models/test_diffusion.py b/test/unit/test_cuda/models/test_diffusion.py
index 3ce230eba..5c402b3c8 100644
--- a/test/unit/test_cuda/models/test_diffusion.py
+++ b/test/unit/test_cuda/models/test_diffusion.py
@@ -43,7 +43,7 @@ class TestAutoRound:
scheme="MXFP4",
iters=0,
disable_opt_rtn=True,
- num_inference_steps=2,
+ calib_num_inference_steps=2,
dataset="coco2014",
)
# skip model saving since it takes much time
@@ -54,7 +54,7 @@ class TestAutoRound:
tiny_z_image_model_path,
iters=1,
nsamples=1,
- num_inference_steps=2,
+ calib_num_inference_steps=2,
dataset="coco2014",
)
# skip model saving since it takes much time
@@ -88,7 +88,7 @@ class TestAutoRound:
scheme="MXFP4",
iters=1,
nsamples=1,
- num_inference_steps=2,
+ calib_num_inference_steps=2,
layer_config=layer_config,
dataset="coco2014",
)
@@ -133,7 +133,7 @@ class TestAutoRound:
scheme="MXFP4",
iters=1,
nsamples=1,
- num_inference_steps=2,
+ calib_num_inference_steps=2,
layer_config=layer_config,
dataset="coco2014",
device_map="0,1",