bitskitten 0.3.0__tar.gz → 0.5.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.
Files changed (35) hide show
  1. {bitskitten-0.3.0/bitskitten.egg-info → bitskitten-0.5.0}/PKG-INFO +87 -16
  2. bitskitten-0.3.0/PKG-INFO → bitskitten-0.5.0/README.md +74 -29
  3. bitskitten-0.5.0/__init__.py +51 -0
  4. bitskitten-0.5.0/_deps.py +20 -0
  5. bitskitten-0.5.0/bandit.py +270 -0
  6. bitskitten-0.3.0/README.md → bitskitten-0.5.0/bitskitten.egg-info/PKG-INFO +100 -8
  7. {bitskitten-0.3.0 → bitskitten-0.5.0}/bitskitten.egg-info/SOURCES.txt +17 -0
  8. {bitskitten-0.3.0 → bitskitten-0.5.0}/bitskitten.egg-info/requires.txt +9 -1
  9. bitskitten-0.5.0/metrics.py +64 -0
  10. {bitskitten-0.3.0 → bitskitten-0.5.0}/pyproject.toml +9 -12
  11. bitskitten-0.5.0/qa/__init__.py +52 -0
  12. bitskitten-0.5.0/qa/checks.py +230 -0
  13. bitskitten-0.5.0/qa/failures.py +137 -0
  14. bitskitten-0.5.0/qa/judge.py +330 -0
  15. bitskitten-0.5.0/qa/runner.py +172 -0
  16. bitskitten-0.5.0/qa/scenario.py +211 -0
  17. bitskitten-0.5.0/qa/users.py +339 -0
  18. bitskitten-0.5.0/tests/test_bandit.py +144 -0
  19. bitskitten-0.5.0/tests/test_boundary.py +52 -0
  20. {bitskitten-0.3.0 → bitskitten-0.5.0}/tests/test_fit_time.py +12 -0
  21. bitskitten-0.5.0/tests/test_qa.py +205 -0
  22. bitskitten-0.5.0/tests/test_qa_judge.py +151 -0
  23. bitskitten-0.5.0/tests/test_qa_runner.py +150 -0
  24. bitskitten-0.5.0/tests/test_qa_users.py +186 -0
  25. bitskitten-0.3.0/__init__.py +0 -33
  26. bitskitten-0.3.0/metrics.py +0 -36
  27. {bitskitten-0.3.0 → bitskitten-0.5.0}/LICENSE +0 -0
  28. {bitskitten-0.3.0 → bitskitten-0.5.0}/bitskitten.egg-info/dependency_links.txt +0 -0
  29. {bitskitten-0.3.0 → bitskitten-0.5.0}/bitskitten.egg-info/top_level.txt +0 -0
  30. {bitskitten-0.3.0 → bitskitten-0.5.0}/classes.py +0 -0
  31. {bitskitten-0.3.0 → bitskitten-0.5.0}/input.py +0 -0
  32. {bitskitten-0.3.0 → bitskitten-0.5.0}/output.py +0 -0
  33. {bitskitten-0.3.0 → bitskitten-0.5.0}/setup.cfg +0 -0
  34. {bitskitten-0.3.0 → bitskitten-0.5.0}/tests/test_smoke.py +0 -0
  35. {bitskitten-0.3.0 → bitskitten-0.5.0}/text.py +0 -0
@@ -1,38 +1,49 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: bitskitten
3
- Version: 0.3.0
4
- Summary: EDA reports, plots and sklearn-compatible encoders
3
+ Version: 0.5.0
4
+ Summary: Small tools for data work (EDA, plots, sklearn-compatible encoders) and for testing LLM bots (scenario suites, checklist judge, Thompson-sampling scheduler); heavy dependencies only per extra
5
5
  Author: Caerno
6
6
  License-Expression: Apache-2.0
7
7
  Project-URL: Homepage, https://github.com/Caerno/bitskit
8
- Keywords: eda,pandas,sklearn,kaggle
8
+ Keywords: eda,pandas,sklearn,kaggle,llm,chatbot,testing,thompson-sampling
9
9
  Requires-Python: >=3.9
10
10
  Description-Content-Type: text/markdown
11
11
  License-File: LICENSE
12
12
  Requires-Dist: numpy>=1.21
