AQIT 0.1.0
Loading...
Searching...
No Matches
stubs.py
Go to the documentation of this file.
1# Copyright (c) 2025-present Aquin Labs Private Limited. All Rights Reserved.
2# This file is part of the Aquin Engine. Unauthorized copying, modification,
3# distribution, or use of this file, via any medium, is strictly prohibited.
4# Proprietary and confidential. See LICENSE for terms.
5
6"""
7Step 35: every tool in tools.ts wired to bridge.call via execute_tool.
8
9Tools already wired with full handlers (not re-registered here):
10 inspect.py — run_full_inspection, get_feature_logits,
11 get_feature_neighbors
12 session_memory.py — write_session_memory, read_session_memory
13"""
14from __future__ import annotations
15from typing import Any
16from .registry import register
17from .executor import execute_tool
18
19
20def _wire(name: str, schema: dict[str, Any]) -> None:
21 @register(name, schema)
22 def _handler(args: dict[str, Any], ctx: dict[str, Any]) -> Any:
23 return execute_tool(name, args, ctx)
24 _handler.__name__ = name
25
26
27# ── Inspection ──
28
29_wire("run_find_feature", {
30 "type": "function",
31 "function": {
32 "name": "run_find_feature",
33 "description": (
34 "Rank SAE features that separate honest vs deceptive probes. "
35 "Default behavior mode generates completions and buckets by observed output. "
36 "Returns top features by activation delta; optionally persists canonical feature id."
37 ),
38 "parameters": {
39 "type": "object",
40 "properties": {
41 "scorer": {"type": "string", "description": "Scorer name (default: deception)."},
42 "prompts": {"type": "string", "description": "Path to JSON/JSONL honest/deceptive probes."},
43 "layer": {"type": "number", "description": "SAE layer (default: model default)."},
44 "checkpoint": {"type": "string", "description": "Optional fine-tuned checkpoint .pt path."},
45 "top_k": {"type": "number", "description": "Number of ranked features to return (default 20)."},
46 "direction": {
47 "type": "string",
48 "description": "both (|delta|, default), deceptive (delta>0 only), honest (delta<0 only).",
49 },
50 "conditioning": {
51 "type": "string",
52 "description": "behavior (default): generate + classify output; prompt: static probe text only.",
53 },
54 "benchmark_top": {"type": "number", "description": "Re-rank top K with InterpScore (needs OpenAI)."},
55 "persist": {"type": "string", "description": "Session/experiment key for chosen feature id."},
56 },
57 "required": [],
58 },
59 },
60})
61
62_wire("run_benchmarks_on_top_feature", {
63 "type": "function",
64 "function": {
65 "name": "run_benchmarks_on_top_feature",
66 "description": (
67 "Feature benchmark: InterpScore, FeaturePurity, and MUI on one SAE feature. "
68 "Use the same SAE layer as the inspection that surfaced the feature."
69 ),
70 "parameters": {
71 "type": "object",
72 "properties": {
73 "feature_idx": {"type": "number"},
74 "layer": {
75 "type": "number",
76 "description": "SAE layer (defaults to lastSaeLayer from session memory).",
77 },
78 "prompt": {
79 "type": "string",
80 "description": "Probe prompt for labeling (defaults to last inspected prompt).",
81 },
82 },
83 "required": ["feature_idx"],
84 },
85 },
86})
87
88_wire("run_audit", {
89 "type": "function",
90 "function": {
91 "name": "run_audit",
92 "description": "Run a full audit: fact-check, bias detection, and censor audit in parallel.",
93 "parameters": {"type": "object", "properties": {}, "required": []},
94 },
95})
96
97_wire("run_consistency_eval", {
98 "type": "function",
99 "function": {
100 "name": "run_consistency_eval",
101 "description": "Measure output stability across paraphrases.",
102 "parameters": {
103 "type": "object",
104 "properties": {
105 "query": {"type": "string"},
106 "templates": {"type": "array", "items": {"type": "string"}},
107 },
108 "required": ["query", "templates"],
109 },
110 },
111})
112
113_wire("run_suppression_eval", {
114 "type": "function",
115 "function": {
116 "name": "run_suppression_eval",
117 "description": "Detect topics where the model's behavior differs from neutral baseline.",
118 "parameters": {
119 "type": "object",
120 "properties": {
121 "topics": {"type": "object", "additionalProperties": {"type": "array", "items": {"type": "string"}}},
122 },
123 "required": ["topics"],
124 },
125 },
126})
127
128_wire("run_boundary_eval", {
129 "type": "function",
130 "function": {
131 "name": "run_boundary_eval",
132 "description": "Map robustness to surface-level input corruptions.",
133 "parameters": {
134 "type": "object",
135 "properties": {
136 "prompts": {"type": "array", "items": {"type": "string"}},
137 },
138 "required": ["prompts"],
139 },
140 },
141})
142
143_wire("run_weight_diff", {
144 "type": "function",
145 "function": {
146 "name": "run_weight_diff",
147 "description": (
148 "Per-layer weight delta analysis: base vs fine-tuned checkpoint. "
149 "Q/K/V/O/MLP ΔW or LoRA effective B@A."
150 ),
151 "parameters": {
152 "type": "object",
153 "properties": {
154 "checkpoint": {"type": "string", "description": "Path to fine-tuned .pt or HF directory."},
155 "name": {"type": "string", "description": "Checkpoint label for the report."},
156 "save": {"type": "string", "description": "Optional JSON export path."},
157 "model_id": {"type": "string"},
158 },
159 "required": ["checkpoint"],
160 },
161 },
162})
163
164_wire("run_merge_analysis", {
165 "type": "function",
166 "function": {
167 "name": "run_merge_analysis",
168 "description": (
169 "Pre-merge LoRA gate: weight-diff + rank/collapse signals + optional behavioral model-diff (LLM). "
170 "Returns mergeVerdict pass|warn|fail."
171 ),
172 "parameters": {
173 "type": "object",
174 "properties": {
175 "checkpoint": {"type": "string", "description": "Path to adapter or merged .pt checkpoint."},
176 "name": {"type": "string", "description": "Checkpoint label for the report."},
177 "prompts": {"type": "string", "description": "Optional JSON/JSONL probes for behavioral diff."},
178 "no_behavioral": {"type": "boolean", "description": "Skip generation-based behavioral scores."},
179 "save": {"type": "string", "description": "Optional JSON export path."},
180 "model_id": {"type": "string"},
181 },
182 "required": ["checkpoint"],
183 },
184 },
185})
186
187_wire("run_trajectory_analysis", {
188 "type": "function",
189 "function": {
190 "name": "run_trajectory_analysis",
191 "description": (
192 "Training trajectory: weight-diff summary per checkpoint vs base, sorted by training step."
193 ),
194 "parameters": {
195 "type": "object",
196 "properties": {
197 "checkpoints": {"type": "string", "description": "Glob of .pt checkpoint paths."},
198 "dir": {"type": "string", "description": "Directory to scan recursively for *.pt."},
199 "name": {"type": "string", "description": "Optional label prefix per step."},
200 "save": {"type": "string", "description": "Optional JSON export path."},
201 "model_id": {"type": "string"},
202 },
203 },
204 },
205})
206
207_wire("run_residual_drift", {
208 "type": "function",
209 "function": {
210 "name": "run_residual_drift",
211 "description": (
212 "Per-layer activation drift: catalog base vs fine-tuned checkpoint on the same probes. "
213 "Last-token hook_resid_post cosine distance."
214 ),
215 "parameters": {
216 "type": "object",
217 "properties": {
218 "checkpoint": {"type": "string", "description": "Path to fine-tuned .pt or HF directory."},
219 "prompts": {"type": "string", "description": "Optional JSON/JSONL probe file."},
220 "name": {"type": "string", "description": "Checkpoint label for the report."},
221 "save": {"type": "string", "description": "Optional JSON export path."},
222 "model_id": {"type": "string"},
223 },
224 "required": ["checkpoint"],
225 },
226 },
227})
228
229_wire("run_confidence_analysis", {
230 "type": "function",
231 "function": {
232 "name": "run_confidence_analysis",
233 "description": (
234 "Per-probe confidence analysis over probes: token logits (mean confidence, entropy, ECE proxy). "
235 "Optional SAE join for confidence ↔ feature ↔ layer on the same prompts."
236 ),
237 "parameters": {
238 "type": "object",
239 "properties": {
240 "prompts": {"type": "string", "description": "Path to JSON/JSONL probe file."},
241 "threshold": {"type": "number", "description": "Low-confidence cutoff (default 0.40)."},
242 "join_sae": {"type": "boolean", "description": "Attach SAE mean L0 + top feature per probe."},
243 "layer": {"type": "number", "description": "SAE layer for join (default model sae_layer)."},
244 "save": {"type": "string", "description": "Optional JSON export path."},
245 "model_id": {"type": "string"},
246 },
247 "required": ["prompts"],
248 },
249 },
250})
251
252_wire("extract_steer_vector", {
253 "type": "function",
254 "function": {
255 "name": "extract_steer_vector",
256 "description": "Export an SAE decoder steering vector (LAT) to a JSON file for reuse across sessions and checkpoints.",
257 "parameters": {
258 "type": "object",
259 "properties": {
260 "feature_idx": {"type": "number", "description": "SAE feature index to export."},
261 "layer": {"type": "number", "description": "SAE layer (default: model default)."},
262 "save": {"type": "string", "description": "Output JSON path."},
263 "feature_label": {"type": "string", "description": "Optional human-readable label stored in the file."},
264 "probe_id": {"type": "string", "description": "Optional experiment key from feature locate --persist (default: deception_feature)."},
265 },
266 "required": ["feature_idx", "save"],
267 },
268 },
269})
270
271_wire("run_steer_and_show", {
272 "type": "function",
273 "function": {
274 "name": "run_steer_and_show",
275 "description": "Run feature steering AND open the steer panel with the result injected. Use feature_idx or a saved LAT vector file. Pass eval=true to score baseline vs steered on a probe suite (default: deception probes).",
276 "parameters": {
277 "type": "object",
278 "properties": {
279 "prompt": {"type": "string", "description": "Optional single-prompt demo. Omit with eval=true to run the probe suite only."},
280 "feature_idx": {"type": "number", "description": "SAE feature index (omit when using vector)."},
281 "vector": {"type": "string", "description": "Path to a saved LAT JSON from steer --save."},
282 "feature_label": {"type": "string", "description": "Optional — auto-resolved from causal labeling if omitted"},
283 "strength": {"type": "number"},
284 "layer": {"type": "number"},
285 "max_new_tokens": {"type": "number"},
286 "eval": {"type": "boolean", "description": "If true, score the same probe set under baseline vs steered and report pass rates."},
287 "prompts": {"type": "string", "description": "Probe file (json/jsonl) or JSON array."},
288 "reference_answers": {"type": "string", "description": "For custom eval mode: JSON array of references matching prompts (keyword-overlap pass)."},
289 "threshold": {"type": "number", "description": "Custom-mode pass threshold (default 0.5)."},
290 },
291 "required": [],
292 },
293 },
294})
295
296_wire("run_multi_steer", {
297 "type": "function",
298 "function": {
299 "name": "run_multi_steer",
300 "description": "Steer multiple SAE features simultaneously in a single forward pass.",
301 "parameters": {
302 "type": "object",
303 "properties": {
304 "prompt": {"type": "string"},
305 "features": {
306 "type": "array",
307 "items": {
308 "type": "object",
309 "properties": {
310 "feature_idx": {"type": "number"},
311 "strength": {"type": "number"},
312 "label": {"type": "string", "description": "Optional — auto-resolved if omitted"},
313 },
314 "required": ["feature_idx", "strength"],
315 },
316 },
317 "max_new_tokens": {"type": "number"},
318 },
319 "required": ["prompt", "features"],
320 },
321 },
322})
323
324_wire("ensure_umap_loaded", {
325 "type": "function",
326 "function": {
327 "name": "ensure_umap_loaded",
328 "description": "Load the UMAP projection and open the UMAP Explorer panel. CLI equivalent: add --umap to a feature command (e.g. aquin feature locate --umap).",
329 "parameters": {"type": "object", "properties": {}, "required": []},
330 },
331})
332
333_wire("run_layer_analysis", {
334 "type": "function",
335 "function": {
336 "name": "run_layer_analysis",
337 "description": (
338 "Run activation stability and OOD similarity together. CLI: aquin check layer. "
339 "Pass localize=true to also rank layers where honest vs deceptive representations "
340 "peak and collapse (optional stressor_prompts / feature_idx / vector)."
341 ),
342 "parameters": {
343 "type": "object",
344 "properties": {
345 "prompts": {
346 "type": "string",
347 "description": "Stability prompts (JSON array) or, with localize, path to deception probe file.",
348 },
349 "top_k": {"type": "number"},
350 "in_domain_prompts": {"type": "array", "items": {"type": "string"}},
351 "ood_prompts": {"type": "array", "items": {"type": "string"}},
352 "localize": {
353 "type": "boolean",
354 "description": "If true, rank layers by honest vs deceptive representation strength and report collapse locus.",
355 },
356 "stressor_prompts": {
357 "type": "string",
358 "description": "Optional second deception probe file for stressor collapse deltas.",
359 },
360 "feature_idx": {
361 "type": "number",
362 "description": "Optional SAE feature to project at its layer.",
363 },
364 "vector": {
365 "type": "string",
366 "description": "Optional saved LAT vector path for direction projection.",
367 },
368 "layer": {"type": "number", "description": "Override SAE/vector layer."},
369 },
370 "required": [],
371 },
372 },
373})
374
375_wire("run_sae_stats", {
376 "type": "function",
377 "function": {
378 "name": "run_sae_stats",
379 "description": (
380 "Export multi-layer SAE statistics over a probe dataset. "
381 "Returns per-layer sparsity, top features, and probe×layer heatmap data."
382 ),
383 "parameters": {
384 "type": "object",
385 "properties": {
386 "prompts": {
387 "type": "string",
388 "description": "Path to JSON/JSONL probe file (text + optional stressor/lang/quant_run_id tags).",
389 },
390 "layers": {
391 "type": "string",
392 "description": "Comma-separated layer indices or 'all' (default: all layers with SAE checkpoints).",
393 },
394 "top_k": {"type": "number", "description": "Top features per layer (default 10)."},
395 "save": {"type": "string", "description": "Optional path to write full JSON export."},
396 "model_id": {"type": "string", "description": "Override active model."},
397 },
398 "required": ["prompts"],
399 },
400 },
401})
402
403_wire("run_perturbation_sensitivity", {
404 "type": "function",
405 "function": {
406 "name": "run_perturbation_sensitivity",
407 "description": "Zero out hidden channels and measure KL divergence vs clean output. CLI: aquin check perturbation.",
408 "parameters": {
409 "type": "object",
410 "properties": {
411 "prompt": {"type": "string"},
412 "n_channels": {"type": "number"},
413 "method": {"type": "string", "enum": ["dropout", "gaussian"]},
414 },
415 "required": ["prompt"],
416 },
417 },
418})
419
420_wire("run_attention_routing", {
421 "type": "function",
422 "function": {
423 "name": "run_attention_routing",
424 "description": "Extract per-head attention patterns and score each head. CLI: aquin check attention.",
425 "parameters": {
426 "type": "object",
427 "properties": {
428 "prompt": {"type": "string"},
429 "top_k": {"type": "number"},
430 },
431 "required": ["prompt"],
432 },
433 },
434})
435
436# ── Training: dataset ──
437
438_wire("dataset_generate", {
439 "type": "function",
440 "function": {
441 "name": "dataset_generate",
442 "description": "Generate instruction/response pairs for a topic and write a .jsonl file in the working directory.",
443 "parameters": {
444 "type": "object",
445 "properties": {
446 "topic": {"type": "string"},
447 "count": {"type": "number"},
448 "save": {"type": "string", "description": "Filename in cwd (default: <topic>_dataset.jsonl)"},
449 },
450 "required": ["topic"],
451 },
452 },
453})
454
455# ── Training: algo run ──
456
457_LORA_PARAMS = {
458 "rank": {"type": "number"},
459 "alpha": {"type": "number"},
460 "lr": {"type": "number"},
461 "epochs": {"type": "number"},
462 "dropout": {"type": "number"},
463 "targetModules": {"type": "array", "items": {"type": "string"}},
464 "warmupSteps": {"type": "number"},
465 "gradClip": {"type": "number"},
466 "weightDecay": {"type": "number"},
467 "gradAccumSteps": {"type": "number"},
468 "optimizer": {"type": "string", "enum": ["adamw", "sgd", "lion"]},
469 "scheduler": {"type": "string", "enum": ["cosine", "linear", "constant"]},
470 "maxSeqLen": {"type": "number"},
471 "useQlora": {"type": "boolean"},
472 "rows": {"type": "array", "items": {"type": "object"}},
473}
474
475_wire("run_simulation", {
476 "type": "function",
477 "function": {
478 "name": "run_simulation",
479 "description": "Simulate the user's existing training setup. Pass paths to their dataset and pipeline (script or config) — no Aquin-specific formats.",
480 "parameters": {
481 "type": "object",
482 "properties": {
483 "topic": {"type": "string", "description": "Quick probe when no dataset path yet."},
484 "dataset": {"type": "string", "description": "Path to the user's dataset file."},
485 "algo": {"type": "string", "description": "Path to the user's training script or config."},
486 "count": {"type": "number"},
487 **{k: v for k, v in _LORA_PARAMS.items() if k != "rows"},
488 "use_rlhf": {"type": "boolean"},
489 "rlhf_beta": {"type": "number"},
490 },
491 "required": [],
492 },
493 },
494})
495
496_wire("list_simulation_runs", {
497 "type": "function",
498 "function": {
499 "name": "list_simulation_runs",
500 "description": "List the user's saved simulation runs.",
501 "parameters": {"type": "object", "properties": {}, "required": []},
502 },
503})
504
505_wire("load_simulation_run", {
506 "type": "function",
507 "function": {
508 "name": "load_simulation_run",
509 "description": "Load a saved simulation run by ID. CLI: aquin replay simulation --run_id <id>.",
510 "parameters": {
511 "type": "object",
512 "properties": {
513 "run_id": {"type": "string"},
514 },
515 "required": ["run_id"],
516 },
517 },
518})
519
520_wire("compare_simulations", {
521 "type": "function",
522 "function": {
523 "name": "compare_simulations",
524 "description": "Compare two saved simulation runs side-by-side, including attack-surface metrics (consistency, suppression, robustness) from model diff.",
525 "parameters": {
526 "type": "object",
527 "properties": {
528 "run_id_a": {"type": "string", "description": "First simulation run ID (before)."},
529 "run_id_b": {"type": "string", "description": "Second simulation run ID (after)."},
530 "run_id_before": {"type": "string", "description": "Alias for run_id_a."},
531 "run_id_after": {"type": "string", "description": "Alias for run_id_b."},
532 "label_a": {"type": "string"},
533 "label_b": {"type": "string"},
534 },
535 "required": ["run_id_a", "run_id_b"],
536 },
537 },
538})
539
540# ── Interactive cards ──
541
542_wire("run_red_team", {
543 "type": "function",
544 "function": {
545 "name": "run_red_team",
546 "description": "Full adversarial red-team suite (all six vectors). Always runs every vector — do not ask the user to pick vectors. call with {}.",
547 "parameters": {
548 "type": "object",
549 "properties": {}, "required": [],
550 },
551 },
552})
553
554_wire("check_weights", {
555 "type": "function",
556 "function": {
557 "name": "check_weights",
558 "description": "Run a combined weight health check: trojan/backdoor signatures and SVD rank analysis. CLI: aquin check weight.",
559 "parameters": {
560 "type": "object",
561 "properties": {
562 "collapse_threshold": {"type": "number"},
563 },
564 "required": [],
565 },
566 },
567})
568
569_wire("run_custom_eval", {
570 "type": "function",
571 "function": {
572 "name": "run_custom_eval",
573 "description": "Run prompts through the model and score each response against a reference answer (keyword overlap). Prefer built-in eval tools over inventing a code runner.",
574 "parameters": {
575 "type": "object",
576 "properties": {
577 "name": {"type": "string"},
578 "description": {"type": "string"},
579 "prompts": {"type": "array", "items": {"type": "string"}},
580 "reference_answers": {"type": "array", "items": {"type": "string"}},
581 "threshold": {"type": "number"},
582 "max_tokens": {"type": "number"},
583 "temperature": {"type": "number"},
584 },
585 "required": ["name", "prompts", "reference_answers"],
586 },
587 },
588})
589
590
591# ── Code execution removed (never shipped) ──
None _wire(str name, dict[str, Any] schema)
Definition stubs.py:24