bitskitten 0.3.0__tar.gz → 0.4.0__tar.gz
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.
- {bitskitten-0.3.0 → bitskitten-0.4.0}/PKG-INFO +60 -3
- {bitskitten-0.3.0 → bitskitten-0.4.0}/README.md +59 -2
- {bitskitten-0.3.0 → bitskitten-0.4.0}/__init__.py +3 -1
- bitskitten-0.4.0/bandit.py +266 -0
- {bitskitten-0.3.0 → bitskitten-0.4.0}/bitskitten.egg-info/PKG-INFO +60 -3
- {bitskitten-0.3.0 → bitskitten-0.4.0}/bitskitten.egg-info/SOURCES.txt +14 -0
- {bitskitten-0.3.0 → bitskitten-0.4.0}/pyproject.toml +3 -2
- bitskitten-0.4.0/qa/__init__.py +52 -0
- bitskitten-0.4.0/qa/checks.py +230 -0
- bitskitten-0.4.0/qa/failures.py +137 -0
- bitskitten-0.4.0/qa/judge.py +322 -0
- bitskitten-0.4.0/qa/runner.py +167 -0
- bitskitten-0.4.0/qa/scenario.py +211 -0
- bitskitten-0.4.0/qa/users.py +339 -0
- bitskitten-0.4.0/tests/test_bandit.py +134 -0
- bitskitten-0.4.0/tests/test_qa.py +205 -0
- bitskitten-0.4.0/tests/test_qa_judge.py +142 -0
- bitskitten-0.4.0/tests/test_qa_runner.py +148 -0
- bitskitten-0.4.0/tests/test_qa_users.py +186 -0
- {bitskitten-0.3.0 → bitskitten-0.4.0}/LICENSE +0 -0
- {bitskitten-0.3.0 → bitskitten-0.4.0}/bitskitten.egg-info/dependency_links.txt +0 -0
- {bitskitten-0.3.0 → bitskitten-0.4.0}/bitskitten.egg-info/requires.txt +0 -0
- {bitskitten-0.3.0 → bitskitten-0.4.0}/bitskitten.egg-info/top_level.txt +0 -0
- {bitskitten-0.3.0 → bitskitten-0.4.0}/classes.py +0 -0
- {bitskitten-0.3.0 → bitskitten-0.4.0}/input.py +0 -0
- {bitskitten-0.3.0 → bitskitten-0.4.0}/metrics.py +0 -0
- {bitskitten-0.3.0 → bitskitten-0.4.0}/output.py +0 -0
- {bitskitten-0.3.0 → bitskitten-0.4.0}/setup.cfg +0 -0
- {bitskitten-0.3.0 → bitskitten-0.4.0}/tests/test_fit_time.py +0 -0
- {bitskitten-0.3.0 → bitskitten-0.4.0}/tests/test_smoke.py +0 -0
- {bitskitten-0.3.0 → bitskitten-0.4.0}/text.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: bitskitten
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.0
|
|
4
4
|
Summary: EDA reports, plots and sklearn-compatible encoders
|
|
5
5
|
Author: Caerno
|
|
6
6
|
License-Expression: Apache-2.0
|
|
@@ -152,6 +152,61 @@ recall — a class-agnostic generalization of F1 for when no class is "the posit
|
|
|
152
152
|
A class that is never predicted or never recovered pulls it to 0. `harmonic_from_confusion(conf)`
|
|
153
153
|
returns `(score, precision[], recall[])` from a ready confusion matrix.
|
|
154
154
|
|
|
155
|
+
## Test scheduler for flaky suites
|
|
156
|
+
|
|
157
|
+
```python
|
|
158
|
+
from bitskitten.bandit import ThompsonScheduler
|
|
159
|
+
|
|
160
|
+
sched = ThompsonScheduler(["happy_path", "reschedule", "angry_user"],
|
|
161
|
+
threshold=0.9, seed=0)
|
|
162
|
+
report = sched.run(run_scenario, budget=80) # run_scenario(name) -> bool
|
|
163
|
+
print(report) # runs, passes, mean, 95 % interval, pass^3, verdict per scenario
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
For suites where one run of a scenario is a coin flip (LLM bots, anything
|
|
167
|
+
stochastic). Each scenario carries a Beta posterior over its pass rate; the next
|
|
168
|
+
run goes to the scenario most likely to fail (Thompson sampling), scenarios whose
|
|
169
|
+
interval has cleared or missed the threshold are retired, and the loop stops when
|
|
170
|
+
nothing is left to learn or the budget is out. `pass_power(alpha, beta, k)` is the
|
|
171
|
+
tau-bench pass^k with the posterior integrated out; `width=` retires scenarios that
|
|
172
|
+
sit on the threshold once their interval is narrow enough; `min_runs=` (default 3)
|
|
173
|
+
stops a single failure from deciding a verdict.
|
|
174
|
+
|
|
175
|
+
## Regression testing for dialogue agents
|
|
176
|
+
|
|
177
|
+
```python
|
|
178
|
+
from bitskitten.qa import Suite, Judge, Checklist, ScriptedUser, TopicClassifier, BotStep, format_report
|
|
179
|
+
|
|
180
|
+
suite = Suite(scenarios, # Scenario.from_dict(...) per YAML entry
|
|
181
|
+
new_bot=lambda sc: MyBot(), # bot(text) -> str | BotStep(text, state, slots, signals)
|
|
182
|
+
new_user=lambda sc, seed: ScriptedUser(classify, asks, facts=sc.facts, seed=seed),
|
|
183
|
+
gates={"collecting_states": {"collecting_date"}},
|
|
184
|
+
judge=Judge(model, Checklist.from_dicts(items))) # model(prompt) -> str, any provider
|
|
185
|
+
result = suite.run(budget=80, threshold=0.9, max_runs=40)
|
|
186
|
+
print(result.report) # per scenario: runs, mean, 95 % interval, pass^3, verdict
|
|
187
|
+
print(format_report(result.failures)) # failed runs grouped by what failed
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
For bots where one run is a coin flip. Per run, cheapest first: the outcome
|
|
191
|
+
against the scenario and trace invariants (stuck in a state, the same reply
|
|
192
|
+
verbatim, invalid slot value, a number not in the allowed set, a scripted user's
|
|
193
|
+
record of re-asks) need no model; the judge is called only on runs that pass
|
|
194
|
+
them. The next run goes where a failure is most likely (Thompson sampling);
|
|
195
|
+
decided scenarios retire, the loop stops when nothing is left to learn.
|
|
196
|
+
|
|
197
|
+
- **Users.** `ScriptedUser` reacts to what the bot said (markers you supply),
|
|
198
|
+
hands out facts and records `repeated_ask` / `unexpected_ask` instead of
|
|
199
|
+
quietly answering them. `MarkovUsers` varies wording from real utterances at
|
|
200
|
+
zero model cost. `CallableUser` wraps any model.
|
|
201
|
+
- **Judge.** Repeated judging merges binary items by majority, not by mean.
|
|
202
|
+
`item_agreement(judged, human)` gives per-item kappa against your own labels
|
|
203
|
+
— check it before trusting an item; `pick_threshold` picks the score cut.
|
|
204
|
+
- **Cost of a verdict.** Proving "passes at least 90 %" at 95 % takes 35 clean
|
|
205
|
+
runs in a row; that is the threshold's price, not the scheduler's. A scenario
|
|
206
|
+
sitting right at the threshold cannot be decided cheaply — cap it with `max_runs`.
|
|
207
|
+
- `validate_scenarios(entries, Vocabulary(...))` checks a scenario file and flags
|
|
208
|
+
absolute dates that will expire.
|
|
209
|
+
|
|
155
210
|
## Plots
|
|
156
211
|
|
|
157
212
|
```python
|
|
@@ -215,8 +270,10 @@ pytest
|
|
|
215
270
|
The repo root *is* the package (flat layout), so the clone has to be in a folder named
|
|
216
271
|
`bitskitten` for `pytest` to import it; CI installs the wheel first for the same reason.
|
|
217
272
|
|
|
218
|
-
The drop-in zip in `download/` is
|
|
273
|
+
The drop-in zip in `download/` is built from committed files only, so no `__pycache__`
|
|
274
|
+
gets in:
|
|
219
275
|
|
|
220
276
|
```bash
|
|
221
|
-
|
|
277
|
+
git archive --format=zip -o download/bitskitten.zip HEAD \
|
|
278
|
+
__init__.py bandit.py classes.py input.py metrics.py output.py text.py qa
|
|
222
279
|
```
|
|
@@ -131,6 +131,61 @@ recall — a class-agnostic generalization of F1 for when no class is "the posit
|
|
|
131
131
|
A class that is never predicted or never recovered pulls it to 0. `harmonic_from_confusion(conf)`
|
|
132
132
|
returns `(score, precision[], recall[])` from a ready confusion matrix.
|
|
133
133
|
|
|
134
|
+
## Test scheduler for flaky suites
|
|
135
|
+
|
|
136
|
+
```python
|
|
137
|
+
from bitskitten.bandit import ThompsonScheduler
|
|
138
|
+
|
|
139
|
+
sched = ThompsonScheduler(["happy_path", "reschedule", "angry_user"],
|
|
140
|
+
threshold=0.9, seed=0)
|
|
141
|
+
report = sched.run(run_scenario, budget=80) # run_scenario(name) -> bool
|
|
142
|
+
print(report) # runs, passes, mean, 95 % interval, pass^3, verdict per scenario
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
For suites where one run of a scenario is a coin flip (LLM bots, anything
|
|
146
|
+
stochastic). Each scenario carries a Beta posterior over its pass rate; the next
|
|
147
|
+
run goes to the scenario most likely to fail (Thompson sampling), scenarios whose
|
|
148
|
+
interval has cleared or missed the threshold are retired, and the loop stops when
|
|
149
|
+
nothing is left to learn or the budget is out. `pass_power(alpha, beta, k)` is the
|
|
150
|
+
tau-bench pass^k with the posterior integrated out; `width=` retires scenarios that
|
|
151
|
+
sit on the threshold once their interval is narrow enough; `min_runs=` (default 3)
|
|
152
|
+
stops a single failure from deciding a verdict.
|
|
153
|
+
|
|
154
|
+
## Regression testing for dialogue agents
|
|
155
|
+
|
|
156
|
+
```python
|
|
157
|
+
from bitskitten.qa import Suite, Judge, Checklist, ScriptedUser, TopicClassifier, BotStep, format_report
|
|
158
|
+
|
|
159
|
+
suite = Suite(scenarios, # Scenario.from_dict(...) per YAML entry
|
|
160
|
+
new_bot=lambda sc: MyBot(), # bot(text) -> str | BotStep(text, state, slots, signals)
|
|
161
|
+
new_user=lambda sc, seed: ScriptedUser(classify, asks, facts=sc.facts, seed=seed),
|
|
162
|
+
gates={"collecting_states": {"collecting_date"}},
|
|
163
|
+
judge=Judge(model, Checklist.from_dicts(items))) # model(prompt) -> str, any provider
|
|
164
|
+
result = suite.run(budget=80, threshold=0.9, max_runs=40)
|
|
165
|
+
print(result.report) # per scenario: runs, mean, 95 % interval, pass^3, verdict
|
|
166
|
+
print(format_report(result.failures)) # failed runs grouped by what failed
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
For bots where one run is a coin flip. Per run, cheapest first: the outcome
|
|
170
|
+
against the scenario and trace invariants (stuck in a state, the same reply
|
|
171
|
+
verbatim, invalid slot value, a number not in the allowed set, a scripted user's
|
|
172
|
+
record of re-asks) need no model; the judge is called only on runs that pass
|
|
173
|
+
them. The next run goes where a failure is most likely (Thompson sampling);
|
|
174
|
+
decided scenarios retire, the loop stops when nothing is left to learn.
|
|
175
|
+
|
|
176
|
+
- **Users.** `ScriptedUser` reacts to what the bot said (markers you supply),
|
|
177
|
+
hands out facts and records `repeated_ask` / `unexpected_ask` instead of
|
|
178
|
+
quietly answering them. `MarkovUsers` varies wording from real utterances at
|
|
179
|
+
zero model cost. `CallableUser` wraps any model.
|
|
180
|
+
- **Judge.** Repeated judging merges binary items by majority, not by mean.
|
|
181
|
+
`item_agreement(judged, human)` gives per-item kappa against your own labels
|
|
182
|
+
— check it before trusting an item; `pick_threshold` picks the score cut.
|
|
183
|
+
- **Cost of a verdict.** Proving "passes at least 90 %" at 95 % takes 35 clean
|
|
184
|
+
runs in a row; that is the threshold's price, not the scheduler's. A scenario
|
|
185
|
+
sitting right at the threshold cannot be decided cheaply — cap it with `max_runs`.
|
|
186
|
+
- `validate_scenarios(entries, Vocabulary(...))` checks a scenario file and flags
|
|
187
|
+
absolute dates that will expire.
|
|
188
|
+
|
|
134
189
|
## Plots
|
|
135
190
|
|
|
136
191
|
```python
|
|
@@ -194,8 +249,10 @@ pytest
|
|
|
194
249
|
The repo root *is* the package (flat layout), so the clone has to be in a folder named
|
|
195
250
|
`bitskitten` for `pytest` to import it; CI installs the wheel first for the same reason.
|
|
196
251
|
|
|
197
|
-
The drop-in zip in `download/` is
|
|
252
|
+
The drop-in zip in `download/` is built from committed files only, so no `__pycache__`
|
|
253
|
+
gets in:
|
|
198
254
|
|
|
199
255
|
```bash
|
|
200
|
-
|
|
256
|
+
git archive --format=zip -o download/bitskitten.zip HEAD \
|
|
257
|
+
__init__.py bandit.py classes.py input.py metrics.py output.py text.py qa
|
|
201
258
|
```
|
|
@@ -6,8 +6,9 @@ Submodules stay importable on their own (`from bitskitten import output`),
|
|
|
6
6
|
which is also how the zipped drop-in build is used: `from classes import NanFixer`.
|
|
7
7
|
'''
|
|
8
8
|
|
|
9
|
-
__version__ = "0.
|
|
9
|
+
__version__ = "0.4.0"
|
|
10
10
|
|
|
11
|
+
from .bandit import ThompsonScheduler, pass_power
|
|
11
12
|
from .classes import Digitalize, Encoder, FeatureTrans, NanFixer, SlowPolyLinearReg
|
|
12
13
|
from .input import number
|
|
13
14
|
from .metrics import harmonic_from_confusion, harmonic_score, harmonic_scorer
|
|
@@ -24,6 +25,7 @@ from .output import (
|
|
|
24
25
|
)
|
|
25
26
|
|
|
26
27
|
__all__ = [
|
|
28
|
+
"ThompsonScheduler", "pass_power",
|
|
27
29
|
"Digitalize", "Encoder", "FeatureTrans", "NanFixer", "SlowPolyLinearReg",
|
|
28
30
|
"number",
|
|
29
31
|
"harmonic_from_confusion", "harmonic_score", "harmonic_scorer",
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
"""Thompson-sampling scheduler for stochastic test scenarios.
|
|
2
|
+
|
|
3
|
+
Regression suites for LLM applications are expensive and flaky: one run of a
|
|
4
|
+
scenario is a coin flip with an unknown pass rate. `ThompsonScheduler` keeps a
|
|
5
|
+
Beta posterior per scenario, spends the next run where it is most likely to
|
|
6
|
+
find a failure (Thompson sampling on the failure probability) and tells you
|
|
7
|
+
when to stop: every scenario is *decided* against the pass threshold, or its
|
|
8
|
+
posterior interval is narrow enough, or the budget is gone.
|
|
9
|
+
|
|
10
|
+
sched = ThompsonScheduler(["happy_path", "reschedule", "angry"],
|
|
11
|
+
threshold=0.9, seed=0)
|
|
12
|
+
while not sched.done(budget=60):
|
|
13
|
+
name = sched.pick()
|
|
14
|
+
sched.update(name, passed=run_once(name))
|
|
15
|
+
print(sched.report())
|
|
16
|
+
|
|
17
|
+
What a verdict costs is set by the threshold, not by the scheduler: proving
|
|
18
|
+
"passes at least 90 % of the time" at 95 % credibility under a flat prior takes
|
|
19
|
+
35 clean runs in a row (0.025 ** (1/36) > 0.9). Lower `threshold` or `level`
|
|
20
|
+
when that is too expensive; spending is where Thompson sampling helps.
|
|
21
|
+
|
|
22
|
+
Decided scenarios are retired from `pick()`: otherwise a scenario known to be
|
|
23
|
+
broken keeps winning the draw (its failure probability is ~1) and the budget
|
|
24
|
+
never reaches the ones still in doubt.
|
|
25
|
+
|
|
26
|
+
No LLM, no I/O: `update()` takes a bool, everything else is arithmetic.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
from dataclasses import dataclass, field
|
|
32
|
+
from typing import Dict, Iterable, List, Optional, Tuple
|
|
33
|
+
|
|
34
|
+
import numpy as np
|
|
35
|
+
import pandas as pd
|
|
36
|
+
|
|
37
|
+
__all__ = ["Arm", "ThompsonScheduler", "pass_power", "beta_interval"]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass
|
|
41
|
+
class Arm:
|
|
42
|
+
"""Posterior state of one scenario: Beta(alpha, beta) over its pass rate."""
|
|
43
|
+
|
|
44
|
+
name: str
|
|
45
|
+
alpha: float = 1.0
|
|
46
|
+
beta: float = 1.0
|
|
47
|
+
runs: int = 0
|
|
48
|
+
passes: int = 0
|
|
49
|
+
history: List[bool] = field(default_factory=list)
|
|
50
|
+
_interval: Optional[Tuple[float, float]] = field(default=None, repr=False)
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def mean(self) -> float:
|
|
54
|
+
return self.alpha / (self.alpha + self.beta)
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def variance(self) -> float:
|
|
58
|
+
n = self.alpha + self.beta
|
|
59
|
+
return self.alpha * self.beta / (n * n * (n + 1))
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def pass_power(alpha: float, beta: float, k: int) -> float:
|
|
63
|
+
"""E[p^k] under Beta(alpha, beta): probability of k consecutive passes.
|
|
64
|
+
|
|
65
|
+
Closed form: prod_{i<k} (alpha + i) / (alpha + beta + i). This is the
|
|
66
|
+
tau-bench pass^k statistic with the posterior integrated out.
|
|
67
|
+
"""
|
|
68
|
+
if k < 0:
|
|
69
|
+
raise ValueError("k must be >= 0")
|
|
70
|
+
out = 1.0
|
|
71
|
+
for i in range(k):
|
|
72
|
+
out *= (alpha + i) / (alpha + beta + i)
|
|
73
|
+
return out
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def beta_interval(alpha: float, beta: float, level: float = 0.95, *,
|
|
77
|
+
rng: Optional[np.random.Generator] = None,
|
|
78
|
+
draws: int = 20_000) -> Tuple[float, float]:
|
|
79
|
+
"""Equal-tailed credible interval of Beta(alpha, beta) by Monte Carlo.
|
|
80
|
+
|
|
81
|
+
numpy has no Beta quantile function and scipy is not a dependency; with
|
|
82
|
+
20 000 draws the quantile error is ~0.005, below any decision threshold
|
|
83
|
+
one would set on a pass rate.
|
|
84
|
+
"""
|
|
85
|
+
if not 0 < level < 1:
|
|
86
|
+
raise ValueError("level must be in (0, 1)")
|
|
87
|
+
rng = np.random.default_rng(0) if rng is None else rng
|
|
88
|
+
sample = rng.beta(alpha, beta, size=draws)
|
|
89
|
+
lo, hi = np.quantile(sample, [(1 - level) / 2, 1 - (1 - level) / 2])
|
|
90
|
+
return float(lo), float(hi)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class ThompsonScheduler:
|
|
94
|
+
"""Allocate scenario runs by Thompson sampling on the failure probability.
|
|
95
|
+
|
|
96
|
+
Parameters
|
|
97
|
+
----------
|
|
98
|
+
scenarios : names of the scenarios (arms).
|
|
99
|
+
threshold : pass rate a scenario must clear; a scenario is *decided* once
|
|
100
|
+
its credible interval lies entirely above or below it.
|
|
101
|
+
level : credibility of the interval (0.95 = 95 %).
|
|
102
|
+
width : optional; a scenario whose interval is already narrower than this
|
|
103
|
+
is also retired — paying for more runs would not change the verdict.
|
|
104
|
+
max_runs : optional cap per scenario. A scenario whose true pass rate sits
|
|
105
|
+
right at the threshold (0.87 against 0.9) cannot be decided in any
|
|
106
|
+
affordable number of runs, and Thompson sampling keeps feeding it — on
|
|
107
|
+
one seed it took 101 of 120 runs and left a perfect scenario without a
|
|
108
|
+
verdict. The cap retires it as 'undecided' and frees the budget.
|
|
109
|
+
(`width` is a poor substitute: an all-pass scenario's interval stays
|
|
110
|
+
wide until it is proven, so `width` retires it unproven.)
|
|
111
|
+
min_runs : no scenario is retired before this many runs. Under a flat
|
|
112
|
+
prior a single failure already puts the 95 % interval below 0.9, so
|
|
113
|
+
without a floor 5 % of genuinely good scenarios would be branded
|
|
114
|
+
'fail' on their first run.
|
|
115
|
+
prior : (alpha, beta) of the Beta prior on the pass rate; (1, 1) is flat.
|
|
116
|
+
Per-scenario priors: pass a dict name -> (alpha, beta).
|
|
117
|
+
seed : seed for the sampler; same seed + same updates = same picks.
|
|
118
|
+
"""
|
|
119
|
+
|
|
120
|
+
def __init__(self, scenarios: Iterable[str], *, threshold: float = 0.9,
|
|
121
|
+
level: float = 0.95, width: Optional[float] = None,
|
|
122
|
+
min_runs: int = 3, max_runs: Optional[int] = None,
|
|
123
|
+
prior=(1.0, 1.0),
|
|
124
|
+
seed: Optional[int] = None):
|
|
125
|
+
names = list(scenarios)
|
|
126
|
+
if not names:
|
|
127
|
+
raise ValueError("at least one scenario is required")
|
|
128
|
+
if len(set(names)) != len(names):
|
|
129
|
+
raise ValueError("scenario names must be unique")
|
|
130
|
+
if not 0 < threshold < 1:
|
|
131
|
+
raise ValueError("threshold must be in (0, 1)")
|
|
132
|
+
if not 0 < level < 1:
|
|
133
|
+
raise ValueError("level must be in (0, 1)")
|
|
134
|
+
if width is not None and width <= 0:
|
|
135
|
+
raise ValueError("width must be positive")
|
|
136
|
+
if min_runs < 0:
|
|
137
|
+
raise ValueError("min_runs must be >= 0")
|
|
138
|
+
if max_runs is not None and max_runs < max(1, min_runs):
|
|
139
|
+
raise ValueError("max_runs must be >= min_runs and >= 1")
|
|
140
|
+
self.min_runs = min_runs
|
|
141
|
+
self.max_runs = max_runs
|
|
142
|
+
self.threshold = threshold
|
|
143
|
+
self.level = level
|
|
144
|
+
self.width = width
|
|
145
|
+
self.rng = np.random.default_rng(seed)
|
|
146
|
+
self._irng = np.random.default_rng(seed) # intervals, apart from picks
|
|
147
|
+
self.arms: Dict[str, Arm] = {}
|
|
148
|
+
for name in names:
|
|
149
|
+
a, b = prior[name] if isinstance(prior, dict) else prior
|
|
150
|
+
if a <= 0 or b <= 0:
|
|
151
|
+
raise ValueError("prior parameters must be positive")
|
|
152
|
+
self.arms[name] = Arm(name, float(a), float(b))
|
|
153
|
+
|
|
154
|
+
# -- posterior summaries -----------------------------------------------
|
|
155
|
+
|
|
156
|
+
def interval(self, name: str) -> Tuple[float, float]:
|
|
157
|
+
"""Credible interval of the scenario's pass rate (cached per update)."""
|
|
158
|
+
arm = self.arms[name]
|
|
159
|
+
if arm._interval is None:
|
|
160
|
+
arm._interval = beta_interval(arm.alpha, arm.beta, self.level,
|
|
161
|
+
rng=self._irng)
|
|
162
|
+
return arm._interval
|
|
163
|
+
|
|
164
|
+
def status(self, name: str) -> str:
|
|
165
|
+
"""'pass' if the whole interval is above the threshold, 'fail' if it is
|
|
166
|
+
below, else 'undecided'."""
|
|
167
|
+
lo, hi = self.interval(name)
|
|
168
|
+
if lo >= self.threshold:
|
|
169
|
+
return "pass"
|
|
170
|
+
if hi < self.threshold:
|
|
171
|
+
return "fail"
|
|
172
|
+
return "undecided"
|
|
173
|
+
|
|
174
|
+
def active(self) -> List[str]:
|
|
175
|
+
"""Scenarios still worth a run: under `min_runs`, or undecided and
|
|
176
|
+
not yet narrow enough."""
|
|
177
|
+
out = []
|
|
178
|
+
for name, arm in self.arms.items():
|
|
179
|
+
if self.max_runs is not None and arm.runs >= self.max_runs:
|
|
180
|
+
continue
|
|
181
|
+
if arm.runs < self.min_runs:
|
|
182
|
+
out.append(name)
|
|
183
|
+
continue
|
|
184
|
+
if self.status(name) != "undecided":
|
|
185
|
+
continue
|
|
186
|
+
if self.width is not None:
|
|
187
|
+
lo, hi = self.interval(name)
|
|
188
|
+
if hi - lo <= self.width:
|
|
189
|
+
continue
|
|
190
|
+
out.append(name)
|
|
191
|
+
return out
|
|
192
|
+
|
|
193
|
+
@property
|
|
194
|
+
def total_runs(self) -> int:
|
|
195
|
+
return sum(a.runs for a in self.arms.values())
|
|
196
|
+
|
|
197
|
+
# -- allocation ---------------------------------------------------------
|
|
198
|
+
|
|
199
|
+
def pick(self) -> Optional[str]:
|
|
200
|
+
"""Scenario to run next, or None when nothing is left to learn.
|
|
201
|
+
|
|
202
|
+
Argmax of the sampled failure probability over active scenarios.
|
|
203
|
+
Sampling from the posterior (rather than taking the mean) is what
|
|
204
|
+
keeps rarely-run scenarios in play: a wide posterior sometimes draws
|
|
205
|
+
a high failure probability and gets its turn.
|
|
206
|
+
"""
|
|
207
|
+
best, best_fail = None, -1.0
|
|
208
|
+
for name in self.active():
|
|
209
|
+
arm = self.arms[name]
|
|
210
|
+
fail = 1.0 - self.rng.beta(arm.alpha, arm.beta)
|
|
211
|
+
if fail > best_fail:
|
|
212
|
+
best, best_fail = name, fail
|
|
213
|
+
return best
|
|
214
|
+
|
|
215
|
+
def update(self, name: str, passed: bool) -> None:
|
|
216
|
+
arm = self.arms[name]
|
|
217
|
+
arm.runs += 1
|
|
218
|
+
arm.history.append(bool(passed))
|
|
219
|
+
if passed:
|
|
220
|
+
arm.passes += 1
|
|
221
|
+
arm.alpha += 1
|
|
222
|
+
else:
|
|
223
|
+
arm.beta += 1
|
|
224
|
+
arm._interval = None
|
|
225
|
+
|
|
226
|
+
def done(self, *, budget: Optional[int] = None) -> bool:
|
|
227
|
+
"""True when the budget is spent or no scenario is active."""
|
|
228
|
+
if budget is not None and self.total_runs >= budget:
|
|
229
|
+
return True
|
|
230
|
+
return not self.active()
|
|
231
|
+
|
|
232
|
+
# -- reporting ----------------------------------------------------------
|
|
233
|
+
|
|
234
|
+
def report(self, *, k: int = 3) -> pd.DataFrame:
|
|
235
|
+
"""One row per scenario: runs, passes, posterior mean, interval,
|
|
236
|
+
pass^k and the verdict against the threshold. Sorted worst first."""
|
|
237
|
+
rows = []
|
|
238
|
+
for name, arm in self.arms.items():
|
|
239
|
+
lo, hi = self.interval(name)
|
|
240
|
+
rows.append({
|
|
241
|
+
"scenario": name,
|
|
242
|
+
"runs": arm.runs,
|
|
243
|
+
"passes": arm.passes,
|
|
244
|
+
"mean": arm.mean,
|
|
245
|
+
"lo": lo,
|
|
246
|
+
"hi": hi,
|
|
247
|
+
f"pass^{k}": pass_power(arm.alpha, arm.beta, k),
|
|
248
|
+
"verdict": self.status(name),
|
|
249
|
+
})
|
|
250
|
+
return (pd.DataFrame(rows)
|
|
251
|
+
.sort_values(["mean", "runs"])
|
|
252
|
+
.reset_index(drop=True))
|
|
253
|
+
|
|
254
|
+
def run(self, run_once, *, budget: int, k: int = 3) -> pd.DataFrame:
|
|
255
|
+
"""Drive the loop: pick -> run_once(name) -> update, until `done()`.
|
|
256
|
+
|
|
257
|
+
`run_once(name)` must return a truthy value for a pass. Returns the
|
|
258
|
+
final report. Raising inside `run_once` aborts the loop; the state
|
|
259
|
+
collected so far stays on the scheduler.
|
|
260
|
+
"""
|
|
261
|
+
if budget <= 0:
|
|
262
|
+
raise ValueError("budget must be positive")
|
|
263
|
+
while not self.done(budget=budget):
|
|
264
|
+
name = self.pick()
|
|
265
|
+
self.update(name, bool(run_once(name)))
|
|
266
|
+
return self.report(k=k)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: bitskitten
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.0
|
|
4
4
|
Summary: EDA reports, plots and sklearn-compatible encoders
|
|
5
5
|
Author: Caerno
|
|
6
6
|
License-Expression: Apache-2.0
|
|
@@ -152,6 +152,61 @@ recall — a class-agnostic generalization of F1 for when no class is "the posit
|
|
|
152
152
|
A class that is never predicted or never recovered pulls it to 0. `harmonic_from_confusion(conf)`
|
|
153
153
|
returns `(score, precision[], recall[])` from a ready confusion matrix.
|
|
154
154
|
|
|
155
|
+
## Test scheduler for flaky suites
|
|
156
|
+
|
|
157
|
+
```python
|
|
158
|
+
from bitskitten.bandit import ThompsonScheduler
|
|
159
|
+
|
|
160
|
+
sched = ThompsonScheduler(["happy_path", "reschedule", "angry_user"],
|
|
161
|
+
threshold=0.9, seed=0)
|
|
162
|
+
report = sched.run(run_scenario, budget=80) # run_scenario(name) -> bool
|
|
163
|
+
print(report) # runs, passes, mean, 95 % interval, pass^3, verdict per scenario
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
For suites where one run of a scenario is a coin flip (LLM bots, anything
|
|
167
|
+
stochastic). Each scenario carries a Beta posterior over its pass rate; the next
|
|
168
|
+
run goes to the scenario most likely to fail (Thompson sampling), scenarios whose
|
|
169
|
+
interval has cleared or missed the threshold are retired, and the loop stops when
|
|
170
|
+
nothing is left to learn or the budget is out. `pass_power(alpha, beta, k)` is the
|
|
171
|
+
tau-bench pass^k with the posterior integrated out; `width=` retires scenarios that
|
|
172
|
+
sit on the threshold once their interval is narrow enough; `min_runs=` (default 3)
|
|
173
|
+
stops a single failure from deciding a verdict.
|
|
174
|
+
|
|
175
|
+
## Regression testing for dialogue agents
|
|
176
|
+
|
|
177
|
+
```python
|
|
178
|
+
from bitskitten.qa import Suite, Judge, Checklist, ScriptedUser, TopicClassifier, BotStep, format_report
|
|
179
|
+
|
|
180
|
+
suite = Suite(scenarios, # Scenario.from_dict(...) per YAML entry
|
|
181
|
+
new_bot=lambda sc: MyBot(), # bot(text) -> str | BotStep(text, state, slots, signals)
|
|
182
|
+
new_user=lambda sc, seed: ScriptedUser(classify, asks, facts=sc.facts, seed=seed),
|
|
183
|
+
gates={"collecting_states": {"collecting_date"}},
|
|
184
|
+
judge=Judge(model, Checklist.from_dicts(items))) # model(prompt) -> str, any provider
|
|
185
|
+
result = suite.run(budget=80, threshold=0.9, max_runs=40)
|
|
186
|
+
print(result.report) # per scenario: runs, mean, 95 % interval, pass^3, verdict
|
|
187
|
+
print(format_report(result.failures)) # failed runs grouped by what failed
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
For bots where one run is a coin flip. Per run, cheapest first: the outcome
|
|
191
|
+
against the scenario and trace invariants (stuck in a state, the same reply
|
|
192
|
+
verbatim, invalid slot value, a number not in the allowed set, a scripted user's
|
|
193
|
+
record of re-asks) need no model; the judge is called only on runs that pass
|
|
194
|
+
them. The next run goes where a failure is most likely (Thompson sampling);
|
|
195
|
+
decided scenarios retire, the loop stops when nothing is left to learn.
|
|
196
|
+
|
|
197
|
+
- **Users.** `ScriptedUser` reacts to what the bot said (markers you supply),
|
|
198
|
+
hands out facts and records `repeated_ask` / `unexpected_ask` instead of
|
|
199
|
+
quietly answering them. `MarkovUsers` varies wording from real utterances at
|
|
200
|
+
zero model cost. `CallableUser` wraps any model.
|
|
201
|
+
- **Judge.** Repeated judging merges binary items by majority, not by mean.
|
|
202
|
+
`item_agreement(judged, human)` gives per-item kappa against your own labels
|
|
203
|
+
— check it before trusting an item; `pick_threshold` picks the score cut.
|
|
204
|
+
- **Cost of a verdict.** Proving "passes at least 90 %" at 95 % takes 35 clean
|
|
205
|
+
runs in a row; that is the threshold's price, not the scheduler's. A scenario
|
|
206
|
+
sitting right at the threshold cannot be decided cheaply — cap it with `max_runs`.
|
|
207
|
+
- `validate_scenarios(entries, Vocabulary(...))` checks a scenario file and flags
|
|
208
|
+
absolute dates that will expire.
|
|
209
|
+
|
|
155
210
|
## Plots
|
|
156
211
|
|
|
157
212
|
```python
|
|
@@ -215,8 +270,10 @@ pytest
|
|
|
215
270
|
The repo root *is* the package (flat layout), so the clone has to be in a folder named
|
|
216
271
|
`bitskitten` for `pytest` to import it; CI installs the wheel first for the same reason.
|
|
217
272
|
|
|
218
|
-
The drop-in zip in `download/` is
|
|
273
|
+
The drop-in zip in `download/` is built from committed files only, so no `__pycache__`
|
|
274
|
+
gets in:
|
|
219
275
|
|
|
220
276
|
```bash
|
|
221
|
-
|
|
277
|
+
git archive --format=zip -o download/bitskitten.zip HEAD \
|
|
278
|
+
__init__.py bandit.py classes.py input.py metrics.py output.py text.py qa
|
|
222
279
|
```
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
LICENSE
|
|
2
2
|
README.md
|
|
3
3
|
__init__.py
|
|
4
|
+
bandit.py
|
|
4
5
|
classes.py
|
|
5
6
|
input.py
|
|
6
7
|
metrics.py
|
|
@@ -8,6 +9,7 @@ output.py
|
|
|
8
9
|
pyproject.toml
|
|
9
10
|
text.py
|
|
10
11
|
./__init__.py
|
|
12
|
+
./bandit.py
|
|
11
13
|
./classes.py
|
|
12
14
|
./input.py
|
|
13
15
|
./metrics.py
|
|
@@ -18,5 +20,17 @@ bitskitten.egg-info/SOURCES.txt
|
|
|
18
20
|
bitskitten.egg-info/dependency_links.txt
|
|
19
21
|
bitskitten.egg-info/requires.txt
|
|
20
22
|
bitskitten.egg-info/top_level.txt
|
|
23
|
+
qa/__init__.py
|
|
24
|
+
qa/checks.py
|
|
25
|
+
qa/failures.py
|
|
26
|
+
qa/judge.py
|
|
27
|
+
qa/runner.py
|
|
28
|
+
qa/scenario.py
|
|
29
|
+
qa/users.py
|
|
30
|
+
tests/test_bandit.py
|
|
21
31
|
tests/test_fit_time.py
|
|
32
|
+
tests/test_qa.py
|
|
33
|
+
tests/test_qa_judge.py
|
|
34
|
+
tests/test_qa_runner.py
|
|
35
|
+
tests/test_qa_users.py
|
|
22
36
|
tests/test_smoke.py
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "bitskitten"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.4.0"
|
|
8
8
|
description = "EDA reports, plots and sklearn-compatible encoders"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.9"
|
|
@@ -29,10 +29,11 @@ Homepage = "https://github.com/Caerno/bitskit"
|
|
|
29
29
|
# flat layout: the repo root itself is the package,
|
|
30
30
|
# so `import classes` (zip drop-in) and `import bitskitten.classes` both work
|
|
31
31
|
[tool.setuptools]
|
|
32
|
-
packages = ["bitskitten"]
|
|
32
|
+
packages = ["bitskitten", "bitskitten.qa"]
|
|
33
33
|
|
|
34
34
|
[tool.setuptools.package-dir]
|
|
35
35
|
bitskitten = "."
|
|
36
|
+
"bitskitten.qa" = "qa"
|
|
36
37
|
|
|
37
38
|
[tool.pytest.ini_options]
|
|
38
39
|
testpaths = ["tests"]
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Judge-free regression testing for dialogue agents.
|
|
2
|
+
|
|
3
|
+
A `Scenario` says what a simulated user wants and what the agent must end up
|
|
4
|
+
with; a `Run` is what actually happened, turn by turn, with the agent's state
|
|
5
|
+
after each turn. Everything in this package is plain arithmetic over those two
|
|
6
|
+
records — no model calls, no I/O — so it can gate a pull request in seconds:
|
|
7
|
+
|
|
8
|
+
from bitskitten.qa import Scenario, Run, Turn, validate_run, check_run
|
|
9
|
+
|
|
10
|
+
scenario = Scenario(id="renew", name="Renew a library card", persona="...",
|
|
11
|
+
goal="renew the card", initial_message="Hi, my card expired",
|
|
12
|
+
expected={"state": "renewed", "slots_required": ["card_no"]})
|
|
13
|
+
run = Run(scenario_id="renew", turns=[Turn(1, "Hi, my card expired", "Card number?",
|
|
14
|
+
state_after="collecting_card_no")],
|
|
15
|
+
final_context={"state": "renewed", "slots": {"card_no": "123"}})
|
|
16
|
+
validate_run(run, scenario).failures # [] when the outcome matches
|
|
17
|
+
check_run(run.turns, collecting_states={"collecting_card_no"}) # loop / repeat invariants
|
|
18
|
+
|
|
19
|
+
Around that: simulated users (`ScriptedUser`, `MarkovUsers`, `CallableUser`),
|
|
20
|
+
a checklist `Judge` over any ``model(prompt) -> str`` with majority quorum and
|
|
21
|
+
calibration against human labels, and `Suite`, which lets `ThompsonScheduler`
|
|
22
|
+
pick the next scenario, runs the cheap gates first and calls the judge only on
|
|
23
|
+
runs that pass them. `group_failures` tells you what broke, grouped by signature.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from .scenario import Issue, Run, Scenario, Turn, Vocabulary, validate_scenarios
|
|
27
|
+
from .checks import (
|
|
28
|
+
ValidatorResult,
|
|
29
|
+
Violation,
|
|
30
|
+
check_grounded_numbers,
|
|
31
|
+
check_no_progress_loop,
|
|
32
|
+
check_run,
|
|
33
|
+
check_script_adherence,
|
|
34
|
+
check_slot_validity,
|
|
35
|
+
check_stuck_state,
|
|
36
|
+
validate_run,
|
|
37
|
+
)
|
|
38
|
+
from .failures import FailureGroup, FailureReport, classify_items, format_report, group_failures
|
|
39
|
+
from .users import CallableUser, MarkovUser, MarkovUsers, ScriptedUser, TopicClassifier
|
|
40
|
+
from .judge import Checklist, ChecklistItem, Judge, item_agreement, pick_threshold
|
|
41
|
+
from .runner import BotStep, Suite, SuiteResult, simulate
|
|
42
|
+
|
|
43
|
+
__all__ = [
|
|
44
|
+
"Scenario", "Turn", "Run", "Vocabulary", "Issue", "validate_scenarios",
|
|
45
|
+
"ValidatorResult", "Violation", "validate_run", "check_run",
|
|
46
|
+
"check_stuck_state", "check_no_progress_loop", "check_slot_validity",
|
|
47
|
+
"check_grounded_numbers", "check_script_adherence",
|
|
48
|
+
"FailureGroup", "FailureReport", "classify_items", "group_failures", "format_report",
|
|
49
|
+
"ScriptedUser", "TopicClassifier", "MarkovUsers", "MarkovUser", "CallableUser",
|
|
50
|
+
"Checklist", "ChecklistItem", "Judge", "item_agreement", "pick_threshold",
|
|
51
|
+
"BotStep", "Suite", "SuiteResult", "simulate",
|
|
52
|
+
]
|