13
- Requires-Dist: pandas>=1.3
14
- Requires-Dist: scikit-learn>=1.0
15
- Requires-Dist: matplotlib>=3.4
16
- Requires-Dist: seaborn>=0.11
17
- Requires-Dist: jinja2>=3
13
+ Provides-Extra: ml
14
+ Requires-Dist: pandas>=1.3; extra == "ml"
15
+ Requires-Dist: scikit-learn>=1.0; extra == "ml"
16
+ Provides-Extra: eda
17
+ Requires-Dist: pandas>=1.3; extra == "eda"
18
+ Requires-Dist: matplotlib>=3.4; extra == "eda"
19
+ Requires-Dist: seaborn>=0.11; extra == "eda"
20
+ Requires-Dist: jinja2>=3; extra == "eda"
21
+ Provides-Extra: all
22
+ Requires-Dist: bitskitten[eda,ml]; extra == "all"
18
23
  Provides-Extra: test
19
24
  Requires-Dist: pytest>=7; extra == "test"
20
25
  Dynamic: license-file
21
26
 
22
27
  # bitskitten
23
28
 
24
- A small toolbox of things I kept re-typing in every EDA notebook:
25
- quick dataset reports, a few plots, and sklearn-compatible encoders that can be
26
- dropped straight into a `Pipeline` / `GridSearchCV`.
29
+ A small toolbox of things I kept re-typing: quick dataset reports, a few plots and
30
+ sklearn-compatible encoders for EDA notebooks, and a regression harness for LLM bots
31
+ (scenario suites, checklist judge, Thompson-sampling scheduler).
27
32
 
28
33
  Nothing here is a framework. Each helper is one function or one class you can read in a minute.
29
34
 
30
35
  ## Install
31
36
 
32
37
  ```bash
33
- pip install bitskitten
38
+ pip install bitskitten # numpy only: test scheduler, bot regression harness, metric
39
+ pip install 'bitskitten[ml]' # + pandas, scikit-learn: encoders, NanFixer, harmonic_scorer
40
+ pip install 'bitskitten[eda]' # + pandas, matplotlib, seaborn: reports and plots
41
+ pip install 'bitskitten[all]' # everything
34
42
  ```
35
43
 
44
+ Each part loads its dependencies only when you use it: `import bitskitten` costs numpy,
45
+ not pandas and scikit-learn. A name whose extra is missing fails with the line to install.
46
+
36
47
  The latest commit: `pip install git+https://github.com/Caerno/bitskit.git`.
37
48
  On Kaggle / Colab the same lines work in a cell (`!pip install ...`).
38
49
  For a kernel with no internet, add
@@ -43,7 +54,7 @@ as a dataset and install it from disk:
43
54
  pip install --no-deps /kaggle/input/<your-dataset>/bitskit-main.zip
