evalsuite-python 0.6.0__cp39-abi3-win_amd64.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.
Files changed (72) hide show
  1. evalsuite/__init__.py +268 -0
  2. evalsuite/__main__.py +5 -0
  3. evalsuite/_bench_metrics.py +2080 -0
  4. evalsuite/_core.pyd +0 -0
  5. evalsuite/_lazy.py +32 -0
  6. evalsuite/_native.py +60 -0
  7. evalsuite/api.py +275 -0
  8. evalsuite/benchmarks.py +946 -0
  9. evalsuite/calibration.py +392 -0
  10. evalsuite/classification/__init__.py +51 -0
  11. evalsuite/classification/_common.py +111 -0
  12. evalsuite/classification/metrics.py +945 -0
  13. evalsuite/cli/__init__.py +5 -0
  14. evalsuite/cli/main.py +606 -0
  15. evalsuite/clinical/__init__.py +18 -0
  16. evalsuite/clinical/metrics.py +342 -0
  17. evalsuite/clinical/report.py +366 -0
  18. evalsuite/core/__init__.py +1 -0
  19. evalsuite/core/context.py +199 -0
  20. evalsuite/core/exceptions.py +52 -0
  21. evalsuite/core/export.py +100 -0
  22. evalsuite/core/registry.py +90 -0
  23. evalsuite/core/result.py +379 -0
  24. evalsuite/core/types.py +23 -0
  25. evalsuite/core/validation.py +256 -0
  26. evalsuite/llmsys/__init__.py +189 -0
  27. evalsuite/llmsys/_common.py +215 -0
  28. evalsuite/llmsys/agents.py +384 -0
  29. evalsuite/llmsys/code.py +923 -0
  30. evalsuite/llmsys/efficiency.py +346 -0
  31. evalsuite/llmsys/longcontext.py +361 -0
  32. evalsuite/llmsys/multilingual.py +339 -0
  33. evalsuite/llmsys/robustness.py +504 -0
  34. evalsuite/llmsys/safety.py +509 -0
  35. evalsuite/llmsys/uncertainty.py +229 -0
  36. evalsuite/plot.py +651 -0
  37. evalsuite/py.typed +0 -0
  38. evalsuite/regression/__init__.py +41 -0
  39. evalsuite/regression/metrics.py +629 -0
  40. evalsuite/reporting.py +241 -0
  41. evalsuite/stats/__init__.py +46 -0
  42. evalsuite/stats/_resolve.py +229 -0
  43. evalsuite/stats/compare.py +420 -0
  44. evalsuite/stats/effect.py +159 -0
  45. evalsuite/stats/hypothesis.py +593 -0
  46. evalsuite/stats/intervals.py +338 -0
  47. evalsuite/stats/paired.py +214 -0
  48. evalsuite/stats/results.py +129 -0
  49. evalsuite/text/__init__.py +154 -0
  50. evalsuite/text/_common.py +97 -0
  51. evalsuite/text/factuality.py +469 -0
  52. evalsuite/text/generation.py +1346 -0
  53. evalsuite/text/judge.py +556 -0
  54. evalsuite/text/qa.py +108 -0
  55. evalsuite/text/rag.py +235 -0
  56. evalsuite/text/reasoning.py +215 -0
  57. evalsuite/text/report.py +158 -0
  58. evalsuite/text/retrieval.py +238 -0
  59. evalsuite/text/semantic.py +499 -0
  60. evalsuite/text/spice.py +162 -0
  61. evalsuite/text/structured.py +793 -0
  62. evalsuite/version.py +3 -0
  63. evalsuite/vision/__init__.py +47 -0
  64. evalsuite/vision/detection.py +696 -0
  65. evalsuite/vision/segmentation.py +1028 -0
  66. evalsuite_python-0.6.0.dist-info/METADATA +509 -0
  67. evalsuite_python-0.6.0.dist-info/RECORD +72 -0
  68. evalsuite_python-0.6.0.dist-info/WHEEL +4 -0
  69. evalsuite_python-0.6.0.dist-info/entry_points.txt +2 -0
  70. evalsuite_python-0.6.0.dist-info/licenses/LICENSE +21 -0
  71. evalsuite_python-0.6.0.dist-info/licenses/LICENSE-APACHE +191 -0
  72. evalsuite_python-0.6.0.dist-info/sboms/evalsuite-py.cyclonedx.json +576 -0
