PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度
feat: implement resume functionality for model-free compression (#2330)
Xin He9e2650f45cb7
diff --git a/auto_round/compressors/model_free.py b/auto_round/compressors/model_free.pyindex ece7cd102..e28829530 100644--- a/auto_round/compressors/model_free.py+++ b/auto_round/compressors/model_free.py@@ -100,17 +100,20 @@ Usage (API)from __future__ import annotationsimport copy+import hashlibimport jsonimport multiprocessing as mpimport osimport reimport shutil+import tempfileimport timefrom concurrent.futures import FIRST_COMPLETED, ProcessPoolExecutor, ThreadPoolExecutor, as_completed, waitfrom dataclasses import asdict, fieldsfrom typing import Any, Optional, Unionimport torch+from safetensors import safe_openfrom auto_round import envsfrom auto_round.compressors.config_resolution import thaw_mapping@@ -198,6 +201,24 @@ _QUANTIZATION_CONFIG_FILENAMES: tuple[str, ...] = ("quant_config.json",)+_RESUME_MANIFEST_NAME = "model_free_resume.json"+++def _atomic_write_json(path: str, data: dict) -> None:+ """Write JSON without leaving a partially-written resume manifest."""+ os.makedirs(os.path.dirname(path), exist_ok=True)+ fd, tmp_path = tempfile.mkstemp(dir=os.path.dirname(path), prefix=".tmp_model_free_resume_")+ try:+ with os.fdopen(fd, "w") as f:+ json.dump(data, f, indent=2, sort_keys=True)+ os.replace(tmp_path, path)+ except Exception:+ try:+ os.remove(tmp_path)+ except OSError:+ pass+ raise+def _find_quantization_config(config: Any) -> dict:"""Return the first quantization_config found in a nested model config."""@@ -595,6 +616,8 @@ class _ModelFreeCompressorCore:self._donor_remaining_recipients: dict[str, int] = {}self._donor_self_consumed: dict[str, bool] = {}self._donor_shard_paths: dict[str, str] = {}+ self._resume_parameters: dict = {}+ self._resume_processed_shards: dict[str, dict] = {}# -------------------------------------------------------------------# Validation / parsing@@ -985,6 +1008,180 @@ class _ModelFreeCompressorCore:# Shard processing pipeline# -------------------------------------------------------------------+ @property+ def _resume_manifest_path(self) -> str:+ return os.path.join(self.output_dir, ".cache", _RESUME_MANIFEST_NAME)++ def _build_resume_parameters(self) -> dict:+ """Return the effective command inputs that determine shard output."""+ source_dir = self.work_dir if self.is_streaming else self.source_dir+ index_files = sorted(+ filename+ for filename in os.listdir(source_dir)+ if filename.endswith((".safetensors.index.json", ".bin.index.json"))+ )+ source_index = []+ for filename in index_files:+ with open(os.path.join(source_dir, filename), "rb") as index_file:+ source_index.append({"name": filename, "sha256": hashlib.file_digest(index_file, "sha256").hexdigest()})+ source_revision = None+ if not os.path.isdir(self.model_name_or_path):+ try:+ from huggingface_hub import HfApi++ source_revision = HfApi().model_info(self.model_name_or_path).sha+ except Exception as exc:+ logger.warning(f"Could not verify Hugging Face source revision; resume will not reuse output: {exc}")++ parameters = {+ "model_name_or_path": (+ os.path.realpath(self.model_name_or_path)+ if os.path.isdir(self.model_name_or_path)+ else self.model_name_or_path+ ),+ # Shard names and index content remain stable when a streaming+ # Hugging Face source becomes fully cached between retries.+ "source_shards": self.shard_names,+ "source_index": source_index,+ "source_revision": source_revision,+ "default_scheme": self.default_scheme,+ "layer_config": self.layer_config,+ "ignore_patterns": self.ignore_patterns,+ "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,+ "model_type": self.model_type,+ "source_quantization_config": self.source_quantization_config,+ }+ return json.loads(json.dumps(parameters, sort_keys=True, default=str))++ def _resume_record_is_valid(self, record: Any) -> bool:+ """Check that a completed shard is present, readable, and unchanged."""+ if not isinstance(record, dict):+ return False+ out_shard_name = record.get("output_file")+ tensor_names = record.get("tensor_names")+ if not isinstance(out_shard_name, str) or not isinstance(tensor_names, list):+ return False+ shard_path = os.path.join(self._quant_output_dir, out_shard_name)+ if not os.path.exists(shard_path) and len(self.shard_names) == 1:+ shard_path = os.path.join(self._quant_output_dir, "model.safetensors")+ try:+ with safe_open(shard_path, framework="pt") as shard:+ return set(shard.keys()) == set(tensor_names)+ except Exception:+ return False++ def _write_resume_manifest(self) -> None:+ processed = self._resume_processed_shards+ pending = [name for name in self.shard_names if name not in processed]+ _atomic_write_json(+ self._resume_manifest_path,+ {+ "version": 1,+ "parameters": self._resume_parameters,+ "pending_files": pending,+ "processed_files": processed,+ },+ )++ def _prepare_resume_state(self) -> None:+ """Load only output shards proven to belong to this exact command."""+ self._resume_parameters = self._build_resume_parameters()+ manifest = None+ try:+ with open(self._resume_manifest_path) as f:+ manifest = json.load(f)+ except FileNotFoundError:+ pass+ except Exception as exc:+ logger.warning(f"Could not read model-free resume state: {exc}; starting from the first shard.")++ source_is_verifiable = (+ os.path.isdir(self.model_name_or_path) or self._resume_parameters["source_revision"] is not None+ )+ if (+ manifest+ and source_is_verifiable+ and manifest.get("version") == 1+ and manifest.get("parameters") == self._resume_parameters+ ):+ cached_processed = manifest.get("processed_files", {})+ if isinstance(cached_processed, dict):+ for shard_name in self.shard_names:+ record = cached_processed.get(shard_name)+ if record is None:+ continue+ if not self._resume_record_is_valid(record):+ logger.warning(f"Cached output for {shard_name} is missing or invalid; processing it again.")+ continue+ self._resume_processed_shards[shard_name] = record+ self.all_quantized_layers.extend(record.get("quantized_layers", []))+ self.all_ignored_layers.extend(record.get("ignored_layers", []))+ for tensor_name in record["tensor_names"]:+ self.output_weight_map[tensor_name] = record["output_file"]+ elif manifest:+ logger.info(+ "Model-free resume state cannot be verified against current command parameters; starting fresh."+ )+ if self.is_streaming:+ cache_dir = os.path.join(self.work_dir, ".cache", "model_free_source_shards")+ shutil.rmtree(cache_dir, ignore_errors=True)++ pending = [name for name in self.shard_names if name not in self._resume_processed_shards]+ if self._resume_processed_shards:+ logger.info(+ f"Model-free resume: skipping {len(self._resume_processed_shards)}/{len(self.shard_names)} "+ "validated output shard(s)."+ )++ # Donor lifetimes only need to account for recipients still pending.+ donor_recipients: dict[str, set[str]] = {}+ for recipient in pending:+ for donor in self.cross_shard_deps.get(recipient, {}):+ donor_recipients.setdefault(donor, set()).add(recipient)+ self._donor_remaining_recipients = {donor: len(recipients) for donor, recipients in donor_recipients.items()}+ self._donor_self_consumed = {+ donor: donor in self._resume_processed_shards for donor in self.donor_shard_tensors+ }+ self._write_resume_manifest()++ def _mark_shard_completed(+ self,+ shard_name: str,+ out_shard_name: str,+ tensor_names: list[str],+ quantized: list[str],+ ignored: list[str],+ ) -> None:+ self._resume_processed_shards[shard_name] = {+ "output_file": out_shard_name,+ "tensor_names": tensor_names,+ "quantized_layers": quantized,+ "ignored_layers": ignored,+ }+ self._write_resume_manifest()++ def _clear_resume_state(self) -> None:+ try:+ os.remove(self._resume_manifest_path)+ except FileNotFoundError:+ pass++ def _create_shard_progress(self, tqdm_factory: Any) -> Any:+ """Create a progress bar that retains the full shard count on resume."""+ if tqdm_factory is None:+ return None+ return tqdm_factory(+ total=len(self.shard_names),+ initial=len(self._resume_processed_shards),+ desc="Processing shards",+ unit="shard",+ )+def _process_all_shards(self) -> None:if self.is_streaming:self._process_all_shards_streaming_pipeline()@@ -995,17 +1192,23 @@ class _ModelFreeCompressorCore:except ImportError:_tqdm = None- if not self.shard_names:+ pending_shards = [+ (shard_idx, shard_name)+ for shard_idx, shard_name in enumerate(self.shard_names)+ if shard_name not in self._resume_processed_shards+ ]+ if not pending_shards:returnos.makedirs(self._quant_output_dir, exist_ok=True)- worker_count = max(1, min(self.shard_parallelism, len(self.shard_names)))+ worker_count = max(1, min(self.shard_parallelism, len(pending_shards)))futures = []pool: ProcessPoolExecutor | None = None+ progress = self._create_shard_progress(_tqdm)try:pool = ProcessPoolExecutor(max_workers=worker_count, mp_context=mp.get_context("spawn"))- for shard_idx, shard_name in enumerate(self.shard_names):+ for shard_idx, shard_name in pending_shards:donor_tensors = list(self.donor_shard_tensors.get(shard_name, ())) or Nonefutures.append(pool.submit(@@ -1031,15 +1234,11 @@ class _ModelFreeCompressorCore:))- shard_iter = (- _tqdm(as_completed(futures), total=len(futures), desc="Processing shards", unit="shard")- if _tqdm- else as_completed(futures)- )-- for future in shard_iter:+ for future in as_completed(futures):result = future.result()self._merge_shard_task_result(result)+ if progress is not None:+ progress.update(1)except KeyboardInterrupt:logger.warning("Interrupted by user; terminating model-free shard worker processes.")_force_cleanup_process_pool(pool)@@ -1049,6 +1248,8 @@ class _ModelFreeCompressorCore:raisefinally:_force_cleanup_process_pool(pool)+ if progress is not None:+ progress.close()def _merge_shard_task_result(self,@@ -1078,6 +1279,8 @@ class _ModelFreeCompressorCore:for tensor_name in tensor_names:self.output_weight_map[tensor_name] = out_shard_name+ self._mark_shard_completed(shard_name, out_shard_name, tensor_names, quantized, ignored)+if self.is_streaming:self._release_donor_dependency(shard_name)@@ -1130,28 +1333,35 @@ class _ModelFreeCompressorCore:except ImportError:_tqdm = None- if not self.shard_names:+ pending_names = {name for name in self.shard_names if name not in self._resume_processed_shards}+ required_donors = {donor for recipient in pending_names for donor in self.cross_shard_deps.get(recipient, {})}+ pipeline_shards = [+ (shard_idx, shard_name)+ for shard_idx, shard_name in enumerate(self.shard_names)+ if shard_name in pending_names or shard_name in required_donors+ ]+ if not pipeline_shards:returnos.makedirs(self._quant_output_dir, exist_ok=True)- worker_count = max(1, min(self.shard_parallelism, len(self.shard_names)))+ worker_count = max(1, min(self.shard_parallelism, len(pending_names) or 1))prefetch_depth = max(2, worker_count)total_shards = len(self.shard_names)+ total_pipeline_shards = len(pipeline_shards)download_pool: ThreadPoolExecutor | None = Nonequant_pool: ProcessPoolExecutor | None = Nonedownload_futures: dict = {}quant_futures = set()next_download_idx = 0- completed_quant = 0+ completed_pipeline_shards = 0def _submit_next_download() -> bool:nonlocal next_download_idx- if next_download_idx >= total_shards:+ if next_download_idx >= total_pipeline_shards:return False- shard_idx = next_download_idx- shard_name = self.shard_names[shard_idx]+ shard_idx, shard_name = pipeline_shards[next_download_idx]future = download_pool.submit(_prefetch_shard,self.model_name_or_path,@@ -1168,12 +1378,12 @@ class _ModelFreeCompressorCore:download_pool = ThreadPoolExecutor(max_workers=1)quant_pool = ProcessPoolExecutor(max_workers=worker_count, mp_context=mp.get_context("spawn"))- for _ in range(min(prefetch_depth, total_shards)):+ for _ in range(min(prefetch_depth, total_pipeline_shards)):_submit_next_download()- progress = _tqdm(total=total_shards, desc="Processing shards", unit="shard") if _tqdm else None+ progress = self._create_shard_progress(_tqdm)- while completed_quant < total_shards:+ while completed_pipeline_shards < total_pipeline_shards:wait_set = set(download_futures.keys()) | set(quant_futures)if not wait_set:break@@ -1185,9 +1395,13 @@ class _ModelFreeCompressorCore:shard_path = future.result()if shard_path is None or not os.path.exists(shard_path):logger.warning(f"Prefetch failed for shard {shard_name}, skipping")- completed_quant += 1- if progress is not None:+ completed_pipeline_shards += 1+ if progress is not None and shard_name in pending_names:progress.update(1)+ elif shard_name not in pending_names:+ self._donor_shard_paths[shard_name] = shard_path+ self._donor_self_consumed[shard_name] = True+ completed_pipeline_shards += 1else:# Donor shards must stay on disk until every recipient# that depends on them has been processed (tracked via@@ -1235,7 +1449,7 @@ class _ModelFreeCompressorCore:quant_futures.remove(future)result = future.result()self._merge_shard_task_result(result)- completed_quant += 1+ completed_pipeline_shards += 1if progress is not None:progress.update(1)@@ -1262,6 +1476,11 @@ class _ModelFreeCompressorCore:def _write_index(self) -> None:_write_index_file(self._quant_output_dir, self.output_weight_map)+ if len(self.shard_names) == 1 and self._resume_processed_shards:+ for record in self._resume_processed_shards.values():+ record["output_file"] = "model.safetensors"+ self.output_weight_map = {name: "model.safetensors" for name in self.output_weight_map}+ self._write_resume_manifest()def _remove_stale_quantization_config_files(self) -> None:"""Remove source/output quantization metadata before writing the new config."""@@ -1411,6 +1630,7 @@ class _ModelFreeCompressorCore:self._build_cross_shard_deps()self._reorder_shards_by_dependency()self.shard_parallelism, shard_parallelism_source = self._resolve_shard_parallelism()+ self._prepare_resume_state()# Determine the output packing format based on scheme data typedata_type = (self.default_scheme.get("data_type") or "int").lower()@@ -1456,10 +1676,18 @@ class _ModelFreeCompressorCore:# ---- main loop ----self._process_all_shards()+ if len(self._resume_processed_shards) != len(self.shard_names):+ missing_shards = [name for name in self.shard_names if name not in self._resume_processed_shards]+ raise RuntimeError(+ "Model-free quantization did not complete all weight shards; resume state was retained for: "+ f"{', '.join(missing_shards)}"+ )+# ---- write outputs ----self._write_index()self._write_config_files()self._copy_metadata_files()+ self._clear_resume_state()self._cleanup_streaming_shard_cache()self._log_summary(time.time() - start_time)diff --git a/test/unit/test_cpu/quantization/test_model_free.py b/test/unit/test_cpu/quantization/test_model_free.pyindex cf2ec25b5..b5a590e60 100644--- a/test/unit/test_cpu/quantization/test_model_free.py+++ b/test/unit/test_cpu/quantization/test_model_free.py@@ -819,6 +819,200 @@ class TestModelFreeQuantize:out_keys = set(sf.keys())assert "layer.qweight" in out_keys+ @staticmethod+ def _make_resume_core(model_dir, output_dir, *, scheme="W4A16"):+ core = _ModelFreeCompressorCore(+ model_name_or_path=model_dir,+ output_dir=output_dir,+ scheme=scheme,+ enable_torch_compile=False,+ )+ core._parse_scheme()+ core._parse_layer_config()+ core._build_ignore_patterns()+ core.source_dir = model_dir+ core.config = dict(_SIMPLE_CONFIG)+ core.model_type = "opt"+ core.shard_names = ["model.safetensors"]+ return core++ def test_resume_skips_only_valid_output_from_same_command(self, tmp_path):+ model_dir = _make_model_dir(tmp_path, _SIMPLE_CONFIG, _SIMPLE_TENSORS)+ output_dir = str(tmp_path / "output")+ os.makedirs(output_dir, exist_ok=True)+ output_shard = "model-00001-of-00001.safetensors"+ tensor_names = ["model.layers.0.qweight"]+ save_file({tensor_names[0]: torch.ones(2, 2)}, os.path.join(output_dir, output_shard))++ first = self._make_resume_core(model_dir, output_dir)+ first._prepare_resume_state()+ first._mark_shard_completed(+ "model.safetensors",+ output_shard,+ tensor_names,+ ["model.layers.0"],+ [],+ )++ resumed = self._make_resume_core(model_dir, output_dir)+ resumed._prepare_resume_state()++ assert set(resumed._resume_processed_shards) == {"model.safetensors"}+ assert resumed.output_weight_map == {tensor_names[0]: output_shard}+ with open(resumed._resume_manifest_path) as f:+ manifest = json.load(f)+ assert manifest["pending_files"] == []+ assert set(manifest["processed_files"]) == {"model.safetensors"}+ assert manifest["parameters"]["default_scheme"]["bits"] == 4++ def test_resume_progress_retains_all_shards(self):+ core = _ModelFreeCompressorCore.__new__(_ModelFreeCompressorCore)+ core.shard_names = [f"model-{index:05d}.safetensors" for index in range(1, 5)]+ core._resume_processed_shards = {+ core.shard_names[0]: {},+ core.shard_names[1]: {},+ }+ progress = Mock()+ tqdm_factory = Mock(return_value=progress)++ assert core._create_shard_progress(tqdm_factory) is progress+ tqdm_factory.assert_called_once_with(+ total=4,+ initial=2,+ desc="Processing shards",+ unit="shard",+ )++ def test_resume_rejects_changed_command_parameters(self, tmp_path):+ model_dir = _make_model_dir(tmp_path, _SIMPLE_CONFIG, _SIMPLE_TENSORS)+ output_dir = str(tmp_path / "output")+ os.makedirs(output_dir, exist_ok=True)+ output_shard = "model-00001-of-00001.safetensors"+ save_file({"layer.qweight": torch.ones(2, 2)}, os.path.join(output_dir, output_shard))++ first = self._make_resume_core(model_dir, output_dir)+ first._prepare_resume_state()+ first._mark_shard_completed("model.safetensors", output_shard, ["layer.qweight"], ["layer"], [])++ changed = self._make_resume_core(model_dir, output_dir, scheme="W2A16")+ changed._prepare_resume_state()++ assert changed._resume_processed_shards == {}+ with open(changed._resume_manifest_path) as f:+ manifest = json.load(f)+ assert manifest["pending_files"] == ["model.safetensors"]++ def test_resume_rejects_corrupt_completed_output(self, tmp_path):+ model_dir = _make_model_dir(tmp_path, _SIMPLE_CONFIG, _SIMPLE_TENSORS)+ output_dir = str(tmp_path / "output")+ os.makedirs(output_dir, exist_ok=True)+ output_shard = "model-00001-of-00001.safetensors"+ output_path = os.path.join(output_dir, output_shard)+ save_file({"layer.qweight": torch.ones(2, 2)}, output_path)++ first = self._make_resume_core(model_dir, output_dir)+ first._prepare_resume_state()+ first._mark_shard_completed("model.safetensors", output_shard, ["layer.qweight"], ["layer"], [])+ with open(output_path, "wb") as f:+ f.write(b"incomplete")++ resumed = self._make_resume_core(model_dir, output_dir)+ resumed._prepare_resume_state()++ assert resumed._resume_processed_shards == {}+ with open(resumed._resume_manifest_path) as f:+ manifest = json.load(f)+ assert manifest["pending_files"] == ["model.safetensors"]++ def test_resume_rejects_changed_index(self, tmp_path):+ model_dir = _make_model_dir(tmp_path, _SIMPLE_CONFIG, _SIMPLE_TENSORS)+ output_dir = str(tmp_path / "output")+ os.makedirs(output_dir, exist_ok=True)+ output_shard = "model-00001-of-00001.safetensors"+ save_file({"layer.qweight": torch.ones(2, 2)}, os.path.join(output_dir, output_shard))+ index_path = os.path.join(model_dir, "model.safetensors.index.json")+ with open(index_path, "w") as index_file:+ json.dump({"metadata": {"total_size": 1}, "weight_map": {"layer.weight": "model.safetensors"}}, index_file)++ first = self._make_resume_core(model_dir, output_dir)+ first._prepare_resume_state()+ first._mark_shard_completed("model.safetensors", output_shard, ["layer.qweight"], ["layer"], [])++ with open(index_path, "w") as index_file:+ json.dump({"metadata": {"total_size": 2}, "weight_map": {"layer.weight": "model.safetensors"}}, index_file)+ resumed = self._make_resume_core(model_dir, output_dir)+ resumed._prepare_resume_state()++ assert resumed._resume_processed_shards == {}++ def test_resume_accepts_single_shard_after_final_rename(self, tmp_path):+ model_dir = _make_model_dir(tmp_path, _SIMPLE_CONFIG, _SIMPLE_TENSORS)+ output_dir = str(tmp_path / "output")+ os.makedirs(output_dir, exist_ok=True)+ output_shard = "model-00001-of-00001.safetensors"+ save_file({"layer.qweight": torch.ones(2, 2)}, os.path.join(output_dir, output_shard))++ first = self._make_resume_core(model_dir, output_dir)+ first._prepare_resume_state()+ first._mark_shard_completed("model.safetensors", output_shard, ["layer.qweight"], ["layer"], [])+ first.output_weight_map = {"layer.qweight": output_shard}+ first._write_index()++ resumed = self._make_resume_core(model_dir, output_dir)+ resumed._prepare_resume_state()++ assert set(resumed._resume_processed_shards) == {"model.safetensors"}+ assert resumed.output_weight_map == {"layer.qweight": "model.safetensors"}++ def test_run_resumes_after_interrupted_shard_processing(self, tmp_path, monkeypatch):+ model_dir = _make_model_dir(tmp_path, _SIMPLE_CONFIG, _SIMPLE_TENSORS)+ output_dir = str(tmp_path / "output")++ def stub_preflight(core):+ for method_name in (+ "_validate_format",+ "_parse_scheme",+ "_parse_layer_config",+ "_build_ignore_patterns",+ "_resolve_source",+ "_check_conv1d_and_embedding",+ "_apply_predefined_ignore_layers",+ "_detect_fp8_source",+ "_resolve_model_type",+ "_discover_shards",+ "_build_cross_shard_deps",+ "_reorder_shards_by_dependency",+ ):+ monkeypatch.setattr(core, method_name, lambda: None)+ monkeypatch.setattr(core, "_resolve_shard_parallelism", lambda: (1, "test"))++ interrupted = self._make_resume_core(model_dir, output_dir)+ stub_preflight(interrupted)++ def process_then_interrupt():+ shard_name = "model-00001-of-00001.safetensors"+ os.makedirs(output_dir, exist_ok=True)+ save_file({"layer.qweight": torch.ones(2, 2)}, os.path.join(output_dir, shard_name))+ interrupted._mark_shard_completed("model.safetensors", shard_name, ["layer.qweight"], ["layer"], [])+ raise RuntimeError("interrupted")++ monkeypatch.setattr(interrupted, "_process_all_shards", process_then_interrupt)+ with pytest.raises(RuntimeError, match="interrupted"):+ interrupted.run()+ assert os.path.exists(interrupted._resume_manifest_path)++ resumed = self._make_resume_core(model_dir, output_dir)+ stub_preflight(resumed)++ def verify_completed_shard_is_skipped():+ assert set(resumed._resume_processed_shards) == {"model.safetensors"}++ monkeypatch.setattr(resumed, "_process_all_shards", verify_completed_shard_is_skipped)++ assert resumed.run() == output_dir+ assert os.path.exists(os.path.join(output_dir, "model.safetensors"))+ assert not os.path.exists(resumed._resume_manifest_path)+# ===========================================================================# MXFP4 / MXFP8 model-free quantization