AQIT 0.1.0
Loading...
Searching...
No Matches
confidence_analysis_cli.py
Go to the documentation of this file.
1# Copyright (c) 2025-present Aquin Labs Private Limited. All Rights Reserved.
2"""aquin check confidence — per-probe confidence + optional SAE join."""
3
4import sys
5
6from aquin.cli_flags import reject_legacy_output_flags
7from pathlib import Path
8from typing import Any
9
10
11def _parse_flag(args: list[str], name: str) -> str | None:
12 for i, a in enumerate(args):
13 if a == name and i + 1 < len(args):
14 return args[i + 1]
15 return None
16
17
18def _has_flag(args: list[str], name: str) -> bool:
19 return name in args
20
21
22def _ensure_compute_env() -> None:
23 from aquin.compute.loader_shim import apply as _shim_apply
24 from aquin.engine.local_server import start as _start_local_server
25
26 _shim_apply()
27 _start_local_server()
28
29
30def _require_loaded_model_id() -> str:
31 from aquin.compute.model_loader import get_active_model_id, resolve_model_id
32
33 active = (get_active_model_id() or "").strip()
34 if not active:
35 print("Error: no model loaded. Run: aquin load --model <id>")
36 sys.exit(1)
37 try:
38 return resolve_model_id(active)
39 except ValueError as e:
40 print(f"Error: {e}")
41 sys.exit(1)
42
43
44def _print_help() -> None:
45 print("Measure confidence patterns over a probe dataset (LLM).")
46 print("")
47 print("Prerequisite: aquin load --model <id>")
48 print(" Token logits (mean greedy prob, entropy)")
49 print("")
50 print("Usage: aquin check confidence --prompts <json|jsonl>")
51 print(" [--threshold <0-1>]")
52 print(" [--join-sae] [--layer <n>]")
53 print(" [--save <path>]")
54 print(" [--check]")
55 print("")
56 print(" --prompts Probe file (text + optional id, stressor, lang, quant_run_id).")
57 print(" --threshold Low-confidence cutoff (default: 0.40).")
58 print(" --join-sae Attach SAE mean L0 + top feature per probe.")
59 print(" --layer SAE layer for join (default: model sae_layer).")
60 print(" --save Write schema_version=1 JSON export.")
61 print(" --check Save confidence-analysis-check.json and confidence-analysis-check.png in cwd.")
62 print("")
63 print("Example (LLM):")
64 print(" aquin check confidence --prompts probes.jsonl --join-sae --layer 8 --check")
65 print("")
66 print("Docs: https://aquin.app/docs/evals/llm")
67
68
69def cmd_confidence_analysis(args: list[str]) -> None:
70 if _has_flag(args, "--help") or _has_flag(args, "-h"):
72 return
74 reject_legacy_output_flags(args)
75
76 prompts = _parse_flag(args, "--prompts")
77 if not prompts:
78 print("Error: --prompts is required.")
79 print("")
81 sys.exit(1)
82
83 from aquin.compute.activation_capture import resolve_prompts_path
84
85 resolved = resolve_prompts_path(Path(prompts).expanduser())
86 if resolved is None:
87 print(f"Error: probe file not found: {prompts}")
88 print(" Tried cwd and repo parent.")
89 sys.exit(1)
90 prompts = str(resolved)
91
92 if _parse_flag(args, "--model") is not None:
93 print("Error: check confidence uses the loaded session model only.")
94 sys.exit(1)
95
97
98 from aquin.cli import _build_tool_ctx
99 from aquin.engine.sync_dispatch import dispatch_with_sync, require_active_session
100
102 ctx = _build_tool_ctx(model_id=mid)
103 require_active_session(ctx, label="aquin check confidence")
104
105 tool_args: dict[str, Any] = {
106 "model_id": mid,
107 "prompts": prompts,
108 "threshold": _parse_flag(args, "--threshold"),
109 "join_sae": _has_flag(args, "--join-sae"),
110 "layer": _parse_flag(args, "--layer"),
111 "save": _parse_flag(args, "--save"),
112 }
113 do_check = _has_flag(args, "--check")
114
115 try:
116 print(
117 f"[check confidence] model={mid} probes={prompts}"
118 f" join_sae={tool_args['join_sae']}"
119 )
120 result = dispatch_with_sync("run_confidence_analysis", tool_args, ctx)
121 except Exception as e:
122 print(f"Error: {e}")
123 sys.exit(1)
124
125 from aquin.cli_output import print_tool_result
126
127 print_tool_result("check confidence", result)
128
129 if do_check:
130 if isinstance(result, dict) and result.get("error"):
131 print(f"[check confidence --check] skipped save: {result['error']}", file=sys.stderr)
132 else:
133 import os
134 from aquin.confidence_analysis_check import write_confidence_analysis_check
135
136 try:
137 json_path, png_path = write_confidence_analysis_check(
138 result, tool_name="run_confidence_analysis", cwd=os.getcwd(),
139 )
140 print(f"Saved {json_path}")
141 print(f"Saved {png_path}")
142 except Exception as exc:
143 print(f"[check confidence --check] failed to save files: {exc}", file=sys.stderr)
144 import traceback
145 traceback.print_exc()
146 sys.exit(1)
147
148 if isinstance(result, dict) and result.get("error"):
149 sys.exit(1)
bool _has_flag(list[str] args, str name)
str|None _parse_flag(list[str] args, str name)
None cmd_confidence_analysis(list[str] args)