evalradar 0.2.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- evalradar/LICENSE +76 -0
- evalradar/__init__.py +9 -0
- evalradar/_compat.py +31 -0
- evalradar/capture/__init__.py +1 -0
- evalradar/capture/hf.py +553 -0
- evalradar/capture/vllm_backend.py +399 -0
- evalradar/cli.py +587 -0
- evalradar/compile.py +139 -0
- evalradar/contracts.py +232 -0
- evalradar/core.py +277 -0
- evalradar/detectors.py +108 -0
- evalradar/doctor.py +81 -0
- evalradar/lens.py +115 -0
- evalradar/localview.py +58 -0
- evalradar/monitoring.py +71 -0
- evalradar/onboarding.py +74 -0
- evalradar/proxy.py +366 -0
- evalradar/sdk.py +1045 -0
- evalradar/selfhosted.py +576 -0
- evalradar/signing.py +172 -0
- evalradar/starter_prompts.py +46 -0
- evalradar/telemetry.py +225 -0
- evalradar/verifiers.py +518 -0
- evalradar-0.2.1.dist-info/METADATA +116 -0
- evalradar-0.2.1.dist-info/RECORD +29 -0
- evalradar-0.2.1.dist-info/WHEEL +5 -0
- evalradar-0.2.1.dist-info/entry_points.txt +2 -0
- evalradar-0.2.1.dist-info/licenses/src/evalradar/LICENSE +76 -0
- evalradar-0.2.1.dist-info/top_level.txt +1 -0
evalradar/cli.py
ADDED
|
@@ -0,0 +1,587 @@
|
|
|
1
|
+
"""EvalRadar CLI: init wizard, proxy, self-hosted collect / onboard / agent, doctor and feedback. Fitting monitors runs on
|
|
2
|
+
your EvalRadar console (`onboard --upload-features`); the console server and the research commands come with the
|
|
3
|
+
separately licensed server package."""
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
import argparse
|
|
6
|
+
import getpass
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
import sys
|
|
11
|
+
import threading
|
|
12
|
+
from ._compat import config_dir
|
|
13
|
+
from .core import Fingerprint, Event, Example, score, load_artifact
|
|
14
|
+
from .doctor import doctor
|
|
15
|
+
from . import starter_prompts
|
|
16
|
+
from .proxy import DEFAULT_UPSTREAM_TIMEOUT, MonitoringProxy, make_proxy_server
|
|
17
|
+
from .sdk import MonitorClient, openai_compatible_judge
|
|
18
|
+
|
|
19
|
+
DEFAULT_CONFIG_DIR = config_dir() # ~/.evalradar, or ~/.evalwatch from before the rename
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _config_paths(config_dir: str | Path | None = None) -> tuple[Path, Path, Path]:
|
|
23
|
+
base = Path(config_dir).expanduser() if config_dir else DEFAULT_CONFIG_DIR
|
|
24
|
+
return base, base / "config.json", base / "token"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _load_saved_config(config_dir: str | Path | None = None) -> dict:
|
|
28
|
+
_, cfg_path, _ = _config_paths(config_dir)
|
|
29
|
+
if cfg_path.is_file():
|
|
30
|
+
try:
|
|
31
|
+
data = json.loads(cfg_path.read_text(encoding="utf-8"))
|
|
32
|
+
if isinstance(data, dict):
|
|
33
|
+
return data
|
|
34
|
+
except Exception:
|
|
35
|
+
pass
|
|
36
|
+
return {}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _write_private_file(path: Path, text: str):
|
|
40
|
+
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
41
|
+
try:
|
|
42
|
+
os.chmod(path.parent, 0o700)
|
|
43
|
+
except OSError:
|
|
44
|
+
pass
|
|
45
|
+
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
46
|
+
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
47
|
+
f.write(text)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _run_init(args) -> int:
|
|
51
|
+
cfg_dir, cfg_path, tok_path = _config_paths(args.config_dir)
|
|
52
|
+
prev = _load_saved_config(cfg_dir)
|
|
53
|
+
interactive = not args.non_interactive and sys.stdin.isatty()
|
|
54
|
+
|
|
55
|
+
def ask(label: str, current: str | None, default: str = "", *, secret: bool = False) -> str:
|
|
56
|
+
if current is not None:
|
|
57
|
+
return current.strip()
|
|
58
|
+
if not interactive:
|
|
59
|
+
return default
|
|
60
|
+
hint = f" [{default}]" if default and not secret else ""
|
|
61
|
+
prompt = f"{label}{hint}: "
|
|
62
|
+
val = getpass.getpass(prompt) if secret else input(prompt)
|
|
63
|
+
return val.strip() or default
|
|
64
|
+
|
|
65
|
+
console = ask("Console URL (e.g. https://console.evalvitals.com)", args.console, prev.get("console_url", ""))
|
|
66
|
+
token_val = args.token
|
|
67
|
+
token_file = args.token_file or prev.get("token_file", "")
|
|
68
|
+
if token_val is None and not token_file and console:
|
|
69
|
+
token_val = ask("Agent token (ewa_..., leave blank to skip)", None, "", secret=True)
|
|
70
|
+
if token_val:
|
|
71
|
+
_write_private_file(tok_path, token_val.strip() + "\n")
|
|
72
|
+
token_file = str(tok_path)
|
|
73
|
+
|
|
74
|
+
upstream = ask("Upstream OpenAI-compatible URL (for `evalradar proxy`)", args.upstream, prev.get("upstream", "http://127.0.0.1:8000"))
|
|
75
|
+
model_id = ask("Model ID to report (e.g. org/my-model)", args.model_id, prev.get("model_id", "custom/model"))
|
|
76
|
+
port = args.port if args.port is not None else int(prev.get("port", 8080))
|
|
77
|
+
|
|
78
|
+
cfg = {
|
|
79
|
+
"console_url": console,
|
|
80
|
+
"token_file": token_file,
|
|
81
|
+
"upstream": upstream,
|
|
82
|
+
"model_id": model_id,
|
|
83
|
+
"adapter": args.adapter or prev.get("adapter", "none"),
|
|
84
|
+
"port": port,
|
|
85
|
+
"console_keys": prev.get("console_keys", {}) if prev.get("console_url") == console else {},
|
|
86
|
+
"upstream_timeout": args.upstream_timeout if args.upstream_timeout is not None else prev.get("upstream_timeout", DEFAULT_UPSTREAM_TIMEOUT),
|
|
87
|
+
"send_text": False if args.no_text else prev.get("send_text", True),
|
|
88
|
+
}
|
|
89
|
+
_write_private_file(cfg_path, json.dumps(cfg, indent=2) + "\n")
|
|
90
|
+
|
|
91
|
+
summary: dict = {"ok": True, "config_path": str(cfg_path), "token_file": token_file or None, "console_connected": False, "synced_targets": 0}
|
|
92
|
+
if console and token_file and Path(token_file).expanduser().is_file():
|
|
93
|
+
try:
|
|
94
|
+
mc = MonitorClient(console, token_file=token_file, model_id=model_id, adapter=cfg["adapter"], auto_sync=False)
|
|
95
|
+
targets = mc.sync_targets()
|
|
96
|
+
summary["console_connected"] = True
|
|
97
|
+
summary["synced_targets"] = len(targets)
|
|
98
|
+
keys = mc.transport.post("keys", {}).get("console_keys", {}) if mc.transport else {}
|
|
99
|
+
if keys: # monitors this console fits are signed with these keys; the agent checks them
|
|
100
|
+
cfg["console_keys"] = {**cfg["console_keys"], **{str(k): str(v) for k, v in keys.items()}}
|
|
101
|
+
_write_private_file(cfg_path, json.dumps(cfg, indent=2) + "\n")
|
|
102
|
+
summary["console_keys"] = sorted(keys)
|
|
103
|
+
except Exception as exc:
|
|
104
|
+
summary["console_error"] = str(exc)
|
|
105
|
+
summary["ok"] = False
|
|
106
|
+
if summary.get("console_connected") and not summary["synced_targets"]:
|
|
107
|
+
summary["note"] = ("No monitor is active in the console yet: requests will be forwarded and reported as unchecked. "
|
|
108
|
+
"Add one under Monitors in the console (a template takes one click).")
|
|
109
|
+
summary["next"] = [
|
|
110
|
+
"evalradar proxy # start zero-code monitoring proxy using saved config",
|
|
111
|
+
"evalradar doctor # check local GPU/architecture support for activation hooks",
|
|
112
|
+
]
|
|
113
|
+
print(json.dumps(summary, indent=2))
|
|
114
|
+
if not summary["ok"]:
|
|
115
|
+
print("The settings were saved, but the console did not accept the connection: " + summary["console_error"] +
|
|
116
|
+
"\nCheck the console URL and the token, then run evalradar init again.", file=sys.stderr)
|
|
117
|
+
return 2
|
|
118
|
+
return 0
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _events(path):
|
|
122
|
+
with Path(path).open() as f:
|
|
123
|
+
for line in f:
|
|
124
|
+
if line.strip():
|
|
125
|
+
d = json.loads(line)
|
|
126
|
+
e = Event(d["event_id"], Fingerprint(**d["fingerprint"]), d.get("text"), d.get("features", {}), d.get("step", 0))
|
|
127
|
+
yield d, e
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _examples(path):
|
|
131
|
+
return [Example(e, d["label"], d["group"]) for d, e in _events(path)]
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _run_selfhosted(args) -> int:
|
|
135
|
+
"""`evalradar collect` and `evalradar agent` (needs the [hf] extra: torch, transformers, safetensors)."""
|
|
136
|
+
try:
|
|
137
|
+
from . import selfhosted as sh
|
|
138
|
+
except ImportError as exc:
|
|
139
|
+
raise SystemExit(f"error: {exc}. Install the model extras: pip install 'evalradar[hf]'") from None
|
|
140
|
+
log = lambda m: print(m, file=sys.stderr, flush=True)
|
|
141
|
+
if args.command == "collect":
|
|
142
|
+
labeler = sh.make_labeler(forbid=args.forbid, require=args.require, case_sensitive=args.case_sensitive, expected=args.expected,
|
|
143
|
+
target=json.loads(Path(args.target_file).read_text()) if args.target_file else None)
|
|
144
|
+
rows = sh.read_jsonl(args.prompts)
|
|
145
|
+
rows = rows[:args.limit] if args.limit > 0 else rows
|
|
146
|
+
log(f"loading {args.model} …")
|
|
147
|
+
adapter = sh.load_model(args.model, model_id=args.model_id, device=args.device, dtype=args.dtype, adapter_dir=args.adapter_dir)
|
|
148
|
+
runner = sh.Runner(adapter, args.layer, max_new_tokens=args.max_new_tokens, system_prompt=args.system_prompt)
|
|
149
|
+
res = sh.collect(runner, rows, args.out, labeler=labeler, keep_text=args.keep_text, progress=log)
|
|
150
|
+
res["next"] = (f"evalradar onboard --events {args.out} --behavior custom:<name> --feature {res['feature']} --out monitor-out "
|
|
151
|
+
"--upload-features")
|
|
152
|
+
print(json.dumps(res, indent=2))
|
|
153
|
+
if not res["events"]:
|
|
154
|
+
return 2
|
|
155
|
+
if res["failures"] in (0, res["events"]):
|
|
156
|
+
log("warning: every reply has the same label; a monitor needs both failures and passes. Use more or different prompts.")
|
|
157
|
+
return 0
|
|
158
|
+
# agent
|
|
159
|
+
from .signing import SignatureError, load_signed, trusted_keys
|
|
160
|
+
saved = _load_saved_config(args.config_dir)
|
|
161
|
+
try:
|
|
162
|
+
artifact, signature = load_signed(args.monitor, trusted_keys(saved))
|
|
163
|
+
except SignatureError as exc:
|
|
164
|
+
raise SystemExit(f"error: {args.monitor}: {exc}. Not starting.") from None
|
|
165
|
+
if signature["signed"]:
|
|
166
|
+
log(f"monitor signed by {signature.get('issuer') or signature['origin']} (key {signature['key_id']}, {signature['origin']})")
|
|
167
|
+
else:
|
|
168
|
+
log("note: this monitor is not signed (fitted locally); the console shows it as unsigned")
|
|
169
|
+
feats = [m.feature for m in artifact.monitors if hasattr(m, "feature")]
|
|
170
|
+
if not feats:
|
|
171
|
+
raise SystemExit("error: this monitor has no activation probe; the agent runs activation monitors from `evalradar onboard`")
|
|
172
|
+
if not artifact.approved:
|
|
173
|
+
log("warning: this monitor did not pass validation; every decision will be abstain (artifact_not_approved)")
|
|
174
|
+
console_url = args.console or saved.get("console_url") or None
|
|
175
|
+
token_file = args.token_file or saved.get("token_file") or None
|
|
176
|
+
token = Path(token_file).expanduser().read_text().strip() if token_file and console_url else None
|
|
177
|
+
if not args.serve and not (console_url and token):
|
|
178
|
+
raise SystemExit("error: without --serve the agent only answers console requests; pass --console/--token-file or run `evalradar init`")
|
|
179
|
+
log(f"loading {args.model} …")
|
|
180
|
+
adapter = sh.load_model(args.model, model_id=args.model_id, device=args.device, dtype=args.dtype, adapter_dir=args.adapter_dir)
|
|
181
|
+
lens = None
|
|
182
|
+
if not args.no_lens:
|
|
183
|
+
from .lens import LogitLens, default_layers
|
|
184
|
+
layers = [int(x) for x in args.lens_layers.split(",")] if args.lens_layers else default_layers(len(adapter.layers), sh.layer_of(feats[0]))
|
|
185
|
+
lens = LogitLens(adapter, layers)
|
|
186
|
+
log(f"logit lens on layers {lens.layers}: for every request the top {lens.top_k} words per layer at the end of the prompt are sent "
|
|
187
|
+
"to the console as an explanation (number-, e-mail- and key-like words and matches of your leak rules are hidden there "
|
|
188
|
+
"until someone confirms). Turn off with --no-lens.")
|
|
189
|
+
runner = sh.Runner(adapter, sh.layer_of(feats[0]), max_new_tokens=args.max_new_tokens, system_prompt=args.system_prompt, lens=lens)
|
|
190
|
+
agent = sh.Agent(runner, artifact, console_url=console_url, token=token, prompts=sh.read_jsonl(args.prompts) if args.prompts else (),
|
|
191
|
+
batch_size=args.batch_size, log=log, signature=signature, send_text=not args.no_text and saved.get("send_text", True) is not False)
|
|
192
|
+
if agent.mismatch and set(agent.mismatch) <= sh.EQUIVALENT_IF_CHECKED and signature.get("origin") == "library":
|
|
193
|
+
log("the runtime (torch / transformers / GPU) differs from where this ready-made monitor was fitted; checking it on its reference prompts …")
|
|
194
|
+
check = agent.check_equivalence()
|
|
195
|
+
if check and check["passed"]:
|
|
196
|
+
log(f"reference check passed: {check['prompts']} prompts, scores within {check['max_abs_diff']:.4f}, "
|
|
197
|
+
f"{100 * check['decision_agreement']:.0f}% same decisions; the monitor is used here")
|
|
198
|
+
elif check:
|
|
199
|
+
log(f"reference check failed: {check['reason']}")
|
|
200
|
+
if agent.mismatch:
|
|
201
|
+
log("warning: this model does not match the fingerprint the monitor was validated on (" + ", ".join(agent.mismatch) +
|
|
202
|
+
"). Every decision will be abstain. Load the same weights, adapter, dtype and generation settings used with `collect`.")
|
|
203
|
+
if agent.transport:
|
|
204
|
+
try:
|
|
205
|
+
agent.hello()
|
|
206
|
+
except RuntimeError as exc:
|
|
207
|
+
if "HTTP 401" in str(exc):
|
|
208
|
+
log("error: the console does not know this token: it was revoked, or copied incompletely")
|
|
209
|
+
return sh.BAD_TOKEN
|
|
210
|
+
raise
|
|
211
|
+
log(f"connected to {console_url} as the agent for {agent.deployment['model_id']}")
|
|
212
|
+
srv = None
|
|
213
|
+
if args.metrics_port is not None:
|
|
214
|
+
agent.client.serve_metrics(args.metrics_port, args.host)
|
|
215
|
+
log(f"Prometheus metrics at http://{args.host}:{args.metrics_port}/metrics")
|
|
216
|
+
if args.serve:
|
|
217
|
+
srv = sh.make_agent_server(agent, host=args.host, port=args.port)
|
|
218
|
+
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
|
219
|
+
log(f"serving {agent.deployment['model_id']} with monitor {agent.monitor['monitor_id']} at http://{args.host}:{srv.server_port}/v1")
|
|
220
|
+
try:
|
|
221
|
+
if agent.transport:
|
|
222
|
+
agent.loop(poll=args.poll, every=args.every)
|
|
223
|
+
else:
|
|
224
|
+
threading.Event().wait()
|
|
225
|
+
except KeyboardInterrupt:
|
|
226
|
+
pass
|
|
227
|
+
finally:
|
|
228
|
+
if srv:
|
|
229
|
+
srv.shutdown()
|
|
230
|
+
agent.stop()
|
|
231
|
+
return 0
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _server(name: str, what: str):
|
|
235
|
+
"""A function from the server package (`evalradar_server`), with a plain message where it is not installed."""
|
|
236
|
+
mod, _, attr = name.rpartition(".")
|
|
237
|
+
try:
|
|
238
|
+
import importlib
|
|
239
|
+
return getattr(importlib.import_module("evalradar_server" + ("." + mod if mod else ".__main__")), attr)
|
|
240
|
+
except ModuleNotFoundError as exc:
|
|
241
|
+
if not (exc.name or "").startswith("evalradar_server"):
|
|
242
|
+
raise
|
|
243
|
+
raise SystemExit(f"{what} is part of the EvalRadar server, which this package does not include. Use your EvalRadar "
|
|
244
|
+
"console, or install the server package where your licence allows it.") from None
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _run_monitors(args) -> int:
|
|
248
|
+
"""List the console's ready-made monitors for a model, or download one (verified against the EvalVitals library key)."""
|
|
249
|
+
from .sdk import ConsoleTransport
|
|
250
|
+
from .signing import SignatureError, check_monitor
|
|
251
|
+
saved = _load_saved_config(args.config_dir)
|
|
252
|
+
console_url = args.console or saved.get("console_url")
|
|
253
|
+
token_file = args.token_file or saved.get("token_file")
|
|
254
|
+
if not console_url or not token_file:
|
|
255
|
+
raise SystemExit("Pass --console and --token-file, or run `evalradar init` first.")
|
|
256
|
+
transport = ConsoleTransport(console_url, Path(token_file).expanduser().read_text(encoding="utf-8").strip(), timeout=60)
|
|
257
|
+
ident = None
|
|
258
|
+
if args.model:
|
|
259
|
+
from .selfhosted import checkpoint_identity
|
|
260
|
+
print("hashing the weight files to identify the checkpoint …", file=sys.stderr, flush=True)
|
|
261
|
+
ident = checkpoint_identity(args.model, args.model_id)
|
|
262
|
+
query = ident or ({"model": args.model_id} if args.model_id else {})
|
|
263
|
+
if not args.get:
|
|
264
|
+
found = transport.post("library", query).get("monitors", [])
|
|
265
|
+
print(json.dumps({"query": query, "monitors": found}, indent=2))
|
|
266
|
+
if not found:
|
|
267
|
+
print("No ready-made monitor for this model yet. Use text checks, or fit one: evalradar collect, then "
|
|
268
|
+
"evalradar onboard --upload-features.", file=sys.stderr)
|
|
269
|
+
return 0
|
|
270
|
+
text = transport.post("library", {"get": args.get})["monitor"]
|
|
271
|
+
doc = json.loads(text)
|
|
272
|
+
try:
|
|
273
|
+
info = check_monitor(doc, {})
|
|
274
|
+
except SignatureError as exc:
|
|
275
|
+
raise SystemExit(f"error: the downloaded monitor failed verification ({exc}); not saved") from None
|
|
276
|
+
if info.get("origin") != "library":
|
|
277
|
+
raise SystemExit("error: the downloaded monitor is not signed as a ready-made EvalVitals monitor; not saved")
|
|
278
|
+
out = Path(args.out)
|
|
279
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
280
|
+
(out / "monitor.json").write_text(text)
|
|
281
|
+
fp, agent = doc["fingerprint"], info["library"]["agent"]
|
|
282
|
+
if ident and (ident["model"], ident["checkpoint"]) != (fp["model"], fp["checkpoint"]):
|
|
283
|
+
print(f"warning: this monitor is for {fp['model']} ({fp['checkpoint'][:60]}…), not the weights in {args.model}; "
|
|
284
|
+
"the agent would abstain on every request", file=sys.stderr)
|
|
285
|
+
cmd = (f"evalradar agent --model {args.model or '<model folder>'} --monitor {out / 'monitor.json'} --serve --port 8000"
|
|
286
|
+
f" --max-new-tokens {agent['max_new_tokens']}" + (f" --dtype {agent['dtype']}" if agent.get("dtype") else "")
|
|
287
|
+
+ (f" --system-prompt '{agent['system_prompt']}'" if agent.get("system_prompt") else ""))
|
|
288
|
+
print(json.dumps({"saved": str(out / "monitor.json"), "title": info["library"].get("title"), "behavior": doc["behavior"],
|
|
289
|
+
"signed_by": "EvalVitals library key " + info["key_id"], "run": cmd}, indent=2))
|
|
290
|
+
return 0
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _onboard_local(onboard_from_jsonl, args, console_url, token_file) -> dict:
|
|
294
|
+
"""Fitting on this machine (the server package, under a licence that includes local fitting)."""
|
|
295
|
+
return onboard_from_jsonl(
|
|
296
|
+
args.events, behavior=args.behavior, feature=args.feature, out_dir=args.out,
|
|
297
|
+
patterns=args.pattern, alpha=args.alpha, min_recall=args.min_recall, min_coverage=args.min_coverage,
|
|
298
|
+
rerun_labels_path=args.rerun, console_url=console_url if token_file else None,
|
|
299
|
+
token_file=token_file if console_url else None,
|
|
300
|
+
)
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _onboard_upload(args, console_url, token_file) -> int:
|
|
304
|
+
from .onboarding import WHAT_IS_SENT, upload_for_fitting
|
|
305
|
+
if args.pattern:
|
|
306
|
+
raise SystemExit("--pattern needs the reply text, which is never uploaded; leave it out (text checks belong in Monitors).")
|
|
307
|
+
if not console_url or not token_file:
|
|
308
|
+
raise SystemExit("Pass --console and --token-file, or run `evalradar init` first.")
|
|
309
|
+
print(WHAT_IS_SENT.format(feature=args.feature), file=sys.stderr, flush=True)
|
|
310
|
+
token = Path(token_file).expanduser().read_text(encoding="utf-8").strip()
|
|
311
|
+
res = upload_for_fitting(args.events, behavior=args.behavior, feature=args.feature, out_dir=args.out, console_url=console_url,
|
|
312
|
+
token=token, alpha=args.alpha, min_recall=args.min_recall, min_coverage=args.min_coverage,
|
|
313
|
+
rerun_labels_path=args.rerun)
|
|
314
|
+
print(json.dumps(res, indent=2))
|
|
315
|
+
return 0 if res.get("approved") else 2
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def main(argv=None):
|
|
319
|
+
argv = list(sys.argv[1:] if argv is None else argv)
|
|
320
|
+
# The console server keeps its own command line (python -m evalradar_server); these two names reach it.
|
|
321
|
+
if argv[:1] in (["serve"], ["server"]):
|
|
322
|
+
server_main = _server("main", "The console server")
|
|
323
|
+
return server_main(["serve", *argv[1:]] if argv[0] == "serve" else argv[1:])
|
|
324
|
+
parser = argparse.ArgumentParser(prog="evalradar", epilog="Console server: `evalradar serve [--data-dir DIR] [--port N]` and "
|
|
325
|
+
"`evalradar server init|add-user|reset-password ...` (see `evalradar server --help`).")
|
|
326
|
+
subs = parser.add_subparsers(dest="command", required=True)
|
|
327
|
+
|
|
328
|
+
ini = subs.add_parser("init", help="interactive setup wizard (writes ~/.evalradar/config.json with mode 600)")
|
|
329
|
+
ini.add_argument("--console", default=None, help="EvalRadar console URL")
|
|
330
|
+
ini.add_argument("--no-text", action="store_true", help="saved: keep prompt and reply text on this machine instead of sending it to the console")
|
|
331
|
+
ini.add_argument("--upstream-timeout", type=float, default=None, help="saved for `evalradar proxy`: seconds to wait for the model server (0 = no limit)")
|
|
332
|
+
ini.add_argument("--token", default=None, help="agent token (ewa_..., saved to ~/.evalradar/token mode 600)")
|
|
333
|
+
ini.add_argument("--token-file", default=None, help="existing token file path")
|
|
334
|
+
ini.add_argument("--upstream", default=None, help="default upstream URL for `evalradar proxy`")
|
|
335
|
+
ini.add_argument("--model-id", default=None, help="default model id reported to the console")
|
|
336
|
+
ini.add_argument("--adapter", default=None)
|
|
337
|
+
ini.add_argument("--port", type=int, default=None)
|
|
338
|
+
ini.add_argument("--config-dir", default=None, help="override ~/.evalradar directory")
|
|
339
|
+
ini.add_argument("--non-interactive", action="store_true", help="do not prompt; use flags and defaults only")
|
|
340
|
+
|
|
341
|
+
d = subs.add_parser("demo", help="run deterministic synthetic demonstration")
|
|
342
|
+
d.add_argument("--out", default="demo-output")
|
|
343
|
+
|
|
344
|
+
f = subs.add_parser("fit", help="train, calibrate and approve monitor on three disjoint datasets")
|
|
345
|
+
for key in ("train", "calibration", "heldout", "behavior", "feature", "out"):
|
|
346
|
+
f.add_argument("--" + key, required=True)
|
|
347
|
+
f.add_argument("--pattern", action="append", required=True)
|
|
348
|
+
f.add_argument("--alpha", type=float, default=.05)
|
|
349
|
+
f.add_argument("--min-recall", type=float, default=.3)
|
|
350
|
+
f.add_argument("--min-coverage", type=float, default=.95)
|
|
351
|
+
|
|
352
|
+
for cmd in ("score", "validate", "compare"):
|
|
353
|
+
s = subs.add_parser(cmd)
|
|
354
|
+
s.add_argument("--artifact", required=True)
|
|
355
|
+
s.add_argument("--events", required=True)
|
|
356
|
+
|
|
357
|
+
doc = subs.add_parser("doctor", help="check environment and whether a model checkpoint supports activation hooks")
|
|
358
|
+
doc.add_argument("--model", default=None, help="path to a Hugging Face model directory or config.json")
|
|
359
|
+
|
|
360
|
+
ob = subs.add_parser("onboard", help="fit an activation monitor from `evalradar collect` events: on your console with --upload-features")
|
|
361
|
+
ob.add_argument("--events", required=True, help="JSONL file of labeled events with features and group")
|
|
362
|
+
ob.add_argument("--behavior", required=True, help="behavior id (e.g. custom:no_pii_leak)")
|
|
363
|
+
ob.add_argument("--feature", required=True, help="activation feature key in events JSONL")
|
|
364
|
+
ob.add_argument("--out", required=True, help="output directory for monitor.json, onboarding_report.json and ledger_records.jsonl")
|
|
365
|
+
ob.add_argument("--upload-features", action="store_true", help="send activation vectors, labels and hashed ids (never text) to the console, "
|
|
366
|
+
"which fits and returns monitor.json")
|
|
367
|
+
ob.add_argument("--pattern", action="append", default=[], help="behavioral pattern fused with the probe (local fitting only: needs the reply text)")
|
|
368
|
+
ob.add_argument("--rerun", default=None, help="optional rerun labels JSONL to verify >=90%% label stability")
|
|
369
|
+
ob.add_argument("--alpha", type=float, default=0.05)
|
|
370
|
+
ob.add_argument("--min-recall", type=float, default=0.30)
|
|
371
|
+
ob.add_argument("--min-coverage", type=float, default=0.95)
|
|
372
|
+
ob.add_argument("--console", default=None, help="optional console URL (falls back to ~/.evalradar/config.json)")
|
|
373
|
+
ob.add_argument("--token-file", default=None, help="path to agent token file (falls back to ~/.evalradar/config.json)")
|
|
374
|
+
ob.add_argument("--config-dir", default=None)
|
|
375
|
+
|
|
376
|
+
px = subs.add_parser("proxy", help="run a transparent OpenAI-compatible monitoring proxy (uses saved `evalradar init` config by default)")
|
|
377
|
+
px.add_argument("--upstream", default=None, help="upstream OpenAI-compatible base URL (e.g. http://127.0.0.1:8000)")
|
|
378
|
+
px.add_argument("--host", default="127.0.0.1")
|
|
379
|
+
px.add_argument("--port", type=int, default=None)
|
|
380
|
+
px.add_argument("--console", default=None, help="EvalRadar console URL to sync targets and report hashed events")
|
|
381
|
+
px.add_argument("--token-file", default=None, help="path to agent token file (mode 600)")
|
|
382
|
+
px.add_argument("--targets", default=None, help="optional local JSON file of MonitorTarget definitions")
|
|
383
|
+
px.add_argument("--model-id", default=None, help="deployment model id reported to the console")
|
|
384
|
+
px.add_argument("--adapter", default=None)
|
|
385
|
+
px.add_argument("--shadow-log", default=None, help="optional local JSONL path to record shadow traces on this host")
|
|
386
|
+
px.add_argument("--judge-model", default=None, help="model that judges rubric targets (sampled, in the background); without it they stay unchecked")
|
|
387
|
+
px.add_argument("--judge-url", default=None, help="OpenAI-compatible endpoint of the judge (default: the proxy's upstream); key from EVALRADAR_JUDGE_API_KEY")
|
|
388
|
+
px.add_argument("--no-text", action="store_true", help="do not send prompt and reply text to the console (read them at /evalradar/requests on this machine)")
|
|
389
|
+
px.add_argument("--upstream-timeout", type=float, default=None, help=f"seconds to wait for the next byte from the model server "
|
|
390
|
+
f"(default {DEFAULT_UPSTREAM_TIMEOUT:.0f}; 0 = no limit). Thinking models without streaming may need more.")
|
|
391
|
+
px.add_argument("--config-dir", default=None)
|
|
392
|
+
|
|
393
|
+
co = subs.add_parser("collect", help="run a local model on your prompts, label the replies and write events for `evalradar onboard`")
|
|
394
|
+
co.add_argument("--model", required=True, help="local Hugging Face model folder (config.json, tokenizer, safetensors)")
|
|
395
|
+
co.add_argument("--prompts", required=True, help='JSONL: {"prompt": "..."} or {"messages": [...]}; optional "label" (0/1), "group", "expected", "id"')
|
|
396
|
+
co.add_argument("--layer", type=int, required=True, help="decoder layer whose residual stream is read at the last prompt token")
|
|
397
|
+
co.add_argument("--out", required=True, help="events JSONL to write")
|
|
398
|
+
co.add_argument("--forbid", action="append", default=[], help="label a reply as failed when it matches this regex (repeatable)")
|
|
399
|
+
co.add_argument("--require", action="append", default=[], help="label a reply as failed when it lacks this regex (repeatable)")
|
|
400
|
+
co.add_argument("--expected", action="store_true", help='label a reply as failed when it does not match its prompt\'s own "expected" regex (as written by `evalradar prompts`)')
|
|
401
|
+
co.add_argument("--target-file", default=None, help="JSON verifier or monitor target (the verifier labels the replies)")
|
|
402
|
+
co.add_argument("--case-sensitive", action="store_true")
|
|
403
|
+
co.add_argument("--keep-text", action="store_true", help="also store each reply (needed only for `onboard --pattern`)")
|
|
404
|
+
co.add_argument("--limit", type=int, default=0, help="use only the first N prompts")
|
|
405
|
+
for sp in (co,):
|
|
406
|
+
sp.add_argument("--max-new-tokens", type=int, default=128)
|
|
407
|
+
sp.add_argument("--system-prompt", default=None)
|
|
408
|
+
sp.add_argument("--device", default="auto", help="auto, cpu, cuda or cuda:N")
|
|
409
|
+
sp.add_argument("--dtype", default="auto", help="auto (bfloat16 on GPU, float32 on CPU), bfloat16, float16 or float32")
|
|
410
|
+
sp.add_argument("--adapter-dir", default=None, help="local PEFT LoRA adapter merged into the weights")
|
|
411
|
+
sp.add_argument("--model-id", default=None, help="name reported for the model (default: from the folder)")
|
|
412
|
+
|
|
413
|
+
pr = subs.add_parser("prompts", help="write a starter prompt set for `evalradar collect`, for trying an activation monitor without prompts of your own")
|
|
414
|
+
pr.add_argument("--example", default="end-word", choices=sorted(starter_prompts.EXAMPLES), help="which starter set")
|
|
415
|
+
pr.add_argument("--n", type=int, default=1600, help="how many prompts (more prompts, a steadier monitor; collect runs each one once)")
|
|
416
|
+
pr.add_argument("--seed", type=int, default=7101)
|
|
417
|
+
pr.add_argument("--out", default="prompts.jsonl")
|
|
418
|
+
|
|
419
|
+
ag = subs.add_parser("agent", help="serve a local model with its activation monitor and report decisions to the console")
|
|
420
|
+
ag.add_argument("--model", required=True, help="the same model folder the monitor was fitted on")
|
|
421
|
+
ag.add_argument("--monitor", required=True, help="monitor.json written by `evalradar onboard`")
|
|
422
|
+
ag.add_argument("--serve", action="store_true", help="answer OpenAI-compatible requests on --host/--port and monitor each one")
|
|
423
|
+
ag.add_argument("--host", default="127.0.0.1")
|
|
424
|
+
ag.add_argument("--port", type=int, default=8000)
|
|
425
|
+
ag.add_argument("--prompts", default=None, help="prompt JSONL used when the console asks for a batch (and for --every)")
|
|
426
|
+
ag.add_argument("--batch-size", type=int, default=8)
|
|
427
|
+
ag.add_argument("--every", type=float, default=0, help="also run a batch every N seconds")
|
|
428
|
+
ag.add_argument("--poll", type=float, default=3.0)
|
|
429
|
+
ag.add_argument("--no-text", action="store_true", help="do not send prompt and reply text to the console (read them at /evalradar/requests here)")
|
|
430
|
+
ag.add_argument("--no-lens", action="store_true", help="do not compute or send the logit lens explanation")
|
|
431
|
+
ag.add_argument("--lens-layers", default=None, help="comma-separated layers for the logit lens (default: four across the depth)")
|
|
432
|
+
ag.add_argument("--metrics-port", type=int, default=None, help="Prometheus metrics on this port at /metrics (with --serve they are also at /evalradar/metrics)")
|
|
433
|
+
ag.add_argument("--console", default=None)
|
|
434
|
+
ag.add_argument("--token-file", default=None)
|
|
435
|
+
ag.add_argument("--config-dir", default=None)
|
|
436
|
+
for sp in (ag,):
|
|
437
|
+
sp.add_argument("--max-new-tokens", type=int, default=128, help="must match the value used with `collect`")
|
|
438
|
+
sp.add_argument("--system-prompt", default=None, help="must match the value used with `collect`")
|
|
439
|
+
sp.add_argument("--device", default="auto")
|
|
440
|
+
sp.add_argument("--dtype", default="auto", help="must match the value used with `collect`")
|
|
441
|
+
sp.add_argument("--adapter-dir", default=None)
|
|
442
|
+
sp.add_argument("--model-id", default=None, help="must match the value used with `collect`")
|
|
443
|
+
|
|
444
|
+
mo = subs.add_parser("monitors", help="ready-made activation monitors your console offers for a model (list, or --get one)")
|
|
445
|
+
mo.add_argument("--model", default=None, help="local model folder; its weight files are hashed to find monitors for exactly this checkpoint")
|
|
446
|
+
mo.add_argument("--model-id", default=None, help="model id (default: from the folder); without --model, lists by id only")
|
|
447
|
+
mo.add_argument("--get", default=None, help="id of the monitor to download")
|
|
448
|
+
mo.add_argument("--out", default="monitor-out", help="folder for the downloaded monitor.json")
|
|
449
|
+
mo.add_argument("--console", default=None)
|
|
450
|
+
mo.add_argument("--token-file", default=None)
|
|
451
|
+
mo.add_argument("--config-dir", default=None)
|
|
452
|
+
|
|
453
|
+
fb = subs.add_parser("feedback", help="report a ground-truth binary label for a previously monitored request")
|
|
454
|
+
fb.add_argument("--console", default=None)
|
|
455
|
+
fb.add_argument("--token-file", default=None)
|
|
456
|
+
fb.add_argument("--request-id", required=True, help="raw or hashed request id (hashed locally before sending)")
|
|
457
|
+
fb.add_argument("--behavior", required=True)
|
|
458
|
+
fb.add_argument("--label", type=int, choices=(0, 1), required=True, help="0 = passed, 1 = failed")
|
|
459
|
+
fb.add_argument("--source", choices=("human", "judge", "rule", "downstream"), default="human")
|
|
460
|
+
fb.add_argument("--model-id", default=None)
|
|
461
|
+
fb.add_argument("--adapter", default=None)
|
|
462
|
+
fb.add_argument("--config-dir", default=None)
|
|
463
|
+
|
|
464
|
+
args = parser.parse_args(argv)
|
|
465
|
+
if args.command == "init":
|
|
466
|
+
return _run_init(args)
|
|
467
|
+
if args.command == "demo":
|
|
468
|
+
print(json.dumps(_server("demo.run", "The synthetic demo")(args.out), indent=2))
|
|
469
|
+
return 0
|
|
470
|
+
if args.command == "fit":
|
|
471
|
+
a = _server("fitting.fit", "Fitting")(_examples(args.train), _examples(args.calibration), _examples(args.heldout), behavior=args.behavior,
|
|
472
|
+
feature=args.feature, patterns=args.pattern, alpha=args.alpha, min_recall=args.min_recall, min_coverage=args.min_coverage)
|
|
473
|
+
_server("fitting.save_artifact", "Fitting")(a, args.out)
|
|
474
|
+
print(json.dumps({"artifact_id": a.artifact_id, "approved": a.approved, "validation": a.body()["validation"]}, indent=2))
|
|
475
|
+
return 0 if a.approved else 2
|
|
476
|
+
if args.command == "doctor":
|
|
477
|
+
print(json.dumps(doctor(args.model), indent=2))
|
|
478
|
+
return 0
|
|
479
|
+
if args.command == "prompts":
|
|
480
|
+
make, what = starter_prompts.EXAMPLES[args.example]
|
|
481
|
+
rows = make(args.n, args.seed)
|
|
482
|
+
out = Path(args.out).expanduser()
|
|
483
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
484
|
+
out.write_text("".join(json.dumps(r) + "\n" for r in rows), encoding="utf-8")
|
|
485
|
+
print(json.dumps({"prompts": len(rows), "out": str(out), "example": args.example, "what": what,
|
|
486
|
+
"next": f"evalradar collect --model /path/to/model --prompts {out} --layer 12 --expected --out events.jsonl"}, indent=2))
|
|
487
|
+
return 0
|
|
488
|
+
if args.command == "onboard":
|
|
489
|
+
saved = _load_saved_config(args.config_dir) # `evalradar init` saved the console and token: use them by default
|
|
490
|
+
console_url = args.console or saved.get("console_url") or None
|
|
491
|
+
token_file = args.token_file or saved.get("token_file") or None
|
|
492
|
+
if args.upload_features:
|
|
493
|
+
return _onboard_upload(args, console_url, token_file)
|
|
494
|
+
try:
|
|
495
|
+
from evalradar_server.onboard import onboard_from_jsonl # installations licensed for local fitting
|
|
496
|
+
except ModuleNotFoundError as exc:
|
|
497
|
+
if not (exc.name or "").startswith("evalradar_server"):
|
|
498
|
+
raise
|
|
499
|
+
raise SystemExit("Fitting runs on your EvalRadar console. Run again with --upload-features: it sends the activation "
|
|
500
|
+
"vectors, labels and hashed ids from the events file (never prompts or replies) and writes the "
|
|
501
|
+
f"returned monitor.json to {args.out}. Without an upload, use text checks (Monitors in the "
|
|
502
|
+
"console) or a ready-made monitor for your model if the console offers one.") from None
|
|
503
|
+
from evalradar_server.licensing import LicenseError
|
|
504
|
+
try:
|
|
505
|
+
res = _onboard_local(onboard_from_jsonl, args, console_url, token_file)
|
|
506
|
+
except LicenseError as exc:
|
|
507
|
+
raise SystemExit(f"error: {exc}") from None
|
|
508
|
+
print(json.dumps(res, indent=2))
|
|
509
|
+
return 0 if res["approved"] else 2
|
|
510
|
+
if args.command == "proxy":
|
|
511
|
+
saved = _load_saved_config(args.config_dir)
|
|
512
|
+
upstream = args.upstream or saved.get("upstream")
|
|
513
|
+
if not upstream:
|
|
514
|
+
raise SystemExit("Pass --upstream <url> or run `evalradar init` first.")
|
|
515
|
+
console_url = args.console or saved.get("console_url") or None
|
|
516
|
+
token_file = args.token_file or saved.get("token_file") or None
|
|
517
|
+
model_id = args.model_id or saved.get("model_id") or "custom/model"
|
|
518
|
+
adapter = args.adapter or saved.get("adapter") or "none"
|
|
519
|
+
port = args.port if args.port is not None else int(saved.get("port", 8080))
|
|
520
|
+
local_targets = json.loads(Path(args.targets).read_text(encoding="utf-8")) if args.targets else None
|
|
521
|
+
if isinstance(local_targets, dict) and "targets" in local_targets:
|
|
522
|
+
local_targets = local_targets["targets"]
|
|
523
|
+
judge = None
|
|
524
|
+
if args.judge_model:
|
|
525
|
+
from ._compat import env
|
|
526
|
+
judge = openai_compatible_judge(args.judge_url or upstream, args.judge_model, api_key=env("JUDGE_API_KEY"))
|
|
527
|
+
print(f"rubric targets are judged by {args.judge_model} at {args.judge_url or upstream} (sampled, in the background); "
|
|
528
|
+
"the judge receives the prompt and the reply", file=sys.stderr, flush=True)
|
|
529
|
+
send_text = not args.no_text and saved.get("send_text", True) is not False
|
|
530
|
+
mc = MonitorClient(console_url, token_file=token_file, model_id=model_id, adapter=adapter,
|
|
531
|
+
targets=local_targets, source="proxy", execution="proxy", background=bool(console_url and token_file), judge=judge,
|
|
532
|
+
send_text=send_text)
|
|
533
|
+
print(f"prompts and replies {'are sent to the console with each decision' if send_text else 'stay on this machine (--no-text)'}; "
|
|
534
|
+
f"read the latest here: http://127.0.0.1:{port}/evalradar/requests", file=sys.stderr, flush=True)
|
|
535
|
+
if mc.last_error and "HTTP 401" in mc.last_error: # a token the console refuses cannot start working later
|
|
536
|
+
mc.close()
|
|
537
|
+
print(f"error: the console refused the token ({mc.last_error}). Create a new token under Connect a model and run "
|
|
538
|
+
"`evalradar init` again.", file=sys.stderr)
|
|
539
|
+
return 2
|
|
540
|
+
if mc.last_error:
|
|
541
|
+
print(f"warning: could not reach the console ({mc.last_error}); forwarding anyway and retrying every "
|
|
542
|
+
f"{mc.sync_interval:.0f} s. See /evalradar/health.", file=sys.stderr, flush=True)
|
|
543
|
+
if not mc.targets:
|
|
544
|
+
print("note: no monitor is active yet, so requests are forwarded and reported as unchecked. Add a monitor in the "
|
|
545
|
+
"console (Monitors); the proxy picks it up within a minute.", file=sys.stderr, flush=True)
|
|
546
|
+
timeout = args.upstream_timeout if args.upstream_timeout is not None else float(saved.get("upstream_timeout", DEFAULT_UPSTREAM_TIMEOUT))
|
|
547
|
+
srv = make_proxy_server(MonitoringProxy(upstream, mc, shadow_log=Path(args.shadow_log) if args.shadow_log else None,
|
|
548
|
+
upstream_timeout=timeout or None),
|
|
549
|
+
host=args.host, port=port)
|
|
550
|
+
print(f"EvalRadar proxy listening on http://{args.host}:{port} -> {upstream} (targets={len(mc.targets)}, upstream timeout "
|
|
551
|
+
f"{'none' if not timeout else f'{timeout:.0f} s'})", flush=True)
|
|
552
|
+
try:
|
|
553
|
+
srv.serve_forever()
|
|
554
|
+
except KeyboardInterrupt:
|
|
555
|
+
pass
|
|
556
|
+
finally:
|
|
557
|
+
srv.server_close()
|
|
558
|
+
mc.close()
|
|
559
|
+
return 0
|
|
560
|
+
if args.command in ("collect", "agent"):
|
|
561
|
+
return _run_selfhosted(args)
|
|
562
|
+
if args.command == "monitors":
|
|
563
|
+
return _run_monitors(args)
|
|
564
|
+
if args.command == "feedback":
|
|
565
|
+
saved = _load_saved_config(args.config_dir)
|
|
566
|
+
console_url = args.console or saved.get("console_url")
|
|
567
|
+
token_file = args.token_file or saved.get("token_file")
|
|
568
|
+
if not console_url or not token_file:
|
|
569
|
+
raise SystemExit("Pass --console and --token-file, or run `evalradar init` first.")
|
|
570
|
+
mc = MonitorClient(console_url, token_file=token_file, model_id=args.model_id or saved.get("model_id") or "custom/model",
|
|
571
|
+
adapter=args.adapter or saved.get("adapter") or "none", auto_sync=False)
|
|
572
|
+
out = mc.report_feedback(args.request_id, args.behavior, args.label, source=args.source)
|
|
573
|
+
print(json.dumps(out, indent=2))
|
|
574
|
+
return 0
|
|
575
|
+
|
|
576
|
+
a = load_artifact(args.artifact)
|
|
577
|
+
if args.command == "score":
|
|
578
|
+
for _, e in _events(args.events):
|
|
579
|
+
print(json.dumps(score(a, e), allow_nan=False))
|
|
580
|
+
return 0
|
|
581
|
+
report = _server("fitting." + args.command, "Validation and comparison")(a, _examples(args.events))
|
|
582
|
+
print(json.dumps(report, indent=2, allow_nan=False))
|
|
583
|
+
return 0
|
|
584
|
+
|
|
585
|
+
|
|
586
|
+
if __name__ == "__main__":
|
|
587
|
+
raise SystemExit(main())
|