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
Remove dormant auto_quant compatibility module (v0.76.0) (#1262)
Kratos452d071fe276
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 2d13bc6c..3e6260b6 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -129,7 +129,7 @@ src/soup_cli/cans/ - Shareable .can artifact format + run/publish orchestrator (v0.26.0 + v0.33.0)data/traces/ - Trace-to-Preference harvester (v0.26.0)data/collators.py - CrossDocCollator for sample packing (v0.33.0)- utils/ - GPU, errors, MoE, GaLore, QAT, Unsloth, vLLM, SGLang, Liger, FlashAttn, FSDP, Ring Attention, long-context, quality, curriculum, freeze, dataset-registry, mlx, peft_builder, paths, topology, launcher, mii, pipeline, cut_ce, fp8, gradient_ckpt, kernel_picker, cross_doc_attn, activation_offload, hf, spec_pairing, structured_output, metrics, tracing, auto_quant, lr_finder, grad_accum, mixed_precision, warmup, spike_recovery, convergence, v028_features, multipack_sampler, multipack, neat_packing, jinja_analyzer, quant_menu, relora, peft_patches, peft_wiring, dpo_variants, optimizer_zoo, lr_groups, loftq_init, block_expansion, tts, classifier, distill, bitnet, ebft_gdpo, moe_quant, reasoning_effort, gguf_quant, kv_cache, advanced_precision, save_formats, deploy_measure, advise, advise_history, adapter_diff, adapter_merge, blame, adapter_branch, unlearning, unlearning_eval, knowledge_edit, edit_governor, edit_diff, ra_dit, steering, citation_faithful, grace_codebook, ingest_sources, prune_prompt, active_sampler, ab_test, drift_alarm, tunability, terraform_plan, env_lock, hardware_fit, completions, license_advisor, behavior_battery, capability_suite, checklist_dsl, irt, sae_diff, sleeper_probe, interference, probe_pack, cmaes_merge, vector_bank, mole_routing, adapter_pr, soup_lock, adapter_bisect, prompt_compile, prompt_distill, compile_tools, apple_adapter, local_rl, build_dag, expectations, magpie, persona_hub, brain_rot, reward_hacking, uld, minillm, rl_checkpoint, iterative_dpo, echo_trap, mod, local_rl_scheduler, spectrum_scan, ship_verdict, reward_hack_control, data_doctor, data_lint, shrink, best_of_n, evolve, reward_synth, reward_stress, layer_stream, layer_shard, layer_stream_runtime+ utils/ - GPU, errors, MoE, GaLore, QAT, Unsloth, vLLM, SGLang, Liger, FlashAttn, FSDP, Ring Attention, long-context, quality, curriculum, freeze, dataset-registry, mlx, peft_builder, paths, topology, launcher, mii, pipeline, cut_ce, fp8, gradient_ckpt, kernel_picker, cross_doc_attn, activation_offload, hf, spec_pairing, structured_output, metrics, tracing, lr_finder, grad_accum, mixed_precision, warmup, spike_recovery, convergence, v028_features, multipack_sampler, multipack, neat_packing, jinja_analyzer, quant_menu, relora, peft_patches, peft_wiring, dpo_variants, optimizer_zoo, lr_groups, loftq_init, block_expansion, tts, classifier, distill, bitnet, ebft_gdpo, moe_quant, reasoning_effort, gguf_quant, kv_cache, advanced_precision, save_formats, deploy_measure, advise, advise_history, adapter_diff, adapter_merge, blame, adapter_branch, unlearning, unlearning_eval, knowledge_edit, edit_governor, edit_diff, ra_dit, steering, citation_faithful, grace_codebook, ingest_sources, prune_prompt, active_sampler, ab_test, drift_alarm, tunability, terraform_plan, env_lock, hardware_fit, completions, license_advisor, behavior_battery, capability_suite, checklist_dsl, irt, sae_diff, sleeper_probe, interference, probe_pack, cmaes_merge, vector_bank, mole_routing, adapter_pr, soup_lock, adapter_bisect, prompt_compile, prompt_distill, compile_tools, apple_adapter, local_rl, build_dag, expectations, magpie, persona_hub, brain_rot, reward_hacking, uld, minillm, rl_checkpoint, iterative_dpo, echo_trap, mod, local_rl_scheduler, spectrum_scan, ship_verdict, reward_hack_control, data_doctor, data_lint, shrink, best_of_n, evolve, reward_synth, reward_stress, layer_stream, layer_shard, layer_stream_runtimetemplates/ - 21 built-in soup.yaml templates (YAML + manifest.json) with load_template loader (v0.39.0, +bco v0.40.0, +4 compliance v0.71.35)ui/ - Web UI (FastAPI + HTML/JS SPA)@@ -286,14 +286,14 @@ Accepted runs are recorded in [`benchmarks/gpu-test-runs.md`](benchmarks/gpu-tes| test_multi_gpu.py | Multi-GPU Mastery: topology, --gpus, accelerate launcher, ZeRO++, FSDP2+compile, pipeline (v0.27.0) || test_training_speed.py | Training Speed & Memory: CCE, FP8, grad-ckpt tiers, kernel picker, cross-doc attn, activation offload (v0.28.0) || test_hf_integration.py | HF Hub Deep Integration: token/endpoint/repo_id, auto-push callback, model card v2, collections, data push, HF Spaces, private-IP SSRF (v0.29.0) |-| test_inference_advanced.py | Inference Excellence: prefix caching, spec-decoding auto-pairing, LoRA hot-swap, structured output, dashboard + /metrics, OpenTelemetry tracing, dormant auto-quant helpers (v0.30.0; serving refuses auto-quant since #816) |+| test_inference_advanced.py | Inference Excellence: prefix caching, spec-decoding auto-pairing, LoRA hot-swap, structured output, dashboard + /metrics, OpenTelemetry tracing (v0.30.0) || test_recipes_v031.py | Model & Recipe Breadth: 34 new recipes (vision/audio/reasoning/edge/domain/multimodal); catalog-wide invariants; CI workflow validation (v0.31.0) || test_auto_tuning.py | Training Stability & Auto-Tuning: LR range finder, grad-accum monitor, auto mixed-precision, auto warmup, spike recovery, convergence detector, autopilot wiring (v0.32.0) || test_part_f_hardening.py | Live Wire Part F: RLVR OS-level sandbox isolation + prune_checkpoints TOCTOU (v0.33.0) || test_part_a_wave1.py | Live Wire Part A: live eval-gate scoring + registry attach (v0.33.0) || test_part_a_wave2.py | Live Wire Part A: soup can run / publish + DeployTarget schema (v0.33.0) || test_part_e.py | Live Wire Part E: --find-lr live loop + spike recovery hint + auto mixed-precision push + grad-accum advisory (v0.33.0) |-| test_part_d.py | Historical Part D primitives: structured-output LogitsProcessor + dormant auto-quant helpers + HF push integration smoke (v0.33.0; serving refuses auto-quant since #816) |+| test_part_d.py | Historical Part D primitives: structured-output LogitsProcessor + HF push integration smoke (v0.33.0) || test_part_c.py | Live Wire Part C: multi-trainer v0.28.0 features + selective ckpt hooks + CrossDocCollator (v0.33.0) || test_part_b.py | Live Wire Part B: auto-reexec under accelerate launch + DeepSpeed-MII live serve (v0.33.0) || test_log_level.py | Smart logging tiers `--log-level quiet/normal/verbose/debug` (v0.34.0 Part A) |@@ -303,7 +303,7 @@ Accepted runs are recorded in [`benchmarks/gpu-test-runs.md`](benchmarks/gpu-tes| test_replay.py | `soup runs replay`: summarise + downsample + CLI rendering (v0.34.0 Part E) || test_profiling.py | Auto-profiling: ProfilerSchedule + path containment + torch-less degradation (v0.34.0 Part F) || test_tui.py | `soup tui`: CLI bounds + missing-textual error + row builders (v0.34.0 Part G) |-| test_trainer_coverage_v035.py | Multi-trainer v0.28.0 wiring smoke matrix: every trainer × every speed/memory feature + auto-quant translators + try_reload_with_fallback + benchmark_kernel_combos + schema-gate lift (v0.35.0 Parts A / B / C / D — #60, #61, #45) |+| test_trainer_coverage_v035.py | Multi-trainer v0.28.0 wiring smoke matrix: every trainer × every speed/memory feature + benchmark_kernel_combos + schema-gate lift (v0.35.0 Parts A / B / C / D — #60, #61, #45) || test_v0470_part_a.py | Synthetic Data Forge: ForgePlan / ProvenanceRecord / ForgeRow frozen dataclasses + VALID_TASKS allowlist + chunk_document + score_uncertainty + discover_documents (cwd-contained, symlink-rejecting, extension allowlist) + build_forge_plan validators (task / target_rows / teacher / NaN+Inf threshold) + synthesise_forge_rows (judge-exception swallow at DEBUG) + write_forge_dataset + write_provenance (atomic, TOCTOU-safe) + CLI smoke (v0.47.0) || test_v0470_part_b.py | Data Quality Moat: BENCHMARKS MappingProxyType + ScoreReport frozen + ngram_set / ngram_overlap_ratio / decontaminate_rows (containment ratio) + detect_pii (ReDoS-hardened regexes + 50 KB pre-cap) + detect_language (6-language stopword heuristic) + score_toxicity (keyword baseline) + score_educational_value + compute_scorecard + load_jsonl_rows / write_jsonl_rows (cwd-contained, symlink-rejecting, atomic) + CLI smoke per subcommand (v0.47.0) || test_v0480_part_a.py | Curriculum-Aware Trainer (BETA): DynamicCurriculumPolicy frozen + bounds; compute_bucket_weights softmax + water-fill (floor-strict invariant); validate_distributed_curriculum DDP gate; render_curve + parse_history_jsonl with 100k-row DoS cap; SoupConfig cross-validators (requires-curriculum / mlx-rejected / non-SFT-rejected / floor ≤ 1/buckets); `soup runs curriculum-curve` CLI (TOCTOU symlink reject + 50 MB cap + corrupt-JSONL exit 2) (v0.48.0) |diff --git a/changelog.d/0.75.1/1262.removed.md b/changelog.d/0.75.1/1262.removed.mdnew file mode 100644index 00000000..5125d06c--- /dev/null+++ b/changelog.d/0.75.1/1262.removed.md@@ -0,0 +1 @@+- Removed the dormant `auto_quant` compatibility module (`soup_cli/utils/auto_quant.py`) that `soup serve --auto-quant` stopped using when it began refusing with exit 2 in #816; the refusal itself is unchanged and still covered by regression tests. `import soup_cli.utils.auto_quant` now raises `ModuleNotFoundError` with nothing replacing it (#1131 by @wanjinhao1 in #1262).diff --git a/src/soup_cli/utils/auto_quant.py b/src/soup_cli/utils/auto_quant.pydeleted file mode 100644index 26cdc3df..00000000--- a/src/soup_cli/utils/auto_quant.py+++ /dev/null@@ -1,278 +0,0 @@-"""Dormant auto-quant decision helpers retained for import compatibility.--There is deliberately no caller under :mod:`soup_cli`: ``soup serve---auto-quant`` refuses before loading a backend because Soup cannot compare-quantization candidates until it has loaded and measured each candidate. Do-not reconnect these timer-based helpers to serving; they remain temporarily-for import compatibility. Removal of this compatibility module is tracked in-#1131.-"""--from __future__ import annotations--import math-import re-from dataclasses import dataclass-from typing import Any, Callable, Iterable--_VALID_NAME_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,31}$")-_DEFAULT_ORDER = ("gguf", "awq", "gptq", "fp8", "none")---def default_candidate_order() -> tuple[str, ...]:- """Canonical order of quant formats to try.-- GGUF first because it's the widest-deployable; AWQ/GPTQ next for 4-bit- quality; FP8 only on Hopper+; 'none' (baseline) last so we always have- a fallback to prove any quant is actually helping.- """- return _DEFAULT_ORDER---def _validate_name(name: str) -> None:- if not isinstance(name, str) or not _VALID_NAME_RE.match(name):- raise ValueError(- f"candidate name must match {_VALID_NAME_RE.pattern}, got {name!r}"- )---@dataclass(frozen=True)-class Candidate:- """One candidate quant configuration + its measured score/latency."""-- name: str- score: float # quality in [0.0, 1.0]; higher is better- latency_ms: float- ok: bool # False if eval crashed / threshold-invalid output-- def __post_init__(self) -> None:- _validate_name(self.name)- # ``bool`` is a subclass of ``int``; reject it explicitly so a caller- # passing ``score=True`` doesn't sneak past as 1.0.- if (- not isinstance(self.score, (int, float))- or isinstance(self.score, bool)- or math.isnan(self.score)- ):- raise ValueError(f"score must be a finite float, got {self.score!r}")- if not 0.0 <= self.score <= 1.0:- raise ValueError(f"score must be in [0.0, 1.0], got {self.score}")- if (- not isinstance(self.latency_ms, (int, float))- or isinstance(self.latency_ms, bool)- or math.isnan(self.latency_ms)- ):- raise ValueError(f"latency_ms must be a finite float, got {self.latency_ms!r}")- if self.latency_ms < 0:- raise ValueError(f"latency_ms must be non-negative, got {self.latency_ms}")- if not isinstance(self.ok, bool):- raise ValueError(f"ok must be a bool, got {type(self.ok).__name__}")---def pick_best(- candidates: Iterable[Candidate],- *,- min_score: float = 0.90,-) -> Candidate:- """Pick the fastest candidate whose score >= min_score.-- Tie-break: first-encountered (stable, matches v0.28.0 kernel_picker).- Raises ValueError if no candidate passes the threshold.- """- if not 0.0 <= min_score <= 1.0:- raise ValueError(f"min_score must be in [0.0, 1.0], got {min_score}")-- # Materialise so we can both filter and count from a generator input.- all_candidates = list(candidates)- pool = [c for c in all_candidates if c.ok and c.score >= min_score]- if not pool:- raise ValueError(- f"no candidate passed min_score={min_score}; "- f"ran {len(all_candidates)} candidates"- )- best = pool[0]- for cand in pool[1:]:- if cand.latency_ms < best.latency_ms:- best = cand- return best---def evaluate_candidate(- name: str, *,- eval_fn,- prompts,- min_correct_fraction: float = 0.5,-) -> Candidate:- """Run ``eval_fn(prompt) -> (response, correct_bool)`` over a small prompt- set, time it, and produce a Candidate.-- Latency is mean per-prompt ms. Score is the fraction correct. ``ok`` is- True when score >= ``min_correct_fraction``.-- Robust to ``eval_fn`` crashes — any prompt that raises sets ``ok=False``- and continues so a single bad prompt doesn't disqualify a candidate that- works on the rest.- """- import time as _time-- if not prompts:- raise ValueError("evaluate_candidate requires at least one prompt")-- correct = 0- total = 0- completed = 0 # for honest latency mean (excludes crashed prompts)- started = _time.perf_counter()- crashed = False- for prompt in prompts:- total += 1- try:- _resp, hit = eval_fn(prompt)- except Exception: # noqa: BLE001 — surface as eval failure- crashed = True- continue- completed += 1- if hit:- correct += 1- elapsed_ms = (_time.perf_counter() - started) * 1000.0 / max(1, completed)- score = correct / total- return Candidate(- name=name,- score=score,- latency_ms=elapsed_ms,- ok=(not crashed) and (score >= min_correct_fraction),- )---def quant_name_to_vllm_kwargs(name: str) -> dict[str, str]:- """v0.35.0 #61 — translate a picker candidate name into vLLM engine kwargs.-- Returns a dict suitable to splat into ``AsyncLLMEngine.from_engine_args``.- Unknown / pass-through names return ``{}`` so the engine uses its default- (i.e. baseline / no quantization).- """- _validate_name(name)- mapping: dict[str, dict[str, str]] = {- "awq": {"quantization": "awq"},- "gptq": {"quantization": "gptq"},- "fp8": {"quantization": "fp8"},- # GGUF needs a path swap, not a kwarg — caller must handle separately.- "gguf": {},- "none": {},- }- return dict(mapping.get(name, {}))---def quant_name_to_bnb_kwargs(name: str) -> dict[str, bool]:- """v0.35.0 #61 — translate a picker name into transformers BnB kwargs.-- Returns ``{"load_in_4bit": True}`` for awq/gptq (treated as 4-bit-class),- and ``{}`` for fp8 / gguf / none / unknown — those formats are not- expressible via BitsAndBytesConfig and are handled either by the engine- directly (fp8) or via a path swap (gguf). Caller wraps these into a- ``BitsAndBytesConfig``.- """- _validate_name(name)- if name in ("awq", "gptq"):- return {"load_in_4bit": True}- return {}---def free_engine(engine: Any) -> None:- """v0.35.0 #61 — best-effort engine release before re-instantiation.-- .. important::- The caller is responsible for releasing their own reference *before*- calling this helper — Python's ``del`` on a function parameter only- removes the local binding, it cannot drop the caller's reference.- Idiomatic use::-- free_engine(engine)- engine = None # caller drops their reference too-- This function exists primarily to invoke ``torch.cuda.empty_cache()``- after the caller has already nulled out their reference. The- parameter is accepted only so the call-site reads naturally.-- Failure to invoke ``empty_cache`` is a soft advisory — caller should- NOT block on it.- """- del engine # local binding only — see docstring caveat- try:- import torch-- if torch.cuda.is_available():- torch.cuda.empty_cache()- except (ImportError, AttributeError, RuntimeError):- pass---def try_reload_with_fallback(- *,- picked: "Candidate",- all_candidates: list["Candidate"],- build_fn: Callable[[str], Any],-) -> tuple["Candidate", Any]:- """v0.35.0 #61 — attempt ``build_fn(picked.name)``, falling back to the- next-highest-scored candidate on load failure.-- ``build_fn`` is a callable ``name -> engine`` that may raise on any- backend-side load error (AWQ kernel missing, GPTQ checkpoint absent, etc).- Returns ``(candidate_actually_used, engine)``. Raises ``RuntimeError``- only when every candidate fails to load — at that point the server cannot- bind and must abort.- """- # Build the fallback queue: picked first, then remaining candidates by- # descending score (matches run_auto_quant_picker's soft-fallback policy).- seen = {picked.name}- queue: list[Candidate] = [picked]- by_score = sorted(all_candidates, key=lambda c: -c.score)- for cand in by_score:- if cand.name not in seen:- queue.append(cand)- seen.add(cand.name)-- last_error: Exception | None = None- for cand in queue:- try:- engine = build_fn(cand.name)- except Exception as exc: # noqa: BLE001 — caller's build is best-effort- last_error = exc- continue- return cand, engine-- # Redact: type+message rather than repr — repr can include filesystem- # paths from inside the backend's load chain (matches v0.34.0 crash.py- # secret-redaction policy).- last_summary = (- f"{type(last_error).__name__}: {last_error}" if last_error else "<none>"- )- raise RuntimeError(- f"every auto-quant candidate failed to load (tried {len(queue)}); "- f"last error: {last_summary}"- )---def run_auto_quant_picker(- *, candidate_specs, prompts, min_score: float = 0.90,-) -> Candidate:- """Run the full pick: evaluate each candidate, pick best by score+latency.-- ``candidate_specs`` is a sequence of ``(name, eval_fn)`` pairs. Each- ``eval_fn`` takes a prompt and returns ``(response, correct_bool)``.-- Falls back to the highest-scoring candidate (regardless of threshold)- when no candidate passes ``min_score``, so the server can still bind a- port. The caller is expected to log the choice.- """- candidates = [- evaluate_candidate(name, eval_fn=fn, prompts=prompts)- for name, fn in candidate_specs- ]- try:- return pick_best(candidates, min_score=min_score)- except ValueError:- # Soft fallback: pick the highest-scored candidate so the server- # still has a valid choice. Documented as advisory in serve.py.- ok_candidates = [c for c in candidates if c.ok]- pool = ok_candidates or candidates- return max(pool, key=lambda c: (c.score, -c.latency_ms))diff --git a/src/soup_cli/utils/vllm.py b/src/soup_cli/utils/vllm.pyindex 43341075..8292b3fe 100644--- a/src/soup_cli/utils/vllm.py+++ b/src/soup_cli/utils/vllm.py@@ -290,7 +290,6 @@ def create_vllm_engine(engine_args.max_model_len = max_model_lenengine_model_name = model_path- # v0.35.0 #61 — Auto-quant live picker forwards the chosen quant here.# vLLM accepts ``quantization`` on AsyncEngineArgs (string: awq/gptq/fp8).# ``None`` is the default (baseline / model's native dtype).if quantization:diff --git a/tests/test_inference_advanced.py b/tests/test_inference_advanced.pyindex 1dfa2896..4aff3cbe 100644--- a/tests/test_inference_advanced.py+++ b/tests/test_inference_advanced.py@@ -1,5 +1,5 @@"""Tests for v0.30.0 Inference Excellence — prefix caching, spec-decoding pairing,-LoRA hot-swap, structured output, batching dashboard, request tracing, auto-quant.+LoRA hot-swap, structured output, batching dashboard, request tracing."""from __future__ import annotations@@ -515,162 +515,6 @@ class TestRequestTracing:validate_otlp_endpoint("http://localhost\x00/evil")-# ═══════════════════════════════════════════════════════════════════════════-# Part G: Auto-Quant on Deploy-# ═══════════════════════════════════════════════════════════════════════════---class TestAutoQuant:- def test_auto_quant_flag_exists(self):- from typer.testing import CliRunner-- from soup_cli.cli import app-- runner = CliRunner()- result = runner.invoke(app, ["serve", "--help"])- assert result.exit_code == 0- assert "--auto-quant" in _strip_ansi(result.output)-- def test_candidate_order_default(self):- from soup_cli.utils.auto_quant import default_candidate_order-- order = default_candidate_order()- # First candidate should be fastest-to-try; we canonicalize order.- assert order[0] in {"gguf", "awq", "gptq", "fp8", "none"}- # No duplicates- assert len(order) == len(set(order))- # At least these quant formats present- assert "gguf" in order- assert "awq" in order-- def test_pick_best_candidate_prefers_fastest_ok(self):- from soup_cli.utils.auto_quant import Candidate, pick_best-- candidates = [- Candidate(name="gguf", score=0.92, latency_ms=200, ok=True),- Candidate(name="awq", score=0.95, latency_ms=180, ok=True),- Candidate(name="none", score=0.96, latency_ms=400, ok=True),- ]- best = pick_best(candidates, min_score=0.90)- # awq wins: ok, score above threshold, lowest latency- assert best.name == "awq"-- def test_pick_best_drops_below_threshold(self):- from soup_cli.utils.auto_quant import Candidate, pick_best-- candidates = [- Candidate(name="gguf", score=0.50, latency_ms=100, ok=True),- Candidate(name="awq", score=0.60, latency_ms=50, ok=True),- Candidate(name="none", score=0.95, latency_ms=400, ok=True),- ]- best = pick_best(candidates, min_score=0.90)- assert best.name == "none"-- def test_pick_best_raises_when_no_candidates_pass(self):- from soup_cli.utils.auto_quant import Candidate, pick_best-- candidates = [- Candidate(name="gguf", score=0.50, latency_ms=100, ok=True),- ]- with pytest.raises(ValueError, match="no candidate"):- pick_best(candidates, min_score=0.90)-- def test_pick_best_skips_failed(self):- from soup_cli.utils.auto_quant import Candidate, pick_best-- candidates = [- Candidate(name="gguf", score=0.99, latency_ms=1, ok=False),- Candidate(name="awq", score=0.91, latency_ms=180, ok=True),- ]- best = pick_best(candidates, min_score=0.90)- assert best.name == "awq"-- def test_candidate_requires_positive_latency(self):- from soup_cli.utils.auto_quant import Candidate-- with pytest.raises(ValueError):- Candidate(name="x", score=0.9, latency_ms=-1, ok=True)-- def test_candidate_score_bounded(self):- from soup_cli.utils.auto_quant import Candidate-- with pytest.raises(ValueError):- Candidate(name="x", score=1.5, latency_ms=100, ok=True)- with pytest.raises(ValueError):- Candidate(name="x", score=-0.1, latency_ms=100, ok=True)-- def test_min_score_bounds(self):- from soup_cli.utils.auto_quant import Candidate, pick_best-- candidates = [- Candidate(name="awq", score=0.9, latency_ms=100, ok=True),- ]- with pytest.raises(ValueError):- pick_best(candidates, min_score=-0.1)- with pytest.raises(ValueError):- pick_best(candidates, min_score=1.1)-- def test_name_validation_on_candidate(self):- """Candidate names must be alphanumeric — prevents arbitrary strings- leaking into log/display."""- from soup_cli.utils.auto_quant import Candidate-- with pytest.raises(ValueError):- Candidate(name="../../etc", score=0.9, latency_ms=100, ok=True)-- def test_pick_best_tie_break_by_first_encountered(self):- """When latency and score are tied, prefer first-encountered- (stable — consistent with v0.28.0 kernel_picker)."""- from soup_cli.utils.auto_quant import Candidate, pick_best-- candidates = [- Candidate(name="gguf", score=0.92, latency_ms=200, ok=True),- Candidate(name="awq", score=0.92, latency_ms=200, ok=True),- ]- best = pick_best(candidates, min_score=0.90)- assert best.name == "gguf"-- def test_pick_best_all_failed(self):- from soup_cli.utils.auto_quant import Candidate, pick_best-- candidates = [- Candidate(name="gguf", score=0.99, latency_ms=100, ok=False),- Candidate(name="awq", score=0.99, latency_ms=50, ok=False),- ]- with pytest.raises(ValueError, match="no candidate"):- pick_best(candidates, min_score=0.90)-- def test_pick_best_empty_list(self):- from soup_cli.utils.auto_quant import pick_best-- with pytest.raises(ValueError, match="no candidate"):- pick_best([], min_score=0.90)-- def test_pick_best_consumes_generator_once(self):- """Regression test: error message counts correctly when input is- a generator (not a list). v0.30.0 review fix."""- from soup_cli.utils.auto_quant import Candidate, pick_best-- def gen():- yield Candidate(name="gguf", score=0.5, latency_ms=100, ok=True)- yield Candidate(name="awq", score=0.4, latency_ms=80, ok=True)-- with pytest.raises(ValueError, match="ran 2 candidates"):- pick_best(gen(), min_score=0.90)-- def test_candidate_nan_score_rejected(self):- from soup_cli.utils.auto_quant import Candidate-- with pytest.raises(ValueError, match="finite"):- Candidate(name="x", score=float("nan"), latency_ms=100, ok=True)-- def test_candidate_nan_latency_rejected(self):- from soup_cli.utils.auto_quant import Candidate-- with pytest.raises(ValueError, match="finite"):- Candidate(name="x", score=0.9, latency_ms=float("nan"), ok=True)--# ═══════════════════════════════════════════════════════════════════════════# Review-fix follow-up: coverage gaps from tdd-guide review# ═══════════════════════════════════════════════════════════════════════════diff --git a/tests/test_part_d.py b/tests/test_part_d.pyindex c5fad632..12ee27a3 100644--- a/tests/test_part_d.py+++ b/tests/test_part_d.py@@ -4,8 +4,8 @@ Covers:- #49 End-to-end --push-as wiring with mocked HF Hub.- #53 build_logits_processors degrades gracefully without outlines/lmfe;chat-completions wires processors into _generate_response.- - #54 evaluate_candidate timing + score; run_auto_quant_picker happy- path + soft-fallback; serve auto_quant flow logs picked candidate.+ - #54 auto-quant picker helpers were removed with the module in v0.76.0 (#1131);+ the serve-side refusal is covered by test_issue816_auto_quant_refusal.py."""from __future__ import annotations@@ -152,94 +152,6 @@ class TestGenerateResponseSignature:assert "model.generate(**gen_kwargs)" in src-# ----------------------------------------------------------------------------# #54 — auto-quant picker-# ------------------------------------------------------------------------------class TestEvaluateCandidate:- def test_empty_prompts_rejected(self):- from soup_cli.utils.auto_quant import evaluate_candidate-- with pytest.raises(ValueError, match="at least one prompt"):- evaluate_candidate("test", eval_fn=lambda _p: ("", True), prompts=[])-- def test_all_correct_marks_ok(self):- from soup_cli.utils.auto_quant import evaluate_candidate-- cand = evaluate_candidate(- "test", eval_fn=lambda _p: ("resp", True),- prompts=["a", "b", "c"],- )- assert cand.score == 1.0- assert cand.ok is True- assert cand.latency_ms >= 0-- def test_eval_crash_marks_not_ok(self):- from soup_cli.utils.auto_quant import evaluate_candidate-- def _flaky(prompt):- if prompt == "b":- raise RuntimeError("boom")- return ("ok", True)-- cand = evaluate_candidate(- "test", eval_fn=_flaky, prompts=["a", "b", "c"],- )- # Score = 2/3 because "b" crashed (counted as wrong)- assert cand.score == pytest.approx(2 / 3)- assert cand.ok is False # any crash → not ok-- def test_below_threshold_marks_not_ok(self):- from soup_cli.utils.auto_quant import evaluate_candidate-- cand = evaluate_candidate(- "test", eval_fn=lambda p: ("", p == "a"),- prompts=["a", "b", "c", "d"],- min_correct_fraction=0.5,- )- # 1/4 = 0.25 < 0.5 → not ok- assert cand.score == 0.25- assert cand.ok is False---class TestRunAutoQuantPicker:- def test_picks_best_when_threshold_passes(self):- from soup_cli.utils.auto_quant import run_auto_quant_picker-- # Two candidates, both pass quality, but "fast" is faster- def _slow(_p):- return ("", True)-- def _fast(_p):- return ("", True)-- # Both score 1.0; tie-break by latency. We can't deterministically- # test which is faster (real timing) — instead we test that picker- # returns one of them.- result = run_auto_quant_picker(- candidate_specs=[("slow", _slow), ("fast", _fast)],- prompts=["a"],- min_score=0.5,- )- assert result.name in {"slow", "fast"}- assert result.score == 1.0-- def test_soft_fallback_when_no_candidate_passes(self):- from soup_cli.utils.auto_quant import run_auto_quant_picker-- # Both fail — score 0/3 < 0.9; min_correct_fraction default 0.5- # also fails so ok=False.- result = run_auto_quant_picker(- candidate_specs=[("a", lambda _p: ("", False)),- ("b", lambda _p: ("", False))],- prompts=["x", "y", "z"],- min_score=0.9,- )- # Soft fallback returns *some* candidate so server can bind- assert result.name in {"a", "b"}--# ---------------------------------------------------------------------------# #49 — End-to-end --push-as integration test (mocked HF)# ---------------------------------------------------------------------------diff --git a/tests/test_trainer_coverage_v035.py b/tests/test_trainer_coverage_v035.pyindex 465002bb..2ecc4b51 100644--- a/tests/test_trainer_coverage_v035.py+++ b/tests/test_trainer_coverage_v035.py@@ -425,226 +425,6 @@ def test_trainer_module_wraps_train_with_offloading_context()-# ----------------------------------------------------------------------------# Part B — auto-quant live model reload-# ------------------------------------------------------------------------------class TestQuantNameTranslators:- @pytest.mark.parametrize(- ("name", "expected"),- (- ("awq", {"quantization": "awq"}),- ("gptq", {"quantization": "gptq"}),- ("fp8", {"quantization": "fp8"}),- ("none", {}),- ("gguf", {}), # GGUF needs a path swap, not a kwarg- ),- )- def test_quant_name_to_vllm_kwargs_known(self, name, expected) -> None:- from soup_cli.utils.auto_quant import quant_name_to_vllm_kwargs-- assert quant_name_to_vllm_kwargs(name) == expected-- def test_quant_name_to_vllm_kwargs_unknown_returns_empty(self) -> None:- from soup_cli.utils.auto_quant import quant_name_to_vllm_kwargs-- # ``int8`` is not in the mapping; pass-through returns {} so caller- # uses the engine default.- assert quant_name_to_vllm_kwargs("int8") == {}-- def test_quant_name_to_vllm_kwargs_rejects_invalid_name(self) -> None:- from soup_cli.utils.auto_quant import quant_name_to_vllm_kwargs-- with pytest.raises(ValueError, match="candidate name must match"):- quant_name_to_vllm_kwargs("AWQ") # uppercase not allowed- with pytest.raises(ValueError):- quant_name_to_vllm_kwargs("../../etc/passwd")-- def test_quant_name_to_vllm_kwargs_returns_new_dict(self) -> None:- """Mutation-safe — caller must not be able to corrupt the mapping."""- from soup_cli.utils.auto_quant import quant_name_to_vllm_kwargs-- a = quant_name_to_vllm_kwargs("awq")- a["leak"] = True- b = quant_name_to_vllm_kwargs("awq")- assert "leak" not in b-- def test_quant_name_to_bnb_kwargs(self) -> None:- from soup_cli.utils.auto_quant import quant_name_to_bnb_kwargs-- assert quant_name_to_bnb_kwargs("awq") == {"load_in_4bit": True}- assert quant_name_to_bnb_kwargs("gptq") == {"load_in_4bit": True}- assert quant_name_to_bnb_kwargs("fp8") == {}- assert quant_name_to_bnb_kwargs("none") == {}---class TestFreeEngine:- def test_free_engine_no_torch(self) -> None:- """free_engine must never raise even if torch is unavailable."""- from soup_cli.utils.auto_quant import free_engine-- # Smoke — no torch on this CI? Still no-raise.- free_engine(MagicMock())-- def test_free_engine_torch_no_cuda(self) -> None:- from soup_cli.utils.auto_quant import free_engine-- with patch("torch.cuda.is_available", return_value=False):- free_engine(MagicMock()) # no exception-- def test_free_engine_torch_cuda_available(self) -> None:- from soup_cli.utils.auto_quant import free_engine-- with (- patch("torch.cuda.is_available", return_value=True),- patch("torch.cuda.empty_cache") as mock_empty,- ):- free_engine(MagicMock())- mock_empty.assert_called_once()---class TestTryReloadWithFallback:- def _candidate(self, name: str, score: float = 0.95):- from soup_cli.utils.auto_quant import Candidate-- return Candidate(name=name, score=score, latency_ms=10.0, ok=True)-- def test_picked_loads_first_try(self) -> None:- from soup_cli.utils.auto_quant import try_reload_with_fallback-- picked = self._candidate("awq")- all_c = [picked, self._candidate("gptq", 0.90)]- engines_built: list[str] = []-- def build(name):- engines_built.append(name)- return f"engine-{name}"-- used, eng = try_reload_with_fallback(- picked=picked, all_candidates=all_c, build_fn=build,- )- assert used.name == "awq"- assert eng == "engine-awq"- assert engines_built == ["awq"] # no fallback exercised-- def test_falls_back_to_next_highest_on_first_failure(self) -> None:- from soup_cli.utils.auto_quant import try_reload_with_fallback-- picked = self._candidate("awq", 0.92)- gptq = self._candidate("gptq", 0.95)- none_c = self._candidate("none", 0.85)- all_c = [picked, gptq, none_c]- engines_built: list[str] = []-- def build(name):- engines_built.append(name)- if name == "awq":- raise RuntimeError("AWQ kernel missing")- return f"engine-{name}"-- used, eng = try_reload_with_fallback(- picked=picked, all_candidates=all_c, build_fn=build,- )- # picked tried first, then by descending score: gptq (0.95)- assert used.name == "gptq"- assert engines_built == ["awq", "gptq"]-- def test_raises_when_all_candidates_fail(self) -> None:- from soup_cli.utils.auto_quant import try_reload_with_fallback-- picked = self._candidate("awq")- all_c = [picked, self._candidate("gptq")]-- def build(name):- raise RuntimeError(f"{name} broken")-- with pytest.raises(RuntimeError, match="every auto-quant candidate"):- try_reload_with_fallback(- picked=picked, all_candidates=all_c, build_fn=build,- )-- def test_duplicate_candidate_name_deduped(self) -> None:- """Two candidates with the same name shouldn't double-build."""- from soup_cli.utils.auto_quant import try_reload_with_fallback-- picked = self._candidate("awq", 0.95)- dup = self._candidate("awq", 0.92) # same name- gptq = self._candidate("gptq", 0.90)- engines_built: list[str] = []-- def build(name):- engines_built.append(name)- if name == "awq":- raise RuntimeError("AWQ broken")- return f"engine-{name}"-- used, _eng = try_reload_with_fallback(- picked=picked, all_candidates=[picked, dup, gptq], build_fn=build,- )- # awq tried once (picked), then gptq — never awq twice.- assert engines_built == ["awq", "gptq"]- assert used.name == "gptq"-- def test_empty_all_candidates_uses_only_picked(self) -> None:- """If all_candidates is empty, only picked is in the queue."""- from soup_cli.utils.auto_quant import try_reload_with_fallback-- picked = self._candidate("awq")-- def build(name):- raise RuntimeError(f"{name} broken")-- with pytest.raises(RuntimeError, match="tried 1"):- try_reload_with_fallback(- picked=picked, all_candidates=[], build_fn=build,- )-- def test_redacts_load_error_path_in_message(self) -> None:- """RuntimeError message must not embed repr() (which can leak paths)."""- from soup_cli.utils.auto_quant import try_reload_with_fallback-- picked = self._candidate("awq")-- def build(name):- # Simulate FileNotFoundError carrying an absolute path.- raise FileNotFoundError("/home/user/.cache/secret/checkpoint")-- with pytest.raises(RuntimeError) as exc_info:- try_reload_with_fallback(- picked=picked, all_candidates=[picked], build_fn=build,- )- msg = str(exc_info.value)- # Type name + str() is fine; repr() with the full path would include- # the FileNotFoundError(...) wrapper — confirm we're using type+str.- assert "FileNotFoundError" in msg- # Defence-in-depth: the message must not double-quote the path- # (which would mean repr() was used).- assert (- "FileNotFoundError(\"/home/user" not in msg- and "FileNotFoundError('/home/user" not in msg- )-- def test_picked_is_always_tried_first_even_if_lower_score(self) -> None:- """The picker's choice respects (score, -latency); fallback queue- must lead with picked even when another candidate has higher score."""- from soup_cli.utils.auto_quant import try_reload_with_fallback-- picked = self._candidate("awq", 0.85)- gptq = self._candidate("gptq", 0.99) # higher score but not picked- engines_built: list[str] = []-- def build(name):- engines_built.append(name)- return f"engine-{name}"-- used, _eng = try_reload_with_fallback(- picked=picked, all_candidates=[picked, gptq], build_fn=build,- )- assert used.name == "awq"- assert engines_built == ["awq"]--class TestVllmCreateEngineQuantizationParam:def test_create_vllm_engine_accepts_quantization_kwarg(self) -> None:"""Source-level proof that the new quantization kwarg is exposed."""diff --git a/tests/test_vllm_serve.py b/tests/test_vllm_serve.pyindex db52897f..6a15ce34 100644--- a/tests/test_vllm_serve.py+++ b/tests/test_vllm_serve.py@@ -504,7 +504,7 @@ class TestServeVllmIntegration:speculative_model=None,num_speculative_tokens=5,enable_prefix_caching=False,- quantization=None, # v0.35.0 #61 — auto-quant default+ quantization=None, # default: model's native dtypetrust_remote_code=False, # v0.71.33 — default-deny gatemax_model_len=None, # #333 — new --max-model-len lever)