# H3 synthesis protocol (real open models: write the rule once vs answer token by token)

Written 2026-11-25, before any execution. Code: `h3_synthesis.py` (generation `run_h3_generate(model_key)`, scoring `run_h3_evaluate(generation)`, predictions `check_predictions`), entry points `h3_synthesis_small` / `h3_synthesis_large` in `app.py`, tests in `out_h3/`. This file freezes the details that the public protocol page (`h3-protocol` on the site) leaves open ("names fixed at launch"). The public protocol is not changed. Hypothesis H3: where an answer can be checked, "rules + exceptions" is a form of compression. Question: on a task that comes back, can the token-by-token execution be replaced by a program written once by a small open model, and at what cost in accuracy?

## Models (fixed here)
- small: `Qwen/Qwen2.5-1.5B-Instruct`; large: `Qwen/Qwen2.5-7B-Instruct` (open weights, Apache-2.0, not gated). bf16, official chat template, `add_generation_prompt=True`, default system prompt of the template (not overridden). Parameters counted as the real `sum(p.numel() for p in model.parameters())` (shared tied weights counted once, as `parameters()` does), recorded with the exact model name, the revision (sha) and the versions (torch, transformers, python, GPU name).
- Loading: the model is downloaded and loaded on the CPU (bf16) OUTSIDE the GPU function (`prefetch_model`, called by the undecorated endpoint), then moved with `.to('cuda')` inside the `@spaces.GPU(duration=600)` function (the ZeroGPU pattern; a 7B in bf16 is about 15 GB, it fits the 24 GB of the A10G with the KV cache of a batch of 25, and the CPU copy fits the Space RAM; no `device_map`). The CPU copy is consumed by the call (removed from the module cache); the next call reloads it from the disk cache. If the CPU side was not run, `run_h3_generate` loads the model itself and the load is then counted in the 600 s.
- Pinned versions in `requirements.txt`: `transformers==5.24.1`, `accelerate==1.16.0` (latest stable on PyPI on 2026-11-25; checked on the PyPI JSON API). `torch` is the ZeroGPU preinstalled one (not pinned here). NOT tested on the Space: first real run = first test of this stack.

## Tasks (generated by program, fixed seeds, exact answer known)
3 families x 3 tasks. For each task: k = 24 shown examples (input -> output) and n = 100 hidden test instances, same data for both models (task i uses seed 2026112500 + i + 1, `random.Random`). The data are fingerprinted (`task_data_sha256`); `run_h3_evaluate` refuses a generation made with other data.
- Family 1, clean rule: 1a ISO date + N days (N in 1..400, start date in 2020-2030; input `2025-12-05 +223`); 1b integer degrees Celsius in -40..120 -> Fahrenheit rounded to the nearest integer, half up (no exact half occurs: 9c/5 has only fifths); 1c five distinct integers in 0..99 -> sorted descending, `a,b,c,d,e`.
- Family 2, rule + exceptions (about 10 %): 2a English plural (+s; +es after s/x/z/ch/sh; consonant+y -> ies; 12 fixed irregulars: child, mouse, foot, tooth, goose, man, woman, person, ox, sheep, fish, deer); 2b price with tax = round(HT x 1.2, 2) (decimal arithmetic, half up), except 8 fixed exempt (code, price) strings where TTC = HT; input `CODE price`; 2c weekday (English) of a date in 2027, except 10 fixed holidays (2027-01-01, 03-17, 05-01, 07-04, 07-14, 08-15, 10-31, 11-11, 12-25, 12-31) -> `holiday`.
  Stratified draw, documented: exactly 2 exceptions among the 24 shown (8.3 %, the closest to 10 %: 2.4 expected), exactly 10 among the 100 test instances (10 %); the rest are regular instances. Regular inputs never overlap (shown / test / within). The exceptions come from the SMALL FIXED SET above and may recur: the 2 shown are drawn without replacement, the 10 test ones with replacement. Hence an exception input can appear both in the shown examples and in the test, which is what lets the table of C cover part of them (the table is keyed by the exact input string). For 2b the exceptions are 8 fixed `CODE price` strings (a table keyed on the whole input cannot match a random price). Expected coverage of the test exceptions by the table: about 2/12 (2a), 2/8 (2b), 2/10 (2c), i.e. a small part: the table can only recover what was shown.
