refactor: pass GGUF files straight through to Transformers
Transformers loads a GGUF checkpoint when gguf_file and GgufConfig(dequantize=True) are set. Heretic now only resolves that filename: a local .gguf path, or the single non-projector file from one Hub listing. Quant ranking, magic-byte checks, and the cache walk are gone. Co-authored-by: Lixin2026 <2023Anita@users.noreply.github.com>
This commit is contained in:
parent
2277faf49c
commit
0f2a4d3926
|
|
@ -204,8 +204,8 @@ class Settings(BaseSettings):
|
|||
model: str = Field(
|
||||
description=(
|
||||
"Hugging Face model ID, or path to model on disk. "
|
||||
"A GGUF file, or a repository that ships GGUF weights and no "
|
||||
"safetensors or PyTorch weights, is dequantized to a dense model "
|
||||
"A .gguf file, or a repository whose only weight file is a single "
|
||||
".gguf (a projector sidecar aside), is dequantized to a dense model "
|
||||
"on load. Saving writes that reconstruction, not the original "
|
||||
"full-precision checkpoint."
|
||||
),
|
||||
|
|
|
|||
|
|
@ -1,26 +1,14 @@
|
|||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
# Copyright (C) 2025-2026 Philipp Emanuel Weidmann <pew@worldwidemann.com> + contributors
|
||||
|
||||
import os
|
||||
from collections.abc import Callable
|
||||
from contextlib import suppress
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any, TypeAlias, cast
|
||||
|
||||
import torch
|
||||
from huggingface_hub import list_repo_files
|
||||
from huggingface_hub.constants import HF_HUB_CACHE
|
||||
from huggingface_hub.utils import (
|
||||
GatedRepoError,
|
||||
HfHubHTTPError,
|
||||
HFValidationError,
|
||||
LocalEntryNotFoundError,
|
||||
OfflineModeIsEnabled,
|
||||
RepositoryNotFoundError,
|
||||
RevisionNotFoundError,
|
||||
)
|
||||
from peft import LoraConfig, PeftModel, get_peft_model
|
||||
from torch import FloatTensor, LongTensor, Tensor
|
||||
from torch.nn import Module, ModuleList
|
||||
|
|
@ -152,241 +140,40 @@ def chat_template_supports_system_role(tokenizer: PreTrainedTokenizerBase) -> bo
|
|||
ModuleIO: TypeAlias = list[dict[str, dict[int, tuple[Tensor, Tensor]]]]
|
||||
|
||||
|
||||
# A listing failure must not block a normal load. Offline use, a missing repo,
|
||||
# and a path that is not a repo id all end up here.
|
||||
_HUB_LISTING_ERRORS = (
|
||||
GatedRepoError,
|
||||
HFValidationError,
|
||||
HfHubHTTPError,
|
||||
LocalEntryNotFoundError,
|
||||
OfflineModeIsEnabled,
|
||||
RepositoryNotFoundError,
|
||||
RevisionNotFoundError,
|
||||
OSError,
|
||||
)
|
||||
|
||||
_GGUF_MAGIC = b"GGUF"
|
||||
|
||||
|
||||
def _is_standard_weight_filename(name: str) -> bool:
|
||||
"""Return whether ``name`` is a weight file Transformers can load on its own."""
|
||||
basename = name.replace("\\", "/").rsplit("/", 1)[-1].lower()
|
||||
if basename.endswith((".safetensors", ".safetensors.index.json")):
|
||||
return True
|
||||
return basename.startswith("pytorch_model") and basename.endswith(
|
||||
(".bin", ".bin.index.json")
|
||||
)
|
||||
|
||||
|
||||
def _has_gguf_magic(path: Path) -> bool:
|
||||
"""Return whether ``path`` starts with the GGUF magic bytes."""
|
||||
try:
|
||||
with path.open("rb") as handle:
|
||||
return handle.read(4) == _GGUF_MAGIC
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def _filenames_are_gguf_only(filenames: list[str]) -> bool:
|
||||
def _only_gguf_file(names: list[str]) -> str | None:
|
||||
"""
|
||||
Return whether a repo file listing is a GGUF checkpoint.
|
||||
Return the one GGUF file to pass as ``gguf_file``, or ``None``.
|
||||
|
||||
GGUF-only means at least one ``.gguf`` file and no safetensors / PyTorch
|
||||
weights. ``config.json`` does not count: the weights still are not loadable
|
||||
with ``from_pretrained`` unless ``gguf_file`` is passed.
|
||||
Transformers does not pick a file inside a repository. A listing that also
|
||||
contains safetensors or PyTorch weights stays on the normal loader. More
|
||||
than one model file is left unresolved. An ``mmproj`` sidecar is skipped
|
||||
when another ``.gguf`` file is present.
|
||||
"""
|
||||
has_gguf = False
|
||||
for name in filenames:
|
||||
if _is_standard_weight_filename(name):
|
||||
return False
|
||||
if name.replace("\\", "/").rsplit("/", 1)[-1].lower().endswith(".gguf"):
|
||||
has_gguf = True
|
||||
return has_gguf
|
||||
|
||||
|
||||
def _hub_cache_root() -> Path:
|
||||
configured = os.environ.get("HF_HUB_CACHE") or os.environ.get(
|
||||
"HUGGINGFACE_HUB_CACHE"
|
||||
)
|
||||
if configured:
|
||||
return Path(configured).expanduser()
|
||||
return Path(HF_HUB_CACHE)
|
||||
|
||||
|
||||
def _cached_hub_filenames(repo_id: str, revision: str | None) -> list[str] | None:
|
||||
"""
|
||||
Return file names from the local Hub cache, or ``None`` when unavailable.
|
||||
|
||||
Used when the Hub cannot be listed (offline, network error, no token).
|
||||
"""
|
||||
if repo_id.count("/") != 1:
|
||||
if any(
|
||||
".safetensors" in name or ("pytorch_model" in name and ".bin" in name)
|
||||
for name in names
|
||||
):
|
||||
return None
|
||||
|
||||
root = _hub_cache_root() / f"models--{repo_id.replace('/', '--')}"
|
||||
snapshots = root / "snapshots"
|
||||
if not snapshots.is_dir():
|
||||
return None
|
||||
|
||||
revision_name = revision or "main"
|
||||
commit: str | None = None
|
||||
ref = root / "refs" / revision_name
|
||||
try:
|
||||
if ref.is_file():
|
||||
commit = ref.read_text(encoding="utf-8").strip()
|
||||
elif (snapshots / revision_name).is_dir():
|
||||
commit = revision_name
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
# A revision is a single cache-directory name, never a path.
|
||||
if not commit or commit in {".", ".."} or "/" in commit or "\\" in commit:
|
||||
return None
|
||||
|
||||
folder = snapshots / commit
|
||||
if not folder.is_dir():
|
||||
return None
|
||||
|
||||
try:
|
||||
return [
|
||||
item.relative_to(folder).as_posix()
|
||||
for item in folder.rglob("*")
|
||||
if item.is_file()
|
||||
]
|
||||
except OSError:
|
||||
return None
|
||||
gguf_files = [name for name in names if name.lower().endswith(".gguf")]
|
||||
model_files = [name for name in gguf_files if "mmproj" not in name.lower()]
|
||||
if len(model_files) == 1:
|
||||
return model_files[0]
|
||||
if len(gguf_files) == 1:
|
||||
return gguf_files[0]
|
||||
return None
|
||||
|
||||
|
||||
def _hub_filenames(repo_id: str, revision: str | None) -> list[str] | None:
|
||||
"""List a model repo, falling back to the local cache. ``None`` if unknown."""
|
||||
try:
|
||||
return list_repo_files(repo_id, revision=revision, repo_type="model")
|
||||
except _HUB_LISTING_ERRORS:
|
||||
return _cached_hub_filenames(repo_id, revision)
|
||||
|
||||
|
||||
# Closer to the original weights first. An unrecognized name sorts last, so a
|
||||
# file that names its quant wins over an unlabeled sidecar. ``bf16`` is listed
|
||||
# before ``f16`` because the check is a substring search.
|
||||
_GGUF_QUANT_RANK = (
|
||||
"f32",
|
||||
"bf16",
|
||||
"f16",
|
||||
"q8_0",
|
||||
"q6_k",
|
||||
"q5_k_m",
|
||||
"q5_k_s",
|
||||
"q5_1",
|
||||
"q5_0",
|
||||
"q4_k_m",
|
||||
"q4_k_s",
|
||||
"q4_1",
|
||||
"q4_0",
|
||||
"q3_k_l",
|
||||
"q3_k_m",
|
||||
"q3_k_s",
|
||||
"q2_k",
|
||||
"iq4_nl",
|
||||
"iq4_xs",
|
||||
"iq3_m",
|
||||
"iq3_s",
|
||||
"iq3_xxs",
|
||||
"iq2_m",
|
||||
"iq2_s",
|
||||
"iq2_xs",
|
||||
"iq2_xxs",
|
||||
"iq1_m",
|
||||
"iq1_s",
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _GGUFCheckpoint:
|
||||
"""
|
||||
Arguments for loading one GGUF file with Transformers.
|
||||
|
||||
``model_id`` is a Hub repo id or a local directory. ``gguf_file`` is the
|
||||
file inside it, or an absolute path when the checkpoint is a local file.
|
||||
Both ``AutoTokenizer.from_pretrained`` and ``AutoModelForCausalLM.from_pretrained``
|
||||
take that pair.
|
||||
"""
|
||||
|
||||
model_id: str
|
||||
gguf_file: str
|
||||
# Other model files in the same checkpoint, not including projector sidecars.
|
||||
alternatives: tuple[str, ...] = ()
|
||||
|
||||
|
||||
def _is_mmproj_gguf(name: str) -> bool:
|
||||
"""Return whether ``name`` is a multimodal projector sidecar, not the model."""
|
||||
basename = name.replace("\\", "/").rsplit("/", 1)[-1].lower()
|
||||
compact = basename.replace("-", "").replace("_", "")
|
||||
return "mmproj" in compact
|
||||
|
||||
|
||||
def _gguf_quant_rank(name: str) -> int:
|
||||
"""Rank a GGUF filename by how close its quant is to the original weights."""
|
||||
basename = name.replace("\\", "/").rsplit("/", 1)[-1].lower().replace("-", "_")
|
||||
for index, token in enumerate(_GGUF_QUANT_RANK):
|
||||
if token in basename:
|
||||
return index
|
||||
return len(_GGUF_QUANT_RANK)
|
||||
|
||||
|
||||
def _choose_gguf_file(names: list[str]) -> tuple[str, tuple[str, ...]]:
|
||||
"""
|
||||
Pick the model GGUF file.
|
||||
|
||||
Projector sidecars (``mmproj``) are skipped when a model file is present.
|
||||
Several model files resolve to the one closest to full precision.
|
||||
"""
|
||||
model_files = [name for name in names if not _is_mmproj_gguf(name)]
|
||||
if not model_files:
|
||||
model_files = list(names)
|
||||
chosen = min(model_files, key=lambda name: (_gguf_quant_rank(name), name.lower()))
|
||||
alternatives = tuple(sorted(name for name in model_files if name != chosen))
|
||||
return chosen, alternatives
|
||||
|
||||
|
||||
def _directory_gguf_checkpoint(root: Path) -> _GGUFCheckpoint | None:
|
||||
"""Return the GGUF file to load from a local directory, or ``None``."""
|
||||
gguf_paths: list[Path] = []
|
||||
has_standard_weights = False
|
||||
for path in root.rglob("*"):
|
||||
if not path.is_file():
|
||||
continue
|
||||
# The header is the format. A ``.gguf`` name that is not a GGUF file,
|
||||
# and a GGUF file that is not named ``.gguf``, are both possible.
|
||||
if _has_gguf_magic(path):
|
||||
gguf_paths.append(path)
|
||||
continue
|
||||
if _is_standard_weight_filename(path.name):
|
||||
has_standard_weights = True
|
||||
if has_standard_weights or not gguf_paths:
|
||||
return None
|
||||
|
||||
chosen, alternatives = _choose_gguf_file(
|
||||
[str(path.resolve()) for path in gguf_paths]
|
||||
)
|
||||
return _GGUFCheckpoint(
|
||||
model_id=str(root),
|
||||
gguf_file=chosen,
|
||||
alternatives=alternatives,
|
||||
)
|
||||
|
||||
|
||||
def _resolve_gguf_checkpoint(
|
||||
def _gguf_load_args(
|
||||
model: str,
|
||||
revision: str | None = None,
|
||||
) -> _GGUFCheckpoint | None:
|
||||
) -> tuple[str, str] | None:
|
||||
"""
|
||||
Return how to load ``model`` when it is a GGUF checkpoint, else ``None``.
|
||||
Return ``(from_pretrained id, gguf_file)`` for one GGUF checkpoint.
|
||||
|
||||
Local files are identified by the GGUF magic header. Local directories are
|
||||
identified by that header plus the absence of safetensors or PyTorch
|
||||
weights. Hub ids use the repo file listing (and, offline, the Hub cache):
|
||||
a ``.gguf`` file and no safetensors or PyTorch weights. A listing failure
|
||||
does not guess from the id string. A repo that also ships safetensors is
|
||||
left to the normal loader.
|
||||
A local ``.gguf`` path is passed through. A directory or Hub repo is used
|
||||
only when :func:`_only_gguf_file` names exactly one file. A Hub listing
|
||||
failure does not guess from the id.
|
||||
"""
|
||||
model = model.strip()
|
||||
if not model:
|
||||
|
|
@ -395,40 +182,31 @@ def _resolve_gguf_checkpoint(
|
|||
path = Path(model).expanduser()
|
||||
try:
|
||||
if path.is_file():
|
||||
if not _has_gguf_magic(path):
|
||||
if path.suffix.lower() != ".gguf":
|
||||
return None
|
||||
resolved = path.resolve()
|
||||
return _GGUFCheckpoint(
|
||||
model_id=str(resolved.parent),
|
||||
gguf_file=str(resolved),
|
||||
)
|
||||
return str(resolved.parent), str(resolved)
|
||||
if path.is_dir():
|
||||
return _directory_gguf_checkpoint(path.resolve())
|
||||
names = [child.name for child in path.iterdir() if child.is_file()]
|
||||
chosen = _only_gguf_file(names)
|
||||
if chosen is None:
|
||||
return None
|
||||
root = path.resolve()
|
||||
return str(root), str(root / chosen)
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
filenames = _hub_filenames(model, revision)
|
||||
if filenames is None or not _filenames_are_gguf_only(filenames):
|
||||
# Offline mode, a missing repo, or a path that is not a repo id must not
|
||||
# block the normal loader, and must not be guessed from the id string.
|
||||
try:
|
||||
names = list_repo_files(model, revision=revision, repo_type="model")
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
gguf_names = [
|
||||
name
|
||||
for name in filenames
|
||||
if name.replace("\\", "/").rsplit("/", 1)[-1].lower().endswith(".gguf")
|
||||
]
|
||||
if not gguf_names:
|
||||
chosen = _only_gguf_file(names)
|
||||
if chosen is None:
|
||||
return None
|
||||
chosen, alternatives = _choose_gguf_file(gguf_names)
|
||||
return _GGUFCheckpoint(
|
||||
model_id=model,
|
||||
gguf_file=chosen,
|
||||
alternatives=alternatives,
|
||||
)
|
||||
|
||||
|
||||
def _is_gguf_checkpoint(model: str, revision: str | None = None) -> bool:
|
||||
"""Return whether ``model`` should be loaded with ``gguf_file``."""
|
||||
return _resolve_gguf_checkpoint(model, revision=revision) is not None
|
||||
return model, chosen
|
||||
|
||||
|
||||
class Model:
|
||||
|
|
@ -449,8 +227,6 @@ class Model:
|
|||
def __init__(self, settings: Settings):
|
||||
self.settings = settings
|
||||
self.needs_reload = False
|
||||
self._announced_gguf: set[tuple[str, str]] = set()
|
||||
self._gguf_alternatives: tuple[str, ...] = ()
|
||||
|
||||
self.revision_kwargs = {}
|
||||
if settings.model_commit is not None:
|
||||
|
|
@ -640,59 +416,30 @@ class Model:
|
|||
|
||||
def _bind_checkpoint(self) -> None:
|
||||
"""
|
||||
Point this model at ``settings.model``, including a GGUF file if that
|
||||
is what the checkpoint is.
|
||||
Point this model at ``settings.model``.
|
||||
|
||||
``loaded_from`` is the settings string this bind used. ``reset_model``
|
||||
compares it so swapping in ``evaluate_model`` reloads, without listing
|
||||
the Hub again on the fast path.
|
||||
compares it so swapping in ``evaluate_model`` reloads.
|
||||
"""
|
||||
checkpoint = _resolve_gguf_checkpoint(
|
||||
loaded = _gguf_load_args(
|
||||
self.settings.model,
|
||||
revision=self.settings.model_commit,
|
||||
)
|
||||
self.loaded_from = self.settings.model
|
||||
if checkpoint is None:
|
||||
if loaded is None:
|
||||
self.pretrained_model_id = self.settings.model
|
||||
self.gguf_file = None
|
||||
self._gguf_alternatives = ()
|
||||
return
|
||||
|
||||
self.pretrained_model_id = checkpoint.model_id
|
||||
self.gguf_file = checkpoint.gguf_file
|
||||
self._gguf_alternatives = checkpoint.alternatives
|
||||
self._announce_gguf_dequantization()
|
||||
|
||||
def _announce_gguf_dequantization(self) -> None:
|
||||
"""Warn once per checkpoint that the loaded weights are a reconstruction."""
|
||||
assert self.gguf_file is not None
|
||||
key = (self.settings.model, self.gguf_file)
|
||||
if key in self._announced_gguf:
|
||||
return
|
||||
self._announced_gguf.add(key)
|
||||
|
||||
extra = ""
|
||||
if self._gguf_alternatives:
|
||||
listed = ", ".join(self._gguf_alternatives)
|
||||
extra = (
|
||||
f" Other GGUF model files were left unused ({listed}). "
|
||||
"This load uses the file closest to full precision."
|
||||
)
|
||||
self.pretrained_model_id, self.gguf_file = loaded
|
||||
bnb = ""
|
||||
if self.settings.quantization == QuantizationMethod.BNB_4BIT:
|
||||
bnb = (
|
||||
" bitsandbytes 4-bit quantization is not applied, because "
|
||||
"Transformers cannot combine it with loading a GGUF file."
|
||||
)
|
||||
bnb = " bitsandbytes 4-bit is not combined with GGUF loading."
|
||||
print(
|
||||
"[yellow]WARNING: "
|
||||
f"'{self.settings.model}' is a GGUF checkpoint. Heretic loads "
|
||||
f"[bold]{self.gguf_file}[/] through Transformers with dequantization "
|
||||
"forced. The weights are a dense reconstruction of that quantized "
|
||||
"file, not the original full-precision weights. Saving and uploading "
|
||||
"write the reconstruction as safetensors. Architectures that "
|
||||
"Transformers cannot map from GGUF still fail to load."
|
||||
f"{extra}{bnb}[/]"
|
||||
f"[bold]{self.gguf_file}[/] will be loaded as a dequantized dense "
|
||||
"reconstruction, not the original full-precision weights. Saving "
|
||||
f"writes that reconstruction as safetensors.{bnb}[/]"
|
||||
)
|
||||
|
||||
def _gguf_file_kwargs(self) -> dict[str, Any]:
|
||||
|
|
@ -705,13 +452,10 @@ class Model:
|
|||
"""
|
||||
Keyword arguments for ``AutoModelForCausalLM.from_pretrained``.
|
||||
|
||||
A GGUF load always asks Transformers to dequantize. Packed GGUF
|
||||
modules (Qwen3.5, when the ggml kernel is installed) are not trainable
|
||||
and ``save_pretrained`` refuses them. ``GgufConfig(dequantize=True)``
|
||||
unpacks every weight into an ordinary ``Linear`` in the requested
|
||||
dtype. The legacy loader already dequantizes; this forces the packed
|
||||
architectures down the same path. bitsandbytes is a different
|
||||
``quantization_config`` and cannot be combined with ``gguf_file``.
|
||||
A GGUF load passes ``gguf_file`` and ``GgufConfig(dequantize=True)``.
|
||||
Dequantization is what yields ordinary ``Linear`` weights Heretic can
|
||||
edit and save. bitsandbytes is a different ``quantization_config`` and
|
||||
cannot be combined with ``gguf_file``.
|
||||
"""
|
||||
kwargs: dict[str, Any] = dict(self.revision_kwargs)
|
||||
kwargs.update(self._gguf_file_kwargs())
|
||||
|
|
|
|||
|
|
@ -1,25 +1,66 @@
|
|||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
# Copyright (C) 2025-2026 Philipp Emanuel Weidmann <pew@worldwidemann.com> + contributors
|
||||
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import torch
|
||||
from huggingface_hub.utils import OfflineModeIsEnabled
|
||||
from transformers import GgufConfig
|
||||
|
||||
from heretic.config import QuantizationMethod, Settings
|
||||
from heretic.model import Model, _is_gguf_checkpoint, _resolve_gguf_checkpoint
|
||||
from heretic.model import Model, _only_gguf_file
|
||||
|
||||
_GEMMA_GGUF_FILES = [
|
||||
".gitattributes",
|
||||
"README.md",
|
||||
"gemma-4-26B-it-mmproj.gguf",
|
||||
"gemma-4-26B_q4_0-it.gguf",
|
||||
]
|
||||
|
||||
class OnlyGgufFileTests(unittest.TestCase):
|
||||
def test_picks_the_single_model_file_and_skips_mmproj(self) -> None:
|
||||
# google/gemma-4-26B-A4B-it-qat-q4_0-gguf (https://github.com/p-e-w/heretic/issues/533)
|
||||
self.assertEqual(
|
||||
_only_gguf_file(
|
||||
[
|
||||
".gitattributes",
|
||||
"README.md",
|
||||
"gemma-4-26B-it-mmproj.gguf",
|
||||
"gemma-4-26B_q4_0-it.gguf",
|
||||
]
|
||||
),
|
||||
"gemma-4-26B_q4_0-it.gguf",
|
||||
)
|
||||
|
||||
def test_uses_the_only_gguf_file(self) -> None:
|
||||
self.assertEqual(
|
||||
_only_gguf_file(["README.md", "mmproj.gguf"]),
|
||||
"mmproj.gguf",
|
||||
)
|
||||
|
||||
def test_leaves_safetensors_and_pytorch_checkpoints_alone(self) -> None:
|
||||
self.assertIsNone(_only_gguf_file(["model.safetensors", "model-q4_k_m.gguf"]))
|
||||
self.assertIsNone(
|
||||
_only_gguf_file(
|
||||
[
|
||||
"model.safetensors.index.json",
|
||||
"model-00001-of-00002.safetensors",
|
||||
"extra.gguf",
|
||||
]
|
||||
)
|
||||
)
|
||||
self.assertIsNone(
|
||||
_only_gguf_file(
|
||||
["pytorch_model.bin", "pytorch_model.bin.index.json", "model.gguf"]
|
||||
)
|
||||
)
|
||||
|
||||
def test_does_not_rank_several_model_files(self) -> None:
|
||||
self.assertIsNone(
|
||||
_only_gguf_file(
|
||||
[
|
||||
"weights-Q8_0.gguf",
|
||||
"weights-Q4_K_M.gguf",
|
||||
"weights-mmproj-f16.gguf",
|
||||
]
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
class GGUFLoadTests(unittest.TestCase):
|
||||
|
|
@ -114,92 +155,52 @@ class GGUFLoadTests(unittest.TestCase):
|
|||
self.assertIsInstance(config, GgufConfig)
|
||||
self.assertTrue(config.dequantize)
|
||||
|
||||
if settings.model_commit is not None:
|
||||
self.assertEqual(tokenizer_calls[0][1]["revision"], settings.model_commit)
|
||||
self.assertEqual(model_calls[0][1]["revision"], settings.model_commit)
|
||||
if files is not None:
|
||||
listing.assert_called_once_with(
|
||||
settings.model,
|
||||
revision=settings.model_commit,
|
||||
repo_type="model",
|
||||
)
|
||||
|
||||
message = "\n".join(messages)
|
||||
self.assertIn(settings.model, message)
|
||||
self.assertIn(gguf_file, message)
|
||||
self.assertIn("dense reconstruction", message)
|
||||
self.assertIn("not the original full-precision", message)
|
||||
self.assertIn("safetensors", message)
|
||||
self.assertNotIn("not supported", message)
|
||||
if files is None and list_side_effect is None:
|
||||
listing.assert_not_called()
|
||||
return message
|
||||
|
||||
def test_hub_gguf_repo_passes_model_file_not_mmproj(self) -> None:
|
||||
# Repro from https://github.com/p-e-w/heretic/issues/533
|
||||
# The id is not what is matched. The repo listing is: two .gguf files,
|
||||
# no safetensors. The projector sidecar is not the model.
|
||||
def test_hub_repo_passes_the_single_model_file(self) -> None:
|
||||
model = "google/gemma-4-26B-A4B-it-qat-q4_0-gguf"
|
||||
self._assert_dequantized_load(
|
||||
self._settings(model),
|
||||
model_id=model,
|
||||
gguf_file="gemma-4-26B_q4_0-it.gguf",
|
||||
files=_GEMMA_GGUF_FILES,
|
||||
)
|
||||
|
||||
def test_hub_gguf_repo_without_gguf_in_the_id(self) -> None:
|
||||
model = "someone/example-model-q4-k-m"
|
||||
filename = "example-model-q4_k_m.gguf"
|
||||
filename = "gemma-4-26B_q4_0-it.gguf"
|
||||
self._assert_dequantized_load(
|
||||
self._settings(model),
|
||||
model_id=model,
|
||||
gguf_file=filename,
|
||||
files=["README.md", filename],
|
||||
files=[
|
||||
".gitattributes",
|
||||
"README.md",
|
||||
"gemma-4-26B-it-mmproj.gguf",
|
||||
filename,
|
||||
],
|
||||
)
|
||||
|
||||
def test_passes_model_commit_when_listing_and_loading(self) -> None:
|
||||
model = "org/example"
|
||||
commit = "abc123def"
|
||||
self._assert_dequantized_load(
|
||||
tokenizer_calls, model_calls, _messages, listing = self._load_until_model(
|
||||
self._settings(model, model_commit=commit),
|
||||
model_id=model,
|
||||
gguf_file="model.gguf",
|
||||
files=["model.gguf"],
|
||||
)
|
||||
self.assertEqual(tokenizer_calls[0][1]["gguf_file"], "model.gguf")
|
||||
self.assertEqual(tokenizer_calls[0][1]["revision"], commit)
|
||||
self.assertEqual(model_calls[0][1]["revision"], commit)
|
||||
config = model_calls[0][1]["quantization_config"]
|
||||
self.assertIsInstance(config, GgufConfig)
|
||||
self.assertTrue(config.dequantize)
|
||||
listing.assert_called_once_with(model, revision=commit, repo_type="model")
|
||||
|
||||
def test_prefers_the_quant_closest_to_full_precision(self) -> None:
|
||||
model = "org/several-quants"
|
||||
files = [
|
||||
"README.md",
|
||||
"weights-Q4_K_M.gguf",
|
||||
"weights-Q2_K.gguf",
|
||||
"weights-Q8_0.gguf",
|
||||
"weights-mmproj-f16.gguf",
|
||||
]
|
||||
source = None
|
||||
with patch("heretic.model.list_repo_files", return_value=files):
|
||||
source = _resolve_gguf_checkpoint(model)
|
||||
assert source is not None
|
||||
self.assertEqual(source.gguf_file, "weights-Q8_0.gguf")
|
||||
self.assertEqual(
|
||||
source.alternatives,
|
||||
("weights-Q2_K.gguf", "weights-Q4_K_M.gguf"),
|
||||
)
|
||||
|
||||
message = self._assert_dequantized_load(
|
||||
self._settings(model),
|
||||
model_id=model,
|
||||
gguf_file="weights-Q8_0.gguf",
|
||||
files=files,
|
||||
)
|
||||
self.assertIn("weights-Q4_K_M.gguf", message)
|
||||
self.assertNotIn("mmproj", message)
|
||||
|
||||
def test_local_file_with_gguf_magic_passes_absolute_path(self) -> None:
|
||||
def test_local_gguf_file_is_passed_through(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
# The name is not a .gguf suffix. The header is.
|
||||
path = Path(tmp) / "weights.bin"
|
||||
path.write_bytes(b"GGUF" + b"\x00" * 8)
|
||||
root = Path(tmp)
|
||||
path = root / "weights.gguf"
|
||||
path.write_bytes(b"not-inspected")
|
||||
# An explicit file wins even when safetensors sit beside it.
|
||||
(root / "model.safetensors").write_bytes(b"st")
|
||||
resolved = path.resolve()
|
||||
self._assert_dequantized_load(
|
||||
self._settings(str(path)),
|
||||
|
|
@ -207,52 +208,52 @@ class GGUFLoadTests(unittest.TestCase):
|
|||
gguf_file=str(resolved),
|
||||
)
|
||||
|
||||
def test_local_directory_of_gguf_files(self) -> None:
|
||||
def test_local_directory_with_one_model_file(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
(root / "README.md").write_text("gguf only\n", encoding="utf-8")
|
||||
(root / "config.json").write_text("{}\n", encoding="utf-8")
|
||||
(root / "model.gguf").write_bytes(b"GGUF-not-a-real-file")
|
||||
(root / "mmproj.gguf").write_bytes(b"projector")
|
||||
model_file = root / "model.gguf"
|
||||
model_file.write_bytes(b"weights")
|
||||
resolved_root = root.resolve()
|
||||
self._assert_dequantized_load(
|
||||
self._settings(str(root)),
|
||||
model_id=str(resolved_root),
|
||||
gguf_file=str((root / "model.gguf").resolve()),
|
||||
gguf_file=str(model_file.resolve()),
|
||||
)
|
||||
|
||||
def test_bitsandbytes_is_not_combined_with_gguf(self) -> None:
|
||||
model = "org/quant"
|
||||
message = self._assert_dequantized_load(
|
||||
self._settings(model, quantization=QuantizationMethod.BNB_4BIT),
|
||||
model_id=model,
|
||||
gguf_file="model-Q4_0.gguf",
|
||||
files=["model-Q4_0.gguf"],
|
||||
self._settings("org/quant", quantization=QuantizationMethod.BNB_4BIT),
|
||||
model_id="org/quant",
|
||||
gguf_file="model.gguf",
|
||||
files=["model.gguf"],
|
||||
)
|
||||
self.assertIn("bitsandbytes", message)
|
||||
|
||||
def test_safetensors_repo_that_also_ships_gguf_is_left_alone(self) -> None:
|
||||
model = "org/Model_GGUF"
|
||||
files = [
|
||||
"config.json",
|
||||
"model.safetensors",
|
||||
"tokenizer.json",
|
||||
"model-q4_k_m.gguf",
|
||||
]
|
||||
tokenizer_calls, model_calls, messages, _listing = self._load_until_model(
|
||||
self._settings(model),
|
||||
files=files,
|
||||
self._settings("org/both"),
|
||||
files=["config.json", "model.safetensors", "model-q4_k_m.gguf"],
|
||||
)
|
||||
self.assertNotIn("gguf_file", tokenizer_calls[0][1])
|
||||
self.assertNotIn("gguf_file", model_calls[0][1])
|
||||
self.assertNotIn("quantization_config", model_calls[0][1])
|
||||
self.assertNotIn("dense reconstruction", "\n".join(messages))
|
||||
with patch("heretic.model.list_repo_files", return_value=files):
|
||||
self.assertIsNone(_resolve_gguf_checkpoint(model))
|
||||
|
||||
def test_several_gguf_files_are_not_guessed(self) -> None:
|
||||
tokenizer_calls, model_calls, messages, listing = self._load_until_model(
|
||||
self._settings("org/several-quants"),
|
||||
files=["weights-Q8_0.gguf", "weights-Q4_K_M.gguf"],
|
||||
)
|
||||
listing.assert_called_once()
|
||||
self.assertNotIn("gguf_file", tokenizer_calls[0][1])
|
||||
self.assertNotIn("gguf_file", model_calls[0][1])
|
||||
self.assertNotIn("dense reconstruction", "\n".join(messages))
|
||||
|
||||
def test_listing_failure_does_not_guess_from_the_repo_id(self) -> None:
|
||||
model = "org/model-q4_0-gguf"
|
||||
tokenizer_calls, model_calls, messages, listing = self._load_until_model(
|
||||
self._settings(model),
|
||||
self._settings("org/model-q4_0-gguf"),
|
||||
list_side_effect=OSError("hub unavailable"),
|
||||
)
|
||||
listing.assert_called()
|
||||
|
|
@ -260,22 +261,20 @@ class GGUFLoadTests(unittest.TestCase):
|
|||
self.assertNotIn("gguf_file", model_calls[0][1])
|
||||
self.assertNotIn("dense reconstruction", "\n".join(messages))
|
||||
|
||||
def test_evaluate_model_gguf_does_not_change_the_initial_load(self) -> None:
|
||||
# evaluate_model is swapped in later, by reset_model. The model loaded
|
||||
# at startup is still the base checkpoint.
|
||||
def test_evaluate_model_does_not_change_the_initial_load(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
evaluate_model = Path(tmp) / "gemma-q4_0.gguf"
|
||||
evaluate_model.write_bytes(b"GGUF")
|
||||
base = "google/gemma-2-2b-it"
|
||||
tokenizer_calls, model_calls, _messages, _listing = self._load_until_model(
|
||||
self._settings(base, evaluate_model=str(evaluate_model)),
|
||||
files=["config.json", "model.safetensors", "tokenizer.json"],
|
||||
files=["config.json", "model.safetensors"],
|
||||
)
|
||||
self.assertEqual(tokenizer_calls[0][0][0], base)
|
||||
self.assertNotIn("gguf_file", tokenizer_calls[0][1])
|
||||
self.assertNotIn("gguf_file", model_calls[0][1])
|
||||
|
||||
def test_reset_model_dequantizes_a_swapped_in_gguf_checkpoint(self) -> None:
|
||||
def test_reset_model_dequantizes_a_swapped_in_gguf_file(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
evaluate_model = Path(tmp) / "gemma-q4_0.gguf"
|
||||
evaluate_model.write_bytes(b"GGUF")
|
||||
|
|
@ -290,15 +289,12 @@ class GGUFLoadTests(unittest.TestCase):
|
|||
model.gguf_file = None
|
||||
model.pretrained_model_id = base
|
||||
model.loaded_from = base
|
||||
model._announced_gguf = set()
|
||||
model._gguf_alternatives = ()
|
||||
model.dtype = torch.float16
|
||||
model.max_memory = None
|
||||
model.trusted_models = set()
|
||||
model.model = MagicMock()
|
||||
model.model.config.name_or_path = base
|
||||
|
||||
# Same swap main() performs before evaluating another checkpoint.
|
||||
settings.model = str(evaluate_model)
|
||||
calls: list[tuple[tuple, dict]] = []
|
||||
|
||||
|
|
@ -340,79 +336,6 @@ class GGUFLoadTests(unittest.TestCase):
|
|||
self.assertTrue(model.reset_model())
|
||||
get_model_class.assert_not_called()
|
||||
|
||||
def test_offline_cache_listing_detects_gguf(self) -> None:
|
||||
repo = "org/cached-quant"
|
||||
commit = "abc123"
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp) / "models--org--cached-quant"
|
||||
snapshot = root / "snapshots" / commit
|
||||
snapshot.mkdir(parents=True)
|
||||
(snapshot / "weights.gguf").write_bytes(b"placeholder")
|
||||
(root / "refs").mkdir()
|
||||
(root / "refs" / "main").write_text(commit, encoding="utf-8")
|
||||
|
||||
with (
|
||||
patch.dict(os.environ, {"HF_HUB_CACHE": tmp}),
|
||||
patch(
|
||||
"heretic.model.list_repo_files",
|
||||
side_effect=OfflineModeIsEnabled("offline"),
|
||||
),
|
||||
):
|
||||
self.assertTrue(_is_gguf_checkpoint(repo))
|
||||
source = _resolve_gguf_checkpoint(repo)
|
||||
assert source is not None
|
||||
self.assertEqual(source.gguf_file, "weights.gguf")
|
||||
|
||||
def test_offline_cache_with_safetensors_is_not_gguf_only(self) -> None:
|
||||
repo = "org/cached-full"
|
||||
commit = "abc123"
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp) / "models--org--cached-full"
|
||||
snapshot = root / "snapshots" / commit
|
||||
snapshot.mkdir(parents=True)
|
||||
(snapshot / "model.safetensors").write_bytes(b"not-gguf")
|
||||
(snapshot / "extra.gguf").write_bytes(b"GGUF")
|
||||
(root / "refs").mkdir()
|
||||
(root / "refs" / "main").write_text(commit, encoding="utf-8")
|
||||
|
||||
with (
|
||||
patch.dict(os.environ, {"HF_HUB_CACHE": tmp}),
|
||||
patch(
|
||||
"heretic.model.list_repo_files",
|
||||
side_effect=OfflineModeIsEnabled("offline"),
|
||||
),
|
||||
):
|
||||
self.assertFalse(_is_gguf_checkpoint(repo))
|
||||
|
||||
def test_local_non_gguf_files_are_not_treated_as_gguf(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
fake = root / "model.gguf"
|
||||
fake.write_bytes(b"this is not a gguf file")
|
||||
safetensors = root / "model.safetensors"
|
||||
safetensors.write_bytes(b"not-a-real-safetensors")
|
||||
mixed = root / "mixed"
|
||||
mixed.mkdir()
|
||||
(mixed / "model.safetensors").write_bytes(b"st")
|
||||
(mixed / "also.gguf").write_bytes(b"GGUF-real-enough")
|
||||
|
||||
self.assertFalse(_is_gguf_checkpoint(str(fake)))
|
||||
self.assertFalse(_is_gguf_checkpoint(str(safetensors)))
|
||||
self.assertFalse(_is_gguf_checkpoint(str(mixed)))
|
||||
|
||||
def test_unreadable_id_is_not_treated_as_gguf(self) -> None:
|
||||
# Not a local file, and not something the Hub listing can resolve.
|
||||
# Do not guess from the name.
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
with patch.dict(os.environ, {"HF_HUB_CACHE": tmp}):
|
||||
self.assertFalse(_is_gguf_checkpoint(r"C:\models\bar.gguf"))
|
||||
with patch(
|
||||
"heretic.model.list_repo_files",
|
||||
side_effect=OSError("hub unavailable"),
|
||||
) as listing:
|
||||
self.assertFalse(_is_gguf_checkpoint("org/model.gguf.txt"))
|
||||
listing.assert_called_once()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
|
|||
Loading…
Reference in New Issue