uppercut-wave-gate 1.0.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.
- uppercut_wave_gate-1.0.0/.gitignore +10 -0
- uppercut_wave_gate-1.0.0/PKG-INFO +117 -0
- uppercut_wave_gate-1.0.0/README.md +95 -0
- uppercut_wave_gate-1.0.0/pyproject.toml +39 -0
- uppercut_wave_gate-1.0.0/src/uppercut_wave_gate/__init__.py +34 -0
- uppercut_wave_gate-1.0.0/src/uppercut_wave_gate/__main__.py +5 -0
- uppercut_wave_gate-1.0.0/src/uppercut_wave_gate/_files.py +61 -0
- uppercut_wave_gate-1.0.0/src/uppercut_wave_gate/_gate.py +103 -0
- uppercut_wave_gate-1.0.0/src/uppercut_wave_gate/_metrics.py +55 -0
- uppercut_wave_gate-1.0.0/src/uppercut_wave_gate/_runner.py +41 -0
- uppercut_wave_gate-1.0.0/src/uppercut_wave_gate/_wave.py +353 -0
- uppercut_wave_gate-1.0.0/src/uppercut_wave_gate/cli.py +100 -0
- uppercut_wave_gate-1.0.0/src/uppercut_wave_gate/py.typed +0 -0
- uppercut_wave_gate-1.0.0/tests/test_wave_gate.py +543 -0
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: uppercut-wave-gate
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Run one prompt over many pieces with a pluggable model runner, count only output that passes a gate command, and refuse to start unless the gate rejects a known-bad sample.
|
|
5
|
+
Project-URL: Source, https://github.com/uppercut-labs/py-kit/tree/main/packages/uppercut-wave-gate
|
|
6
|
+
Author-email: Uppercut Labs <packages@uppercut-labs.com>
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
Keywords: batch,gate,llm,manifest,resume,throughput,validation
|
|
9
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Operating System :: MacOS
|
|
12
|
+
Classifier: Operating System :: Microsoft :: Windows
|
|
13
|
+
Classifier: Operating System :: POSIX
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Typing :: Typed
|
|
20
|
+
Requires-Python: >=3.10
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# uppercut-wave-gate
|
|
24
|
+
|
|
25
|
+
Runs one prompt over many pieces and counts only the output that passes a gate. The model is a function you pass in, so the package works with a local server, a hosted API or a command line tool. A run keeps every attempt in a ledger, can be stopped and started again without redoing accepted work, and refuses to reuse old results after the prompt, the gate, the workers or a piece have changed. It also refuses to start at all unless the gate rejects a sample you know is bad: a gate that passes everything proves nothing about the real output. Standard library only.
|
|
26
|
+
|
|
27
|
+
```sh
|
|
28
|
+
pip install uppercut-wave-gate
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
from uppercut_wave_gate import Call, WaveConfig, Worker, run_wave
|
|
33
|
+
|
|
34
|
+
def runner(call: Call) -> str:
|
|
35
|
+
# Ask your model. call.worker, call.text (the piece), call.system (the prompt file),
|
|
36
|
+
# call.timeout and call.settings are what you need. Raise HostError if the host is down.
|
|
37
|
+
return my_client.chat(model=call.worker.model, system=call.system, user=call.text, timeout=call.timeout)
|
|
38
|
+
|
|
39
|
+
cfg = WaveConfig(
|
|
40
|
+
pieces="pieces.jsonl", # one {"id": "p01", "text": "..."} per line
|
|
41
|
+
prompt="prompt.txt", # the system prompt
|
|
42
|
+
out="run", # results/, failed/, attempts/, ledger.jsonl, manifest.json, summary.json
|
|
43
|
+
workers=[Worker("a", "model-x")] * 2,
|
|
44
|
+
gate='python check.py {out}', # exit 0 passes
|
|
45
|
+
bad="known_bad.txt", # the gate must reject this, or the wave will not start
|
|
46
|
+
retries=2,
|
|
47
|
+
stop_after=8, # stop if 8 pieces in a row fail the gate
|
|
48
|
+
)
|
|
49
|
+
exit_code = run_wave(cfg, runner)
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
The command line does the same with a command that calls your model. The piece text arrives on standard input and the output is printed on standard output:
|
|
53
|
+
|
|
54
|
+
```sh
|
|
55
|
+
uppercut-wave-gate --pieces pieces.jsonl --prompt prompt.txt --out run \
|
|
56
|
+
--worker a=model-x*2 --gate "python check.py {out}" --bad known_bad.txt \
|
|
57
|
+
--runner-cmd "python ask.py --host {host} --model {model} --system-file {prompt_file}"
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
Run the same command again to resume: passed pieces and pieces already given up are skipped. `--retry-failed` tries the failed ones again after a prompt fix.
|
|
61
|
+
|
|
62
|
+
## Gates
|
|
63
|
+
|
|
64
|
+
A gate is a shell command string, an argument list, or a function. The only passing result is a clean pass.
|
|
65
|
+
|
|
66
|
+
| Gate | How it is called | Passes when |
|
|
67
|
+
| --- | --- | --- |
|
|
68
|
+
| `"python check.py {out}"` | Through the shell. `{out}` becomes the quoted path of the output file, `{id}` the file's name without its extension | exit code 0 |
|
|
69
|
+
| `["python", "check.py", "{out}"]` | Without a shell. The same two replacements in each item | exit code 0 |
|
|
70
|
+
| `def gate(text): ...` | With the output text | returns `True`, or `(True, "why")` |
|
|
71
|
+
|
|
72
|
+
A nonzero exit, a timeout, an exception, a command that cannot start and empty output all fail. Name the `bad` file after a real piece (`bad/p01.out`) when the gate looks the piece up by `{id}`. The probe also refuses a gate that could not give a verdict on the bad sample (it timed out or crashed), because that is not a rejection, and a `bad` file that does not exist.
|
|
73
|
+
|
|
74
|
+
## What a run writes
|
|
75
|
+
|
|
76
|
+
| File | Holds |
|
|
77
|
+
| --- | --- |
|
|
78
|
+
| `results/<id>.out` | Output that passed the gate |
|
|
79
|
+
| `failed/<id>.out`, `failed/<id>.why` | The last output and the reason, after `retries` more gate failures or five host errors |
|
|
80
|
+
| `attempts/` | The output being gated now |
|
|
81
|
+
| `ledger.jsonl` | One line per attempt: piece, host, model, status (`pass`, `gate_fail`, `host_error`), seconds, reason, hashes of the piece and the output |
|
|
82
|
+
| `manifest.json` | Hashes of the prompt, the gate (its command line and the files it names), the workers, the settings and every piece |
|
|
83
|
+
| `summary.json` | `pieces`, `passed`, `failed`, `remaining`, `pass_rate`, `unique_outputs`, `duplicate_count`, `diversity_ratio`, `seconds` |
|
|
84
|
+
|
|
85
|
+
A rerun with a changed prompt, gate, worker list, `settings` or piece text stops with an error and exit code 2 instead of mixing old and new results. `--invalidate-changed` clears the old results and runs again; `--new-run` insists on an empty folder. A folder with results but no manifest is refused the same way.
|
|
86
|
+
|
|
87
|
+
## Exit codes
|
|
88
|
+
|
|
89
|
+
`0` every piece run passed (look at `remaining` after a `--limit` pilot), `2` usage error, refused resume or a gate probe that failed, `3` finished with failures, `4` no workers left, `5` `--budget` reached (run again to continue), `6` `--stop-after` tripped (fix the prompt).
|
|
90
|
+
|
|
91
|
+
## API
|
|
92
|
+
|
|
93
|
+
| Name | What it does |
|
|
94
|
+
| --- | --- |
|
|
95
|
+
| `run_wave(cfg, runner)` | Run the wave; returns the exit code. Raises `WaveError` when it cannot start |
|
|
96
|
+
| `WaveConfig(pieces, prompt, out, workers, gate, bad, timeout=120, gate_timeout=10, retries=2, budget=None, stop_after=0, limit=None, retry_failed=False, invalidate_changed=False, new_run=False, settings={})` | Everything a run needs. `settings` is passed to the runner in `call.settings` and is part of the manifest |
|
|
97
|
+
| `Worker(host, model)`, `parse_workers(["a=m*2"])` | One worker slot, and the `HOST=MODEL*SLOTS` shorthand. Both names are opaque to the package |
|
|
98
|
+
| `Call(worker, piece_id, text, system, timeout, settings)` | What a runner receives |
|
|
99
|
+
| `HostError` | Raise it from a runner when the host failed. Three host errors in a row drop that worker; five fail the piece. Any other exception counts the same way |
|
|
100
|
+
| `command_runner(build, *, stdin=True, env=None)` | A runner that runs the argument list `build(call)` returns, with the piece on standard input, and raises `HostError` on a nonzero exit or a timeout |
|
|
101
|
+
| `run_gate(gate, path, timeout=10)` | `(passed, why)` for one file |
|
|
102
|
+
| `gate_fingerprint(gate)` | The hash the manifest keeps for the gate |
|
|
103
|
+
| `load_pieces(path)` | Read and check a pieces file (filename-safe unique ids, non-empty text) |
|
|
104
|
+
| `add_wave_arguments(parser, **defaults)`, `config_from_args(args, settings)`, `main(argv, runner)` | The shared command line options, so a project's own wave command adds only its model options |
|
|
105
|
+
| `summarize_samples(samples)` | Pass rate, accepted outputs per second, mean first-token time and speed, and speed multiplied by pass rate, for a benchmark of several samples |
|
|
106
|
+
| `output_diversity(texts)` | Unique outputs, duplicates and the diversity ratio of accepted outputs |
|
|
107
|
+
|
|
108
|
+
## Notes
|
|
109
|
+
|
|
110
|
+
- Everything model specific stays with the caller: which hosts exist, which models run, how a request is sent, and the prompt. The package only hands the runner a `Call`.
|
|
111
|
+
- Gate commands run through the shell with the timeout you give. A gate that starts its own children can leave them running after a timeout; give such a gate its own timeout handling.
|
|
112
|
+
- The runner is called from one thread per worker slot, so it must be safe to call from several threads.
|
|
113
|
+
- The ledger hashes pieces and outputs (16 hex digits of SHA-256) instead of storing text; the full output of a failed piece is kept in `failed/`.
|
|
114
|
+
|
|
115
|
+
## License
|
|
116
|
+
|
|
117
|
+
MIT
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
# uppercut-wave-gate
|
|
2
|
+
|
|
3
|
+
Runs one prompt over many pieces and counts only the output that passes a gate. The model is a function you pass in, so the package works with a local server, a hosted API or a command line tool. A run keeps every attempt in a ledger, can be stopped and started again without redoing accepted work, and refuses to reuse old results after the prompt, the gate, the workers or a piece have changed. It also refuses to start at all unless the gate rejects a sample you know is bad: a gate that passes everything proves nothing about the real output. Standard library only.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
pip install uppercut-wave-gate
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```python
|
|
10
|
+
from uppercut_wave_gate import Call, WaveConfig, Worker, run_wave
|
|
11
|
+
|
|
12
|
+
def runner(call: Call) -> str:
|
|
13
|
+
# Ask your model. call.worker, call.text (the piece), call.system (the prompt file),
|
|
14
|
+
# call.timeout and call.settings are what you need. Raise HostError if the host is down.
|
|
15
|
+
return my_client.chat(model=call.worker.model, system=call.system, user=call.text, timeout=call.timeout)
|
|
16
|
+
|
|
17
|
+
cfg = WaveConfig(
|
|
18
|
+
pieces="pieces.jsonl", # one {"id": "p01", "text": "..."} per line
|
|
19
|
+
prompt="prompt.txt", # the system prompt
|
|
20
|
+
out="run", # results/, failed/, attempts/, ledger.jsonl, manifest.json, summary.json
|
|
21
|
+
workers=[Worker("a", "model-x")] * 2,
|
|
22
|
+
gate='python check.py {out}', # exit 0 passes
|
|
23
|
+
bad="known_bad.txt", # the gate must reject this, or the wave will not start
|
|
24
|
+
retries=2,
|
|
25
|
+
stop_after=8, # stop if 8 pieces in a row fail the gate
|
|
26
|
+
)
|
|
27
|
+
exit_code = run_wave(cfg, runner)
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
The command line does the same with a command that calls your model. The piece text arrives on standard input and the output is printed on standard output:
|
|
31
|
+
|
|
32
|
+
```sh
|
|
33
|
+
uppercut-wave-gate --pieces pieces.jsonl --prompt prompt.txt --out run \
|
|
34
|
+
--worker a=model-x*2 --gate "python check.py {out}" --bad known_bad.txt \
|
|
35
|
+
--runner-cmd "python ask.py --host {host} --model {model} --system-file {prompt_file}"
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Run the same command again to resume: passed pieces and pieces already given up are skipped. `--retry-failed` tries the failed ones again after a prompt fix.
|
|
39
|
+
|
|
40
|
+
## Gates
|
|
41
|
+
|
|
42
|
+
A gate is a shell command string, an argument list, or a function. The only passing result is a clean pass.
|
|
43
|
+
|
|
44
|
+
| Gate | How it is called | Passes when |
|
|
45
|
+
| --- | --- | --- |
|
|
46
|
+
| `"python check.py {out}"` | Through the shell. `{out}` becomes the quoted path of the output file, `{id}` the file's name without its extension | exit code 0 |
|
|
47
|
+
| `["python", "check.py", "{out}"]` | Without a shell. The same two replacements in each item | exit code 0 |
|
|
48
|
+
| `def gate(text): ...` | With the output text | returns `True`, or `(True, "why")` |
|
|
49
|
+
|
|
50
|
+
A nonzero exit, a timeout, an exception, a command that cannot start and empty output all fail. Name the `bad` file after a real piece (`bad/p01.out`) when the gate looks the piece up by `{id}`. The probe also refuses a gate that could not give a verdict on the bad sample (it timed out or crashed), because that is not a rejection, and a `bad` file that does not exist.
|
|
51
|
+
|
|
52
|
+
## What a run writes
|
|
53
|
+
|
|
54
|
+
| File | Holds |
|
|
55
|
+
| --- | --- |
|
|
56
|
+
| `results/<id>.out` | Output that passed the gate |
|
|
57
|
+
| `failed/<id>.out`, `failed/<id>.why` | The last output and the reason, after `retries` more gate failures or five host errors |
|
|
58
|
+
| `attempts/` | The output being gated now |
|
|
59
|
+
| `ledger.jsonl` | One line per attempt: piece, host, model, status (`pass`, `gate_fail`, `host_error`), seconds, reason, hashes of the piece and the output |
|
|
60
|
+
| `manifest.json` | Hashes of the prompt, the gate (its command line and the files it names), the workers, the settings and every piece |
|
|
61
|
+
| `summary.json` | `pieces`, `passed`, `failed`, `remaining`, `pass_rate`, `unique_outputs`, `duplicate_count`, `diversity_ratio`, `seconds` |
|
|
62
|
+
|
|
63
|
+
A rerun with a changed prompt, gate, worker list, `settings` or piece text stops with an error and exit code 2 instead of mixing old and new results. `--invalidate-changed` clears the old results and runs again; `--new-run` insists on an empty folder. A folder with results but no manifest is refused the same way.
|
|
64
|
+
|
|
65
|
+
## Exit codes
|
|
66
|
+
|
|
67
|
+
`0` every piece run passed (look at `remaining` after a `--limit` pilot), `2` usage error, refused resume or a gate probe that failed, `3` finished with failures, `4` no workers left, `5` `--budget` reached (run again to continue), `6` `--stop-after` tripped (fix the prompt).
|
|
68
|
+
|
|
69
|
+
## API
|
|
70
|
+
|
|
71
|
+
| Name | What it does |
|
|
72
|
+
| --- | --- |
|
|
73
|
+
| `run_wave(cfg, runner)` | Run the wave; returns the exit code. Raises `WaveError` when it cannot start |
|
|
74
|
+
| `WaveConfig(pieces, prompt, out, workers, gate, bad, timeout=120, gate_timeout=10, retries=2, budget=None, stop_after=0, limit=None, retry_failed=False, invalidate_changed=False, new_run=False, settings={})` | Everything a run needs. `settings` is passed to the runner in `call.settings` and is part of the manifest |
|
|
75
|
+
| `Worker(host, model)`, `parse_workers(["a=m*2"])` | One worker slot, and the `HOST=MODEL*SLOTS` shorthand. Both names are opaque to the package |
|
|
76
|
+
| `Call(worker, piece_id, text, system, timeout, settings)` | What a runner receives |
|
|
77
|
+
| `HostError` | Raise it from a runner when the host failed. Three host errors in a row drop that worker; five fail the piece. Any other exception counts the same way |
|
|
78
|
+
| `command_runner(build, *, stdin=True, env=None)` | A runner that runs the argument list `build(call)` returns, with the piece on standard input, and raises `HostError` on a nonzero exit or a timeout |
|
|
79
|
+
| `run_gate(gate, path, timeout=10)` | `(passed, why)` for one file |
|
|
80
|
+
| `gate_fingerprint(gate)` | The hash the manifest keeps for the gate |
|
|
81
|
+
| `load_pieces(path)` | Read and check a pieces file (filename-safe unique ids, non-empty text) |
|
|
82
|
+
| `add_wave_arguments(parser, **defaults)`, `config_from_args(args, settings)`, `main(argv, runner)` | The shared command line options, so a project's own wave command adds only its model options |
|
|
83
|
+
| `summarize_samples(samples)` | Pass rate, accepted outputs per second, mean first-token time and speed, and speed multiplied by pass rate, for a benchmark of several samples |
|
|
84
|
+
| `output_diversity(texts)` | Unique outputs, duplicates and the diversity ratio of accepted outputs |
|
|
85
|
+
|
|
86
|
+
## Notes
|
|
87
|
+
|
|
88
|
+
- Everything model specific stays with the caller: which hosts exist, which models run, how a request is sent, and the prompt. The package only hands the runner a `Call`.
|
|
89
|
+
- Gate commands run through the shell with the timeout you give. A gate that starts its own children can leave them running after a timeout; give such a gate its own timeout handling.
|
|
90
|
+
- The runner is called from one thread per worker slot, so it must be safe to call from several threads.
|
|
91
|
+
- The ledger hashes pieces and outputs (16 hex digits of SHA-256) instead of storing text; the full output of a failed piece is kept in `failed/`.
|
|
92
|
+
|
|
93
|
+
## License
|
|
94
|
+
|
|
95
|
+
MIT
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.25"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "uppercut-wave-gate"
|
|
7
|
+
version = "1.0.0"
|
|
8
|
+
description = "Run one prompt over many pieces with a pluggable model runner, count only output that passes a gate command, and refuse to start unless the gate rejects a known-bad sample."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
authors = [{ name = "Uppercut Labs", email = "packages@uppercut-labs.com" }]
|
|
13
|
+
keywords = ["llm", "batch", "gate", "validation", "resume", "manifest", "throughput"]
|
|
14
|
+
dependencies = []
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 5 - Production/Stable",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"Operating System :: MacOS",
|
|
19
|
+
"Operating System :: Microsoft :: Windows",
|
|
20
|
+
"Operating System :: POSIX",
|
|
21
|
+
"Programming Language :: Python :: 3",
|
|
22
|
+
"Programming Language :: Python :: 3.10",
|
|
23
|
+
"Programming Language :: Python :: 3.11",
|
|
24
|
+
"Programming Language :: Python :: 3.12",
|
|
25
|
+
"Programming Language :: Python :: 3.13",
|
|
26
|
+
"Typing :: Typed",
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
[project.scripts]
|
|
30
|
+
uppercut-wave-gate = "uppercut_wave_gate.cli:main"
|
|
31
|
+
|
|
32
|
+
[project.urls]
|
|
33
|
+
Source = "https://github.com/uppercut-labs/py-kit/tree/main/packages/uppercut-wave-gate"
|
|
34
|
+
|
|
35
|
+
[tool.hatch.build.targets.wheel]
|
|
36
|
+
packages = ["src/uppercut_wave_gate"]
|
|
37
|
+
|
|
38
|
+
[tool.hatch.build.targets.sdist]
|
|
39
|
+
include = ["src", "tests", "README.md"]
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Run one prompt over many pieces, count only output that passes a gate, and refuse to start with a gate that proves nothing."""
|
|
2
|
+
|
|
3
|
+
from ._files import SAFE_ID, WaveError, load_pieces, write_atomic
|
|
4
|
+
from ._gate import Gate, GateResult, gate_fingerprint, run_gate
|
|
5
|
+
from ._metrics import output_diversity, summarize_samples
|
|
6
|
+
from ._runner import command_runner
|
|
7
|
+
from ._wave import Call, HostError, Runner, Wave, WaveConfig, Worker, parse_workers, run_wave
|
|
8
|
+
from .cli import add_wave_arguments, config_from_args, main
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"Call",
|
|
12
|
+
"Gate",
|
|
13
|
+
"GateResult",
|
|
14
|
+
"HostError",
|
|
15
|
+
"Runner",
|
|
16
|
+
"SAFE_ID",
|
|
17
|
+
"Wave",
|
|
18
|
+
"WaveConfig",
|
|
19
|
+
"WaveError",
|
|
20
|
+
"Worker",
|
|
21
|
+
"add_wave_arguments",
|
|
22
|
+
"command_runner",
|
|
23
|
+
"config_from_args",
|
|
24
|
+
"gate_fingerprint",
|
|
25
|
+
"load_pieces",
|
|
26
|
+
"main",
|
|
27
|
+
"output_diversity",
|
|
28
|
+
"parse_workers",
|
|
29
|
+
"run_gate",
|
|
30
|
+
"run_wave",
|
|
31
|
+
"summarize_samples",
|
|
32
|
+
"write_atomic",
|
|
33
|
+
]
|
|
34
|
+
__version__ = "1.0.0"
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Piece loading and atomic file writes."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import threading
|
|
9
|
+
from typing import Any, Dict, List
|
|
10
|
+
|
|
11
|
+
SAFE_ID = re.compile(r"^[A-Za-z0-9._-]{1,120}$")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class WaveError(Exception):
|
|
15
|
+
"""A run that cannot start or continue: bad usage, a refused resume, or a gate that proves nothing.
|
|
16
|
+
|
|
17
|
+
The command line turns it into exit code 2.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
exit_code = 2
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def write_atomic(path: str, text: str) -> None:
|
|
24
|
+
"""Write `text` to `path` through a temporary file in the same folder, then rename it into place."""
|
|
25
|
+
tmp = "%s.%d.%d.tmp" % (path, os.getpid(), threading.get_ident())
|
|
26
|
+
try:
|
|
27
|
+
with open(tmp, "w", encoding="utf-8") as fh:
|
|
28
|
+
fh.write(text)
|
|
29
|
+
os.replace(tmp, path)
|
|
30
|
+
except BaseException:
|
|
31
|
+
try:
|
|
32
|
+
os.remove(tmp)
|
|
33
|
+
except OSError:
|
|
34
|
+
pass
|
|
35
|
+
raise
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def load_pieces(path: "str | os.PathLike[str]") -> List[Dict[str, Any]]:
|
|
39
|
+
"""Read a JSON Lines file of `{"id": ..., "text": ...}` pieces.
|
|
40
|
+
|
|
41
|
+
Ids must be filename safe (letters, digits, `.`, `_`, `-`, at most 120 characters), unique, and every
|
|
42
|
+
piece needs non-empty text. Blank lines are skipped. Raises WaveError otherwise.
|
|
43
|
+
"""
|
|
44
|
+
pieces: List[Dict[str, Any]] = []
|
|
45
|
+
seen = set()
|
|
46
|
+
with open(path, encoding="utf-8") as fh:
|
|
47
|
+
for n, line in enumerate(fh, 1):
|
|
48
|
+
if not line.strip():
|
|
49
|
+
continue
|
|
50
|
+
try:
|
|
51
|
+
piece = json.loads(line)
|
|
52
|
+
except json.JSONDecodeError as exc:
|
|
53
|
+
raise WaveError("%s line %d is not JSON: %s" % (path, n, exc.msg))
|
|
54
|
+
if not isinstance(piece, dict) or not SAFE_ID.match(str(piece.get("id", ""))) \
|
|
55
|
+
or not str(piece.get("text", "")).strip():
|
|
56
|
+
raise WaveError("%s line %d needs a filename-safe id and non-empty text" % (path, n))
|
|
57
|
+
if piece["id"] in seen:
|
|
58
|
+
raise WaveError("duplicate id %s" % piece["id"])
|
|
59
|
+
seen.add(piece["id"])
|
|
60
|
+
pieces.append(piece)
|
|
61
|
+
return pieces
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""Run a gate over one output file. A gate fails closed: only a clean pass counts."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import subprocess
|
|
9
|
+
import sys
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Callable, NamedTuple, Sequence, Union
|
|
12
|
+
|
|
13
|
+
# A gate is a shell command string, an argument list, or a function from the output text to a verdict.
|
|
14
|
+
Verdict = Union[bool, "tuple[bool, str]"]
|
|
15
|
+
Gate = Union[str, Sequence[str], Callable[[str], Verdict]]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class GateResult(NamedTuple):
|
|
19
|
+
passed: bool
|
|
20
|
+
why: str
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _check(gate: Gate, path: str, timeout: float) -> "tuple[bool, str, bool]":
|
|
24
|
+
"""(passed, why, errored). `errored` is True when the gate could not give a verdict at all."""
|
|
25
|
+
if callable(gate):
|
|
26
|
+
try:
|
|
27
|
+
text = Path(path).read_text(encoding="utf-8", errors="replace")
|
|
28
|
+
verdict = gate(text)
|
|
29
|
+
except Exception as exc: # a gate that crashes must not pass anything
|
|
30
|
+
return False, "gate error: %s" % exc, True
|
|
31
|
+
if isinstance(verdict, tuple):
|
|
32
|
+
ok, why = bool(verdict[0]), str(verdict[1]) if len(verdict) > 1 else ""
|
|
33
|
+
return ok, why or ("ok" if ok else "gate rejected the output"), False
|
|
34
|
+
return bool(verdict), "ok" if verdict else "gate rejected the output", False
|
|
35
|
+
stem = os.path.splitext(os.path.basename(path))[0]
|
|
36
|
+
if isinstance(gate, str):
|
|
37
|
+
cmd = gate.replace("{out}", '"%s"' % path).replace("{id}", stem)
|
|
38
|
+
shell = True
|
|
39
|
+
else:
|
|
40
|
+
cmd = [str(part).replace("{out}", path).replace("{id}", stem) for part in gate]
|
|
41
|
+
shell = False
|
|
42
|
+
label = cmd if isinstance(cmd, str) else " ".join(cmd)
|
|
43
|
+
try:
|
|
44
|
+
r = subprocess.run(cmd, shell=shell, capture_output=True, text=True, encoding="utf-8",
|
|
45
|
+
errors="replace", timeout=timeout)
|
|
46
|
+
except subprocess.TimeoutExpired:
|
|
47
|
+
return False, "gate error: command '%s' timed out after %s seconds" % (label, timeout), True
|
|
48
|
+
except Exception as exc:
|
|
49
|
+
return False, "gate error: %s" % exc, True
|
|
50
|
+
if r.returncode == 0:
|
|
51
|
+
return True, "ok", False
|
|
52
|
+
msg = (r.stderr or r.stdout).strip()
|
|
53
|
+
return False, "gate exit %d: %s" % (r.returncode, msg[:200] if msg else "nonzero"), False
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def run_gate(gate: Gate, path: "str | os.PathLike[str]", timeout: float = 10) -> GateResult:
|
|
57
|
+
"""Run `gate` on the output file at `path`; returns (passed, why).
|
|
58
|
+
|
|
59
|
+
A command string has `{out}` replaced by the quoted file path and `{id}` by the file's name without its
|
|
60
|
+
extension, and runs through the shell. An argument list runs without a shell, with the same two
|
|
61
|
+
replacements in each item. A function receives the file's text and returns a bool or `(bool, why)`.
|
|
62
|
+
Exit code 0, a true verdict, is the only pass. A nonzero exit, a timeout, an exception or a gate that
|
|
63
|
+
cannot start all fail.
|
|
64
|
+
"""
|
|
65
|
+
passed, why, _ = _check(gate, os.fspath(path), timeout)
|
|
66
|
+
return GateResult(passed, why)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def gate_fingerprint(gate: Gate) -> str:
|
|
70
|
+
"""Hash of the gate itself: the command line and the contents of every existing file it names.
|
|
71
|
+
|
|
72
|
+
A changed gate script changes the fingerprint even when the command line stays the same. For a
|
|
73
|
+
function the fingerprint covers its name and its bytecode.
|
|
74
|
+
"""
|
|
75
|
+
if callable(gate):
|
|
76
|
+
h = hashlib.sha256(("%s.%s" % (getattr(gate, "__module__", ""), getattr(gate, "__qualname__", repr(gate)))).encode())
|
|
77
|
+
code = getattr(gate, "__code__", None)
|
|
78
|
+
if code is not None:
|
|
79
|
+
h.update(b"\0code:")
|
|
80
|
+
h.update(code.co_code)
|
|
81
|
+
h.update(repr(code.co_consts).encode("utf-8", "replace"))
|
|
82
|
+
return h.hexdigest()
|
|
83
|
+
cmd = gate if isinstance(gate, str) else "\0".join(str(p) for p in gate)
|
|
84
|
+
h = hashlib.sha256(cmd.encode("utf-8"))
|
|
85
|
+
if isinstance(gate, str):
|
|
86
|
+
tokens = re.findall(r'"([^"]+)"', gate) + re.findall(r"'([^']+)'", gate) + gate.split()
|
|
87
|
+
else:
|
|
88
|
+
tokens = [str(p) for p in gate]
|
|
89
|
+
own = os.path.realpath(sys.executable).lower()
|
|
90
|
+
for cand in sorted(set(tokens)):
|
|
91
|
+
cand_clean = cand.strip('\'"')
|
|
92
|
+
if os.path.isfile(cand_clean):
|
|
93
|
+
try:
|
|
94
|
+
if os.path.realpath(cand_clean).lower() == own:
|
|
95
|
+
continue # the interpreter is not part of the gate's logic
|
|
96
|
+
with open(cand_clean, "rb") as fh:
|
|
97
|
+
h.update(b"\0file:")
|
|
98
|
+
h.update(cand_clean.encode("utf-8"))
|
|
99
|
+
h.update(b"\0")
|
|
100
|
+
h.update(fh.read())
|
|
101
|
+
except OSError:
|
|
102
|
+
pass
|
|
103
|
+
return h.hexdigest()
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""Numbers worth reporting about a run: gate pass rate, throughput that counts only accepted output, diversity."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
from typing import Any, Dict, Iterable, Mapping, Sequence
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def output_diversity(outputs: Iterable[str]) -> Dict[str, Any]:
|
|
10
|
+
"""How many accepted outputs are distinct. Whitespace around an output is ignored.
|
|
11
|
+
|
|
12
|
+
Returns `accepted`, `unique_outputs`, `duplicate_count` and `diversity_ratio` (1.0 for no outputs).
|
|
13
|
+
A gate can pass a model that returns the same text for every piece; this shows it.
|
|
14
|
+
"""
|
|
15
|
+
digests = [hashlib.sha256(text.strip().encode("utf-8")).hexdigest() for text in outputs]
|
|
16
|
+
unique = len(set(digests))
|
|
17
|
+
return {
|
|
18
|
+
"accepted": len(digests),
|
|
19
|
+
"unique_outputs": unique,
|
|
20
|
+
"duplicate_count": len(digests) - unique,
|
|
21
|
+
"diversity_ratio": round(unique / len(digests), 4) if digests else 1.0,
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def summarize_samples(samples: Sequence[Mapping[str, Any]]) -> Dict[str, Any]:
|
|
26
|
+
"""Quality-adjusted throughput for one model on one task.
|
|
27
|
+
|
|
28
|
+
Each sample is a mapping with `passed` (the gate verdict) and `wall_clock_s`, and optionally `ttft_s`
|
|
29
|
+
(seconds to the first token, or None) and `eval_tokens_per_s` (0 when unknown). Returns:
|
|
30
|
+
|
|
31
|
+
- `pass_rate`: passed over total, two places.
|
|
32
|
+
- `accepted_outputs_per_s`: passed samples over the total wall clock, three places.
|
|
33
|
+
- `mean_wall_clock_s` and `mean_ttft_s`: three places; the mean skips samples without a first-token time.
|
|
34
|
+
- `mean_tokens_per_s`: the mean over samples with a positive speed, two places.
|
|
35
|
+
- `quality_adjusted_tokens_per_s`: `mean_tokens_per_s * pass_rate`, so a fast model whose output keeps
|
|
36
|
+
failing the gate scores low.
|
|
37
|
+
"""
|
|
38
|
+
total = len(samples)
|
|
39
|
+
passed = sum(1 for s in samples if s.get("passed"))
|
|
40
|
+
pass_rate = round(passed / total, 2) if total else 0.0
|
|
41
|
+
clocks = [float(s.get("wall_clock_s") or 0.0) for s in samples]
|
|
42
|
+
total_clock = sum(clocks)
|
|
43
|
+
ttfts = [s["ttft_s"] for s in samples if s.get("ttft_s") is not None]
|
|
44
|
+
speeds = [s["eval_tokens_per_s"] for s in samples if (s.get("eval_tokens_per_s") or 0) > 0]
|
|
45
|
+
mean_speed = round(sum(speeds) / len(speeds), 2) if speeds else 0.0
|
|
46
|
+
return {
|
|
47
|
+
"total_samples": total,
|
|
48
|
+
"passed_samples": passed,
|
|
49
|
+
"pass_rate": pass_rate,
|
|
50
|
+
"accepted_outputs_per_s": round(passed / total_clock, 3) if total_clock > 0 else 0.0,
|
|
51
|
+
"mean_ttft_s": round(sum(ttfts) / len(ttfts), 3) if ttfts else 0.0,
|
|
52
|
+
"mean_wall_clock_s": round(total_clock / len(clocks), 3) if clocks else 0.0,
|
|
53
|
+
"mean_tokens_per_s": mean_speed,
|
|
54
|
+
"quality_adjusted_tokens_per_s": round(mean_speed * pass_rate, 2),
|
|
55
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""A runner that calls an external command, for models that sit behind a command line tool."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import subprocess
|
|
7
|
+
from typing import Callable, Mapping, Optional, Sequence
|
|
8
|
+
|
|
9
|
+
from ._wave import Call, HostError, Runner
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def command_runner(
|
|
13
|
+
build: Callable[[Call], Sequence[str]],
|
|
14
|
+
*,
|
|
15
|
+
stdin: bool = True,
|
|
16
|
+
env: Optional[Mapping[str, str]] = None,
|
|
17
|
+
) -> Runner:
|
|
18
|
+
"""Make a runner from a function that turns a Call into an argument list.
|
|
19
|
+
|
|
20
|
+
The command runs with the call's timeout. Its standard output, stripped, is the model output. A nonzero
|
|
21
|
+
exit, a timeout or a command that cannot start raises HostError, so the wave counts it as a host failure
|
|
22
|
+
and not as output that failed the gate. With `stdin=True` the piece text is sent on standard input as
|
|
23
|
+
UTF-8; otherwise the function is expected to put the text in the argument list. `env` is added to the
|
|
24
|
+
environment, and `PYTHONUTF8=1` is set unless `env` says otherwise, so a Python command reads UTF-8.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def run(call: Call) -> str:
|
|
28
|
+
argv = list(build(call))
|
|
29
|
+
environment = {**os.environ, "PYTHONUTF8": "1", **(env or {})}
|
|
30
|
+
try:
|
|
31
|
+
r = subprocess.run(argv, input=call.text if stdin else None, capture_output=True, text=True,
|
|
32
|
+
encoding="utf-8", errors="replace", timeout=call.timeout, env=environment)
|
|
33
|
+
except subprocess.TimeoutExpired:
|
|
34
|
+
raise HostError("timed out after %s seconds" % call.timeout)
|
|
35
|
+
except OSError as exc:
|
|
36
|
+
raise HostError("%s: %s" % (type(exc).__name__, exc))
|
|
37
|
+
if r.returncode != 0:
|
|
38
|
+
raise HostError((r.stderr or "").strip()[:300] or "exit %d" % r.returncode)
|
|
39
|
+
return r.stdout.strip()
|
|
40
|
+
|
|
41
|
+
return run
|