Skip to content

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

fix: pin Hugging Face snapshots for AutoScheme offload reloads (#2318)

Heng Guo34c385adb580
diff --git a/auto_round/auto_scheme/delta_loss.py b/auto_round/auto_scheme/delta_loss.py
index e7d4dae5f..8d23ff152 100644
--- a/auto_round/auto_scheme/delta_loss.py
+++ b/auto_round/auto_scheme/delta_loss.py
@@ -2579,7 +2579,12 @@ def _gen_layer_config(
if _model_dir is None and hasattr(model, "config"):
_model_dir = getattr(model.config, "_name_or_path", None)
offload_mode = "clean"
- offload_kwargs = {"model_dir": _model_dir}
+ model_revision = getattr(getattr(model, "config", None), "_commit_hash", None)
+ from auto_round import envs
+
+ if envs.AR_USE_MODELSCOPE:
+ model_revision = None
+ offload_kwargs = {"model_dir": _model_dir, "model_revision": model_revision}
# Rotation mutates weights in memory before AutoScheme starts. Clean-mode
# reloads from the original checkpoint and would silently discard those
# transformed weights during scoring and final restore.
diff --git a/auto_round/compressors/base.py b/auto_round/compressors/base.py
index b4c9437b2..788bbfec2 100644
--- a/auto_round/compressors/base.py
+++ b/auto_round/compressors/base.py
@@ -79,7 +79,7 @@ from auto_round.utils.device import (
set_non_auto_device_map,
)
from auto_round.utils.device_manager import default_enable_torch_compile, device_manager
-from auto_round.utils.offload import OffloadManager
+from auto_round.utils.offload import OffloadManager, _resolve_model_dir
# ``torch.compile`` only pays for itself when the compiled quant function is
# replayed many times. Below this many SignRound iterations the one-off
@@ -450,7 +450,12 @@ class BaseOrchestrator(object):
# each block on first touch directly from disk instead of assuming
# blocks already hold real weights (see OffloadManager._reload).
if self.model_context.disk_stream_model_dir is not None:
- self._offloader.model_dir = self.model_context.disk_stream_model_dir
+ model_dir = self.model_context.disk_stream_model_dir
+ model_revision = getattr(getattr(self.model_context.model, "config", None), "_commit_hash", None)
+ if self.model_context.platform == "hf" and model_revision is not None:
+ model_dir = _resolve_model_dir(model_dir, revision=model_revision)
+ self.model_context.disk_stream_model_dir = model_dir
+ self._offloader.model_dir = model_dir
# A meta skeleton (explicit AR_DISK_STREAM_MODEL=1, or auto-selected for
# fused-MoE checkpoints -- signalled by `_disk_stream_index`) leaves every
# block on the meta device, so per-block reload from disk is mandatory: the
diff --git a/auto_round/utils/offload.py b/auto_round/utils/offload.py
index 0cea78e8c..6ae7fc84a 100644
--- a/auto_round/utils/offload.py
+++ b/auto_round/utils/offload.py
@@ -189,15 +189,29 @@ def _clear_module_weights(
# =====================================================================
-def _resolve_model_dir(model_dir: str) -> str:
+def _resolve_model_dir(model_dir: str, revision: Optional[str] = None) -> str:
"""Resolve a model name/path to a local directory containing weight files."""
if os.path.isdir(model_dir):
return model_dir
try:
- from huggingface_hub import snapshot_download
-
+ from huggingface_hub import snapshot_download, try_to_load_from_cache
+
+ for filename in (
+ "model.safetensors.index.json",
+ "model.safetensors",
+ "pytorch_model.bin.index.json",
+ "pytorch_model.bin",
+ ):
+ cached_file = try_to_load_from_cache(model_dir, filename, revision=revision)
+ if isinstance(cached_file, str):
+ return os.path.dirname(cached_file)
+
+ if revision is not None:
+ return snapshot_download(model_dir, revision=revision, local_files_only=True)
return snapshot_download(model_dir, local_files_only=True)
except Exception:
+ if revision is not None:
+ raise
return model_dir
@@ -329,6 +343,9 @@ class OffloadManager:
model_dir : str, optional
Path to the model checkpoint directory. Required for ``"clean"``
mode; optional for ``"offload"``.
+ model_revision : str, optional
+ Commit hash used to resolve a Hugging Face model ID without relying
+ on a mutable branch reference.
offload_dir_prefix : str
Prefix for the temp directory name (``"offload"`` mode only).
cache_numel : bool
@@ -344,12 +361,17 @@ class OffloadManager:
offload_dir_prefix: str = "ar_offload",
cache_numel: bool = False,
retain_saved_entries: bool = False,
+ model_revision: Optional[str] = None,
):
from auto_round import envs
self.enabled = enabled and not envs.AR_DISABLE_OFFLOAD
self.mode = mode
- self.model_dir = model_dir
+ self.model_dir = (
+ _resolve_model_dir(model_dir, revision=model_revision)
+ if mode == "clean" and model_dir is not None and model_revision is not None
+ else model_dir
+ )
self.cache_numel = cache_numel
self._prefix = offload_dir_prefix
self.retain_saved_entries = retain_saved_entries
diff --git a/test/unit/common/core/test_init.py b/test/unit/common/core/test_init.py
index ef50a5ef7..72e13d4fb 100644
--- a/test/unit/common/core/test_init.py
+++ b/test/unit/common/core/test_init.py
@@ -112,6 +112,38 @@ def test_torch_compile_runtime_defaults(tiny_opt_model_path):
assert ar.enable_torch_compile == default_enable_torch_compile(ar.device)
+def test_hf_model_id_sets_resolved_checkpoint_on_compressor_offloader(tiny_opt_model_path, monkeypatch):
+ """Zero-shot block reloads use the resolved snapshot rather than the model ID."""
+ from transformers import AutoConfig, AutoModelForCausalLM
+
+ commit = "a" * 40
+ resolve_calls = []
+ config = AutoConfig.from_pretrained(tiny_opt_model_path)
+ config._commit_hash = commit
+
+ def load_model(*_args, **_kwargs):
+ model = AutoModelForCausalLM.from_pretrained(tiny_opt_model_path)
+ model.config._commit_hash = commit
+ return model, None
+
+ def resolve_model_dir(model_id, revision):
+ resolve_calls.append((model_id, revision))
+ return tiny_opt_model_path
+
+ monkeypatch.setattr("auto_round.utils.model.detect_model_type", lambda _model: "llm")
+ monkeypatch.setattr("auto_round.compressors.base.BaseOrchestrator._preload_model_config", lambda *_: config)
+ monkeypatch.setattr("auto_round.context.model.is_diffusion_model", lambda *_args, **_kwargs: False)
+ monkeypatch.setattr("auto_round.context.model.is_mllm_model", lambda *_args, **_kwargs: False)
+ monkeypatch.setattr("auto_round.context.model.llm_load_model", load_model)
+ monkeypatch.setattr("auto_round.compressors.base._resolve_model_dir", resolve_model_dir)
+
+ ar = AutoRound(model="org/model", scheme="W4A16", iters=0, nsamples=1)
+
+ assert resolve_calls == [("org/model", commit)]
+ assert ar.model_context.disk_stream_model_dir == tiny_opt_model_path
+ assert ar._offloader.model_dir == tiny_opt_model_path
+
+
def _assert_compile(ar, expected: bool):
"""Assert the effective torch.compile flag, tolerating the model-free path.
diff --git a/test/unit/common/utils/test_offload_helpers.py b/test/unit/common/utils/test_offload_helpers.py
index 7d7b6c465..ee0038cf4 100644
--- a/test/unit/common/utils/test_offload_helpers.py
+++ b/test/unit/common/utils/test_offload_helpers.py
@@ -261,3 +261,64 @@ class TestResolveModelDir:
):
result = _resolve_model_dir(str(tmp_path / "missing"))
assert result == str(tmp_path / "missing")
+
+ def test_revision_resolves_partial_snapshot_from_cached_weight_index(self, tmp_path):
+ """A usable weight snapshot need not contain every repository file."""
+ from auto_round.utils.offload import _resolve_model_dir
+
+ snapshot = tmp_path / "snapshots" / "commit"
+ index_path = snapshot / "model.safetensors.index.json"
+ index_path.parent.mkdir(parents=True)
+ index_path.write_text('{"weight_map": {}}')
+ incomplete = RuntimeError("snapshot is missing README.md")
+ with (
+ patch("huggingface_hub.try_to_load_from_cache", return_value=str(index_path)) as cached,
+ patch("huggingface_hub.snapshot_download", side_effect=incomplete) as download,
+ ):
+ resolved = _resolve_model_dir("org/model", revision="commit")
+
+ assert resolved == str(snapshot)
+ cached.assert_called_once_with("org/model", "model.safetensors.index.json", revision="commit")
+ download.assert_not_called()
+
+ def test_offload_manager_resolves_model_id_once(self, tmp_path):
+ """Block reloads must reuse the snapshot resolved when the manager is created."""
+ from auto_round.utils.offload import OffloadManager
+
+ snapshot = tmp_path / "snapshot"
+ snapshot.mkdir()
+ model = nn.Sequential(nn.Linear(2, 2))
+ with (
+ patch("auto_round.utils.offload._resolve_model_dir", return_value=str(snapshot)) as resolve,
+ patch("auto_round.utils.offload.load_block_from_model_files") as load_block,
+ ):
+ manager = OffloadManager(mode="clean", model_dir="org/model", model_revision="commit")
+ manager.reload(model, "0")
+
+ assert manager.model_dir == str(snapshot)
+ resolve.assert_called_once_with("org/model", revision="commit")
+ load_block.assert_called_once_with(str(snapshot), "0", model[0])
+
+ def test_offload_manager_does_not_eagerly_resolve_without_revision(self):
+ """Revision-less and non-Hugging Face sources retain the legacy lazy path."""
+ from auto_round.utils.offload import OffloadManager
+
+ with patch("auto_round.utils.offload._resolve_model_dir") as resolve:
+ manager = OffloadManager(mode="clean", model_dir="modelscope/model")
+
+ assert manager.model_dir == "modelscope/model"
+ resolve.assert_not_called()
+
+ def test_revision_resolution_preserves_hub_error(self):
+ """A pinned lookup failure must not be hidden behind a local-path error."""
+ from auto_round.utils.offload import _resolve_model_dir
+
+ error = RuntimeError("snapshot unavailable")
+ with (
+ patch("huggingface_hub.try_to_load_from_cache", return_value=None),
+ patch("huggingface_hub.snapshot_download", side_effect=error),
+ pytest.raises(RuntimeError) as exc_info,
+ ):
+ _resolve_model_dir("org/model", revision="commit")
+
+ assert exc_info.value is error