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(cli): validate benchmark and CUDA graph requests before loading (#1841)
Nariman Abdikarimdaf9b88740fc
diff --git a/changelog.d/0.76.0/1841.fixed.md b/changelog.d/0.76.0/1841.fixed.mdnew file mode 100644index 00000000..6a3a8c33--- /dev/null+++ b/changelog.d/0.76.0/1841.fixed.md@@ -0,0 +1 @@+- Early CLI validation and device preflight checks for `soup bench train` (`--steps <= --warmup`), `soup recipes verify` (missing or unparseable `--config`), and `soup infer` / `soup bench infer` (`--cuda-graphs` on non-CUDA setups) now refuse in well under a second before torch is imported or a model is loaded (#1817 by @Nari-Ab in #1841).diff --git a/src/soup_cli/bench/train_run.py b/src/soup_cli/bench/train_run.pyindex 411de90f..194a3c52 100644--- a/src/soup_cli/bench/train_run.py+++ b/src/soup_cli/bench/train_run.py@@ -31,6 +31,16 @@ def bench_scope_error(cfg: Any) -> Optional[str]:return None+def check_steps_warmup(steps: int, warmup: int) -> Optional[str]:+ """Return an error message if steps <= warmup, else None."""+ if steps <= warmup:+ return (+ f"--steps {steps} leaves nothing after --warmup {warmup}: raise "+ f"--steps or lower --warmup."+ )+ return None++def config_hash(resolved: dict) -> str:"""sha256 of the fully resolved config, so a schema-default change that movesthe run is visible in the report (#716)."""@@ -195,18 +205,16 @@ def run_bench_train(``clock_sampler`` builds the SM-clock sampler; by default a:class:`ClockSampler` on CUDA and none elsewhere. Tests inject one on CPU."""+ err = check_steps_warmup(steps, warmup)+ if err is not None:+ raise ValueError(err)+import torchfrom soup_cli.bench.collector import BenchCollector, summarize_trainablefrom soup_cli.bench.train_report import check_trainable, summarize_clock_samplesfrom soup_cli.trainer.sft import SFTTrainerWrapper- if steps <= warmup:- raise ValueError(- f"--steps {steps} leaves nothing after --warmup {warmup}: raise "- f"--steps or lower --warmup."- )-with tempfile.TemporaryDirectory(prefix="soup-bench-") as scratch:# Log every step (the grad_norm check reads each one), never save, and# never write into the config's own output directory.diff --git a/src/soup_cli/commands/bench.py b/src/soup_cli/commands/bench.pyindex 93908ea4..ee361fee 100644--- a/src/soup_cli/commands/bench.py+++ b/src/soup_cli/commands/bench.py@@ -85,8 +85,6 @@ def bench(),) -> None:"""Run an inference benchmark (speed and memory) on a loaded model."""- import torch-from soup_cli.commands.infer import _generate, _load_model, _resolve_model_sourcefrom soup_cli.utils.gpu import detect_device@@ -106,8 +104,6 @@ def bench()model_target = model_ref- device, _ = detect_device()-# v0.53.9 #28 — backend auto-detect.from soup_cli.utils.backend_detect import SUPPORTED_BACKENDS, detect_backend@@ -132,6 +128,23 @@ def bench("backend")+ if cuda_graphs is True:+ from soup_cli.commands.infer import _with_omit_hint+ from soup_cli.utils.cuda_graphs import check_cuda_graphs_preflight+ from soup_cli.utils.terminal import for_terminal++ try:+ check_cuda_graphs_preflight(+ device=None,+ model_target=model_ref if model_kind == "local" else None,+ base=base,+ )+ except RuntimeError as exc:+ console.print(f"[red]{for_terminal(_with_omit_hint(str(exc)))}[/]")+ raise typer.Exit(1) from exc++ device, _ = detect_device()+if device == "cpu":console.print("[yellow]Warning:[/] Running on CPU. Inference speed is typically "@@ -220,6 +233,8 @@ def bench(# Reset peak stats before load -- "Max VRAM" reflects total footprint# (model load + inference), i.e. what users need for deployment planning.+ import torch+if torch.cuda.is_available():torch.cuda.reset_peak_memory_stats()@@ -372,6 +387,13 @@ def train(console.print(f"[red]Invalid output:[/] {for_terminal(exc)}")raise typer.Exit(2) from exc+ from soup_cli.bench.train_run import check_steps_warmup++ err = check_steps_warmup(steps, warmup)+ if err is not None:+ console.print(f"[red]{err}[/]")+ raise typer.Exit(1)+from soup_cli.bench.train_run import bench_scope_error, run_bench_trainfrom soup_cli.config.loader import load_configfrom soup_cli.data.loader import load_datasetdiff --git a/src/soup_cli/commands/infer.py b/src/soup_cli/commands/infer.pyindex 8af248a8..e7376893 100644--- a/src/soup_cli/commands/infer.py+++ b/src/soup_cli/commands/infer.py@@ -239,6 +239,19 @@ def infer(console.print("[dim]Expected JSONL with {\"prompt\": \"...\"} or plain text lines.[/]")raise typer.Exit(1)+ if cuda_graphs is True:+ from soup_cli.utils.cuda_graphs import check_cuda_graphs_preflight++ try:+ check_cuda_graphs_preflight(+ device=device,+ model_target=model_ref if model_kind == "local" else None,+ base=base,+ )+ except RuntimeError as exc:+ console.print(f"[red]{for_terminal(_with_omit_hint(str(exc)))}[/]")+ raise typer.Exit(1) from exc+# Detect deviceif not device:from soup_cli.utils.gpu import detect_devicediff --git a/src/soup_cli/commands/recipes.py b/src/soup_cli/commands/recipes.pyindex 572e7bd4..ad539297 100644--- a/src/soup_cli/commands/recipes.py+++ b/src/soup_cli/commands/recipes.py@@ -169,7 +169,16 @@ def verify(import json as _jsonimport sys- from soup_cli.utils.exit_codes import EXIT_RUNTIME_ERROR+ from soup_cli.utils.exit_codes import EXIT_RUNTIME_ERROR, EXIT_USAGE_ERROR++ # The config loader prints its own warnings (a deprecated value, #759; a+ # staged field, #808) on stdout, ahead of --json's document. Send them to+ # stderr with every other diagnostic.+ with contextlib.redirect_stdout(sys.stderr):+ configs = _configs_to_verify(config, templates)+ if not configs:+ err_console.print("[red]Nothing to verify.[/]")+ raise typer.Exit(EXIT_USAGE_ERROR)# #1117 review: without these the per-stage catch-alls turned a missing# library into a verdict (unverified, exit 0; or cannot_attach, exit 2).@@ -195,16 +204,6 @@ def verify(check_attach,load_hf_config,)- from soup_cli.utils.exit_codes import EXIT_USAGE_ERROR-- # The config loader prints its own warnings (a deprecated value, #759; a- # staged field, #808) on stdout, ahead of --json's document. Send them to- # stderr with every other diagnostic.- with contextlib.redirect_stdout(sys.stderr):- configs = _configs_to_verify(config, templates)- if not configs:- err_console.print("[red]Nothing to verify.[/]")- raise typer.Exit(EXIT_USAGE_ERROR)report = PreflightReport()for name, cfg in configs:diff --git a/src/soup_cli/utils/cuda_graphs.py b/src/soup_cli/utils/cuda_graphs.pyindex 4889eb25..96de5e51 100644--- a/src/soup_cli/utils/cuda_graphs.py+++ b/src/soup_cli/utils/cuda_graphs.py@@ -11,12 +11,16 @@ from __future__ import annotationsimport functoolsimport inspect+import json+import osimport re+import sysimport threadingfrom importlib import import_modulefrom itertools import chain+from pathlib import Pathfrom types import SimpleNamespace-from typing import Any+from typing import Any, Optional_BACKEND_NAME = "soup_cudagraphs"_REGISTRATION_LOCK = threading.Lock()@@ -56,6 +60,93 @@ def _cuda_device_key(device: Any) -> str:return value+def _is_cuda_available_light() -> bool:+ """Lightweight check for CUDA availability without importing torch.++ A driver-less ROCm setup reports False.+ """+ if "torch" in sys.modules:+ import torch++ return bool(torch.cuda.is_available())+ if sys.platform == "darwin":+ return False+ visible = os.environ.get("CUDA_VISIBLE_DEVICES")+ if visible is not None and visible.strip() in ("", "-1"):+ return False+ try:+ import ctypes++ if sys.platform == "win32":+ lib = ctypes.CDLL("nvcuda.dll")+ else:+ lib = ctypes.CDLL("libcuda.so.1")+ if lib.cuInit(0) != 0:+ return False+ count = ctypes.c_int()+ if lib.cuDeviceGetCount(ctypes.byref(count)) != 0:+ return False+ return count.value > 0+ except (OSError, AttributeError):+ return False+++def check_cuda_graphs_preflight(+ device: Optional[str] = None,+ model_target: Optional[str] = None,+ base: Optional[str] = None,+) -> None:+ """Pre-flight checks for CUDA graphs before loading model weights or torch."""+ if device is not None:+ normalized = str(device).strip().lower()+ if not (normalized == "cuda" or normalized.startswith("cuda:")):+ raise RuntimeError("CUDA graphs require every model tensor on a single CUDA device")+ else:+ if not _is_cuda_available_light():+ raise RuntimeError("CUDA graphs require every model tensor on a single CUDA device")++ for target in (model_target, base):+ if not target:+ continue+ target_path = Path(target)+ if not target_path.is_dir():+ continue++ adapter_cfg_file = target_path / "adapter_config.json"+ if adapter_cfg_file.is_file():+ try:+ with open(adapter_cfg_file, encoding="utf-8") as f:+ adapter_cfg = json.load(f)+ if isinstance(adapter_cfg, dict):+ peft_type = adapter_cfg.get("peft_type")+ if peft_type and peft_type != "LORA":+ raise RuntimeError(+ f"CUDA graph decoding supports LoRA adapters only, not {peft_type}"+ )+ if adapter_cfg.get("use_dora") is True:+ raise RuntimeError("CUDA graph decoding does not support DoRA adapters")+ except (OSError, ValueError):+ pass++ cfg_file = target_path / "config.json"+ if cfg_file.is_file():+ try:+ with open(cfg_file, encoding="utf-8") as f:+ cfg_data = json.load(f)+ if isinstance(cfg_data, dict):+ model_type = cfg_data.get("model_type")+ if model_type and model_type not in ("qwen2", "llama"):+ raise RuntimeError(+ "CUDA graph decoding supports stock Qwen2 and Llama causal models"+ )+ if cfg_data.get("quantization_config") is not None:+ raise RuntimeError(+ "CUDA graph decoding currently requires an unquantized model"+ )+ except (OSError, ValueError):+ pass++def _has_offload_hook(hook: Any) -> bool:return bool(getattr(hook, "offload", False)) or any(_has_offload_hook(child) for child in getattr(hook, "hooks", ())diff --git a/tests/test_cli_startup_is_light.py b/tests/test_cli_startup_is_light.pyindex 058a1112..15b822cd 100644--- a/tests/test_cli_startup_is_light.py+++ b/tests/test_cli_startup_is_light.py@@ -21,6 +21,13 @@ import sysimport pytest+from tests.conftest import strip_ansi+++def _plain(text: str) -> str:+ """Whitespace-collapsed, ANSI-stripped output."""+ return " ".join(strip_ansi(text).split())+# Heavy deps that the documented "light core" (v0.71.0 deps-split) excludes.# These live behind the [train] extra; the CLI must import without them.HEAVY = ("torch", "transformers", "accelerate", "peft", "trl", "datasets", "bitsandbytes")@@ -94,6 +101,7 @@ def test_probe_would_catch_a_regression():"soup_cli.utils.advise","soup_cli.eval.gate_suites","soup_cli.recipes.catalog",+ "soup_cli.utils.cuda_graphs",],)def test_documented_light_module_stays_light(module: str):@@ -246,3 +254,153 @@ def test_stress_sentinel_matches_the_controller():from soup_cli.utils import reward_hack_control, reward_stressassert reward_stress.DEFAULT_SENTINEL == reward_hack_control._DEFAULT_SENTINEL+++def _invoke_with_probe(argv: list[str], monkey_patch_code: str = "") -> tuple[int, list[str], str]:+ """Run an invocation in a clean subprocess, returning (exit_code, leaked_deps, output)."""+ probe = (+ "import sys\n"+ f"{monkey_patch_code}\n"+ "from typer.testing import CliRunner\n"+ "from soup_cli.cli import app\n"+ f"r = CliRunner().invoke(app, {argv!r})\n"+ "leaked = ','.join(sorted(m for m in " + repr(HEAVY) + " if m in sys.modules))\n"+ "print('---SOUPPROBE---')\n"+ "print(r.exit_code)\n"+ "print(leaked)\n"+ "print(r.output)\n"+ )+ proc = subprocess.run(+ [sys.executable, "-c", probe],+ capture_output=True,+ text=True,+ timeout=300,+ )+ assert proc.returncode == 0, (proc.stdout, proc.stderr)+ parts = proc.stdout.split("---SOUPPROBE---\n", 1)[1]+ exit_code_str, leaked_str, output = parts.split("\n", 2)+ leaked = [m for m in leaked_str.strip().split(",") if m]+ return int(exit_code_str), leaked, output++[email protected](("steps", "warmup"), [("2", "5"), ("2", "2")])+def test_bench_train_warmup_refusal_is_light(tmp_path, steps, warmup):+ """bench train --steps <= --warmup must refuse before loading torch (#1817)."""+ cfg_file = tmp_path / "soup.yaml"+ cfg_file.write_text(+ "base: meta-llama/Llama-3.1-8B-Instruct\n"+ "task: sft\n"+ "data:\n"+ " train: ./data/train.jsonl\n"+ " format: auto\n"+ "training:\n"+ " epochs: 1\n"+ " lr: 2e-4\n",+ encoding="utf-8",+ )+ exit_code, leaked, output = _invoke_with_probe(+ ["bench", "train", "-c", str(cfg_file), "--steps", steps, "--warmup", warmup]+ )+ assert exit_code == 1+ assert (+ f"--steps {steps} leaves nothing after --warmup {warmup}: raise "+ f"--steps or lower --warmup."+ ) in _plain(output)+ assert not leaked, f"bench train early refusal pulled in {leaked}"+++def test_recipes_verify_missing_config_refusal_is_light():+ """recipes verify with non-existent config must exit 3 before loading torch (#1817)."""+ exit_code, leaked, output = _invoke_with_probe(+ ["recipes", "verify", "-c", "nonexistent_recipe_file.yaml"]+ )+ assert exit_code == 3+ assert "Config not found: nonexistent_recipe_file.yaml" in _plain(output)+ assert not leaked, f"recipes verify missing config pulled in {leaked}"+++def test_recipes_verify_unparseable_config_refusal_is_light(tmp_path):+ """recipes verify with unparseable config must exit 3 before loading torch (#1817)."""+ bad_cfg = tmp_path / "bad.yaml"+ bad_cfg.write_text("invalid: yaml: [", encoding="utf-8")+ exit_code, leaked, output = _invoke_with_probe(+ ["recipes", "verify", "-c", str(bad_cfg)]+ )+ assert exit_code == 3+ assert "Config does not parse:" in _plain(output)+ assert not leaked, f"recipes verify unparseable config pulled in {leaked}"+++def test_cuda_graphs_cpu_refusal_is_light(tmp_path):+ """infer and bench infer with --cuda-graphs on CPU must exit before loading torch (#1817)."""+ model_dir = tmp_path / "model"+ model_dir.mkdir(exist_ok=True)+ (model_dir / "config.json").write_text("{}", encoding="utf-8")+ prompt_file = tmp_path / "prompts.jsonl"+ prompt_file.write_text('{"prompt": "hello"}\n', encoding="utf-8")+ out_file = tmp_path / "out.jsonl"++ expected_msg = (+ "CUDA graphs require every model tensor on a single CUDA device. Omit --cuda-graphs."+ )++ # bench infer on CPU (force CPU via CUDA_VISIBLE_DEVICES="" probe environment)+ env_code = "import os; os.environ['CUDA_VISIBLE_DEVICES'] = ''"+ exit_code, leaked, output = _invoke_with_probe(+ ["bench", "infer", str(model_dir), "--cuda-graphs"],+ monkey_patch_code=env_code,+ )+ assert exit_code == 1+ assert expected_msg in _plain(output)+ assert not leaked, f"bench infer --cuda-graphs pulled in {leaked}"++ # infer on CPU without --device+ exit_code, leaked, output = _invoke_with_probe(+ [+ "infer",+ "-m",+ str(model_dir),+ "-i",+ str(prompt_file),+ "-o",+ str(out_file),+ "--cuda-graphs",+ ],+ monkey_patch_code=env_code,+ )+ assert exit_code == 1+ assert expected_msg in _plain(output)+ assert not leaked, f"infer --cuda-graphs pulled in {leaked}"++ # infer on explicit --device cpu+ exit_code, leaked, output = _invoke_with_probe(+ [+ "infer",+ "-m",+ str(model_dir),+ "-i",+ str(prompt_file),+ "-o",+ str(out_file),+ "--device",+ "cpu",+ "--cuda-graphs",+ ],+ )+ assert exit_code == 1+ assert expected_msg in _plain(output)+ assert not leaked, f"infer --device cpu --cuda-graphs pulled in {leaked}"+++def test_check_steps_warmup_logic():+ """check_steps_warmup helper catches steps <= warmup without pulling in torch."""+ from soup_cli.bench.train_run import check_steps_warmup++ assert check_steps_warmup(2, 5) == (+ "--steps 2 leaves nothing after --warmup 5: raise --steps or lower --warmup."+ )+ assert check_steps_warmup(2, 2) == (+ "--steps 2 leaves nothing after --warmup 2: raise --steps or lower --warmup."+ )+ assert check_steps_warmup(3, 2) is None+diff --git a/tests/test_cuda_graph_cli.py b/tests/test_cuda_graph_cli.pyindex a7dc1d8d..8e6243a8 100644--- a/tests/test_cuda_graph_cli.py+++ b/tests/test_cuda_graph_cli.py@@ -86,6 +86,7 @@ def _infer_env(monkeypatch, tmp_path, prompts, generate):(tmp_path / "prompts.txt").write_text("\n".join(prompts) + "\n")monkeypatch.setattr("soup_cli.utils.gpu.detect_device", lambda: ("cpu", None))monkeypatch.setattr("torch.cuda.is_available", lambda: False)+ monkeypatch.setattr("soup_cli.utils.cuda_graphs._is_cuda_available_light", lambda: True)monkeypatch.setattr("soup_cli.utils.cuda_graphs.cuda_graph_generation_kwargs", lambda model: {})monkeypatch.setattr(infer, "_load_model", MagicMock(return_value=(object(), object())))monkeypatch.setattr(infer, "_count_prompt_tokens", lambda tokenizer, text: len(text.split()))@@ -166,6 +167,7 @@ def test_unsupported_graph_model_preserves_existing_output(monkeypatch, tmp_pathoutput = tmp_path / "output.jsonl"output.write_text("previous results\n")monkeypatch.setattr("soup_cli.utils.gpu.detect_device", lambda: ("cpu", None))+ monkeypatch.setattr("soup_cli.utils.cuda_graphs._is_cuda_available_light", lambda: True)monkeypatch.setattr(infer, "_load_model", MagicMock(return_value=(object(), object())))reject = MagicMock(side_effect=RuntimeError("Unsupported model for CUDA graphs"))monkeypatch.setattr("soup_cli.utils.cuda_graphs.cuda_graph_generation_kwargs", reject)@@ -183,6 +185,20 @@ def test_unsupported_graph_model_preserves_existing_output(monkeypatch, tmp_pathgenerate.assert_not_called()+def test_cpu_refusal_happens_before_the_model_loads(monkeypatch, tmp_path):+ from soup_cli.cli import app+ from soup_cli.commands import infer++ model_dir = _infer_env(monkeypatch, tmp_path, ["question"], MagicMock())+ monkeypatch.setattr("soup_cli.utils.cuda_graphs._is_cuda_available_light", lambda: False)+ load = MagicMock()+ monkeypatch.setattr(infer, "_load_model", load)+ result = CliRunner().invoke(app, _infer_args(model_dir, "--cuda-graphs"))+ assert result.exit_code == 1+ assert "single CUDA device" in _plain(result.output)+ load.assert_not_called()++def test_infer_warms_up_greedily_on_the_longest_prompt_before_writing(monkeypatch, tmp_path):from soup_cli.cli import app@@ -462,3 +478,72 @@ def test_bench_timed_failure_is_named_and_the_default_re_raises(monkeypatch, tmpmonkeypatch.setattr(infer, "_generate", MagicMock(side_effect=[("warm", 1), boom]))result = CliRunner().invoke(app, _bench_args(model_dir))assert result.exception is boom+++def _invoke(command, model_dir, *extra):+ from soup_cli.cli import app++ if command == "bench":+ args = ["bench", "infer", str(model_dir), "--num-prompts", "1", *extra]+ else:+ args = _infer_args(model_dir, *extra)+ return CliRunner().invoke(app, [*args, "--cuda-graphs"])++[email protected]("command", ["infer", "bench"])+def test_local_model_files_are_refused_before_the_model_loads(monkeypatch, tmp_path, command):+ from soup_cli.commands import infer++ model_dir = _infer_env(monkeypatch, tmp_path, ["question"], MagicMock())+ (model_dir / "config.json").write_text(json.dumps({"model_type": "gpt2"}))+ load = MagicMock()+ monkeypatch.setattr(infer, "_load_model", load)+ result = _invoke(command, model_dir)+ assert result.exit_code == 1, (result.output, repr(result.exception))+ assert "stock Qwen2 and Llama" in _plain(result.output)+ assert "Omit --cuda-graphs" in _plain(result.output)+ load.assert_not_called()++[email protected]("command", ["infer", "bench"])+def test_an_explicit_base_directory_is_inspected_too(monkeypatch, tmp_path, command):+ from soup_cli.commands import infer++ model_dir = _infer_env(monkeypatch, tmp_path, ["question"], MagicMock())+ base_dir = tmp_path / "base"+ base_dir.mkdir()+ (base_dir / "config.json").write_text(+ json.dumps({"model_type": "qwen2", "quantization_config": {"bits": 4}})+ )+ load = MagicMock()+ monkeypatch.setattr(infer, "_load_model", load)+ result = _invoke(command, model_dir, "--base", str(base_dir))+ assert result.exit_code == 1, (result.output, repr(result.exception))+ assert "unquantized" in _plain(result.output)+ load.assert_not_called()+++def test_an_explicit_cpu_device_is_refused_even_when_cuda_is_present(monkeypatch, tmp_path):+ from soup_cli.commands import infer++ model_dir = _infer_env(monkeypatch, tmp_path, ["question"], MagicMock()) # CUDA "present"+ load = MagicMock()+ monkeypatch.setattr(infer, "_load_model", load)+ result = _invoke("infer", model_dir, "--device", "cpu")+ assert result.exit_code == 1, (result.output, repr(result.exception))+ assert "single CUDA device" in _plain(result.output)+ load.assert_not_called()++[email protected]("command", ["infer", "bench"])+def test_file_derived_text_in_the_refusal_is_terminal_safe(monkeypatch, tmp_path, command):+ model_dir = _infer_env(monkeypatch, tmp_path, ["question"], MagicMock())+ (model_dir / "adapter_config.json").write_text(+ json.dumps({"peft_type": "EVIL\x1b[2J\x1b]0;pwned\x07"})+ )+ result = _invoke(command, model_dir)+ assert result.exit_code == 1, (result.output, repr(result.exception))+ assert "LoRA adapters only" in _plain(result.output)+ for raw in ("\x1b[2J", "\x1b]0;", "\x07"):+ assert raw not in result.output+diff --git a/tests/test_cuda_graphs_preflight.py b/tests/test_cuda_graphs_preflight.pynew file mode 100644index 00000000..6864951c--- /dev/null+++ b/tests/test_cuda_graphs_preflight.py@@ -0,0 +1,186 @@+"""Tests for CUDA graph pre-flight checks before loading torch or weights (#1817)."""++import json+import sys+import types+from unittest.mock import MagicMock++import pytest++from soup_cli.utils import cuda_graphs+++def cuda_present(monkeypatch):+ monkeypatch.setattr(cuda_graphs, "_is_cuda_available_light", lambda: True)+++def _dir(tmp_path, config=None, adapter=None):+ if config is not None:+ (tmp_path / "config.json").write_text(json.dumps(config), encoding="utf-8")+ if adapter is not None:+ (tmp_path / "adapter_config.json").write_text(json.dumps(adapter), encoding="utf-8")+ return str(tmp_path)+++ ("config", "adapter", "message"),+ [+ ({"model_type": "gpt2"}, None, "stock Qwen2 and Llama"),+ ({"model_type": "qwen2", "quantization_config": {"bits": 4}}, None, "unquantized"),+ (None, {"peft_type": "IA3"}, "LoRA adapters only, not IA3"),+ (None, {"peft_type": "LORA", "use_dora": True}, "DoRA"),+ ],+)+def test_the_model_files_refuse_before_any_load(tmp_path, cuda_present, config, adapter, message):+ with pytest.raises(RuntimeError, match=message):+ cuda_graphs.check_cuda_graphs_preflight(+ device="cuda", model_target=_dir(tmp_path, config, adapter)+ )++[email protected]("model_type", ["qwen2", "llama"])[email protected]("device", ["cuda", "cuda:1", "CUDA", " cuda:0 "])+def test_a_stock_model_on_a_cuda_device_passes(tmp_path, cuda_present, model_type, device):+ cuda_graphs.check_cuda_graphs_preflight(+ device=device, model_target=_dir(tmp_path, {"model_type": model_type})+ )++[email protected]("device", ["cpu", "mps", "cuda0", "cudax"])+def test_a_non_cuda_device_is_refused(device):+ with pytest.raises(RuntimeError, match="single CUDA device"):+ cuda_graphs.check_cuda_graphs_preflight(device=device)++[email protected]("payload", [b"\xff\xfe\x00", b"{not json", b"[]"])+def test_an_unreadable_config_is_left_to_the_loader(tmp_path, cuda_present, payload):+ (tmp_path / "config.json").write_bytes(payload)+ cuda_graphs.check_cuda_graphs_preflight(device="cuda", model_target=str(tmp_path))++[email protected]("payload", [b"\xff\xfe\x00", b"{not json", b"[]"])+def test_an_unreadable_adapter_config_is_left_to_the_loader(tmp_path, cuda_present, payload):+ (tmp_path / "adapter_config.json").write_bytes(payload)+ cuda_graphs.check_cuda_graphs_preflight(device="cuda", model_target=str(tmp_path))+++def test_an_adapter_config_without_peft_type_is_left_to_the_loader(tmp_path, cuda_present):+ (tmp_path / "adapter_config.json").write_text(json.dumps({"r": 8}), encoding="utf-8")+ cuda_graphs.check_cuda_graphs_preflight(device="cuda", model_target=str(tmp_path))++[email protected]("visible", ["", "-1", " -1 "])+def test_is_cuda_available_light_respects_cuda_visible_devices(monkeypatch, visible):+ import ctypes++ monkeypatch.delitem(sys.modules, "torch", raising=False)+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", visible)+ monkeypatch.setattr(ctypes, "CDLL", lambda *a, **kw: pytest.fail("CDLL called"))+ assert cuda_graphs._is_cuda_available_light() is False+++def _driver(monkeypatch, *, init_rc=0, count_rc=0, devices=1, platform="linux", symbols=True):+ import ctypes++ monkeypatch.delitem(sys.modules, "torch", raising=False)+ monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising=False)+ monkeypatch.setattr(sys, "platform", platform)+ opened = []+ lib = MagicMock()+ lib.cuInit.return_value = init_rc++ def get_count(ref):+ ref._obj.value = devices+ return count_rc++ lib.cuDeviceGetCount.side_effect = get_count+ if not symbols:+ del lib.cuInit++ def fake_cdll(name, *args, **kwargs):+ opened.append(name)+ return lib++ monkeypatch.setattr(ctypes, "CDLL", fake_cdll)+ return lib, opened+++ ("platform", "library"), [("linux", "libcuda.so.1"), ("win32", "nvcuda.dll")]+)+def test_the_driver_library_per_platform(monkeypatch, platform, library):+ _, opened = _driver(monkeypatch, platform=platform)+ assert cuda_graphs._is_cuda_available_light() is True+ assert opened == [library]+++def test_a_failing_cuinit_means_no_cuda(monkeypatch):+ lib, _ = _driver(monkeypatch, init_rc=100)+ assert cuda_graphs._is_cuda_available_light() is False+ lib.cuDeviceGetCount.assert_not_called()+++def test_a_failing_device_count_call_means_no_cuda(monkeypatch):+ _driver(monkeypatch, count_rc=1, devices=1)+ assert cuda_graphs._is_cuda_available_light() is False+++def test_zero_devices_means_no_cuda(monkeypatch):+ _driver(monkeypatch, devices=0)+ assert cuda_graphs._is_cuda_available_light() is False+++def test_a_driver_without_the_symbols_means_no_cuda(monkeypatch):+ _driver(monkeypatch, symbols=False)+ assert cuda_graphs._is_cuda_available_light() is False+++def test_macos_never_probes_the_driver(monkeypatch):+ _, opened = _driver(monkeypatch, platform="darwin")+ assert cuda_graphs._is_cuda_available_light() is False+ assert opened == []+++def test_a_missing_driver_library_raises_oserror_means_no_cuda(monkeypatch):+ import ctypes++ _driver(monkeypatch)++ def raise_oserror(*args, **kwargs):+ raise OSError("libcuda.so.1: cannot open shared object file")++ monkeypatch.setattr(ctypes, "CDLL", raise_oserror)+ assert cuda_graphs._is_cuda_available_light() is False+ with pytest.raises(RuntimeError, match="single CUDA device"):+ cuda_graphs.check_cuda_graphs_preflight()++[email protected]("available", [True, False])+def test_a_loaded_torch_is_trusted(monkeypatch, available):+ fake = types.SimpleNamespace(cuda=types.SimpleNamespace(is_available=lambda: available))+ _, opened = _driver(monkeypatch)+ monkeypatch.setitem(sys.modules, "torch", fake)+ assert cuda_graphs._is_cuda_available_light() is available+ assert opened == []+++def test_run_bench_train_refuses_before_importing_torch():+ import subprocess++ probe = (+ "import sys\n"+ "from soup_cli.bench.train_run import run_bench_train\n"+ "try:\n"+ " run_bench_train(None, steps=2, warmup=2, device='cpu', load_dataset=lambda c: {})\n"+ "except ValueError as exc:\n"+ " print('REFUSED', exc)\n"+ "print('TORCH', 'torch' in sys.modules)\n"+ )+ proc = subprocess.run(+ [sys.executable, "-c", probe], capture_output=True, text=True, timeout=120+ )+ assert proc.returncode == 0, proc.stderr+ # ansi-ok: subprocess probe stdout is uncoloured+ assert "REFUSED --steps 2 leaves nothing after --warmup 2" in proc.stdout+ assert "TORCH False" in proc.stdout