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): wire --registry-id and --deploy across non-GGUF export formats (Refs #1448) (#1679)

Sohaib Kamash43f12255d9cb
diff --git a/changelog.d/0.75.1/1679.fixed.md b/changelog.d/0.75.1/1679.fixed.md
new file mode 100644
index 00000000..a245d3a5
--- /dev/null
+++ b/changelog.d/0.75.1/1679.fixed.md
@@ -0,0 +1,5 @@
+- `soup export --registry-id` now records the exported files for `onnx`,
+ `tensorrt`, `awq`, `gptq`, `torchao`, `gguf-ud`, `bitnet` and `tq1_0` (every
+ shard or engine file, named in the success line). `--deploy ollama` now works
+ with `gguf-ud`, `bitnet` and `tq1_0` and is refused before the export starts
+ for the formats Ollama cannot load (part of #1448 by @Nick-800 in #1679).
diff --git a/docs/serving-and-export.md b/docs/serving-and-export.md
index 54530f0b..4af27a4c 100644
--- a/docs/serving-and-export.md
+++ b/docs/serving-and-export.md
@@ -175,6 +175,13 @@ soup deploy ollama --remove soup-my-model
Auto-detected chat templates: `chatml`, `llama`, `mistral`, `vicuna`, `zephyr` (or `auto` to infer from soup.yaml).
+### Registry Attachment and Deploy Options
+
+`soup export` integrates with Soup's local artifact registry and deployment workflows:
+
+- **Deploying on export (`--deploy`)**: `--deploy ollama` is supported for GGUF-family formats (`gguf`, `gguf-ud`, `bitnet`, `tq1_0`). For non-GGUF formats (`onnx`, `tensorrt`, `awq`, `gptq`, `torchao`), `--deploy` fails fast with an informative error because Ollama cannot load non-GGUF weight files. Use `--deploy-name` to assign a custom model name in Ollama.
+- **Registering exports (`--registry-id`)**: Pass `--registry-id <id>` to record and attach exported artifacts to a local registry entry across all export formats (`gguf`, `gguf-ud`, `bitnet`, `tq1_0`, `onnx`, `tensorrt`, `awq`, `gptq`, `torchao`). When an export produces a directory (such as multi-shard safetensors, ONNX data, or TensorRT engine files in `<output>/engine/*.engine`), all produced weight and engine files are discovered and attached to the registry entry.
+
## Batch Inference
diff --git a/src/soup_cli/commands/card.py b/src/soup_cli/commands/card.py
index 9febcd96..eea5019b 100644
--- a/src/soup_cli/commands/card.py
+++ b/src/soup_cli/commands/card.py
@@ -56,7 +56,9 @@ def _truncate(text: str, limit: int) -> str:
# Export kinds that prove the artifact is a standalone (non-adapter) model.
-_DENSE_KINDS = frozenset({"merged", "gguf", "onnx", "awq", "gptq", "tensorrt", "edited_model"})
+_DENSE_KINDS = frozenset({
+ "merged", "gguf", "onnx", "awq", "gptq", "tensorrt", "torchao", "edited_model",
+})
def _is_adapter(artifacts: Sequence[Mapping[str, Any]], config: Mapping[str, Any]) -> bool:
diff --git a/src/soup_cli/commands/export.py b/src/soup_cli/commands/export.py
index dfe23cf5..a294f919 100644
--- a/src/soup_cli/commands/export.py
+++ b/src/soup_cli/commands/export.py
@@ -206,42 +206,84 @@ def export(
)
raise typer.Exit(1)
+ model_name = Path(model).name
+
+ # --- Deploy target validation ---
+ if deploy:
+ if fmt not in ("gguf", "gguf-ud", "bitnet", "tq1_0"):
+ console.print(
+ f"[red]--deploy is not supported for format '{fmt}'. "
+ "Supported formats for deploy: gguf, gguf-ud, bitnet, tq1_0[/]"
+ )
+ raise typer.Exit(1)
+ if deploy != "ollama":
+ console.print(
+ f"[red]Unsupported deploy target: {deploy}[/]\n"
+ "Supported: ollama"
+ )
+ raise typer.Exit(1)
+
# --- ONNX export path ---
if fmt == "onnx":
- _export_onnx(model_path, output, base, onnx_task, trust_remote_code)
+ output_path = _export_onnx(model_path, output, base, onnx_task, trust_remote_code)
+ if output_path is not None:
+ _maybe_attach_export(
+ artifact_path=str(output_path), kind="onnx",
+ explicit_id=registry_id, source_model=str(Path(model)),
+ )
return
# --- TensorRT-LLM export path ---
if fmt == "tensorrt":
- _export_tensorrt(model_path, output, base, trust_remote_code)
+ output_path = _export_tensorrt(model_path, output, base, trust_remote_code)
+ if output_path is not None:
+ _maybe_attach_export(
+ artifact_path=str(output_path), kind="tensorrt",
+ explicit_id=registry_id, source_model=str(Path(model)),
+ )
return
# --- AWQ export path ---
if fmt == "awq":
- _export_awq(
+ output_path = _export_awq(
model_path, output, base, bits, group_size,
calibration_data, calibration_samples, trust_remote_code,
)
+ if output_path is not None:
+ _maybe_attach_export(
+ artifact_path=str(output_path), kind="awq",
+ explicit_id=registry_id, source_model=str(Path(model)),
+ )
return
# --- GPTQ export path ---
if fmt == "gptq":
- _export_gptq(
+ output_path = _export_gptq(
model_path, output, base, bits, group_size,
calibration_data, calibration_samples, trust_remote_code,
)
+ if output_path is not None:
+ _maybe_attach_export(
+ artifact_path=str(output_path), kind="gptq",
+ explicit_id=registry_id, source_model=str(Path(model)),
+ )
return
# --- TorchAO PTQ export path (v0.53.1 #142) ---
if fmt == "torchao":
- _export_torchao_cli(
+ output_path = _export_torchao_cli(
model_path, output, quant_config, trust_remote_code,
)
+ if output_path is not None:
+ _maybe_attach_export(
+ artifact_path=str(output_path), kind="torchao",
+ explicit_id=registry_id, source_model=str(Path(model)),
+ )
return
# --- Advanced GGUF export path (UD / IQ / Apple-ARM, v0.53.1 #139) ---
if fmt == "gguf-ud":
- _export_gguf_advanced(
+ output_path = _export_gguf_advanced(
model_path=model_path,
output=output,
base=base,
@@ -250,6 +292,13 @@ def export(
llama_cpp_path=llama_cpp_path,
trust_remote_code=trust_remote_code,
)
+ if output_path is not None:
+ _maybe_attach_export(
+ artifact_path=str(output_path), kind="gguf",
+ explicit_id=registry_id, source_model=str(Path(model)),
+ )
+ if deploy:
+ _auto_deploy_ollama(output_path, model_name, deploy, deploy_name)
return
# --- BitNet 1.58-bit / TQ1_0 GGUF (v0.71.20 #134) ---
@@ -257,7 +306,7 @@ def export(
# toolchain; the convert/quantize binaries surface a friendly
# FileNotFoundError when absent (infra-blocked, mirrors gguf-ud).
if fmt in ("bitnet", "tq1_0"):
- _export_bitnet_gguf(
+ output_path = _export_bitnet_gguf(
model_path=model_path,
output=output,
base=base,
@@ -265,6 +314,13 @@ def export(
llama_cpp_path=llama_cpp_path,
trust_remote_code=trust_remote_code,
)
+ if output_path is not None:
+ _maybe_attach_export(
+ artifact_path=str(output_path), kind="gguf",
+ explicit_id=registry_id, source_model=str(Path(model)),
+ )
+ if deploy:
+ _auto_deploy_ollama(output_path, model_name, deploy, deploy_name)
return
if quant not in GGUF_QUANT_TYPES:
@@ -279,7 +335,6 @@ def export(
# from mkdtemp AFTER an adapter was merged, and the cleanup then deleted
# the merged model. Create the parent up front (what ``_run_convert``
# already did for the f16 path) so no finished work is discarded.
- model_name = Path(model).name
if output:
output_path = Path(output)
else:
@@ -653,7 +708,7 @@ def _export_onnx(
model_path: Path, output: Optional[str], base: Optional[str],
task: str = "text-generation",
trust_remote_code: bool = False,
-):
+) -> Optional[Path]:
"""Export model to ONNX format via optimum."""
try:
from optimum.exporters.onnx import main_export
@@ -724,6 +779,7 @@ def _export_onnx(
title="[bold green]ONNX Export Complete![/]",
)
)
+ return output_path
def _export_tensorrt(
@@ -731,7 +787,7 @@ def _export_tensorrt(
output: Optional[str],
base: Optional[str],
trust_remote_code: bool = False,
-):
+) -> Optional[Path]:
"""Export model to TensorRT-LLM format."""
# TensorRT-LLM uses trtllm-build CLI from the tensorrt_llm package
trtllm_available = False
@@ -865,6 +921,7 @@ def _export_tensorrt(
title="[bold green]TensorRT-LLM Export Complete![/]",
)
)
+ return output_path
def _validate_output_path(output: Optional[str]) -> Optional[Path]:
@@ -959,7 +1016,7 @@ def _export_awq(
calibration_data: Optional[str] = None,
calibration_samples: int = 128,
trust_remote_code: bool = False,
-) -> None:
+) -> Optional[Path]:
"""Export model to AWQ format via autoawq."""
# First, so it is there whatever stops the run (most stop at the extra).
_warn_deprecated_format("awq")
@@ -1091,6 +1148,7 @@ def _export_awq(
title="[bold green]AWQ Export Complete![/]",
)
)
+ return output_path
def _export_gptq(
@@ -1102,7 +1160,7 @@ def _export_gptq(
calibration_data: Optional[str] = None,
calibration_samples: int = 128,
trust_remote_code: bool = False,
-) -> None:
+) -> Optional[Path]:
"""Export model to GPTQ format via auto-gptq."""
# First, so it is there whatever stops the run (most stop at the extra).
_warn_deprecated_format("gptq")
@@ -1242,6 +1300,7 @@ def _export_gptq(
title="[bold green]GPTQ Export Complete![/]",
)
)
+ return output_path
def _auto_deploy_ollama(
@@ -1330,16 +1389,39 @@ def _maybe_attach_export(
entry_id = lookup_entry_by_output_dir(source_model)
if entry_id is None:
return
+
+ target = Path(artifact_path)
+ files_to_attach: list[Path] = []
+ if target.is_file():
+ files_to_attach = [target]
+ elif target.is_dir():
+ engine_dir = target / "engine"
+ if engine_dir.is_dir():
+ files_to_attach.extend(sorted(engine_dir.glob("*.engine")))
+
+ for ext in ("*.safetensors", "*.onnx", "*.onnx_data", "*.pt", "*.bin", "*.engine"):
+ for f in sorted(target.glob(ext)):
+ if f not in files_to_attach:
+ files_to_attach.append(f)
+
+ if not files_to_attach:
+ files_to_attach = [target]
+
+ attached_names: list[str] = []
try:
- attach_artifact(entry_id, path=artifact_path, kind=kind)
+ for f in files_to_attach:
+ attach_artifact(entry_id, path=str(f), kind=kind)
+ attached_names.append(for_terminal(f.name))
except (ValueError, FileNotFoundError) as exc:
console.print(
f"[yellow]Could not attach export to registry "
f"'{entry_id}':[/] {exc}"
)
return
+
+ names_str = ", ".join(attached_names)
console.print(
- f"[green]Attached export to registry entry '{entry_id}' as {kind}.[/]"
+ f"[green]Attached export to registry entry '{entry_id}' as {kind} ({names_str}).[/]"
)
@@ -1351,7 +1433,7 @@ def _export_torchao_cli(
output: Optional[str],
quant_config: Optional[str],
trust_remote_code: bool,
-) -> None:
+) -> Optional[Path]:
"""Dispatch ``soup export --format torchao``.
Per v0.53.0 ``validate_quant_config_path`` docstring contract:
@@ -1427,6 +1509,7 @@ def _export_torchao_cli(
f"Scheme: [bold]{scheme}[/]",
title="[bold green]TorchAO Export Complete[/]",
))
+ return output_path
# --- v0.53.1 #139 — Advanced GGUF export CLI dispatch -----------------------
@@ -1440,7 +1523,7 @@ def _export_bitnet_gguf(
export_format: str,
llama_cpp_path: Optional[str],
trust_remote_code: bool,
-) -> None:
+) -> Optional[Path]:
"""Dispatch ``soup export --format bitnet | tq1_0`` (v0.71.20 #134).
Reuses the v0.53.1 gguf convert→quantize pipeline with the TQ1_0 ternary
@@ -1504,6 +1587,7 @@ def _export_bitnet_gguf(
f"Format: [bold]{canonical}[/]",
title="[bold green]BitNet GGUF Export Complete[/]",
))
+ return output_path
def _export_gguf_advanced(
@@ -1515,7 +1599,7 @@ def _export_gguf_advanced(
calibration_data: Optional[str],
llama_cpp_path: Optional[str],
trust_remote_code: bool,
-) -> None:
+) -> Optional[Path]:
"""Dispatch ``soup export --format gguf-ud --gguf-flavour <...>``.
Routes through llama.cpp's ``imatrix`` + ``quantize`` binaries. Supports
@@ -1612,3 +1696,4 @@ def _export_gguf_advanced(
f"Flavour: [bold]{gguf_flavour}[/]",
title="[bold green]Advanced GGUF Export Complete[/]",
))
+ return output_path
diff --git a/src/soup_cli/registry/store.py b/src/soup_cli/registry/store.py
index 169fb813..655f25f3 100644
--- a/src/soup_cli/registry/store.py
+++ b/src/soup_cli/registry/store.py
@@ -40,7 +40,7 @@ _VALID_KINDS = frozenset(
{
"adapter", "merged", "gguf", "awq", "gptq", "onnx", "dataset", "config",
"eval_results", "tensorrt", "eval_suite", "canaries",
- "diagnose_report",
+ "diagnose_report", "torchao",
# v0.62.0 Part C — Activation steering vectors (CAA / ITI / RepE).
"steering_vector",
# v0.71.1 #214 — pairwise-judge calibration reports.
diff --git a/tests/test_issue1448_export_deploy_options.py b/tests/test_issue1448_export_deploy_options.py
new file mode 100644
index 00000000..47679745
--- /dev/null
+++ b/tests/test_issue1448_export_deploy_options.py
@@ -0,0 +1,360 @@
+"""Tests for issue #1448: soup export --deploy and --registry-id on non-GGUF formats.
+
+Acceptance criteria:
+- Formats that Ollama cannot load (onnx, tensorrt, awq, gptq, torchao) refuse --deploy.
+- Advanced GGUF formats (gguf-ud, bitnet, tq1_0) wire --deploy to _auto_deploy_ollama.
+- All export formats wire --registry-id (and auto-attach) to _maybe_attach_export.
+- _VALID_KINDS in registry store includes 'torchao'.
+"""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+from unittest.mock import patch
+
+import pytest
+from typer.testing import CliRunner
+
+from soup_cli.cli import app
+from soup_cli.registry.store import _VALID_KINDS
+from tests.conftest import strip_ansi
+
+runner = CliRunner()
+
+
+def _clean(text: str) -> str:
+ return " ".join(strip_ansi(text).split())
+
+
+def test_torchao_in_valid_kinds():
+ """torchao must be recognized as a valid registry artifact kind."""
+ assert "torchao" in _VALID_KINDS
+
+
[email protected]("fmt", ["onnx", "tensorrt", "awq", "gptq", "torchao"])
+def test_export_refuses_deploy_for_unsupported_formats(tmp_path: Path, fmt: str):
+ """Formats Ollama cannot load must refuse --deploy with an informative error."""
+ model_dir = tmp_path / "model"
+ model_dir.mkdir()
+
+ result = runner.invoke(
+ app,
+ ["export", "--model", str(model_dir), "--format", fmt, "--deploy", "ollama"],
+ )
+ assert result.exit_code == 1
+ output = _clean(result.output)
+ assert f"--deploy is not supported for format '{fmt}'" in output
+ assert "Supported formats for deploy: gguf, gguf-ud, bitnet, tq1_0" in output
+
+
+def test_export_refuses_unsupported_deploy_target(tmp_path: Path):
+ """Unsupported deploy targets must exit 1 and report supported targets."""
+ model_dir = tmp_path / "model"
+ model_dir.mkdir()
+
+ result = runner.invoke(
+ app,
+ ["export", "--model", str(model_dir), "--format", "gguf", "--deploy", "invalid_target"],
+ )
+ assert result.exit_code == 1
+ output = _clean(result.output)
+ assert "Unsupported deploy target: invalid_target" in output
+ assert "Supported: ollama" in output
+
+
[email protected]("fmt", ["gguf-ud", "bitnet", "tq1_0"])
+def test_export_wires_deploy_for_deployable_formats(tmp_path: Path, fmt: str):
+ """Formats producing deployable GGUF files must forward --deploy to _auto_deploy_ollama."""
+ model_dir = tmp_path / "model"
+ model_dir.mkdir()
+ fake_gguf = tmp_path / "exported.gguf"
+ fake_gguf.write_bytes(b"GGUF_TEST")
+
+ with patch("soup_cli.commands.export._auto_deploy_ollama") as mock_deploy, \
+ patch("soup_cli.commands.export._maybe_attach_export") as mock_attach, \
+ patch("soup_cli.commands.export._export_gguf_advanced", return_value=fake_gguf), \
+ patch("soup_cli.commands.export._export_bitnet_gguf", return_value=fake_gguf):
+
+ extra_args = ["--gguf-flavour", "Q4_0_4_4"] if fmt == "gguf-ud" else []
+ result = runner.invoke(
+ app,
+ [
+ "export",
+ "--model", str(model_dir),
+ "--format", fmt,
+ "--deploy", "ollama",
+ "--deploy-name", "my-deployed-model",
+ *extra_args,
+ ],
+ )
+
+ assert result.exit_code == 0, f"Command failed: {result.output}"
+ mock_deploy.assert_called_once()
+ call_args = mock_deploy.call_args[0]
+ assert call_args[0] == fake_gguf
+ assert call_args[2] == "ollama"
+ assert call_args[3] == "my-deployed-model"
+ mock_attach.assert_called_once()
+
+
+ ("fmt", "patch_target", "expected_kind"),
+ [
+ ("onnx", "soup_cli.commands.export._export_onnx", "onnx"),
+ ("tensorrt", "soup_cli.commands.export._export_tensorrt", "tensorrt"),
+ ("awq", "soup_cli.commands.export._export_awq", "awq"),
+ ("gptq", "soup_cli.commands.export._export_gptq", "gptq"),
+ ("torchao", "soup_cli.commands.export._export_torchao_cli", "torchao"),
+ ("gguf-ud", "soup_cli.commands.export._export_gguf_advanced", "gguf"),
+ ("bitnet", "soup_cli.commands.export._export_bitnet_gguf", "gguf"),
+ ("tq1_0", "soup_cli.commands.export._export_bitnet_gguf", "gguf"),
+ ],
+)
+def test_export_wires_registry_id_across_all_formats(
+ tmp_path: Path, fmt: str, patch_target: str, expected_kind: str
+):
+ """Every export format must attach its artifact via _maybe_attach_export with --registry-id."""
+ model_dir = tmp_path / "model"
+ model_dir.mkdir()
+ exported_file = tmp_path / f"export_{fmt}.bin"
+ exported_file.write_bytes(b"DATA")
+
+ with patch(patch_target, return_value=exported_file), \
+ patch("soup_cli.commands.export._maybe_attach_export") as mock_attach:
+
+ extra_args = []
+ if fmt == "gguf-ud":
+ extra_args = ["--gguf-flavour", "Q4_0_4_4"]
+ elif fmt == "torchao":
+ q_file = tmp_path / "q.yaml"
+ q_file.write_text("scheme: int8wo\n", encoding="utf-8")
+ extra_args = ["--quant-config", str(q_file)]
+
+ result = runner.invoke(
+ app,
+ [
+ "export",
+ "--model", str(model_dir),
+ "--format", fmt,
+ "--registry-id", "reg-12345",
+ *extra_args,
+ ],
+ )
+
+ assert result.exit_code == 0, f"Export for {fmt} failed: {result.output}"
+ mock_attach.assert_called_once()
+ kwargs = mock_attach.call_args[1]
+ assert kwargs["explicit_id"] == "reg-12345"
+ assert kwargs["kind"] == expected_kind
+ assert kwargs["artifact_path"] == str(exported_file)
+
+
+def test_the_real_helper_hands_its_output_to_the_registry(tmp_path: Path, monkeypatch):
+ """Integration test: CLI command dispatches to real _maybe_attach_export and registers in DB."""
+ from soup_cli.registry.store import RegistryStore
+
+ monkeypatch.chdir(tmp_path)
+ db_path = tmp_path / "reg.db"
+ monkeypatch.setenv("SOUP_REGISTRY_DB_PATH", str(db_path))
+
+ store = RegistryStore(db_path=db_path)
+ entry_id = store.push(
+ name="my-onnx-model", tag="v1", base_model="org/base", task="sft", run_id=None, config={},
+ )
+ store.close()
+
+ model_dir = tmp_path / "model"
+ model_dir.mkdir()
+ exported_file = tmp_path / "output.onnx"
+ exported_file.write_bytes(b"MODEL_DATA")
+
+ with patch("soup_cli.commands.export._export_onnx", return_value=exported_file):
+ result = runner.invoke(
+ app,
+ [
+ "export",
+ "--model", str(model_dir),
+ "--format", "onnx",
+ "--registry-id", entry_id,
+ ],
+ )
+
+ assert result.exit_code == 0, result.output
+ output = _clean(result.output)
+ expected_msg = (
+ f"Attached export to registry entry '{entry_id}' as onnx ({exported_file.name})"
+ )
+ assert expected_msg in output
+
+ store = RegistryStore(db_path=db_path)
+ artifacts = store.get_artifacts(entry_id)
+ store.close()
+
+ assert len(artifacts) == 1
+ assert artifacts[0]["kind"] == "onnx"
+ assert os.path.realpath(artifacts[0]["path"]) == os.path.realpath(str(exported_file))
+
+
+def test_maybe_attach_export_resolves_directory_to_primary_file(tmp_path: Path, monkeypatch):
+ """When artifact_path is a directory, _maybe_attach_export finds the primary model file."""
+ from soup_cli.commands.export import _maybe_attach_export
+ from soup_cli.registry.store import RegistryStore
+
+ monkeypatch.chdir(tmp_path)
+ db_path = tmp_path / "reg.db"
+ monkeypatch.setenv("SOUP_REGISTRY_DB_PATH", str(db_path))
+
+ store = RegistryStore(db_path=db_path)
+ entry_id = store.push(
+ name="test-model", tag="v1", base_model="org/base", task="sft", run_id=None, config={},
+ )
+ store.close()
+
+ export_dir = tmp_path / "onnx_out"
+ export_dir.mkdir()
+ onnx_file = export_dir / "model.onnx"
+ onnx_file.write_bytes(b"FAKE_ONNX_WEIGHTS")
+
+ _maybe_attach_export(
+ artifact_path=str(export_dir),
+ kind="onnx",
+ explicit_id=entry_id,
+ source_model=str(tmp_path / "source"),
+ )
+
+ store = RegistryStore(db_path=db_path)
+ artifacts = store.get_artifacts(entry_id)
+ store.close()
+
+ assert len(artifacts) == 1
+ assert artifacts[0]["kind"] == "onnx"
+ assert os.path.realpath(artifacts[0]["path"]) == os.path.realpath(str(onnx_file))
+
+
+def test_a_tensorrt_export_is_attached(tmp_path: Path, monkeypatch):
+ """TensorRT engine layout (<target>/engine/*.engine) is discovered and attached."""
+ from soup_cli.commands.export import _maybe_attach_export
+ from soup_cli.registry.store import RegistryStore
+
+ monkeypatch.chdir(tmp_path)
+ db_path = tmp_path / "reg.db"
+ monkeypatch.setenv("SOUP_REGISTRY_DB_PATH", str(db_path))
+
+ store = RegistryStore(db_path=db_path)
+ entry_id = store.push(
+ name="trt-model", tag="v1", base_model="org/base", task="sft", run_id=None, config={},
+ )
+ store.close()
+
+ trt_dir = tmp_path / "trt_out"
+ (trt_dir / "checkpoint").mkdir(parents=True)
+ (trt_dir / "checkpoint" / "config.json").write_text("{}", encoding="utf-8")
+ (trt_dir / "engine").mkdir(parents=True)
+ engine_file = trt_dir / "engine" / "rank0.engine"
+ engine_file.write_bytes(b"TRT_ENGINE_BYTES")
+
+ _maybe_attach_export(
+ artifact_path=str(trt_dir),
+ kind="tensorrt",
+ explicit_id=entry_id,
+ source_model=str(tmp_path / "source"),
+ )
+
+ store = RegistryStore(db_path=db_path)
+ artifacts = store.get_artifacts(entry_id)
+ store.close()
+
+ assert len(artifacts) == 1
+ assert artifacts[0]["kind"] == "tensorrt"
+ assert os.path.realpath(artifacts[0]["path"]) == os.path.realpath(str(engine_file))
+
+
+def test_directory_with_multiple_shards_attaches_all_shards(tmp_path: Path, monkeypatch):
+ """Directory export containing multiple shards attaches all shard files."""
+ from soup_cli.commands.export import _maybe_attach_export
+ from soup_cli.registry.store import RegistryStore
+
+ monkeypatch.chdir(tmp_path)
+ db_path = tmp_path / "reg.db"
+ monkeypatch.setenv("SOUP_REGISTRY_DB_PATH", str(db_path))
+
+ store = RegistryStore(db_path=db_path)
+ entry_id = store.push(
+ name="multi-shard", tag="v1", base_model="org/base", task="sft", run_id=None, config={},
+ )
+ store.close()
+
+ export_dir = tmp_path / "sharded_out"
+ export_dir.mkdir()
+ shard1 = export_dir / "model-00001-of-00002.safetensors"
+ shard2 = export_dir / "model-00002-of-00002.safetensors"
+ shard1.write_bytes(b"SHARD1")
+ shard2.write_bytes(b"SHARD2")
+ (export_dir / "tokenizer.json").write_text("{}", encoding="utf-8")
+
+ _maybe_attach_export(
+ artifact_path=str(export_dir),
+ kind="torchao",
+ explicit_id=entry_id,
+ source_model=str(tmp_path / "source"),
+ )
+
+ store = RegistryStore(db_path=db_path)
+ artifacts = store.get_artifacts(entry_id)
+ store.close()
+
+ assert len(artifacts) == 2
+ attached_paths = {os.path.realpath(a["path"]) for a in artifacts}
+ assert attached_paths == {os.path.realpath(str(shard1)), os.path.realpath(str(shard2))}
+ assert all(a["kind"] == "torchao" for a in artifacts)
+
+
+def test_onnx_external_data_attaches_both_files(tmp_path: Path, monkeypatch):
+ """ONNX export with external data file (.onnx + .onnx_data) attaches both."""
+ from soup_cli.commands.export import _maybe_attach_export
+ from soup_cli.registry.store import RegistryStore
+
+ monkeypatch.chdir(tmp_path)
+ db_path = tmp_path / "reg.db"
+ monkeypatch.setenv("SOUP_REGISTRY_DB_PATH", str(db_path))
+
+ store = RegistryStore(db_path=db_path)
+ entry_id = store.push(
+ name="onnx-large", tag="v1", base_model="org/base", task="sft", run_id=None, config={},
+ )
+ store.close()
+
+ export_dir = tmp_path / "onnx_dir"
+ export_dir.mkdir()
+ onnx_file = export_dir / "model.onnx"
+ data_file = export_dir / "model.onnx_data"
+ onnx_file.write_bytes(b"ONNX_GRAPH")
+ data_file.write_bytes(b"ONNX_WEIGHTS")
+
+ _maybe_attach_export(
+ artifact_path=str(export_dir),
+ kind="onnx",
+ explicit_id=entry_id,
+ source_model=str(tmp_path / "source"),
+ )
+
+ store = RegistryStore(db_path=db_path)
+ artifacts = store.get_artifacts(entry_id)
+ store.close()
+
+ assert len(artifacts) == 2
+ attached_paths = {os.path.realpath(a["path"]) for a in artifacts}
+ assert attached_paths == {os.path.realpath(str(onnx_file)), os.path.realpath(str(data_file))}
+ assert all(a["kind"] == "onnx" for a in artifacts)
+
+
+def test_torchao_dense_export_artifact_beats_lora_config():
+ """A torchao export proves the artifact is a standalone model even if trained via LoRA."""
+ from soup_cli.commands.card import _DENSE_KINDS, _is_adapter
+
+ assert "torchao" in _DENSE_KINDS
+ artifacts = [{"kind": "torchao", "path": "model.torchao", "sha256": "x"}]
+ config = {"training": {"lora": {"r": 8}}}
+ assert _is_adapter(artifacts, config) is False
+
diff --git a/tests/test_issue1448_real_helpers.py b/tests/test_issue1448_real_helpers.py
new file mode 100644
index 00000000..c5c05b97
--- /dev/null
+++ b/tests/test_issue1448_real_helpers.py
@@ -0,0 +1,162 @@
+"""#1448: `soup export --registry-id` with the real helpers; only the converters are stubbed.
+
+The helpers' own ``return output_path`` is what hands the exported path to the registry, so
+nothing here replaces a helper: each test stubs the third-party converter one level below it and
+checks what the registry recorded.
+"""
+
+from __future__ import annotations
+
+import subprocess
+import sys
+import types
+from pathlib import Path
+from unittest.mock import patch
+
+import pytest
+from typer.testing import CliRunner
+
+from soup_cli.cli import app
+from soup_cli.registry.store import RegistryStore
+
+runner = CliRunner()
+
+
+def _write(path, size=10):
+ path = Path(path)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(b"x" * size)
+
+
+def _module(name, **attrs):
+ module = types.ModuleType(name)
+ for key, value in attrs.items():
+ setattr(module, key, value)
+ return module
+
+
+def _quantizer(module_name, cls_name, saved_name):
+ class _Model:
+ def quantize(self, *args, **kwargs):
+ return None
+
+ def save_quantized(self, path):
+ _write(Path(path) / saved_name, 3000)
+
+ return {
+ module_name: _module(
+ module_name,
+ BaseQuantizeConfig=lambda **kwargs: None,
+ **{cls_name: types.SimpleNamespace(from_pretrained=lambda *a, **k: _Model())},
+ )
+ }
+
+
+def _gptq_modules():
+ return _quantizer("auto_gptq", "AutoGPTQForCausalLM", "gptq_model-4bit-128g.safetensors")
+
+
+def _awq_modules():
+ return _quantizer("awq", "AutoAWQForCausalLM", "model.safetensors")
+
+
+def _onnx_modules():
+ def main_export(model_name_or_path, output, task):
+ _write(Path(output) / "model.onnx", 100)
+ _write(Path(output) / "model.onnx_data", 5000)
+
+ return {
+ "optimum": _module("optimum"),
+ "optimum.exporters": _module("optimum.exporters"),
+ "optimum.exporters.onnx": _module("optimum.exporters.onnx", main_export=main_export),
+ }
+
+
+def _tensorrt_modules():
+ names = ("tensorrt_llm", "tensorrt_llm.commands", "tensorrt_llm.commands.convert_checkpoint")
+ return {name: _module(name) for name in names}
+
+
+def _fake_run(argv, **_kwargs):
+ # convert_checkpoint fills <out>/checkpoint, trtllm-build fills <out>/engine
+ out = Path(argv[argv.index("--output_dir") + 1])
+ _write(out / ("rank0.engine" if argv[0] == "trtllm-build" else "rank0.safetensors"), 4000)
+ return subprocess.CompletedProcess(argv, 0, "", "")
+
+
+class _Tokenizer:
+ def __call__(self, *args, **kwargs):
+ return {}
+
+ def save_pretrained(self, path):
+ _write(Path(path) / "tokenizer.json")
+
+
+def _gguf(*, output_path, **_kwargs):
+ _write(output_path, 2000)
+
+
+def _torchao(*, output_dir, **_kwargs):
+ _write(Path(output_dir) / "pytorch_model.bin", 3000)
+
+
+# format -> (extra CLI args, third-party modules to stub, what the registry must hold)
+CASES = {
+ "onnx": ([], _onnx_modules,
+ [("onnx", "model.onnx"), ("onnx", "model.onnx_data")]),
+ "tensorrt": ([], _tensorrt_modules,
+ [("tensorrt", "rank0.engine")]),
+ "awq": (["--calibration-data", "calib.jsonl"], _awq_modules,
+ [("awq", "model.safetensors")]),
+ "gptq": (["--calibration-data", "calib.jsonl"], _gptq_modules,
+ [("gptq", "model.safetensors")]),
+ "torchao": (["--quant-config", "q.yaml"], dict,
+ [("torchao", "pytorch_model.bin")]),
+ "gguf-ud": (["--gguf-flavour", "Q4_0_4_4"], dict, [("gguf", "out.gguf")]),
+ "bitnet": ([], dict, [("gguf", "out.gguf")]),
+ "tq1_0": ([], dict, [("gguf", "out.gguf")]),
+}
+
+
[email protected]("fmt", sorted(CASES))
+def test_every_format_attaches_what_its_helper_returned(tmp_path, monkeypatch, fmt):
+ extra_args, modules, expected = CASES[fmt]
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.setenv("SOUP_REGISTRY_DB_PATH", str(tmp_path / "reg.db"))
+ (tmp_path / "model").mkdir()
+ (tmp_path / "model" / "config.json").write_text("{}", encoding="utf-8")
+ (tmp_path / "calib.jsonl").write_text('{"text": "hello"}\n', encoding="utf-8")
+ (tmp_path / "q.yaml").write_text("scheme: Int4WeightOnly\n", encoding="utf-8")
+ with RegistryStore() as store:
+ entry_id = store.push(
+ name="m", tag="v1", base_model="org/base", task="sft", run_id=None, config={},
+ )
+ for name, module in modules().items():
+ monkeypatch.setitem(sys.modules, name, module)
+ if "transformers" not in sys.modules:
+ monkeypatch.setitem(
+ sys.modules,
+ "transformers",
+ _module(
+ "transformers",
+ AutoTokenizer=types.SimpleNamespace(from_pretrained=lambda *a, **k: _Tokenizer()),
+ ),
+ )
+
+ with patch.object(subprocess, "run", _fake_run), \
+ patch("transformers.AutoTokenizer.from_pretrained", lambda *a, **k: _Tokenizer()), \
+ patch("soup_cli.utils.save_formats.export_torchao", _torchao), \
+ patch("soup_cli.utils.gguf_quant.export_advanced_gguf", _gguf), \
+ patch("soup_cli.utils.bitnet.export_bitnet_gguf", _gguf), \
+ patch("soup_cli.commands.export._find_llama_cpp", return_value=Path("llama")):
+ output = "out.gguf" if fmt in ("gguf-ud", "bitnet", "tq1_0") else f"out_{fmt}"
+ result = runner.invoke(
+ app,
+ ["export", "--model", "model", "--format", fmt, "-o", output,
+ "--registry-id", entry_id, *extra_args],
+ )
+
+ assert result.exit_code == 0, (result.output, repr(result.exception))
+ with RegistryStore() as store:
+ rows = [(row["kind"], Path(row["path"]).name) for row in store.get_artifacts(entry_id)]
+ assert sorted(rows) == sorted(expected)