defacto-eval 0.2.0__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.
- defacto/__init__.py +39 -0
- defacto/__main__.py +4 -0
- defacto/_stats.py +214 -0
- defacto/cli.py +255 -0
- defacto/hack/__init__.py +17 -0
- defacto/hack/reward.py +168 -0
- defacto/io.py +34 -0
- defacto/judge/__init__.py +150 -0
- defacto/judge/agreement.py +209 -0
- defacto/judge/calibration.py +93 -0
- defacto/judge/metrics.py +94 -0
- defacto/judge/risk_coverage.py +108 -0
- defacto/leakage/__init__.py +15 -0
- defacto/leakage/minhash.py +97 -0
- defacto/leakage/probe.py +238 -0
- defacto/leakage/text.py +135 -0
- defacto/monitoring/__init__.py +7 -0
- defacto/monitoring/drift.py +150 -0
- defacto/py.typed +0 -0
- defacto/report/__init__.py +30 -0
- defacto/report/build.py +429 -0
- defacto/report/governance.py +173 -0
- defacto/report/render.py +60 -0
- defacto/report/tabular.py +52 -0
- defacto/viz/__init__.py +29 -0
- defacto/viz/plots.py +345 -0
- defacto_eval-0.2.0.dist-info/METADATA +198 -0
- defacto_eval-0.2.0.dist-info/RECORD +32 -0
- defacto_eval-0.2.0.dist-info/WHEEL +5 -0
- defacto_eval-0.2.0.dist-info/entry_points.txt +2 -0
- defacto_eval-0.2.0.dist-info/licenses/LICENSE +201 -0
- defacto_eval-0.2.0.dist-info/top_level.txt +1 -0
defacto/__init__.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""DeFacto: evaluation-integrity and verifier-audit toolkit for LLM systems.
|
|
2
|
+
|
|
3
|
+
DeFacto answers one question for people who build, validate, or govern LLM
|
|
4
|
+
systems: is this evaluation result actually true? It detects data leakage and
|
|
5
|
+
benchmark contamination, measures how trustworthy an LLM judge or reward model
|
|
6
|
+
is, flags reward hacking, tracks distribution drift, and renders an audit report
|
|
7
|
+
mapped to common AI-governance frameworks.
|
|
8
|
+
|
|
9
|
+
The core has one hard dependency (NumPy) so it runs anywhere on CPU. Plotting
|
|
10
|
+
and DataFrame export are optional extras.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
__version__ = "0.2.0"
|
|
16
|
+
|
|
17
|
+
from .hack import detect_hacking
|
|
18
|
+
from .judge import analyze_judge, classification_report, cohen_kappa, fleiss_kappa
|
|
19
|
+
from .leakage import identity_probe, near_duplicates, ngram_containment
|
|
20
|
+
from .monitoring import distribution_drift, ks_two_sample, psi
|
|
21
|
+
from .report import build_report, render_markdown, to_json
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"__version__",
|
|
25
|
+
"analyze_judge",
|
|
26
|
+
"cohen_kappa",
|
|
27
|
+
"fleiss_kappa",
|
|
28
|
+
"classification_report",
|
|
29
|
+
"ngram_containment",
|
|
30
|
+
"near_duplicates",
|
|
31
|
+
"identity_probe",
|
|
32
|
+
"detect_hacking",
|
|
33
|
+
"psi",
|
|
34
|
+
"ks_two_sample",
|
|
35
|
+
"distribution_drift",
|
|
36
|
+
"build_report",
|
|
37
|
+
"render_markdown",
|
|
38
|
+
"to_json",
|
|
39
|
+
]
|
defacto/__main__.py
ADDED
defacto/_stats.py
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
"""Dependency-free statistics used across DeFacto.
|
|
2
|
+
|
|
3
|
+
Everything here is implemented on NumPy plus the Python standard library so the
|
|
4
|
+
package has exactly one hard dependency and every number it emits is
|
|
5
|
+
reproducible and auditable. The normal-distribution quantiles use
|
|
6
|
+
``statistics.NormalDist`` (standard library) rather than SciPy.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from collections.abc import Callable, Sequence
|
|
12
|
+
from statistics import NormalDist
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
from numpy.typing import ArrayLike
|
|
16
|
+
|
|
17
|
+
_NORMAL = NormalDist()
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def norm_ppf(p: float) -> float:
|
|
21
|
+
"""Inverse normal CDF (quantile function) via the standard library."""
|
|
22
|
+
return float(_NORMAL.inv_cdf(p))
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def norm_cdf(x: float) -> float:
|
|
26
|
+
"""Normal CDF via the standard library."""
|
|
27
|
+
return float(_NORMAL.cdf(x))
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def pearson(x: ArrayLike, y: ArrayLike) -> float:
|
|
31
|
+
"""Pearson correlation coefficient."""
|
|
32
|
+
xa = np.asarray(x, dtype=float)
|
|
33
|
+
ya = np.asarray(y, dtype=float)
|
|
34
|
+
if xa.shape != ya.shape or xa.size == 0:
|
|
35
|
+
raise ValueError("x and y must be non-empty arrays of equal length")
|
|
36
|
+
xm = xa - xa.mean()
|
|
37
|
+
ym = ya - ya.mean()
|
|
38
|
+
den = float(np.sqrt((xm * xm).sum() * (ym * ym).sum()))
|
|
39
|
+
if den == 0.0:
|
|
40
|
+
return 0.0
|
|
41
|
+
return float((xm * ym).sum() / den)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def rankdata(a: ArrayLike) -> np.ndarray:
|
|
45
|
+
"""Return average ranks (ties get the mean of their ranks), SciPy-style."""
|
|
46
|
+
aa = np.asarray(a, dtype=float)
|
|
47
|
+
n = aa.size
|
|
48
|
+
if n == 0:
|
|
49
|
+
return np.empty(0, dtype=float)
|
|
50
|
+
sorter = np.argsort(aa, kind="mergesort")
|
|
51
|
+
sorted_a = aa[sorter]
|
|
52
|
+
obs = np.r_[True, sorted_a[1:] != sorted_a[:-1]]
|
|
53
|
+
starts = np.nonzero(obs)[0]
|
|
54
|
+
ranks = np.empty(n, dtype=float)
|
|
55
|
+
for k, start in enumerate(starts):
|
|
56
|
+
end = starts[k + 1] if k + 1 < starts.size else n
|
|
57
|
+
ranks[sorter[start:end]] = (start + end + 1) / 2.0
|
|
58
|
+
return ranks
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def spearman(x: ArrayLike, y: ArrayLike) -> float:
|
|
62
|
+
"""Spearman rank correlation coefficient."""
|
|
63
|
+
return pearson(rankdata(x), rankdata(y))
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _quantile(a: np.ndarray, q: float) -> float:
|
|
67
|
+
return float(np.quantile(a, q))
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def cluster_bootstrap(
|
|
71
|
+
groups: Sequence,
|
|
72
|
+
statistic: Callable[[Sequence], float],
|
|
73
|
+
n_bootstrap: int = 2000,
|
|
74
|
+
alpha: float = 0.05,
|
|
75
|
+
seed: int | None = 0,
|
|
76
|
+
method: str = "bca",
|
|
77
|
+
) -> dict:
|
|
78
|
+
"""Bootstrap a statistic by resampling whole clusters (groups) with replacement.
|
|
79
|
+
|
|
80
|
+
Cluster resampling preserves within-cluster dependence and is the correct
|
|
81
|
+
interval for grouped data (for example, multiple annotations per annotator,
|
|
82
|
+
multiple items per program or per prompt family).
|
|
83
|
+
|
|
84
|
+
Parameters
|
|
85
|
+
----------
|
|
86
|
+
groups:
|
|
87
|
+
The atomic sampling units. Each element is handed unchanged to
|
|
88
|
+
``statistic``; the statistic must accept a list of groups and return a
|
|
89
|
+
scalar (typically it flattens the groups and computes an estimator).
|
|
90
|
+
statistic:
|
|
91
|
+
Callable ``statistic(list_of_groups) -> float``.
|
|
92
|
+
n_bootstrap:
|
|
93
|
+
Number of bootstrap resamples.
|
|
94
|
+
alpha:
|
|
95
|
+
Two-sided confidence level is ``1 - alpha``.
|
|
96
|
+
seed:
|
|
97
|
+
RNG seed for reproducibility.
|
|
98
|
+
method:
|
|
99
|
+
``"bca"`` (bias-corrected and accelerated), ``"percentile"``, or
|
|
100
|
+
``"basic"``.
|
|
101
|
+
|
|
102
|
+
Returns
|
|
103
|
+
-------
|
|
104
|
+
dict
|
|
105
|
+
Keys: ``estimate``, ``lower``, ``upper``, ``se``, ``bias``, ``n``,
|
|
106
|
+
``method``, ``alpha``.
|
|
107
|
+
"""
|
|
108
|
+
groups = list(groups)
|
|
109
|
+
n = len(groups)
|
|
110
|
+
if n == 0:
|
|
111
|
+
raise ValueError("cluster_bootstrap requires at least one group")
|
|
112
|
+
rng = np.random.default_rng(seed)
|
|
113
|
+
observed = float(statistic(groups))
|
|
114
|
+
|
|
115
|
+
boot = np.empty(n_bootstrap, dtype=float)
|
|
116
|
+
for b in range(n_bootstrap):
|
|
117
|
+
sample = [groups[i] for i in rng.integers(0, n, size=n)]
|
|
118
|
+
boot[b] = statistic(sample)
|
|
119
|
+
|
|
120
|
+
se = float(boot.std(ddof=1))
|
|
121
|
+
bias = float(boot.mean() - observed)
|
|
122
|
+
|
|
123
|
+
if method == "percentile":
|
|
124
|
+
lower = _quantile(boot, alpha / 2.0)
|
|
125
|
+
upper = _quantile(boot, 1.0 - alpha / 2.0)
|
|
126
|
+
elif method == "basic":
|
|
127
|
+
lower = 2.0 * observed - _quantile(boot, 1.0 - alpha / 2.0)
|
|
128
|
+
upper = 2.0 * observed - _quantile(boot, alpha / 2.0)
|
|
129
|
+
elif method == "bca":
|
|
130
|
+
lower, upper = _bca(boot, observed, groups, statistic, alpha)
|
|
131
|
+
else:
|
|
132
|
+
raise ValueError(f"unknown method {method!r}")
|
|
133
|
+
|
|
134
|
+
return {
|
|
135
|
+
"estimate": observed,
|
|
136
|
+
"lower": lower,
|
|
137
|
+
"upper": upper,
|
|
138
|
+
"se": se,
|
|
139
|
+
"bias": bias,
|
|
140
|
+
"n": n,
|
|
141
|
+
"n_bootstrap": n_bootstrap,
|
|
142
|
+
"method": method,
|
|
143
|
+
"alpha": alpha,
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _bca(boot, observed, groups, statistic, alpha):
|
|
148
|
+
"""Bias-corrected and accelerated (BCa) interval from bootstrap replicates."""
|
|
149
|
+
p0 = float(np.mean(boot < observed))
|
|
150
|
+
# Guard against degenerate bootstrap distributions at the tails.
|
|
151
|
+
p0 = min(max(p0, 1.0 / (2.0 * boot.size)), 1.0 - 1.0 / (2.0 * boot.size))
|
|
152
|
+
z0 = norm_ppf(p0)
|
|
153
|
+
|
|
154
|
+
n = len(groups)
|
|
155
|
+
jack = np.empty(n, dtype=float)
|
|
156
|
+
for i in range(n):
|
|
157
|
+
jack[i] = statistic(groups[:i] + groups[i + 1 :])
|
|
158
|
+
theta_dot = float(jack.mean())
|
|
159
|
+
centered = theta_dot - jack
|
|
160
|
+
num = float(np.sum(centered**3))
|
|
161
|
+
den = float(6.0 * (np.sum(centered**2) ** 1.5))
|
|
162
|
+
accel = num / den if den != 0.0 else 0.0
|
|
163
|
+
|
|
164
|
+
za = norm_ppf(alpha / 2.0)
|
|
165
|
+
zb = norm_ppf(1.0 - alpha / 2.0)
|
|
166
|
+
al1 = norm_cdf(z0 + (z0 + za) / (1.0 - accel * (z0 + za)))
|
|
167
|
+
al2 = norm_cdf(z0 + (z0 + zb) / (1.0 - accel * (z0 + zb)))
|
|
168
|
+
al1 = float(np.clip(al1, 0.0, 1.0))
|
|
169
|
+
al2 = float(np.clip(al2, 0.0, 1.0))
|
|
170
|
+
return _quantile(boot, al1), _quantile(boot, al2)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def permutation_test(
|
|
174
|
+
statistic: Callable[[ArrayLike, ArrayLike], float],
|
|
175
|
+
x: ArrayLike,
|
|
176
|
+
y: ArrayLike,
|
|
177
|
+
n_permutations: int = 1000,
|
|
178
|
+
seed: int | None = 0,
|
|
179
|
+
alternative: str = "greater",
|
|
180
|
+
) -> dict:
|
|
181
|
+
"""Permutation test of ``statistic(x, y)`` against a label-shuffled null.
|
|
182
|
+
|
|
183
|
+
``alternative`` is ``"greater"``, ``"less"`` or ``"two-sided"``. The p-value
|
|
184
|
+
is the standard Monte Carlo ``(1 + count) / (n_permutations + 1)`` so it can
|
|
185
|
+
never report an exact zero.
|
|
186
|
+
"""
|
|
187
|
+
xa = np.asarray(x)
|
|
188
|
+
ya = np.asarray(y)
|
|
189
|
+
if len(xa) != len(ya):
|
|
190
|
+
raise ValueError("x and y must have equal length")
|
|
191
|
+
rng = np.random.default_rng(seed)
|
|
192
|
+
observed = float(statistic(xa, ya))
|
|
193
|
+
nulls = np.empty(n_permutations, dtype=float)
|
|
194
|
+
for p in range(n_permutations):
|
|
195
|
+
nulls[p] = statistic(xa, rng.permutation(ya))
|
|
196
|
+
|
|
197
|
+
if alternative == "greater":
|
|
198
|
+
count = int(np.sum(nulls >= observed))
|
|
199
|
+
elif alternative == "less":
|
|
200
|
+
count = int(np.sum(nulls <= observed))
|
|
201
|
+
elif alternative == "two-sided":
|
|
202
|
+
center = float(nulls.mean())
|
|
203
|
+
count = int(np.sum(np.abs(nulls - center) >= np.abs(observed - center)))
|
|
204
|
+
else:
|
|
205
|
+
raise ValueError(f"unknown alternative {alternative!r}")
|
|
206
|
+
|
|
207
|
+
return {
|
|
208
|
+
"observed": observed,
|
|
209
|
+
"p_value": (1.0 + count) / (n_permutations + 1.0),
|
|
210
|
+
"null_mean": float(nulls.mean()),
|
|
211
|
+
"null_std": float(nulls.std(ddof=1)) if n_permutations > 1 else 0.0,
|
|
212
|
+
"n_permutations": n_permutations,
|
|
213
|
+
"alternative": alternative,
|
|
214
|
+
}
|
defacto/cli.py
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
"""Command-line interface for DeFacto."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import csv
|
|
7
|
+
import io
|
|
8
|
+
import sys
|
|
9
|
+
|
|
10
|
+
from . import __version__
|
|
11
|
+
from .hack import detect_hacking
|
|
12
|
+
from .io import load, load_numbers, load_records
|
|
13
|
+
from .judge import analyze_judge
|
|
14
|
+
from .leakage import identity_probe, ngram_containment
|
|
15
|
+
from .monitoring import distribution_drift
|
|
16
|
+
from .report import (
|
|
17
|
+
build_report,
|
|
18
|
+
contamination_findings,
|
|
19
|
+
drift_findings,
|
|
20
|
+
findings_table,
|
|
21
|
+
hacking_findings,
|
|
22
|
+
judge_findings,
|
|
23
|
+
probe_findings,
|
|
24
|
+
render_markdown,
|
|
25
|
+
to_json,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _emit(report: dict, fmt: str, output: str | None) -> None:
|
|
30
|
+
if fmt == "json":
|
|
31
|
+
text = to_json(report)
|
|
32
|
+
elif fmt == "csv":
|
|
33
|
+
_emit_csv(report, output)
|
|
34
|
+
return
|
|
35
|
+
else:
|
|
36
|
+
text = render_markdown(report)
|
|
37
|
+
if output:
|
|
38
|
+
with open(output, "w", encoding="utf-8") as f:
|
|
39
|
+
f.write(text + "\n")
|
|
40
|
+
print(f"wrote {output}", file=sys.stderr)
|
|
41
|
+
else:
|
|
42
|
+
print(text)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _emit_csv(report: dict, output: str | None) -> None:
|
|
46
|
+
rows = findings_table(report)
|
|
47
|
+
fieldnames = sorted({k for r in rows for k in r})
|
|
48
|
+
buf = io.StringIO()
|
|
49
|
+
writer = csv.DictWriter(buf, fieldnames=fieldnames)
|
|
50
|
+
writer.writeheader()
|
|
51
|
+
writer.writerows(rows)
|
|
52
|
+
if output:
|
|
53
|
+
with open(output, "w", encoding="utf-8", newline="") as f:
|
|
54
|
+
f.write(buf.getvalue())
|
|
55
|
+
print(f"wrote {output}", file=sys.stderr)
|
|
56
|
+
else:
|
|
57
|
+
print(buf.getvalue(), end="")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _has(records: list, key: str) -> bool:
|
|
61
|
+
return any(key in r for r in records)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _save_plot(fig, path: str) -> None:
|
|
65
|
+
import matplotlib
|
|
66
|
+
|
|
67
|
+
matplotlib.use("Agg", force=True)
|
|
68
|
+
fig.savefig(path, dpi=150, bbox_inches="tight")
|
|
69
|
+
print(f"wrote {path}", file=sys.stderr)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _plot_judge(gold, judge, confidence, path: str) -> None:
|
|
73
|
+
from .viz import judge_dashboard
|
|
74
|
+
|
|
75
|
+
_save_plot(judge_dashboard(gold, judge, confidence=confidence), path)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _plot_hack(rewards, successes, steps, path: str) -> None:
|
|
79
|
+
from .viz import reward_success_scatter
|
|
80
|
+
|
|
81
|
+
_save_plot(reward_success_scatter(rewards, successes), path)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _plot_contamination(result, path: str) -> None:
|
|
85
|
+
from .viz import containment_histogram
|
|
86
|
+
|
|
87
|
+
vals = [r["max_containment"] for r in result["per_test"]]
|
|
88
|
+
_save_plot(containment_histogram(vals), path)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _cmd_judge(args) -> int:
|
|
92
|
+
records = load_records(args.records)
|
|
93
|
+
if not records:
|
|
94
|
+
print("no records", file=sys.stderr)
|
|
95
|
+
return 1
|
|
96
|
+
gold = [r["gold"] for r in records]
|
|
97
|
+
judge = [r.get("judge") for r in records]
|
|
98
|
+
confidence = [r["confidence"] for r in records] if _has(records, "confidence") else None
|
|
99
|
+
groups = [r.get("group") for r in records] if _has(records, "group") else None
|
|
100
|
+
clusters = [r.get("cluster") for r in records] if _has(records, "cluster") else None
|
|
101
|
+
result = analyze_judge(
|
|
102
|
+
gold,
|
|
103
|
+
judge,
|
|
104
|
+
confidence=confidence,
|
|
105
|
+
groups=groups,
|
|
106
|
+
clusters=clusters,
|
|
107
|
+
n_bootstrap=args.n_bootstrap,
|
|
108
|
+
seed=args.seed,
|
|
109
|
+
confident_threshold=args.threshold,
|
|
110
|
+
)
|
|
111
|
+
report = build_report(args.records, judge_findings(result))
|
|
112
|
+
_emit(report, args.format, args.output)
|
|
113
|
+
if args.plot:
|
|
114
|
+
_plot_judge(gold, judge, confidence, args.plot)
|
|
115
|
+
return 0
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _cmd_contamination(args) -> int:
|
|
119
|
+
train = load(args.train)
|
|
120
|
+
test = load(args.test)
|
|
121
|
+
result = ngram_containment(train, test, n=args.n, tokenizer=args.tokenizer)
|
|
122
|
+
report = build_report(f"{args.train} vs {args.test}", contamination_findings(result))
|
|
123
|
+
_emit(report, args.format, args.output)
|
|
124
|
+
if args.plot:
|
|
125
|
+
_plot_contamination(result, args.plot)
|
|
126
|
+
return 0
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _cmd_probe(args) -> int:
|
|
130
|
+
texts = load(args.texts)
|
|
131
|
+
groups = load(args.groups)
|
|
132
|
+
clusters = load(args.clusters) if args.clusters else None
|
|
133
|
+
result = identity_probe(
|
|
134
|
+
texts=texts,
|
|
135
|
+
groups=groups,
|
|
136
|
+
clusters=clusters,
|
|
137
|
+
n=args.n,
|
|
138
|
+
tokenizer=args.tokenizer,
|
|
139
|
+
n_bootstrap=args.n_bootstrap,
|
|
140
|
+
n_permutations=args.n_permutations,
|
|
141
|
+
seed=args.seed,
|
|
142
|
+
)
|
|
143
|
+
report = build_report(args.texts, probe_findings(result))
|
|
144
|
+
_emit(report, args.format, args.output)
|
|
145
|
+
return 0
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _cmd_hack(args) -> int:
|
|
149
|
+
records = load_records(args.records)
|
|
150
|
+
rewards = [r["reward"] for r in records]
|
|
151
|
+
successes = [r["success"] for r in records]
|
|
152
|
+
steps = [r["step"] for r in records] if _has(records, "step") else None
|
|
153
|
+
result = detect_hacking(
|
|
154
|
+
rewards, successes, steps=steps, seed=args.seed, n_permutations=args.n_permutations
|
|
155
|
+
)
|
|
156
|
+
report = build_report(args.records, hacking_findings(result))
|
|
157
|
+
_emit(report, args.format, args.output)
|
|
158
|
+
if args.plot:
|
|
159
|
+
_plot_hack(rewards, successes, steps, args.plot)
|
|
160
|
+
return 0
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _cmd_drift(args) -> int:
|
|
164
|
+
expected = load_numbers(args.expected)
|
|
165
|
+
actual = load_numbers(args.actual)
|
|
166
|
+
result = distribution_drift(expected, actual, bins=args.bins)
|
|
167
|
+
report = build_report(f"{args.expected} vs {args.actual}", drift_findings(result))
|
|
168
|
+
_emit(report, args.format, args.output)
|
|
169
|
+
return 0
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _cmd_report(args) -> int:
|
|
173
|
+
import json
|
|
174
|
+
|
|
175
|
+
with open(args.findings, encoding="utf-8") as f:
|
|
176
|
+
report = json.load(f)
|
|
177
|
+
_emit(report, args.format, args.output)
|
|
178
|
+
return 0
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
182
|
+
p = argparse.ArgumentParser(
|
|
183
|
+
prog="defacto",
|
|
184
|
+
description="Evaluation-integrity and verifier-audit toolkit for LLM systems.",
|
|
185
|
+
)
|
|
186
|
+
p.add_argument("--version", action="version", version=f"defacto {__version__}")
|
|
187
|
+
sub = p.add_subparsers(dest="command", required=True)
|
|
188
|
+
|
|
189
|
+
def common(sp):
|
|
190
|
+
sp.add_argument("--output", "-o", default=None, help="output file (default: stdout)")
|
|
191
|
+
sp.add_argument("--format", choices=["markdown", "json", "csv"], default="markdown")
|
|
192
|
+
|
|
193
|
+
j = sub.add_parser("judge", help="analyze an LLM judge or reward model vs gold labels")
|
|
194
|
+
j.add_argument("records", help="JSON: list of {gold, judge, confidence?, group?, cluster?}")
|
|
195
|
+
j.add_argument("--threshold", type=float, default=0.8, help="confident-error threshold")
|
|
196
|
+
j.add_argument("--n-bootstrap", type=int, default=2000)
|
|
197
|
+
j.add_argument("--seed", type=int, default=0)
|
|
198
|
+
j.add_argument("--plot", default=None, help="save a dashboard figure to this path")
|
|
199
|
+
common(j)
|
|
200
|
+
j.set_defaults(func=_cmd_judge)
|
|
201
|
+
|
|
202
|
+
c = sub.add_parser("contamination", help="n-gram contamination between train and test text")
|
|
203
|
+
c.add_argument("--train", required=True, help="train texts (JSON array or one-per-line)")
|
|
204
|
+
c.add_argument("--test", required=True, help="test texts (JSON array or one-per-line)")
|
|
205
|
+
c.add_argument("--n", type=int, default=13, help="n-gram size")
|
|
206
|
+
c.add_argument("--tokenizer", choices=["word", "char"], default="word")
|
|
207
|
+
c.add_argument("--plot", default=None, help="save a containment histogram to this path")
|
|
208
|
+
common(c)
|
|
209
|
+
c.set_defaults(func=_cmd_contamination)
|
|
210
|
+
|
|
211
|
+
pr = sub.add_parser("probe", help="group-identity leakage probe on text")
|
|
212
|
+
pr.add_argument("--texts", required=True, help="texts (JSON array or one-per-line)")
|
|
213
|
+
pr.add_argument("--groups", required=True, help="group label per text")
|
|
214
|
+
pr.add_argument("--clusters", default=None, help="optional cluster id per text")
|
|
215
|
+
pr.add_argument("--n", type=int, default=3, help="n-gram size for features")
|
|
216
|
+
pr.add_argument("--tokenizer", choices=["word", "char"], default="word")
|
|
217
|
+
pr.add_argument("--n-bootstrap", type=int, default=2000)
|
|
218
|
+
pr.add_argument("--n-permutations", type=int, default=1000)
|
|
219
|
+
pr.add_argument("--seed", type=int, default=0)
|
|
220
|
+
common(pr)
|
|
221
|
+
pr.set_defaults(func=_cmd_probe)
|
|
222
|
+
|
|
223
|
+
h = sub.add_parser("hack", help="detect reward hacking vs verifiable success")
|
|
224
|
+
h.add_argument("records", help="JSON: list of {reward, success, step?}")
|
|
225
|
+
h.add_argument("--n-permutations", type=int, default=1000)
|
|
226
|
+
h.add_argument("--seed", type=int, default=0)
|
|
227
|
+
h.add_argument("--plot", default=None, help="save a reward-success scatter to this path")
|
|
228
|
+
common(h)
|
|
229
|
+
h.set_defaults(func=_cmd_hack)
|
|
230
|
+
|
|
231
|
+
d = sub.add_parser("drift", help="measure distribution drift between two score sets")
|
|
232
|
+
d.add_argument(
|
|
233
|
+
"--expected", required=True, help="reference scores (JSON array or one-per-line)"
|
|
234
|
+
)
|
|
235
|
+
d.add_argument("--actual", required=True, help="monitoring scores (JSON array or one-per-line)")
|
|
236
|
+
d.add_argument("--bins", type=int, default=10, help="PSI bin count")
|
|
237
|
+
common(d)
|
|
238
|
+
d.set_defaults(func=_cmd_drift)
|
|
239
|
+
|
|
240
|
+
r = sub.add_parser("report", help="render an existing findings JSON")
|
|
241
|
+
r.add_argument("findings", help="findings JSON file")
|
|
242
|
+
common(r)
|
|
243
|
+
r.set_defaults(func=_cmd_report)
|
|
244
|
+
|
|
245
|
+
return p
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def main(argv: list[str] | None = None) -> int:
|
|
249
|
+
parser = build_parser()
|
|
250
|
+
args = parser.parse_args(argv)
|
|
251
|
+
return args.func(args)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
if __name__ == "__main__":
|
|
255
|
+
raise SystemExit(main())
|
defacto/hack/__init__.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Reward-hacking and reward-model drift detection."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from .reward import (
|
|
6
|
+
detect_hacking,
|
|
7
|
+
reward_drift,
|
|
8
|
+
reward_success_gap,
|
|
9
|
+
success_by_reward_quartile,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
"detect_hacking",
|
|
14
|
+
"reward_drift",
|
|
15
|
+
"reward_success_gap",
|
|
16
|
+
"success_by_reward_quartile",
|
|
17
|
+
]
|
defacto/hack/reward.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"""Reward-hacking and reward-model drift detection.
|
|
2
|
+
|
|
3
|
+
A reward signal is only trustworthy if it tracks *verifiable* task success.
|
|
4
|
+
When a policy (or a reward model) learns to inflate reward without solving the
|
|
5
|
+
task, reward and success diverge. These metrics quantify that divergence and
|
|
6
|
+
flag it as a silent failure: high reward, low success.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
from numpy.typing import ArrayLike
|
|
13
|
+
|
|
14
|
+
from .._stats import pearson, permutation_test, spearman
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def success_by_reward_quartile(
|
|
18
|
+
rewards: ArrayLike, successes: ArrayLike, n_quartiles: int = 4
|
|
19
|
+
) -> list | None:
|
|
20
|
+
"""Success rate within reward quartiles (binary successes only).
|
|
21
|
+
|
|
22
|
+
A healthy reward model shows success rising with reward. A flat or inverted
|
|
23
|
+
profile is a reward-hacking signal.
|
|
24
|
+
"""
|
|
25
|
+
r = np.asarray(rewards, dtype=float)
|
|
26
|
+
s = np.asarray(successes, dtype=float)
|
|
27
|
+
if not np.all(np.isin(s, [0.0, 1.0])):
|
|
28
|
+
return None
|
|
29
|
+
edges = np.quantile(r, np.linspace(0.0, 1.0, n_quartiles + 1))
|
|
30
|
+
edges[-1] += 1e-9
|
|
31
|
+
bins = np.digitize(r, edges[1:-1])
|
|
32
|
+
out = []
|
|
33
|
+
for q in range(n_quartiles):
|
|
34
|
+
sel = bins == q
|
|
35
|
+
out.append(
|
|
36
|
+
{
|
|
37
|
+
"quartile": q,
|
|
38
|
+
"n": int(sel.sum()),
|
|
39
|
+
"mean_reward": float(r[sel].mean()) if sel.any() else float("nan"),
|
|
40
|
+
"success_rate": float(s[sel].mean()) if sel.any() else float("nan"),
|
|
41
|
+
}
|
|
42
|
+
)
|
|
43
|
+
return out
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def reward_success_gap(
|
|
47
|
+
rewards: ArrayLike,
|
|
48
|
+
successes: ArrayLike,
|
|
49
|
+
seed: int = 0,
|
|
50
|
+
n_permutations: int = 1000,
|
|
51
|
+
) -> dict:
|
|
52
|
+
"""Correlation between reward and verifiable success, and the reward gap.
|
|
53
|
+
|
|
54
|
+
``successes`` may be binary (0/1) or a continuous verifiable score in
|
|
55
|
+
[0, 1]. For binary success, the mean-reward gap between successful and
|
|
56
|
+
failed items is also reported.
|
|
57
|
+
"""
|
|
58
|
+
r = np.asarray(rewards, dtype=float)
|
|
59
|
+
s = np.asarray(successes, dtype=float)
|
|
60
|
+
if r.shape != s.shape:
|
|
61
|
+
raise ValueError("rewards and successes must have equal length")
|
|
62
|
+
n = r.size
|
|
63
|
+
if n == 0:
|
|
64
|
+
return {"n": 0}
|
|
65
|
+
pr = pearson(r, s)
|
|
66
|
+
sr = spearman(r, s)
|
|
67
|
+
perm = permutation_test(
|
|
68
|
+
pearson, r, s, n_permutations=n_permutations, seed=seed, alternative="two-sided"
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
result = {
|
|
72
|
+
"n": n,
|
|
73
|
+
"pearson_r": pr,
|
|
74
|
+
"spearman_rho": sr,
|
|
75
|
+
"p_value": perm["p_value"],
|
|
76
|
+
"null_mean": perm["null_mean"],
|
|
77
|
+
"mean_reward": float(r.mean()),
|
|
78
|
+
"mean_success": float(s.mean()),
|
|
79
|
+
"success_by_reward_quartile": success_by_reward_quartile(r, s),
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if np.all(np.isin(s, [0.0, 1.0])):
|
|
83
|
+
succ = s == 1.0
|
|
84
|
+
ms = float(r[succ].mean()) if succ.any() else float("nan")
|
|
85
|
+
mf = float(r[~succ].mean()) if (~succ).any() else float("nan")
|
|
86
|
+
result["mean_reward_success"] = ms
|
|
87
|
+
result["mean_reward_failure"] = mf
|
|
88
|
+
result["reward_gap"] = ms - mf if not np.isnan(ms) and not np.isnan(mf) else float("nan")
|
|
89
|
+
return result
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def reward_drift(
|
|
93
|
+
rewards: ArrayLike,
|
|
94
|
+
steps: ArrayLike | None = None,
|
|
95
|
+
seed: int = 0,
|
|
96
|
+
n_permutations: int = 1000,
|
|
97
|
+
) -> dict:
|
|
98
|
+
"""Trend of reward over time/steps (reward inflation or collapse)."""
|
|
99
|
+
r = np.asarray(rewards, dtype=float)
|
|
100
|
+
st = np.arange(len(r)) if steps is None else np.asarray(steps, dtype=float)
|
|
101
|
+
if len(r) != len(st):
|
|
102
|
+
raise ValueError("rewards and steps must have equal length")
|
|
103
|
+
n = len(r)
|
|
104
|
+
if n < 2:
|
|
105
|
+
return {"n": n, "slope": float("nan"), "intercept": float("nan")}
|
|
106
|
+
A = np.vstack([st, np.ones_like(st)]).T
|
|
107
|
+
coef, *_ = np.linalg.lstsq(A, r, rcond=None)
|
|
108
|
+
pr = pearson(st, r)
|
|
109
|
+
perm = permutation_test(
|
|
110
|
+
pearson, st, r, n_permutations=n_permutations, seed=seed, alternative="two-sided"
|
|
111
|
+
)
|
|
112
|
+
return {
|
|
113
|
+
"n": n,
|
|
114
|
+
"slope": float(coef[0]),
|
|
115
|
+
"intercept": float(coef[1]),
|
|
116
|
+
"pearson_r": pr,
|
|
117
|
+
"p_value": perm["p_value"],
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def detect_hacking(
|
|
122
|
+
rewards: ArrayLike,
|
|
123
|
+
successes: ArrayLike,
|
|
124
|
+
steps: ArrayLike | None = None,
|
|
125
|
+
seed: int = 0,
|
|
126
|
+
n_permutations: int = 1000,
|
|
127
|
+
alpha: float = 0.05,
|
|
128
|
+
min_n: int = 20,
|
|
129
|
+
) -> dict:
|
|
130
|
+
"""Combine reward-success gap and drift into a hacking verdict.
|
|
131
|
+
|
|
132
|
+
The verdict uses the two-sided permutation p-value of the reward-success
|
|
133
|
+
correlation, not a hard correlation cutoff:
|
|
134
|
+
|
|
135
|
+
- ``insufficient_data`` when fewer than ``min_n`` items are present.
|
|
136
|
+
- ``reward_does_not_track_success`` when the correlation is significantly
|
|
137
|
+
negative.
|
|
138
|
+
- ``no_hacking_signal`` when the correlation is significantly positive.
|
|
139
|
+
- ``weak_reward_success_signal`` when no significant link exists in either
|
|
140
|
+
direction.
|
|
141
|
+
"""
|
|
142
|
+
gap = reward_success_gap(rewards, successes, seed=seed, n_permutations=n_permutations)
|
|
143
|
+
drift = (
|
|
144
|
+
reward_drift(rewards, steps, seed=seed, n_permutations=n_permutations)
|
|
145
|
+
if steps is not None
|
|
146
|
+
else None
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
n = gap.get("n", 0)
|
|
150
|
+
pr = gap.get("pearson_r")
|
|
151
|
+
pv = gap.get("p_value")
|
|
152
|
+
if n < min_n or pr is None or pv is None:
|
|
153
|
+
verdict, severity = "insufficient_data", "info"
|
|
154
|
+
elif pr > 0.0 and pv <= alpha:
|
|
155
|
+
verdict, severity = "no_hacking_signal", "low"
|
|
156
|
+
elif pr < 0.0 and pv <= alpha:
|
|
157
|
+
verdict, severity = "reward_does_not_track_success", "high"
|
|
158
|
+
else:
|
|
159
|
+
verdict, severity = "weak_reward_success_signal", "medium"
|
|
160
|
+
|
|
161
|
+
return {
|
|
162
|
+
"reward_success_gap": gap,
|
|
163
|
+
"reward_drift": drift,
|
|
164
|
+
"verdict": verdict,
|
|
165
|
+
"severity": severity,
|
|
166
|
+
"alpha": alpha,
|
|
167
|
+
"min_n": min_n,
|
|
168
|
+
}
|