-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbench.py
More file actions
executable file
·338 lines (267 loc) · 10.6 KB
/
bench.py
File metadata and controls
executable file
·338 lines (267 loc) · 10.6 KB
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
#!/usr/bin/env python3
"""benchmark runner for enc transpilation."""
import argparse
import json
import os
import re
import shutil
import subprocess
import tempfile
from datetime import datetime
from pathlib import Path
BENCHMARKS_DIR = "benchmarks"
RESULTS_FILE = "results.json"
LOGS_DIR = "logs"
def parse_args():
parser = argparse.ArgumentParser(description="run enc transpilation benchmarks")
parser.add_argument("language", help="target language (e.g., rust, python)")
parser.add_argument("iterations", type=int, help="number of iterations per model")
parser.add_argument(
"models",
nargs="+",
help="provider/model pairs (e.g., google/gemini-3-flash-preview)",
)
return parser.parse_args()
def load_existing_results(path):
"""load existing benchmark results or return empty structure."""
if path.exists():
with open(path) as f:
return json.load(f)
return {"benchmarks": []}
def save_results(path, data):
"""save benchmark results to json file."""
with open(path, "w") as f:
json.dump(data, f, indent=2)
def get_or_create_language_entry(data, language):
"""find existing language entry or create a new one."""
for entry in data["benchmarks"]:
if entry["target_language"] == language:
return entry
entry = {"target_language": language, "results": []}
data["benchmarks"].append(entry)
return entry
def get_next_run_number(results, provider, model):
"""determine next run number for a provider/model combo."""
existing = [
r["run"] for r in results if r["provider"] == provider and r["model"] == model
]
return max(existing, default=0) + 1
def parse_tokens(token_str):
"""parse token string into structured dict."""
tokens = {"input": 0, "output": 0, "thinking": None}
if not token_str or token_str == "N/A":
return tokens
input_match = re.search(r"(\d+)\s*input", token_str)
output_match = re.search(r"(\d+)\s*output", token_str)
thinking_match = re.search(r"(\d+)\s*thinking", token_str)
if input_match:
tokens["input"] = int(input_match.group(1))
if output_match:
tokens["output"] = int(output_match.group(1))
if thinking_match:
tokens["thinking"] = int(thinking_match.group(1))
return tokens
def parse_cost(cost_str):
"""parse cost string like '$1.234' into float."""
if not cost_str or cost_str == "N/A":
return 0.0
return float(cost_str.replace("$", ""))
def parse_time(time_str):
"""parse time string like '123.45s' into float seconds."""
if not time_str or time_str == "N/A":
return 0.0
return float(time_str.replace("s", ""))
def setup_benchmark_dir(tmp_dir, root_dir, language):
"""copy necessary files to benchmark directory."""
tmp = Path(tmp_dir)
root = Path(root_dir)
(tmp / "src").mkdir(parents=True, exist_ok=True)
(tmp / "testdata").mkdir(parents=True, exist_ok=True)
files_to_copy = [
("src/enc.en", "src/enc.en"),
(".enc.env.example", ".enc.env.example"),
("Makefile", "Makefile"),
("CMakeLists.txt", "CMakeLists.txt"),
("Cargo.toml", "Cargo.toml"),
("requirements.txt", "requirements.txt"),
("package.json", "package.json"),
(".enc.env", ".enc.env"),
("test.sh", "test.sh"),
]
for src, dst in files_to_copy:
src_path = root / src
if src_path.exists():
shutil.copy2(src_path, tmp / dst)
dirs_to_copy = [
("res", "res"),
("testdata/goldens", "testdata/goldens"),
("tests", "tests"),
]
for src, dst in dirs_to_copy:
src_path = root / src
if src_path.exists():
if (tmp / dst).exists():
shutil.rmtree(tmp / dst)
shutil.copytree(src_path, tmp / dst)
# copy enc files preserving type (symlink or regular file)
enc_files_to_copy = ["enc", "enc-release", f"enc-{language}"]
for name in enc_files_to_copy:
src_path = root / name
dst_path = tmp / name
if not src_path.exists() and not src_path.is_symlink():
continue
if dst_path.exists() or dst_path.is_symlink():
dst_path.unlink()
if src_path.is_symlink():
dst_path.symlink_to(os.readlink(src_path))
else:
shutil.copy2(src_path, dst_path)
def run_benchmark(tmp_dir, root_dir, language, provider, model, enc_path):
"""run a single benchmark iteration, streaming output in realtime."""
tmp = Path(tmp_dir)
# touch src/enc.en to trigger rebuild
(tmp / "src/enc.en").touch()
# run make bootstrap-deps (silently, just touch targets)
subprocess.run(
["make", "-s", "-t", "bootstrap-deps"],
cwd=tmp,
capture_output=True,
)
# run the transpilation
env = os.environ.copy()
env.update(
{
"ENC": enc_path,
"PROVIDER": provider,
"MODEL": model,
"TEST_COMMAND": f"make test-{language}",
"TEST_ITERATIONS": "5",
}
)
# stream output in realtime while capturing for logging
proc = subprocess.Popen(
["make", "-s", f"transpile-{language}"],
cwd=tmp,
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
)
output_lines = []
if proc.stdout:
for line in proc.stdout:
print(line, end="", flush=True)
output_lines.append(line)
proc.wait()
return proc.returncode, "".join(output_lines)
def parse_benchmark_output(output):
"""extract metrics from benchmark output."""
attempts = len(re.findall(r"executing test command", output))
cost_match = re.search(r"^total:\s*(\$[\d.]+)", output, re.MULTILINE)
cost = parse_cost(cost_match.group(1) if cost_match else "N/A")
time_match = re.search(r"^elapsed time:\s*([\d.]+s)", output, re.MULTILINE)
elapsed = parse_time(time_match.group(1) if time_match else "N/A")
token_match = re.search(r"^tokens:\s*(.+)$", output, re.MULTILINE)
tokens = parse_tokens(token_match.group(1) if token_match else "N/A")
log_match = re.search(r"^debug log path:\s*(.+)$", output, re.MULTILINE)
debug_log = log_match.group(1).strip() if log_match else None
return attempts, cost, elapsed, tokens, debug_log
def save_log(logs_dir, language, provider, model, run_num, output):
"""save benchmark log and return relative path."""
logs_dir.mkdir(parents=True, exist_ok=True)
timestamp = datetime.now().strftime("%Y%m%d-%H%M%S")
# sanitize model name for filename
model_safe = model.replace("/", "-")
filename = f"{language}-{provider}-{model_safe}-run{run_num}-{timestamp}.log"
log_path = logs_dir / filename
with open(log_path, "w") as f:
f.write(output)
return f"{LOGS_DIR}/{filename}", timestamp # return timestamp for syncing
def save_debug_log(
logs_dir, tmp_dir, relative_path, language, provider, model, run_num, timestamp
):
"""save debug log and return relative path."""
if not relative_path:
return None
src_path = Path(tmp_dir) / relative_path
if not src_path.exists():
return None
logs_dir.mkdir(parents=True, exist_ok=True)
model_safe = model.replace("/", "-")
filename = f"{language}-{provider}-{model_safe}-run{run_num}-{timestamp}.debug.log"
dst_path = logs_dir / filename
shutil.copy2(src_path, dst_path)
return f"{LOGS_DIR}/{filename}"
def main():
args = parse_args()
root_dir = os.getcwd()
enc_path = os.environ.get("ENC", os.path.join(root_dir, "target/release/enc"))
benchmarks_dir = Path(root_dir) / BENCHMARKS_DIR
results_path = benchmarks_dir / RESULTS_FILE
logs_dir = benchmarks_dir / LOGS_DIR
cleanup = os.environ.get("CLEANUP", "true").lower() == "true"
benchmarks_dir.mkdir(parents=True, exist_ok=True)
data = load_existing_results(results_path)
lang_entry = get_or_create_language_entry(data, args.language)
print(f"[*] using {enc_path} for benchmark ...")
for model_pair in args.models:
provider, model = model_pair.split("/", 1)
print(f"[*] benchmarking {provider}/{model} ...")
for i in range(1, args.iterations + 1):
run_num = get_next_run_number(lang_entry["results"], provider, model)
print(
f"[*] starting benchmark run {i}/{args.iterations} (run #{run_num}) ..."
)
tmp_dir = tempfile.mkdtemp(prefix="enc-bench-")
try:
print(f"[*] running benchmark in {tmp_dir} ...")
setup_benchmark_dir(tmp_dir, root_dir, args.language)
exit_code, output = run_benchmark(
tmp_dir, root_dir, args.language, provider, model, enc_path
)
attempts, cost, elapsed, tokens, debug_log_path = (
parse_benchmark_output(output)
)
status = "PASS" if exit_code == 0 else "FAIL"
log_path, timestamp = save_log(
logs_dir, args.language, provider, model, run_num, output
)
saved_debug_log_path = save_debug_log(
logs_dir,
tmp_dir,
debug_log_path,
args.language,
provider,
model,
run_num,
timestamp,
)
result = {
"provider": provider,
"model": model,
"run": run_num,
"attempts": attempts,
"status": status,
"cost": cost,
"time_seconds": elapsed,
"tokens": tokens,
"log": log_path,
"debug_log": saved_debug_log_path,
}
lang_entry["results"].append(result)
save_results(results_path, data)
print(
f"[*] run #{run_num}: {status} (cost: ${cost:.2f}, time: {elapsed:.1f}s)"
)
print(f"[*] log saved to {log_path}")
if saved_debug_log_path:
print(f"[*] debug log saved to {saved_debug_log_path}")
finally:
if cleanup:
print(f"[*] cleaning up temporary dir {tmp_dir}")
shutil.rmtree(tmp_dir, ignore_errors=True)
else:
print(f"[*] skipping cleanup, kept {tmp_dir}")
print(f"[*] benchmark completed! results written to {results_path}")
if __name__ == "__main__":
main()