Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.
Python cliconsumer-gpudpofine-tuningggufhuggingfacellmllmopslocal-ailocal-llmloralow-vrammachine-learningollamapeftpythonpytorchqlorasfttransformers
perf(quest): refuse a disqualifying local base before hashing it (#1199) (#1588)
Yunare Maia35197a6ef926
diff --git a/changelog.d/0.75.1/1588.changed.md b/changelog.d/0.75.1/1588.changed.mdnew file mode 100644index 00000000..7532cac3--- /dev/null+++ b/changelog.d/0.75.1/1588.changed.md@@ -0,0 +1 @@+- QuEST: refuse a local base whose `config.json` cannot satisfy the route before any weight file is read, instead of after the model loads. The 24-block count and the group-128 / power-of-two widths are now checked from the config the fingerprint already parses, so a base that was going to be refused is no longer loaded and no longer has every byte of its weights read and SHA-256-hashed — on `main` that was once per run, and it is now none. The refusal message is unchanged and the post-load topology gate still runs; a width that cannot be read from the config is left to that gate rather than guessed at. (#1199 by @yunaremaia in #1588)\ No newline at end of filediff --git a/docs/performance-and-quantization.md b/docs/performance-and-quantization.mdindex 3fc66960..f316bb39 100644--- a/docs/performance-and-quantization.md+++ b/docs/performance-and-quantization.md@@ -175,8 +175,11 @@ format-v2 metadata records a `local-sha256:` identity derived from theTransformers selects (or its index and referenced shards). The identity usesrelative file names and content, so moving the same base keeps resume valid;changing a selected file refuses resume. Soup checks the identity before and-after loading the model. The sidecar and `config.json["soup_quest"]` contain-the identity, not the source directory.+after loading the model. A local base whose `config.json` declares another+layer count or an incompatible width is refused before any file is hashed; a+value that is missing or not an integer is left to the post-load gate. The+sidecar and `config.json["soup_quest"]` contain the identity, not the source+directory.Local models or tokenizers using custom `auto_map` code are refused by thisfingerprint route because code loaded from elsewhere would not be covered.Local tokenizers declaring `fast_tokenizer_files` are also refused becausediff --git a/src/soup_cli/utils/quest.py b/src/soup_cli/utils/quest.pyindex b47e631f..ee0ab6b9 100644--- a/src/soup_cli/utils/quest.py+++ b/src/soup_cli/utils/quest.py@@ -65,6 +65,7 @@ SUFFIXES = (EXPECTED_MODULES = tuple(f"model.layers.{block}.{suffix}" for block in BLOCKS for suffix in SUFFIXES)+LAYER_COUNT_REFUSAL = "QuEST first slice requires the measured 24 blocks"A16_MODULES = tuple(f"model.layers.23.{suffix}" for suffix in SUFFIXES)ROUTE_PROVENANCE = {"schema_version": 1,@@ -113,14 +114,8 @@ _METADATA_KEYS = frozenset()-def _selected_local_model_files(root: Path) -> list[tuple[str, Path]]:- """Mirror the default local weight choice in AutoModelForCausalLM.from_pretrained.-- QuEST supplies no variant, subfolder, or use_safetensors override. A single- safetensors file takes precedence over its index, then PyTorch files. The- selected weights, their index, model configuration, and tokenizer inputs- bind the base.- """+def _read_local_config(root: Path) -> dict[str, Any]:+ """Read the base ``config.json`` and check the fingerprint's own contract."""config = root / "config.json"if not config.is_file():raise ValueError("QuEST local base requires config.json")@@ -130,7 +125,20 @@ def _selected_local_model_files(root: Path) -> list[tuple[str, Path]]:raise ValueError("QuEST local base config.json is unreadable") from excif not isinstance(config_data, dict) or config_data.get("auto_map"):raise ValueError("QuEST local base fingerprint requires a standard model config")+ return config_data+++def _selected_local_model_files(root: Path) -> list[tuple[str, Path]]:+ """Mirror the default local weight choice in AutoModelForCausalLM.from_pretrained.++ QuEST supplies no variant, subfolder, or use_safetensors override. A single+ safetensors file takes precedence over its index, then PyTorch files. The+ selected weights, their index, model configuration, and tokenizer inputs+ bind the base.+ """+ _read_local_config(root)+ config = root / "config.json"files: list[tuple[str, Path]] = [("config.json", config)]generation_config = root / "generation_config.json"if generation_config.is_file():@@ -229,6 +237,58 @@ def _hash_local_file(path: Path) -> tuple[int, str]:return before.st_size, digest.hexdigest()+def _config_topology(config_data: dict[str, Any]) -> dict[str, Any]:+ """Return the QuEST topology the local ``config.json`` already declares.++ A multimodal config keeps the text stack under ``text_config``; the route+ only ever adapts that stack, so prefer it when it is present.+ """+ nested = config_data.get("text_config")+ if isinstance(nested, dict):+ return {**config_data, **nested}+ return config_data+++def _local_topology_widths(config_data: dict[str, Any]) -> list[tuple[str, int]]:+ """Collect the input widths ``_validate_raw_topology`` will later measure.++ Only values present as real ints are returned. A width we cannot read is+ left to the post-load gate rather than guessed at here.+ """+ config = _config_topology(config_data)+ widths: list[tuple[str, int]] = []+ for field in ("hidden_size", "intermediate_size"):+ value = config.get(field)+ if type(value) is int:+ widths.append((field, value))+ heads = config.get("num_attention_heads")+ # ``o_proj`` takes num_attention_heads * head_dim, which a config may pin; with no+ # explicit head_dim it is as wide as hidden_size, which the loop above already checked.+ head_dim = config.get("head_dim")+ if type(heads) is int and type(head_dim) is int:+ widths.append(("num_attention_heads * head_dim", heads * head_dim))+ return widths+++def _refuse_disqualifying_local_topology(config_data: dict[str, Any]) -> None:+ """Gate a local base on the cheap parts of the topology before hashing it.++ ``_validate_raw_topology`` runs inside calibration, so on ``main`` a base+ that can never satisfy the route had every byte of its weights read and+ SHA-256-hashed first. This repeats the two checks that ``config.json``+ answers on its own — the block count and the group-128 / power-of-two+ widths — with the same refusal text the post-load gate uses. The module+ coverage, the dtype check and the topology that only a loaded model can+ show stay where they are; this narrows nothing, it only refuses earlier.+ """+ config = _config_topology(config_data)+ layers = config.get("num_hidden_layers")+ if type(layers) is int and layers != len(BLOCKS):+ raise ValueError(LAYER_COUNT_REFUSAL)+ for _field, width in _local_topology_widths(config_data):+ validate_group(width)++def resolve_base_model_identity(source: str) -> str:"""Keep Hub IDs intact; replace a local directory with its loaded-file digest."""if not isinstance(source, str) or not source:@@ -236,6 +296,7 @@ def resolve_base_model_identity(source: str) -> str:if not os.path.isdir(source):return sourceroot = Path(os.path.realpath(source))+ _refuse_disqualifying_local_topology(_read_local_config(root))files = _selected_local_model_files(root)digest = hashlib.sha256(b"soup.quest.local-base.v2\0")for name, path in files:@@ -336,8 +397,8 @@ def _validate_raw_topology(model: Any) -> dict[str, Any]:targets = _target_linears(model)layers = getattr(getattr(model, "model", None), "layers", None)- if layers is None or len(layers) != 24:- raise ValueError("QuEST first slice requires the measured 24 blocks")+ if layers is None or len(layers) != len(BLOCKS):+ raise ValueError(LAYER_COUNT_REFUSAL)if set(targets) != set(EXPECTED_MODULES) or len(targets) != 168:raise ValueError("QuEST calibration must cover exactly all 168 measured Llama transformer linears"diff --git a/tests/test_issue1162_quest_base_identity.py b/tests/test_issue1162_quest_base_identity.pyindex 1cc61bab..d4cf354d 100644--- a/tests/test_issue1162_quest_base_identity.py+++ b/tests/test_issue1162_quest_base_identity.py@@ -64,7 +64,11 @@ def test_selected_safetensors_matches_real_transformers_loader(tmp_path):LlamaConfig(hidden_size=128,intermediate_size=256,- num_hidden_layers=1,+ # 24, not 1: #1199 refuses a local base whose config.json declares+ # a layer count the measured route cannot cover, so a 1-layer toy+ # is no longer a legal local QuEST base. These two tests pin which+ # files are selected, for which the layer count is irrelevant.+ num_hidden_layers=24,num_attention_heads=4,vocab_size=256,)@@ -84,7 +88,8 @@ def test_sharded_safetensors_matches_real_transformers_loader(tmp_path):LlamaConfig(hidden_size=128,intermediate_size=256,- num_hidden_layers=1,+ # 24, not 1: see the note in the safetensors test above.+ num_hidden_layers=24,num_attention_heads=4,vocab_size=256,)diff --git a/tests/test_issue1199_quest_local_base_topology.py b/tests/test_issue1199_quest_local_base_topology.pynew file mode 100644index 00000000..8f0785ca--- /dev/null+++ b/tests/test_issue1199_quest_local_base_topology.py@@ -0,0 +1,264 @@+"""Issue #1199: a local QuEST base is refused on topology before it is hashed.++``_validate_raw_topology`` runs inside calibration, after ``AutoModelForCausalLM``+has already read every byte of the base. A base that can never satisfy the route+is therefore SHA-256-hashed in full twice before the gate refuses it. These+tests pin the pre-hash refusal and its ordering.+"""++from __future__ import annotations++import json+from pathlib import Path+from typing import Any++import pytest++from soup_cli.utils import quest+from soup_cli.utils.quest import resolve_base_model_identity++COMPATIBLE_WIDTHS = {+ "hidden_size": 1024,+ "intermediate_size": 4096,+ "num_attention_heads": 16,+}+++def _config(layers: int = 24, **overrides: Any) -> dict[str, Any]:+ return {+ "model_type": "llama",+ "num_hidden_layers": layers,+ **COMPATIBLE_WIDTHS,+ **overrides,+ }+++def _base(directory: Path, config: dict[str, Any], *, weights: bytes = b"safe-weights") -> Path:+ directory.mkdir(parents=True)+ (directory / "config.json").write_text(json.dumps(config), encoding="utf-8")+ (directory / "model.safetensors").write_bytes(weights)+ return directory+++def hashed_paths(monkeypatch: pytest.MonkeyPatch) -> list[str]:+ """Record every file whose content is read through ``_hash_local_file``."""+ reads: list[str] = []+ original = quest._hash_local_file++ def recording(path: Path) -> tuple[int, str]:+ reads.append(path.name)+ return original(path)++ monkeypatch.setattr(quest, "_hash_local_file", recording)+ return reads++[email protected]("layers", [16, 22, 30])+def test_wrong_layer_count_is_refused_before_a_weight_is_read(+ tmp_path: Path, hashed_paths, layers: int+):+ """Any other block count is refused, not only a larger one.++ A smaller base is the likelier mistake, so ``layers > len(BLOCKS)`` must not+ pass here: 16 and 22 would then hash a base that is refused later.+ """+ root = _base(tmp_path / "base", _config(layers=layers))++ with pytest.raises(ValueError, match="24 blocks"):+ resolve_base_model_identity(str(root))++ assert hashed_paths == []+++def test_narrow_width_is_refused_before_a_weight_is_read(tmp_path: Path, hashed_paths):+ """Qwen2.5-0.5B has exactly 24 layers; width 896 is what disqualifies it."""+ root = _base(+ tmp_path / "base",+ {+ "model_type": "qwen2",+ "num_hidden_layers": 24,+ "hidden_size": 896,+ "intermediate_size": 4864,+ "num_attention_heads": 14,+ },+ )++ with pytest.raises(ValueError, match="power-of-two input width"):+ resolve_base_model_identity(str(root))++ assert hashed_paths == []+++ ("field", "value"),+ [("hidden_size", 768), ("intermediate_size", 3000)],+)+def test_every_measured_width_is_gated_before_a_weight_is_read(+ tmp_path: Path, hashed_paths, field: str, value: int+):+ root = _base(tmp_path / "base", _config(**{field: value}))++ with pytest.raises(ValueError, match="power-of-two input width"):+ resolve_base_model_identity(str(root))++ assert hashed_paths == []+++def test_the_derived_attention_width_is_the_hidden_size(tmp_path: Path, hashed_paths):+ """With no explicit ``head_dim``, ``o_proj`` is as wide as ``hidden_size``.++ transformers derives ``head_dim = hidden_size // num_attention_heads``, so+ the attention width the gate measures is exactly the hidden width. Gating+ the head count separately would only add a way to refuse a base the+ post-load gate accepts.+ """+ root = _base(tmp_path / "base", _config(hidden_size=768, num_attention_heads=12))++ with pytest.raises(ValueError, match="power-of-two input width"):+ resolve_base_model_identity(str(root))++ assert hashed_paths == []+++def test_a_below_group_width_is_refused_before_a_weight_is_read(tmp_path: Path, hashed_paths):+ root = _base(tmp_path / "base", _config(hidden_size=64))++ with pytest.raises(ValueError, match="power-of-two input width"):+ resolve_base_model_identity(str(root))++ assert hashed_paths == []+++def test_nested_text_config_widths_are_gated(tmp_path: Path, hashed_paths):+ """A multimodal config carries the text stack under ``text_config``.++ The top-level ``hidden_size`` is compatible on purpose: the nested stack+ must win the merge, or the gate would read the wrong width.+ """+ root = _base(+ tmp_path / "base",+ {+ "model_type": "qwen3_vl",+ "hidden_size": 1024,+ "text_config": {"num_hidden_layers": 24, **COMPATIBLE_WIDTHS, "hidden_size": 896},+ },+ )++ with pytest.raises(ValueError, match="power-of-two input width"):+ resolve_base_model_identity(str(root))++ assert hashed_paths == []+++def test_a_compatible_base_is_still_fingerprinted(tmp_path: Path, hashed_paths):+ root = _base(tmp_path / "base", _config())++ identity = resolve_base_model_identity(str(root))++ assert identity.startswith(quest.LOCAL_BASE_PREFIX)+ assert hashed_paths == ["config.json", "model.safetensors"]+++def test_an_explicit_head_dim_is_gated(tmp_path: Path, hashed_paths):+ """``o_proj`` takes ``num_attention_heads * head_dim``; a config may set it."""+ root = _base(tmp_path / "base", _config(head_dim=300))++ with pytest.raises(ValueError, match="power-of-two input width"):+ resolve_base_model_identity(str(root))++ assert hashed_paths == []+++def test_a_sharded_compatible_base_is_still_fingerprinted(tmp_path: Path, hashed_paths):+ root = tmp_path / "base"+ root.mkdir()+ (root / "config.json").write_text(json.dumps(_config()), encoding="utf-8")+ (root / "model.safetensors.index.json").write_text(+ json.dumps({"weight_map": {"a": "model-00001-of-00002.safetensors"}}),+ encoding="utf-8",+ )+ (root / "model-00001-of-00002.safetensors").write_bytes(b"first")++ identity = resolve_base_model_identity(str(root))++ assert identity.startswith(quest.LOCAL_BASE_PREFIX)+ assert hashed_paths == [+ "config.json",+ "model.safetensors.index.json",+ "model-00001-of-00002.safetensors",+ ]+++ "config",+ [+ pytest.param({"model_type": "llama"}, id="no-topology-keys"),+ pytest.param({"model_type": "llama", "num_hidden_layers": 24}, id="widths-absent"),+ pytest.param(+ {"model_type": "llama", "num_hidden_layers": True, **COMPATIBLE_WIDTHS},+ id="bool-is-not-a-layer-count",+ ),+ pytest.param(+ {"model_type": "llama", "num_hidden_layers": "24", **COMPATIBLE_WIDTHS},+ id="string-layer-count",+ ),+ pytest.param(+ {"model_type": "llama", "num_hidden_layers": 24, "hidden_size": "1024"},+ id="string-width",+ ),+ pytest.param(+ {"model_type": "llama", "num_hidden_layers": 24, "hidden_size": True},+ id="bool-is-not-a-width",+ ),+ ],+)+def test_an_unreadable_topology_is_left_to_the_post_load_gate(+ tmp_path: Path, hashed_paths, config: dict[str, Any]+):+ """Only a value we can positively disqualify refuses early; the rest loads.++ Refusing on a value we merely cannot parse would reject bases that the+ post-load gate would accept.+ """+ root = _base(tmp_path / "base", config)++ identity = resolve_base_model_identity(str(root))++ assert identity.startswith(quest.LOCAL_BASE_PREFIX)+ assert hashed_paths == ["config.json", "model.safetensors"]+++def test_a_malformed_config_is_still_refused(tmp_path: Path, hashed_paths):+ """The fingerprint's own contract is unchanged by the topology gate."""+ root = tmp_path / "base"+ root.mkdir()+ (root / "config.json").write_text("{not json", encoding="utf-8")+ (root / "model.safetensors").write_bytes(b"safe-weights")++ with pytest.raises(ValueError, match="config.json is unreadable"):+ resolve_base_model_identity(str(root))++ assert hashed_paths == []+++def test_a_hub_id_is_returned_unchanged(hashed_paths):+ assert resolve_base_model_identity("owner/model") == "owner/model"+ assert hashed_paths == []+++def test_both_layer_count_refusals_are_the_constant_verbatim(tmp_path: Path):+ """`match="24 blocks"` would also accept a drifted message; compare the whole text."""+ torch = pytest.importorskip("torch")++ model = torch.nn.Module()+ model.model = torch.nn.Module()+ model.model.layers = torch.nn.ModuleList(torch.nn.Identity() for _ in range(30))+ with pytest.raises(ValueError) as post_load:+ quest._validate_raw_topology(model)++ root = _base(tmp_path / "base", _config(layers=30))+ with pytest.raises(ValueError) as pre_hash:+ resolve_base_model_identity(str(root))++ assert str(post_load.value) == str(pre_hash.value) == quest.LAYER_COUNT_REFUSAL