@@ -0,0 +1,509 @@
1
+ """Safety, security and responsible AI (v0.5.0).
2
+
3
+ The verdicts these functions aggregate (harmful or not, refused or not, attack succeeded or not, toxicity
4
+ scores, policy labels) come from your own classifier, LLM judge or human annotation; EvalSuite turns them into
5
+ rates with confidence intervals and breakdowns. Two measures are computed from raw material directly: PII
6
+ leakage (built-in detectors, including Luhn-checked card numbers) and memorization exposure (Carlini et al.).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import math
12
+ import re
13
+ from collections.abc import Mapping, Sequence
14
+ from typing import Any, Optional
15
+
16
+ import numpy as np
17
+
18
+ from ..core.exceptions import InputValidationError
19
+ from ..core.registry import register
20
+ from ..core.result import MetricResult
21
+ from ._common import bools, by_group, floats, lists_of, rate, same_length, seq, wilson
22
+
23
+ __all__ = [
24
+ "PII_PATTERNS",
25
+ "attack_success_rate",
26
+ "detect_pii",
27
+ "exposure",
28
+ "harmful_response_rate",
29
+ "over_refusal_rate",
30
+ "pii_leakage_rate",
31
+ "policy_violation_rate",
32
+ "red_team_success_rate",
33
+ "refusal_rate",
34
+ "stereotype_preference",
35
+ "toxicity_score",
36
+ "weat_effect_size",
37
+ ]
38
+
39
+ _C = "safety"
40
+ _REF_HARMBENCH = (
41
+ "Mazeika M, Phan L, Yin X, et al. HarmBench: a standardized evaluation framework for automated red teaming "
42
+ "and robust refusal. ICML. 2024."
43
+ )
44
+ _REF_XSTEST = (
45
+ "Röttger P, Kirk HR, Vidgen B, et al. XSTest: a test suite for identifying exaggerated safety behaviours in "
46
+ "large language models. NAACL. 2024:5377-5400."
47
+ )
48
+ _REF_RTP = (
49
+ "Gehman S, Gururangan S, Sap M, Choi Y, Smith NA. RealToxicityPrompts: evaluating neural toxic degeneration "
50
+ "in language models. Findings of EMNLP. 2020:3356-3369."
51
+ )
52
+ _REF_CROWS = (
53
+ "Nangia N, Vania C, Bhalerao R, Bowman SR. CrowS-Pairs: a challenge dataset for measuring social biases in "
54
+ "masked language models. EMNLP. 2020:1953-1967."
55
+ )
56
+ _REF_WEAT = (
57
+ "Caliskan A, Bryson JJ, Narayanan A. Semantics derived automatically from language corpora contain human-like "
58
+ "biases. Science. 2017;356(6334):183-186."
59
+ )
60
+ _REF_EXPOSURE = (
61
+ "Carlini N, Liu C, Erlingsson Ú, Kos J, Song D. The secret sharer: evaluating and testing unintended "
62
+ "memorization in neural networks. USENIX Security. 2019:267-284."
63
+ )
64
+ _REF_INJECTION = (
65
+ "Liu Y, Jia Y, Geng R, Jia J, Gong NZ. Formalizing and benchmarking prompt injection attacks and defenses. "
66
+ "USENIX Security. 2024."
67
+ )
68
+ _REF_PERSPECTIVE = (
69
+ "Lees A, Tran VQ, Tay Y, et al. A new generation of Perspective API: efficient multilingual character-level "
70
+ "transformers. KDD. 2022:3197-3207."
71
+ )
72
+ _REF_GANGULI = (
73
+ "Ganguli D, Lovitt L, Kernion J, et al. Red teaming language models to reduce harms: methods, scaling "
74
+ "behaviors, and lessons learned. arXiv:2209.07858. 2022."
75
+ )
76
+
77
+
78
+ def _masked(flags: np.ndarray, mask: Optional[np.ndarray], what: str) -> np.ndarray:
79
+ if mask is None:
80
+ return flags
81
+ if not mask.any():
82
+ raise InputValidationError(f"No {what} examples: the rate is undefined.")
83
+ return np.asarray(flags[mask], dtype=bool)
84
+
85
+
86
+ @register(
87
+ category=_C,
88
+ task="safety",
89
+ name="Harmful response rate",
90
+ definition="Share of responses judged harmful. Given which prompts request harmful content, it is the "
91
+ "unsafe compliance rate: harmful responses among harmful prompts (HarmBench attack success).",
92
+ formula="harmful responses / responses (restricted to harmful prompts when given)",
93
+ range="[0, 1]",
94
+ input_requirements=("harmful",),
95
+ references=(_REF_HARMBENCH,),
96
+ higher_is_better=False,
97
+ )
98
+ def harmful_response_rate(
99
+ harmful: Any, *, harmful_prompt: Any = None, categories: Optional[Sequence[Any]] = None
100
+ ) -> MetricResult:
101
+ """``harmful``: one verdict per response. ``harmful_prompt`` (optional): whether each prompt asked for
102
+ harmful content; the rate is then over those prompts only. ``categories``: per-category rates."""
103
+ h = bools(harmful, "harmful")
104
+ mask = None
105
+ if harmful_prompt is not None:
106
+ mask = bools(harmful_prompt, "harmful_prompt")
107
+ same_length(("harmful", h), ("harmful_prompt", mask))
108
+ extra: dict[str, Any] = {"unsafe_compliance": mask is not None}
109
+ if categories is not None:
110
+ cats = seq(categories, "categories")
111
+ same_length(("harmful", h), ("categories", cats))
112
+ if mask is not None:
113
+ cats = [c for c, m in zip(cats, mask) if m]
114
+ extra["by_category"] = by_group(_masked(h, mask, "harmful-prompt").astype(float), cats)
115
+ return rate("harmful_response_rate", "Harmful response rate", _masked(h, mask, "harmful-prompt"), extra)
116
+
117
+
118
+ @register(
119
+ category=_C,
120
+ task="safety",
121
+ name="Refusal rate",
122
+ definition="Share of prompts the model refuses. Given which prompts should be refused, the value is the "
123
+ "appropriate refusal rate (refusals among should-refuse prompts) and precision and F1 are reported.",
124
+ formula="refused / prompts, or refused ∧ should_refuse / should_refuse",
125
+ range="[0, 1]",
126
+ input_requirements=("refused",),
127
+ references=(_REF_XSTEST, _REF_HARMBENCH),
128
+ )
129
+ def refusal_rate(refused: Any, *, should_refuse: Any = None) -> MetricResult:
130
+ r = bools(refused, "refused")
131
+ if should_refuse is None:
132
+ return rate("refusal_rate", "Refusal rate", r, {"appropriate": False})
133
+ s = bools(should_refuse, "should_refuse")
134
+ same_length(("refused", r), ("should_refuse", s))
135
+ if not s.any():
136
+ raise InputValidationError("No prompt should be refused: the appropriate refusal rate is undefined.")
137
+ tp = int((r & s).sum())
138
+ precision = tp / int(r.sum()) if r.any() else math.nan
139
+ recall = tp / int(s.sum())
140
+ f1 = 2 * precision * recall / (precision + recall) if r.any() and precision + recall > 0 else 0.0
141
+ return rate(
142
+ "refusal_rate",
143
+ "Appropriate refusal rate",
144
+ r[s],
145
+ {"appropriate": True, "precision": precision, "f1": f1, "overall_refusal_rate": float(r.mean())},
146
+ )
147
+
148
+
149
+ @register(
150
+ category=_C,
151
+ task="safety",
152
+ name="Over-refusal rate",
153
+ definition="Share of safe prompts the model refuses (exaggerated safety, XSTest): refusals among prompts "
154
+ "that should be answered.",
155
+ formula="refused ∧ ¬should_refuse / ¬should_refuse",
156
+ range="[0, 1]",
157
+ input_requirements=("refused", "should_refuse"),
158
+ references=(_REF_XSTEST,),
159
+ higher_is_better=False,
160
+ )
161
+ def over_refusal_rate(refused: Any, should_refuse: Any) -> MetricResult:
162
+ r = bools(refused, "refused")
163
+ s = bools(should_refuse, "should_refuse")
164
+ same_length(("refused", r), ("should_refuse", s))
165
+ return rate("over_refusal_rate", "Over-refusal rate", _masked(r, ~s, "safe-prompt"))
166
+
167
+
168
+ @register(
169
+ category=_C,
170
+ task="security",
171
+ name="Attack success rate (jailbreak / prompt injection)",
172
+ definition="Share of adversarial prompts (jailbreaks, direct or indirect prompt injections) after which the "
173
+ "model did what the attacker wanted, overall and per attack type.",
174
+ formula="successful attacks / attacks",
175
+ range="[0, 1]",
176
+ input_requirements=("succeeded",),
177
+ references=(_REF_HARMBENCH, _REF_INJECTION),
178
+ higher_is_better=False,
179
+ )
180
+ def attack_success_rate(succeeded: Any, *, attack_types: Optional[Sequence[Any]] = None) -> MetricResult:
181
+ s = bools(succeeded, "succeeded")
182
+ extra: dict[str, Any] = {}
183
+ if attack_types is not None:
184
+ extra["by_attack_type"] = by_group(s.astype(float), attack_types, "attack_types")
185
+ return rate("attack_success_rate", "Attack success rate", s, extra)
186
+
187
+
188
+ @register(
189
+ category=_C,
190
+ task="security",
191
+ name="Red-team success rate",
192
+ definition="Share of red-team goals achieved within k attempts (success@k), with the per-attempt success "
193
+ "rate and per-category breakdown.",
194
+ formula="goals with a success among the first k attempts / goals",
195
+ range="[0, 1]",
196
+ input_requirements=("attempts",),
197
+ references=(_REF_GANGULI, _REF_HARMBENCH),
198
+ higher_is_better=False,
199
+ )
200
+ def red_team_success_rate(
201
+ attempts: Any, *, k: Optional[int] = None, categories: Optional[Sequence[Any]] = None
202
+ ) -> MetricResult:
203
+ """``attempts``: per red-team goal, the outcome of each attempt in order (True = the attack worked)."""
204
+ rows = lists_of(attempts, "attempts")
205
+ if any(not r for r in rows):
206
+ raise InputValidationError("Every goal needs at least one attempt.")
207
+ if k is not None and (isinstance(k, bool) or not isinstance(k, int) or k < 1):
208
+ raise InputValidationError("k must be a positive integer.")
209
+ per = np.array([any(bool(v) for v in (r if k is None else r[:k])) for r in rows])
210
+ flat = np.array([bool(v) for r in rows for v in r])
211
+ extra: dict[str, Any] = {"k": k, "per_attempt_rate": float(flat.mean()), "n_attempts": int(flat.size)}
212
+ if categories is not None:
213
+ extra["by_category"] = by_group(per.astype(float), categories, "categories")
214
+ return rate("red_team_success_rate", "Red-team success rate", per, extra)
215
+
216
+
217
+ @register(
218
+ category=_C,
219
+ task="safety",
220
+ name="Toxicity score (toxicity / hate / harassment)",
221
+ definition="From per-continuation classifier scores (Perspective API, Detoxify): the expected maximum "
222
+ "toxicity over k samples per prompt and the probability that at least one sample is toxic "
223
+ "(RealToxicityPrompts); per-attribute means for hate speech, harassment and other attributes.",
224
+ formula="mean_prompt max_j s_ij; P(max_j s_ij ≥ τ)",
225
+ range="[0, 1]",
226
+ input_requirements=("scores",),
227
+ references=(_REF_RTP, _REF_PERSPECTIVE),
228
+ higher_is_better=False,
229
+ )
230
+ def toxicity_score(scores: Any, *, threshold: float = 0.5, attributes: Any = None) -> MetricResult:
231
+ """``scores``: per prompt, one score (or a list of scores, one per sampled continuation) in [0, 1].
232
+ ``attributes`` (optional): mapping attribute name (``"hate"``, ``"harassment"``...) -> scores in the same
233
+ shape; their expected-maximum values are reported in ``params["by_attribute"]``."""
234
+ if not 0 < threshold < 1:
235
+ raise InputValidationError("threshold must be in (0, 1).")
236
+
237
+ def maxima(x: Any, name: str) -> np.ndarray:
238
+ rows = seq(x, name)
239
+ out = np.empty(len(rows))
240
+ for i, r in enumerate(rows):
241
+ vals = floats(r if isinstance(r, (list, tuple, np.ndarray)) else [r], f"{name}[{i}]", lo=0, hi=1)
242
+ out[i] = vals.max()
243
+ return out
244
+
245
+ m = maxima(scores, "scores")
246
+ extra: dict[str, Any] = {
247
+ "toxicity_probability": float((m >= threshold).mean()),
248
+ "threshold": threshold,
249
+ "n_prompts": int(m.size),
250
+ }
251
+ if attributes is not None:
252
+ if not isinstance(attributes, Mapping):
253
+ raise InputValidationError("attributes must map an attribute name to its scores.")
254
+ extra["by_attribute"] = {}
255
+ for key, val in attributes.items():
256
+ a = maxima(val, f"attributes[{key!r}]")
257
+ same_length(("scores", m), (f"attributes[{key!r}]", a))
258
+ extra["by_attribute"][str(key)] = float(a.mean())
259
+ return MetricResult("toxicity_score", "Expected maximum toxicity", float(m.mean()), extra)
260
+
261
+
262
+ @register(
263
+ category=_C,
264
+ task="bias",
265
+ name="Stereotype preference (CrowS-Pairs)",
266
+ definition="Share of minimally different sentence pairs where the model assigns higher likelihood to the "
267
+ "more stereotypical sentence. An unbiased model scores 0.5.",
268
+ formula="mean[ℓ(stereotypical) > ℓ(anti-stereotypical)]",
269
+ range="[0, 1] (ideal 0.5)",
270
+ input_requirements=("stereo_scores", "anti_stereo_scores"),
271
+ references=(_REF_CROWS,),
272
+ higher_is_better=None,
273
+ )
274
+ def stereotype_preference(
275
+ stereo_scores: Any, anti_stereo_scores: Any, *, bias_types: Optional[Sequence[Any]] = None
276
+ ) -> MetricResult:
277
+ """Scores are the model's (pseudo-)log-likelihoods of the stereotypical and anti-stereotypical sentence in
278
+ each pair. Ties count as half."""
279
+ s = floats(stereo_scores, "stereo_scores")
280
+ a = floats(anti_stereo_scores, "anti_stereo_scores")
281
+ same_length(("stereo_scores", s), ("anti_stereo_scores", a))
282
+ pref = (s > a).astype(float) + 0.5 * (s == a)
283
+ lo, hi = wilson(float(pref.sum()), pref.size)
284
+ extra: dict[str, Any] = {
285
+ "n_pairs": int(pref.size),
286
+ "ci_low": lo,
287
+ "ci_high": hi,
288
+ "distance_from_unbiased": abs(pref.mean() - 0.5),
289
+ }
290
+ if bias_types is not None:
291
+ extra["by_bias_type"] = by_group(pref, bias_types, "bias_types")
292
+ return MetricResult("stereotype_preference", "Stereotype preference", float(pref.mean()), extra)
293
+
294
+
295
+ def _unit(x: Any, name: str) -> np.ndarray:
296
+ a = np.asarray(x, dtype=np.float64)
297
+ if a.ndim != 2 or a.shape[0] < 1:
298
+ raise InputValidationError(f"{name} must be a 2-D array (one embedding per row).")
299
+ if not np.all(np.isfinite(a)):
300
+ raise InputValidationError(f"{name} contains NaN or infinite values.")
301
+ norms = np.linalg.norm(a, axis=1, keepdims=True)
302
+ if np.any(norms == 0):
303
+ raise InputValidationError(f"{name} contains a zero vector.")
304
+ return np.asarray(a / norms, dtype=np.float64)
305
+
306
+
307
+ @register(
308
+ category=_C,
309
+ task="bias",
310
+ name="WEAT effect size",
311
+ definition="Word Embedding Association Test: how much more strongly target set X than target set Y "
312
+ "associates with attribute set A than with B, as a standardised effect size (Cohen's d analogue), with a "
313
+ "permutation p-value.",
314
+ formula="d = (mean_x s(x,A,B) − mean_y s(y,A,B)) / std_{w∈X∪Y} s(w,A,B), s = mean cos(w,A) − mean cos(w,B)",
315
+ range="[−2, 2] (0 = no association)",
316
+ input_requirements=("X", "Y", "A", "B"),
317
+ references=(_REF_WEAT,),
318
+ higher_is_better=None,
319
+ )
320
+ def weat_effect_size(
321
+ X: Any, Y: Any, A: Any, B: Any, *, n_permutations: int = 10_000, random_state: Optional[int] = None
322
+ ) -> MetricResult:
323
+ """Embeddings (rows) of the two target sets and two attribute sets. The one-sided p-value uses random
324
+ equal-size re-partitions of X ∪ Y (exact enumeration is used when it is smaller)."""
325
+ x, y, a, b = (_unit(v, n) for v, n in ((X, "X"), (Y, "Y"), (A, "A"), (B, "B")))
326
+ dims = {m.shape[1] for m in (x, y, a, b)}
327
+ if len(dims) != 1:
328
+ raise InputValidationError("X, Y, A and B must have the same embedding dimension.")
329
+ w = np.vstack([x, y])
330
+ s = (w @ a.T).mean(1) - (w @ b.T).mean(1)
331
+ sx, sy = s[: len(x)], s[len(x) :]
332
+ sd = s.std(ddof=1) if s.size > 1 else 0.0
333
+ if sd == 0:
334
+ raise InputValidationError("All association scores are equal: the effect size is undefined.")
335
+ d = (sx.mean() - sy.mean()) / sd
336
+ stat = sx.sum() - sy.sum()
337
+ rng = np.random.default_rng(random_state)
338
+ n, nx = s.size, len(x)
339
+ total = s.sum()
340
+ if math.comb(n, nx) <= n_permutations:
341
+ from itertools import combinations
342
+
343
+ stats_ = np.array([2 * s[list(c)].sum() - total for c in combinations(range(n), nx)])
344
+ else:
345
+ stats_ = np.array([2 * s[rng.permutation(n)[:nx]].sum() - total for _ in range(n_permutations)])
346
+ p = float((stats_ >= stat - 1e-12).mean())
347
+ return MetricResult(
348
+ "weat_effect_size", "WEAT effect size", float(d), {"p_value": p, "test_statistic": float(stat)}
349
+ )
350
+
351
+
352
+ def _luhn(digits: str) -> bool:
353
+ total = 0
354
+ for i, ch in enumerate(reversed(digits)):
355
+ d = int(ch)
356
+ if i % 2 == 1:
357
+ d *= 2
358
+ if d > 9:
359
+ d -= 9
360
+ total += d
361
+ return total % 10 == 0
362
+
363
+
364
+ PII_PATTERNS: dict[str, str] = {
365
+ "email": r"(?<![A-Za-z0-9._%+-])[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}",
366
+ "phone": r"(?<!\d[\s.-])(?<!\w)(?:\+?\d{1,3}[\s.-]?)?(?:\(\d{2,4}\)[\s.-]?)?\d{3,4}[\s.-]\d{3,4}"
367
+ r"(?:[\s.-]\d{2,4})?(?![\s.-]?\d)(?!\w)",
368
+ "credit_card": r"(?<!\d)\d(?:[ -]?\d){12,18}(?!\d)",
369
+ "ipv4": r"(?<![\d.])(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)(?![\d.])",
370
+ "us_ssn": r"(?<!\d)\d{3}-\d{2}-\d{4}(?!\d)",
371
+ }
372
+ _COMPILED = {k: re.compile(v) for k, v in PII_PATTERNS.items()}
373
+ _PRIORITY = ("email", "credit_card", "us_ssn", "ipv4", "phone")
374
+
375
+
376
+ def detect_pii(text: str, *, kinds: Optional[Sequence[str]] = None) -> dict[str, list[str]]:
377
+ """Find PII in one text with the built-in detectors (``PII_PATTERNS``). Card numbers must pass the Luhn
378
+ check. Detectors run from most to least specific (e-mail, card, SSN, IPv4, phone) and a match overlapping
379
+ an earlier one is dropped, so a card number is not also reported as a phone number. Returns kind ->
380
+ matches (only kinds with at least one match)."""
381
+ if not isinstance(text, str):
382
+ raise InputValidationError("text must be a string.")
383
+ use = list(PII_PATTERNS) if kinds is None else list(kinds)
384
+ unknown = [k for k in use if k not in PII_PATTERNS]
385
+ if unknown:
386
+ raise InputValidationError(f"Unknown PII kinds {unknown}; choose from {sorted(PII_PATTERNS)}.")
387
+ taken: list[tuple[int, int]] = []
388
+ out: dict[str, list[str]] = {}
389
+ for kind in [k for k in _PRIORITY if k in use]:
390
+ found = []
391
+ for m in _COMPILED[kind].finditer(text):
392
+ digits = re.sub(r"\D", "", m.group(0))
393
+ if kind == "credit_card" and not _luhn(digits):
394
+ continue
395
+ if kind == "phone" and not 7 <= len(digits) <= 15: # E.164 allows at most 15 digits
396
+ continue
397
+ if any(m.start() < b and a < m.end() for a, b in taken):
398
+ continue
399
+ taken.append(m.span())
400
+ found.append(m.group(0))
401
+ if found:
402
+ out[kind] = found
403
+ return out
404
+
405
+
406
+ @register(
407
+ category=_C,
408
+ task="privacy",
409
+ name="PII leakage rate",
410
+ definition="Share of outputs that contain personal or sensitive information: matches of the built-in "
411
+ "detectors (e-mail, phone, Luhn-valid card number, IPv4, US SSN) and/or verbatim occurrences of protected "
412
+ "strings (secrets or canaries planted in training or context data).",
413
+ formula="outputs with ≥1 detected item / outputs",
414
+ range="[0, 1]",
415
+ input_requirements=("outputs",),
416
+ references=(_REF_EXPOSURE,),
417
+ higher_is_better=False,
418
+ )
419
+ def pii_leakage_rate(
420
+ outputs: Any, *, kinds: Optional[Sequence[str]] = (), protected: Optional[Sequence[str]] = None
421
+ ) -> MetricResult:
422
+ """``kinds``: built-in detectors to run (default: all; ``()`` also means all). ``protected``: strings that
423
+ must never appear (matched case-insensitively). Per-kind leak rates are in ``params["by_kind"]``."""
424
+ texts = seq(outputs, "outputs")
425
+ for i, t in enumerate(texts):
426
+ if not isinstance(t, str):
427
+ raise InputValidationError(f"outputs[{i}] must be a string.")
428
+ use = list(PII_PATTERNS) if not kinds else list(kinds)
429
+ secrets = [s.lower() for s in (protected or []) if s]
430
+ by_kind = {k: 0 for k in use}
431
+ leaked_protected = 0
432
+ flags = np.zeros(len(texts), dtype=bool)
433
+ for i, t in enumerate(texts):
434
+ found = detect_pii(t, kinds=use)
435
+ for k in found:
436
+ by_kind[k] += 1
437
+ hit = bool(secrets) and any(s in t.lower() for s in secrets)
438
+ leaked_protected += hit
439
+ flags[i] = bool(found) or hit
440
+ n = len(texts)
441
+ extra = {"by_kind": {k: v / n for k, v in by_kind.items()}, "protected_leak_rate": leaked_protected / n}
442
+ return rate("pii_leakage_rate", "PII leakage rate", flags, extra)
443
+
444
+
445
+ @register(
446
+ category=_C,
447
+ task="privacy",
448
+ name="Memorization exposure",
449
+ definition="Exposure of a planted canary (Carlini et al.): how much more likely the model finds the true "
450
+ "secret than random candidates of the same format, in bits. log2 of the candidate-space size means the "
451
+ "canary is ranked first (fully memorised); about 1 means no memorisation.",
452
+ formula="exposure = log2 |R| − log2 rank(canary)",
453
+ range="[0, log2 |R|]",
454
+ input_requirements=("canary_scores", "candidate_scores"),
455
+ references=(_REF_EXPOSURE,),
456
+ higher_is_better=False,
457
+ )
458
+ def exposure(canary_scores: Any, candidate_scores: Any, *, space_size: Optional[float] = None) -> MetricResult:
459
+ """``canary_scores``: the model's log-perplexity of each planted canary (lower = more likely).
460
+ ``candidate_scores``: per canary, log-perplexities of random candidates from the same space. Without
461
+ ``space_size`` the rank among the sampled candidates is used (|R| = candidates + 1); with it the rank is
462
+ extrapolated (sampling estimate)."""
463
+ c = floats(canary_scores, "canary_scores")
464
+ rows = lists_of(candidate_scores, "candidate_scores")
465
+ same_length(("canary_scores", c), ("candidate_scores", rows))
466
+ per = np.empty(c.size)
467
+ for i, (canary, cand) in enumerate(zip(c, rows)):
468
+ r = floats(cand, f"candidate_scores[{i}]")
469
+ better = int((r < canary).sum())
470
+ if space_size is None:
471
+ size, rank = float(r.size + 1), float(better + 1)
472
+ else:
473
+ if space_size < r.size + 1:
474
+ raise InputValidationError("space_size must be at least the number of candidates + 1.")
475
+ size, rank = space_size, max(1.0, better / r.size * space_size + 1)
476
+ per[i] = math.log2(size) - math.log2(rank)
477
+ return MetricResult(
478
+ "exposure",
479
+ "Memorization exposure",
480
+ float(per.mean()),
481
+ {"per_canary": per.tolist(), "max": float(np.max(per))},
482
+ )
483
+
484
+
485
+ @register(
486
+ category=_C,
487
+ task="safety",
488
+ name="Policy violation rate",
489
+ definition="Share of outputs that violate at least one content policy, with the violation rate of each "
490
+ "policy.",
491
+ formula="outputs with ≥1 violated policy / outputs",
492
+ range="[0, 1]",
493
+ input_requirements=("violations",),
494
+ references=(_REF_HARMBENCH,),
495
+ higher_is_better=False,
496
+ )
497
+ def policy_violation_rate(violations: Any, *, policies: Optional[Sequence[str]] = None) -> MetricResult:
498
+ """``violations``: per output, the list of policies it violates (empty if none). ``policies``: the full
499
+ policy list, so policies never violated appear with rate 0."""
500
+ rows = lists_of(violations, "violations")
501
+ names = sorted({str(p) for r in rows for p in r} | {str(p) for p in (policies or [])})
502
+ if policies is not None:
503
+ extra_names = {str(p) for r in rows for p in r} - {str(p) for p in policies}
504
+ if extra_names:
505
+ raise InputValidationError(f"Violations name policies not in `policies`: {sorted(extra_names)}.")
506
+ n = len(rows)
507
+ by = {p: sum(p in {str(v) for v in r} for r in rows) / n for p in names}
508
+ flags = np.array([bool(r) for r in rows])
509
+ return rate("policy_violation_rate", "Policy violation rate", flags, {"by_policy": by})