44
55
  ```
45
56
 
46
- Requires Python ≥ 3.9, numpy, pandas, scikit-learn, matplotlib, seaborn.
57
+ Requires Python ≥ 3.9 and numpy; the rest comes with the extras above.
47
58
 
48
59
  ## Quick start
49
60
 
@@ -152,6 +163,64 @@ recall — a class-agnostic generalization of F1 for when no class is "the posit
152
163
  A class that is never predicted or never recovered pulls it to 0. `harmonic_from_confusion(conf)`
153
164
  returns `(score, precision[], recall[])` from a ready confusion matrix.
154
165
 
166
+ ## Test scheduler for flaky suites
167
+
168
+ ```python
169
+ from bitskitten.bandit import ThompsonScheduler
170
+
171
+ sched = ThompsonScheduler(["happy_path", "reschedule", "angry_user"],
172
+ threshold=0.9, seed=0)
173
+ rows = sched.run(run_scenario, budget=80) # run_scenario(name) -> bool
174
+ # one dict per scenario, worst first: runs, passes, mean, 95 % interval, pass^3, verdict
175
+ print(sched.report()) # the same as a DataFrame, needs pandas
176
+ ```
177
+
178
+ For suites where one run of a scenario is a coin flip (LLM bots, anything
179
+ stochastic). Each scenario carries a Beta posterior over its pass rate; the next
180
+ run goes to the scenario most likely to fail (Thompson sampling), scenarios whose
181
+ interval has cleared or missed the threshold are retired, and the loop stops when
182
+ nothing is left to learn or the budget is out. `pass_power(alpha, beta, k)` is the
183
+ tau-bench pass^k with the posterior integrated out; `width=` retires scenarios that
184
+ sit on the threshold once their interval is narrow enough; `min_runs=` (default 3)
185
+ stops a single failure from deciding a verdict.
186
+
187
+ ## Regression testing for dialogue agents
188
+
189
+ ```python
190
+ from bitskitten.qa import Suite, Judge, Checklist, ScriptedUser, TopicClassifier, BotStep, format_report
191
+
192
+ suite = Suite(scenarios, # Scenario.from_dict(...) per YAML entry
193
+ new_bot=lambda sc: MyBot(), # bot(text) -> str | BotStep(text, state, slots, signals)
194
+ new_user=lambda sc, seed: ScriptedUser(classify, asks, facts=sc.facts, seed=seed),
195
+ gates={"collecting_states": {"collecting_date"}},
196
+ judge=Judge(model, Checklist.from_dicts(items))) # model(prompt) -> str, any provider
197
+ result = suite.run(budget=80, threshold=0.9, max_runs=40)
198
+ print(result.rows) # per scenario: runs, mean, 95 % interval, pass^3, verdict
199
+ # result.report: the same as a DataFrame, needs pandas
200
+ print(format_report(result.failures)) # failed runs grouped by what failed
201
+ ```
202
+
203
+ For bots where one run is a coin flip. Per run, cheapest first: the outcome
204
+ against the scenario and trace invariants (stuck in a state, the same reply
205
+ verbatim, invalid slot value, a number not in the allowed set, a scripted user's
206
+ record of re-asks) need no model; the judge is called only on runs that pass
207
+ them. The next run goes where a failure is most likely (Thompson sampling);
208
+ decided scenarios retire, the loop stops when nothing is left to learn.
209
+
210
+ - **Users.** `ScriptedUser` reacts to what the bot said (markers you supply),
211
+ hands out facts and records `repeated_ask` / `unexpected_ask` instead of
212
+ quietly answering them. `MarkovUsers` varies wording from real utterances at
213
+ zero model cost. `CallableUser` wraps any model.
214
+ - **Judge.** Repeated judging merges binary items by majority, not by mean.
215
+ `item_agreement_rows(judged, human)` gives per-item kappa against your own labels
216
+ (`item_agreement` — the same as a DataFrame)
217
+ — check it before trusting an item; `pick_threshold` picks the score cut.
218
+ - **Cost of a verdict.** Proving "passes at least 90 %" at 95 % takes 35 clean
219
+ runs in a row; that is the threshold's price, not the scheduler's. A scenario
220
+ sitting right at the threshold cannot be decided cheaply — cap it with `max_runs`.
221
+ - `validate_scenarios(entries, Vocabulary(...))` checks a scenario file and flags
222
+ absolute dates that will expire.
223
+
155
224
  ## Plots
156
225
 
157
226
  ```python
@@ -208,15 +277,17 @@ and satisfies the condition.
208
277
  ## Development
209
278
 
210
279
  ```bash
211
- pip install -e .[test]
280
+ pip install '.[all,test]'
212
281
  pytest
213
282
  ```
214
283
 
215
284
  The repo root *is* the package (flat layout), so the clone has to be in a folder named
216
285
  `bitskitten` for `pytest` to import it; CI installs the wheel first for the same reason.
217
286
 
218
- The drop-in zip in `download/` is a plain stdlib call, no notebook needed:
287
+ The drop-in zip in `download/` is built from committed files only, so no `__pycache__`
288
+ gets in:
219
289
 
220
290
  ```bash
221
- python -m zipfile -c download/bitskitten.zip __init__.py classes.py input.py metrics.py output.py text.py
291
+ git archive --format=zip -o download/bitskitten.zip HEAD \
292
+ __init__.py _deps.py bandit.py classes.py input.py metrics.py output.py text.py qa
222
293
  ```
@@ -1,38 +1,23 @@
1
- Metadata-Version: 2.4
2
- Name: bitskitten
3
- Version: 0.3.0
4
- Summary: EDA reports, plots and sklearn-compatible encoders
5
- Author: Caerno
6
- License-Expression: Apache-2.0
7
- Project-URL: Homepage, https://github.com/Caerno/bitskit
8
- Keywords: eda,pandas,sklearn,kaggle
9
- Requires-Python: >=3.9
10
- Description-Content-Type: text/markdown
11
- License-File: LICENSE
12
- Requires-Dist: numpy>=1.21
13
- Requires-Dist: pandas>=1.3
14
- Requires-Dist: scikit-learn>=1.0
15
- Requires-Dist: matplotlib>=3.4
16
- Requires-Dist: seaborn>=0.11
17
- Requires-Dist: jinja2>=3
18
- Provides-Extra: test
19
- Requires-Dist: pytest>=7; extra == "test"
20
- Dynamic: license-file
21
-
22
1
  # bitskitten
