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.

feat(adapters): pre-flight adapter health audit for silent training failures (#1721) (#1738)

Harshit Sharma970ac19b892e
diff --git a/changelog.d/0.75.1/1738.added.md b/changelog.d/0.75.1/1738.added.md
new file mode 100644
index 00000000..b9cb55f6
--- /dev/null
+++ b/changelog.d/0.75.1/1738.added.md
@@ -0,0 +1,6 @@
+- **Single-adapter health and silent-failure diagnostic scan (`soup adapters check`).**
+ Audits a LoRA adapter for Frobenius weight delta ||ΔW||_F with float64 accumulation
+ and rsLoRA scaling awareness, live layer fraction, all-zero lora_B initialisation traps,
+ orphaned projections, and legacy .inner. wrapper namespace leaks without a PyTorch dependency,
+ ending in a single contract line (`alive` vs `inactive: <reason>`).
+ (#1721 by @harshitthek in #1738)
diff --git a/docs/adapters-and-governance.md b/docs/adapters-and-governance.md
index e1bcce2d..268b64ef 100644
--- a/docs/adapters-and-governance.md
+++ b/docs/adapters-and-governance.md
@@ -22,6 +22,7 @@
- [Adapter Backdoor Scanner (`soup adapters scan`)](#adapter-backdoor-scanner-soup-adapters-scan)
- [Adapter Sign + Verify (`soup adapters sign` / `verify`)](#adapter-sign--verify-soup-adapters-sign--verify)
- [Strict Safetensors Mode (`soup adapters check-safetensors`)](#strict-safetensors-mode-soup-adapters-check-safetensors)
+- [Pre-Flight Adapter Health Audit (`soup adapters check`)](#pre-flight-adapter-health-audit-soup-adapters-check)
- [Namespace Pinning (Anti-AI-Jacking)](#namespace-pinning-anti-ai-jacking)
- [License-Conflict Matrix at Merge](#license-conflict-matrix-at-merge)
- [Airgap Bundle (`soup airgap-bundle`)](#airgap-bundle-soup-airgap-bundle)
@@ -724,6 +725,32 @@ offending file and the canonical `from safetensors.torch import save_file`
recipe. Exit code 3 under `--strict` for CI gating.
+## Pre-Flight Adapter Health Audit (`soup adapters check`)
+
+Pre-flight scan auditing single LoRA adapters for silent training failures (#1721):
+- **Total and per-layer ||dW||_F**: Frobenius norm of LoRA parameter updates (dW = scaling * (B @ A), with alpha / r for standard LoRA and alpha / sqrt(r) for rsLoRA) with float64 accumulation via matrix trace contraction.
+- **Live fraction**: Proportion of adapter layers with active, non-zero updates.
+- **All-zero lora_B layers**: Flags un-trained or zero-initialized layers that failed to move during training.
+- **Incomplete LoRA pairs**: Flags orphaned or partially-saved projections missing either A or B.
+- **Leaked .inner. keys**: Flags legacy wrapper namespaces for adapters saved prior to the #1011 save-time guard.
+
+```bash
+soup adapters check path/to/adapter/
+# Machine-readable output
+soup adapters check path/to/adapter/ --json
+```
+
+Outputs human diagnostics ending in a single verdict line: `alive` (exit code 0) or `inactive: <reason>` (exit code 2 for inactive/silent failure, distinct from usage error 1). Possible inactivity reasons include:
+- `all lora_B layers are zero (n/n)`
+- `lora_B layers are zero (k/n)`
+- `total ||ΔW||_F is 0.0`
+- `leaked .inner. keys detected (<n> tensors)`
+- `incomplete LoRA pairs detected (<n> orphans)`
+- `shape mismatch in LoRA projections (<n> layers)`
+- `non-finite weights detected (NaN/Inf)`
+- `no lora weights found`
+
+
## Namespace Pinning (Anti-AI-Jacking)
Trust-on-first-use SQLite cache: records `(repo_id, author, created_at)`
diff --git a/docs/commands.md b/docs/commands.md
index 14e95c66..3d63eee6 100644
--- a/docs/commands.md
+++ b/docs/commands.md
@@ -274,6 +274,7 @@ soup bom emit --name <n> --base-sha <hex> --config-sha <hex> --format cyclonedx|
soup adapters scan <adapter> Spectral backdoor scan (rank-1 dominance + outlier detection)
soup adapters sign <adapter> [--backend unsigned|ed25519|sigstore] [--key <pem>|--generate-key <pem>] [--interactive-oidc] Merkle manifest + ed25519/Sigstore sign
soup adapters verify <adapter> [--strict] [--public-key <pem>] [--cert-identity <san> --cert-oidc-issuer <url>] Verify manifest + ed25519/Sigstore signature
+soup adapters check <adapter> [--json] Is the adapter trained? Total/per-layer ||dW||_F, live fraction, all-zero lora_B, leaked .inner. keys; ends in alive or inactive: <reason> (exit 0 / 2; 1 = usage error)
soup adapters check-safetensors <adapter> [--strict] Refuse pickle / PyTorch-classic weights
soup adapters merge ... [--license <id>] [--license-override <reason>] [--allow-unscanned] License + backdoor-scan gates (auto-detect license; scan FAIL refused)
soup adapters arithmetic "coder + 0.5*math - toxic" --adapter coder=<p> --adapter math=<p> --adapter toxic=<p> -o <out> [--allow-unscanned --allow-cross-base] Task-vector algebra over LoRA adapters (add/scale/negate; same-rank; scan + same-base gated) (v0.71.34)
diff --git a/src/soup_cli/commands/adapters.py b/src/soup_cli/commands/adapters.py
index 4c6ad4b1..23661e82 100644
--- a/src/soup_cli/commands/adapters.py
+++ b/src/soup_cli/commands/adapters.py
@@ -1904,3 +1904,41 @@ def audit(
f"{f', {result.unknown_count} unchecked' if result.unknown_count else ''}"
)
raise typer.Exit(result.exit_code)
+
+
+_err_console = Console(stderr=True)
+
+
[email protected](name="check")
+def check_cmd(
+ adapter: str = typer.Argument(..., help="Path to adapter directory"),
+ json_out: bool = typer.Option(False, "--json", help="Emit machine-readable JSON document"),
+):
+ """Audit whether an adapter is trained: Frobenius delta, zero B, inner keys (#1721)."""
+ from soup_cli.utils.adapter_check import (
+ check_adapter,
+ render_check_json,
+ render_check_terminal,
+ )
+ from soup_cli.utils.paths import enforce_under_cwd_and_no_symlink
+
+ try:
+ enforce_under_cwd_and_no_symlink(adapter, "adapter directory")
+ except (ValueError, OSError) as exc:
+ _err_console.print(f"[red]Path refused: {for_terminal(str(exc))}[/]")
+ raise typer.Exit(1) from exc
+
+ try:
+ report = check_adapter(adapter)
+ rendered = render_check_json(report) if json_out else render_check_terminal(report)
+ except (FileNotFoundError, OSError, ValueError, TypeError, RuntimeError) as exc:
+ _err_console.print(f"[red]{for_terminal(str(exc))}[/]")
+ raise typer.Exit(1) from exc
+
+ print(rendered)
+
+ if report.verdict == "alive":
+ raise typer.Exit(0)
+ else:
+ raise typer.Exit(2)
+
diff --git a/src/soup_cli/utils/adapter_check.py b/src/soup_cli/utils/adapter_check.py
new file mode 100644
index 00000000..cd63e538
--- /dev/null
+++ b/src/soup_cli/utils/adapter_check.py
@@ -0,0 +1,491 @@
+"""Single-adapter pre-flight health audit and silent failure diagnostics (Issue #1721).
+
+Pure numpy math (no torch); safetensors is loaded lazily with float64 accumulation.
+Scans for:
+- Total and per-layer Frobenius weight delta ||ΔW||_F
+- Live layer fraction (non-zero updates)
+- All-zero lora_B layers (initialization traps / frozen layers)
+- Leaked .inner. wrapper namespaces (adapters saved before #1011)
+
+Outputs a detailed report and terminal verdict line: `alive` vs `inactive: <reason>`.
+"""
+
+from __future__ import annotations
+
+import json
+import math
+import os
+import stat
+from dataclasses import asdict, dataclass
+from pathlib import Path
+from typing import Any, Optional, Tuple
+
+from soup_cli.utils.adapter_diff import _adapter_weights_path, _require_str
+from soup_cli.utils.paths import enforce_under_cwd_and_no_symlink, is_under_cwd
+from soup_cli.utils.terminal import strip_control
+
+INNER_NAMESPACE_MARKER = ".inner."
+_MAX_LAYERS = 10_000
+
+
+@dataclass(frozen=True)
+class LayerCheck:
+ """Health metrics for a single LoRA projection pair or tensor."""
+
+ name: str
+ frobenius: float
+ is_b_zero: bool
+ has_non_finite: bool
+ shape_a: Tuple[int, ...]
+ shape_b: Tuple[int, ...]
+
+
+@dataclass(frozen=True)
+class AdapterCheckReport:
+ """Full health diagnostic report for a single LoRA adapter."""
+
+ adapter: str
+ verdict: str # "alive" or "inactive"
+ reason: Optional[str]
+ total_frobenius: float
+ live_fraction: float
+ live_layers: int
+ total_layers: int
+ all_zero_lora_b_layers: Tuple[str, ...]
+ inner_keys: Tuple[str, ...]
+ per_layer: Tuple[LayerCheck, ...]
+ orphaned_layers: Tuple[str, ...] = ()
+ standalone_tensors: Tuple[LayerCheck, ...] = ()
+ shape_mismatches: Tuple[str, ...] = ()
+
+ @property
+ def verdict_line(self) -> str:
+ """The single final line required by contract."""
+ if self.verdict == "alive":
+ return "alive"
+ return f"inactive: {strip_control(self.reason)}" if self.reason else "inactive"
+
+
+def _read_config(adapter_dir: Path) -> dict[str, Any]:
+ """Read adapter_config.json if present and not a symlink."""
+ cfg_path = adapter_dir / "adapter_config.json"
+ if not os.path.lexists(str(cfg_path)):
+ return {}
+ st = os.lstat(str(cfg_path))
+ if stat.S_ISLNK(st.st_mode):
+ raise ValueError(
+ f"{adapter_dir.name}/adapter_config.json: must not be a symlink"
+ )
+ try:
+ with open(cfg_path, encoding="utf-8") as f:
+ data = json.load(f)
+ except (ValueError, OSError) as exc:
+ raise ValueError(
+ f"{adapter_dir.name}/adapter_config.json: unreadable or invalid JSON: {exc}"
+ ) from exc
+
+ if not isinstance(data, dict):
+ raise ValueError(
+ f"{adapter_dir.name}/adapter_config.json: expected JSON object"
+ )
+ return data
+
+
+def _load_safetensors_numpy(path: Path) -> dict[str, Any]:
+ """Lazy-load adapter tensors using safetensors numpy framework."""
+ try:
+ from safetensors import safe_open
+ except ImportError as exc:
+ raise RuntimeError(
+ "safetensors package required; pip install safetensors"
+ ) from exc
+
+ result: dict[str, Any] = {}
+ try:
+ with safe_open(str(path), framework="numpy") as f:
+ keys = list(f.keys())
+ if len(keys) > _MAX_LAYERS:
+ raise ValueError(f"adapter has >{_MAX_LAYERS} tensors")
+ for key in keys:
+ _require_str(key, "tensor name")
+ result[key] = f.get_tensor(key)
+ except (ValueError, RuntimeError):
+ raise
+ except Exception as exc:
+ raise ValueError(
+ f"Corrupt or unreadable safetensors weights in {path.name}: {exc}"
+ ) from exc
+ return result
+
+
+def _split_lora_role(name: str) -> Optional[Tuple[str, str]]:
+ """Extract (pair_key, role) for a LoRA weight name.
+
+ Returns (pair_key, 'A') or (pair_key, 'B'), or None if not a LoRA weight.
+ Replaces the leaf role tag with a unified marker so that matching A and B
+ tensors share the exact same pair key.
+ """
+ for marker, role in (
+ (".lora_embedding_A.", "A"),
+ (".lora_embedding_B.", "B"),
+ (".lora_A.", "A"),
+ (".lora_B.", "B"),
+ ):
+ if marker in name:
+ idx = name.rfind(marker)
+ sub = ".__LORA_EMB__." if "embedding" in marker else ".__LORA__."
+ pair_key = name[:idx] + sub + name[idx + len(marker) :]
+ return pair_key, role
+
+ for suffix, role in (
+ (".lora_embedding_A", "A"),
+ (".lora_embedding_B", "B"),
+ (".lora_A", "A"),
+ (".lora_B", "B"),
+ ):
+ if name.endswith(suffix):
+ idx = name.rfind(suffix)
+ sub = ".__LORA_EMB__" if "embedding" in suffix else ".__LORA__"
+ pair_key = name[:idx] + sub
+ return pair_key, role
+
+ return None
+
+
+def check_adapter(adapter_dir: str | Path) -> AdapterCheckReport:
+ """Audit single adapter health for silent training failures.
+
+ Checks:
+ 1. Total and per-layer ||ΔW||_F on LoRA pairs (scaling * ||B @ A||_F).
+ 2. Live fraction: fraction of LoRA layers with non-zero parameter updates.
+ 3. All-zero lora_B layers: layers that remained at initial zero state.
+ 4. .inner. keys: layer-streaming wrapper namespace leaks.
+ """
+ enforce_under_cwd_and_no_symlink(str(adapter_dir), "adapter")
+ dir_path = Path(adapter_dir).resolve()
+ if not dir_path.is_dir():
+ raise FileNotFoundError(f"Adapter directory not found: {adapter_dir}")
+
+ weights_file = _adapter_weights_path(dir_path)
+ if not is_under_cwd(str(weights_file)):
+ raise ValueError(
+ f"adapter weights must stay under cwd: {weights_file.name}"
+ )
+
+ config = _read_config(dir_path)
+ weights = _load_safetensors_numpy(weights_file)
+
+ lora_r = config.get("r")
+ lora_alpha = config.get("lora_alpha")
+ use_rslora = bool(config.get("use_rslora", False))
+ scaling = 1.0
+ if (
+ isinstance(lora_r, (int, float))
+ and not isinstance(lora_r, bool)
+ and lora_r > 0
+ ):
+ if (
+ isinstance(lora_alpha, (int, float))
+ and not isinstance(lora_alpha, bool)
+ ):
+ if use_rslora:
+ scaling = abs(float(lora_alpha)) / math.sqrt(float(lora_r))
+ else:
+ scaling = abs(float(lora_alpha)) / float(lora_r)
+
+ import numpy as np
+
+ # Check for leaked .inner. wrapper namespaces
+ inner_keys = tuple(
+ sorted(k for k in weights.keys() if INNER_NAMESPACE_MARKER in k)
+ )
+
+ # Discover and group LoRA pairs
+ lora_modules: dict[str, dict[str, Any]] = {}
+ other_tensors: dict[str, Any] = {}
+
+ for name, tensor in weights.items():
+ role_info = _split_lora_role(name)
+ if role_info is not None:
+ pair_key, role = role_info
+ lora_modules.setdefault(pair_key, {})[role] = (name, tensor)
+ else:
+ other_tensors[name] = tensor
+
+ layer_checks: list[LayerCheck] = []
+ orphaned_layers: list[str] = []
+ shape_mismatches: list[str] = []
+ has_any_non_finite = False
+
+ for mod_name in sorted(lora_modules.keys()):
+ pair = lora_modules[mod_name]
+ a_info = pair.get("A")
+ b_info = pair.get("B")
+
+ if not a_info or not b_info:
+ # Incomplete LoRA pair (missing A or missing B)
+ tensor = a_info[1] if a_info else b_info[1]
+ name = a_info[0] if a_info else b_info[0]
+ orphaned_layers.append(name)
+ arr = np.asarray(tensor, dtype=np.float64)
+ is_finite = bool(np.isfinite(arr).all())
+ if not is_finite:
+ has_any_non_finite = True
+ # Orphaned single tensors cannot form ΔW = B @ A; fro stays 0.0
+ fro = 0.0
+ layer_checks.append(
+ LayerCheck(
+ name=name,
+ frobenius=fro,
+ is_b_zero=False,
+ has_non_finite=not is_finite,
+ shape_a=tuple(arr.shape) if a_info else (),
+ shape_b=tuple(arr.shape) if b_info else (),
+ )
+ )
+ continue
+
+ a_name, a_tensor = a_info
+ b_name, b_tensor = b_info
+
+ a_arr = np.asarray(a_tensor, dtype=np.float64)
+ b_arr = np.asarray(b_tensor, dtype=np.float64)
+
+ is_a_finite = bool(np.isfinite(a_arr).all())
+ is_b_finite = bool(np.isfinite(b_arr).all())
+ is_finite = is_a_finite and is_b_finite
+ if not is_finite:
+ has_any_non_finite = True
+
+ is_b_zero = bool(np.all(b_arr == 0.0))
+
+ # Compute ||ΔW||_F = scaling * ||B @ A||_F
+ # Using exact trace identity: ||B @ A||_F^2 = sum((B.T @ B) * (A @ A.T))
+ if is_b_zero:
+ fro = 0.0
+ elif not is_finite:
+ fro = float("nan")
+ else:
+ # Squeeze unit dimensions and reshape to 2D
+ a_2d = a_arr.reshape(1, -1) if a_arr.ndim == 1 else (
+ a_arr.reshape(a_arr.shape[0], -1) if a_arr.ndim > 2 else a_arr
+ )
+ b_2d = b_arr.reshape(-1, 1) if b_arr.ndim == 1 else (
+ b_arr.reshape(b_arr.shape[0], -1) if b_arr.ndim > 2 else b_arr
+ )
+
+ # Determine contraction layout:
+ # Standard Linear: B is (out, r), A is (r, in) -> rank axis is (B axis 1, A axis 0)
+ # Transposed / Conv1D: B is (r, out), A is (in, r) -> rank axis is (B axis 0, A axis 1)
+ is_std = b_2d.ndim == 2 and a_2d.ndim == 2 and b_2d.shape[1] == a_2d.shape[0]
+ is_trans = b_2d.ndim == 2 and a_2d.ndim == 2 and b_2d.shape[0] == a_2d.shape[1]
+
+ if is_std and is_trans:
+ # Disambiguate when in_features == out_features
+ integral_r = (
+ int(lora_r)
+ if isinstance(lora_r, (int, float))
+ and not isinstance(lora_r, bool)
+ and lora_r > 0
+ and float(lora_r).is_integer()
+ else None
+ )
+ if integral_r is not None:
+ if b_2d.shape[1] == integral_r:
+ is_trans = False
+ elif b_2d.shape[0] == integral_r:
+ is_std = False
+ elif b_2d.shape[1] <= b_2d.shape[0]:
+ # Rank is typically the bottleneck dimension (r <= out_features)
+ is_trans = False
+ else:
+ is_std = False
+
+ if is_std:
+ btb = np.matmul(b_2d.T, b_2d)
+ aat = np.matmul(a_2d, a_2d.T)
+ sum_sq = float(np.sum(btb * aat))
+ fro = float(scaling * math.sqrt(max(0.0, sum_sq)))
+ elif is_trans:
+ bbt = np.matmul(b_2d, b_2d.T)
+ ata = np.matmul(a_2d.T, a_2d)
+ sum_sq = float(np.sum(bbt * ata))
+ fro = float(scaling * math.sqrt(max(0.0, sum_sq)))
+ else:
+ try:
+ delta = scaling * np.matmul(b_2d, a_2d)
+ fro = float(np.sqrt(np.sum(delta * delta)))
+ except (ValueError, TypeError):
+ fro = float("nan")
+ shape_mismatches.append(mod_name)
+
+ layer_checks.append(
+ LayerCheck(
+ name=mod_name,
+ frobenius=fro,
+ is_b_zero=is_b_zero,
+ has_non_finite=not is_finite,
+ shape_a=tuple(a_arr.shape),
+ shape_b=tuple(b_arr.shape),
+ )
+ )
+
+ # Process other standalone tensors (e.g. bias or custom heads)
+ standalone_checks: list[LayerCheck] = []
+ for name in sorted(other_tensors.keys()):
+ arr = np.asarray(other_tensors[name], dtype=np.float64)
+ is_finite = bool(np.isfinite(arr).all())
+ if not is_finite:
+ has_any_non_finite = True
+ is_zero = bool(np.all(arr == 0.0))
+ fro = 0.0 if is_zero else float(np.sqrt(np.sum(arr * arr)))
+ standalone_checks.append(
+ LayerCheck(
+ name=name,
+ frobenius=fro,
+ is_b_zero=False,
+ has_non_finite=not is_finite,
+ shape_a=(),
+ shape_b=tuple(arr.shape),
+ )
+ )
+
+ # Compute metrics strictly from LoRA projections
+ total_layers = len(layer_checks)
+ all_zero_b_layers = tuple(lc.name for lc in layer_checks if lc.is_b_zero)
+ live_layers = len(
+ [lc for lc in layer_checks if not lc.is_b_zero and lc.frobenius > 0.0]
+ )
+ live_fraction = (live_layers / total_layers) if total_layers > 0 else 0.0
+
+ if has_any_non_finite or shape_mismatches:
+ total_frobenius = float("nan")
+ else:
+ sum_sq_total = sum(
+ lc.frobenius * lc.frobenius
+ for lc in layer_checks
+ if math.isfinite(lc.frobenius)
+ )
+ total_frobenius = (
+ math.sqrt(sum_sq_total)
+ if math.isfinite(sum_sq_total)
+ else float("nan")
+ )
+
+ # Determine verdict according to contract
+ if inner_keys:
+ verdict = "inactive"
+ reason = f"leaked .inner. keys detected ({len(inner_keys)} tensors)"
+ elif orphaned_layers:
+ verdict = "inactive"
+ reason = (
+ f"incomplete LoRA pairs detected ({len(orphaned_layers)} orphan"
+ f"{'s' if len(orphaned_layers) != 1 else ''})"
+ )
+ elif shape_mismatches:
+ verdict = "inactive"
+ reason = (
+ f"shape mismatch in LoRA projections ({len(shape_mismatches)} layer"
+ f"{'s' if len(shape_mismatches) != 1 else ''})"
+ )
+ elif has_any_non_finite or math.isnan(total_frobenius) or math.isinf(total_frobenius):
+ verdict = "inactive"
+ reason = "non-finite weights detected (NaN/Inf)"
+ elif total_layers == 0:
+ verdict = "inactive"
+ reason = "no lora weights found"
+ elif len(all_zero_b_layers) == total_layers:
+ verdict = "inactive"
+ reason = f"all lora_B layers are zero ({total_layers}/{total_layers})"
+ elif len(all_zero_b_layers) > 0:
+ verdict = "inactive"
+ reason = f"lora_B layers are zero ({len(all_zero_b_layers)}/{total_layers})"
+ elif total_frobenius <= 0.0 or live_fraction <= 0.0:
+ verdict = "inactive"
+ reason = "total ||ΔW||_F is 0.0"
+ else:
+ verdict = "alive"
+ reason = None
+
+ return AdapterCheckReport(
+ adapter=str(dir_path),
+ verdict=verdict,
+ reason=reason,
+ total_frobenius=total_frobenius,
+ live_fraction=live_fraction,
+ live_layers=live_layers,
+ total_layers=total_layers,
+ all_zero_lora_b_layers=all_zero_b_layers,
+ inner_keys=inner_keys,
+ per_layer=tuple(layer_checks),
+ orphaned_layers=tuple(orphaned_layers),
+ standalone_tensors=tuple(standalone_checks),
+ shape_mismatches=tuple(shape_mismatches),
+ )
+
+
+def render_check_terminal(report: AdapterCheckReport) -> str:
+ """Format human-readable terminal output ending with the exact verdict line."""
+ lines = [
+ f"Adapter: {strip_control(report.adapter)}",
+ f"Total ||ΔW||_F: {report.total_frobenius:.6f}",
+ (
+ f"Live fraction: {report.live_fraction:.1%} "
+ f"({report.live_layers}/{report.total_layers} layers)"
+ ),
+ f"All-zero lora_B layers: {len(report.all_zero_lora_b_layers)}/{report.total_layers}",
+ f"Leaked .inner. keys: {len(report.inner_keys)}",
+ ]
+
+ if report.standalone_tensors:
+ lines.append(f"Standalone non-LoRA tensors: {len(report.standalone_tensors)}")
+
+ if report.orphaned_layers:
+ lines.append(f"Incomplete LoRA pairs: {len(report.orphaned_layers)}")
+ for name in report.orphaned_layers[:5]:
+ lines.append(f" - {strip_control(name)}")
+ if len(report.orphaned_layers) > 5:
+ lines.append(f" ... and {len(report.orphaned_layers) - 5} more")
+
+ if report.shape_mismatches:
+ lines.append(f"Shape-mismatched LoRA pairs: {len(report.shape_mismatches)}")
+ for name in report.shape_mismatches[:5]:
+ lines.append(f" - {strip_control(name)}")
+ if len(report.shape_mismatches) > 5:
+ lines.append(f" ... and {len(report.shape_mismatches) - 5} more")
+
+ if report.all_zero_lora_b_layers:
+ lines.append("Zero lora_B projections:")
+ for name in report.all_zero_lora_b_layers[:5]:
+ lines.append(f" - {strip_control(name)}")
+ if len(report.all_zero_lora_b_layers) > 5:
+ lines.append(f" ... and {len(report.all_zero_lora_b_layers) - 5} more")
+
+ if report.inner_keys:
+ lines.append("Leaked wrapper keys:")
+ for key in report.inner_keys[:5]:
+ lines.append(f" - {strip_control(key)}")
+ if len(report.inner_keys) > 5:
+ lines.append(f" ... and {len(report.inner_keys) - 5} more")
+
+ # Contract requires exact terminal verdict line
+ lines.append(report.verdict_line)
+ return "\n".join(lines)
+
+
+def _sanitize_for_json(val: Any) -> Any:
+ """Coerce non-finite floats to None (null) for RFC 8259 compliance."""
+ if isinstance(val, float):
+ return val if math.isfinite(val) else None
+ if isinstance(val, dict):
+ return {k: _sanitize_for_json(v) for k, v in val.items()}
+ if isinstance(val, (list, tuple)):
+ return [_sanitize_for_json(v) for v in val]
+ return val
+
+
+def render_check_json(report: AdapterCheckReport) -> str:
+ """Render check report as machine-readable JSON document."""
+ data = _sanitize_for_json(asdict(report))
+ data["verdict_line"] = report.verdict_line
+ return json.dumps(data, indent=2, sort_keys=True, allow_nan=False)
diff --git a/tests/test_issue1721_adapters_check.py b/tests/test_issue1721_adapters_check.py
new file mode 100644
index 00000000..f384ba15
--- /dev/null
+++ b/tests/test_issue1721_adapters_check.py
@@ -0,0 +1,855 @@
+"""Tests for soup adapters check: pre-flight health audit (Issue #1721).
+
+Acceptance coverage:
+1. Healthy adapter: ||ΔW||_F > 0, live fraction 1.0, verdict `alive`, exit 0.
+2. Synthetic adapter with all-zero lora_B: verdict `inactive: all lora_B layers are zero`, exit 2.
+3. Synthetic adapter with .inner. wrapper keys: verdict `inactive: leaked .inner. keys`, exit 2.
+4. Partially zero lora_B: live fraction < 1.0, verdict `inactive: lora_B layers are zero`, exit 2.
+5. Non-finite weights (NaN/Inf): verdict `inactive: non-finite weights detected`, exit 2.
+6. JSON mode: --json emits complete document matching terminal metrics.
+7. Pathguard: outside-cwd and symlink rejections exit 1.
+8. Mathematical identity: trace formula matches explicit (B @ A) Frobenius norm bit-for-bit.
+9. rsLoRA scaling factor: alpha / sqrt(r).
+10. Transposed Conv1D shapes: trace identity bit-exact.
+11. Incomplete LoRA pairs: orphaned weights report inactive.
+12. Standalone non-LoRA tensors: zero bias not flagged as zero lora_B.
+13. Strict RFC 8259 JSON: null serialization under NaN weights.
+14. Boolean rank guard: booleans in adapter_config.json safely ignored.
+"""
+
+from __future__ import annotations
+
+import json
+import math
+from pathlib import Path
+
+import numpy as np
+import pytest
+from typer.testing import CliRunner
+
+from soup_cli.cli import app as soup_app
+from soup_cli.utils.adapter_check import (
+ AdapterCheckReport,
+ check_adapter,
+ render_check_terminal,
+)
+from tests.conftest import strip_ansi
+
+runner = CliRunner()
+
+Q_LORA_A = "base_model.model.layers.0.self_attn.q_proj.lora_A.weight"
+Q_LORA_B = "base_model.model.layers.0.self_attn.q_proj.lora_B.weight"
+V_LORA_A = "base_model.model.layers.0.self_attn.v_proj.lora_A.weight"
+V_LORA_B = "base_model.model.layers.0.self_attn.v_proj.lora_B.weight"
+INNER_LORA_A = "base_model.model.layers.0.inner.self_attn.q_proj.lora_A.weight"
+INNER_LORA_B = "base_model.model.layers.0.inner.self_attn.q_proj.lora_B.weight"
+
+
+def _write_synthetic_adapter(
+ dir_path: Path,
+ weights: dict[str, np.ndarray],
+ r: int = 8,
+ alpha: float = 16.0,
+ extra_cfg: dict | None = None,
+) -> None:
+ """Write synthetic adapter directory with safetensors and adapter_config.json."""
+ pytest.importorskip("safetensors")
+ from safetensors.numpy import save_file
+
+ dir_path.mkdir(parents=True, exist_ok=True)
+ save_file(weights, str(dir_path / "adapter_model.safetensors"))
+ cfg = {
+ "peft_type": "LORA",
+ "r": r,
+ "lora_alpha": alpha,
+ "target_modules": ["q_proj", "v_proj"],
+ }
+ if extra_cfg:
+ cfg.update(extra_cfg)
+ (dir_path / "adapter_config.json").write_text(json.dumps(cfg), encoding="utf-8")
+
+
+# ---------- Core Acceptance Tests ----------
+
+
+def test_healthy_adapter_is_alive(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ """A healthy adapter with non-zero updates reports 'alive' and exits 0."""
+ pytest.importorskip("safetensors")
+ monkeypatch.chdir(tmp_path)
+ adapter_dir = tmp_path / "healthy"
+
+ weights = {
+ Q_LORA_A: np.ones((8, 16), dtype=np.float32),
+ Q_LORA_B: 0.5 * np.ones((16, 8), dtype=np.float32),
+ }
+ _write_synthetic_adapter(adapter_dir, weights, r=8, alpha=16.0)
+
+ report = check_adapter("healthy")
+ assert report.verdict == "alive"
+ assert report.reason is None
+ assert report.verdict_line == "alive"
+ assert report.total_frobenius > 0.0
+ assert report.live_fraction == 1.0
+ assert report.live_layers == 1
+ assert report.total_layers == 1
+ assert len(report.all_zero_lora_b_layers) == 0
+ assert len(report.inner_keys) == 0
+
+ # CLI test
+ res = runner.invoke(soup_app, ["adapters", "check", "healthy"])
+ assert res.exit_code == 0
+ lines = res.stdout.strip().splitlines()
+ assert lines[-1] == "alive"
+ assert "Live fraction: 100.0%" in strip_ansi(res.stdout)
+
+
+def test_all_zero_lora_b_reports_inactive(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ """An untrained adapter with all-zero lora_B reports inactive and exits 2."""
+ pytest.importorskip("safetensors")
+ monkeypatch.chdir(tmp_path)
+ adapter_dir = tmp_path / "zero_b"
+
+ weights = {
+ Q_LORA_A: np.ones((8, 16), dtype=np.float32),
+ Q_LORA_B: np.zeros((16, 8), dtype=np.float32),
+ }
+ _write_synthetic_adapter(adapter_dir, weights, r=8, alpha=16.0)
+
+ report = check_adapter("zero_b")
+ assert report.verdict == "inactive"
+ assert report.reason == "all lora_B layers are zero (1/1)"
+ assert report.verdict_line == "inactive: all lora_B layers are zero (1/1)"
+ assert report.total_frobenius == 0.0
+ assert report.live_fraction == 0.0
+ assert report.live_layers == 0
+ assert len(report.all_zero_lora_b_layers) == 1
+
+ # CLI test
+ res = runner.invoke(soup_app, ["adapters", "check", "zero_b"])
+ assert res.exit_code == 2
+ lines = res.stdout.strip().splitlines()
+ assert lines[-1] == "inactive: all lora_B layers are zero (1/1)"
+
+
+def test_inner_namespace_leak_reports_inactive(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ """An adapter with leaked .inner. wrapper keys reports inactive and exits 2."""
+ pytest.importorskip("safetensors")
+ monkeypatch.chdir(tmp_path)
+ adapter_dir = tmp_path / "inner_leak"
+
+ weights = {
+ INNER_LORA_A: np.ones((8, 16), dtype=np.float32),
+ INNER_LORA_B: 0.5 * np.ones((16, 8), dtype=np.float32),
+ }
+ _write_synthetic_adapter(adapter_dir, weights, r=8, alpha=16.0)
+
+ report = check_adapter("inner_leak")
+ assert report.verdict == "inactive"
+ assert "leaked .inner. keys detected" in (report.reason or "")
+ assert len(report.inner_keys) == 2
+ assert INNER_LORA_A in report.inner_keys
+
+ # CLI test
+ res = runner.invoke(soup_app, ["adapters", "check", "inner_leak"])
+ assert res.exit_code == 2
+ lines = res.stdout.strip().splitlines()
+ assert lines[-1].startswith("inactive: leaked .inner. keys detected")
+
+
+def test_partially_zero_lora_b(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ """An adapter with some zero and some live lora_B layers reports inactive with layer ratio."""
+ pytest.importorskip("safetensors")
+ monkeypatch.chdir(tmp_path)
+ adapter_dir = tmp_path / "partial"
+
+ weights = {
+ Q_LORA_A: np.ones((8, 16), dtype=np.float32),
+ Q_LORA_B: 0.5 * np.ones((16, 8), dtype=np.float32),
+ V_LORA_A: np.ones((8, 16), dtype=np.float32),
+ V_LORA_B: np.zeros((16, 8), dtype=np.float32),
+ }
+ _write_synthetic_adapter(adapter_dir, weights, r=8, alpha=16.0)
+
+ report = check_adapter("partial")
+ assert report.verdict == "inactive"
+ assert report.reason == "lora_B layers are zero (1/2)"
+ assert report.live_fraction == 0.5
+ assert report.live_layers == 1
+ assert report.total_layers == 2
+ assert len(report.all_zero_lora_b_layers) == 1
+
+ res = runner.invoke(soup_app, ["adapters", "check", "partial"])
+ assert res.exit_code == 2
+ lines = res.stdout.strip().splitlines()
+ assert lines[-1] == "inactive: lora_B layers are zero (1/2)"
+
+
+def test_non_finite_weights_rejected(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ """NaN/Inf in weights causes inactive classification."""
+ pytest.importorskip("safetensors")
+ monkeypatch.chdir(tmp_path)
+ adapter_dir = tmp_path / "nan_adapter"
+
+ nan_b = np.ones((16, 8), dtype=np.float32)
+ nan_b[0, 0] = np.nan
+ weights = {
+ Q_LORA_A: np.ones((8, 16), dtype=np.float32),
+ Q_LORA_B: nan_b,
+ }
+ _write_synthetic_adapter(adapter_dir, weights, r=8, alpha=16.0)
+
+ report = check_adapter("nan_adapter")
+ assert report.verdict == "inactive"
+ assert report.reason == "non-finite weights detected (NaN/Inf)"
+ assert math.isnan(report.total_frobenius)
+
+ res = runner.invoke(soup_app, ["adapters", "check", "nan_adapter"])
+ assert res.exit_code == 2
+ assert "inactive: non-finite weights detected" in res.stdout
+
+
+def test_json_output_mode(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ """--json emits valid parseable JSON document matching the terminal metrics."""
+ pytest.importorskip("safetensors")
+ monkeypatch.chdir(tmp_path)
+ adapter_dir = tmp_path / "healthy"
+
+ weights = {
+ Q_LORA_A: np.ones((4, 8), dtype=np.float32),
+ Q_LORA_B: np.ones((8, 4), dtype=np.float32),
+ }
+ _write_synthetic_adapter(adapter_dir, weights, r=4, alpha=8.0)
+
+ res = runner.invoke(soup_app, ["adapters", "check", "healthy", "--json"])
+ assert res.exit_code == 0
+ doc = json.loads(res.stdout)
+ assert doc["verdict"] == "alive"
+ assert doc["verdict_line"] == "alive"
+ assert doc["live_fraction"] == 1.0
+ assert doc["live_layers"] == 1
+ assert doc["total_layers"] == 1
+ assert doc["total_frobenius"] > 0.0
+ assert "inner_keys" in doc and doc["inner_keys"] == []
+ assert "all_zero_lora_b_layers" in doc and doc["all_zero_lora_b_layers"] == []
+ assert "reason" in doc and doc["reason"] is None
+ assert len(doc["per_layer"]) == 1
+
+
+# ---------- Security & Path Validation ----------
+
+
+def test_outside_cwd_rejected(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ """Adapters outside cwd must be refused by the path guard."""
+ work_dir = tmp_path / "work"
+ work_dir.mkdir()
+ outside_dir = tmp_path / "outside_adapter"
+ outside_dir.mkdir()
+ monkeypatch.chdir(work_dir)
+
+ with pytest.raises(ValueError, match="must stay under cwd"):
+ check_adapter(str(outside_dir))
+
+ res = runner.invoke(soup_app, ["adapters", "check", str(outside_dir)])
+ assert res.exit_code == 1
+ assert "refused" in res.output.lower()
+ assert "not found" not in res.output.lower()
+
+
+def test_missing_adapter_rejected(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ """Non-existent adapter directory exits 1."""
+ monkeypatch.chdir(tmp_path)
+ with pytest.raises(FileNotFoundError):
+ check_adapter("does_not_exist")
+
+ res = runner.invoke(soup_app, ["adapters", "check", "does_not_exist"])
+ assert res.exit_code == 1
+ assert "does_not_exist" in res.output or "not found" in res.output.lower()
+
+
+# ---------- Multi-Layer RSS & Conv1D Transposed Contraction ----------
+
+
+def test_two_layer_and_conv1d_transposed_adapter(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+):
+ """Assert total_frobenius == sqrt(sum of squares) and Conv1D transposed contraction."""
+ pytest.importorskip("safetensors")
+ monkeypatch.chdir(tmp_path)
+ adapter_dir = tmp_path / "two_layer_conv1d"
+
+ # Layer 0: standard Linear (q_proj), r=8, out=16, in=32 -> B is (16, 8), A is (8, 32)
+ rng = np.random.default_rng(123)
+ q_b = rng.standard_normal((16, 8)).astype(np.float32)
+ q_a = rng.standard_normal((8, 32)).astype(np.float32)
+
+ # Layer 1: transposed Conv1D (v_proj), r=8, in=32, out=16 -> B is (8, 16), A is (32, 8)
+ v_b = rng.standard_normal((8, 16)).astype(np.float32)
+ v_a = rng.standard_normal((32, 8)).astype(np.float32)
+
+ weights = {
+ Q_LORA_A: q_a,
+ Q_LORA_B: q_b,
+ V_LORA_A: v_a,
+ V_LORA_B: v_b,
+ }
+ _write_synthetic_adapter(adapter_dir, weights, r=8, alpha=16.0)
+
+ report = check_adapter("two_layer_conv1d")
+ assert report.verdict == "alive"
+ assert report.total_layers == 2
+ assert report.live_layers == 2
+
+ # Direct computation: scaling = 16.0 / 8 = 2.0
+ delta0 = 2.0 * np.matmul(q_b.astype(np.float64), q_a.astype(np.float64))
+ expected_fro0 = float(np.linalg.norm(delta0))
+
+ delta1 = 2.0 * np.matmul(v_a.astype(np.float64), v_b.astype(np.float64))
+ expected_fro1 = float(np.linalg.norm(delta1))
+
+ assert math.isclose(report.per_layer[0].frobenius, expected_fro0, rel_tol=1e-12)
+ assert math.isclose(report.per_layer[1].frobenius, expected_fro1, rel_tol=1e-12)
+
+ # Total frobenius must equal Root-Sum-of-Squares (RSS), not simple linear sum
+ expected_total = math.sqrt(expected_fro0**2 + expected_fro1**2)
+ assert math.isclose(report.total_frobenius, expected_total, rel_tol=1e-12)
+
+
+# ---------- Hardening & Invariant Defenses ----------
+
+
+def test_rslora_scaling_factor(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ """When use_rslora is True, scaling factor must be alpha / sqrt(r)."""
+ pytest.importorskip("safetensors")
+ monkeypatch.chdir(tmp_path)
+ adapter_dir = tmp_path / "rslora"
+
+ r = 16
+ alpha = 32.0
+ # Expected scaling: 32 / sqrt(16) = 32 / 4 = 8.0
+ weights = {
+ Q_LORA_A: np.ones((16, 8), dtype=np.float32),
+ Q_LORA_B: np.ones((8, 16), dtype=np.float32),
+ }
+ _write_synthetic_adapter(
+ adapter_dir, weights, r=r, alpha=alpha, extra_cfg={"use_rslora": True}
+ )
+
+ report = check_adapter("rslora")
+ assert report.verdict == "alive"
+ # Direct computation: 8.0 * ||B @ A||_F
+ b_mat = np.ones((8, 16), dtype=np.float64)
+ a_mat = np.ones((16, 8), dtype=np.float64)
+ expected_fro = 8.0 * float(np.sqrt(np.sum(np.matmul(b_mat, a_mat) ** 2)))
+ assert math.isclose(report.total_frobenius, expected_fro, rel_tol=1e-6)
+
+
+def test_incomplete_lora_pair_reported_inactive(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+):
+ """An adapter with orphaned LoRA weights (missing A or missing B) reports inactive."""
+ pytest.importorskip("safetensors")
+ monkeypatch.chdir(tmp_path)
+ adapter_dir = tmp_path / "orphan"
+
+ weights = {
+ Q_LORA_A: np.ones((8, 16), dtype=np.float32),
+ # Q_LORA_B is intentionally missing
+ }
+ _write_synthetic_adapter(adapter_dir, weights, r=8, alpha=16.0)
+
+ report = check_adapter("orphan")
+ assert report.verdict == "inactive"
+ assert "incomplete LoRA pairs detected" in (report.reason or "")
+ assert len(report.orphaned_layers) == 1
+
+ res = runner.invoke(soup_app, ["adapters", "check", "orphan"])
+ assert res.exit_code == 2
+ assert "inactive: incomplete LoRA pairs detected" in res.stdout
+
+
+def test_standalone_tensor_not_flagged_as_lora_b(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+):
+ """Zero-valued standalone non-LoRA tensors must not be counted as all-zero lora_B layers."""
+ pytest.importorskip("safetensors")
+ monkeypatch.chdir(tmp_path)
+ adapter_dir = tmp_path / "with_bias"
+
+ weights = {
+ Q_LORA_A: np.ones((8, 16), dtype=np.float32),
+ Q_LORA_B: 0.5 * np.ones((16, 8), dtype=np.float32),
+ "base_model.model.custom_bias": np.zeros((16,), dtype=np.float32),
+ }
+ _write_synthetic_adapter(adapter_dir, weights, r=8, alpha=16.0)
+
+ report = check_adapter("with_bias")
+ assert report.verdict == "alive"
+ assert len(report.all_zero_lora_b_layers) == 0
+ assert report.total_layers == 1
+ assert report.live_fraction == 1.0
+ assert len(report.standalone_tensors) == 1
+
+
+def test_adapter_with_only_standalone_tensors_reports_no_lora(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+):
+ """An adapter with only saved heads / biases and 0 LoRA pairs reports no lora weights."""
+ pytest.importorskip("safetensors")
+ monkeypatch.chdir(tmp_path)
+ adapter_dir = tmp_path / "only_heads"
+
+ weights = {
+ "base_model.model.lm_head.weight": np.ones((32, 16), dtype=np.float32),
+ }
+ _write_synthetic_adapter(adapter_dir, weights, r=8, alpha=16.0)
+
+ report = check_adapter("only_heads")
+ assert report.verdict == "inactive"
+ assert report.reason == "no lora weights found"
+ assert report.total_layers == 0
+ assert len(report.standalone_tensors) == 1
+
+
+def test_json_mode_rfc8259_strict_under_nan(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+):
+ """Under NaN weights, render_check_json produces RFC 8259 compliant JSON with nulls."""
+ pytest.importorskip("safetensors")
+ monkeypatch.chdir(tmp_path)
+ adapter_dir = tmp_path / "nan_adapter"
+
+ nan_b = np.ones((16, 8), dtype=np.float32)
+ nan_b[0, 0] = np.nan
+ weights = {
+ Q_LORA_A: np.ones((8, 16), dtype=np.float32),
+ Q_LORA_B: nan_b,
+ }
+ _write_synthetic_adapter(adapter_dir, weights, r=8, alpha=16.0)
+
+ res = runner.invoke(soup_app, ["adapters", "check", "nan_adapter", "--json"])
+ assert res.exit_code == 2
+ def reject_constant(c):
+ raise ValueError(f"Non-compliant JSON token: {c}")
+
+ doc = json.loads(res.stdout, parse_constant=reject_constant)
+ assert doc["verdict"] == "inactive"
+ assert doc["reason"] == "non-finite weights detected (NaN/Inf)"
+ assert doc["total_frobenius"] is None
+ assert "inner_keys" in doc
+ assert "all_zero_lora_b_layers" in doc
+ assert '"total_frobenius": null' in strip_ansi(res.stdout)
+
+
+def test_boolean_rank_in_config_not_coerced(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+):
+ """Boolean 'r': true in adapter_config.json must not be coerced to integer 1."""
+ pytest.importorskip("safetensors")
+ monkeypatch.chdir(tmp_path)
+ adapter_dir = tmp_path / "bool_cfg"
+
+ weights = {
+ Q_LORA_A: np.ones((8, 16), dtype=np.float32),
+ Q_LORA_B: 0.5 * np.ones((16, 8), dtype=np.float32),
+ }
+ _write_synthetic_adapter(
+ adapter_dir, weights, r=8, alpha=16.0, extra_cfg={"r": True}
+ )
+
+ report = check_adapter("bool_cfg")
+ # Rank is invalid (bool), so fallback scaling 1.0 is used rather than 16/1 = 16.0
+ b_mat = 0.5 * np.ones((16, 8), dtype=np.float64)
+ a_mat = np.ones((8, 16), dtype=np.float64)
+ expected_fro = 1.0 * float(np.sqrt(np.sum(np.matmul(b_mat, a_mat) ** 2)))
+ assert math.isclose(report.total_frobenius, expected_fro, rel_tol=1e-6)
+
+
+def test_lora_shape_mismatch_reported_inactive(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+):
+ """Mismatched A and B matrix shapes report inactive with shape mismatch reason."""
+ pytest.importorskip("safetensors")
+ monkeypatch.chdir(tmp_path)
+ adapter_dir = tmp_path / "bad_shapes"
+
+ # Incompatible shapes: A is (7, 13), B is (11, 19)
+ weights = {
+ Q_LORA_A: np.ones((7, 13), dtype=np.float32),
+ Q_LORA_B: np.ones((11, 19), dtype=np.float32),
+ }
+ _write_synthetic_adapter(adapter_dir, weights, r=8, alpha=16.0)
+
+ report = check_adapter("bad_shapes")
+ assert report.verdict == "inactive"
+ assert "shape mismatch in LoRA projections" in (report.reason or "")
+ assert len(report.shape_mismatches) == 1
+ assert math.isnan(report.total_frobenius)
+
+ res = runner.invoke(soup_app, ["adapters", "check", "bad_shapes"])
+ assert res.exit_code == 2
+ assert "inactive: shape mismatch in LoRA projections" in res.stdout
+
+
+# ---------- Mutation Resistance Teeth ----------
+
+
+def test_mutation_zero_b_detection_teeth():
+ """Verify that if all-zero B check is removed, healthy and zero-B adapters would conflate."""
+ # Control: zero B must report is_b_zero True
+ zero_b = np.zeros((16, 8), dtype=np.float64)
+ assert bool(np.all(zero_b == 0.0)) is True
+
+ # Perturbed: even a 1e-7 perturbation must report is_b_zero False
+ live_b = zero_b.copy()
+ live_b[0, 0] = 1e-7
+ assert bool(np.all(live_b == 0.0)) is False
+
+
+def test_corrupt_adapter_config_json_raises(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ """Corrupted adapter_config.json must raise ValueError and exit 1."""
+ pytest.importorskip("safetensors")
+ from safetensors.numpy import save_file
+
+ monkeypatch.chdir(tmp_path)
+ adapter_dir = tmp_path / "corrupt_cfg"
+ adapter_dir.mkdir(parents=True, exist_ok=True)
+
+ weights = {
+ Q_LORA_A: np.ones((16, 8), dtype=np.float32),
+ Q_LORA_B: np.ones((8, 16), dtype=np.float32),
+ }
+ save_file(weights, str(adapter_dir / "adapter_model.safetensors"))
+ (adapter_dir / "adapter_config.json").write_text("{\"r\": 8, invalid_json", encoding="utf-8")
+
+ with pytest.raises(ValueError, match="unreadable or invalid JSON"):
+ check_adapter("corrupt_cfg")
+
+ res = runner.invoke(soup_app, ["adapters", "check", "corrupt_cfg"])
+ assert res.exit_code == 1
+
+
+def test_non_dict_adapter_config_json_raises(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ """Non-dict JSON in adapter_config.json must raise ValueError and exit 1."""
+ pytest.importorskip("safetensors")
+ from safetensors.numpy import save_file
+
+ monkeypatch.chdir(tmp_path)
+ adapter_dir = tmp_path / "nondict_cfg"
+ adapter_dir.mkdir(parents=True, exist_ok=True)
+
+ weights = {
+ Q_LORA_A: np.ones((16, 8), dtype=np.float32),
+ Q_LORA_B: np.ones((8, 16), dtype=np.float32),
+ }
+ save_file(weights, str(adapter_dir / "adapter_model.safetensors"))
+ (adapter_dir / "adapter_config.json").write_text("[1, 2, 3]", encoding="utf-8")
+
+ with pytest.raises(ValueError, match="expected JSON object"):
+ check_adapter("nondict_cfg")
+
+ res = runner.invoke(soup_app, ["adapters", "check", "nondict_cfg"])
+ assert res.exit_code == 1
+
+
+def test_fp16_float64_accumulation_precision(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+):
+ """FP16 inputs must accumulate in float64 without float32 precision loss (rel_tol=1e-12)."""
+ pytest.importorskip("safetensors")
+ monkeypatch.chdir(tmp_path)
+ adapter_dir = tmp_path / "fp16_prec"
+
+ rng = np.random.default_rng(42)
+ b_fp16 = (rng.standard_normal((512, 16)) * 1000.0).astype(np.float16)
+ a_fp16 = (rng.standard_normal((16, 512)) * 1000.0).astype(np.float16)
+ weights = {
+ Q_LORA_A: a_fp16,
+ Q_LORA_B: b_fp16,
+ }
+ _write_synthetic_adapter(adapter_dir, weights, r=16, alpha=16.0)
+
+ report = check_adapter("fp16_prec")
+ assert report.verdict == "alive"
+
+ b64 = b_fp16.astype(np.float64)
+ a64 = a_fp16.astype(np.float64)
+ expected_fro = float(np.linalg.norm(b64 @ a64))
+
+ assert math.isclose(report.total_frobenius, expected_fro, rel_tol=1e-12)
+
+
+def test_symlinked_components_refused(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+):
+ """Symlinked adapter dir, adapter_model.safetensors, and adapter_config.json each exit 1."""
+ pytest.importorskip("safetensors")
+ monkeypatch.chdir(tmp_path)
+
+ real_dir = tmp_path / "real_adapter"
+ weights = {
+ Q_LORA_A: np.ones((8, 16), dtype=np.float32),
+ Q_LORA_B: np.ones((16, 8), dtype=np.float32),
+ }
+ _write_synthetic_adapter(real_dir, weights, r=8, alpha=16.0)
+
+ # 1. Symlinked directory
+ symlink_dir = tmp_path / "symlink_dir"
+ symlink_dir.symlink_to(real_dir, target_is_directory=True)
+ res1 = runner.invoke(soup_app, ["adapters", "check", "symlink_dir"])
+ assert res1.exit_code == 1
+ assert "must not be a symlink" in strip_ansi(res1.output)
+
+ # 2. Symlinked adapter_model.safetensors
+ adapter_symlink_weights = tmp_path / "symlink_weights"
+ adapter_symlink_weights.mkdir()
+ (adapter_symlink_weights / "adapter_config.json").write_text(
+ (real_dir / "adapter_config.json").read_text(encoding="utf-8"), encoding="utf-8"
+ )
+ (adapter_symlink_weights / "adapter_model.safetensors").symlink_to(
+ real_dir / "adapter_model.safetensors"
+ )
+ res2 = runner.invoke(soup_app, ["adapters", "check", "symlink_weights"])
+ assert res2.exit_code == 1
+ assert "must not be a symlink" in strip_ansi(res2.output)
+
+ # 3. Symlinked adapter_config.json
+ adapter_symlink_cfg = tmp_path / "symlink_cfg"
+ adapter_symlink_cfg.mkdir()
+ (adapter_symlink_cfg / "adapter_model.safetensors").write_bytes(
+ (real_dir / "adapter_model.safetensors").read_bytes()
+ )
+ (adapter_symlink_cfg / "adapter_config.json").symlink_to(
+ real_dir / "adapter_config.json"
+ )
+ res3 = runner.invoke(soup_app, ["adapters", "check", "symlink_cfg"])
+ assert res3.exit_code == 1
+ assert "must not be a symlink" in strip_ansi(res3.output)
+
+
+def test_standard_lora_scaling_factor(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+):
+ """Standard LoRA scaling must compute scaling = alpha / r (e.g. 32 / 8 = 4.0)."""
+ pytest.importorskip("safetensors")
+ monkeypatch.chdir(tmp_path)
+ adapter_dir = tmp_path / "standard_scaling"
+
+ r = 8
+ alpha = 32.0
+ weights = {
+ Q_LORA_A: np.ones((8, 16), dtype=np.float32),
+ Q_LORA_B: np.ones((16, 8), dtype=np.float32),
+ }
+ _write_synthetic_adapter(adapter_dir, weights, r=r, alpha=alpha)
+
+ report = check_adapter("standard_scaling")
+ assert report.verdict == "alive"
+
+ b_mat = np.ones((16, 8), dtype=np.float64)
+ a_mat = np.ones((8, 16), dtype=np.float64)
+ expected_fro = 4.0 * float(np.linalg.norm(b_mat @ a_mat))
+ assert math.isclose(report.total_frobenius, expected_fro, rel_tol=1e-6)
+
+
+def test_terminal_injection_control_bytes_stripped(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+):
+ """Control and ANSI escape sequences in tensor names must be stripped in terminal output."""
+ pytest.importorskip("safetensors")
+ monkeypatch.chdir(tmp_path)
+ adapter_dir = tmp_path / "esc_adapter"
+
+ esc_key = "base_model.model.layers.0.inner.\x1b[2Jself_attn.q_proj.lora_A.weight"
+ weights = {
+ esc_key: np.ones((8, 16), dtype=np.float32),
+ }
+ _write_synthetic_adapter(adapter_dir, weights, r=8, alpha=16.0)
+
+ res = runner.invoke(soup_app, ["adapters", "check", "esc_adapter"])
+ assert chr(27) not in res.stdout
+ assert "\x1b" not in res.stdout
+
+
+def test_zero_lora_a_is_inactive(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ """When lora_A is all zeros, adapter is inactive with reason 'total ||ΔW||_F is 0.0'."""
+ pytest.importorskip("safetensors")
+ monkeypatch.chdir(tmp_path)
+ weights = {
+ Q_LORA_A: np.zeros((8, 16), dtype=np.float32),
+ Q_LORA_B: np.ones((16, 8), dtype=np.float32),
+ }
+ _write_synthetic_adapter(tmp_path / "za", weights, r=8, alpha=16.0)
+
+ report = check_adapter("za")
+ assert report.verdict == "inactive"
+ assert report.reason == "total ||ΔW||_F is 0.0"
+ assert report.verdict_line == "inactive: total ||ΔW||_F is 0.0"
+ assert report.total_frobenius == 0.0
+ assert report.live_fraction == 0.0
+ assert report.live_layers == 0
+ assert len(report.all_zero_lora_b_layers) == 0
+
+ res = runner.invoke(soup_app, ["adapters", "check", "za"])
+ assert res.exit_code == 2
+ out = strip_ansi(res.stdout)
+ assert out.strip().splitlines()[-1].startswith("inactive: total ||")
+ assert "inactive: total ||ΔW||_F is 0.0" in out
+ assert "Total ||ΔW||_F: 0.000000" in out
+ assert "Live fraction: 0.0% (0/1 layers)" in out
+
+
+def test_terminal_sanitization_adapter_path():
+ """Adapter path carrying escape bytes in terminal report must be stripped."""
+ report = AdapterCheckReport(
+ adapter="models/\x1b[2Jmalicious_run\x1b[0m",
+ verdict="alive",
+ reason=None,
+ total_frobenius=1.0,
+ live_fraction=1.0,
+ live_layers=1,
+ total_layers=1,
+ all_zero_lora_b_layers=(),
+ inner_keys=(),
+ per_layer=(),
+ )
+ rendered = render_check_terminal(report)
+ assert chr(27) not in rendered
+ assert "\x1b" not in rendered
+ assert "malicious_run" in rendered
+
+
+def test_terminal_sanitization_shape_mismatches(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+):
+ """Shape-mismatched projection names with control bytes must be sanitized."""
+ pytest.importorskip("safetensors")
+ monkeypatch.chdir(tmp_path)
+ adapter_dir = tmp_path / "mismatch_esc"
+
+ esc_shape_a = "base_model.model.layers.0.self_attn.\x1b[31mmismatch_layer\x1b[0m.lora_A.weight"
+ esc_shape_b = "base_model.model.layers.0.self_attn.\x1b[31mmismatch_layer\x1b[0m.lora_B.weight"
+ weights = {
+ esc_shape_a: np.ones((16, 8), dtype=np.float32),
+ esc_shape_b: np.ones((16, 8), dtype=np.float32),
+ }
+ _write_synthetic_adapter(adapter_dir, weights, r=4, alpha=16.0)
+
+ res = runner.invoke(soup_app, ["adapters", "check", "mismatch_esc"])
+ assert res.exit_code == 2
+ assert chr(27) not in res.stdout
+ assert "\x1b" not in res.stdout
+ assert "Shape-mismatched LoRA pairs:" in res.stdout
+ assert "mismatch_layer" in res.stdout
+
+
+def test_terminal_sanitization_zero_b_names(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+):
+ """Zero-B layer names carrying control bytes must be sanitized in terminal output."""
+ pytest.importorskip("safetensors")
+ monkeypatch.chdir(tmp_path)
+ adapter_dir = tmp_path / "zero_b_esc"
+
+ esc_b_name = "base_model.model.layers.0.self_attn.\x1b[2Jzero_b_layer\x1b[0m.lora_B.weight"
+ esc_a_name = "base_model.model.layers.0.self_attn.\x1b[2Jzero_b_layer\x1b[0m.lora_A.weight"
+ weights = {
+ esc_a_name: np.ones((8, 16), dtype=np.float32),
+ esc_b_name: np.zeros((16, 8), dtype=np.float32),
+ }
+ _write_synthetic_adapter(adapter_dir, weights, r=8, alpha=16.0)
+
+ res = runner.invoke(soup_app, ["adapters", "check", "zero_b_esc"])
+ assert res.exit_code == 2
+ assert chr(27) not in res.stdout
+ assert "\x1b" not in res.stdout
+ assert "Zero lora_B projections:" in res.stdout
+ assert "zero_b_layer" in res.stdout
+
+
+def test_terminal_sanitization_cli_errors(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+):
+ """CLI errors and invalid JSON messages with control characters must be stripped on stderr."""
+ pytest.importorskip("safetensors")
+ from rich.console import Console
+
+ import soup_cli.commands.adapters as adapters_cmd
+
+ monkeypatch.setattr(
+ adapters_cmd, "_err_console", Console(stderr=True, force_terminal=False)
+ )
+ monkeypatch.chdir(tmp_path)
+
+ # 1. Non-existent path argument with escape bytes
+ res_path = runner.invoke(soup_app, ["adapters", "check", "nonexistent_\x1b[2J_dir"])
+ assert res_path.exit_code == 1
+ assert chr(27) not in res_path.output
+ assert "\x1b" not in res_path.output
+
+ # 2. Corrupt adapter_config.json with escape bytes
+ corrupt_dir = tmp_path / "corrupt_esc"
+ corrupt_dir.mkdir()
+ (corrupt_dir / "adapter_config.json").write_text(
+ "{\x1b[2J\"invalid_json\":", encoding="utf-8"
+ )
+ (corrupt_dir / "adapter_model.safetensors").write_bytes(b"empty")
+
+ res_cfg = runner.invoke(soup_app, ["adapters", "check", "corrupt_esc"])
+ assert res_cfg.exit_code == 1
+ assert chr(27) not in res_cfg.output
+ assert "\x1b" not in res_cfg.output
+
+
+def test_terminal_sanitization_verdict_line():
+ """Verdict line carrying control bytes in reason must be sanitized by verdict_line."""
+ report = AdapterCheckReport(
+ adapter="models/run",
+ verdict="inactive",
+ reason="injected\x1b[2Jreason\x1b[0m",
+ total_frobenius=0.0,
+ live_fraction=0.0,
+ live_layers=0,
+ total_layers=1,
+ all_zero_lora_b_layers=(),
+ inner_keys=(),
+ per_layer=(),
+ )
+ line = report.verdict_line
+ assert chr(27) not in line
+ assert "\x1b" not in line
+ assert line == "inactive: injected[2Jreason[0m"
+
+
+def test_every_rendered_name_is_stripped(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+):
+ """Every rendered name and CLI error path must have control bytes stripped."""
+ from rich.console import Console
+
+ import soup_cli.commands.adapters as adapters_cmd
+
+ monkeypatch.setattr(
+ adapters_cmd, "_err_console", Console(stderr=True, force_terminal=False)
+ )
+ evil = "x\x1b[2Jy\x9bz"
+ report = AdapterCheckReport(
+ adapter=evil,
+ verdict="inactive",
+ reason="r",
+ total_frobenius=0.0,
+ live_fraction=0.0,
+ live_layers=0,
+ total_layers=2,
+ all_zero_lora_b_layers=(evil,),
+ inner_keys=(evil,),
+ per_layer=(),
+ orphaned_layers=(evil,),
+ shape_mismatches=(evil,),
+ )
+ out = render_check_terminal(report)
+ assert chr(27) not in out and "\x9b" not in out
+ assert out.count("x[2Jyz") == 5
+ monkeypatch.chdir(tmp_path)
+ res = runner.invoke(soup_app, ["adapters", "check", "no\x1b[2Jdir"])
+ assert res.exit_code == 1 and chr(27) not in res.output