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
fix(export): diagnose unsupported GGUF architectures before setup (#1955)
Nurkhan Esenbek08a57d50ddfd
diff --git a/changelog.d/0.76.0/1955.fixed.md b/changelog.d/0.76.0/1955.fixed.mdnew file mode 100644index 00000000..1634f68a--- /dev/null+++ b/changelog.d/0.76.0/1955.fixed.md@@ -0,0 +1 @@+- Diagnose unsupported text architectures before a fresh default GGUF converter clone or dependency/conversion work, using generated capabilities from the exact llama.cpp pin; probe explicit, environment-selected and cached converters independently, preserve inconclusive probe behavior, validate nested text metadata and clean temporary adapter merges on refusal. The shared b5270 pin is unchanged. (#1911 by @kok-o in #1955)diff --git a/docs/serving-and-export.md b/docs/serving-and-export.mdindex 75fd075d..6a5c53ed 100644--- a/docs/serving-and-export.md+++ b/docs/serving-and-export.md@@ -82,11 +82,45 @@ of the last 100 lines (up to 2,000 characters per line) for that summary.`--no-install-deps` checks `gguf`, `sentencepiece` and `protobuf` in Soup's Pythonenvironment and refuses with the missing package names before merging an adapter-or looking up/cloning the toolchain. It never runs pip. Install the packages through+or cloning/running the toolchain. It never runs pip. Install the packages throughyour environment manager and retry. This flag does not disable toolchain lookup orcloning; use `--llama-cpp` to supply your own checkout. Both new flags apply only to`--format gguf`; other formats refuse them rather than ignore them.+### Converter compatibility++For a fresh default auto-clone, Soup checks the effective text architecture in+`config.json` against capability data generated from the exact `b5270` converter.+`text_config.architectures`, when present, takes precedence over the root's+architecture, as in that converter. Known unsupported architectures are refused+before cloning, installing dependencies, converting or quantizing, with a+`--llama-cpp <dir>` hint. Malformed metadata has a separate diagnostic; metadata+reads are limited to 1 MiB. An adapter is checked after its temporary merge, and+that temporary directory is cleaned up on refusal.++Explicit `--llama-cpp`, `LLAMA_CPP_PATH` and cached checkouts can be newer than the+default pin. Soup probes their own `--print-supported-models` output (TEXT group,+including stderr), with a 15-second timeout. A failed or unrecognized probe is+inconclusive: conversion remains the final check, without applying the default+pin's capability set to that checkout. No runtime network lookup is added.++The shared pin remains `b5270`; this diagnostic does not enable Qwen3.5 export on+that version. A compatible selected converter may need additional handling such+as the MTP boundary tracked in [#1912](https://github.com/MakazhanAlpamys/Soup/issues/1912).++To regenerate capabilities when changing the pin, obtain the unmodified+`convert_hf_to_gguf.py` from its immutable upstream commit, then run:++```bash+python scripts/gen_llama_cpp_capabilities.py --converter /path/to/convert_hf_to_gguf.py \+ --tag b5270 --commit 3bf785f3efa89ed28294fbf73054558a2b034bfb+```++The generated `src/soup_cli/utils/llama_cpp_capabilities.json` records the tag,+commit, source URL, SHA-256 and Git blob identity. The generator parses registered+classes and inherited model kinds without importing or executing upstream code.+The pin/data guard rejects a changed pin until its capabilities are regenerated.+### Building llama.cpp (required for quantized GGUF)Soup auto-clones llama.cpp (pinned tag `b5270`) to `~/.soup/llama.cpp` on first use,diff --git a/scripts/gen_llama_cpp_capabilities.py b/scripts/gen_llama_cpp_capabilities.pynew file mode 100644index 00000000..cdb56a4f--- /dev/null+++ b/scripts/gen_llama_cpp_capabilities.py@@ -0,0 +1,99 @@+"""Generate offline capabilities from the exact pinned llama.cpp converter AST.++Supply the unmodified convert_hf_to_gguf.py from the recorded commit. This script+never imports the converter or fetches source at runtime. See docs/serving-and-export.md.+"""++from __future__ import annotations++import argparse+import ast+import hashlib+import json+import re+from pathlib import Path++ROOT = Path(__file__).resolve().parents[1]+OUTPUT = ROOT / "src/soup_cli/utils/llama_cpp_capabilities.json"+++def extract_capabilities(source: bytes) -> dict[str, list[str]]:+ """Resolve the same class inheritance/model_arch rule as ModelBase.register."""+ tree = ast.parse(source)+ classes = {node.name: node for node in tree.body if isinstance(node, ast.ClassDef)}++ def model_arch(name: str, visited: frozenset[str] = frozenset()) -> str | None:+ if name in visited:+ raise ValueError(f"cyclic converter class inheritance: {name}")+ node = classes[name]+ for statement in node.body:+ if (isinstance(statement, ast.Assign)+ and any(isinstance(target, ast.Name) and target.id == "model_arch"+ for target in statement.targets)):+ if not isinstance(statement.value, ast.Attribute):+ raise ValueError(f"unrecognized model_arch on {name}")+ return statement.value.attr+ for base in node.bases:+ if isinstance(base, ast.Name) and base.id in classes:+ value = model_arch(base.id, visited | {name})+ if value is not None:+ return value+ return None++ kinds: dict[str, set[str]] = {"TEXT": set(), "VISION": set()}+ for node in classes.values():+ for decorator in node.decorator_list:+ if (isinstance(decorator, ast.Call)+ and isinstance(decorator.func, ast.Attribute)+ and isinstance(decorator.func.value, ast.Name)+ and decorator.func.value.id == "ModelBase"+ and decorator.func.attr == "register"):+ arch = model_arch(node.name)+ if arch is None or not decorator.args or decorator.keywords:+ raise ValueError(f"unrecognized registration on {node.name}")+ kind = "VISION" if arch == "CLIP_VISION" else "TEXT"+ for argument in decorator.args:+ name = ast.literal_eval(argument)+ if not isinstance(name, str) or not name:+ raise ValueError(f"non-string architecture on {node.name}")+ kinds[kind].add(name)+ if not kinds["TEXT"]:+ raise ValueError("converter has no recognized text registrations")+ return {kind: sorted(names) for kind, names in kinds.items()}+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--converter", type=Path, required=True)+ parser.add_argument("--commit", required=True)+ parser.add_argument("--tag", required=True)+ parser.add_argument("--output", type=Path, default=OUTPUT)+ arguments = parser.parse_args()+ export_tree = ast.parse((ROOT / "src/soup_cli/commands/export.py").read_text(encoding="utf-8"))+ pin = next(ast.literal_eval(node.value) for node in export_tree.body+ if isinstance(node, ast.Assign)+ and any(isinstance(target, ast.Name) and target.id == "LLAMA_CPP_TAG"+ for target in node.targets))+ if arguments.tag != pin:+ parser.error(f"--tag must match LLAMA_CPP_TAG={pin}")+ if not re.fullmatch(r"[0-9a-f]{40}", arguments.commit):+ parser.error("--commit must be a full immutable Git commit SHA")+ source = arguments.converter.read_bytes()+ # Record both the file hash and Git's blob identity, not a reformatted copy.+ blob = f"blob {len(source)}\0".encode() + source+ manifest = {+ "schema_version": 1,+ "tag": arguments.tag,+ "commit": arguments.commit,+ "source_url": (+ f"https://github.com/ggml-org/llama.cpp/blob/{arguments.commit}/convert_hf_to_gguf.py"+ ),+ "source_sha256": hashlib.sha256(source).hexdigest(),+ "source_git_blob": hashlib.sha1(blob).hexdigest(),+ "architectures": extract_capabilities(source),+ }+ arguments.output.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")+++if __name__ == "__main__":+ main()diff --git a/src/soup_cli/commands/export.py b/src/soup_cli/commands/export.pyindex 7107b2aa..a33b6387 100644--- a/src/soup_cli/commands/export.py+++ b/src/soup_cli/commands/export.py@@ -348,6 +348,9 @@ def export()raise typer.Exit(1)+ if not (model_path / "adapter_config.json").exists():+ _check_gguf_capabilities(model_path, llama_cpp_path, probe_selected=not no_install_deps)+# --- Resolve the destination before any merge/convert work ---# #1445 — a missing output parent used to surface as FileNotFoundError# from mkdtemp AFTER an adapter was merged, and the cleanup then deleted@@ -362,6 +365,8 @@ def export(if no_install_deps:console.print("[dim]GGUF: dependencies (managed environment)...[/]")_install_convert_deps(install=False)+ if not (model_path / "adapter_config.json").exists():+ _check_gguf_capabilities(model_path, llama_cpp_path)output_path.parent.mkdir(parents=True, exist_ok=True)@@ -387,6 +392,12 @@ def export()model_path = merge_dir+ try:+ _check_gguf_capabilities(model_path, llama_cpp_path)+ except typer.Exit:+ shutil.rmtree(merge_dir, ignore_errors=True)+ raise+# --- Find llama.cpp ---console.print("[dim]GGUF: toolchain lookup...[/]")llama_dir = _find_llama_cpp(llama_cpp_path)@@ -615,14 +626,8 @@ def _install_convert_deps(*, install: bool = True) -> None:)-def _find_llama_cpp(user_path: Optional[str] = None) -> Path:- """Find or clone llama.cpp directory.-- Looking only. The convert-script dependencies are installed by the caller,- once, just before conversion (#144 G2) — a lookup that silently shells out to- pip is a surprise, and it made an existing test that mocks ``subprocess.run``- to detect clone attempts see a pip call instead.- """+def _existing_llama_cpp(user_path: Optional[str] = None) -> Optional[Path]:+ """Select an existing explicit, environment or cached checkout without cloning."""from soup_cli.utils.constants import SOUP_DIR# 1. User-specified path@@ -651,6 +656,53 @@ def _find_llama_cpp(user_path: Optional[str] = None) -> Path:soup_llama = Path.home() / SOUP_DIR / LLAMA_CPP_DIR_NAMEif soup_llama.exists() and (soup_llama / "convert_hf_to_gguf.py").exists():return soup_llama+ return None+++def _check_gguf_capabilities(+ model: Path, user_path: Optional[str], *, probe_selected: bool = True,+) -> None:+ from soup_cli.utils.gguf_capabilities import (+ model_text_architecture,+ pinned_text_architectures,+ probe_text_architectures,+ )++ try:+ architecture = model_text_architecture(model)+ selected = _existing_llama_cpp(user_path)+ if selected is None:+ supported = pinned_text_architectures(LLAMA_CPP_TAG)+ toolchain = f"default llama.cpp {LLAMA_CPP_TAG}"+ else:+ if not probe_selected:+ return+ supported = probe_text_architectures(selected / "convert_hf_to_gguf.py")+ toolchain = f"selected converter {selected}"+ if supported is None:+ console.print(+ "[dim]GGUF: capability probe inconclusive; the selected converter "+ "will validate the architecture during conversion.[/]"+ )+ return+ if architecture not in supported:+ raise ValueError(+ f"Architecture {architecture!r} is not supported for text conversion by "+ f"{toolchain}. Select a compatible checkout with --llama-cpp <dir>."+ )+ except ValueError as exc:+ console.print(f"[red]{for_terminal(str(exc))}[/]")+ raise typer.Exit(1) from exc+++def _find_llama_cpp(user_path: Optional[str] = None) -> Path:+ """Find or clone llama.cpp, without installing conversion dependencies (#144 G2)."""+ from soup_cli.utils.constants import SOUP_DIR++ selected = _existing_llama_cpp(user_path)+ if selected is not None:+ return selected+ soup_llama = Path.home() / SOUP_DIR / LLAMA_CPP_DIR_NAME# 4. Auto-cloneconsole.print("[yellow]llama.cpp not found. Cloning to ~/.soup/llama.cpp...[/]")diff --git a/src/soup_cli/utils/gguf_capabilities.py b/src/soup_cli/utils/gguf_capabilities.pynew file mode 100644index 00000000..6a7bcb38--- /dev/null+++ b/src/soup_cli/utils/gguf_capabilities.py@@ -0,0 +1,79 @@+"""Read model metadata and probe the selected text GGUF converter's capabilities."""++from __future__ import annotations++import json+import re+import subprocess+import sys+from pathlib import Path+++def model_text_architecture(model: Path) -> str:+ """Match the converter's root architecture and optional text-config override."""+ path = model / "config.json"+ try:+ with path.open("rb") as handle:+ raw = handle.read(1024 * 1024 + 1)+ if len(raw) > 1024 * 1024:+ raise ValueError("config exceeds the 1 MiB metadata limit")+ config = json.loads(raw)+ if not isinstance(config, dict):+ raise ValueError("config must be a JSON object")++ def architecture(value: object, field: str) -> str:+ if (not isinstance(value, list) or not value or not isinstance(value[0], str)+ or not value[0].strip()):+ raise ValueError(f"{field} must be a nonempty list with a string architecture")+ return value[0]++ result = architecture(config.get("architectures"), "architectures")+ text = config.get("text_config", {})+ if not isinstance(text, dict):+ raise ValueError("text_config must be an object")+ if text.get("architectures") is not None:+ result = architecture(text["architectures"], "text_config.architectures")+ return result+ except (OSError, UnicodeError, ValueError) as exc:+ raise ValueError(f"Invalid GGUF model metadata in {path}: {exc}") from exc+++def pinned_text_architectures(tag: str) -> frozenset[str]:+ """Load generated capabilities; a pin change requires regenerating the data."""+ path = Path(__file__).with_name("llama_cpp_capabilities.json")+ data = json.loads(path.read_text(encoding="utf-8"))+ if data["tag"] != tag:+ raise ValueError(+ f"llama.cpp pin {tag} does not match generated capability data {data['tag']}; "+ "regenerate it with scripts/gen_llama_cpp_capabilities.py"+ )+ return frozenset(data["architectures"]["TEXT"])+++def probe_text_architectures(converter: Path) -> frozenset[str] | None:+ """Return advertised TEXT models, or None when the probe is inconclusive.++ b5270 writes grouped capabilities to stderr. A nonzero exit, timeout, missing+ interpreter/dependency or an unrecognized/empty listing proves no exclusion.+ """+ try:+ result = subprocess.run(+ [sys.executable, str(converter), "--print-supported-models"],+ capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=15,+ )+ except (OSError, subprocess.SubprocessError):+ return None+ if result.returncode != 0:+ return None+ names: set[str] = set()+ for output in (result.stderr, result.stdout):+ kind = None+ for line in output.splitlines():+ heading = re.search(r"(?:^|:)\s*(TEXT|VISION) models:\s*$", line)+ if heading:+ kind = heading[1]+ continue+ entry = re.search(r"(?:^|:)\s*-\s+([A-Za-z0-9_]+)\s*$", line)+ if kind == "TEXT" and entry:+ names.add(entry[1])+ return frozenset(names) if names else Nonediff --git a/src/soup_cli/utils/llama_cpp_capabilities.json b/src/soup_cli/utils/llama_cpp_capabilities.jsonnew file mode 100644index 00000000..03c98eaf--- /dev/null+++ b/src/soup_cli/utils/llama_cpp_capabilities.json@@ -0,0 +1,118 @@+{+ "schema_version": 1,+ "tag": "b5270",+ "commit": "3bf785f3efa89ed28294fbf73054558a2b034bfb",+ "source_url": "https://github.com/ggml-org/llama.cpp/blob/3bf785f3efa89ed28294fbf73054558a2b034bfb/convert_hf_to_gguf.py",+ "source_sha256": "b69d3b6a51636b580966bf931088fa095d88cd3f13bc91083eb85b29c23eb05e",+ "source_git_blob": "838999531e58041976c8e612bc97b382874bf227",+ "architectures": {+ "TEXT": [+ "ArcticForCausalLM",+ "BaiChuanForCausalLM",+ "BaichuanForCausalLM",+ "BailingMoeForCausalLM",+ "BertForMaskedLM",+ "BertModel",+ "BitnetForCausalLM",+ "BloomForCausalLM",+ "BloomModel",+ "CamembertModel",+ "ChameleonForCausalLM",+ "ChameleonForConditionalGeneration",+ "ChatGLMForConditionalGeneration",+ "ChatGLMModel",+ "CodeShellForCausalLM",+ "Cohere2ForCausalLM",+ "CohereForCausalLM",+ "DbrxForCausalLM",+ "DeciLMForCausalLM",+ "DeepseekForCausalLM",+ "DeepseekV2ForCausalLM",+ "DeepseekV3ForCausalLM",+ "ExaoneForCausalLM",+ "FalconForCausalLM",+ "FalconMambaForCausalLM",+ "GPT2LMHeadModel",+ "GPTBigCodeForCausalLM",+ "GPTNeoXForCausalLM",+ "GPTRefactForCausalLM",+ "Gemma2ForCausalLM",+ "Gemma3ForCausalLM",+ "Gemma3ForConditionalGeneration",+ "GemmaForCausalLM",+ "Glm4ForCausalLM",+ "GlmForCausalLM",+ "GraniteForCausalLM",+ "GraniteMoeForCausalLM",+ "GrokForCausalLM",+ "InternLM2ForCausalLM",+ "InternLM3ForCausalLM",+ "JAISLMHeadModel",+ "JinaBertForMaskedLM",+ "JinaBertModel",+ "LLaMAForCausalLM",+ "Llama4ForConditionalGeneration",+ "LlamaForCausalLM",+ "LlavaForConditionalGeneration",+ "LlavaStableLMEpochForCausalLM",+ "MPTForCausalLM",+ "MT5ForConditionalGeneration",+ "MambaForCausalLM",+ "MambaLMHeadModel",+ "MiniCPM3ForCausalLM",+ "MiniCPMForCausalLM",+ "Mistral3ForConditionalGeneration",+ "MistralForCausalLM",+ "MixtralForCausalLM",+ "NemotronForCausalLM",+ "NomicBertModel",+ "OLMoForCausalLM",+ "Olmo2ForCausalLM",+ "OlmoForCausalLM",+ "OlmoeForCausalLM",+ "OpenELMForCausalLM",+ "OrionForCausalLM",+ "PLMForCausalLM",+ "Phi3ForCausalLM",+ "PhiForCausalLM",+ "PhiMoEForCausalLM",+ "PlamoForCausalLM",+ "QWenLMHeadModel",+ "Qwen2ForCausalLM",+ "Qwen2Model",+ "Qwen2MoeForCausalLM",+ "Qwen2VLForConditionalGeneration",+ "Qwen2_5_VLForConditionalGeneration",+ "Qwen3ForCausalLM",+ "Qwen3MoeForCausalLM",+ "RWForCausalLM",+ "RWKV6Qwen2ForCausalLM",+ "RWKV7ForCausalLM",+ "RobertaModel",+ "Rwkv6ForCausalLM",+ "Rwkv7ForCausalLM",+ "RwkvHybridForCausalLM",+ "StableLMEpochForCausalLM",+ "StableLmForCausalLM",+ "Starcoder2ForCausalLM",+ "T5EncoderModel",+ "T5ForConditionalGeneration",+ "T5WithLMHeadModel",+ "UMT5ForConditionalGeneration",+ "VLlama3ForCausalLM",+ "WavTokenizerDec",+ "XLMRobertaForSequenceClassification",+ "XLMRobertaModel",+ "XverseForCausalLM"+ ],+ "VISION": [+ "Gemma3ForConditionalGeneration",+ "Idefics3ForConditionalGeneration",+ "LlavaForConditionalGeneration",+ "Mistral3ForConditionalGeneration",+ "Qwen2VLForConditionalGeneration",+ "Qwen2_5_VLForConditionalGeneration",+ "SmolVLMForConditionalGeneration"+ ]+ }+}diff --git a/tests/test_gguf_converter_capabilities.py b/tests/test_gguf_converter_capabilities.pynew file mode 100644index 00000000..d67d70f9--- /dev/null+++ b/tests/test_gguf_converter_capabilities.py@@ -0,0 +1,280 @@+"""#1911: diagnose converter capability before expensive GGUF work."""++import json+import subprocess+import sys+from pathlib import Path+from types import SimpleNamespace++import pytest+from typer.testing import CliRunner++from soup_cli.cli import app+from soup_cli.commands import export as export_mod+from tests.conftest import strip_ansi+++def _converter(path: Path, text: tuple[str, ...], *, vision=(), failed=False) -> None:+ path.mkdir(parents=True, exist_ok=True)+ output = "Supported models:\nERROR:hf-to-gguf:TEXT models:\n"+ output += "".join(f"ERROR:hf-to-gguf: - {name}\n" for name in text)+ output += "ERROR:hf-to-gguf:VISION models:\n"+ output += "".join(f"ERROR:hf-to-gguf: - {name}\n" for name in vision)+ (path / "convert_hf_to_gguf.py").write_text(+ "import sys\n"+ f"sys.stderr.write({output!r})\n"+ f"sys.exit({1 if failed else 0})\n", encoding="utf-8",+ )+++def export_flow(tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ monkeypatch.delenv("LLAMA_CPP_PATH", raising=False)+ home = tmp_path / "home"+ home.mkdir()+ monkeypatch.setattr(Path, "home", lambda: home)+ calls = []+ original_run = subprocess.run++ def run(command, **kwargs):+ if command[:2] == ["git", "clone"]:+ calls.append("clone")+ _converter(Path(command[-1]), ("LlamaForCausalLM",))+ return subprocess.CompletedProcess(command, 0, "", "")+ if "--print-supported-models" in command:+ calls.append("probe")+ return original_run(command, **kwargs)++ def convert(script, model, output, outtype, **kwargs):+ calls.append("convert")+ output.write_bytes(b"synthetic conversion")++ def quantize(llama, source, output, quant, **kwargs):+ calls.append("quantize")+ output.write_bytes(b"synthetic quantization")++ monkeypatch.setattr(subprocess, "run", run)+ monkeypatch.setattr(export_mod, "_install_convert_deps", lambda **kwargs: calls.append("deps"))+ monkeypatch.setattr(export_mod, "_run_convert", convert)+ monkeypatch.setattr(export_mod, "_run_quantize", quantize)+ monkeypatch.setattr(export_mod, "_maybe_attach_export", lambda **kwargs: None)++ def invoke(config, *, selection=None, converter_text=("Qwen3_5ForCausalLM",),+ converter_vision=(), failed=False, managed=False, adapter=False):+ model = tmp_path / "model"+ model.mkdir(exist_ok=True)+ if config is not None and not adapter:+ (model / "config.json").write_text(+ config if isinstance(config, str) else json.dumps(config), encoding="utf-8",+ )+ if adapter:+ (model / "adapter_config.json").write_text(+ '{"base_model_name_or_path":"synthetic-base"}', encoding="utf-8",+ )++ def merge(source, base, output, trust_remote_code=False):+ calls.append("merge")+ Path(output).mkdir()+ (Path(output) / "config.json").write_text(json.dumps(config), encoding="utf-8")++ monkeypatch.setattr(export_mod, "_merge_adapter", merge)+ arguments = ["export", "--model", str(model), "--output", str(tmp_path / "out.gguf")]+ if managed:+ arguments.append("--no-install-deps")+ if selection:+ converter_dir = (home / ".soup" / "llama.cpp" if selection == "cached" else+ tmp_path / "new-llama.cpp")+ _converter(converter_dir, converter_text, vision=converter_vision, failed=failed)+ if selection == "explicit":+ arguments += ["--llama-cpp", str(converter_dir)]+ elif selection == "env":+ monkeypatch.setenv("LLAMA_CPP_PATH", str(converter_dir))+ result = CliRunner().invoke(app, arguments)+ # Rich may emit per-character style sequences under FORCE_COLOR=1.+ return SimpleNamespace(exit_code=result.exit_code, output=strip_ansi(result.output),+ exception=result.exception), calls++ return invoke++[email protected]("managed", [False, True])+def test_unsupported_fresh_default_refuses_before_any_work(export_flow, managed):+ result, calls = export_flow({"architectures": ["Qwen3_5ForCausalLM"]}, managed=managed)+ assert result.exit_code == 1, result.output+ assert "Qwen3_5ForCausalLM" in result.output+ assert "b5270" in result.output+ assert "--llama-cpp" in result.output+ assert calls == []+++def test_supported_fresh_default_still_exports(export_flow):+ result, calls = export_flow({"architectures": ["LlamaForCausalLM"]})+ assert result.exit_code == 0, (result.output, result.exception)+ assert calls == ["clone", "deps", "convert", "quantize"]++[email protected]("architecture,allowed", [+ ("LlamaForCausalLM", True), ("Qwen3_5ForCausalLM", False),+])+def test_adapter_checks_merged_metadata_and_cleans_up(export_flow, tmp_path, architecture, allowed):+ result, calls = export_flow({"architectures": [architecture]}, adapter=True)+ assert result.exit_code == (0 if allowed else 1), (result.output, result.exception)+ assert calls == (["merge", "clone", "deps", "convert", "quantize"] if allowed else ["merge"])+ assert not (tmp_path / ".soup_merge_tmp_model").exists()+++def test_managed_missing_dependencies_refuse_before_running_selected_converter(+ export_flow, monkeypatch,+):+ calls = []++ def missing(*, install=True):+ import typer++ assert install is False+ calls.append("managed refusal")+ raise typer.Exit(1)++ monkeypatch.setattr(export_mod, "_install_convert_deps", missing)+ result, work = export_flow({"architectures": ["LlamaForCausalLM"]}, selection="explicit",+ converter_text=("LlamaForCausalLM",), managed=True)+ assert result.exit_code == 1+ assert work == []+ assert calls == ["managed refusal"]++[email protected]("selection", ["explicit", "env", "cached"])+def test_selected_newer_converter_uses_its_own_capabilities(export_flow, selection):+ result, calls = export_flow({"architectures": ["Qwen3_5ForCausalLM"]}, selection=selection)+ assert result.exit_code == 0, (result.output, result.exception)+ assert calls == ["probe", "deps", "convert", "quantize"]++[email protected]("failed", [False, True])+def test_unavailable_capability_probe_is_inconclusive(export_flow, failed):+ result, calls = export_flow({"architectures": ["Qwen3_5ForCausalLM"]}, selection="explicit",+ converter_text=(), failed=failed)+ assert result.exit_code == 0, (result.output, result.exception)+ assert calls == ["probe", "deps", "convert", "quantize"]+++def test_vision_support_does_not_imply_text_support(export_flow):+ result, calls = export_flow({"architectures": ["Qwen3_5ForCausalLM"]}, selection="explicit",+ converter_text=("LlamaForCausalLM",),+ converter_vision=("Qwen3_5ForCausalLM",))+ assert result.exit_code == 1, result.output+ assert "Qwen3_5ForCausalLM" in result.output+ assert "--llama-cpp" in result.output+ assert calls == ["probe"]++[email protected]("root,nested,allowed", [+ ("Qwen3_5ForCausalLM", "LlamaForCausalLM", True),+ ("LlamaForCausalLM", "Qwen3_5ForCausalLM", False),+])+def test_nested_text_architecture_takes_precedence(export_flow, root, nested, allowed):+ result, calls = export_flow({"architectures": [root],+ "text_config": {"architectures": [nested]}})+ assert result.exit_code == (0 if allowed else 1), result.output+ assert calls == (["clone", "deps", "convert", "quantize"] if allowed else [])+++def test_null_nested_architectures_keeps_root_architecture(export_flow):+ result, _ = export_flow({"architectures": ["LlamaForCausalLM"],+ "text_config": {"architectures": None}})+ assert result.exit_code == 0, (result.output, result.exception)++[email protected]("config", [+ None, "{bad", [], {}, {"architectures": []}, {"architectures": "LlamaForCausalLM"},+ {"architectures": [None]}, {"architectures": ["LlamaForCausalLM"], "text_config": []},+ {"architectures": ["LlamaForCausalLM"], "text_config": {"architectures": []}},+])[email protected]("console_width", [40, 80, 120])+def test_malformed_metadata_has_its_own_diagnostic_without_work(+ export_flow, config, console_width, monkeypatch,+):+ from rich.console import Console++ monkeypatch.setattr(export_mod, "console", Console(width=console_width))+ result, calls = export_flow(config)+ assert result.exit_code == 1, result.output+ # Rich may fold a long POSIX path inside the filename on a narrow terminal.+ plain = strip_ansi(result.output).replace("\n", "")+ assert "metadata" in plain.lower()+ assert "config.json" in plain+ assert calls == []+++def test_generated_capabilities_match_pin_and_record_immutable_source():+ from soup_cli.utils.gguf_capabilities import pinned_text_architectures++ path = Path(export_mod.__file__).parents[1] / "utils/llama_cpp_capabilities.json"+ data = json.loads(path.read_text(encoding="utf-8"))+ assert data["tag"] == export_mod.LLAMA_CPP_TAG+ assert data["commit"] == "3bf785f3efa89ed28294fbf73054558a2b034bfb"+ assert data["source_git_blob"] == "838999531e58041976c8e612bc97b382874bf227"+ assert data["source_url"].endswith(f'{data["commit"]}/convert_hf_to_gguf.py')+ supported = pinned_text_architectures(export_mod.LLAMA_CPP_TAG)+ assert {"LlamaForCausalLM", "GPT2LMHeadModel", "Qwen2ForCausalLM"} <= supported+ assert "Qwen3_5ForCausalLM" not in supported+ with pytest.raises(ValueError, match="regenerate"):+ pinned_text_architectures("changed-pin")+++def test_generator_resolves_inheritance_and_keeps_model_kinds_separate():+ from scripts.gen_llama_cpp_capabilities import extract_capabilities++ source = b'''+raise AssertionError("source must never execute")+class ModelBase: pass+class TextModel(ModelBase): model_arch = gguf.MODEL_ARCH.LLAMA+class VisionModel(ModelBase): model_arch = gguf.MODEL_ARCH.CLIP_VISION[email protected]("TextAlias", "SharedName")+class Decoder(TextModel): pass[email protected]("InheritedText")+class Child(Decoder): pass[email protected]("VisionAlias", "SharedName")+class Encoder(VisionModel): pass+'''+ assert extract_capabilities(source) == {+ "TEXT": ["InheritedText", "SharedName", "TextAlias"],+ "VISION": ["SharedName", "VisionAlias"],+ }+++def test_timed_out_probe_is_inconclusive(monkeypatch, tmp_path):+ from soup_cli.utils.gguf_capabilities import probe_text_architectures++ def timed_out(command, **kwargs):+ assert kwargs["timeout"] == 15+ raise subprocess.TimeoutExpired(command, kwargs["timeout"])++ monkeypatch.setattr(subprocess, "run", timed_out)+ assert probe_text_architectures(tmp_path / "convert_hf_to_gguf.py") is None++[email protected]("tag,commit,diagnostic", [+ ("different-pin", "a" * 40, "LLAMA_CPP_TAG"),+ ("b5270", "short-sha", "immutable Git commit"),+])+def test_regeneration_refuses_wrong_pin_or_mutable_source(tmp_path, tag, commit, diagnostic):+ script = Path(__file__).resolve().parents[1] / "scripts/gen_llama_cpp_capabilities.py"+ output = tmp_path / "capabilities.json"+ result = subprocess.run([+ sys.executable, str(script), "--converter", str(tmp_path / "unused.py"),+ "--tag", tag, "--commit", commit, "--output", str(output),+ ], capture_output=True, text=True)+ assert result.returncode == 2+ assert diagnostic in result.stderr+ assert not output.exists()+++def test_oversized_metadata_is_refused_without_work(export_flow):+ result, calls = export_flow(" " * (1024 * 1024 + 1))+ assert result.exit_code == 1+ plain = " ".join(strip_ansi(result.output).split())+ assert "metadata" in plain.lower()+ assert "1 MiB" in plain+ assert calls == []diff --git a/tests/test_issue1445_early_destination_validation.py b/tests/test_issue1445_early_destination_validation.pyindex 90773b74..516ffa49 100644--- a/tests/test_issue1445_early_destination_validation.py+++ b/tests/test_issue1445_early_destination_validation.py@@ -148,6 +148,9 @@ def _stub_export_backend(monkeypatch, tmp_path, merges):out = Path(output_dir)out.mkdir(parents=True, exist_ok=True)(out / "model.safetensors").write_bytes(b"\0" * 16)+ (out / "config.json").write_text(+ '{"architectures":["GPT2LMHeadModel"]}', encoding="utf-8",+ )monkeypatch.setattr(export_mod, "_merge_adapter", fake_merge)monkeypatch.setattr(export_mod, "_find_llama_cpp", lambda path=None: llama)diff --git a/tests/test_issue144_gguf_export.py b/tests/test_issue144_gguf_export.pyindex 8bfe5065..96884ed5 100644--- a/tests/test_issue144_gguf_export.py+++ b/tests/test_issue144_gguf_export.py@@ -48,7 +48,9 @@ class TestTheF16IntermediateCannotEatAUsersFile:def _model_dir(self, tmp_path):model = tmp_path / "mymodel"model.mkdir()- (model / "config.json").write_text('{"model_type": "llama"}', encoding="utf-8")+ (model / "config.json").write_text(+ '{"model_type":"llama","architectures":["LlamaForCausalLM"]}', encoding="utf-8",+ )return modeldef test_a_quantised_export_does_not_delete_an_existing_f16_gguf(@@ -124,7 +126,9 @@ class TestConvertDepsAreInstalledOnEveryPath:model = tmp_path / "mymodel"model.mkdir()- (model / "config.json").write_text('{"model_type": "llama"}', encoding="utf-8")+ (model / "config.json").write_text(+ '{"model_type":"llama","architectures":["LlamaForCausalLM"]}', encoding="utf-8",+ )llama = tmp_path / "llama.cpp"llama.mkdir()(llama / "convert_hf_to_gguf.py").write_text("# stub", encoding="utf-8")diff --git a/tests/test_issue1760_gguf_progress.py b/tests/test_issue1760_gguf_progress.pyindex f68054f7..70ce7805 100644--- a/tests/test_issue1760_gguf_progress.py+++ b/tests/test_issue1760_gguf_progress.py@@ -101,7 +101,9 @@ def cli_inputs(tmp_path, monkeypatch):monkeypatch.setenv("SOUP_REGISTRY_DB_PATH", str(tmp_path / "registry.db"))model = tmp_path / "model"model.mkdir()- (model / "config.json").write_text('{"model_type":"llama"}')+ (model / "config.json").write_text(+ '{"model_type":"llama","architectures":["LlamaForCausalLM"]}', encoding="utf-8",+ )llama = tmp_path / "llama.cpp"llama.mkdir()(llama / "convert_hf_to_gguf.py").write_text("# fixture")@@ -274,6 +276,9 @@ def test_cli_reports_each_reached_phase_once(monkeypatch, cli_inputs, quant, mandef merge(source, base, output, trust_remote_code):calls.append(("merge", base))Path(output).mkdir()+ (Path(output) / "config.json").write_text(+ '{"architectures":["LlamaForCausalLM"]}', encoding="utf-8",+ )def convert(script, source, output, outtype, **kwargs):calls.append(("convert", outtype))