passgate 0.1.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.
- passgate/__init__.py +17 -0
- passgate/__main__.py +6 -0
- passgate/cli.py +149 -0
- passgate/gate.py +174 -0
- passgate/py.typed +0 -0
- passgate/stats.py +79 -0
- passgate-0.1.1.dist-info/METADATA +112 -0
- passgate-0.1.1.dist-info/RECORD +12 -0
- passgate-0.1.1.dist-info/WHEEL +5 -0
- passgate-0.1.1.dist-info/entry_points.txt +2 -0
- passgate-0.1.1.dist-info/licenses/LICENSE +21 -0
- passgate-0.1.1.dist-info/top_level.txt +1 -0
passgate/__init__.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""passgate - statistical pass^N reliability gate for evals."""
|
|
2
|
+
|
|
3
|
+
from .gate import GateResult, Round, compare, evaluate_rounds
|
|
4
|
+
from .stats import fisher_exact_2x2, two_proportion_z, wilson_interval, wilson_lower
|
|
5
|
+
|
|
6
|
+
__version__ = "0.1.1"
|
|
7
|
+
__all__ = [
|
|
8
|
+
"Round",
|
|
9
|
+
"GateResult",
|
|
10
|
+
"evaluate_rounds",
|
|
11
|
+
"compare",
|
|
12
|
+
"wilson_lower",
|
|
13
|
+
"wilson_interval",
|
|
14
|
+
"two_proportion_z",
|
|
15
|
+
"fisher_exact_2x2",
|
|
16
|
+
"__version__",
|
|
17
|
+
]
|
passgate/__main__.py
ADDED
passgate/cli.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"""passgate CLI: gate eval rounds, or compare a candidate against a baseline.
|
|
2
|
+
|
|
3
|
+
Exit codes: 0 = pass, 1 = gate/comparison did not pass, 2 = bad input or usage.
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import argparse
|
|
8
|
+
import csv
|
|
9
|
+
import json
|
|
10
|
+
import sys
|
|
11
|
+
from typing import Any, List, Optional
|
|
12
|
+
|
|
13
|
+
from . import __version__
|
|
14
|
+
from .gate import Round, compare, evaluate_rounds
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class InputError(ValueError):
|
|
18
|
+
"""Bad user input (file, format, or number). Reported with exit code 2."""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def parse_ratio(text: str) -> Round:
|
|
22
|
+
"""'93/100' -> Round(trials=100, passes=93)."""
|
|
23
|
+
try:
|
|
24
|
+
passes_s, trials_s = text.split("/", 1)
|
|
25
|
+
return Round(trials=int(trials_s), passes=int(passes_s))
|
|
26
|
+
except (ValueError, AttributeError):
|
|
27
|
+
raise InputError(f"bad round {text!r}, expected PASSES/TRIALS e.g. 93/100") from None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _to_int(value: Any, what: str, where: str) -> int:
|
|
31
|
+
if value is None or isinstance(value, bool):
|
|
32
|
+
raise InputError(f"{where}: missing or invalid {what}")
|
|
33
|
+
try:
|
|
34
|
+
if isinstance(value, float):
|
|
35
|
+
if not value.is_integer():
|
|
36
|
+
raise ValueError
|
|
37
|
+
return int(value)
|
|
38
|
+
return int(str(value).strip())
|
|
39
|
+
except ValueError:
|
|
40
|
+
raise InputError(f"{where}: {what} must be a whole number, got {value!r}") from None
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _make_round(trials: Any, passes: Any, label: str, where: str) -> Round:
|
|
44
|
+
t = _to_int(trials, "trials", where)
|
|
45
|
+
p = _to_int(passes, "passes", where)
|
|
46
|
+
try:
|
|
47
|
+
return Round(trials=t, passes=p, label=label)
|
|
48
|
+
except ValueError as e:
|
|
49
|
+
raise InputError(f"{where}: {e}") from None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def load_rounds(path: str) -> List[Round]:
|
|
53
|
+
"""JSON list of {trials, passes} (or [passes, trials] pairs) or CSV (trials,passes[,label]).
|
|
54
|
+
|
|
55
|
+
Files may carry a UTF-8 BOM (common from Windows tools) and CRLF line endings.
|
|
56
|
+
"""
|
|
57
|
+
rounds: List[Round] = []
|
|
58
|
+
try:
|
|
59
|
+
if path.lower().endswith(".csv"):
|
|
60
|
+
with open(path, newline="", encoding="utf-8-sig") as fh:
|
|
61
|
+
for i, row in enumerate(csv.DictReader(fh), start=1):
|
|
62
|
+
row = {(k or "").strip().lower(): v for k, v in row.items()}
|
|
63
|
+
trials = row.get("trials") if row.get("trials") not in (None, "") else row.get("n")
|
|
64
|
+
passes = row.get("passes") if row.get("passes") not in (None, "") else row.get("k")
|
|
65
|
+
rounds.append(
|
|
66
|
+
_make_round(trials, passes, (row.get("label") or "").strip(), f"{path} row {i}")
|
|
67
|
+
)
|
|
68
|
+
return rounds
|
|
69
|
+
with open(path, encoding="utf-8-sig") as fh:
|
|
70
|
+
data = json.load(fh)
|
|
71
|
+
except FileNotFoundError:
|
|
72
|
+
raise InputError(f"rounds file not found: {path}") from None
|
|
73
|
+
except OSError as e:
|
|
74
|
+
raise InputError(f"cannot read {path}: {e.strerror or e}") from None
|
|
75
|
+
except UnicodeDecodeError:
|
|
76
|
+
raise InputError(f"{path} is not valid UTF-8 text") from None
|
|
77
|
+
except json.JSONDecodeError as e:
|
|
78
|
+
raise InputError(f"{path} is not valid JSON: {e}") from None
|
|
79
|
+
if not isinstance(data, list):
|
|
80
|
+
raise InputError(f"{path}: expected a JSON list of rounds")
|
|
81
|
+
for i, item in enumerate(data, start=1):
|
|
82
|
+
where = f"{path} round {i}"
|
|
83
|
+
if isinstance(item, dict):
|
|
84
|
+
rounds.append(
|
|
85
|
+
_make_round(item.get("trials"), item.get("passes"), str(item.get("label", "")), where)
|
|
86
|
+
)
|
|
87
|
+
elif isinstance(item, (list, tuple)) and len(item) == 2:
|
|
88
|
+
rounds.append(_make_round(item[1], item[0], f"round {i}", where))
|
|
89
|
+
else:
|
|
90
|
+
raise InputError(f"{where}: expected {{trials, passes}} or [passes, trials]")
|
|
91
|
+
return rounds
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
95
|
+
ap = argparse.ArgumentParser(
|
|
96
|
+
prog="passgate",
|
|
97
|
+
description="Require an eval candidate to clear a Wilson-bound pass bar on EVERY round.",
|
|
98
|
+
epilog="Exit codes: 0 pass, 1 fail / not significant, 2 bad input.",
|
|
99
|
+
)
|
|
100
|
+
ap.add_argument("--version", action="version", version=f"passgate {__version__}")
|
|
101
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
102
|
+
|
|
103
|
+
g = sub.add_parser("gate", help="pass^N gate over eval rounds; exit 1 if any round is weak")
|
|
104
|
+
g.add_argument("rounds", help="JSON or CSV rounds file")
|
|
105
|
+
g.add_argument("--threshold", type=float, default=0.9, help="required Wilson lower bound (default 0.9)")
|
|
106
|
+
g.add_argument("--confidence", type=float, default=0.95, help="interval confidence (default 0.95)")
|
|
107
|
+
g.add_argument("--min-rounds", type=int, default=1, help="fail if fewer rounds than this")
|
|
108
|
+
g.add_argument("--json", action="store_true", help="machine-readable output")
|
|
109
|
+
|
|
110
|
+
c = sub.add_parser("compare", help="candidate vs baseline: is the candidate actually better?")
|
|
111
|
+
c.add_argument("--candidate", required=True, action="append", help="PASSES/TRIALS (repeatable, one per round)")
|
|
112
|
+
c.add_argument("--baseline", required=True, action="append", help="PASSES/TRIALS (repeatable)")
|
|
113
|
+
c.add_argument("--alpha", type=float, default=0.05)
|
|
114
|
+
c.add_argument("--json", action="store_true", help="machine-readable output")
|
|
115
|
+
return ap
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _emit(text: str) -> None:
|
|
119
|
+
"""Print without ever crashing on a legacy Windows console encoding."""
|
|
120
|
+
try:
|
|
121
|
+
print(text)
|
|
122
|
+
except UnicodeEncodeError:
|
|
123
|
+
enc = getattr(sys.stdout, "encoding", None) or "ascii"
|
|
124
|
+
print(text.encode(enc, errors="replace").decode(enc))
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def main(argv: Optional[List[str]] = None) -> int:
|
|
128
|
+
args = _build_parser().parse_args(argv)
|
|
129
|
+
try:
|
|
130
|
+
if args.cmd == "gate":
|
|
131
|
+
rounds = load_rounds(args.rounds)
|
|
132
|
+
result = evaluate_rounds(
|
|
133
|
+
rounds, threshold=args.threshold, confidence=args.confidence, min_rounds=args.min_rounds
|
|
134
|
+
)
|
|
135
|
+
_emit(json.dumps(result.as_dict(), indent=2) if args.json else str(result))
|
|
136
|
+
return 0 if result.passed else 1
|
|
137
|
+
|
|
138
|
+
cand = [parse_ratio(x) for x in args.candidate]
|
|
139
|
+
base = [parse_ratio(x) for x in args.baseline]
|
|
140
|
+
cmp_ = compare(cand, base, alpha=args.alpha)
|
|
141
|
+
_emit(json.dumps(cmp_.as_dict(), indent=2) if args.json else str(cmp_))
|
|
142
|
+
return 0 if cmp_.verdict == "candidate-better" else 1
|
|
143
|
+
except ValueError as e: # includes InputError and validation errors from the library
|
|
144
|
+
print(f"passgate: {e}", file=sys.stderr)
|
|
145
|
+
return 2
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
if __name__ == "__main__": # pragma: no cover
|
|
149
|
+
sys.exit(main())
|
passgate/gate.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
"""The pass^N gate and the candidate-vs-baseline comparison."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import math
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import Any, Dict, List, Sequence
|
|
7
|
+
|
|
8
|
+
from .stats import fisher_exact_2x2, two_proportion_z, wilson_lower, z_for_confidence
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(frozen=True)
|
|
12
|
+
class Round:
|
|
13
|
+
"""One evaluation round: how many trials, how many passed."""
|
|
14
|
+
|
|
15
|
+
trials: int
|
|
16
|
+
passes: int
|
|
17
|
+
label: str = ""
|
|
18
|
+
|
|
19
|
+
def __post_init__(self) -> None:
|
|
20
|
+
if self.trials <= 0:
|
|
21
|
+
raise ValueError("trials must be positive")
|
|
22
|
+
if not 0 <= self.passes <= self.trials:
|
|
23
|
+
raise ValueError(f"passes {self.passes} outside [0, {self.trials}]")
|
|
24
|
+
|
|
25
|
+
@property
|
|
26
|
+
def rate(self) -> float:
|
|
27
|
+
return self.passes / self.trials
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass
|
|
31
|
+
class RoundEval:
|
|
32
|
+
round: Round
|
|
33
|
+
wilson_lower: float
|
|
34
|
+
meets: bool
|
|
35
|
+
|
|
36
|
+
def as_dict(self) -> Dict[str, Any]:
|
|
37
|
+
return {
|
|
38
|
+
"label": self.round.label,
|
|
39
|
+
"trials": self.round.trials,
|
|
40
|
+
"passes": self.round.passes,
|
|
41
|
+
"rate": round(self.round.rate, 6),
|
|
42
|
+
"wilson_lower": round(self.wilson_lower, 6),
|
|
43
|
+
"meets": self.meets,
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass
|
|
48
|
+
class GateResult:
|
|
49
|
+
threshold: float
|
|
50
|
+
confidence: float
|
|
51
|
+
min_rounds: int
|
|
52
|
+
rounds: List[RoundEval] = field(default_factory=list)
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def passed(self) -> bool:
|
|
56
|
+
return (
|
|
57
|
+
len(self.rounds) >= self.min_rounds
|
|
58
|
+
and all(r.meets for r in self.rounds)
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
def __bool__(self) -> bool:
|
|
62
|
+
return self.passed
|
|
63
|
+
|
|
64
|
+
def as_dict(self) -> Dict[str, Any]:
|
|
65
|
+
return {
|
|
66
|
+
"passed": self.passed,
|
|
67
|
+
"threshold": self.threshold,
|
|
68
|
+
"confidence": self.confidence,
|
|
69
|
+
"min_rounds": self.min_rounds,
|
|
70
|
+
"rounds": [r.as_dict() for r in self.rounds],
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
def __str__(self) -> str:
|
|
74
|
+
head = (
|
|
75
|
+
f"passgate: {sum(r.meets for r in self.rounds)}/{len(self.rounds)} round(s) "
|
|
76
|
+
f"clear Wilson-lower >= {self.threshold:.3f} "
|
|
77
|
+
f"({self.confidence:.0%} confidence, min {self.min_rounds} rounds)"
|
|
78
|
+
)
|
|
79
|
+
lines = [
|
|
80
|
+
f" {'PASS' if r.meets else 'FAIL'} "
|
|
81
|
+
f"{(r.round.label or 'round ' + str(i + 1)):>12}: "
|
|
82
|
+
f"{r.round.passes}/{r.round.trials} = {r.round.rate:.3f} "
|
|
83
|
+
f"(lower {r.wilson_lower:.3f})"
|
|
84
|
+
for i, r in enumerate(self.rounds)
|
|
85
|
+
]
|
|
86
|
+
verdict = "PASS" if self.passed else "FAIL"
|
|
87
|
+
return "\n".join([head] + lines + [f"verdict: {verdict}"])
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def evaluate_rounds(
|
|
91
|
+
rounds: Sequence[Round],
|
|
92
|
+
threshold: float = 0.9,
|
|
93
|
+
confidence: float = 0.95,
|
|
94
|
+
min_rounds: int = 1,
|
|
95
|
+
) -> GateResult:
|
|
96
|
+
"""Gate: EVERY round's Wilson lower bound must clear ``threshold``.
|
|
97
|
+
|
|
98
|
+
A flaky candidate that spikes on average but has one weak round fails —
|
|
99
|
+
the "pass^N" property.
|
|
100
|
+
"""
|
|
101
|
+
if not 0.0 < threshold < 1.0:
|
|
102
|
+
raise ValueError("threshold must be between 0 and 1")
|
|
103
|
+
z_for_confidence(confidence) # validates 0.5 < confidence < 1
|
|
104
|
+
if min_rounds < 1:
|
|
105
|
+
raise ValueError("min_rounds must be >= 1")
|
|
106
|
+
result = GateResult(threshold=threshold, confidence=confidence, min_rounds=min_rounds)
|
|
107
|
+
for r in rounds:
|
|
108
|
+
lower = wilson_lower(r.passes, r.trials, confidence)
|
|
109
|
+
result.rounds.append(RoundEval(round=r, wilson_lower=lower, meets=lower >= threshold))
|
|
110
|
+
return result
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@dataclass
|
|
114
|
+
class Comparison:
|
|
115
|
+
candidate_rate: float
|
|
116
|
+
baseline_rate: float
|
|
117
|
+
z: float
|
|
118
|
+
p_one_sided: float
|
|
119
|
+
fisher_p: float
|
|
120
|
+
alpha: float
|
|
121
|
+
|
|
122
|
+
@property
|
|
123
|
+
def better(self) -> bool:
|
|
124
|
+
return self.candidate_rate > self.baseline_rate and self.p_one_sided < self.alpha
|
|
125
|
+
|
|
126
|
+
@property
|
|
127
|
+
def verdict(self) -> str:
|
|
128
|
+
if self.p_one_sided < self.alpha:
|
|
129
|
+
return "candidate-better" if self.candidate_rate > self.baseline_rate else "baseline-better"
|
|
130
|
+
return "inconclusive"
|
|
131
|
+
|
|
132
|
+
def as_dict(self) -> Dict[str, Any]:
|
|
133
|
+
return {
|
|
134
|
+
"candidate_rate": round(self.candidate_rate, 6),
|
|
135
|
+
"baseline_rate": round(self.baseline_rate, 6),
|
|
136
|
+
"z": round(self.z, 6) if math.isfinite(self.z) else None,
|
|
137
|
+
"p_one_sided": round(self.p_one_sided, 6),
|
|
138
|
+
"fisher_p": round(self.fisher_p, 6),
|
|
139
|
+
"alpha": self.alpha,
|
|
140
|
+
"verdict": self.verdict,
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
def __str__(self) -> str:
|
|
144
|
+
return (
|
|
145
|
+
f"candidate {self.candidate_rate:.3f} vs baseline {self.baseline_rate:.3f} - "
|
|
146
|
+
f"z={self.z:.3f}, one-sided p={self.p_one_sided:.4g}, "
|
|
147
|
+
f"fisher p={self.fisher_p:.4g}, verdict: {self.verdict}"
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def compare(
|
|
152
|
+
candidate: Sequence[Round],
|
|
153
|
+
baseline: Sequence[Round],
|
|
154
|
+
alpha: float = 0.05,
|
|
155
|
+
) -> Comparison:
|
|
156
|
+
"""Compare candidate vs baseline on pooled totals, with Fisher as a check."""
|
|
157
|
+
if not candidate or not baseline:
|
|
158
|
+
raise ValueError("compare needs at least one candidate round and one baseline round")
|
|
159
|
+
if not 0.0 < alpha < 1.0:
|
|
160
|
+
raise ValueError("alpha must be between 0 and 1")
|
|
161
|
+
c1 = sum(r.passes for r in candidate)
|
|
162
|
+
n1 = sum(r.trials for r in candidate)
|
|
163
|
+
c2 = sum(r.passes for r in baseline)
|
|
164
|
+
n2 = sum(r.trials for r in baseline)
|
|
165
|
+
z, p = two_proportion_z(c1, n1, c2, n2)
|
|
166
|
+
fisher = fisher_exact_2x2(c1, n1 - c1, c2, n2 - c2)
|
|
167
|
+
return Comparison(
|
|
168
|
+
candidate_rate=c1 / n1,
|
|
169
|
+
baseline_rate=c2 / n2,
|
|
170
|
+
z=z,
|
|
171
|
+
p_one_sided=p,
|
|
172
|
+
fisher_p=fisher,
|
|
173
|
+
alpha=alpha,
|
|
174
|
+
)
|
passgate/py.typed
ADDED
|
File without changes
|
passgate/stats.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Small, dependency-free statistics used by the gate.
|
|
2
|
+
|
|
3
|
+
All bounds are exact closed forms; ``z`` comes from the standard normal
|
|
4
|
+
quantile (``statistics.NormalDist``), so results match any reference
|
|
5
|
+
implementation to floating-point precision.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import math
|
|
10
|
+
from statistics import NormalDist
|
|
11
|
+
from typing import Tuple
|
|
12
|
+
|
|
13
|
+
_NORMAL = NormalDist()
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def z_for_confidence(confidence: float) -> float:
|
|
17
|
+
if not 0.5 < confidence < 1.0:
|
|
18
|
+
raise ValueError("confidence must be between 0.5 and 1.0")
|
|
19
|
+
return _NORMAL.inv_cdf(0.5 + confidence / 2.0)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def wilson_interval(passes: int, trials: int, confidence: float = 0.95) -> Tuple[float, float]:
|
|
23
|
+
"""Two-sided Wilson score interval for a binomial proportion."""
|
|
24
|
+
if trials <= 0:
|
|
25
|
+
raise ValueError("trials must be positive")
|
|
26
|
+
if not 0 <= passes <= trials:
|
|
27
|
+
raise ValueError("passes must be within [0, trials]")
|
|
28
|
+
z = z_for_confidence(confidence)
|
|
29
|
+
phat = passes / trials
|
|
30
|
+
denom = 1.0 + z * z / trials
|
|
31
|
+
center = (phat + z * z / (2 * trials)) / denom
|
|
32
|
+
half = (z * math.sqrt((phat * (1 - phat) + z * z / (4 * trials)) / trials)) / denom
|
|
33
|
+
return max(0.0, center - half), min(1.0, center + half)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def wilson_lower(passes: int, trials: int, confidence: float = 0.95) -> float:
|
|
37
|
+
"""Lower bound of the Wilson interval — the conservative pass-rate estimate."""
|
|
38
|
+
return wilson_interval(passes, trials, confidence)[0]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def two_proportion_z(c1: int, n1: int, c2: int, n2: int) -> Tuple[float, float]:
|
|
42
|
+
"""Pooled two-proportion z-test: candidate (c1/n1) vs baseline (c2/n2).
|
|
43
|
+
|
|
44
|
+
Returns (z, one_sided_p). Positive z means the candidate is better.
|
|
45
|
+
"""
|
|
46
|
+
if n1 <= 0 or n2 <= 0:
|
|
47
|
+
raise ValueError("sample sizes must be positive")
|
|
48
|
+
if not (0 <= c1 <= n1 and 0 <= c2 <= n2):
|
|
49
|
+
raise ValueError("passes must be within [0, trials]")
|
|
50
|
+
p1, p2 = c1 / n1, c2 / n2
|
|
51
|
+
pooled = (c1 + c2) / (n1 + n2)
|
|
52
|
+
se = math.sqrt(pooled * (1 - pooled) * (1 / n1 + 1 / n2))
|
|
53
|
+
if se == 0.0:
|
|
54
|
+
return (0.0, 1.0) if p1 == p2 else (math.inf if p1 > p2 else -math.inf, 0.0)
|
|
55
|
+
z = (p1 - p2) / se
|
|
56
|
+
return z, _NORMAL.cdf(-z)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def fisher_exact_2x2(a: int, b: int, c: int, d: int) -> float:
|
|
60
|
+
"""Two-sided Fisher's exact p-value for [[a, b], [c, d]].
|
|
61
|
+
|
|
62
|
+
Exact hypergeometric enumeration — right for small eval rounds where the
|
|
63
|
+
normal approximation lies.
|
|
64
|
+
"""
|
|
65
|
+
for v in (a, b, c, d):
|
|
66
|
+
if v < 0:
|
|
67
|
+
raise ValueError("counts must be non-negative")
|
|
68
|
+
n = a + b + c + d
|
|
69
|
+
if n == 0:
|
|
70
|
+
raise ValueError("table is empty")
|
|
71
|
+
row1, col1 = a + b, a + c
|
|
72
|
+
|
|
73
|
+
def prob(x: int) -> float:
|
|
74
|
+
return math.comb(col1, x) * math.comb(n - col1, row1 - x) / math.comb(n, row1)
|
|
75
|
+
|
|
76
|
+
lo = max(0, row1 + col1 - n)
|
|
77
|
+
hi = min(row1, col1)
|
|
78
|
+
observed = prob(a)
|
|
79
|
+
return min(1.0, sum(prob(x) for x in range(lo, hi + 1) if prob(x) <= observed + 1e-12))
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: passgate
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: Statistical pass^N gate: require an eval candidate to clear a Wilson-bound bar on every round, not just on average
|
|
5
|
+
Author: calasdan-sketch
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Keywords: evals,llm,reliability,wilson,statistics,gate,regression,ci
|
|
8
|
+
Classifier: Development Status :: 4 - Beta
|
|
9
|
+
Classifier: Environment :: Console
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Topic :: Scientific/Engineering :: Information Analysis
|
|
19
|
+
Classifier: Topic :: Software Development :: Testing
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Python: >=3.9
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Dynamic: license-file
|
|
25
|
+
|
|
26
|
+
# passgate
|
|
27
|
+
|
|
28
|
+
**Pass once is luck. Pass^N is a gate.** A statistical reliability gate for LLM evals: a candidate must clear a Wilson-bound pass bar on **every** evaluation round, not just on average — then optionally prove it beats your baseline.
|
|
29
|
+
|
|
30
|
+
Eval flakiness is the quiet killer: a prompt scores 91% once, ships, and regresses. Averaging hides the weak round. `passgate` requires each round's *conservative* pass-rate estimate (the lower bound of the Wilson score interval) to clear your bar, so a candidate that needs 3 good rounds to ship must produce 3 good rounds.
|
|
31
|
+
|
|
32
|
+
## Install
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pip install passgate
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Also runnable as `python -m passgate ...`. Python 3.9+, no dependencies.
|
|
39
|
+
|
|
40
|
+
## The gate
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
passgate gate rounds.json --threshold 0.9 --min-rounds 3
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
`rounds.json` (or `.csv`) holds one entry per round:
|
|
47
|
+
|
|
48
|
+
```json
|
|
49
|
+
[
|
|
50
|
+
{ "label": "baseline-eval-set", "trials": 100, "passes": 93 },
|
|
51
|
+
{ "label": "adversarial-set", "trials": 100, "passes": 95 },
|
|
52
|
+
{ "label": "regression-set", "trials": 120, "passes": 116 }
|
|
53
|
+
]
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Output is a per-round scoreboard and a verdict; exit code `1` fails CI:
|
|
57
|
+
|
|
58
|
+
```
|
|
59
|
+
passgate: 2/3 round(s) clear Wilson-lower >= 0.900 (95% confidence, min 3 rounds)
|
|
60
|
+
PASS round 1: 93/100 = 0.930 (lower 0.863)
|
|
61
|
+
FAIL round 2: 70/100 = 0.700 (lower 0.604)
|
|
62
|
+
verdict: FAIL
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
Note what the gate does: **93/100 does not certify ≥ 0.9** at 95% confidence with 100 trials — you need more data or a lower bar. That is the point: the bar scales with evidence, not vibes. Add `--json` for machines.
|
|
66
|
+
|
|
67
|
+
## Candidate vs baseline
|
|
68
|
+
|
|
69
|
+
```bash
|
|
70
|
+
passgate compare --candidate 93/100 --candidate 95/100 \
|
|
71
|
+
--baseline 85/100 --baseline 88/100
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Pooled two-proportion z-test with a one-sided p-value, plus Fisher's exact p (exact hypergeometric enumeration — right for small rounds where the normal approximation lies). Exit `0` only when the improvement is statistically significant at `--alpha` (default 0.05).
|
|
75
|
+
|
|
76
|
+
## Python API
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
from passgate import Round, evaluate_rounds, compare
|
|
80
|
+
|
|
81
|
+
result = evaluate_rounds(
|
|
82
|
+
[Round(trials=100, passes=93), Round(trials=100, passes=95)],
|
|
83
|
+
threshold=0.9, confidence=0.95, min_rounds=2,
|
|
84
|
+
)
|
|
85
|
+
assert result.passed, str(result)
|
|
86
|
+
|
|
87
|
+
cmp = compare([Round(100, 93)], [Round(100, 85)])
|
|
88
|
+
print(cmp.verdict) # candidate-better | baseline-better | inconclusive
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## CI
|
|
92
|
+
|
|
93
|
+
```yaml
|
|
94
|
+
- run: pip install passgate
|
|
95
|
+
- run: python run_evals.py --out rounds.json # your eval runner
|
|
96
|
+
- run: passgate gate rounds.json --threshold 0.9 --min-rounds 3
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
## Notes
|
|
100
|
+
|
|
101
|
+
- Wilson interval (not Wald): behaves correctly near 0% and 100%, where the naive interval explodes.
|
|
102
|
+
- `gate` fails when rounds < `--min-rounds`, so "we only ran it once" cannot pass a 3-round gate.
|
|
103
|
+
- Pure stdlib — no scipy, no pandas.
|
|
104
|
+
- Exit codes: `0` pass, `1` gate failed / improvement not significant, `2` bad input (missing file, bad JSON/CSV, invalid number). Keeps CI from treating a typo as a model regression.
|
|
105
|
+
- Input files may be UTF-8 with or without a BOM, LF or CRLF.
|
|
106
|
+
- The Wilson interval is two-sided, so a 95% interval gives a one-sided 97.5% lower bound per round. Requiring every round to clear the bar is conservative, but passgate does not apply a formal multiple-testing correction.
|
|
107
|
+
- Rounds are treated as independent samples of one pass rate. If rounds reuse the same test items, the real uncertainty is larger than the bound shows.
|
|
108
|
+
- `compare` pools all rounds; it does not model round-to-round variance.
|
|
109
|
+
|
|
110
|
+
## License
|
|
111
|
+
|
|
112
|
+
MIT. See `LICENSE`.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
passgate/__init__.py,sha256=_wsXeTHIx2RXeLRrfCbU5J_TGYGt0tq-oOUlMZJLZXo,428
|
|
2
|
+
passgate/__main__.py,sha256=49E-7XEAwqHkzYgC4YBetOQtkrFesmLnxHPOjQp8j2s,88
|
|
3
|
+
passgate/cli.py,sha256=Yf33hIXTBpMe84VC5avA0pI7R0phj8uuNPUB8A_b0Ls,6400
|
|
4
|
+
passgate/gate.py,sha256=4xYYg_T5DnK9VWONRKu21PYt1KqkNiz3Hru1u4zkQk8,5530
|
|
5
|
+
passgate/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
passgate/stats.py,sha256=gGbK-ePGWeJzuwEflhKgRp0bJbCjZUFGuq23pYsX2E0,2907
|
|
7
|
+
passgate-0.1.1.dist-info/licenses/LICENSE,sha256=f409aSdfGpgy5kMR99eFaIPNwFDJfW41IpiNE_elcZ0,1072
|
|
8
|
+
passgate-0.1.1.dist-info/METADATA,sha256=usWh-K8x62azXiMhxcZwZwKmhclxP1O14pNTN745ERA,4639
|
|
9
|
+
passgate-0.1.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
10
|
+
passgate-0.1.1.dist-info/entry_points.txt,sha256=87mez3bdpYkfbS9rna2k2ghIooF1x2NN5oq_buNc-2g,47
|
|
11
|
+
passgate-0.1.1.dist-info/top_level.txt,sha256=yuEx2ys9Uivw2J5m8UDwtSH3xy3kMPlZTSw3q7Bfr_Q,9
|
|
12
|
+
passgate-0.1.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 calasdan-sketch
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
passgate
|