23
2
 
24
- A small toolbox of things I kept re-typing in every EDA notebook:
25
- quick dataset reports, a few plots, and sklearn-compatible encoders that can be
26
- dropped straight into a `Pipeline` / `GridSearchCV`.
3
+ A small toolbox of things I kept re-typing: quick dataset reports, a few plots and
4
+ sklearn-compatible encoders for EDA notebooks, and a regression harness for LLM bots
5
+ (scenario suites, checklist judge, Thompson-sampling scheduler).
27
6
 
28
7
  Nothing here is a framework. Each helper is one function or one class you can read in a minute.
29
8
 
30
9
  ## Install
31
10
 
32
11
  ```bash
33
- pip install bitskitten
12
+ pip install bitskitten # numpy only: test scheduler, bot regression harness, metric
13
+ pip install 'bitskitten[ml]' # + pandas, scikit-learn: encoders, NanFixer, harmonic_scorer
14
+ pip install 'bitskitten[eda]' # + pandas, matplotlib, seaborn: reports and plots
15
+ pip install 'bitskitten[all]' # everything
34
16
  ```
35
17
 
18
+ Each part loads its dependencies only when you use it: `import bitskitten` costs numpy,
19
+ not pandas and scikit-learn. A name whose extra is missing fails with the line to install.
20
+
36
21
  The latest commit: `pip install git+https://github.com/Caerno/bitskit.git`.
37
22
  On Kaggle / Colab the same lines work in a cell (`!pip install ...`).
38
23
  For a kernel with no internet, add
@@ -43,7 +28,7 @@ as a dataset and install it from disk:
43
28
  pip install --no-deps /kaggle/input/<your-dataset>/bitskit-main.zip
