AQIT 0.1.0
Loading...
Searching...
No Matches
residual_drift_cli.py
Go to the documentation of this file.
1# Copyright (c) 2025-present Aquin Labs Private Limited. All Rights Reserved.
2"""aquin diff residue — base vs checkpoint per-layer activation drift."""
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 _resolve_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("Per-layer activation drift between catalog base and a fine-tuned checkpoint.")
46 print("")
47 print("Prerequisite: aquin load --model <id>")
48 print("")
49 print("Usage: aquin diff residue --checkpoint <path>")
50 print(" [--prompts <json|jsonl>] [--name <label>] [--save <path>]")
51 print("")
52 print(" --checkpoint Fine-tuned .pt state_dict or HF save_pretrained directory.")
53 print(" --prompts Probe strings (default: built-in short prompts).")
54 print(" --name Label for checkpoint in output and web card.")
55 print(" --save Write schema_version=1 JSON export.")
56 print("")
57 print("LLM: last-token hook_resid_post cosine distance per layer.")
58 print("Embedding: mean-pooled hidden-state cosine distance per encoder layer.")
59 print("")
60 print("Example:")
61 print(" aquin diff residue --checkpoint ~/runs/checkpoint.pt \\")
62 print(" --prompts probes.json --save drift.json")
63 print("")
64 print("Docs: https://aquin.app/docs/checkpoint-sae")
65
66
67def cmd_residual_drift(args: list[str]) -> None:
68 if _has_flag(args, "--help") or _has_flag(args, "-h"):
70 return
72 reject_legacy_output_flags(args)
73
74 checkpoint = _parse_flag(args, "--checkpoint")
75 if not checkpoint:
76 print("Error: --checkpoint is required.")
77 print("")
79 sys.exit(1)
80
81 ckpt = Path(checkpoint).expanduser()
82 if not ckpt.exists():
83 print(f"Error: checkpoint not found: {checkpoint}")
84 sys.exit(1)
85
86 if _parse_flag(args, "--model") is not None:
87 print("Error: diff residue uses the loaded session model only.")
88 sys.exit(1)
89
90 prompts_arg = _parse_flag(args, "--prompts")
91 if prompts_arg:
92 from aquin.compute.activation_capture import resolve_prompts_path
93
94 resolved = resolve_prompts_path(Path(prompts_arg).expanduser())
95 if resolved is None:
96 print(f"Error: probe file not found: {prompts_arg}")
97 print(" Pass a probe file that exists on disk.")
98 sys.exit(1)
99 prompts_arg = str(resolved)
100
102
103 from aquin.cli import _build_tool_ctx
104 from aquin.engine.sync_dispatch import dispatch_with_sync, require_active_session
105
106 mid = _resolve_model_id()
107 ctx = _build_tool_ctx(model_id=mid)
108 require_active_session(ctx, label="aquin diff residue")
109
110 tool_args: dict[str, Any] = {
111 "model_id": mid,
112 "checkpoint": str(ckpt),
113 "name": _parse_flag(args, "--name") or ckpt.stem,
114 "save": _parse_flag(args, "--save"),
115 }
116 if prompts_arg:
117 tool_args["prompts"] = prompts_arg
118 try:
119 print(f"[diff residue] model={mid} checkpoint={ckpt.name}")
120 result = dispatch_with_sync("run_residual_drift", 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("diff residue", result)
128
129 if isinstance(result, dict) and result.get("error"):
130 sys.exit(1)
bool _has_flag(list[str] args, str name)
str|None _parse_flag(list[str] args, str name)
None cmd_residual_drift(list[str] args)