auto-optimize 1.0.0__py3-none-any.whl

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 (67) hide show
  1. auto_optimize/__init__.py +3 -0
  2. auto_optimize/__main__.py +5 -0
  3. auto_optimize/cli.py +651 -0
  4. auto_optimize/skills/auto-optimize-code/LICENSE +21 -0
  5. auto_optimize/skills/auto-optimize-code/SKILL.md +251 -0
  6. auto_optimize/skills/auto-optimize-code/VERSION +1 -0
  7. auto_optimize/skills/auto-optimize-code/references/algorithm.md +182 -0
  8. auto_optimize/skills/auto-optimize-code/references/changes.md +146 -0
  9. auto_optimize/skills/auto-optimize-code/references/cli.md +206 -0
  10. auto_optimize/skills/auto-optimize-code/references/dashboard.md +203 -0
  11. auto_optimize/skills/auto-optimize-code/references/documents.md +55 -0
  12. auto_optimize/skills/auto-optimize-code/references/extending.md +87 -0
  13. auto_optimize/skills/auto-optimize-code/references/external-validation.md +98 -0
  14. auto_optimize/skills/auto-optimize-code/references/glossary.md +134 -0
  15. auto_optimize/skills/auto-optimize-code/references/idea-miner.md +108 -0
  16. auto_optimize/skills/auto-optimize-code/references/issue-bugs.md +182 -0
  17. auto_optimize/skills/auto-optimize-code/references/layout.md +300 -0
  18. auto_optimize/skills/auto-optimize-code/references/main-session.md +45 -0
  19. auto_optimize/skills/auto-optimize-code/references/measuring.md +208 -0
  20. auto_optimize/skills/auto-optimize-code/references/pr-optimization.md +127 -0
  21. auto_optimize/skills/auto-optimize-code/references/pr-tests.md +254 -0
  22. auto_optimize/skills/auto-optimize-code/references/promotion.md +133 -0
  23. auto_optimize/skills/auto-optimize-code/references/reading-a-search.md +65 -0
  24. auto_optimize/skills/auto-optimize-code/references/repo-mode.md +224 -0
  25. auto_optimize/skills/auto-optimize-code/references/resume.md +81 -0
  26. auto_optimize/skills/auto-optimize-code/references/shared-knowledge.md +114 -0
  27. auto_optimize/skills/auto-optimize-code/references/step0-interview.md +298 -0
  28. auto_optimize/skills/auto-optimize-code/references/step1-unit-tests.md +136 -0
  29. auto_optimize/skills/auto-optimize-code/references/step2-baseline.md +708 -0
  30. auto_optimize/skills/auto-optimize-code/references/step3-rounds.md +350 -0
  31. auto_optimize/skills/auto-optimize-code/references/step4-final.md +121 -0
  32. auto_optimize/skills/auto-optimize-code/references/step5-ship.md +220 -0
  33. auto_optimize/skills/auto-optimize-code/references/step6-finish.md +67 -0
  34. auto_optimize/skills/auto-optimize-code/references/subagent.md +467 -0
  35. auto_optimize/skills/auto-optimize-code/references/symptoms.md +67 -0
  36. auto_optimize/skills/auto-optimize-code/references/writing-briefs.md +117 -0
  37. auto_optimize/skills/auto-optimize-code/scripts/attribution.py +156 -0
  38. auto_optimize/skills/auto-optimize-code/scripts/autoopt.py +12863 -0
  39. auto_optimize/skills/auto-optimize-code/scripts/check_seeding.py +334 -0
  40. auto_optimize/skills/auto-optimize-code/scripts/cold.py +90 -0
  41. auto_optimize/skills/auto-optimize-code/scripts/dashboard/README.md +165 -0
  42. auto_optimize/skills/auto-optimize-code/scripts/dashboard/autoopt_monitor.py +850 -0
  43. auto_optimize/skills/auto-optimize-code/scripts/dashboard/gpu_scan.py +954 -0
  44. auto_optimize/skills/auto-optimize-code/scripts/dashboard/monitor_writer.py +684 -0
  45. auto_optimize/skills/auto-optimize-code/scripts/dashboard/scan.py +1030 -0
  46. auto_optimize/skills/auto-optimize-code/scripts/dashboard/static/dashboard.css +775 -0
  47. auto_optimize/skills/auto-optimize-code/scripts/dashboard/static/dashboard.js +3652 -0
  48. auto_optimize/skills/auto-optimize-code/scripts/dashboard/static/index.html +191 -0
  49. auto_optimize/skills/auto-optimize-code/scripts/issue_body.py +2118 -0
  50. auto_optimize/skills/auto-optimize-code/scripts/lint_text.py +448 -0
  51. auto_optimize/skills/auto-optimize-code/scripts/opt_pr_body.py +894 -0
  52. auto_optimize/skills/auto-optimize-code/scripts/opt_pr_tables.py +367 -0
  53. auto_optimize/skills/auto-optimize-code/scripts/paired.py +188 -0
  54. auto_optimize/skills/auto-optimize-code/scripts/preflight.py +280 -0
  55. auto_optimize/skills/auto-optimize-code/scripts/probe_run.py +72 -0
  56. auto_optimize/skills/auto-optimize-code/scripts/publish.py +385 -0
  57. auto_optimize/skills/auto-optimize-code/scripts/run_iteration.py +1382 -0
  58. auto_optimize/skills/auto-optimize-code/scripts/ship.py +1193 -0
  59. auto_optimize/skills/auto-optimize-code/scripts/stages.py +651 -0
  60. auto_optimize/skills/auto-optimize-code/scripts/tests_pr_body.py +1267 -0
  61. auto_optimize/skills/auto-optimize-code/scripts/tests_pr_push.py +426 -0
  62. auto_optimize/skills/auto-optimize-code/scripts/tests_pr_tables.py +779 -0
  63. auto_optimize-1.0.0.dist-info/METADATA +610 -0
  64. auto_optimize-1.0.0.dist-info/RECORD +67 -0
  65. auto_optimize-1.0.0.dist-info/WHEEL +4 -0
  66. auto_optimize-1.0.0.dist-info/entry_points.txt +2 -0
  67. auto_optimize-1.0.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,1382 @@
