1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
|
"""End-to-end helpers used by the reproduction notebook."""
from __future__ import annotations
import json
import os
import time
from pathlib import Path
from typing import Any
from .clients import OpenAIJsonClient, ScriptedClient
from .models import CanonicalItem
from .offline import load_dataset
from .paper_pipeline import PaperKernelPipeline, PaperPipelineConfig
from .release import export_release
from .store import RunStore
from .surface import SurfacePipeline
def _ensure_fresh(path: Path) -> None:
if path.exists() and any(path.iterdir()):
raise FileExistsError(f"refusing to reuse non-empty output directory {path}")
def _review_accept() -> dict[str, str]:
return {
"verdict": "accept",
"step_by_step_check": "n1 passes; n2 passes; n3 passes",
"blocking_issues": "",
"patch_suggestion": "",
}
def _offline_record() -> dict[str, Any]:
return {
"index": "demo-A-1",
"question": r"Let \(a>0\). Prove that \(a+1/a\ge 2\).",
"solution": (
r"Since \((a-1)^2\ge0\), expand and divide by \(a>0\) "
r"to obtain \(a+1/a\ge2\)."
),
"vars": ["a"],
"params": [],
"sci_consts": [],
"problem_type": "proof",
"variants": {},
}
async def run_live_item(
*,
dataset_dir: Path,
item_id: str,
work_root: Path,
model: str = "o3",
api_key: str | None = None,
) -> dict[str, Any]:
"""Generate four surface variants and one verified kernel variant."""
if not (api_key or os.getenv("OPENAI_API_KEY")):
raise RuntimeError(
"OPENAI_API_KEY is missing. Set it in the environment or enter it "
"with getpass in the notebook."
)
_ensure_fresh(work_root)
work_root.mkdir(parents=True, exist_ok=True)
surface_root = work_root / "surface-runs"
kernel_root = work_root / "kernel-runs"
release_root = work_root / "release"
records = load_dataset(dataset_dir)
if item_id not in records:
raise KeyError(f"{item_id!r} not found in {dataset_dir}")
item = CanonicalItem.from_public_record(records[item_id])
started = time.monotonic()
surface_store = RunStore(surface_root, item.item_id)
surface_store.write_input(item)
surface_store.write_config(
{"protocol_name": "gap-surface-original-prompts", "model": model}
)
surfaces = await SurfacePipeline(
OpenAIJsonClient(model, api_key=api_key),
surface_store,
).run_all(item)
config = PaperPipelineConfig(proposer_model=model, judge_model=model)
kernel = await PaperKernelPipeline(
proposer=OpenAIJsonClient(model, api_key=api_key),
judges=[OpenAIJsonClient(model, api_key=api_key) for _ in range(5)],
store=RunStore(kernel_root, item.item_id),
config=config,
).run(item)
if kernel.status != "accepted":
raise RuntimeError(
f"kernel candidate was rejected after {len(kernel.iterations)} rounds"
)
manifest = export_release(
source_dataset=dataset_dir,
surface_run_root=surface_root,
kernel_run_root=kernel_root,
output_root=release_root,
item_ids={item_id},
)
return {
"mode": "live",
"item_id": item_id,
"model": model,
"elapsed_seconds": round(time.monotonic() - started, 2),
"surface_families": sorted(surfaces),
"kernel_status": kernel.status,
"verification_rounds": len(kernel.iterations),
"export_status": manifest["status"],
"exported_item_count": manifest["exported_item_count"],
"work_root": str(work_root.resolve()),
"release_record": manifest["exported"][0]["path"],
"manifest": str((release_root / "manifest.json").resolve()),
}
async def run_offline_smoke(work_root: Path) -> dict[str, Any]:
"""Exercise the end-to-end wiring with deterministic model responses."""
_ensure_fresh(work_root)
work_root.mkdir(parents=True, exist_ok=True)
source_root = work_root / "source"
source_root.mkdir()
surface_root = work_root / "surface-runs"
kernel_root = work_root / "kernel-runs"
release_root = work_root / "release"
record = _offline_record()
item_id = str(record["index"])
(source_root / f"{item_id}.json").write_text(
json.dumps(record, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
item = CanonicalItem.from_public_record(record)
names = {
"descriptive_long": "positivequantity",
"descriptive_long_confusing": "walnutvioletterrace",
"descriptive_long_misleading": "primefieldorder",
"garbled_string": "qzxwvtnphjgrksla",
}
surface_responses = {
f"{item_id}.surface.{family}": {
"map": {"a": name},
"question": record["question"].replace("a", name),
"solution": record["solution"].replace("a", name),
}
for family, name in names.items()
}
surface_store = RunStore(surface_root, item_id)
surface_store.write_input(item)
surface_store.write_config(
{"protocol_name": "gap-surface-smoke", "model": "scripted"}
)
surfaces = await SurfacePipeline(
ScriptedClient(surface_responses),
surface_store,
).run_all(item)
proposer = ScriptedClient(
{
f"{item_id}.stage1.dag": {
"nodes": [
{
"node_id": "n1",
"claim": "(a-1)^2 >= 0",
"dependencies": [],
},
{
"node_id": "n2",
"claim": "a^2-2a+1 >= 0",
"dependencies": ["n1"],
},
{
"node_id": "n3",
"claim": "a+1/a >= 2",
"dependencies": ["n2"],
},
],
"terminal_node_id": "n3",
},
f"{item_id}.stage2.methods": {
"nodes": [
{
"node_id": "n1",
"method_label": "use nonnegativity of a square",
},
{
"node_id": "n2",
"method_label": "expand the square",
},
{
"node_id": "n3",
"method_label": "divide by a positive quantity",
},
]
},
f"{item_id}.stage3.replacement": {
"changes": [
{
"slot_id": "slot1",
"source_node_id": "n1",
"description": "positive square root at equality",
"original_value": "1",
"replacement_value": "2",
"guard_condition": "replacement is positive",
"guard_justification": "2 is positive",
}
],
"closure_statement": "The equality value is the only change.",
},
f"{item_id}.stage4.diffusion": {
"nodes": [
{
"node_id": "n1",
"dependencies": [],
"method_label": "use nonnegativity of a square",
"instantiated_claim": "(x-2)^2 >= 0",
"justification": "squares are nonnegative",
},
{
"node_id": "n2",
"dependencies": ["n1"],
"method_label": "expand the square",
"instantiated_claim": "x^2-4x+4 >= 0",
"justification": "expand n1",
},
{
"node_id": "n3",
"dependencies": ["n2"],
"method_label": "divide by a positive quantity",
"instantiated_claim": "x+4/x >= 4",
"justification": "divide n2 by x>0",
},
],
"terminal_node_id": "n3",
"terminal_answer": "4",
},
f"{item_id}.stage5.render": {
"question": "Let x>0. Prove that x+4/x >= 4.",
"solution": (
"[n1] Since (x-2)^2 >= 0. [n2] Expanding gives "
"x^2-4x+4 >= 0. [n3] Divide by x>0 to get x+4/x >= 4."
),
"node_order": ["n1", "n2", "n3"],
"terminal_answer": "4",
},
}
)
judges = [
ScriptedClient(
{f"{item_id}.verify": [_review_accept(), _review_accept()]}
)
for _ in range(5)
]
kernel = await PaperKernelPipeline(
proposer=proposer,
judges=judges,
store=RunStore(kernel_root, item_id),
config=PaperPipelineConfig(
proposer_model="scripted",
judge_model="scripted",
),
).run(item)
manifest = export_release(
source_dataset=source_root,
surface_run_root=surface_root,
kernel_run_root=kernel_root,
output_root=release_root,
item_ids={item_id},
)
return {
"mode": "offline-smoke",
"item_id": item_id,
"surface_families": sorted(surfaces),
"kernel_status": kernel.status,
"verification_rounds": len(kernel.iterations),
"export_status": manifest["status"],
"exported_item_count": manifest["exported_item_count"],
"work_root": str(work_root.resolve()),
"release_record": manifest["exported"][0]["path"],
"manifest": str((release_root / "manifest.json").resolve()),
}
|