PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度
fix: quantize all diffusion transformers in RTN routes (#2497)
Wang, Chang9645350f79b5
diff --git a/auto_round/compressors/diffusion_mixin.py b/auto_round/compressors/diffusion_mixin.pyindex 7716bf1eb..81065e9f1 100644--- a/auto_round/compressors/diffusion_mixin.py+++ b/auto_round/compressors/diffusion_mixin.py@@ -11,9 +11,11 @@# 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 copyimport jsonimport mathimport os+from dataclasses import replacefrom typing import Anyimport torch@@ -81,6 +83,9 @@ class DiffusionMixin:"diffusion_tuning_cache_size must be 'auto' or finite and non-negative (GiB).") from None+ self._diffusion_user_block_selector = copy.deepcopy(kwargs.get("to_quant_block_names"))+ self._diffusion_user_layer_config = copy.deepcopy(kwargs.get("layer_config"))+# Store diffusion-specific attributesself.guidance_scale = guidance_scaleself.num_inference_steps = num_inference_steps@@ -260,7 +265,7 @@ class DiffusionMixin:# Zero-shot (RTN) path: no calibration data neededif not self.need_calib:- return self._quantize_zero_shot()+ return self._quantize_all_transformers_zero_shot()# Get block names and call cache_inter_data to populate self.inputsif bool(self.quant_block_list):@@ -420,6 +425,73 @@ class DiffusionMixin:return self.model_context.model, self.layer_config+ def _quantize_all_transformers_zero_shot(self):+ """Quantize every transformer without running pipeline calibration."""+ from auto_round.utils import find_matching_blocks, get_block_names++ additional = self._find_additional_transformers()+ if not additional:+ return self._quantize_zero_shot()++ primary_model = self.model_context.model+ primary_blocks = self.quant_block_list+ primary_config = self.layer_config+ primary_quantized = self.model_context.quantized+ state_keys = (+ "compression_plan",+ "_format_resolution",+ "_alg_composer",+ "to_quant_block_names",+ "ignore_layers",+ "calibration",+ "_post_init_done",+ )+ primary_state = {key: getattr(self, key, None) for key in state_keys}+ context = self.compress_context+ original_flags = (context.low_cpu_mem_usage, context.is_immediate_packing, context.is_immediate_saving)+ context.low_cpu_mem_usage = False+ self._defer_multi_transformer_serialization()+ extras = {}+ plans = {}+ try:+ self._quantize_zero_shot()+ primary_quantized = True+ primary_config = dict(self.layer_config)+ primary_state["compression_plan"] = getattr(self, "compression_plan", None)+ for name, transformer in additional:+ logger.info(f"Quantizing {name} without calibration")+ self.model_context.model = transformer+ self.model_context.quantized = False+ self._post_init_done = False+ self.calibration = None+ self.to_quant_block_names = copy.deepcopy(self._diffusion_user_block_selector)+ self.quant_block_list = find_matching_blocks(+ transformer, get_block_names(transformer), self.to_quant_block_names+ )+ # Build the component's plan from user overrides, not the primary's expanded plan.+ self.layer_config = copy.deepcopy(self._diffusion_user_layer_config) or {}+ self.ignore_layers = primary_state["ignore_layers"]+ resolution = getattr(self, "_format_resolution", None)+ if resolution is not None:+ self._format_resolution = replace(resolution, quant_block_list=self.quant_block_list)+ self.post_init()+ self._defer_multi_transformer_serialization()+ self._quantize_zero_shot()+ extras[name] = (self.model_context.model, dict(self.layer_config))+ plans[name] = getattr(self, "compression_plan", None)+ setattr(self.model_context.pipe, name, self.model_context.model)+ finally:+ self.model_context.model = primary_model+ for key, value in primary_state.items():+ setattr(self, key, value)+ self.layer_config = primary_config+ self.quant_block_list = primary_blocks+ self.model_context.quantized = primary_quantized+ self._quantized_transformers = extras+ self._quantized_transformer_plans = plans+ context.low_cpu_mem_usage, context.is_immediate_packing, context.is_immediate_saving = original_flags+ return primary_model, self.layer_config+def save_quantized(self,output_dir: str | None = None,@@ -472,6 +544,13 @@ class DiffusionMixin:# Save secondary quantized transformersaved_model = self.model_context.modelsaved_lc = self.layer_config+ saved_plan = getattr(self, "compression_plan", None)+ saved_selector = self.to_quant_block_names+ component_plan = getattr(self, "_quantized_transformer_plans", {}).get(name)+ if component_plan is not None:+ self.compression_plan = component_plan+ # None lets serialization derive the selector from this component's plan.+ self.to_quant_block_names = copy.deepcopy(self._diffusion_user_block_selector)saved_immediate_saving = self.compress_context.is_immediate_savingself.model_context.model, self.layer_config = quantized_transformers[name]saved_subfolder = getattr(self.model_context.model, "_autoround_pipeline_subfolder", None)@@ -479,18 +558,22 @@ class DiffusionMixin:self.compress_context.is_immediate_saving = Falseif saved_subfolder is not None:delattr(self.model_context.model, "_autoround_pipeline_subfolder")- compressed_model = super().save_quantized(- output_dir=target_output_dir,- format=_format,- inplace=inplace,- return_folders=False,- **kwargs,- )- self.compress_context.is_immediate_saving = saved_immediate_saving- if saved_subfolder is not None:- self.model_context.model._autoround_pipeline_subfolder = saved_subfolder- self.model_context.model = saved_model- self.layer_config = saved_lc+ try:+ compressed_model = super().save_quantized(+ output_dir=target_output_dir,+ format=_format,+ inplace=inplace,+ return_folders=False,+ **kwargs,+ )+ finally:+ self.compress_context.is_immediate_saving = saved_immediate_saving+ if saved_subfolder is not None:+ self.model_context.model._autoround_pipeline_subfolder = saved_subfolder+ self.model_context.model = saved_model+ self.compression_plan = saved_plan+ self.to_quant_block_names = saved_selector+ self.layer_config = saved_lcelif val is self.model_context.model:# Save primary quantized transformersaved_immediate_saving = self.compress_context.is_immediate_savingdiff --git a/auto_round/compressors/model_free.py b/auto_round/compressors/model_free.pyindex c9dbdd5c8..0e834d52c 100644--- a/auto_round/compressors/model_free.py+++ b/auto_round/compressors/model_free.py@@ -319,6 +319,7 @@ def _prefetch_shard(work_dir: str,source_dir: str,streaming: bool,+ subfolder: str | None = None,) -> str | None:"""Return the local path of the next shard (download if needed)."""try:@@ -326,6 +327,18 @@ def _prefetch_shard(# Keep source shards in a dedicated cache directory to avoid# colliding with quantized output shard names in output_dir.shard_cache_dir = os.path.join(work_dir, ".cache", "model_free_source_shards")+ if subfolder:+ if os.path.isdir(model_name_or_path):+ model_name_or_path = os.path.join(model_name_or_path, subfolder)+ else:+ local_path = str(resolve_within_directory(shard_cache_dir, shard_name, origin="shard list"))+ if os.path.isfile(local_path):+ return local_path+ remote_name = subfolder + "/" + shard_name+ path = _download_single_shard(model_name_or_path, remote_name, shard_cache_dir)+ os.makedirs(os.path.dirname(local_path), exist_ok=True)+ shutil.move(path, local_path)+ return local_pathreturn _download_single_shard(model_name_or_path, shard_name, shard_cache_dir)path = str(resolve_within_directory(source_dir, shard_name, origin="shard list"))return path if os.path.exists(path) else None@@ -597,6 +610,8 @@ class _ModelFreeCompressorCore:self.is_streaming: bool = Falseself.is_diffusion_model: bool = Falseself.diffusion_root_dir: str = ""+ self.diffusion_component = "transformer"+ self._resolved_diffusion_source = Noneself.work_dir: str = ""self.source_dir: str = ""self.shard_names: list[str] = []@@ -723,6 +738,17 @@ class _ModelFreeCompressorCore:# -------------------------------------------------------------------def _resolve_source(self) -> None:+ if self._resolved_diffusion_source is not None:+ self.diffusion_root_dir, self.is_streaming = self._resolved_diffusion_source+ self.is_diffusion_model = True+ component_dir = os.path.join(self.diffusion_root_dir, self.diffusion_component)+ if self.is_streaming:+ self.work_dir = component_dir+ else:+ self.source_dir = component_dir+ self.config = _load_config(component_dir)+ self.source_quantization_config = copy.deepcopy(_find_quantization_config(self.config))+ returnos.makedirs(self.output_dir, exist_ok=True)cached, cache_reason = _get_model_cache_status(self.model_name_or_path)self.is_streaming = not cached@@ -737,7 +763,7 @@ class _ModelFreeCompressorCore:"(snapshot_download with weight ignore patterns), then fetch ""weight shards on demand (hf_hub_download).")- self.work_dir = self.output_dir+ self.work_dir = os.path.join(self.output_dir, ".cache", "model_free_metadata")_download_metadata_files(self.model_name_or_path, self.work_dir)transformer_work_dir = os.path.join(self.work_dir, "transformer")if (@@ -750,7 +776,7 @@ class _ModelFreeCompressorCore:self.work_dir = transformer_work_dirlogger.info("Detected diffusion model (no root config.json, found transformer/ subfolder). "- "Only the transformer component will be quantized; other sub-components are skipped."+ "All transformer components will be quantized; other sub-components are copied.")self.config = _load_config(self.work_dir)else:@@ -770,7 +796,7 @@ class _ModelFreeCompressorCore:self.source_dir = transformer_source_dirlogger.info("Detected diffusion model (no root config.json, found transformer/ subfolder). "- "Only the transformer component will be quantized; other sub-components are skipped."+ "All transformer components will be quantized; other sub-components are copied.")self.config = _load_config(self.source_dir)@@ -849,12 +875,20 @@ class _ModelFreeCompressorCore:def _discover_shards(self) -> None:search_dir = self.work_dir if self.is_streaming else self.source_dir- self.shard_names = _list_weight_shards(search_dir)- if self.is_streaming and not self.shard_names:+ # Source indices live in the isolated metadata cache; never infer streamed+ # source names from output shards, or include remote files outside the index.+ has_source_index = any(+ name.endswith((".safetensors.index.json", ".bin.index.json")) for name in os.listdir(search_dir)+ )+ self.shard_names = _list_weight_shards(search_dir) if not self.is_streaming or has_source_index else []+ if self.is_streaming and not has_source_index:from auto_round.utils.model_free_utils import _list_remote_weight_shards- subfolder = "transformer" if self.is_diffusion_model else None+ subfolder = self.diffusion_component if self.is_diffusion_model else Noneself.shard_names = _list_remote_weight_shards(self.model_name_or_path, subfolder=subfolder)+ if subfolder:+ prefix = subfolder + "/"+ self.shard_names = [name.removeprefix(prefix) for name in self.shard_names]if not self.shard_names:raise FileNotFoundError(f"No safetensors or PyTorch weight files found for {self.model_name_or_path}")@@ -1012,12 +1046,12 @@ class _ModelFreeCompressorCore:def _quant_output_dir(self) -> str:"""Effective output directory for quantized weight shards and config.- For diffusion models the quantized transformer component is written- to ``<output_dir>/transformer/``; for all other models the top-level+ For diffusion models each quantized transformer component is written+ to its own subdirectory; for all other models the top-level``output_dir`` is used directly."""if self.is_diffusion_model:- return os.path.join(self.output_dir, "transformer")+ return os.path.join(self.output_dir, self.diffusion_component)return self.output_dir# -------------------------------------------------------------------@@ -1026,7 +1060,7 @@ class _ModelFreeCompressorCore:@propertydef _resume_manifest_path(self) -> str:- return os.path.join(self.output_dir, ".cache", _RESUME_MANIFEST_NAME)+ return os.path.join(self._quant_output_dir, ".cache", _RESUME_MANIFEST_NAME)def _build_resume_parameters(self) -> dict:"""Return the effective command inputs that determine shard output."""@@ -1385,6 +1419,7 @@ class _ModelFreeCompressorCore:self.work_dir,self.source_dir,self.is_streaming,+ self.diffusion_component if self.is_diffusion_model else None,)download_futures[future] = (shard_idx, shard_name)next_download_idx += 1@@ -1448,6 +1483,7 @@ class _ModelFreeCompressorCore:quant_output_dir=self._quant_output_dir,total_shards=total_shards,enable_torch_compile=self.enable_torch_compile,+ disable_opt_rtn=self.disable_opt_rtn,# Keep donor shards alive for recipient hydration.cleanup_source_shard=not is_donor,donor_tensors_to_exclude=donor_tensors,@@ -1544,12 +1580,37 @@ class _ModelFreeCompressorCore:with open(os.path.join(self._quant_output_dir, "quantization_config.json"), "w") as f:json.dump(quantization_config, f, indent=2)- def _copy_metadata_files(self) -> None:- if self.is_streaming:- # Metadata was downloaded directly to output_dir (or output_dir/transformer/- # for diffusion models) — nothing to copy or clean up.+ def _quantize_additional_transformers(self) -> None:+ """Run a separate shard pipeline for each additional transformer."""+ if not self.is_diffusion_model or self.diffusion_component != "transformer":return+ for name in sorted(os.listdir(self.diffusion_root_dir)):+ if name == "transformer" or not name.startswith("transformer"):+ continue+ if not os.path.isfile(os.path.join(self.diffusion_root_dir, name, "config.json")):+ continue+ logger.info(f"Model-free quantization of {name}")+ component = _ModelFreeCompressorCore(+ model_name_or_path=self.model_name_or_path,+ output_dir=self.output_dir,+ scheme=copy.deepcopy(self.scheme_input),+ layer_config=copy.deepcopy(self.layer_config_input),+ ignore_layers=self.ignore_layers_input,+ format=self.format,+ device=self.device,+ quant_lm_head=self.quant_lm_head,+ quant_nontext_module=self.quant_nontext_module,+ enable_torch_compile=self.enable_torch_compile,+ disable_opt_rtn=self.disable_opt_rtn,+ )+ component.user_scheme_overrides = copy.deepcopy(getattr(self, "user_scheme_overrides", {}))+ component.diffusion_component = name+ component._resolved_diffusion_source = (self.diffusion_root_dir, self.is_streaming)+ component.run()+ def _copy_metadata_files(self) -> None:+ if self.diffusion_component != "transformer":+ returnif self.is_diffusion_model:# For diffusion models, copy root-level metadata files and# sub-component directories (vae, scheduler, tokenizer, …) to@@ -1569,10 +1630,11 @@ class _ModelFreeCompressorCore:shutil.copy2(src, dst)return- for fname in os.listdir(self.source_dir):+ metadata_dir = self.work_dir if self.is_streaming else self.source_dir+ for fname in os.listdir(metadata_dir):if _is_weight_shard(fname) or _is_stale_quantization_metadata(fname):continue- src = os.path.join(self.source_dir, fname)+ src = os.path.join(metadata_dir, fname)dst = os.path.join(self.output_dir, fname)if os.path.isdir(src):if not os.path.exists(dst):@@ -1710,6 +1772,7 @@ class _ModelFreeCompressorCore:# ---- write outputs ----self._write_index()self._write_config_files()+ self._quantize_additional_transformers()self._copy_metadata_files()self._clear_resume_state()self._cleanup_streaming_shard_cache()diff --git a/test/unit/common/compressors/test_diffusion_mixin.py b/test/unit/common/compressors/test_diffusion_mixin.pyindex c16fb7a05..d6fccae38 100644--- a/test/unit/common/compressors/test_diffusion_mixin.py+++ b/test/unit/common/compressors/test_diffusion_mixin.py@@ -167,3 +167,190 @@ class TestAlignDeviceAndDtype:comp = MockCompressor()# Should not raisecomp._align_device_and_dtype_for_secondary("transformer")++[email protected]("fail_secondary", [False, True])+def test_zero_shot_quantizes_secondary_and_restores_primary(monkeypatch, fail_secondary):+ primary = torch.nn.Linear(4, 4)+ secondary = torch.nn.Linear(4, 4)+ calls = []++ class Compressor(DiffusionMixin):+ def __init__(self):+ self.model_context = SimpleNamespace(+ model=primary,+ quantized=False,+ pipe=SimpleNamespace(+ components=["transformer", "transformer_2"], transformer=primary, transformer_2=secondary+ ),+ )+ self.compress_context = SimpleNamespace(+ low_cpu_mem_usage=True, is_immediate_packing=True, is_immediate_saving=True+ )+ self.layer_config = {"primary": {}}+ self.quant_block_list = [["primary"]]+ self._diffusion_user_block_selector = None+ self._diffusion_user_layer_config = None+ self.compression_plan = SimpleNamespace(regex_config={"primary": {}}, has_qlayer_outside_block=False)+ self.to_quant_block_names = "primary"++ def post_init(self):+ assert self.quant_block_list == [["secondary"]]+ assert self.to_quant_block_names is None+ self.compression_plan = SimpleNamespace(regex_config={"secondary": {}}, has_qlayer_outside_block=True)+ self.layer_config = {"secondary": {}}+ self.compress_context.is_immediate_packing = True+ self.compress_context.is_immediate_saving = True++ def _quantize_zero_shot(self):+ assert not self.compress_context.is_immediate_packing+ assert not self.compress_context.is_immediate_saving+ calls.append(self.model_context.model)+ if fail_secondary and self.model_context.model is secondary:+ raise RuntimeError("secondary failed")++ monkeypatch.setattr("auto_round.utils.get_block_names", lambda _: [["secondary"]])+ monkeypatch.setattr("auto_round.utils.find_matching_blocks", lambda model, blocks, pattern: blocks)+ comp = Compressor()+ if fail_secondary:+ with pytest.raises(RuntimeError, match="secondary failed"):+ comp._quantize_all_transformers_zero_shot()+ else:+ comp._quantize_all_transformers_zero_shot()+ assert comp._quantized_transformers == {"transformer_2": (secondary, {"secondary": {}})}+ assert calls == [primary, secondary]+ assert comp.model_context.model is primary+ assert comp.model_context.quantized+ assert comp.compression_plan.regex_config == {"primary": {}}+ assert not comp.compression_plan.has_qlayer_outside_block+ assert comp.to_quant_block_names == "primary"+ assert comp.layer_config == {"primary": {}}+ assert comp.quant_block_list == [["primary"]]+ assert comp.compress_context.low_cpu_mem_usage+ assert comp.compress_context.is_immediate_packing+ assert comp.compress_context.is_immediate_saving++[email protected]("selector", [None, r"\.1$"])+def test_zero_shot_resolves_component_plan_before_initialization(monkeypatch, selector):+ from auto_round.compressors.base import BaseOrchestrator+ from auto_round.compressors.config_resolution.contracts import (+ FormatResolution,+ ResolvedQuantizationConfig,+ ResolvedScheme,+ )+ from auto_round.schemes import QuantizationScheme++ primary, secondary = torch.nn.Linear(4, 4), torch.nn.Linear(4, 4)+ scheme = ResolvedScheme.from_scheme(QuantizationScheme(bits=8))+ primary_blocks = [["blocks.0", "blocks.1"]] if selector is None else [["blocks.1"]]+ secondary_blocks = [["layers.0", "layers.1", "layers.2"]] if selector is None else [["layers.1"]]+ primary_plan = ResolvedQuantizationConfig(+ scheme=scheme,+ formats=(),+ layer_config={"primary": {"bits": 8}},+ regex_config={"primary": {"bits": 8}},+ quant_block_list=primary_blocks,+ )+ secondary_plan = ResolvedQuantizationConfig(+ scheme=scheme,+ formats=(),+ layer_config={"secondary": {"bits": 8}},+ regex_config={"secondary": {"bits": 8}},+ quant_block_list=secondary_blocks,+ has_qlayer_outside_block=True,+ )++ class Compressor(DiffusionMixin, BaseOrchestrator):+ def __init__(self):+ self.model_context = SimpleNamespace(+ model=primary,+ quantized=False,+ pipe=SimpleNamespace(+ components=["transformer", "transformer_2"], transformer=primary, transformer_2=secondary+ ),+ )+ self.compress_context = SimpleNamespace(+ low_cpu_mem_usage=False, is_immediate_packing=False, is_immediate_saving=False+ )+ self.compression_plan = primary_plan+ self._format_resolution = FormatResolution(formats=(), scheme=scheme, quant_block_list=primary_blocks)+ self._diffusion_user_block_selector = selector+ self._diffusion_user_layer_config = None+ self.to_quant_block_names = selector or "blocks"+ self._alg_composer = object()++ def post_init(self):+ assert self.quant_block_list == secondary_blocks+ assert self._format_resolution.quant_block_list == tuple(tuple(group) for group in secondary_blocks)+ self.compression_plan = secondary_plan+ self._alg_composer = object()++ def _quantize_zero_shot(self):+ self.model_context.quantized = True++ monkeypatch.setattr("auto_round.utils.get_block_names", lambda model: [["layers.0", "layers.1", "layers.2"]])+ comp = Compressor()+ primary_composer = comp._alg_composer+ comp._quantize_all_transformers_zero_shot()+ assert comp.compression_plan == primary_plan+ assert comp._alg_composer is primary_composer+ assert comp._quantized_transformer_plans["transformer_2"] == secondary_plan++[email protected]("fail_save", [False, True])[email protected]("selector", [None, r"\.1$"])+def test_secondary_export_selects_and_restores_full_plan(tmp_path, monkeypatch, fail_save, selector):+ from auto_round.compressors.base import BaseOrchestrator+ from auto_round.utils import extract_block_names_to_str++ primary, secondary = torch.nn.Linear(4, 4), torch.nn.Linear(4, 4)+ primary_plan = SimpleNamespace(quant_block_list=(("blocks.0", "blocks.1"),))+ secondary_plan = SimpleNamespace(quant_block_list=(("layers.0", "layers.1"),))+ calls = []++ class Parent:+ def save_quantized(self, **kwargs):+ exported_selector = self.to_quant_block_names+ if exported_selector is None:+ exported_selector = extract_block_names_to_str(self.quant_block_list)+ calls.append((self.model_context.model, self.compression_plan, exported_selector))+ assert exported_selector == (selector or ("blocks" if self.model_context.model is primary else "layers"))+ if self.model_context.model is secondary and fail_save:+ raise RuntimeError("export failed")+ return self.model_context.model++ class Compressor(DiffusionMixin, Parent):+ quant_block_list = BaseOrchestrator.quant_block_list++ def __init__(self):+ self._diffusion_user_block_selector = selector+ self.to_quant_block_names = selector or "blocks"+ self.model_context = SimpleNamespace(+ model=primary,+ pipe=SimpleNamespace(+ components={"transformer": primary, "transformer_2": secondary},+ transformer=primary,+ transformer_2=secondary,+ save_config=lambda path: None,+ ),+ )+ self.compress_context = SimpleNamespace(is_immediate_saving=True)+ self.compression_plan = primary_plan+ self.layer_config = {"primary": {}}+ self._quantized_transformers = {"transformer_2": (secondary, {"secondary": {}})}+ self._quantized_transformer_plans = {"transformer_2": secondary_plan}++ monkeypatch.setattr("auto_round.compressors.diffusion_mixin.rename_weights_files", lambda path: None)+ comp = Compressor()+ if fail_save:+ with pytest.raises(RuntimeError, match="export failed"):+ comp.save_quantized(str(tmp_path), format=[])+ else:+ comp.save_quantized(str(tmp_path), format=[])+ assert calls == [(primary, primary_plan, selector or "blocks"), (secondary, secondary_plan, selector or "layers")]+ assert comp.to_quant_block_names == (selector or "blocks")+ assert comp.model_context.model is primary+ assert comp.compression_plan is primary_plan+ assert comp.layer_config == {"primary": {}}+ assert comp.compress_context.is_immediate_savingdiff --git a/test/unit/test_cpu/quantization/test_model_free.py b/test/unit/test_cpu/quantization/test_model_free.pyindex b9c9238fe..debd20bb3 100644--- a/test/unit/test_cpu/quantization/test_model_free.py+++ b/test/unit/test_cpu/quantization/test_model_free.py@@ -2006,3 +2006,238 @@ class TestMXFPAutoRoundFormat:assert extra["lm_head"]["data_type"] == "mx_fp"keys = _read_output_keys(output_dir)assert "lm_head.weight_packed" in keys++[email protected]("streaming", [False, True])+def test_diffusion_quantizes_both_transformers(tmp_path, monkeypatch, streaming):+ import shutil++ import auto_round.compressors.model_free as module++ root = _make_diffusion_model_dir(tmp_path, _TRANSFORMER_CONFIG, _TRANSFORMER_TENSORS)+ shutil.copytree(os.path.join(root, "transformer"), os.path.join(root, "transformer_2"))+ secondary_tensors = {key: -tensor * 2 for key, tensor in _TRANSFORMER_TENSORS.items()}+ save_file(secondary_tensors, os.path.join(root, "transformer_2", "model.safetensors"))+ output = tmp_path / "output"+ if streaming:+ monkeypatch.setattr(module, "_get_model_cache_status", lambda _: (False, "test"))+ monkeypatch.setattr(+ "auto_round.utils.model_free_utils._list_remote_weight_shards",+ lambda model, subfolder=None: [f"{subfolder}/model.safetensors"],+ )+ core = _ModelFreeCompressorCore(+ model_name_or_path=root,+ output_dir=str(output),+ scheme="MXFP8",+ device="cpu",+ enable_torch_compile=False,+ disable_opt_rtn=True,+ )+ core.run()+ component_weights = {}+ for name in ("transformer", "transformer_2"):+ config = json.loads((output / name / "config.json").read_text())+ assert config["quantization_config"]["bits"] == 8+ tensors = {}+ for shard in (output / name).glob("*.safetensors"):+ with safe_open(shard, framework="pt") as f:+ tensors.update({key: f.get_tensor(key) for key in f.keys()})+ for key in _TRANSFORMER_TENSORS:+ if key.endswith(".weight"):+ assert tensors[key].dtype == torch.float8_e4m3fn+ assert tensors[key.replace(".weight", ".weight_scale")].dtype == torch.uint8+ from auto_round.utils.model_free_utils import _process_shard++ expected, _, _ = _process_shard(+ os.path.join(root, name, "model.safetensors"),+ default_scheme=core.default_scheme,+ layer_config={},+ device="cpu",+ model_type="flux",+ disable_opt_rtn=True,+ )+ for key in expected:+ # float8 equality is not implemented on every torch backend.+ assert torch.equal(tensors[key].view(torch.uint8), expected[key].view(torch.uint8))+ for key in _TRANSFORMER_TENSORS:+ component_weights[name, key] = tensors[key].view(torch.uint8)+ assert any(+ not torch.equal(component_weights["transformer", key], component_weights["transformer_2", key])+ for key in _TRANSFORMER_TENSORS+ )+ assert (output / "vae" / "config.json").exists()+ assert not (output / "transformer" / ".cache" / "model_free_resume.json").exists()++[email protected]("component", ["transformer", "transformer_2"])+def test_streaming_download_uses_transformer_subfolder(tmp_path, monkeypatch, component):+ import auto_round.compressors.model_free as module++ downloads = []++ def download(repo, filename, cache_dir):+ downloads.append((repo, filename))+ path = tmp_path / "download" / filename+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes(b"weights")+ return str(path)++ monkeypatch.setattr(module, "_download_single_shard", download)+ path = module._prefetch_shard("org/wan", "model.safetensors", str(tmp_path), "", True, component)+ assert downloads == [("org/wan", f"{component}/model.safetensors")]+ assert path == str(tmp_path / ".cache" / "model_free_source_shards" / "model.safetensors")+ assert os.path.isfile(path)++[email protected]("component", ["transformer", "transformer_2"])+def test_streaming_discovery_ignores_partial_quantized_output(tmp_path, monkeypatch, component):+ output = tmp_path / component+ output.mkdir()+ save_file({"layer.weight": torch.randn(32, 32)}, output / "model-00001-of-00002.safetensors")+ core = _ModelFreeCompressorCore("org/wan", str(tmp_path), enable_torch_compile=False)+ core.is_streaming = True+ core.is_diffusion_model = True+ core.diffusion_component = component+ core.work_dir = str(output)+ calls = []++ def remote(model, subfolder=None):+ calls.append(subfolder)+ return [f"{component}/original-a.safetensors", f"{component}/original-b.safetensors"]++ monkeypatch.setattr("auto_round.utils.model_free_utils._list_remote_weight_shards", remote)+ core._discover_shards()+ assert calls == [component]+ assert core.shard_names == ["original-a.safetensors", "original-b.safetensors"]+++def test_streaming_secondary_resume_uses_original_sources(tmp_path, monkeypatch):+ from types import SimpleNamespace++ import auto_round.compressors.model_free as module++ root = _make_diffusion_model_dir(tmp_path, _TRANSFORMER_CONFIG, _TRANSFORMER_TENSORS)+ import shutil++ shutil.copytree(os.path.join(root, "transformer"), os.path.join(root, "transformer_2"))+ source = {}+ for component in ("transformer", "transformer_2"):+ for index, (key, tensor) in enumerate(list(_TRANSFORMER_TENSORS.items())[:2]):+ path = tmp_path / f"{component}-source-{index}.safetensors"+ save_file({key: tensor if component == "transformer" else -tensor}, path)+ source[component, f"source-{index}.safetensors"] = str(path)++ monkeypatch.setattr(module, "_get_model_cache_status", lambda _: (False, "test"))+ monkeypatch.setattr(+ "huggingface_hub.HfApi.model_info", lambda *args, **kwargs: SimpleNamespace(sha="fixed-revision")+ )+ original_metadata = module._download_metadata_files+ monkeypatch.setattr(module, "_download_metadata_files", lambda model, directory: original_metadata(root, directory))+ monkeypatch.setattr(+ "auto_round.utils.model_free_utils._list_remote_weight_shards",+ lambda model, subfolder=None: [f"{subfolder}/source-{index}.safetensors" for index in range(2)],+ )+ processed = []+ interrupted = [False]++ def process_shards(core):+ for index, name in enumerate(core.shard_names):+ if name in core._resume_processed_shards:+ continue+ if core.diffusion_component == "transformer_2" and index == 1 and not interrupted[0]:+ interrupted[0] = True+ raise RuntimeError("interrupted secondary")+ tensors, quantized, ignored = _process_shard(+ source[core.diffusion_component, name],+ default_scheme=core.default_scheme,+ disable_opt_rtn=core.disable_opt_rtn,+ model_type="flux",+ )+ output_name = f"model-{index + 1:05d}-of-00002.safetensors"+ os.makedirs(core._quant_output_dir, exist_ok=True)+ save_file(tensors, os.path.join(core._quant_output_dir, output_name))+ core.output_weight_map.update({key: output_name for key in tensors})+ core.all_quantized_layers.extend(quantized)+ core._mark_shard_completed(name, output_name, list(tensors), quantized, ignored)+ processed.append((core.diffusion_component, name))++ monkeypatch.setattr(module._ModelFreeCompressorCore, "_process_all_shards", process_shards)+ output = tmp_path / "output"++ def compressor():+ return _ModelFreeCompressorCore(+ "org/wan", str(output), scheme="MXFP8", enable_torch_compile=False, disable_opt_rtn=True+ )++ with pytest.raises(RuntimeError, match="interrupted secondary"):+ compressor().run()+ assert processed == [+ ("transformer", "source-0.safetensors"),+ ("transformer", "source-1.safetensors"),+ ("transformer_2", "source-0.safetensors"),+ ]+ processed.clear()+ compressor().run()+ assert processed == [("transformer_2", "source-1.safetensors")]+ for component in ("transformer", "transformer_2"):+ config = json.loads((output / component / "config.json").read_text())+ assert config["quantization_config"]["bits"] == 8+ assert not (output / component / ".cache" / "model_free_resume.json").exists()+++def test_streaming_worker_receives_disable_opt_rtn(tmp_path, monkeypatch):+ from concurrent.futures import ThreadPoolExecutor++ import auto_round.compressors.model_free as module++ shard = tmp_path / "source.safetensors"+ save_file({"layer.weight": torch.randn(32, 32)}, shard)+ core = _ModelFreeCompressorCore("org/wan", str(tmp_path), enable_torch_compile=False, disable_opt_rtn=True)+ core.is_streaming = True+ core.is_diffusion_model = True+ core.diffusion_component = "transformer_2"+ core.work_dir = str(tmp_path)+ core.shard_names = ["source.safetensors"]+ received = []+ monkeypatch.setattr(+ module, "ProcessPoolExecutor", lambda max_workers, **kwargs: ThreadPoolExecutor(max_workers=max_workers)+ )+ monkeypatch.setattr(module, "_prefetch_shard", lambda *args: str(shard))+ monkeypatch.setattr(+ module, "_quantize_local_shard_task", lambda *args, **kwargs: received.append(kwargs["disable_opt_rtn"])+ )+ monkeypatch.setattr(core, "_merge_shard_task_result", lambda result: None)+ core._process_all_shards_streaming_pipeline()+ assert received == [True]++[email protected]("component", ["transformer", "transformer_2"])+ "index_name",+ ["model.safetensors.index.json", "diffusion_pytorch_model.safetensors.index.json", "pytorch_model.bin.index.json"],+)+def test_streaming_discovery_prefers_source_index(tmp_path, monkeypatch, component, index_name):+ from unittest.mock import Mock++ metadata = tmp_path / "metadata" / component+ metadata.mkdir(parents=True)+ suffix = ".bin" if index_name.endswith(".bin.index.json") else ".safetensors"+ shards = [f"source-b{suffix}", f"source-a{suffix}"]+ index = {"weight_map": {"blocks.1.weight": shards[0], "blocks.0.weight": shards[1], "blocks.1.bias": shards[0]}}+ (metadata / index_name).write_text(json.dumps(index))+ output = tmp_path / "output"+ component_output = output / component+ component_output.mkdir(parents=True)+ (component_output / "model.safetensors.index.json").write_text(+ json.dumps({"weight_map": {"blocks.0.weight": "partial-output.safetensors"}})+ )+ core = _ModelFreeCompressorCore("org/wan", str(output), enable_torch_compile=False)+ core.is_streaming = True+ core.is_diffusion_model = True+ core.diffusion_component = component+ core.work_dir = str(metadata)+ remote = Mock(return_value=[f"{component}/{name}" for name in shards] + [f"{component}/backup{suffix}"])+ monkeypatch.setattr("auto_round.utils.model_free_utils._list_remote_weight_shards", remote)+ core._discover_shards()+ assert core.shard_names == shards+ remote.assert_not_called()