- Family 3, no clean rule (negative control, asks for knowledge): 3a English adjective -> positive / negative (84 + 82 fixed adjectives without ambiguity; 12 + 12 shown, 50 + 50 test); 3b country -> Europe / not Europe (43 listed European countries, 108 others; Russia, Turkey, Cyprus, Georgia, Armenia, Azerbaijan, Kazakhstan and Kosovo are left out as ambiguous; 8 Europe + 16 not shown, 33 + 67 test, because Europe has too few listed countries for 50 %); 3c animal -> mammal / not mammal (65 + 69 fixed animals; 12 + 12 shown, 50 + 50 test). The lists are in the code.

## Prompts (fixed)
The instruction is one line that gives the formats and the label set, never the rule (e.g. 1b: `Input: an integer. Output: an integer.`; 3a: `Input: an English adjective. Output: positive or negative.`). Examples are written `x -> y`, one per line, in a random fixed order.
- A: instruction + the 24 examples + "Give the output for the new input below. Reply with the output only, on one line." + `Input: x` + `Output:`. Greedy (`do_sample=False`, `repetition_penalty=1.0`, which overrides the 1.05 of the Qwen generation config), `max_new_tokens=24`. Answer = first line of the stripped output; exact match with the true output (strict: `Output: 5` is wrong).
- B: instruction + the 24 examples + a request for `def solve(x: str) -> str` (standard library only, no input/output, a single ```python block). R = 5 attempts per task and model from ONE prompt, sampling temperature 0.7, top_p 0.95, `top_k=0` (disabled), `repetition_penalty=1.0`, `max_new_tokens=512`, `num_return_sequences=5`, `torch.manual_seed(2026112600 + i + 1)` per task (i = task index 0..8). GPU sampling is not bit-reproducible across hardware or library versions; the seeds fix the intent.
- Code extraction: first ```python block that contains `def solve`; else any fenced block that contains it (an unterminated block is accepted); else the text from the first `def solve` on; none = failed attempt.
- Selection: the attempt with the best accuracy on the 24 SHOWN examples (never on the test); tie -> first attempt.
- C: the program selected in B plus a table: every shown example whose `solve(x)` differs from the output goes in the table (x -> y). At execution: if the test input is in the table return the table value, else `solve(x)`. Cost of C = cost of B.
- Execution (sandbox, best effort for code written by an open model on a private Space, not a security boundary against adversarial code): subprocess `python -I`, JSON on stdin, 2 s wall-clock for the whole batch of one program (24 shown + 100 test inputs together), `RLIMIT_AS` 1 GiB (enforced on Linux, best effort elsewhere), `RLIMIT_CPU` 4 s, `RLIMIT_FSIZE` 1 MiB, empty temporary working directory, minimal environment, sockets / `subprocess` / `os.system` / `fork` / `exec` patched to raise, stdout and stderr of the program discarded, normal builtins. An exception on one instance = that instance wrong; a crash or a timeout = all instances of that attempt wrong; a result that is not a `str` = wrong.

## Measures
- Accuracy: exact match over the 100 hidden instances of the task.
- Compute (published formula): **2 x parameters x (tokens read + tokens generated)**, no prompt cache (every call counted in full). A: sum over the 100 instances of (tokens of the full chat prompt + generated tokens; the first end-of-sequence token counts as generated, padding does not). B and C: sum over the R = 5 attempts of (prompt tokens + generated tokens). CPU execution is measured in seconds (recorded, not counted). Indicative only: the total A with a prefix cache (instruction + examples counted once; the shared prefix is the prompt up to `Input:`).
- Break-even **N\*** per task: N\* = ceil(cost_B / mean cost of A per instance), integer arithmetic. Also reported by task and as mean over the three tasks of a family.
- Always recorded: GPU time per function and per task and stage, versions, exact model name and revision, seeds, code hash, task-data hash. Raw generations (A answers, B texts) are in the JSON.

## Predictions declared in advance (frozen rules, no tolerance; exact arithmetic on integer counts; means over the 3 tasks of a family unless stated)
- **P1** (large, family 1): acc_B >= 0.95 x acc_A AND mean N\*(B) <= 200 (N\* also reported per task).
- **P2** (large, family 2): acc_A - acc_B >= 5 points AND acc_C - acc_B >= 0.5 x (acc_A - acc_B).
- **P3** (both models, family 3): acc_B < acc_A AND acc_C < acc_A, for each model (strict).
- **P4** (small, family 1): the number of attempts with >= 95 correct out of the 100 hidden instances is < 50 % of the 15 attempts (3 tasks x 5); i.e. at most 7 of 15 (all 5 attempts of each task are run on the test for this count, but only the selected one is used for B and C).
- **P5** (both models, families 1-2, N = 1000 instances extrapolated): cost_B (and cost_C) <= cost_A(1000) / 10, i.e. cost_B <= 100 x mean A cost per instance, i.e. N\* <= 100, on each of the 6 tasks and for each model (12 conditions).
`predictions_check` = {P1..P5: {holds, values}}; `holds` is `null` (with `missing`) when a needed model or task is absent (incomplete run). One JSON per model is returned by the Space; the joint P1-P5 are computed locally: `python h3_synthesis.py --combine small.json large.json` (same code as the tests). Results are published as they come, whether the predictions hold or not.
Design note, stated before the run: with 2 shown exceptions the table can recover at most the test exceptions whose input was shown, so P2's second half (C recovers at least half of the A-B gap) is demanding; it is a legitimate test, not tuned.

## Budget (GPU function <= 600 s on A10G, model load included)
Estimate, not measured (order of magnitude; the first run will tell). A: 9 tasks x 100 prompts of about 500-600 tokens (24 examples at about 20 tokens + instructions + the default system prompt), about 0.5 M prompt tokens; prefill of the 7B at about 40 TFLOP/s effective: 2 x 7.6e9 x 5e5 = 7.6e15 -> about 150-190 s; decoding 36 batches of 25 x about 10-24 steps x 40 ms -> about 15-35 s. B: 9 tasks x 1 prompt x 5 sequences, prefill about 10 s in all, decoding 9 x (longest of 5 programs, 150-512 tokens) x 35 ms -> about 50-160 s. Move of the 15 GB model to the GPU about 10-30 s. Total 7B: about 250-400 s typical, up to about 420 s in a bad case, under 450 s. The 1.5B is about 4-5x faster. Batch sizes: A in batches of 25 prompts (left padding), B one batch of 5. If the first run shows more than about 450 s for the 7B, the lever is the batch size, not k or n (published).
Guard: before each stage, if elapsed > GPU_BUDGET_SECONDS - 60 = 540 s, stop cleanly; the JSON has `incomplete: true`, `tasks_done`, and only the finished tasks are scored; the predictions needing the missing tasks are `null`. Tasks run in the order 1a ... 3c, B then A within a task.

## Limitations
Synthetic tasks; 9 tasks only; two model sizes of one family; one prompt wording per condition (not tuned); R = 5 sampled programs; k = 24 and n = 100 (accuracy granularity 1 point; no significance test); compute is estimated (2 x parameters x tokens, attention cost ignored), not measured energy; ZeroGPU gives no reliable energy measure; the sandbox is best effort; family 3 lists may be known by the model or hard-coded into the program (that is part of what the control tests); the table of C is keyed on exact input strings; GPU sampling is not bit-reproducible; the stack (transformers 5.x) is untested on the Space before the run.