44
29
  ```
45
30
 
46
- Requires Python ≥ 3.9, numpy, pandas, scikit-learn, matplotlib, seaborn.
31
+ Requires Python ≥ 3.9 and numpy; the rest comes with the extras above.
47
32
 
48
33
  ## Quick start
49
34
 
@@ -152,6 +137,64 @@ recall — a class-agnostic generalization of F1 for when no class is "the posit
152
137
  A class that is never predicted or never recovered pulls it to 0. `harmonic_from_confusion(conf)`
153
138
  returns `(score, precision[], recall[])` from a ready confusion matrix.
154
139
 
140
+ ## Test scheduler for flaky suites
141
+
142
+ ```python
143
+ from bitskitten.bandit import ThompsonScheduler
144
+
145
+ sched = ThompsonScheduler(["happy_path", "reschedule", "angry_user"],
146
+ threshold=0.9, seed=0)
147
+ rows = sched.run(run_scenario, budget=80) # run_scenario(name) -> bool
148
+ # one dict per scenario, worst first: runs, passes, mean, 95 % interval, pass^3, verdict
149
+ print(sched.report()) # the same as a DataFrame, needs pandas
150
+ ```
151
+
152
+ For suites where one run of a scenario is a coin flip (LLM bots, anything
153
+ stochastic). Each scenario carries a Beta posterior over its pass rate; the next
154
+ run goes to the scenario most likely to fail (Thompson sampling), scenarios whose
155
+ interval has cleared or missed the threshold are retired, and the loop stops when
156
+ nothing is left to learn or the budget is out. `pass_power(alpha, beta, k)` is the
157
+ tau-bench pass^k with the posterior integrated out; `width=` retires scenarios that
158
+ sit on the threshold once their interval is narrow enough; `min_runs=` (default 3)
159
+ stops a single failure from deciding a verdict.
160
+
161
+ ## Regression testing for dialogue agents
162
+
163
+ ```python
164
+ from bitskitten.qa import Suite, Judge, Checklist, ScriptedUser, TopicClassifier, BotStep, format_report
165
+
166
+ suite = Suite(scenarios, # Scenario.from_dict(...) per YAML entry
167
+ new_bot=lambda sc: MyBot(), # bot(text) -> str | BotStep(text, state, slots, signals)
168
+ new_user=lambda sc, seed: ScriptedUser(classify, asks, facts=sc.facts, seed=seed),
169
+ gates={"collecting_states": {"collecting_date"}},
170
+ judge=Judge(model, Checklist.from_dicts(items))) # model(prompt) -> str, any provider
171
+ result = suite.run(budget=80, threshold=0.9, max_runs=40)
172
+ print(result.rows) # per scenario: runs, mean, 95 % interval, pass^3, verdict
173
+ # result.report: the same as a DataFrame, needs pandas
174
+ print(format_report(result.failures)) # failed runs grouped by what failed
175
+ ```
176
+
177
+ For bots where one run is a coin flip. Per run, cheapest first: the outcome
178
+ against the scenario and trace invariants (stuck in a state, the same reply
179
+ verbatim, invalid slot value, a number not in the allowed set, a scripted user's
180
+ record of re-asks) need no model; the judge is called only on runs that pass
181
+ them. The next run goes where a failure is most likely (Thompson sampling);
182
+ decided scenarios retire, the loop stops when nothing is left to learn.
183
+
184
+ - **Users.** `ScriptedUser` reacts to what the bot said (markers you supply),
185
+ hands out facts and records `repeated_ask` / `unexpected_ask` instead of
186
+ quietly answering them. `MarkovUsers` varies wording from real utterances at
187
+ zero model cost. `CallableUser` wraps any model.
188
+ - **Judge.** Repeated judging merges binary items by majority, not by mean.
189
+ `item_agreement_rows(judged, human)` gives per-item kappa against your own labels
190
+ (`item_agreement` — the same as a DataFrame)
191
+ — check it before trusting an item; `pick_threshold` picks the score cut.
192
+ - **Cost of a verdict.** Proving "passes at least 90 %" at 95 % takes 35 clean
193
+ runs in a row; that is the threshold's price, not the scheduler's. A scenario
194
+ sitting right at the threshold cannot be decided cheaply — cap it with `max_runs`.
195
+ - `validate_scenarios(entries, Vocabulary(...))` checks a scenario file and flags
196
+ absolute dates that will expire.
197
+
155
198
  ## Plots
156
199
 
157
200
  ```python
@@ -208,15 +251,17 @@ and satisfies the condition.
208
251
  ## Development
209
252
 
210
253
  ```bash
211
- pip install -e .[test]
254
+ pip install '.[all,test]'
212
255
  pytest
213
256
  ```
214
257
 
215
258
  The repo root *is* the package (flat layout), so the clone has to be in a folder named
216
259
  `bitskitten` for `pytest` to import it; CI installs the wheel first for the same reason.
217
260
 
218
- The drop-in zip in `download/` is a plain stdlib call, no notebook needed:
261
+ The drop-in zip in `download/` is built from committed files only, so no `__pycache__`
262
+ gets in:
219
263
 
220
264
  ```bash
221
- python -m zipfile -c download/bitskitten.zip __init__.py classes.py input.py metrics.py output.py text.py
265
+ git archive --format=zip -o download/bitskitten.zip HEAD \
266
+ __init__.py _deps.py bandit.py classes.py input.py metrics.py output.py text.py qa
222
267
  ```