1
+ #!/usr/bin/env python3
2
+ """Run one iteration: the same idea several times, aggregated into a verdict.
3
+
4
+ CUDA_VISIBLE_DEVICES=2 python3 run_iteration.py autooptimize/iterations/3
5
+
6
+ One *run* is one execution of the benchmark command with one seed. One
7
+ *iteration* is every run of one idea, reduced to a median objective, a
8
+ pass/fail for each gate, and a median for each observer measure. This script
9
+ turns the first into the second and writes `result.json`.
10
+
11
+ What it does, in order:
12
+
13
+ 1. Commits whatever is uncommitted in the iteration's worktree, so
14
+ `git diff autoopt/<parent>..autoopt/<id>` is exactly the idea tried.
15
+ 2. Times the cold first call on an empty compiler cache, when the search
16
+ has compiled code (`first_call`), beside the parent's recorded value.
17
+ 3. Runs one run, every gate and observer on it.
18
+ 4. Runs the unit tests, then the task's compare against A0's cached
19
+ outputs, when they are configured.
20
+ 5. Runs the rest of `runs_per_iteration`, one seed each, every gate and
21
+ observer on every run; one at a time, they stop at the first failure.
22
+ 6. When the tests ran only the changed modules' files (`{selected}`), runs
23
+ the whole suite for an iteration whose median passes the keep rule.
24
+ 7. Records the keep verdict against the parent and, with
25
+ `promote: auto`, promotes on it, then runs the closed round's approved
26
+ external validation.
27
+ 8. Writes `result.json` and a report for the subagent to paste back to
28
+ the orchestrator.
29
+
30
+ Each stage runs only when the stages before it passed. A search made with
31
+ `init --staged` screens at `runs_per_iteration` and confirms to
32
+ `confirm_runs` when the median nears the frontier.
33
+
34
+ Every run's own output stays in `runs/seed-<N>/`: its `metrics.json`, its
35
+ `log.txt`, and whatever the benchmark saved beside them.
36
+
37
+ Re-running is cheap and safe: a seed whose `metrics.json` is already on disk
38
+ is not run again unless `--rerun` is passed. An iteration interrupted halfway
39
+ picks up where it stopped.
40
+ """
41
+
42
+ import os
43
+ import sys
44
+ import json
45
+ import time
46
+ import shutil
47
+ import queue
48
+ import argparse
49
+ import statistics
50
+ import subprocess
51
+ import concurrent.futures
52
+
53
+ HERE = os.path.dirname(os.path.abspath(__file__))
54
+ sys.path.insert(0, HERE)
55
+
56
+ import autoopt
57
+ from autoopt import OPS, fail, git, fmt, cache_dir
58
+
59
+ # The least time, in seconds, a run's CPU idle share is sampled over; the
60
+ # first run of a call waits for it, later ones measure the gap since the
61
+ # run before.
62
+ RUN_IDLE_SAMPLE = 0.2
63
+
64
+
65
+ def check_lease(config):
66
+ """Refuse to start without a GPU lease: `CUDA_VISIBLE_DEVICES` naming the
67
+ GPUs this iteration owns, or `gpu_command` to take one (`autoopt.hold_lease`).
68
+
69
+ Without it every run would see every GPU, and two iterations would land
70
+ on the same card.
71
+ """
72
+
73
+ return autoopt.hold_lease(config)
74
+
75
+
76
+ def leased_devices(config, wanted):
77
+ """The GPU indices to spread this iteration's runs over.
78
+
79
+ A lease of four GPUs is `CUDA_VISIBLE_DEVICES=2,3,5,6`; each run takes
80
+ one of them. Fewer leased than asked for is not an error -- the iteration
81
+ simply runs that many at a time -- but it is worth saying, because the
82
+ usual cause is asking for more than the machine had free.
83
+ """
84
+
85
+ if not config.get('gpu', True):
86
+ return [None] * max(1, wanted)
87
+
88
+ raw = os.environ.get('CUDA_VISIBLE_DEVICES', '')
89
+ devices = [item.strip() for item in raw.split(',') if item.strip()]
90
+
91
+ if not devices:
92
+ return [None]
93
+
94
+ if wanted > len(devices):
95
+ print(' note: {} GPU(s) requested per iteration, {} leased; running '
96
+ '{} run(s) at a time'.format(wanted, len(devices), len(devices)))
97
+
98
+ return devices[:max(1, wanted)]
99
+
100
+
101
+ def load_metrics(run_dir, config):
102
+ """Read and check one run's `metrics.json`.
103
+
104
+ Returns `(record, error)`. A gate the benchmark did not measure is an
105
+ error, not a pass: an unmeasured constraint is the one that silently
106
+ stops holding.
107
+ """
108
+
109
+ path = os.path.join(run_dir, 'metrics.json')
110
+
111
+ try:
112
+ with open(path) as infile:
113
+ metrics = json.load(infile)
114
+ except OSError:
115
+ return None, 'wrote no metrics.json'
116
+ except ValueError as error:
117
+ return None, 'metrics.json is not valid JSON: {}'.format(error)
118
+
119
+ if not isinstance(metrics, dict):
120
+ return None, 'metrics.json is not an object'
121
+
122
+ value = metrics.get('objective')
123
+
124
+ if not isinstance(value, (int, float)) or value != value:
125
+ return None, 'metrics.json has no numeric "objective" (got {!r})'.format(
126
+ value)
127
+
128
+ record = {'objective': float(value), 'gates': {}, 'observers': {}}
129
+
130
+ for gate in config['gates']:
131
+ found = (metrics.get('gates') or {}).get(gate['name'],
132
+ metrics.get(gate['name']))
133
+
134
+ if not isinstance(found, (int, float)) or found != found:
135
+ return None, 'metrics.json has no numeric value for the gate ' \
136
+ '"{}"'.format(gate['name'])
137
+
138
+ record['gates'][gate['name']] = float(found)
139
+
140
+ for observer in config['observers']:
141
+ found = (metrics.get('observers') or {}).get(observer['name'],
142
+ metrics.get(observer['name']))
143
+
144
+ record['observers'][observer['name']] = (float(found)
145
+ if isinstance(found, (int, float)) and found == found else None)
146
+
147
+ record['note'] = metrics.get('note') or ''
148
+
149
+ return record, None
150
+
151
+
152
+ def execute(command, iteration, seed, run_dir, timeout, device=None,
153
+ src=None, cache='', sample=False):
154
+ """One run. Returns `(returncode, seconds)`; output is tee'd to log.txt.
155
+
156
+ `device` pins the run to one leased GPU by setting `CUDA_VISIBLE_DEVICES`
157
+ for the child alone. The value is a physical index out of the lease, so
158
+ two runs of the same iteration never land on the same card. With
159
+ `sample`, the most threads the run had running at once goes to
160
+ `<run_dir>/workers.json`.
161
+ """
162
+
163
+ os.makedirs(run_dir, exist_ok=True)
164
+
165
+ # Relative, so a log or a saved output is found from the iteration
166
+ # directory whichever machine reads it later.
167
+ relative = os.path.relpath(run_dir, iteration)
168
+ line = autoopt.fill(command, seed=seed, out=relative, out_abs=run_dir,
169
+ iteration=iteration, src=src or iteration, cache=cache)
170
+
171
+ start = time.time()
172
+
173
+ with open(os.path.join(run_dir, 'log.txt'), 'w') as log:
174
+ log.write('$ {}\n\n'.format(line))
175
+ log.flush()
176
+
177
+ environment = (dict(os.environ, CUDA_VISIBLE_DEVICES=str(device))
178
+ if device is not None else None)
179
+
180
+ found = {} if sample else None
181
+ code, timed_out = autoopt.run_shell(line, iteration, log,
182
+ environment, timeout, found)
183
+
184
+ if sample:
185
+ autoopt.write_json(os.path.join(run_dir, 'workers.json'), found)
186
+
187
+ if timed_out:
188
+ log.write('\n[killed after {}s by --timeout]\n'.format(timeout))
189
+
190
+ return code, time.time() - start
191
+
192
+
193
+ def select_tests(config, checkout, parent_commit, commit):
194
+ """The test files for what this iteration changed, or None for all.
195
+
196
+ `pkg/foo.py` maps to every `test_foo.py` under the tests path, and a
197
+ changed test file selects itself. Anything that maps to nothing -- a
198
+ `conftest.py`, an `__init__.py`, a file that is not Python, a module
199
+ with no test file of its own -- runs the whole suite, since a subset
200
+ that misses the code it should cover is a pass nobody earned.
201
+ """
202
+
203
+ tests = config['tests']
204
+ path = tests.get('path') or 'tests'
205
+
206
+ if '{selected}' not in tests['command']:
207
+ return None, 'the test command has no {selected}'
208
+
209
+ if not parent_commit:
210
+ return None, 'the parent has no measured commit'
211
+
212
+ try:
213
+ changed = git('-C', checkout, 'diff', '--name-only', parent_commit,
214
+ commit).split()
215
+ except RuntimeError as error:
216
+ return None, 'git diff against the parent failed: {}'.format(error)
217
+
218
+ if not changed:
219
+ return None, 'nothing changed against the parent'
220
+
221
+ root = os.path.join(checkout, path)
222
+ available = {}
223
+
224
+ for directory, _, names in os.walk(root):
225
+ for name in names:
226
+ if name.startswith('test_') and name.endswith('.py'):
227
+ available.setdefault(name, []).append(os.path.relpath(
228
+ os.path.join(directory, name), checkout))
229
+
230
+ selected = set()
231
+ prefix = path.rstrip('/') + '/'
232
+
233
+ for name in changed:
234
+ base = os.path.basename(name)
235
+
236
+ if name.startswith(prefix) and base.startswith('test_') \
237
+ and base.endswith('.py'):
238
+ selected.add(name)
239
+ elif (not name.endswith('.py') or base == '__init__.py'
240
+ or name.startswith(prefix)):
241
+ return None, '{} maps to no single test file'.format(name)
242
+ elif 'test_' + base in available:
243
+ selected.update(available['test_' + base])
244
+ else:
245
+ return None, 'no test_{} under {}'.format(base, path)
246
+
247
+ return sorted(selected), 'the tests for {}'.format(', '.join(changed))
248
+
249
+
250
+ def untracked(checkout):
251
+ """The worktree's untracked files git does not ignore, or None when it is
252
+ not a git worktree."""
253
+
254
+ done = subprocess.run(['git', '-C', checkout, 'ls-files', '--others',
255
+ '--exclude-standard', '-z'], capture_output=True, text=True)
256
+
257
+ if done.returncode != 0:
258
+ return None
259
+
260
+ return set(name for name in done.stdout.split('\0') if name)
261
+
262
+
263
+ def remove_created(checkout, before):
264
+ """Remove the untracked files that appeared since `before` (a snapshot
265
+ from `untracked`), and the directories that leaves empty. Returns their
266
+ paths, relative to `checkout`."""
267
+
268
+ after = untracked(checkout)
269
+
270
+ if before is None or after is None:
271
+ return []
272
+
273
+ created = sorted(after - before)
274
+
275
+ for name in created:
276
+ path = os.path.join(checkout, name)
277
+
278
+ try:
279
+ os.remove(path)
280
+ except OSError:
281
+ continue
282
+
283
+ folder = os.path.dirname(path)
284
+
285
+ while os.path.abspath(folder) != os.path.abspath(checkout):
286
+ try:
287
+ os.rmdir(folder)
288
+ except OSError:
289
+ break
290
+ folder = os.path.dirname(folder)
291
+
292
+ return created
293
+
294
+
295
+ def run_tests(config, iteration, checkout, commit, rerun, parent_commit=None,
296
+ full=False):
297
+ """The package's own test suite, once per iteration, as a gate.
298
+
299
+ Once and not per run: the suite checks the code, which is the same for
300
+ every seed. It runs in the worktree, so it tests this iteration's code.
301
+ The verdict is kept in `unit-tests/result.json` beside the commit it
302
+ tested, and a resumed iteration whose commit has not moved reuses it.
303
+
304
+ With `{selected}` in the command, only the test files for the changed
305
+ modules run (`select_tests`); `full=True` runs the whole suite, which an
306
+ iteration whose median passes the keep rule gets before it can be
307
+ promoted.
308
+ """
309
+
310
+ tests = config['tests']
311
+ directory = os.path.join(iteration, 'unit-tests')
312
+ record_path = os.path.join(directory, 'result.json')
313
+
314
+ earlier = 0.0
315
+
316
+ record = None
317
+
318
+ if os.path.exists(record_path):
319
+ try:
320
+ with open(record_path) as infile:
321
+ record = json.load(infile)
322
+ except ValueError as error:
323
+ # Only a cache of the verdict: running the tests again rebuilds
324
+ # it, which is better than refusing the iteration.
325
+ print(' unit tests: {} is not valid JSON ({}); running them '
326
+ 'again'.format(record_path, error))
327
+
328
+ if record is not None:
329
+ # A full pass after a subset pass on the same code: both are time the
330
+ # iteration spent on tests, and the dashboard's breakdown counts both.
331
+ if record.get('commit') == commit:
332
+ earlier = record.get('seconds_total', record.get('seconds') or 0.0)
333
+
334
+ if not rerun and record.get('commit') == commit and (not full
335
+ or record.get('scope', 'full') == 'full'):
336
+ print(' unit tests: {} (already run on {}, {})'.format(
337
+ 'pass' if record['pass'] else 'FAIL', commit[:10],
338
+ record.get('scope', 'full')))
339
+ return record
340
+
341
+ selected, reason = ((None, 'the full suite was asked for') if full
342
+ else select_tests(config, checkout, parent_commit, commit))
343
+ scope = 'full' if selected is None else 'subset'
344
+ arguments = [tests.get('path') or 'tests'] if selected is None \
345
+ else selected
346
+
347
+ os.makedirs(directory, exist_ok=True)
348
+ line = autoopt.fill(tests['command'], src=checkout, iteration=iteration,
349
+ out=directory, cache=cache_dir(iteration, commit), selected=arguments)
350
+
351
+ print(' unit tests: running {} ({})…'.format(
352
+ 'the full suite' if scope == 'full' else ' '.join(arguments), reason),
353
+ flush=True)
354
+ start = time.time()
355
+
356
+ before = untracked(checkout)
357
+
358
+ with open(os.path.join(directory, 'log.txt'), 'w') as log:
359
+ log.write('$ {}\n\n'.format(line))
360
+ log.flush()
361
+
362
+ code, timed_out = autoopt.run_shell(line, checkout, log,
363
+ timeout=tests.get('timeout_seconds'))
364
+
365
+ if timed_out:
366
+ log.write('\n[killed after {}s]\n'.format(
367
+ tests['timeout_seconds']))
368
+
369
+ # Files the test run wrote into the worktree are not the
370
+ # iteration's change: left there, the next commit takes them in.
371
+ created = remove_created(checkout, before)
372
+
373
+ if created:
374
+ log.write('\n[removed {} file(s) the tests created in the '
375
+ 'worktree: {}]\n'.format(len(created), ', '.join(created)))
376
+
377
+ record = {'command': line, 'exit_code': code, 'pass': code == 0,
378
+ 'scope': scope, 'selected': selected, 'reason': reason,
379
+ 'seconds': time.time() - start, 'commit': commit,
380
+ 'log': os.path.relpath(os.path.join(directory, 'log.txt'), iteration),
381
+ 'removed': created}
382
+
383
+ record['seconds_total'] = record['seconds'] + earlier
384
+ autoopt.record_artifacts(os.path.dirname(os.path.dirname(os.path.abspath(
385
+ iteration))), created)
386
+
387
+ autoopt.write_json(record_path, record)
388
+
389
+ print(' unit tests: {} {} (exit {}, {:.0f} s; {})'.format(
390
+ 'pass' if record['pass'] else 'FAIL', scope, code, record['seconds'],
391
+ record['log']), flush=True)
392
+
393
+ return record
394
+
395
+
396
+ def measured_commit(run_dir):
397
+ """The commit a stored run measured, or None when the run directory has
398
+ no `commit` file."""
399
+
400
+ try:
401
+ with open(os.path.join(run_dir, 'commit')) as infile:
402
+ return infile.read().strip() or None
403
+ except OSError:
404
+ return None
405
+
406
+
407
+ def start_load(run_dir, name='load'):
408
+ """A number a stored run recorded when it started, or None: `idle`, the
409
+ percent of the CPUs idle just before it (/proc/stat); `load`, the
410
+ one-minute load average, which runs recorded before `idle` existed."""
411
+
412
+ try:
413
+ with open(os.path.join(run_dir, name)) as infile:
414
+ return float(infile.read().strip())
415
+ except (OSError, ValueError):
416
+ return None
417
+
418
+
419
+ def reusable(run_dir, config, commit):
420
+ """A stored run's record, if it measured this commit; otherwise None.
421
+
422
+ Without the commit check, code committed after the measurement would take
423
+ over the stored numbers on the next plain re-run and be recorded as
424
+ measured.
425
+ """
426
+
427
+ record = load_metrics(run_dir, config)[0]
428
+
429
+ if record is None:
430
+ return None
431
+
432
+ stored = measured_commit(run_dir)
433
+
434
+ if stored not in (None, commit):
435
+ return None
436
+
437
+ record['idle'] = start_load(run_dir, 'idle')
438
+ record['load'] = start_load(run_dir)
439
+
440
+ return record
441
+
442
+
443
+ def spread(values):
444
+ """Sample standard deviation, or 0.0 when there are too few values."""
445
+
446
+ values = [v for v in values if v is not None]
447
+
448
+ return statistics.stdev(values) if len(values) > 1 else 0.0
449
+
450
+
451
+ def worst_of(values, op, threshold):
452
+ """The value that comes closest to breaking the gate, or breaks it most."""
453
+
454
+ if not values:
455
+ return None
456
+ if op == '<=':
457
+ return max(values)
458
+ if op == '>=':
459
+ return min(values)
460
+
461
+ return max(values, key=lambda value: abs(value - threshold))
462
+
463
+
464
+ def aggregate(root, config, meta, records, failures, stage, frontier_value,
465
+ band, tests=None):
466
+ """Everything the orchestrator and the dashboard read: `result.json`."""
467
+
468
+ objective = config['objective']
469
+ values = [record['objective'] for record in records]
470
+
471
+ gates = {}
472
+ for gate in config['gates']:
473
+ gate_values = [record['gates'][gate['name']] for record in records]
474
+ test = OPS[gate['op']]
475
+ passes = [test(value, gate['threshold'], gate.get('tol'))
476
+ for value in gate_values]
477
+
478
+ gates[gate['name']] = {
479
+ 'op': gate['op'],
480
+ 'threshold': gate['threshold'],
481
+ 'tol': gate.get('tol'),
482
+ 'values': gate_values,
483
+ 'median': statistics.median(gate_values) if gate_values else None,
484
+ 'worst': worst_of(gate_values, gate['op'], gate['threshold']),
485
+ 'pass': bool(gate_values) and all(passes),
486
+ 'n_violations': sum(1 for ok in passes if not ok),
487
+ }
488
+
489
+ observers = {}
490
+ for observer in config['observers']:
491
+ seen = [record['observers'].get(observer['name'])
492
+ for record in records]
493
+ seen = [value for value in seen if value is not None]
494
+
495
+ observers[observer['name']] = {
496
+ 'values': seen,
497
+ 'median': statistics.median(seen) if seen else None,
498
+ 'std': spread(seen),
499
+ }
500
+
501
+ if failures or not records:
502
+ state = 'error'
503
+ elif not all(gate['pass'] for gate in gates.values()):
504
+ state = 'gate-failed'
505
+ elif config.get('tests') and not (tests or {}).get('pass'):
506
+ # A suite that failed, or never ran, is not a pass.
507
+ state = 'gate-failed'
508
+ elif len(records) < config['runs_per_iteration'] and not meta.get('split'):
509
+ # Fewer runs than an iteration's count, so this is a smoke test or an
510
+ # interrupted iteration, not a measurement. Keeping it out of `ok`
511
+ # keeps it off the frontier, where one lucky seed would be what every
512
+ # later iteration is compared with.
513
+ state = 'partial'
514
+ else:
515
+ state = 'ok'
516
+
517
+ best = (max(records, key=lambda r: r['objective'])
518
+ if objective['direction'] == 'max' and records
519
+ else min(records, key=lambda r: r['objective']) if records else None)
520
+
521
+ return {
522
+ 'schema_version': autoopt.SCHEMA_VERSION,
523
+ 'id': meta['id'],
524
+ 'parent': meta.get('parent'),
525
+ 'prediction': meta.get('prediction'),
526
+ 'round': meta.get('round'),
527
+ 'branch': meta.get('branch'),
528
+ 'title': meta.get('title'),
529
+ 'category': meta.get('category'),
530
+ 'topic': meta.get('topic', ''),
531
+ 'commit': meta.get('commit'),
532
+ # A same-code control is never on the frontier (autoopt.frontier).
533
+ 'control': bool(meta.get('control')),
534
+ # A checked-only iteration (`meta.split`), one run: never on the frontier either.
535
+ 'split': bool(meta.get('split')),
536
+ 'status': state,
537
+ 'stage': stage,
538
+ 'n_runs': len(records),
539
+ 'n_failed': len(failures),
540
+ 'objective': {
541
+ 'name': objective['name'],
542
+ 'direction': objective['direction'],
543
+ 'unit': objective.get('unit', ''),
544
+ 'median': statistics.median(values) if values else None,
545
+ 'mean': statistics.fmean(values) if values else None,
546
+ 'std': spread(values),
547
+ 'min': min(values) if values else None,
548
+ 'max': max(values) if values else None,
549
+ 'values': values,
550
+ },
551
+ 'gates': gates,
552
+ 'observers': observers,
553
+ 'frontier_at_start': frontier_value,
554
+ 'noise_band': band,
555
+ 'best_run': best['dir'] if best else None,
556
+ 'runs': [{key: record.get(key) for key in ('seed', 'dir', 'objective',
557
+ 'seconds', 'gates', 'observers', 'note', 'idle', 'load')}
558
+ for record in records],
559
+ 'failures': failures,
560
+ 'tests': tests,
561
+ 'seconds': sum(record['seconds'] for record in records),
562
+ 'gpu': os.environ.get('CUDA_VISIBLE_DEVICES'),
563
+ 'finished': autoopt.now(),
564
+ }
565
+
566
+
567
+ def workers_seen(iteration, records, expected):
568
+ """`{expected, busy_peak, procs_peak, samples}` over the runs'
569
+ `workers.json`: the most threads any run had running at once."""
570
+
571
+ seen = {'expected': expected, 'busy_peak': 0, 'procs_peak': 0, 'samples': 0}
572
+
573
+ for record in records:
574
+ path = os.path.join(iteration, record['dir'], 'workers.json')
575
+
576
+ try:
577
+ one = autoopt.read_json(path)
578
+ except (OSError, ValueError):
579
+ continue
580
+
581
+ for key in ('busy_peak', 'procs_peak'):
582
+ seen[key] = max(seen[key], one.get(key, 0))
583
+
584
+ seen['samples'] += one.get('samples', 0)
585
+
586
+ return seen
587
+
588
+
589
+ def commit_worktree(iteration, meta):
590
+ """Commit the idea, so the branch carries the change and nothing else.
591
+
592
+ A subagent that forgot to commit would otherwise leave the diff to be
593
+ reconstructed from a directory that the next reader has no reason to
594
+ trust.
595
+ """
596
+
597
+ skip = []
598
+ root = os.path.dirname(os.path.dirname(os.path.abspath(os.path.dirname(
599
+ iteration) if os.path.basename(iteration) == 'src' else iteration)))
600
+ known = autoopt.test_artifacts(root) if os.path.isdir(os.path.join(root,
601
+ 'iterations')) else set()
602
+ left = sorted(name for name in untracked(iteration) or () if name in
603
+ known)
604
+
605
+ if left:
606
+ print(' commit: leaving out {} file(s) the unit tests create: {}'
607
+ .format(len(left), ', '.join(left[:5])))
608
+ skip += [':(exclude){}'.format(name) for name in left]
609
+
610
+ skip += [':(exclude){}'.format(name) for name in autoopt.RUNNER_FILES if
611
+ os.path.exists(os.path.join(iteration, name)) and subprocess.run(['git',
612
+ '-C', iteration, 'check-ignore', '-q', name], capture_output=True)
613
+ .returncode != 0]
614
+ spec = ['--', '.'] + skip
615
+
616
+ dirty = git('-C', iteration, 'status', '--porcelain', *spec).strip()
617
+
618
+ if not dirty:
619
+ return git('-C', iteration, 'rev-parse', 'HEAD').strip()
620
+
621
+ git('-C', iteration, 'add', '-A', *spec)
622
+ name = '{}{}'.format(autoopt.LABEL_LETTER, meta['id'])
623
+
624
+ # A machine with no git identity would refuse the commit, and with it
625
+ # the whole iteration. Only a missing name or email is filled, so a
626
+ # configured identity is never overridden.
627
+ identity = []
628
+
629
+ for key, value in (('user.name', 'auto-optimize'),
630
+ ('user.email', 'auto-optimize@localhost')):
631
+ if not subprocess.run(['git', '-C', iteration, 'config', key],
632
+ capture_output=True, text=True).stdout.strip():
633
+ identity += ['-c', '{}={}'.format(key, value)]
634
+
635
+ git('-C', iteration, *identity, 'commit', '-q', '-m', '{}: {}'.format(
636
+ name, meta.get('title') or 'iteration {}'.format(name)))
637
+
638
+ return git('-C', iteration, 'rev-parse', 'HEAD').strip()
639
+
640
+
641
+ def decide(config, median, frontier_value, band):
642
+ """A staged search: is this iteration close enough to the frontier to
643
+ confirm?
644
+
645
+ Close enough means "within one seed-noise band", not "better": a real
646
+ improvement read through three seeds lands below the frontier often
647
+ enough that a strict test throws most of them away. The band is the wider
648
+ of the reference spread (the root's, as measured when the phase opened)
649
+ and this iteration's.
650
+ """
651
+
652
+ if frontier_value is None or median is None:
653
+ return True, 'no frontier yet'
654
+
655
+ if config['objective']['direction'] == 'max':
656
+ promote = median >= frontier_value - band
657
+ else:
658
+ promote = median <= frontier_value + band
659
+
660
+ return promote, '{} vs frontier {} ± band {}'.format(fmt(median),
661
+ fmt(frontier_value), fmt(band))
662
+
663
+
664
+ def run_rows(result, config, parent, parent_label):
665
+ """One line per run: its objective and each observer, the parent's run
666
+ of the same seed in brackets, any gate the run broke, and how idle the
667
+ CPUs were when it started (this search's own runs included; the load
668
+ average for a run recorded before that). What a subagent otherwise reads
669
+ out of every `metrics.json`."""
670
+
671
+ theirs = {run.get('seed'): run for run in (parent or {}).get('runs') or []}
672
+ rows = []
673
+
674
+ for run in result.get('runs') or []:
675
+ other = theirs.get(run['seed']) or {}
676
+ parts = ['{}{}'.format(fmt(run['objective']), ' ({} {})'.format(
677
+ parent_label, fmt(other['objective']))
678
+ if other.get('objective') is not None else '')]
679
+
680
+ for name, value in (run.get('observers') or {}).items():
681
+ before = (other.get('observers') or {}).get(name)
682
+ parts.append('{} {}{}'.format(name, fmt(value), ' ({})'.format(
683
+ fmt(before)) if before is not None else ''))
684
+
685
+ for gate in config['gates']:
686
+ value = (run.get('gates') or {}).get(gate['name'])
687
+ if value is not None and not OPS[gate['op']](value,
688
+ gate['threshold'], gate.get('tol')):
689
+ parts.append('{} {} BROKEN'.format(gate['name'], fmt(value)))
690
+
691
+ if run.get('idle') is not None:
692
+ parts.append('idle {:.0f}%'.format(run['idle']))
693
+ elif run.get('load') is not None:
694
+ parts.append('load {:.1f}'.format(run['load']))
695
+
696
+ rows.append((run, ' '.join(parts)))
697
+
698
+ return rows
699
+
700
+
701
+ def report(result, config, reason, parent=None, parent_label=None):
702
+ """The block the subagent pastes back to the orchestrator. `parent` is
703
+ the parent's result: the keep rule's reference, beside which the median
704
+ and each observer are given."""
705
+
706
+ objective = result['objective']
707
+ before = parent if (parent or {}).get('objective') else None
708
+
709
+ # One label column, wide enough for the longest gate or observer name:
710
+ # the orchestrator reads these side by side across iterations.
711
+ labels = ([objective['name'], 'status', 'frontier', 'best so far',
712
+ 'parent', 'wall clock',
713
+ 'unit tests']
714
+ + ['gate ' + name for name in result['gates']]
715
+ + ['obs ' + name for name in result['observers']]
716
+ + ['run {}'.format(run['seed']) for run in result.get('runs') or []])
717
+ width = max(len(label) for label in labels) + 2
718
+
719
+ def row(label, text):
720
+ return '{}{}'.format(label.ljust(width), text)
721
+
722
+ lines = ['', 'iteration {}{} {} [{}]'.format(
723
+ autoopt.LABEL_LETTER, result['id'],
724
+ result.get('title'), result.get('category')),
725
+ row('status', '{} ({}{} run{})'.format(result['status'],
726
+ result['stage'] + ', ' if config.get('staged') else '',
727
+ result['n_runs'],
728
+ '' if result['n_runs'] == 1 else 's')),
729
+ row(objective['name'], '{} median, {} ± {} (min {}, max {})'.format(
730
+ fmt(objective['median']), fmt(objective['mean']),
731
+ fmt(objective['std'], 3), fmt(objective['min']),
732
+ fmt(objective['max']))),
733
+ row('best so far', '{} at start{}; {}'.format(
734
+ fmt(result['frontier_at_start']), ', held by {}, not in the '
735
+ 'root'.format(result['frontier_holder'])
736
+ if result.get('frontier_holder') is not None and not result.get(
737
+ 'frontier_on_path', True) else '', reason))]
738
+
739
+ if before is not None:
740
+ lines.append(row('parent', '{} {} median, what the keep rule judges '
741
+ 'against'.format(parent_label, fmt(before['objective']['median']))))
742
+
743
+ for name, gate in result['gates'].items():
744
+ lines.append(row('gate ' + name, '{} {} {} worst {}{}'.format(
745
+ 'PASS' if gate['pass'] else 'FAIL', gate['op'],
746
+ fmt(gate['threshold']), fmt(gate['worst']),
747
+ '' if gate['pass'] else ' ({} run(s) broke it)'.format(
748
+ gate['n_violations']))))
749
+
750
+ for name, observer in result['observers'].items():
751
+ theirs = ((before or {}).get('observers') or {}).get(name) or {}
752
+ lines.append(row('obs ' + name, '{} median{}'.format(
753
+ fmt(observer['median']), ' ({} {})'.format(parent_label,
754
+ fmt(theirs['median'])) if theirs.get('median') is not None
755
+ else '')))
756
+
757
+ lines += [row('run {}'.format(run['seed']), text)
758
+ for run, text in run_rows(result, config, before, parent_label)]
759
+
760
+ if result.get('tests'):
761
+ tests = result['tests']
762
+ lines.append(row('unit tests', '{} {} (exit {}; {})'.format(
763
+ 'PASS' if tests['pass'] else 'FAIL', tests.get('scope', 'full'),
764
+ tests['exit_code'], tests['log'])))
765
+
766
+ if result['failures']:
767
+ lines.append(row('failures', '; '.join(
768
+ 'seed {}: {}'.format(failure['seed'], failure['error'])
769
+ for failure in result['failures'])))
770
+
771
+ lines.append(row('wall clock', '{:.1f} min over {} run(s)'.format(
772
+ result['seconds'] / 60.0, result['n_runs'])))
773
+
774
+ return '\n'.join(lines)
775
+
776
+
777
+ def promote_on_keep(root, config, meta, result, no_promote=False):
778
+ """With `promote: auto`, promote an iteration that passes
779
+ the keep rule while its parent is still the root, then run the approved
780
+ external validation of the round that closed. Returns the report's
781
+ lines."""
782
+
783
+ keep = result.get('keep')
784
+
785
+ if not keep:
786
+ return []
787
+ if keep['verdict'] != 'pass':
788
+ return ['keep: no, ' + keep['why']]
789
+ if no_promote:
790
+ return ['keep: passes ({}); not promoted (--no-promote)'.format(
791
+ keep['why'])]
792
+ if config.get('promote', 'orchestrator') != 'auto':
793
+ return ['keep: passes ({}); promotion is the orchestrator\'s '
794
+ '(config "promote")'.format(keep['why'])]
795
+ if meta.get('after_end'):
796
+ return ['keep: passes ({}); not promoted: an iteration made after the '
797
+ 'end becomes the winner only by `promote --id`, on the user\'s '
798
+ 'word (references/step4-final.md)'.format(keep['why'])]
799
+
800
+ head = autoopt.load_state(root)['root']
801
+
802
+ if meta['id'] in autoopt.lineage(root, head):
803
+ return ['keep: passes; already on the root\'s path']
804
+
805
+ done = subprocess.run([sys.executable, os.path.join(HERE, 'autoopt.py'),
806
+ 'promote', root, '--id', str(meta['id'])], capture_output=True,
807
+ text=True)
808
+
809
+ if done.returncode != 0:
810
+ message = (done.stderr or done.stdout).strip().splitlines()[-1:]
811
+ message = message[0] if message else 'exit {}'.format(done.returncode)
812
+ keep['promoted'] = False
813
+ autoopt.write_json(os.path.join(autoopt.iteration_dir(root,
814
+ meta['id']), 'result.json'), result)
815
+ return ['keep: passes ({}); not promoted: {}'.format(keep['why'],
816
+ message.replace('error: ', ''))]
817
+
818
+ keep['promoted'] = True
819
+ keep['round_closed'] = autoopt.load_state(root)['round'] - 1
820
+ lines = ['keep: promoted to the root ({}); round {} '
821
+ 'closed'.format(keep['why'], keep['round_closed'])]
822
+ # promote profiled the new root (checks.profile) and recorded its time.
823
+ lines += [line for line in done.stdout.splitlines()
824
+ if line.startswith('profile: ')]
825
+ seconds = (autoopt.load_result(root, meta['id']) or {}).get(
826
+ 'profile_seconds')
827
+ if seconds is not None:
828
+ result['profile_seconds'] = seconds
829
+ validation = config.get('external_validation') or {}
830
+
831
+ if validation.get('command') and validation.get('approved'):
832
+ ran = subprocess.run([sys.executable, os.path.join(HERE, 'autoopt.py'),
833
+ 'validate', root, '--round', str(keep['round_closed'])],
834
+ capture_output=True, text=True)
835
+ record = autoopt.load_validation(root, keep['round_closed']) or {}
836
+ keep['validation'] = {'round': keep['round_closed'],
837
+ 'ok': record.get('ok'), 'exit': ran.returncode}
838
+ lines.append('validation, round {}: {}{}'.format(keep['round_closed'],
839
+ 'ok' if record.get('ok') else 'NEEDS ATTENTION',
840
+ ' ({})'.format(', '.join('{} {}'.format(key, fmt(value))
841
+ for key, value in (record.get('measures') or {}).items()))
842
+ if record.get('measures') else ''))
843
+ elif validation.get('command'):
844
+ lines.append('validation: not run, the user has not approved it')
845
+
846
+ autoopt.write_json(os.path.join(autoopt.iteration_dir(root, meta['id']),
847
+ 'result.json'), result)
848
+ return lines
849
+
850
+
851
+ def main(argv=None):
852
+ parser = argparse.ArgumentParser(description=__doc__,
853
+ formatter_class=argparse.RawDescriptionHelpFormatter)
854
+
855
+ parser.add_argument('iteration', help='autooptimize/iterations/<id>')
856
+ parser.add_argument('--runs', type=int, help='override '
857
+ 'runs_per_iteration from config.json')
858
+ parser.add_argument('--confirm-runs', type=int, help='a search made with '
859
+ 'init --staged: override confirm_runs from config.json')
860
+ parser.add_argument('--stage', choices=('screen', 'confirm', 'all'),
861
+ default='all', help='a search made with init --staged: screen stops '
862
+ 'after the screening runs; confirm goes straight to the full '
863
+ 'count; all screens, then confirms if the median earns it '
864
+ '(default)')
865
+ parser.add_argument('--rerun', action='store_true',
866
+ help='re-run seeds that already have a metrics.json')
867
+ parser.add_argument('--no-promote', action='store_true',
868
+ help='never promote, whatever config "promote" says, and run no '
869
+ 'external validation')
870
+ parser.add_argument('--full-tests', action='store_true',
871
+ help='run the whole unit-test suite rather than the files for the '
872
+ 'changed modules; what promote needs, and what the runner gives '
873
+ 'an iteration whose median passes the keep rule itself')
874
+ parser.add_argument('--dry-run', action='store_true',
875
+ help='print the runs that would happen, and stop')
876
+ parser.add_argument('--background', action='store_true',
877
+ help='start this call detached, writing <iteration>/probe/runner.log '
878
+ '(ending `exit <code>`), and return; watch it with autoopt.py wait')
879
+
880
+ args = parser.parse_args(argv)
881
+
882
+ iteration = os.path.abspath(os.path.expanduser(args.iteration))
883
+
884
+ if not os.path.isdir(iteration):
885
+ fail('not a directory: {}'.format(iteration))
886
+
887
+ if args.background:
888
+ return autoopt.detach(os.path.abspath(__file__), sys.argv[1:],
889
+ os.path.join(iteration, 'probe', 'runner.log'))
890
+
891
+ root = os.path.dirname(os.path.dirname(iteration))
892
+ root = autoopt.resolve(root)
893
+ config = autoopt.load_config(root)
894
+
895
+ problem = autoopt.harness_problem(root)
896
+
897
+ if problem:
898
+ fail(problem)
899
+
900
+ meta = autoopt.load_meta(root, os.path.basename(iteration))
901
+
902
+ if meta is None:
903
+ fail('{} has no meta.json; make the iteration with `autoopt.py new` '
904
+ 'rather than by hand'.format(iteration))
905
+
906
+ screen = args.runs or config['runs_per_iteration']
907
+ confirm = args.confirm_runs or config['confirm_runs']
908
+ staged = config['staged'] and args.stage != 'screen'
909
+
910
+ # One count of runs: every iteration runs it, and it is the depth.
911
+ if not config['staged']:
912
+ if args.confirm_runs or args.stage == 'confirm':
913
+ fail('--confirm-runs and --stage confirm are for a staged search; '
914
+ 'this one runs runs_per_iteration ({}) on every iteration'
915
+ .format(config['runs_per_iteration']))
916
+ confirm = config['runs_per_iteration']
917
+
918
+ # A staged search measures the baseline, which sets the frontier and the
919
+ # noise band, at the full count, unless the caller asked for a count: a
920
+ # smoke run on the baseline stays one run.
921
+ if (meta['id'] == 0 and config['staged'] and args.runs is None
922
+ and args.stage == 'all'):
923
+ screen = confirm
924
+
925
+ if args.stage == 'confirm':
926
+ screen = confirm
927
+
928
+ # A checked-only iteration (`meta.split`) is not measured: one run for
929
+ # the gates and the tests, since several runs would cost a slow base's
930
+ # time several times over.
931
+ earlier = autoopt.load_result(root, meta['id']) or {}
932
+
933
+ if meta.get('split') and args.runs is None and earlier.get('n_runs', 0) \
934
+ <= 1:
935
+ screen = confirm = 1
936
+ staged = False
937
+
938
+ if args.dry_run:
939
+ print('would run seeds {} in {}'.format(
940
+ list(range(config['seed_base'], config['seed_base'] + screen)),
941
+ iteration))
942
+ return 0
943
+
944
+ autoopt.require_spec(root, 'run {}'.format(autoopt.label(root, meta['id'])))
945
+
946
+ # A pruned iteration keeps its record but not its checkout, so the code
947
+ # this would run is in the branch and not on disk.
948
+ checkout = autoopt.checkout_dir(root, meta['id'], config)
949
+
950
+ if not os.path.exists(os.path.join(checkout, '.git')):
951
+ fail('{} has no git checkout: it was pruned, or made by hand. '
952
+ 'Restore it with:\n\n python3 {} restore {} --id {}\n'.format(
953
+ checkout, os.path.join(HERE, 'autoopt.py'), root,
954
+ meta['id']))
955
+
956
+ meta['commit'] = commit_worktree(checkout, meta)
957
+ autoopt.write_meta(root, meta['id'], meta)
958
+
959
+ # A compare reads A0's cached outputs: cache them before any run is
960
+ # spent, when they are missing or the gates or the checks changed.
961
+ if (config.get('checks') or {}).get('compare'):
962
+ autoopt.ensure_reference(root, config)
963
+
964
+ everything = autoopt.all_results(root)
965
+ results = [r for r in everything if r.get('id') != meta['id']]
966
+ direction = config['objective']['direction']
967
+
968
+ state = autoopt.load_state(root)
969
+ frontier_value, frontier_id = autoopt.search_frontier(
970
+ root, results, direction)
971
+
972
+ # Whether this iteration's earlier result already held the frontier. A
973
+ # re-run of it (to add --full-tests, say) is compared above against the
974
+ # runner-up, and must not announce that as a new frontier.
975
+ held = autoopt.search_frontier(root, everything, direction)[1] \
976
+ == meta['id']
977
+
978
+ # The band's reference spread is the root's, re-measured when each phase
979
+ # opens (`autoopt.py loop`): after a tenfold speedup the baseline's
980
+ # spread is far wider than the noise at the new scale.
981
+ baseline_spread = autoopt.band_spread(root, state)
982
+
983
+ # Runs already on disk from an earlier attempt, counted so a re-run
984
+ # reports every run it has. A staged search would otherwise re-take its
985
+ # decision against a frontier that has since moved, stop at the
986
+ # screening count, and rewrite result.json with fewer runs than were
987
+ # measured.
988
+ already = 0
989
+
990
+ if not args.rerun:
991
+ for index in range(confirm):
992
+ run_dir = os.path.join(iteration, 'runs',
993
+ 'seed-{}'.format(config['seed_base'] + index))
994
+
995
+ if reusable(run_dir, config, meta['commit']) is None:
996
+ break
997
+
998
+ already = index + 1
999
+
1000
+ # Only when a run could actually happen. Re-aggregating an iteration
1001
+ # whose seeds are all on disk needs no GPU, and demanding a lease for it
1002
+ # means queueing behind other GPU jobs to re-read a directory.
1003
+ if already < confirm:
1004
+ check_lease(config)
1005
+
1006
+ # The baseline sets the frontier and the noise band: measured beside
1007
+ # another job, it makes every later iteration look like a win once that
1008
+ # job ends. This never refuses: whether to measure a CPU benchmark under
1009
+ # load is the user's call, asked before this runs (`autoopt.py busy`);
1010
+ # what was busy is recorded.
1011
+ busy_at_start = []
1012
+ if (meta['id'] == 0 and already < confirm and not config.get('gpu', True)
1013
+ and not os.environ.get('AUTOOPT_SKIP_QUIET_CHECK')):
1014
+ busy_at_start = [{'pid': pid, 'user': user, 'percent': round(percent),
1015
+ 'command': command} for pid, user, percent, command in
1016
+ autoopt.busy_processes(root)]
1017
+ if busy_at_start:
1018
+ print(' the machine is busy: {}. The baseline is measured under '
1019
+ 'this load: say so in A0\'s README and the ledger '
1020
+ '(references/step2-baseline.md, *Check the machine is quiet*)'
1021
+ .format(autoopt.busy_words(busy_at_start[:8])), flush=True)
1022
+
1023
+ records, failures = [], []
1024
+ stage = 'screen'
1025
+ promoted = False
1026
+ reason = ('the baseline: the frontier and the noise band start here'
1027
+ if meta['id'] == 0 else 'not evaluated')
1028
+
1029
+ if already > screen:
1030
+ stage = 'confirmed' if already >= confirm else 'screen'
1031
+ reason = 're-run of {} run(s) already on disk'.format(already)
1032
+
1033
+ print('iteration {} ({}), frontier {} = {} from iteration {}'.format(
1034
+ autoopt.label(root, meta['id']), meta.get('title'),
1035
+ config['objective']['name'], fmt(frontier_value),
1036
+ autoopt.label(root, frontier_id)))
1037
+
1038
+ devices = leased_devices(config, config.get('gpus_per_agent', 1) or 1)
1039
+
1040
+ # How idle the CPUs were before each run, over the time since the one
1041
+ # before it (at least RUN_IDLE_SAMPLE seconds), from /proc/stat.
1042
+ sampler = autoopt.CpuSampler()
1043
+
1044
+ # A run takes a device off the queue and gives it back when it ends, so
1045
+ # each GPU holds one run at a time, even when runs finish out of turn.
1046
+ free = queue.Queue()
1047
+ for device in devices:
1048
+ free.put(device)
1049
+
1050
+ def one(seed):
1051
+ """Run or recover a single seed. Returns a record, or None."""
1052
+
1053
+ run_dir = os.path.join(iteration, 'runs', 'seed-{}'.format(seed))
1054
+ record = reusable(run_dir, config, meta['commit'])
1055
+
1056
+ if record is not None and not args.rerun:
1057
+ record.update(seed=seed, dir=os.path.relpath(run_dir, iteration),
1058
+ seconds=record.get('seconds', 0.0))
1059
+ return record, None, ' seed {}: already done, {} = {}'.format(
1060
+ seed, config['objective']['name'], fmt(record['objective']))
1061
+
1062
+ if os.path.isdir(run_dir):
1063
+ # --rerun, or a run of an older commit: its numbers are not this
1064
+ # code's.
1065
+ shutil.rmtree(run_dir)
1066
+
1067
+ device = free.get()
1068
+ machine = sampler.sample(RUN_IDLE_SAMPLE)
1069
+ idle = machine['idle_pct'] if machine else None
1070
+
1071
+ try:
1072
+ code, seconds = execute(config['command'], iteration, seed,
1073
+ run_dir, config.get('timeout_seconds'), device, checkout,
1074
+ cache_dir(iteration, meta['commit']), bool(config.get('workers')))
1075
+ finally:
1076
+ free.put(device)
1077
+
1078
+ record, error = load_metrics(run_dir, config)
1079
+
1080
+ if code != 0 or record is None:
1081
+ message = (error or 'exit code {}'.format(code)) if record is None \
1082
+ else 'exit code {}'.format(code)
1083
+
1084
+ return None, {'seed': seed, 'error': message,
1085
+ 'dir': os.path.relpath(run_dir, iteration),
1086
+ 'seconds': seconds}, \
1087
+ ' seed {}: FAILED -- {} (see {}/log.txt)'.format(seed,
1088
+ message, os.path.relpath(run_dir, iteration))
1089
+
1090
+ with open(os.path.join(run_dir, 'commit'), 'w') as out:
1091
+ out.write(meta['commit'] + '\n')
1092
+
1093
+ if idle is not None:
1094
+ with open(os.path.join(run_dir, 'idle'), 'w') as out:
1095
+ out.write('{:.1f}\n'.format(idle))
1096
+
1097
+ record.update(seed=seed, dir=os.path.relpath(run_dir, iteration),
1098
+ seconds=seconds, idle=idle, load=None)
1099
+
1100
+ return record, None, ' seed {}: {} = {} in {:.1f} min'.format(seed,
1101
+ config['objective']['name'], fmt(record['objective']),
1102
+ seconds / 60.0)
1103
+
1104
+ def passes(record):
1105
+ return all(OPS[gate['op']](record['gates'][gate['name']],
1106
+ gate['threshold'], gate.get('tol')) for gate in config['gates'])
1107
+
1108
+ def batch(first_index, last_index):
1109
+ """Run a contiguous block of seeds, len(devices) at a time. One at a
1110
+ time, the block stops at the first run that fails or breaks a gate:
1111
+ the iteration's verdict is settled, and the rest would measure
1112
+ nothing."""
1113
+
1114
+ seeds = [config['seed_base'] + index
1115
+ for index in range(first_index, last_index)]
1116
+
1117
+ if not seeds:
1118
+ return
1119
+
1120
+ if len(devices) == 1:
1121
+ # Serial, and printed as each finishes.
1122
+ for seed in seeds:
1123
+ print(' seed {}: running…'.format(seed), flush=True)
1124
+ record, failure, line = one(seed)
1125
+ print(line, flush=True)
1126
+
1127
+ if record is not None:
1128
+ records.append(record)
1129
+ elif failure is not None:
1130
+ failures.append(failure)
1131
+
1132
+ if failure is not None or (record is not None
1133
+ and not passes(record)):
1134
+ if seed != seeds[-1]:
1135
+ print(' stopping: seed {} {}'.format(seed, 'failed'
1136
+ if failure is not None else 'broke a gate'),
1137
+ flush=True)
1138
+ return
1139
+
1140
+ return
1141
+
1142
+ print(' seeds {} on {} GPU(s): {}'.format(
1143
+ ', '.join(str(seed) for seed in seeds), len(devices),
1144
+ ', '.join(str(device) for device in devices)), flush=True)
1145
+
1146
+ with concurrent.futures.ThreadPoolExecutor(
1147
+ max_workers=len(devices)) as pool:
1148
+
1149
+ futures = {pool.submit(one, seed): seed for seed in seeds}
1150
+
1151
+ try:
1152
+ for future in concurrent.futures.as_completed(futures):
1153
+ record, failure, line = future.result()
1154
+ print(line, flush=True)
1155
+
1156
+ if record is not None:
1157
+ records.append(record)
1158
+ elif failure is not None:
1159
+ failures.append(failure)
1160
+ except BaseException:
1161
+ # Ctrl-C lands here, in the main thread. The runs are in
1162
+ # sessions of their own and never saw it, and the pool's
1163
+ # exit waits for them: stop them first.
1164
+ for future in futures:
1165
+ future.cancel()
1166
+ autoopt.kill_live()
1167
+ raise
1168
+
1169
+ # Completion order is arbitrary when runs are parallel; the record
1170
+ # is kept in seed order so the median and the per-seed table do not
1171
+ # depend on which GPU finished first.
1172
+ records.sort(key=lambda record: record['seed'])
1173
+ failures.sort(key=lambda failure: failure['seed'])
1174
+
1175
+ # The cold first call, before any timed run: this iteration's code on
1176
+ # empty compiler caches, beside the parent's recorded value, which is
1177
+ # never re-measured. A crash stops the iteration here.
1178
+ cold = None
1179
+
1180
+ if (config.get('checks') or {}).get('first_call') and not meta.get(
1181
+ 'control'):
1182
+ cold = autoopt.measure_cold(root, config, meta['id'], meta['commit'],
1183
+ meta.get('parent'), fresh=args.rerun)
1184
+ print(' ' + autoopt.check_line({'cold': cold}), flush=True)
1185
+
1186
+ cold_ok = cold is None or cold['verdict'] != 'error'
1187
+
1188
+ # One run, then the unit tests and the compare, then the other runs: a
1189
+ # broken edit costs one run, not the whole count.
1190
+ first = max(screen, already)
1191
+ if cold_ok:
1192
+ batch(0, 1)
1193
+
1194
+ def gates_hold():
1195
+ return all(passes(record) for record in records)
1196
+
1197
+ # Each stage runs only when the ones before it passed: a verdict of
1198
+ # `error` or `gate-failed` is settled by the first that fails, and the
1199
+ # rest would spend minutes measuring nothing.
1200
+ def screened():
1201
+ return bool(records) and not failures and gates_hold()
1202
+
1203
+ tests = None
1204
+ checked = None
1205
+
1206
+ parent_commit = (autoopt.load_result(root, meta.get('parent')) or {}).get(
1207
+ 'commit') if meta.get('parent') is not None else None
1208
+
1209
+ # The unit tests and the compare are gates on the code, so each runs
1210
+ # once, after the first run, and the compare only once the tests pass.
1211
+ if config.get('tests') and screened():
1212
+ tests = run_tests(config, iteration, checkout, meta['commit'],
1213
+ args.rerun, parent_commit, full=args.full_tests)
1214
+
1215
+ if ((config.get('checks') or {}).get('compare') and screened()
1216
+ and (tests is None or tests['pass'])):
1217
+ checked = autoopt.check_compare(root, config, meta['id'],
1218
+ meta['commit'], fresh=args.rerun)
1219
+ print(' ' + autoopt.check_line(checked), flush=True)
1220
+
1221
+ compared = checked is None or checked['compare']['verdict'] == 'pass'
1222
+
1223
+ if cold_ok and screened() and (tests is None or tests['pass']) and compared:
1224
+ batch(1, first)
1225
+
1226
+ # A staged search: decide whether confirming is worth its runs.
1227
+ if not cold_ok:
1228
+ reason = 'not run: the cold first call crashed'
1229
+ elif staged and confirm > screen and first == screen:
1230
+ if tests is not None and not tests['pass']:
1231
+ reason = 'not confirmed: the unit tests failed'
1232
+ elif not compared:
1233
+ reason = 'not confirmed: the compare {}'.format(
1234
+ 'found outputs that differ' if checked['compare']['verdict']
1235
+ == 'differ' else 'crashed')
1236
+ elif failures:
1237
+ reason = 'not confirmed: {} run(s) failed'.format(len(failures))
1238
+ elif not records:
1239
+ reason = 'not confirmed: no run produced a number'
1240
+ else:
1241
+ median = statistics.median([r['objective'] for r in records])
1242
+ band = max(baseline_spread, spread(
1243
+ [r['objective'] for r in records]))
1244
+ if not gates_hold():
1245
+ reason = 'not confirmed: a gate is broken'
1246
+ else:
1247
+ promoted, why = decide(config, median, frontier_value, band)
1248
+ reason = ('confirming: ' if promoted else
1249
+ 'not confirmed: ') + why
1250
+
1251
+ if promoted:
1252
+ stage = 'confirmed'
1253
+
1254
+ print(' {}'.format(reason))
1255
+
1256
+ if promoted:
1257
+ batch(screen, confirm)
1258
+
1259
+ band = max(baseline_spread, spread([r['objective'] for r in records]))
1260
+
1261
+ if not staged or confirm <= screen:
1262
+ stage = 'confirmed' if len(records) >= confirm else 'screen'
1263
+ reason = 'noise band {}'.format(fmt(band)) if not config['staged'] \
1264
+ else reason
1265
+
1266
+ # An iteration whose median passes the keep rule is a candidate for the
1267
+ # root, and a subset of the suite is not enough to promote on: run the
1268
+ # rest now, while the lease and the checkout are both here.
1269
+ def keep_candidate():
1270
+ """Whether the median passes the keep rule against the parent: only
1271
+ such an iteration can be promoted, so only it pays for the
1272
+ whole test suite."""
1273
+ if meta.get('control') or meta.get('parent') is None or not records:
1274
+ return False
1275
+ probe = {'status': 'ok', 'stage': stage, 'noise_band': band,
1276
+ 'objective': {'median': statistics.median(
1277
+ [r['objective'] for r in records])}}
1278
+ return autoopt.keep_verdict(config, probe, autoopt.load_result(root,
1279
+ meta['parent']))[0]
1280
+
1281
+ if (tests is not None and tests['pass'] and tests.get('scope') == 'subset'
1282
+ and stage == 'confirmed' and compared and screened()
1283
+ and (args.full_tests or keep_candidate())):
1284
+ tests = run_tests(config, iteration, checkout, meta['commit'],
1285
+ args.rerun, parent_commit, full=True)
1286
+
1287
+ result = aggregate(root, config, meta, records, failures, stage,
1288
+ frontier_value, band, tests)
1289
+ if config.get('workers'):
1290
+ result['workers'] = workers_seen(iteration, records, config['workers'])
1291
+
1292
+ result['frontier_holder'] = (autoopt.label(root, frontier_id)
1293
+ if frontier_id is not None else None)
1294
+ result['frontier_on_path'] = frontier_id is None or frontier_id in \
1295
+ autoopt.known_lineage(root, meta['id'])
1296
+ if busy_at_start:
1297
+ result['busy_at_start'] = busy_at_start
1298
+
1299
+ # The cold first call joins the compare's record. Without a compare (none
1300
+ # configured, or the runs failed first) it is recorded alone, and a
1301
+ # crash, which ran nothing, names it the failed check.
1302
+ if checked is not None and cold is not None:
1303
+ checked = dict(checked, cold=cold)
1304
+ elif cold is not None:
1305
+ result['check'] = {'cold': cold}
1306
+ if not cold_ok:
1307
+ result['failed_check'] = 'cold'
1308
+
1309
+ if checked is not None:
1310
+ autoopt.apply_check(result, checked, config['runs_per_iteration'])
1311
+
1312
+ # The keep rule against the parent, recorded on every settled iteration
1313
+ # so promotion and the status tables read it.
1314
+ if (meta.get('parent') is not None and result['status'] == 'ok'
1315
+ and not meta.get('control') and not meta.get('split')):
1316
+ passes, why = autoopt.keep_verdict(config, result,
1317
+ autoopt.load_result(root, meta['parent']))
1318
+ result['keep'] = {'verdict': 'pass' if passes else 'fail', 'why': why}
1319
+
1320
+ autoopt.write_json(os.path.join(iteration, 'result.json'), result)
1321
+ keep_lines = promote_on_keep(root, config, meta, result,
1322
+ args.no_promote)
1323
+
1324
+ text = report(result, config, reason, autoopt.load_result(root,
1325
+ meta['parent']) if meta.get('parent') is not None else None,
1326
+ autoopt.label(root, meta['parent'])
1327
+ if meta.get('parent') is not None else None)
1328
+ if result.get('busy_at_start'):
1329
+ text += '\nbusy at start: ' + autoopt.busy_words(
1330
+ result['busy_at_start'][:8])
1331
+ if result.get('check'):
1332
+ text += '\n' + autoopt.check_line(result['check'])
1333
+ if keep_lines:
1334
+ text += '\n' + '\n'.join(keep_lines)
1335
+ print(text)
1336
+
1337
+ with open(os.path.join(iteration, 'report.txt'), 'w') as out:
1338
+ out.write(text + '\n')
1339
+
1340
+ # A README assembled from the subagent's notes.md quotes this result's
1341
+ # numbers; re-assemble it so a re-run never leaves it quoting old ones.
1342
+ if os.path.exists(os.path.join(iteration, 'notes.md')):
1343
+ problem = autoopt.write_readme(root, config, meta['id'])
1344
+ if problem:
1345
+ print('note: README.md was not re-assembled: ' + problem)
1346
+
1347
+ leads = result['status'] == 'ok' and autoopt.better(
1348
+ result['objective']['median'], frontier_value, direction)
1349
+
1350
+ if meta.get('control'):
1351
+ # Unchanged code: the difference is the machine's, never a frontier.
1352
+ median = result['objective']['median']
1353
+ if median is not None and frontier_value:
1354
+ print('\ncontrol: unchanged code reads {} against the frontier\'s '
1355
+ '{} ({:+.1%}), noise band {}; a control never holds the '
1356
+ 'frontier'.format(fmt(median), fmt(frontier_value),
1357
+ median / frontier_value - 1, fmt(band)))
1358
+ elif leads and held:
1359
+ print('\nfrontier unchanged: {} still holds the frontier at {}'.format(
1360
+ autoopt.label(root, meta['id']),
1361
+ fmt(result['objective']['median'])))
1362
+ elif leads and (result.get('keep') or {}).get('verdict') == 'fail':
1363
+ print('\nbest median so far ({} against {}), but within the noise '
1364
+ 'band of its parent: not kept'.format(
1365
+ fmt(result['objective']['median']), fmt(frontier_value)))
1366
+ elif leads:
1367
+ print('\nNEW FRONTIER: {} beats {}'.format(
1368
+ fmt(result['objective']['median']), fmt(frontier_value)))
1369
+ elif held:
1370
+ print('\nfrontier moved: {} no longer holds it; {} = {} from '
1371
+ 'iteration {}'.format(autoopt.label(root, meta['id']),
1372
+ config['objective']['name'], fmt(frontier_value),
1373
+ autoopt.label(root, frontier_id)))
1374
+
1375
+ if meta['id'] == 0 and result['status'] == 'ok':
1376
+ print('\n' + '\n'.join(autoopt.price_lines(root, config)))
1377
+
1378
+ return 0 if result['status'] != 'error' else 2
1379
+
1380
+
1381
+ if __name__ == '__main__':
1382
+ sys.exit(main())