Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

fix(export): report GGUF progress and managed dependencies (#1760) (#1777)

AmixDigitalb59af252f3bc
diff --git a/changelog.d/0.76.0/1777.fixed.md b/changelog.d/0.76.0/1777.fixed.md
new file mode 100644
index 00000000..cb20f674
--- /dev/null
+++ b/changelog.d/0.76.0/1777.fixed.md
@@ -0,0 +1 @@
+- GGUF export reports pipeline phases and streams converter/quantizer logs with `--verbose`; `--no-install-deps` refuses missing conversion packages before merge/toolchain work without invoking pip. (#1760 by @Amix29 in #1777)
diff --git a/docs/cli-reference.md b/docs/cli-reference.md
index 443c1a2f..a11ea60f 100644
--- a/docs/cli-reference.md
+++ b/docs/cli-reference.md
@@ -2349,6 +2349,8 @@ Usage: `soup export [OPTIONS]`
| `--quant-config` | text | | | Path to YAML for torchao PTQ export (v0.53.1 #142). Required when --format=torchao. |
| `--gguf-flavour` | text | | | Advanced GGUF format flag — UD-Q\*\_K_XL / IQ\*\_M / Q4_0_4_4 / etc. Required when --format=gguf-ud (v0.53.1 #139). |
| `--hub` | text | `hf` | | Source hub for the base model when --model is a LoRA adapter: hf (default) / modelscope / modelers (v0.53.10 #152). |
+| `--verbose` | flag | off | | Stream GGUF converter and quantizer logs while they run. |
+| `--no-install-deps` | flag | off | | GGUF only: never invoke pip; refuse missing conversion dependencies before work. |
## `soup fetch`
diff --git a/docs/commands.md b/docs/commands.md
index 9627fbf1..570735c4 100644
--- a/docs/commands.md
+++ b/docs/commands.md
@@ -48,6 +48,8 @@ soup export --model ./output --format onnx Export to ONNX
soup export --model ./output --format tensorrt Export to TensorRT-LLM
soup export --model ./output --format awq --calibration-data cal.jsonl Export to AWQ (4-bit; deprecated, removed in Soup v0.77)
soup export --model ./output --format gptq --calibration-data cal.jsonl Export to GPTQ (4-bit; deprecated, removed in Soup v0.77)
+soup export --model ./output --format gguf --verbose Show export phases and stream converter/quantizer logs while they run (#1760)
+soup export --model ./output --format gguf --no-install-deps Never invoke pip; refuse missing conversion packages before merge/toolchain work (#1760)
soup deploy ollama --model m.gguf --name x Deploy GGUF to Ollama
soup deploy ollama --list List Soup-deployed models
soup deploy ollama --remove <name> Remove model from Ollama
diff --git a/docs/serving-and-export.md b/docs/serving-and-export.md
index 576d28a0..258873fa 100644
--- a/docs/serving-and-export.md
+++ b/docs/serving-and-export.md
@@ -63,10 +63,30 @@ soup export --model ./merged --format gguf
# Specify llama.cpp path manually
soup export --model ./output --format gguf --llama-cpp /path/to/llama.cpp
+
+# Show the converter and quantizer's stdout/stderr while they run
+soup export --model ./output --format gguf --verbose
+
+# The environment manages its own conversion packages: never attempt pip
+soup export --model ./output --format gguf --no-install-deps --verbose
```
Supported quantizations: `q4_0`, `q4_k_m`, `q5_k_m`, `q8_0`, `f16`, `f32`
+GGUF export prints phase lines for toolchain lookup, dependency checking, adapter
+merge when needed, conversion and quantization when needed. `--verbose` additionally
+streams the converter and quantizer's combined stdout/stderr as lines arrive; the
+child tool may buffer its own output. Without the flag, successful child-tool logs
+stay quiet. Both modes retain a failure summary; verbose mode keeps a bounded tail
+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 Python
+environment 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
+your environment manager and retry. This flag does not disable toolchain lookup or
+cloning; use `--llama-cpp` to supply your own checkout. Both new flags apply only to
+`--format gguf`; other formats refuse them rather than ignore them.
+
### 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/src/soup_cli/commands/export.py b/src/soup_cli/commands/export.py
index d634e908..ef432474 100644
--- a/src/soup_cli/commands/export.py
+++ b/src/soup_cli/commands/export.py
@@ -5,6 +5,7 @@ import shutil
import subprocess
import sys
import tempfile
+from collections import deque
from pathlib import Path
from typing import Optional
@@ -14,7 +15,7 @@ from rich.markup import escape
from rich.panel import Panel
from soup_cli.config.deprecation import DEPRECATED_VALUE_REJECTION_VERSION
-from soup_cli.utils.terminal import for_terminal
+from soup_cli.utils.terminal import for_terminal, strip_control
console = Console()
@@ -179,6 +180,13 @@ def export(
"hf (default) / modelscope / modelers (v0.53.10 #152)."
),
),
+ verbose: bool = typer.Option(
+ False, "--verbose", help="Stream GGUF converter and quantizer logs while they run.",
+ ),
+ no_install_deps: bool = typer.Option(
+ False, "--no-install-deps",
+ help="GGUF only: never invoke pip; refuse missing conversion dependencies before work.",
+ ),
):
"""Export a model to GGUF, ONNX, TensorRT-LLM, AWQ, GPTQ, or TorchAO format."""
# v0.53.10 #152 — pre-fetch the base model from a non-HF hub. ``model``
@@ -209,6 +217,13 @@ def export(
)
raise typer.Exit(1)
+ if (verbose or no_install_deps) and fmt != "gguf":
+ flags = [name for name, enabled in (
+ ("--verbose", verbose), ("--no-install-deps", no_install_deps),
+ ) if enabled]
+ console.print(f"[red]{' and '.join(flags)} require --format gguf.[/]")
+ raise typer.Exit(2)
+
model_name = Path(model).name
# --- Deploy target validation ---
@@ -333,7 +348,7 @@ def export(
)
raise typer.Exit(1)
- # --- Resolve and create the destination before any merge/convert work ---
+ # --- 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
# the merged model. Create the parent up front (what ``_run_convert``
@@ -342,6 +357,12 @@ def export(
output_path = Path(output)
else:
output_path = Path(model).parent / f"{model_name}.{quant}.gguf"
+
+ # Managed environments must refuse missing deps before a merge or toolchain clone.
+ if no_install_deps:
+ console.print("[dim]GGUF: dependencies (managed environment)...[/]")
+ _install_convert_deps(install=False)
+
output_path.parent.mkdir(parents=True, exist_ok=True)
# --- Check if LoRA adapter (needs merge first) ---
@@ -350,6 +371,7 @@ def export(
merge_dir = None
if is_adapter:
+ console.print("[dim]GGUF: merge adapter...[/]")
console.print("[yellow]LoRA adapter detected - merging with base model first...[/]")
base_model = base or _detect_base_model(adapter_config_path)
if not base_model:
@@ -366,12 +388,16 @@ def export(
model_path = merge_dir
# --- Find llama.cpp ---
+ console.print("[dim]GGUF: toolchain lookup...[/]")
llama_dir = _find_llama_cpp(llama_cpp_path)
# #144 G2 — this used to run only after an auto-clone, so `--llama-cpp` and an
# already-present ~/.soup/llama.cpp died on `ModuleNotFoundError:
# sentencepiece`. Here it covers every branch, and returns immediately when
# the packages are already importable.
- _install_convert_deps()
+ if not no_install_deps:
+ console.print("[dim]GGUF: conversion dependencies...[/]")
+ _install_convert_deps()
+ tool_options = {"verbose": True} if verbose else {}
# --- Convert to GGUF ---
console.print(
@@ -397,8 +423,8 @@ def export(
if quant in ("f16", "f32"):
# Direct conversion without quantization
outtype = "f16" if quant == "f16" else "f32"
- console.print(f"[dim]Converting to GGUF ({outtype})...[/]")
- _run_convert(convert_script, model_path, output_path, outtype)
+ console.print(f"[dim]GGUF: convert — Converting to GGUF ({outtype})...[/]")
+ _run_convert(convert_script, model_path, output_path, outtype, **tool_options)
else:
# Convert to f16 first, then quantize.
#
@@ -414,12 +440,12 @@ def export(
)
try:
f16_path = tmp_dir / f"{model_name}.f16.gguf"
- console.print("[dim]Converting to GGUF (f16)...[/]")
- _run_convert(convert_script, model_path, f16_path, "f16")
+ console.print("[dim]GGUF: convert — Converting to GGUF (f16)...[/]")
+ _run_convert(convert_script, model_path, f16_path, "f16", **tool_options)
# Quantize
- console.print(f"[dim]Quantizing to {quant}...[/]")
- _run_quantize(llama_dir, f16_path, output_path, quant)
+ console.print(f"[dim]GGUF: quantize — Quantizing to {quant}...[/]")
+ _run_quantize(llama_dir, f16_path, output_path, quant, **tool_options)
finally:
shutil.rmtree(tmp_dir, ignore_errors=True)
@@ -530,17 +556,28 @@ def _merge_adapter(
_CONVERT_EXTRA_DEPS = ("gguf", "sentencepiece", "protobuf")
-def _convert_deps_present() -> bool:
- """Are the convert script's extra deps already importable?"""
+def _missing_convert_deps() -> list[str]:
+ """Name missing convert packages without importing the heavy training stack."""
import importlib.util
- for module in ("gguf", "sentencepiece"):
- if importlib.util.find_spec(module) is None:
- return False
- return True
+ missing = []
+ for module, package in (("gguf", "gguf"), ("sentencepiece", "sentencepiece"),
+ ("google.protobuf", "protobuf")):
+ try:
+ present = importlib.util.find_spec(module) is not None
+ except (ImportError, ValueError):
+ present = False
+ if not present:
+ missing.append(package)
+ return missing
+
+
+def _convert_deps_present() -> bool:
+ """Are the convert script's extra deps already importable?"""
+ return not _missing_convert_deps()
-def _install_convert_deps() -> None:
+def _install_convert_deps(*, install: bool = True) -> None:
"""Install the convert script's extra deps without disturbing torch.
#144 G2 — this used to run ONLY after an auto-clone, so `--llama-cpp /path`
@@ -549,6 +586,15 @@ def _install_convert_deps() -> None:
It is now called on every path, and returns immediately when the packages are
already importable so an ordinary export does not shell out to pip.
"""
+ if not install:
+ missing = _missing_convert_deps()
+ if missing:
+ console.print(
+ "[red]--no-install-deps: missing GGUF conversion packages: "
+ f"{', '.join(missing)}.[/] Install them in the managed environment and retry."
+ )
+ raise typer.Exit(1)
+ return
if _convert_deps_present():
return
try:
@@ -636,7 +682,50 @@ def _find_llama_cpp(user_path: Optional[str] = None) -> Path:
raise typer.Exit(1)
-def _run_convert(script: Path, model_dir: Path, output_path: Path, outtype: str):
+def _run_export_tool(cmd: list[str], label: str, *, verbose: bool) -> None:
+ """Keep quiet capture by default; stream merged output with a bounded error tail."""
+ if not verbose:
+ result = subprocess.run(cmd, capture_output=True, text=True)
+ if result.returncode != 0:
+ console.print(f"[red]{label} failed:[/]")
+ console.print(strip_control(result.stderr), markup=False, highlight=False)
+ raise typer.Exit(1)
+ return
+
+ tail: deque[str] = deque(maxlen=100)
+ process = subprocess.Popen(
+ cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
+ encoding="utf-8", errors="replace", bufsize=1,
+ )
+ try:
+ assert process.stdout is not None
+ for line in process.stdout:
+ text = strip_control(line.rstrip("\r\n"))
+ tail.append(text[-2000:])
+ console.print(text, markup=False, highlight=False)
+ returncode = process.wait()
+ except BaseException:
+ # A cancelled export or output failure must not leave the tool running.
+ if process.poll() is None:
+ process.terminate()
+ try:
+ process.wait(timeout=2)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.wait()
+ raise
+ finally:
+ if process.stdout is not None:
+ process.stdout.close()
+ if returncode != 0:
+ console.print(f"[red]{label} failed (exit {returncode}):[/]")
+ console.print("\n".join(tail), markup=False, highlight=False)
+ raise typer.Exit(1)
+
+
+def _run_convert(
+ script: Path, model_dir: Path, output_path: Path, outtype: str, *, verbose: bool = False,
+) -> None:
"""Run llama.cpp convert_hf_to_gguf.py script."""
output_path.parent.mkdir(parents=True, exist_ok=True)
@@ -646,13 +735,12 @@ def _run_convert(script: Path, model_dir: Path, output_path: Path, outtype: str)
"--outfile", str(output_path),
"--outtype", outtype,
]
- result = subprocess.run(cmd, capture_output=True, text=True)
- if result.returncode != 0:
- console.print(f"[red]Conversion failed:[/]\n{result.stderr}")
- raise typer.Exit(1)
+ _run_export_tool(cmd, "Conversion", verbose=verbose)
-def _run_quantize(llama_dir: Path, input_path: Path, output_path: Path, quant_type: str):
+def _run_quantize(
+ llama_dir: Path, input_path: Path, output_path: Path, quant_type: str, *, verbose: bool = False,
+) -> None:
"""Run llama-quantize (or llama.cpp/build/bin/llama-quantize)."""
# Try to find the quantize binary
quantize_bin = _find_quantize_binary(llama_dir)
@@ -666,10 +754,7 @@ def _run_quantize(llama_dir: Path, input_path: Path, output_path: Path, quant_ty
raise typer.Exit(1)
cmd = [str(quantize_bin), str(input_path), str(output_path), quant_type.upper()]
- result = subprocess.run(cmd, capture_output=True, text=True)
- if result.returncode != 0:
- console.print(f"[red]Quantization failed:[/]\n{result.stderr}")
- raise typer.Exit(1)
+ _run_export_tool(cmd, "Quantization", verbose=verbose)
# MSVC / Xcode are multi-config generators: they nest binaries under a
diff --git a/tests/test_issue1760_gguf_progress.py b/tests/test_issue1760_gguf_progress.py
new file mode 100644
index 00000000..f68054f7
--- /dev/null
+++ b/tests/test_issue1760_gguf_progress.py
@@ -0,0 +1,315 @@
+"""GGUF progress is live, and managed dependencies never invoke pip (#1760)."""
+
+import importlib.util
+import io
+import sys
+from pathlib import Path
+
+import pytest
+from rich.console import Console
+from typer.testing import CliRunner
+
+from soup_cli.cli import app
+from soup_cli.commands import export as export_module
+from tests.conftest import strip_ansi
+
+
+def test_verbose_conversion_delivers_output_before_child_exit(monkeypatch, tmp_path):
+ ack = tmp_path / "ack"
+ script = tmp_path / "convert.py"
+ script.write_text(
+ "import pathlib, sys, time\n"
+ "print('child-converter-started', flush=True)\n"
+ f"ack = pathlib.Path({str(ack)!r})\n"
+ "deadline = time.monotonic() + 5\n"
+ "while not ack.exists() and time.monotonic() < deadline: time.sleep(.01)\n"
+ "if not ack.exists(): sys.exit(7)\n"
+ "print('[red]literal[/]\\x1b[2J', file=sys.stderr, flush=True)\n"
+ "pathlib.Path(sys.argv[sys.argv.index('--outfile') + 1]).write_bytes(b'fixture')\n",
+ encoding="utf-8",
+ )
+ output = io.StringIO()
+
+ class AcknowledgingConsole(Console):
+ def print(self, *objects, **kwargs):
+ if "child-converter-started" in " ".join(str(obj) for obj in objects):
+ ack.write_text("seen before exit")
+ return super().print(*objects, **kwargs)
+
+ monkeypatch.setattr(export_module, "console", AcknowledgingConsole(file=output, width=120))
+ destination = tmp_path / "out.gguf"
+ export_module._run_convert(script, tmp_path, destination, "f16", verbose=True)
+ assert ack.exists()
+ assert destination.read_bytes() == b"fixture"
+ rendered = strip_ansi(output.getvalue())
+ assert "[red]literal[/]" in rendered
+ assert "\x1b" not in rendered
+
+
+def test_verbose_quantization_streams_stdout_and_stderr(monkeypatch, tmp_path):
+ # Python stands in for the binary; its first argument is an actual child script.
+ source = tmp_path / "input.gguf"
+ source.write_text(
+ "import pathlib, sys\n"
+ "print('quant-out', flush=True)\n"
+ "print('quant-error-stream', file=sys.stderr, flush=True)\n"
+ "assert sys.argv[2] == 'Q4_0'\n"
+ "pathlib.Path(sys.argv[1]).write_bytes(b'quantized fixture')\n",
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(export_module, "_find_quantize_binary", lambda path: Path(sys.executable))
+ output = io.StringIO()
+ monkeypatch.setattr(export_module, "console", Console(file=output))
+ destination = tmp_path / "out.gguf"
+ export_module._run_quantize(tmp_path, source, destination, "q4_0", verbose=True)
+ assert destination.read_bytes() == b"quantized fixture"
+ rendered = strip_ansi(output.getvalue())
+ assert "quant-out" in rendered
+ assert "quant-error-stream" in rendered
+
+
[email protected]("verbose", [False, True])
+def test_conversion_failure_keeps_diagnostic_summary(monkeypatch, tmp_path, verbose):
+ import typer
+
+ script = tmp_path / "fail.py"
+ payload = "distinctive failure [/x] [bold]b[/]\x1b[2J\x9b31m"
+ script.write_text(f"import sys\nprint({payload!r}, file=sys.stderr)\nsys.exit(4)\n")
+ output = io.StringIO()
+ monkeypatch.setattr(export_module, "console", Console(file=output))
+ with pytest.raises(typer.Exit) as exc:
+ export_module._run_convert(script, tmp_path, tmp_path / "out.gguf", "f16", verbose=verbose)
+ assert exc.value.exit_code == 1
+ rendered = strip_ansi(output.getvalue())
+ assert "Conversion failed" in rendered
+ assert rendered.count("distinctive failure [/x] [bold]b[/][2J31m") == (2 if verbose else 1)
+ assert "\x1b" not in rendered
+ assert "\x9b" not in rendered
+
+
+def test_default_conversion_success_stays_quiet(monkeypatch, tmp_path):
+ script = tmp_path / "quiet.py"
+ script.write_text("print('child-success-log')\n")
+ output = io.StringIO()
+ monkeypatch.setattr(export_module, "console", Console(file=output))
+ export_module._run_convert(script, tmp_path, tmp_path / "out.gguf", "f16")
+ assert "child-success-log" not in strip_ansi(output.getvalue())
+
+
+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"}')
+ llama = tmp_path / "llama.cpp"
+ llama.mkdir()
+ (llama / "convert_hf_to_gguf.py").write_text("# fixture")
+ return model, llama, tmp_path / "out.gguf"
+
+
+def test_no_install_deps_missing_packages_refuses_before_merge_or_lookup(
+ monkeypatch, cli_inputs,
+):
+ model, llama, destination = cli_inputs
+ destination = destination.parent / "must-not-create" / "out.gguf"
+ (model / "adapter_config.json").write_text('{"base_model_name_or_path":"unused"}')
+ monkeypatch.setattr(export_module, "_missing_convert_deps", lambda: ["gguf", "protobuf"])
+
+ def unexpected(*args, **kwargs):
+ pytest.fail("managed missing deps must fail before expensive work or pip")
+
+ monkeypatch.setattr(export_module, "_merge_adapter", unexpected)
+ monkeypatch.setattr(export_module, "_find_llama_cpp", unexpected)
+ monkeypatch.setattr(export_module.subprocess, "run", unexpected)
+ result = CliRunner().invoke(app, ["export", "--model", str(model), "--output",
+ str(destination), "--no-install-deps"])
+ assert result.exit_code == 1, result.output
+ output = strip_ansi(result.output)
+ assert "gguf" in output and "protobuf" in output
+ assert "--no-install-deps" in output
+ assert not (model.parent / ".soup_merge_tmp_model").exists()
+ assert not destination.parent.exists()
+
+
+def test_no_install_deps_present_never_runs_pip_and_reports_phases(monkeypatch, cli_inputs):
+ model, llama, destination = cli_inputs
+ calls = []
+ monkeypatch.setattr(export_module, "_missing_convert_deps", lambda: [])
+ monkeypatch.setattr(export_module, "_find_llama_cpp", lambda path: llama)
+
+ def convert(script, source, output, outtype, **kwargs):
+ calls.append(("convert", kwargs))
+ output.write_bytes(b"f16 fixture")
+
+ def quantize(toolchain, source, output, quant, **kwargs):
+ calls.append(("quantize", kwargs))
+ output.write_bytes(b"q4 fixture")
+
+ def unexpected(*args, **kwargs):
+ pytest.fail("no pip call is allowed")
+
+ monkeypatch.setattr(export_module.subprocess, "run", unexpected)
+ monkeypatch.setattr(export_module, "_run_convert", convert)
+ monkeypatch.setattr(export_module, "_run_quantize", quantize)
+ result = CliRunner().invoke(app, ["export", "--model", str(model), "--output",
+ str(destination), "--no-install-deps", "--verbose"])
+ assert result.exit_code == 0, result.output
+ assert destination.read_bytes() == b"q4 fixture"
+ assert calls == [("convert", {"verbose": True}), ("quantize", {"verbose": True})]
+ output = strip_ansi(result.output)
+ assert "GGUF: toolchain" in output
+ assert "GGUF: convert" in output
+ assert "GGUF: quantize" in output
+ assert not list(destination.parent.glob(".soup_gguf_*"))
+
+
[email protected]("flag", ["--verbose", "--no-install-deps"])
+def test_gguf_only_flags_are_not_silently_ignored(monkeypatch, cli_inputs, flag):
+ model, _, destination = cli_inputs
+ result = CliRunner().invoke(app, ["export", "--model", str(model), "--format", "onnx",
+ "--output", str(destination), flag])
+ assert result.exit_code == 2, result.output
+ output = strip_ansi(result.output)
+ assert "--format gguf" in output
+ assert flag in output
+ other = "--no-install-deps" if flag == "--verbose" else "--verbose"
+ assert other not in output
+
+
+def test_dependency_probe_names_all_missing_packages(monkeypatch):
+ monkeypatch.setattr(importlib.util, "find_spec", lambda name: None)
+ assert export_module._missing_convert_deps() == ["gguf", "sentencepiece", "protobuf"]
+
+
+def test_only_protobuf_missing_is_probed_and_triggers_the_pip_attempt(monkeypatch):
+ real_find_spec = importlib.util.find_spec
+ probed = []
+
+ def find_spec(name, *args, **kwargs):
+ probed.append(name)
+ if name == "google.protobuf":
+ return None
+ return object() # gguf and sentencepiece look installed
+
+ monkeypatch.setattr(importlib.util, "find_spec", find_spec)
+ assert export_module._missing_convert_deps() == ["protobuf"]
+ assert "google.protobuf" in probed
+ assert export_module._convert_deps_present() is False
+
+ runs = []
+ monkeypatch.setattr(
+ export_module.subprocess, "run",
+ lambda cmd, *args, **kwargs: runs.append(cmd) or type("R", (), {"returncode": 0})(),
+ )
+ export_module._install_convert_deps()
+ assert runs and "pip" in " ".join(map(str, runs[0]))
+ assert real_find_spec is not find_spec
+
+
+def test_stream_failure_keeps_only_a_bounded_tail(monkeypatch):
+ import typer
+
+ printed = []
+
+ class OutputConsole:
+ def print(self, text, **kwargs):
+ printed.append(text)
+
+ class Process:
+ stdout = io.StringIO("".join(f"row-{index} " + "x" * 3000 + "\n" for index in range(110)))
+
+ def wait(self):
+ return 5
+
+ monkeypatch.setattr(export_module, "console", OutputConsole())
+ monkeypatch.setattr(export_module.subprocess, "Popen", lambda *args, **kwargs: Process())
+ with pytest.raises(typer.Exit):
+ export_module._run_export_tool(["fixture"], "Conversion", verbose=True)
+ assert len(printed[-1].splitlines()) == 100
+ assert len(printed[-1]) <= 100 * 2000 + 99
+
+
+def test_output_failure_terminates_the_child_and_closes_its_pipe(monkeypatch):
+ actions = []
+
+ class BrokenConsole:
+ def print(self, text, **kwargs):
+ raise OSError("output closed")
+
+ class Process:
+ stdout = io.StringIO("progress\n")
+
+ def poll(self):
+ return None
+
+ def terminate(self):
+ actions.append("terminate")
+
+ def wait(self, **kwargs):
+ actions.append("wait")
+
+ process = Process()
+ monkeypatch.setattr(export_module, "console", BrokenConsole())
+ monkeypatch.setattr(export_module.subprocess, "Popen", lambda *args, **kwargs: process)
+ with pytest.raises(OSError, match="output closed"):
+ export_module._run_export_tool(["fixture"], "Conversion", verbose=True)
+ assert actions == ["terminate", "wait"]
+ assert process.stdout.closed
+
+
[email protected]("quant", ["f16", "f32", "q4_0"])
[email protected]("managed", [False, True])
[email protected]("adapter", [False, True])
+def test_cli_reports_each_reached_phase_once(monkeypatch, cli_inputs, quant, managed, adapter):
+ model, llama, destination = cli_inputs
+ if adapter:
+ (model / "adapter_config.json").write_text('{"base_model_name_or_path":"base"}')
+ calls = []
+ convert_options = []
+
+ def deps(*, install=True):
+ calls.append(("dependencies", install))
+
+ def merge(source, base, output, trust_remote_code):
+ calls.append(("merge", base))
+ Path(output).mkdir()
+
+ def convert(script, source, output, outtype, **kwargs):
+ calls.append(("convert", outtype))
+ convert_options.append(kwargs)
+ output.write_bytes(b"converted fixture")
+
+ def quantize(toolchain, source, output, quant, **kwargs):
+ calls.append(("quantize", quant))
+ output.write_bytes(b"quantized fixture")
+
+ monkeypatch.setattr(export_module, "_install_convert_deps", deps)
+ monkeypatch.setattr(export_module, "_merge_adapter", merge)
+ monkeypatch.setattr(export_module, "_find_llama_cpp", lambda path: llama)
+ monkeypatch.setattr(export_module, "_run_convert", convert)
+ monkeypatch.setattr(export_module, "_run_quantize", quantize)
+ flags = ["--no-install-deps"] if managed else []
+ if quant in ("f16", "f32"):
+ flags.append("--verbose")
+ result = CliRunner().invoke(app, [
+ "export", "--model", str(model), "--output", str(destination), "--quant", quant, *flags,
+ ])
+ assert result.exit_code == 0, result.output
+ output = strip_ansi(result.output)
+ assert output.count("GGUF: merge adapter") == int(adapter)
+ assert output.count("GGUF: conversion dependencies") == int(not managed)
+ assert output.count("GGUF: dependencies (managed environment)") == int(managed)
+ assert output.count("GGUF: toolchain lookup") == 1
+ outtype = "f16" if quant == "q4_0" else quant
+ assert output.count(f"GGUF: convert — Converting to GGUF ({outtype})") == 1
+ assert output.count("GGUF: quantize") == int(quant == "q4_0")
+ assert ("dependencies", not managed) in calls
+ assert ("convert", "f16" if quant == "q4_0" else quant) in calls
+ assert convert_options == [{"verbose": True} if quant in ("f16", "f32") else {}]
+ if quant == "q4_0":
+ assert ("quantize", "q4_0") in calls
+ else:
+ assert all(name != "quantize" for name, _ in calls)
+ assert not (model.parent / ".soup_merge_tmp_model").exists()
+ assert not list(destination.parent.glob(".soup_gguf_*"))