@@ -0,0 +1,51 @@
1
+ '''bitskitten - small tools for data work and for LLM bots and agents.
2
+
3
+ from bitskitten import imperfection, NanFixer, Digitalize # pip install 'bitskitten[eda,ml]'
4
+ from bitskitten import ThompsonScheduler # numpy only
5
+ from bitskitten.qa import Scenario, Suite # numpy only
6
+
7
+ One distribution, independent parts: a name is imported only when you use it, so `import bitskitten` and the
8
+ light parts (qa, bandit, metrics, input) do not load pandas, scikit-learn or matplotlib. A part whose extra is
9
+ not installed says which one to install. Submodules stay importable on their own (`from bitskitten import output`).
10
+ '''
11
+ import importlib
12
+
13
+ from ._deps import hint as _hint
14
+
15
+ __version__ = "0.5.0"
16
+
17
+ _EXPORTS = {
18
+ "ThompsonScheduler": "bandit", "pass_power": "bandit",
19
+ "Digitalize": "classes", "Encoder": "classes", "FeatureTrans": "classes", "NanFixer": "classes",
20
+ "SlowPolyLinearReg": "classes",
21
+ "number": "input",
22
+ "harmonic_from_confusion": "metrics", "harmonic_score": "metrics", "harmonic_scorer": "metrics",
23
+ "text_imperfection": "text",
24
+ "imperfection": "output", "informer": "output", "informer_print": "output", "multicolumn": "output",
25
+ "plot_conf_map": "output", "plot_some_scatters": "output", "img_squeeze": "output", "img_framaker": "output",
26
+ }
27
+ _SUBMODULES = {"bandit", "classes", "input", "metrics", "text", "output", "qa"}
28
+
29
+ __all__ = list(_EXPORTS)
30
+
31
+
32
+ _MODULE_EXTRA = {"classes": "ml", "metrics": "ml", "output": "eda", "text": "eda"}
33
+
34
+
35
+ def __getattr__(name):
36
+ mod = _EXPORTS.get(name) or (name if name in _SUBMODULES else None)
37
+ if mod is None:
38
+ raise AttributeError(f"module 'bitskitten' has no attribute {name!r}")
39
+ try:
40
+ m = importlib.import_module(f".{mod}", __name__)
41
+ except ModuleNotFoundError as e:
42
+ if e.name and e.name.split(".")[0] != __name__:
43
+ raise ImportError(_hint(e.name, f"bitskitten.{name}", _MODULE_EXTRA.get(mod))) from e
44
+ raise
45
+ value = m if name == mod else getattr(m, name)
46
+ globals()[name] = value
47
+ return value
48
+
49
+
50
+ def __dir__():
51
+ return sorted(set(globals()) | set(_EXPORTS) | _SUBMODULES)
@@ -0,0 +1,20 @@
1
+ """Optional dependencies: which extra brings which package, and a clear error when it is missing."""
2
+ import importlib
3
+
4
+ EXTRA = {"pandas": "ml", "sklearn": "ml", "matplotlib": "eda", "seaborn": "eda", "jinja2": "eda",
5
+ "onnxruntime": "search", "tokenizers": "search", "yaml": "nollm", "Stemmer": "nollm"}
6
+ PIP = {"sklearn": "scikit-learn", "yaml": "PyYAML", "Stemmer": "PyStemmer"}
7
+
8
+
9
+ def hint(missing, what="this", extra=None):
10
+ top = (missing or "").split(".")[0]
11
+ return (f"{what} needs {PIP.get(top, top)}: pip install 'bitskitten[{extra or EXTRA.get(top, 'all')}]' "
12
+ f"(or pip install {PIP.get(top, top)})")
13
+
14
+
15
+ def need(module, what="this"):
16
+ """import an optional module or raise ImportError naming the extra to install"""
17
+ try:
18
+ return importlib.import_module(module)
19
+ except ModuleNotFoundError as e:
20
+ raise ImportError(hint(e.name or module, what)) from e
@@ -0,0 +1,270 @@
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
+
36
+ __all__ = ["Arm", "ThompsonScheduler", "pass_power", "beta_interval"]
37
+
38
+
39
+ @dataclass
40
+ class Arm:
41
+ """Posterior state of one scenario: Beta(alpha, beta) over its pass rate."""
42
+
43
+ name: str
44
+ alpha: float = 1.0
45
+ beta: float = 1.0
46
+ runs: int = 0
47
+ passes: int = 0
48
+ history: List[bool] = field(default_factory=list)
49
+ _interval: Optional[Tuple[float, float]] = field(default=None, repr=False)
50
+
51
+ @property
52
+ def mean(self) -> float:
53
+ return self.alpha / (self.alpha + self.beta)
54
+
55
+ @property
56
+ def variance(self) -> float:
57
+ n = self.alpha + self.beta
58
+ return self.alpha * self.beta / (n * n * (n + 1))
59
+
60
+
61
+ def pass_power(alpha: float, beta: float, k: int) -> float:
62
+ """E[p^k] under Beta(alpha, beta): probability of k consecutive passes.
63
+
64
+ Closed form: prod_{i<k} (alpha + i) / (alpha + beta + i). This is the
65
+ tau-bench pass^k statistic with the posterior integrated out.
66
+ """
67
+ if k < 0:
68
+ raise ValueError("k must be >= 0")
69
+ out = 1.0
70
+ for i in range(k):
71
+ out *= (alpha + i) / (alpha + beta + i)
72
+ return out
73
+
74
+
75
+ def beta_interval(alpha: float, beta: float, level: float = 0.95, *,
76
+ rng: Optional[np.random.Generator] = None,
77
+ draws: int = 20_000) -> Tuple[float, float]:
78
+ """Equal-tailed credible interval of Beta(alpha, beta) by Monte Carlo.
79
+
80
+ numpy has no Beta quantile function and scipy is not a dependency; with
81
+ 20 000 draws the quantile error is ~0.005, below any decision threshold
82
+ one would set on a pass rate.
83
+ """
84
+ if not 0 < level < 1:
85
+ raise ValueError("level must be in (0, 1)")
86
+ rng = np.random.default_rng(0) if rng is None else rng
87
+ sample = rng.beta(alpha, beta, size=draws)
88
+ lo, hi = np.quantile(sample, [(1 - level) / 2, 1 - (1 - level) / 2])
89
+ return float(lo), float(hi)
90
+
91
+
92
+ class ThompsonScheduler:
93
+ """Allocate scenario runs by Thompson sampling on the failure probability.
94
+
95
+ Parameters
96
+ ----------
97
+ scenarios : names of the scenarios (arms).
98
+ threshold : pass rate a scenario must clear; a scenario is *decided* once
99
+ its credible interval lies entirely above or below it.
100
+ level : credibility of the interval (0.95 = 95 %).
101
+ width : optional; a scenario whose interval is already narrower than this
102
+ is also retired — paying for more runs would not change the verdict.
103
+ max_runs : optional cap per scenario. A scenario whose true pass rate sits
104
+ right at the threshold (0.87 against 0.9) cannot be decided in any
105
+ affordable number of runs, and Thompson sampling keeps feeding it — on
106
+ one seed it took 101 of 120 runs and left a perfect scenario without a
107
+ verdict. The cap retires it as 'undecided' and frees the budget.
108
+ (`width` is a poor substitute: an all-pass scenario's interval stays
109
+ wide until it is proven, so `width` retires it unproven.)
110
+ min_runs : no scenario is retired before this many runs. Under a flat
111
+ prior a single failure already puts the 95 % interval below 0.9, so
112
+ without a floor 5 % of genuinely good scenarios would be branded
113
+ 'fail' on their first run.
114
+ prior : (alpha, beta) of the Beta prior on the pass rate; (1, 1) is flat.
115
+ Per-scenario priors: pass a dict name -> (alpha, beta).
116
+ seed : seed for the sampler; same seed + same updates = same picks.
117
+ """
118
+
119
+ def __init__(self, scenarios: Iterable[str], *, threshold: float = 0.9,
120
+ level: float = 0.95, width: Optional[float] = None,
121
+ min_runs: int = 3, max_runs: Optional[int] = None,
122
+ prior=(1.0, 1.0),
123
+ seed: Optional[int] = None):
124
+ names = list(scenarios)
125
+ if not names:
126
+ raise ValueError("at least one scenario is required")
127
+ if len(set(names)) != len(names):
128
+ raise ValueError("scenario names must be unique")
129
+ if not 0 < threshold < 1:
130
+ raise ValueError("threshold must be in (0, 1)")
131
+ if not 0 < level < 1:
132
+ raise ValueError("level must be in (0, 1)")
133
+ if width is not None and width <= 0:
134
+ raise ValueError("width must be positive")
135
+ if min_runs < 0:
136
+ raise ValueError("min_runs must be >= 0")
137
+ if max_runs is not None and max_runs < max(1, min_runs):
138
+ raise ValueError("max_runs must be >= min_runs and >= 1")
139
+ self.min_runs = min_runs
140
+ self.max_runs = max_runs
141
+ self.threshold = threshold
142
+ self.level = level
143
+ self.width = width
144
+ self.rng = np.random.default_rng(seed)
145
+ self._irng = np.random.default_rng(seed) # intervals, apart from picks
146
+ self.arms: Dict[str, Arm] = {}
147
+ for name in names:
148
+ a, b = prior[name] if isinstance(prior, dict) else prior
149
+ if a <= 0 or b <= 0:
150
+ raise ValueError("prior parameters must be positive")
151
+ self.arms[name] = Arm(name, float(a), float(b))
152
+
153
+ # -- posterior summaries -----------------------------------------------
154
+
155
+ def interval(self, name: str) -> Tuple[float, float]:
156
+ """Credible interval of the scenario's pass rate (cached per update)."""
157
+ arm = self.arms[name]
158
+ if arm._interval is None:
159
+ arm._interval = beta_interval(arm.alpha, arm.beta, self.level,
160
+ rng=self._irng)
161
+ return arm._interval
162
+
163
+ def status(self, name: str) -> str:
164
+ """'pass' if the whole interval is above the threshold, 'fail' if it is
165
+ below, else 'undecided'."""
166
+ lo, hi = self.interval(name)
167
+ if lo >= self.threshold:
168
+ return "pass"
169
+ if hi < self.threshold:
170
+ return "fail"
171
+ return "undecided"
172
+
173
+ def active(self) -> List[str]:
174
+ """Scenarios still worth a run: under `min_runs`, or undecided and
175
+ not yet narrow enough."""
176
+ out = []
177
+ for name, arm in self.arms.items():
178
+ if self.max_runs is not None and arm.runs >= self.max_runs:
179
+ continue
180
+ if arm.runs < self.min_runs:
181
+ out.append(name)
182
+ continue
183
+ if self.status(name) != "undecided":
184
+ continue
185
+ if self.width is not None:
186
+ lo, hi = self.interval(name)
187
+ if hi - lo <= self.width:
188
+ continue
189
+ out.append(name)
190
+ return out
191
+
192
+ @property
193
+ def total_runs(self) -> int:
194
+ return sum(a.runs for a in self.arms.values())
195
+
196
+ # -- allocation ---------------------------------------------------------
197
+
198
+ def pick(self) -> Optional[str]:
199
+ """Scenario to run next, or None when nothing is left to learn.
200
+
201
+ Argmax of the sampled failure probability over active scenarios.
202
+ Sampling from the posterior (rather than taking the mean) is what
203
+ keeps rarely-run scenarios in play: a wide posterior sometimes draws
204
+ a high failure probability and gets its turn.
205
+ """
206
+ best, best_fail = None, -1.0
207
+ for name in self.active():
208
+ arm = self.arms[name]
209
+ fail = 1.0 - self.rng.beta(arm.alpha, arm.beta)
210
+ if fail > best_fail:
211
+ best, best_fail = name, fail
212
+ return best
213
+
214
+ def update(self, name: str, passed: bool) -> None:
215
+ arm = self.arms[name]
216
+ arm.runs += 1
217
+ arm.history.append(bool(passed))
218
+ if passed:
219
+ arm.passes += 1
220
+ arm.alpha += 1
221
+ else:
222
+ arm.beta += 1
223
+ arm._interval = None
224
+
225
+ def done(self, *, budget: Optional[int] = None) -> bool:
226
+ """True when the budget is spent or no scenario is active."""
227
+ if budget is not None and self.total_runs >= budget:
228
+ return True
229
+ return not self.active()
230
+
231
+ # -- reporting ----------------------------------------------------------
232
+
233
+ def rows(self, *, k: int = 3) -> List[dict]:
234
+ """One dict per scenario: runs, passes, posterior mean, interval,
235
+ pass^k and the verdict against the threshold. Sorted worst first.
236
+ Plain Python: no pandas needed."""
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 sorted(rows, key=lambda r: (r["mean"], r["runs"]))
251
+
252
+ def report(self, *, k: int = 3):
253
+ """`rows()` as a pandas DataFrame (needs pandas)."""
254
+ from ._deps import need
255
+ return need("pandas", "ThompsonScheduler.report").DataFrame(self.rows(k=k))
256
+
257
+ def run(self, run_once, *, budget: int, k: int = 3):
258
+ """Drive the loop: pick -> run_once(name) -> update, until `done()`.
259
+
260
+ `run_once(name)` must return a truthy value for a pass. Returns the
261
+ final `rows(k)`, worst scenario first; `report(k)` gives the same as a
262
+ DataFrame. Raising inside `run_once` aborts the loop; the state
263
+ collected so far stays on the scheduler.
264
+ """
265
+ if budget <= 0:
266
+ raise ValueError("budget must be positive")
267
+ while not self.done(budget=budget):
268
+ name = self.pick()
269
+ self.update(name, bool(run_once(name)))
270
+ return self.rows(k=k)