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/detectors.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""Detectors added in Phase 1. A detector score is an association, not a causal explanation.
|
|
2
|
+
|
|
3
|
+
`LogisticProbe` is an L2-regularized logistic regression over one named numeric feature. The
|
|
4
|
+
feature may be behavioral (prompt- or output-derived), a readout summary, or an internal state;
|
|
5
|
+
`signal_class` records which, so comparisons stay honest.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
from dataclasses import dataclass, asdict
|
|
9
|
+
from typing import Sequence
|
|
10
|
+
import math
|
|
11
|
+
import numpy as np
|
|
12
|
+
|
|
13
|
+
SIGNAL_CLASSES = ("behavioral", "readout", "internal")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True)
|
|
17
|
+
class LogisticProbe:
|
|
18
|
+
feature: str
|
|
19
|
+
weight: tuple[float, ...]
|
|
20
|
+
bias: float
|
|
21
|
+
mean: tuple[float, ...]
|
|
22
|
+
scale: tuple[float, ...]
|
|
23
|
+
name: str
|
|
24
|
+
signal_class: str = "internal"
|
|
25
|
+
|
|
26
|
+
def __post_init__(self):
|
|
27
|
+
if self.signal_class not in SIGNAL_CLASSES:
|
|
28
|
+
raise ValueError(f"invalid signal class: {self.signal_class}")
|
|
29
|
+
if not self.name.strip() or not self.feature.strip():
|
|
30
|
+
raise ValueError("name and feature required")
|
|
31
|
+
|
|
32
|
+
@classmethod
|
|
33
|
+
def train(cls, rows: Sequence, feature: str, *, name: str, signal_class: str = "internal",
|
|
34
|
+
l2: float = 1.0, max_iter: int = 100, tol: float = 1e-8) -> "LogisticProbe":
|
|
35
|
+
"""Fit on labeled rows (objects with `.label` and `.event.features`). Deterministic."""
|
|
36
|
+
if l2 <= 0 or not math.isfinite(l2):
|
|
37
|
+
raise ValueError("l2 must be positive")
|
|
38
|
+
y = np.asarray([r.label for r in rows], dtype=float)
|
|
39
|
+
if len(set(y.tolist())) != 2:
|
|
40
|
+
raise ValueError("training requires both classes")
|
|
41
|
+
try:
|
|
42
|
+
x = np.asarray([r.event.features[feature] for r in rows], dtype=float)
|
|
43
|
+
except (KeyError, ValueError, TypeError) as exc:
|
|
44
|
+
raise ValueError("complete, rectangular training features required") from exc
|
|
45
|
+
if x.ndim != 2 or not x.shape[1] or not np.isfinite(x).all():
|
|
46
|
+
raise ValueError("finite nonempty 2D features required")
|
|
47
|
+
mean = x.mean(axis=0)
|
|
48
|
+
scale = x.std(axis=0)
|
|
49
|
+
scale[scale < 1e-8] = 1.0
|
|
50
|
+
z = (x - mean) / scale
|
|
51
|
+
n, d = z.shape
|
|
52
|
+
# Work in the n-dimensional dual when the feature is wider than the sample (kernel trick
|
|
53
|
+
# for a linear kernel), so a 1024-d residual with a few hundred rows stays cheap and stable.
|
|
54
|
+
if d > n:
|
|
55
|
+
basis = z # w = basis.T @ a
|
|
56
|
+
design = z @ z.T # n x n
|
|
57
|
+
penalty = design
|
|
58
|
+
else:
|
|
59
|
+
basis = None
|
|
60
|
+
design = z
|
|
61
|
+
penalty = np.eye(d)
|
|
62
|
+
k = design.shape[1]
|
|
63
|
+
coef = np.zeros(k)
|
|
64
|
+
b = 0.0
|
|
65
|
+
for _ in range(max_iter):
|
|
66
|
+
eta = np.clip(design @ coef + b, -30.0, 30.0)
|
|
67
|
+
p = 1.0 / (1.0 + np.exp(-eta))
|
|
68
|
+
w_diag = np.maximum(p * (1.0 - p), 1e-6)
|
|
69
|
+
grad = design.T @ (p - y) + l2 * (penalty @ coef)
|
|
70
|
+
grad_b = float(np.sum(p - y))
|
|
71
|
+
hess = design.T @ (design * w_diag[:, None]) + l2 * penalty + 1e-8 * np.eye(k)
|
|
72
|
+
hess_b = design.T @ w_diag
|
|
73
|
+
full = np.block([[hess, hess_b[:, None]], [hess_b[None, :], np.array([[w_diag.sum()]])]])
|
|
74
|
+
step = np.linalg.solve(full, np.concatenate([grad, [grad_b]]))
|
|
75
|
+
coef -= step[:-1]
|
|
76
|
+
b -= float(step[-1])
|
|
77
|
+
if float(np.max(np.abs(step))) < tol:
|
|
78
|
+
break
|
|
79
|
+
w = basis.T @ coef if basis is not None else coef
|
|
80
|
+
if not (np.isfinite(w).all() and math.isfinite(b)):
|
|
81
|
+
raise ValueError("logistic fit did not produce finite parameters")
|
|
82
|
+
return cls(feature, tuple(w.tolist()), float(b), tuple(mean.tolist()), tuple(scale.tolist()), name, signal_class)
|
|
83
|
+
|
|
84
|
+
def raw(self, event) -> float | None:
|
|
85
|
+
try:
|
|
86
|
+
x = np.asarray(event.features[self.feature], dtype=float)
|
|
87
|
+
if x.shape != (len(self.weight),) or not np.isfinite(x).all():
|
|
88
|
+
return None
|
|
89
|
+
z = float(np.dot((x - self.mean) / self.scale, self.weight) + self.bias)
|
|
90
|
+
if not math.isfinite(z):
|
|
91
|
+
return None
|
|
92
|
+
return 1.0 / (1.0 + math.exp(-max(-60.0, min(60.0, z))))
|
|
93
|
+
except (KeyError, ValueError, TypeError, OverflowError):
|
|
94
|
+
return None
|
|
95
|
+
|
|
96
|
+
def spec(self) -> dict:
|
|
97
|
+
return {"kind": "logistic_probe", **asdict(self)}
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def logistic_from_spec(d: dict) -> LogisticProbe:
|
|
101
|
+
for key in ("weight", "mean", "scale"):
|
|
102
|
+
d[key] = tuple(d[key])
|
|
103
|
+
p = LogisticProbe(**d)
|
|
104
|
+
if not p.weight or not (len(p.weight) == len(p.mean) == len(p.scale)) or any(v <= 0 for v in p.scale):
|
|
105
|
+
raise ValueError("invalid probe parameters")
|
|
106
|
+
if not all(math.isfinite(v) for v in (*p.weight, *p.mean, *p.scale, p.bias)):
|
|
107
|
+
raise ValueError("nonfinite probe parameters")
|
|
108
|
+
return p
|
evalradar/doctor.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""`evalradar doctor`: is this machine ready for output monitoring or for activation monitors, and which layers to try."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
import importlib.util
|
|
4
|
+
import json
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import platform
|
|
7
|
+
|
|
8
|
+
from .capture.hf import ARCH_LAYOUTS
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def doctor(model_path: str | Path | None = None) -> dict:
|
|
12
|
+
"""Inspect local runtime readiness and whether a checkpoint supports activation-hook monitoring."""
|
|
13
|
+
has_torch = importlib.util.find_spec("torch") is not None
|
|
14
|
+
has_transformers = importlib.util.find_spec("transformers") is not None
|
|
15
|
+
has_vllm = importlib.util.find_spec("vllm") is not None
|
|
16
|
+
cuda_available = False
|
|
17
|
+
gpu_name = None
|
|
18
|
+
if has_torch:
|
|
19
|
+
try:
|
|
20
|
+
import torch
|
|
21
|
+
cuda_available = bool(torch.cuda.is_available())
|
|
22
|
+
if cuda_available:
|
|
23
|
+
gpu_name = torch.cuda.get_device_name(0)
|
|
24
|
+
except Exception:
|
|
25
|
+
pass
|
|
26
|
+
|
|
27
|
+
report: dict = {
|
|
28
|
+
"python": platform.python_version(),
|
|
29
|
+
"packages": {"torch": has_torch, "transformers": has_transformers, "vllm": has_vllm},
|
|
30
|
+
"cuda": {"available": cuda_available, "device": gpu_name},
|
|
31
|
+
"supported_hook_architectures": sorted(ARCH_LAYOUTS.keys()),
|
|
32
|
+
"recommended_tier": "level_0_output_proxy",
|
|
33
|
+
"recommendation": "Use `evalradar proxy` or `MonitorClient` for immediate output-level monitoring.",
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
if model_path is not None:
|
|
37
|
+
p = Path(model_path).expanduser()
|
|
38
|
+
cfg_path = p / "config.json" if p.is_dir() else p
|
|
39
|
+
if not cfg_path.is_file():
|
|
40
|
+
report["model"] = {"path": str(p), "error": "config.json not found", "hook_supported": False}
|
|
41
|
+
return report
|
|
42
|
+
cfg = json.loads(cfg_path.read_text(encoding="utf-8"))
|
|
43
|
+
model_type = cfg.get("model_type")
|
|
44
|
+
archs = cfg.get("architectures") or []
|
|
45
|
+
layout = ARCH_LAYOUTS.get(model_type)
|
|
46
|
+
arch_match = bool(layout and (not archs or layout.architecture in archs))
|
|
47
|
+
report["model"] = {
|
|
48
|
+
"path": str(p),
|
|
49
|
+
"model_type": model_type,
|
|
50
|
+
"architectures": archs,
|
|
51
|
+
"hook_supported": arch_match,
|
|
52
|
+
"expected_architecture": layout.architecture if layout else None,
|
|
53
|
+
}
|
|
54
|
+
text_cfg = cfg.get("text_config") if isinstance(cfg.get("text_config"), dict) else cfg
|
|
55
|
+
n_layers = text_cfg.get("num_hidden_layers") or text_cfg.get("n_layer")
|
|
56
|
+
if isinstance(n_layers, int) and n_layers > 0:
|
|
57
|
+
report["model"]["layers"] = n_layers
|
|
58
|
+
# Middle-to-late layers usually carry the most linearly readable task state; there is no universal best
|
|
59
|
+
# layer, so try a few on a held-out comparison rather than trusting one.
|
|
60
|
+
report["model"]["suggested_layers"] = sorted({n_layers // 2, (2 * n_layers) // 3, (3 * n_layers) // 4})
|
|
61
|
+
if arch_match and has_torch and has_transformers:
|
|
62
|
+
report["recommended_tier"] = "level_2_activation_hooks"
|
|
63
|
+
report["recommendation"] = (
|
|
64
|
+
f"Architecture {model_type!r} ({layout.architecture}) is in the verified hook allowlist. "
|
|
65
|
+
+ (f"It has {n_layers} layers; start with `evalradar collect --layer {(2 * n_layers) // 3}` "
|
|
66
|
+
f"(also worth trying: {', '.join(str(x) for x in report['model']['suggested_layers'])}), then `evalradar onboard`."
|
|
67
|
+
if isinstance(n_layers, int) and n_layers > 0 else "Run `evalradar collect`, then `evalradar onboard`.")
|
|
68
|
+
)
|
|
69
|
+
elif arch_match:
|
|
70
|
+
report["recommended_tier"] = "level_1_install_hf"
|
|
71
|
+
report["recommendation"] = (
|
|
72
|
+
f"Architecture {model_type!r} is supported, but torch/transformers are not installed in this environment. "
|
|
73
|
+
"Install `evalradar[hf]` or start with `evalradar proxy`."
|
|
74
|
+
)
|
|
75
|
+
else:
|
|
76
|
+
report["recommended_tier"] = "level_0_output_proxy"
|
|
77
|
+
report["recommendation"] = (
|
|
78
|
+
f"Architecture {model_type!r} is not yet in ARCH_LAYOUTS ({', '.join(sorted(ARCH_LAYOUTS))}). "
|
|
79
|
+
"Start with Level 0 (`evalradar proxy` or `MonitorClient`) for output monitoring."
|
|
80
|
+
)
|
|
81
|
+
return report
|
evalradar/lens.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""Logit lens on the self-hosted agent: what the model leans towards saying, layer by layer, before its reply.
|
|
2
|
+
|
|
3
|
+
At the last prompt position, each chosen layer's residual is decoded with the model's own final norm and unembedding
|
|
4
|
+
and reduced to its top tokens. At the last layer this is the model's real next-token distribution; at earlier layers
|
|
5
|
+
it is a readout convention: not the model's belief, not a calibrated probability, and not a detector (in this project's
|
|
6
|
+
tests lens-based detectors did not beat a text-only baseline). It explains an alert; it does not raise one.
|
|
7
|
+
|
|
8
|
+
The top tokens are words derived from the prompt, so they are flagged when they look like personal or secret data
|
|
9
|
+
(digit runs, e-mail parts, key prefixes, credential words, or a match for the workspace's own leak rules); the console
|
|
10
|
+
hides flagged words until a person confirms. Person names are not detected.
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
import re
|
|
14
|
+
from typing import Iterable, Sequence
|
|
15
|
+
|
|
16
|
+
from .contracts import CaptureSpec
|
|
17
|
+
|
|
18
|
+
TOP_K = 5
|
|
19
|
+
MAX_TOKEN_CHARS = 32
|
|
20
|
+
# What a single token can show of personal or secret data. Tokens are short pieces, so long patterns (a whole key, a
|
|
21
|
+
# whole e-mail address) rarely match one token; these catch the pieces.
|
|
22
|
+
PII_RULES: tuple[tuple[str, re.Pattern], ...] = (
|
|
23
|
+
("digits", re.compile(r"\d{3,}")),
|
|
24
|
+
("email", re.compile(r"@|\b[\w.-]+\.(com|org|net|edu|io|cn|ca|uk|de)\b", re.I)),
|
|
25
|
+
("key", re.compile(r"^\s*(sk-|sk_|pk_|ghp_|gho_|xox[abp]-|AKIA|AIza|Bearer\b|eyJ)", re.I)),
|
|
26
|
+
("credential", re.compile(r"password|passwd|secret|api[_ ]?key|token|ssn|passport|身份证|密码|口令|银行卡|手机号", re.I)),
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def flag(token: str, rules: Sequence[re.Pattern] = ()) -> str | None:
|
|
31
|
+
"""Why this token may be personal or secret data, or None."""
|
|
32
|
+
for name, rx in PII_RULES:
|
|
33
|
+
if rx.search(token):
|
|
34
|
+
return name
|
|
35
|
+
for rx in rules:
|
|
36
|
+
if rx.search(token) or rx.search(token.strip()):
|
|
37
|
+
return "workspace_rule"
|
|
38
|
+
return None
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def compile_rules(targets: Iterable[dict]) -> list[re.Pattern]:
|
|
42
|
+
"""The workspace's leak rules (active regex_forbidden targets), used to flag tokens; unusable patterns are skipped."""
|
|
43
|
+
out = []
|
|
44
|
+
for tg in targets or ():
|
|
45
|
+
v = (tg or {}).get("verifier") or {}
|
|
46
|
+
if v.get("kind") != "regex_forbidden":
|
|
47
|
+
continue
|
|
48
|
+
pats = v.get("patterns") or []
|
|
49
|
+
for p in (pats.splitlines() if isinstance(pats, str) else pats):
|
|
50
|
+
try:
|
|
51
|
+
out.append(re.compile(str(p), 0 if v.get("case_sensitive") else re.I))
|
|
52
|
+
except re.error:
|
|
53
|
+
continue
|
|
54
|
+
return out
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def default_layers(n_layers: int, monitor_layer: int | None = None) -> list[int]:
|
|
58
|
+
"""Four layers across the depth: a third of the way, the monitor's layer, between it and the end, the last."""
|
|
59
|
+
last = n_layers - 1
|
|
60
|
+
mid = monitor_layer if monitor_layer is not None else (2 * n_layers) // 3
|
|
61
|
+
return sorted({max(0, round(n_layers / 3)), mid, (mid + last + 1) // 2, last})
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def feature_id(layer: int) -> str:
|
|
65
|
+
return f"lens.{layer}.last_token"
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class LogitLens:
|
|
69
|
+
def __init__(self, adapter, layers: Sequence[int], top_k: int = TOP_K):
|
|
70
|
+
n = len(adapter.layers)
|
|
71
|
+
bad = [x for x in layers if not 0 <= int(x) < n]
|
|
72
|
+
if bad:
|
|
73
|
+
raise ValueError(f"lens layers must be between 0 and {n - 1}; got {bad}")
|
|
74
|
+
self.adapter, self.layers, self.top_k = adapter, sorted({int(x) for x in layers}), int(top_k)
|
|
75
|
+
self.specs = [CaptureSpec(layer=x, module_path=None, tap="resid_post", position_policy="last_prefill", dtype=adapter.dtype,
|
|
76
|
+
reduction="none", feature_id=feature_id(x)) for x in self.layers]
|
|
77
|
+
|
|
78
|
+
def _text(self, token_id: int) -> str:
|
|
79
|
+
t = self.adapter.tokenizer.decode([int(token_id)], skip_special_tokens=False)
|
|
80
|
+
return t[:MAX_TOKEN_CHARS]
|
|
81
|
+
|
|
82
|
+
def read(self, trace, rules: Sequence[re.Pattern] = ()) -> dict | None:
|
|
83
|
+
"""{"position", "emitted", "layers": [{"layer", "entropy", "top": [{"t", "p", "pii"?}]}]} from a generation trace."""
|
|
84
|
+
torch = self.adapter._torch
|
|
85
|
+
rows, used = [], []
|
|
86
|
+
for spec in self.specs:
|
|
87
|
+
cap = trace.captures.get(spec.feature_id) if trace.capture_error is None else None
|
|
88
|
+
if cap is None:
|
|
89
|
+
continue
|
|
90
|
+
rows.append(cap.data[-1].reshape(-1))
|
|
91
|
+
used.append(spec.layer)
|
|
92
|
+
if not rows:
|
|
93
|
+
return None
|
|
94
|
+
with torch.inference_mode():
|
|
95
|
+
h = torch.stack(rows).to(self.adapter.device)
|
|
96
|
+
logp = torch.log_softmax(self.adapter.head(self.adapter.final_norm(h.unsqueeze(0).to(next(self.adapter.head.parameters()).dtype)))[0].float(), dim=-1)
|
|
97
|
+
top = torch.topk(logp, self.top_k, dim=-1)
|
|
98
|
+
entropy = (-(logp.exp() * logp).sum(dim=-1)).cpu().tolist()
|
|
99
|
+
ids, vals = top.indices.cpu().tolist(), top.values.exp().cpu().tolist()
|
|
100
|
+
out = []
|
|
101
|
+
for layer, ent, row_ids, row_p in zip(used, entropy, ids, vals):
|
|
102
|
+
toks = []
|
|
103
|
+
for i, p in zip(row_ids, row_p):
|
|
104
|
+
t = self._text(i)
|
|
105
|
+
item = {"t": t, "p": round(float(p), 4)}
|
|
106
|
+
why = flag(t, rules)
|
|
107
|
+
if why:
|
|
108
|
+
item["pii"] = why
|
|
109
|
+
toks.append(item)
|
|
110
|
+
out.append({"layer": layer, "entropy": round(float(ent), 3), "top": toks})
|
|
111
|
+
emitted = None
|
|
112
|
+
if trace.new_token_ids:
|
|
113
|
+
t = self._text(trace.new_token_ids[0])
|
|
114
|
+
emitted = {"t": t, **({"pii": flag(t, rules)} if flag(t, rules) else {})}
|
|
115
|
+
return {"method": "logit_lens", "position": "last_prompt", "emitted": emitted, "layers": out}
|
evalradar/localview.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""The local request viewer: the latest requests seen by this proxy, SDK client or agent, with their prompt, reply and
|
|
2
|
+
every check's decision, at /evalradar/requests on the machine itself. It answers only to loopback clients, so text that
|
|
3
|
+
is kept off the console (send_text off) is readable where it is, and nowhere else."""
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
import html
|
|
6
|
+
import ipaddress
|
|
7
|
+
import json
|
|
8
|
+
import time
|
|
9
|
+
|
|
10
|
+
PATHS = ("/evalradar/requests", "/evalradar/requests.json")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def is_loopback(addr: str) -> bool:
|
|
14
|
+
try:
|
|
15
|
+
return ipaddress.ip_address(addr).is_loopback
|
|
16
|
+
except ValueError:
|
|
17
|
+
return False
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def render(rows: list[dict], *, title: str, sent: bool) -> bytes:
|
|
21
|
+
def check(c):
|
|
22
|
+
tone = {"alert": "#c33c1d", "no_alert": "#0a7f66"}.get(c.get("status"), "#657086")
|
|
23
|
+
word = {"alert": "Alert", "no_alert": "Passed", "abstain": "Not decided"}.get(c.get("status"), c.get("status") or "")
|
|
24
|
+
return (f'<li><b style="color:{tone}">{html.escape(word)}</b> · {html.escape(str(c.get("behavior") or ""))}'
|
|
25
|
+
f'{" · " + html.escape(str(c["reason"])) if c.get("reason") else ""}</li>')
|
|
26
|
+
items = "".join(
|
|
27
|
+
f'<article><header><time>{time.strftime("%H:%M:%S", time.localtime(r.get("ts") or 0))}</time> <code>{html.escape(r["request_id"][:12])}</code></header>'
|
|
28
|
+
f'<h3>Prompt</h3><pre>{html.escape(r.get("prompt") or "")}</pre><h3>Reply</h3><pre>{html.escape(r.get("reply") or "")}</pre>'
|
|
29
|
+
f'<ul>{"".join(check(c) for c in r.get("checks") or [])}</ul></article>' for r in rows)
|
|
30
|
+
note = ("Prompts and replies are also sent to your EvalRadar console with each decision." if sent else
|
|
31
|
+
"Prompts and replies are not sent to the console (send_text is off); this page is the only place they can be read.")
|
|
32
|
+
page = f"""<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{html.escape(title)}</title>
|
|
33
|
+
<style>body{{font:15px/1.5 system-ui,sans-serif;margin:0 auto;max-width:900px;padding:16px;color:#0f1420;background:#f4f6fa}}
|
|
34
|
+
article{{background:#fff;border:1px solid #dde2ec;border-radius:10px;padding:12px 14px;margin:10px 0}}h3{{font-size:12px;color:#657086;margin:8px 0 2px}}
|
|
35
|
+
pre{{white-space:pre-wrap;word-break:break-word;background:#eceff5;padding:8px;border-radius:6px;margin:0}}ul{{margin:8px 0 0;padding-left:18px}}
|
|
36
|
+
header{{color:#657086;font-size:13px}}</style><h1>{html.escape(title)}</h1><p>{html.escape(note)} Showing the latest {len(rows)} requests, newest first; this page is
|
|
37
|
+
served only to this machine. <a href="?">Refresh</a> · <a href="requests.json">JSON</a></p>{items or "<p>No requests yet.</p>"}"""
|
|
38
|
+
return page.encode()
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def respond(handler, client, title: str) -> bool:
|
|
42
|
+
"""Serve the viewer from a BaseHTTPRequestHandler. Returns False when the path is not the viewer's."""
|
|
43
|
+
path = handler.path.split("?")[0]
|
|
44
|
+
if path not in PATHS:
|
|
45
|
+
return False
|
|
46
|
+
if not is_loopback(handler.client_address[0]):
|
|
47
|
+
body, ctype, status = b'{"error": "the request viewer is only served to this machine"}', "application/json", 403
|
|
48
|
+
elif path.endswith(".json"):
|
|
49
|
+
body, ctype, status = json.dumps(client.local_requests()).encode(), "application/json", 200
|
|
50
|
+
else:
|
|
51
|
+
body, ctype, status = render(client.local_requests(), title=title, sent=client.send_text), "text/html; charset=utf-8", 200
|
|
52
|
+
handler.send_response(status)
|
|
53
|
+
handler.send_header("Content-Type", ctype)
|
|
54
|
+
handler.send_header("Content-Length", str(len(body)))
|
|
55
|
+
handler.send_header("Cache-Control", "no-store")
|
|
56
|
+
handler.end_headers()
|
|
57
|
+
handler.wfile.write(body)
|
|
58
|
+
return True
|
evalradar/monitoring.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""Runtime use of a compiled monitor: attach, score, report, escalate.
|
|
2
|
+
|
|
3
|
+
The runtime path only captures the declared sites and evaluates a fixed linear probe. It never
|
|
4
|
+
runs a backward pass, a patching experiment or an agent. A failure to capture or score is
|
|
5
|
+
reported as `unavailable` / `error`, never as a healthy `no_alert`.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
from dataclasses import asdict, dataclass, field
|
|
9
|
+
from typing import Sequence
|
|
10
|
+
import time
|
|
11
|
+
|
|
12
|
+
from .compile import MonitorSpec, featurize, load_monitor, node_to_site, site_feature_id
|
|
13
|
+
from .core import Artifact, Event, Fingerprint, score
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class RuntimeMonitor:
|
|
18
|
+
spec: MonitorSpec
|
|
19
|
+
artifact: Artifact
|
|
20
|
+
fingerprint: Fingerprint
|
|
21
|
+
mode: str = "shadow" # shadow: report only; active: the caller may act on alerts
|
|
22
|
+
escalations: list = field(default_factory=list)
|
|
23
|
+
|
|
24
|
+
def __post_init__(self):
|
|
25
|
+
if self.mode not in ("shadow", "active"):
|
|
26
|
+
raise ValueError("mode must be shadow or active")
|
|
27
|
+
|
|
28
|
+
@classmethod
|
|
29
|
+
def load(cls, spec_path, artifact_path, fingerprint: Fingerprint, *, mode: str = "shadow") -> "RuntimeMonitor":
|
|
30
|
+
spec, art = load_monitor(spec_path, artifact_path, fingerprint) # refuses an incompatible deployment
|
|
31
|
+
return cls(spec, art, fingerprint, mode)
|
|
32
|
+
|
|
33
|
+
def capture_specs(self):
|
|
34
|
+
return self.spec.specs()
|
|
35
|
+
|
|
36
|
+
def evaluate(self, trace, *, behavioral: Sequence[float] | None = None) -> dict:
|
|
37
|
+
"""Score one generation trace (from HFModelAdapter.generate / generate_batch with capture_specs())."""
|
|
38
|
+
start = time.perf_counter_ns()
|
|
39
|
+
features = {}
|
|
40
|
+
if trace.capture_error:
|
|
41
|
+
ev = Event(trace.request_id, self.fingerprint, None, {})
|
|
42
|
+
else:
|
|
43
|
+
try:
|
|
44
|
+
sv = {}
|
|
45
|
+
for site in self.spec.sites:
|
|
46
|
+
layer, tap = node_to_site(site)
|
|
47
|
+
cap = trace.captures[site_feature_id(layer, tap)]
|
|
48
|
+
sv[site] = cap.data[-1].float().cpu().numpy() # last captured position for last_prefill specs
|
|
49
|
+
features["x"] = featurize(self.spec, sv)
|
|
50
|
+
except Exception:
|
|
51
|
+
features = {}
|
|
52
|
+
if behavioral is not None:
|
|
53
|
+
features["behavioral"] = list(behavioral)
|
|
54
|
+
ev = Event(trace.request_id, self.fingerprint, None, features)
|
|
55
|
+
record = score(self.artifact, ev)
|
|
56
|
+
record["monitor_id"] = self.spec.monitor_id
|
|
57
|
+
record["monitor_spec_digest"] = self.spec.digest
|
|
58
|
+
record["mode"] = self.mode
|
|
59
|
+
record["capture_error"] = trace.capture_error.split(":")[0] if trace.capture_error else None
|
|
60
|
+
record["monitor_ms"] = (time.perf_counter_ns() - start) / 1e6
|
|
61
|
+
if record["status"] == "alert":
|
|
62
|
+
self.escalations.append({"event_id_hash": record["event_id_hash"], "monitor_id": self.spec.monitor_id,
|
|
63
|
+
"risk_id": self.artifact.behavior, "fusion_score": (record["fusion"] or {}).get("score")})
|
|
64
|
+
return record
|
|
65
|
+
|
|
66
|
+
def escalation_request(self, request_id: str) -> dict:
|
|
67
|
+
"""Package alerts for the offline pipeline (a DiagnosisRequest skeleton without raw content)."""
|
|
68
|
+
return {"request_id": request_id, "target_behavior": self.artifact.behavior, "failure_category": self.artifact.behavior,
|
|
69
|
+
"model_fingerprint": asdict(self.fingerprint), "monitor_id": self.spec.monitor_id,
|
|
70
|
+
"case_refs": [e["event_id_hash"] for e in self.escalations], "n_alerts": len(self.escalations),
|
|
71
|
+
"note": "case_refs are hashed event IDs; raw inputs stay with the caller"}
|
evalradar/onboarding.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""`evalradar onboard --upload-features`: send activation vectors and labels to your EvalRadar console, which fits,
|
|
2
|
+
calibrates and tests the activation monitor and returns monitor.json for `evalradar agent`.
|
|
3
|
+
|
|
4
|
+
What is sent: for each reply in the events file, the activation vector of one feature (float32), its 0/1 label, and
|
|
5
|
+
hashed event and group ids; plus the model fingerprint and the operating limits. Prompts, replies and label reasons
|
|
6
|
+
are never sent (the console refuses any text field). Activation vectors are not text, but they are derived from it,
|
|
7
|
+
and parts of a prompt can in principle be reconstructed from them; upload only where that is acceptable.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
import base64
|
|
11
|
+
import hashlib
|
|
12
|
+
import json
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
|
|
17
|
+
from .sdk import ConsoleTransport
|
|
18
|
+
|
|
19
|
+
FINGERPRINT_KEYS = ("model", "checkpoint", "tokenizer", "backend", "quantization", "adapter", "config", "feature_spec")
|
|
20
|
+
WHAT_IS_SENT = ("Sends, for each reply: the activation vector of {feature} (float32), its label, and hashed event and group ids; "
|
|
21
|
+
"plus the model fingerprint. Never sends prompts, replies or label reasons. Activation vectors are derived from "
|
|
22
|
+
"the text, and parts of it can in principle be reconstructed from them.")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _h(kind: str, value: str) -> str:
|
|
26
|
+
return hashlib.sha256(f"{kind}:{value}".encode()).hexdigest()[:32]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def build_upload(events_path: str | Path, *, behavior: str, feature: str, alpha: float = 0.05, min_recall: float = 0.30,
|
|
30
|
+
min_coverage: float = 0.95, rerun_labels_path: str | Path | None = None) -> dict:
|
|
31
|
+
"""The request body, built only from the fields that may leave the machine."""
|
|
32
|
+
rows, fingerprint = [], None
|
|
33
|
+
with Path(events_path).open(encoding="utf-8") as f:
|
|
34
|
+
for n, line in enumerate(f, 1):
|
|
35
|
+
if not line.strip():
|
|
36
|
+
continue
|
|
37
|
+
d = json.loads(line)
|
|
38
|
+
vec = (d.get("features") or {}).get(feature)
|
|
39
|
+
if vec is None:
|
|
40
|
+
raise ValueError(f"{events_path}:{n}: no feature {feature!r} (features here: {', '.join(d.get('features') or {}) or 'none'})")
|
|
41
|
+
if d.get("label") not in (0, 1) or "group" not in d or "event_id" not in d:
|
|
42
|
+
raise ValueError(f"{events_path}:{n}: each row needs event_id, group and a 0/1 label")
|
|
43
|
+
fp = {k: str(v) for k, v in (d.get("fingerprint") or {}).items() if k in FINGERPRINT_KEYS}
|
|
44
|
+
if fingerprint is None:
|
|
45
|
+
fingerprint = fp
|
|
46
|
+
elif fp != fingerprint:
|
|
47
|
+
raise ValueError(f"{events_path}:{n}: a different model fingerprint; one upload fits one exact model")
|
|
48
|
+
rows.append({"event_id": _h("event", str(d["event_id"])), "group": _h("group", str(d["group"])), "label": int(d["label"]),
|
|
49
|
+
"x": base64.b64encode(np.asarray(vec, dtype="<f4").tobytes()).decode()})
|
|
50
|
+
body = {"behavior": behavior, "feature": feature, "fingerprint": fingerprint or {}, "rows": rows,
|
|
51
|
+
"alpha": alpha, "min_recall": min_recall, "min_coverage": min_coverage}
|
|
52
|
+
if rerun_labels_path:
|
|
53
|
+
with Path(rerun_labels_path).open(encoding="utf-8") as f:
|
|
54
|
+
body["rerun"] = {_h("event", str(d["event_id"])): int(d["label"]) for d in (json.loads(x) for x in f if x.strip())}
|
|
55
|
+
return body
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def upload_for_fitting(events_path: str | Path, *, behavior: str, feature: str, out_dir: str | Path, console_url: str,
|
|
59
|
+
token: str, alpha: float = 0.05, min_recall: float = 0.30, min_coverage: float = 0.95,
|
|
60
|
+
rerun_labels_path: str | Path | None = None, timeout: float = 900.0) -> dict:
|
|
61
|
+
"""Upload, let the console fit, and write monitor.json, ledger_records.jsonl and onboarding_report.json to out_dir."""
|
|
62
|
+
body = build_upload(events_path, behavior=behavior, feature=feature, alpha=alpha, min_recall=min_recall,
|
|
63
|
+
min_coverage=min_coverage, rerun_labels_path=rerun_labels_path)
|
|
64
|
+
out = Path(out_dir)
|
|
65
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
66
|
+
reply = ConsoleTransport(console_url, token, timeout=timeout).post("onboard", body)
|
|
67
|
+
result = dict(reply["result"])
|
|
68
|
+
if reply.get("monitor"):
|
|
69
|
+
(out / "monitor.json").write_text(reply["monitor"])
|
|
70
|
+
result["artifact_path"] = str(out / "monitor.json")
|
|
71
|
+
(out / "ledger_records.jsonl").write_text("\n".join(json.dumps(r) for r in reply.get("records", [])) + "\n", encoding="utf-8")
|
|
72
|
+
result["uploaded"] = {"rows": len(body["rows"]), "feature": feature, "bytes": len(json.dumps(body))}
|
|
73
|
+
(out / "onboarding_report.json").write_text(json.dumps(result, indent=2), encoding="utf-8")
|
|
74
|
+
return result
|