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,1030 @@
1
+ """Read an `autooptimize/` search tree into the payloads the page draws.
2
+
3
+ from scan import RunScanner
4
+ snapshot = RunScanner('<work>/autooptimize').snapshot()
5
+
6
+ Nothing here writes to the search directory and nothing here talks to a
7
+ browser: `monitor_writer.py` publishes these payloads as JSON, but the reading
8
+ is all in this file so it can be called from a notebook cell on its own.
9
+
10
+ snapshot() -> state.json, every scan
11
+ hardware.resources() -> resources.json, every hardware tick
12
+
13
+ The external validation, when there is one, comes from `config.json` and
14
+ `validations/round-<N>.json` into the snapshot's `validation`.
15
+
16
+ The source of truth is `iterations/<id>/result.json`, written by
17
+ `run_iteration.py`. An iteration with a `meta.json` and no `result.json` is
18
+ still running, and is reported as such rather than skipped -- a search where
19
+ half the round has not landed yet is the normal state of things.
20
+ """
21
+
22
+ import os
23
+ import re
24
+ import sys
25
+ import json
26
+ import time
27
+ import random
28
+ import statistics
29
+ import subprocess
30
+
31
+ HERE = os.path.dirname(os.path.abspath(__file__))
32
+ sys.path.insert(0, os.path.dirname(HERE))
33
+
34
+ import autoopt
35
+ import stages
36
+ from gpu_scan import Hardware, stdout_of
37
+
38
+
39
+ # How much of an iteration's README rides along in the payload, for the
40
+ # tooltip. The whole file can be pages long; the top of it is the idea.
41
+ #
42
+ # A long search pays this per iteration on every poll: 2,600 iterations at
43
+ # 600 characters is 1.5 MB of README in a payload that crosses an ssh tunnel
44
+ # every few seconds, and it is the single largest block. Past `MANY` the
45
+ # budget drops to NOTES_CHARS_LARGE, the first line or two, which is all a
46
+ # tooltip shows anyway.
47
+ NOTES_CHARS = 600
48
+ NOTES_CHARS_LARGE = 160
49
+ # Seconds of silence after which a README-less iteration is not 'working'.
50
+ WORKING_IDLE = 3600
51
+
52
+ # Above this many iterations the README excerpt shrinks to NOTES_CHARS_LARGE.
53
+ # The lineage diagram condenses on its own past the same count, in the page
54
+ # (`LINEAGE_MANY` in dashboard.js).
55
+ MANY = 120
56
+
57
+ # An iteration set aside without a measurement (references/resume.md).
58
+ ABANDONED = re.compile(r'^(\d+)\.abandoned$')
59
+
60
+ # The objective's confidence interval, drawn as whiskers by the page's
61
+ # "Confidence intervals" toggle: a percentile bootstrap of the median over an
62
+ # iteration's runs, with a fixed seed so the whiskers do not move between
63
+ # polls. A settled iteration's runs never change, so each set of values is
64
+ # resampled once per writer.
65
+ CI_LEVEL = 0.95
66
+ CI_RESAMPLES = 2000
67
+ _CI_CACHE = {}
68
+
69
+ # An iteration's code change against its parent, from their merge base:
70
+ # lines added and deleted, and files added, deleted and modified (a rename or
71
+ # a mode change is a modification). Commits never change, so each pair is
72
+ # asked of git once per writer. A first scan of a long search would otherwise
73
+ # spend tens of seconds in git, so each scan spends at most DIFF_BUDGET
74
+ # seconds on pairs it has not seen, newest iteration first, and the rest fill
75
+ # in over the next polls.
76
+ DIFF_BUDGET = 2.0
77
+ _DIFF_CACHE = {}
78
+
79
+
80
+ def median_ci(values, level=CI_LEVEL, resamples=CI_RESAMPLES, seed=0):
81
+ """[low, high] of the bootstrap distribution of the median of `values`,
82
+ or None for fewer than two finite values. The percentiles interpolate
83
+ linearly between order statistics, as numpy's default does. With few runs
84
+ the resampled medians can take only a few values: at three runs the
85
+ interval is at most min to max."""
86
+
87
+ values = tuple(v for v in values if isinstance(v, (int, float))
88
+ and v == v and abs(v) != float('inf'))
89
+ if len(values) < 2:
90
+ return None
91
+
92
+ key = (values, level, resamples, seed)
93
+ if key not in _CI_CACHE:
94
+ rng = random.Random(seed)
95
+ medians = sorted(statistics.median(rng.choices(values, k=len(values)))
96
+ for _ in range(resamples))
97
+
98
+ def percentile(q):
99
+ position = q * (resamples - 1)
100
+ low = int(position)
101
+ high = min(low + 1, resamples - 1)
102
+ return medians[low] + (medians[high] - medians[low]) * (position - low)
103
+
104
+ tail = (1 - level) / 2
105
+ _CI_CACHE[key] = [percentile(tail), percentile(1 - tail)]
106
+
107
+ return list(_CI_CACHE[key])
108
+
109
+
110
+ def classify(cmdline):
111
+ """What a process of this search is doing, for the GPU monitor.
112
+
113
+ `run_iteration.py` owns the benchmark runs it launches, so they fold into
114
+ its row; a run started by hand shows as a `run` of its own.
115
+ """
116
+
117
+ if 'run_iteration.py' in cmdline:
118
+ return 'iteration'
119
+ if ('dashboard.ipynb' in cmdline or 'monitor.ipynb' in cmdline
120
+ or 'autoopt_monitor' in cmdline):
121
+ return 'other'
122
+ if re.search(r'iterations/\d+', cmdline):
123
+ return 'run'
124
+
125
+ return 'other'
126
+
127
+
128
+ def target(cmdline, pid=None):
129
+ """The iteration a process is working on: `iterations/<id>` in its
130
+ command line, else in the path its stdout goes to. `run_iteration.py`
131
+ starts each benchmark run with a relative command line from inside the
132
+ iteration and its stdout in `runs/seed-<n>/log.txt`, so only the second
133
+ names the iteration."""
134
+
135
+ match = re.search(r'iterations/(\d+)', cmdline) \
136
+ or re.search(r'iterations/(\d+)/', stdout_of(pid) or '')
137
+
138
+ return '#' + match.group(1) if match else None
139
+
140
+
141
+ def time_breakdown(directory, meta, result, gpus=1):
142
+ """Where an iteration's wall clock went: the steps the scripts time, and
143
+ the rest, which is the subagent's own work (reading, editing, probes,
144
+ its own checks). Only the fixed steps are measured; everything else is
145
+ inferred as the remainder, since each subagent structures its work
146
+ differently.
147
+
148
+ The end is the last of the files a finished iteration writes, README.md
149
+ last by protocol, so a subagent that kept measuring after the runner
150
+ finished is counted to when it stopped.
151
+ """
152
+
153
+ def stamp(text):
154
+ try:
155
+ return time.mktime(time.strptime(text, '%Y-%m-%dT%H:%M:%S'))
156
+ except (TypeError, ValueError):
157
+ return None
158
+
159
+ start = stamp(meta.get('created'))
160
+
161
+ if start is None or not result:
162
+ return None
163
+
164
+ ends = [stamp(result.get('finished'))]
165
+
166
+ for name in ('README.md', 'result.json', 'report.txt',
167
+ os.path.join('unit-tests', 'result.json'),
168
+ os.path.join('validation', 'record.json')):
169
+ try:
170
+ ends.append(os.path.getmtime(os.path.join(directory, name)))
171
+ except OSError:
172
+ pass
173
+
174
+ ends = [end for end in ends if end is not None]
175
+ total = max(ends) - start if ends else None
176
+
177
+ if total is None or total < 0:
178
+ return None
179
+
180
+ # With several GPUs an iteration's seeds run side by side, so their sum
181
+ # overstates the wall clock they took; divide by the cards they shared.
182
+ runs = sum(run.get('seconds') or 0.0 for run in result.get('runs') or [])
183
+ runs_wall = runs / max(1, min(gpus, len(result.get('runs') or []) or 1))
184
+
185
+ tests = result.get('tests') if isinstance(result.get('tests'), dict) \
186
+ else None
187
+ test_seconds = (tests.get('seconds_total', tests.get('seconds')) or 0.0) \
188
+ if tests else 0.0
189
+
190
+ validation = 0.0
191
+ record = os.path.join(directory, 'validation', 'record.json')
192
+
193
+ if os.path.exists(record):
194
+ try:
195
+ with open(record) as infile:
196
+ validation = float(json.load(infile).get('seconds') or 0.0)
197
+ except (OSError, ValueError, TypeError):
198
+ validation = 0.0
199
+
200
+ fixed = runs_wall + test_seconds + validation
201
+
202
+ return {'total': total, 'runs': runs_wall,
203
+ 'n_runs': len(result.get('runs') or []),
204
+ 'tests': test_seconds if tests else None,
205
+ 'tests_scope': (tests or {}).get('scope', 'full') if tests else None,
206
+ 'validation': validation if os.path.exists(record) else None,
207
+ 'subagent': max(0.0, total - fixed)}
208
+
209
+
210
+ def read_json(path):
211
+ """A JSON file, or None when it is missing or malformed."""
212
+
213
+ try:
214
+ with open(path) as handle:
215
+ return json.load(handle)
216
+ except (OSError, ValueError):
217
+ return None
218
+
219
+
220
+ def read_text(path, limit=None):
221
+ return read_excerpt(path, limit)[0]
222
+
223
+
224
+ def read_excerpt(path, limit=None):
225
+ """`(text, cut)`: the file's first `limit` characters, and whether it
226
+ held more, in which case the text ends with an ellipsis."""
227
+
228
+ try:
229
+ with open(path) as infile:
230
+ text = infile.read(limit + 1 if limit else None)
231
+ except OSError:
232
+ return '', False
233
+
234
+ if limit and len(text) > limit:
235
+ return text[:limit].rstrip() + '…', True
236
+
237
+ return text, False
238
+
239
+
240
+ def diffstat(repo, base, commit):
241
+ """`[lines added, lines deleted, files added, files deleted, files
242
+ modified]` from the merge base of `base` and `commit` to `commit`, or None
243
+ when git cannot say. A binary file counts as a file and adds no lines."""
244
+
245
+ try:
246
+ done = subprocess.run(['git', '-C', repo, 'diff', '--raw', '--numstat',
247
+ '-M', '--no-color', '{}...{}'.format(base, commit)],
248
+ capture_output=True, text=True, timeout=30)
249
+ except (OSError, subprocess.SubprocessError):
250
+ return None
251
+
252
+ if done.returncode != 0:
253
+ return None
254
+
255
+ added = deleted = 0
256
+ files = {'A': 0, 'D': 0, 'M': 0}
257
+
258
+ for line in done.stdout.splitlines():
259
+ if line.startswith(':'):
260
+ status = line.split('\t', 1)[0].split()[-1][:1]
261
+ files[status if status in files else 'M'] += 1
262
+ continue
263
+ parts = line.split('\t')
264
+ if len(parts) >= 3 and parts[0].isdigit() and parts[1].isdigit():
265
+ added += int(parts[0])
266
+ deleted += int(parts[1])
267
+
268
+ return [added, deleted, files['A'], files['D'], files['M']]
269
+
270
+
271
+ PATCH_LINE_CHARS = 1000
272
+ PATCH_FILE_ROWS = 2000
273
+ PATCH_BYTES = 400000
274
+ _HUNK = re.compile(r'^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@ ?(.*)$')
275
+
276
+
277
+ def parse_patch(text):
278
+ """The files of a `git diff` as dicts for the page's diff panel.
279
+
280
+ Each file has `path`, `old` (the path before a rename, else None),
281
+ `status` (A, D, M or R), `binary`, `additions`, `deletions`, `truncated`
282
+ and `hunks`: `{old, new, head, rows}` where `old` and `new` are the first
283
+ line numbers and a row is `[tag, text]`, tag one of ' ', '+', '-'. A line
284
+ is cut at PATCH_LINE_CHARS. A file past PATCH_FILE_ROWS rows, or after
285
+ the files before it have used PATCH_BYTES, keeps its counts and loses its
286
+ hunks (`truncated`)."""
287
+
288
+ files, current, hunk = [], None, None
289
+ spent = 0
290
+
291
+ for line in text.split('\n'):
292
+ if line.startswith('diff --git '):
293
+ head = line[len('diff --git '):]
294
+ half = head.find(' b/')
295
+ current = {'path': head[half + 3:] if half >= 0 else head,
296
+ 'old': None, 'status': 'M', 'binary': False, 'additions': 0,
297
+ 'deletions': 0, 'truncated': False, 'hunks': [], 'rows': 0,
298
+ 'bytes': 0}
299
+ files.append(current)
300
+ hunk = None
301
+ elif current is None:
302
+ continue
303
+ elif hunk is None and line.startswith('new file mode'):
304
+ current['status'] = 'A'
305
+ elif hunk is None and line.startswith('deleted file mode'):
306
+ current['status'] = 'D'
307
+ elif hunk is None and line.startswith('rename from '):
308
+ current['old'], current['status'] = line[len('rename from '):], 'R'
309
+ elif hunk is None and line.startswith('rename to '):
310
+ current['path'] = line[len('rename to '):]
311
+ elif hunk is None and line.startswith('Binary files '):
312
+ current['binary'] = True
313
+ elif hunk is None and line.startswith('+++ b/'):
314
+ current['path'] = line[len('+++ b/'):]
315
+ elif hunk is None and line.startswith('--- a/') and current['status'] == 'D':
316
+ current['path'] = line[len('--- a/'):]
317
+ else:
318
+ match = _HUNK.match(line)
319
+ if match:
320
+ hunk = {'old': int(match.group(1)), 'new': int(match.group(2)),
321
+ 'head': match.group(3), 'rows': []}
322
+ current['hunks'].append(hunk)
323
+ elif hunk is not None and line[:1] in (' ', '+', '-'):
324
+ if line[0] == '+':
325
+ current['additions'] += 1
326
+ elif line[0] == '-':
327
+ current['deletions'] += 1
328
+ body = line[1:]
329
+ if len(body) > PATCH_LINE_CHARS:
330
+ body = body[:PATCH_LINE_CHARS] + '…'
331
+ hunk['rows'].append([line[0], body])
332
+ current['rows'] += 1
333
+ current['bytes'] += len(body) + 8
334
+
335
+ for item in files:
336
+ spent += item['bytes']
337
+ if item['rows'] > PATCH_FILE_ROWS or spent > PATCH_BYTES:
338
+ item['hunks'], item['truncated'] = [], True
339
+ del item['rows'], item['bytes']
340
+
341
+ return files
342
+
343
+
344
+ def patch(repo, base, commit):
345
+ """`parse_patch` of the diff from the merge base of `base` and `commit` to
346
+ `commit` (the same range as `diffstat`), or None when git cannot say."""
347
+
348
+ try:
349
+ done = subprocess.run(['git', '-C', repo, '-c', 'core.quotepath=off',
350
+ 'diff', '-M', '--no-color', '--no-ext-diff', '-U3',
351
+ '--src-prefix=a/', '--dst-prefix=b/',
352
+ '{}...{}'.format(base, commit)], capture_output=True,
353
+ timeout=30)
354
+ except (OSError, subprocess.SubprocessError):
355
+ return None
356
+
357
+ if done.returncode != 0:
358
+ return None
359
+
360
+ return parse_patch(done.stdout.decode('utf-8', 'replace'))
361
+
362
+
363
+ class RunScanner:
364
+ def __init__(self, root):
365
+ self.root = autoopt.resolve(root)
366
+ self.started_at = time.time()
367
+ self.hardware = Hardware(self.root, classify=classify, target=target)
368
+
369
+ ###
370
+ # The payloads
371
+ ###
372
+
373
+ def snapshot(self):
374
+ config = autoopt.load_config(self.root)
375
+ state = autoopt.load_state(self.root)
376
+
377
+ iterations = self.iterations(config)
378
+ settled = [row for row in iterations if row['status'] != 'running']
379
+
380
+ direction = config['objective']['direction']
381
+
382
+ # On-frontier is decided over the settled passing iterations, seeded
383
+ # by nothing: the baseline is one of them.
384
+ path = autoopt.frontier_path([row for row in settled
385
+ if row['status'] == 'ok'], direction)
386
+ on_frontier = {row['id'] for row in path}
387
+
388
+ for row in iterations:
389
+ row['on_frontier'] = row['id'] in on_frontier
390
+
391
+ return {
392
+ 'root': self.root,
393
+ 'generated': time.time(),
394
+ 'uptime': time.time() - self.started_at,
395
+ # The search kind's categories, plus any an iteration used: a
396
+ # chip and a colour for each, empty ones included.
397
+ 'categories': [autoopt.ROOT_CATEGORY] + list(autoopt.categories_for(
398
+ self.root)) + sorted({row['category'] for row in iterations}
399
+ - set(autoopt.categories_for(self.root))
400
+ - {autoopt.ROOT_CATEGORY}),
401
+ 'mining': state.get('mining') or {},
402
+ 'task': config.get('task', ''),
403
+ 'objective': config['objective'],
404
+ 'gates': config['gates'],
405
+ 'observers': config['observers'],
406
+ 'plan': {'runs_per_iteration': config['runs_per_iteration'],
407
+ 'confirm_runs': config['confirm_runs'],
408
+ 'staged': config['staged']},
409
+ 'state': state,
410
+ 'iterations': iterations,
411
+ 'counts': self.counts(iterations, state),
412
+ 'frontier': self.frontier_block(path, settled, config),
413
+ 'stats': self.stats(iterations, settled, config, path),
414
+ 'validation': self.validation(config),
415
+ 'unreadable': [{'id': row['id'], 'error': row['error']}
416
+ for row in iterations if row['status'] == 'unreadable'],
417
+ 'abandoned': self.abandoned(),
418
+ 'after': self.after(),
419
+ }
420
+
421
+ ###
422
+ # What the search wrote about its own ending
423
+ ###
424
+
425
+ def after(self):
426
+ """The search's own account of where it stands: `ended` (ended.json
427
+ and final.json; None while the search runs) and the six `stages`.
428
+ A part that raises is None and named in `errors`."""
429
+
430
+ work = os.path.dirname(self.root)
431
+ out = {}
432
+
433
+ for key, read in (('ended', lambda: self.ended()),
434
+ ('stages', lambda: self.stages(work))):
435
+ try:
436
+ out[key] = read()
437
+ except Exception as error:
438
+ out[key] = None
439
+ out.setdefault('errors', {})[key] = '{}: {}'.format(
440
+ type(error).__name__, error)[:200]
441
+
442
+ return out
443
+
444
+ def ended(self):
445
+ ended = autoopt.load_ended(self.root)
446
+
447
+ if not ended:
448
+ return None
449
+
450
+ medians = ended.get('medians') or {}
451
+ winner = ended.get('winner') or {}
452
+ paired = read_json(os.path.join(self.root, 'final.json')) or {}
453
+
454
+ return {'at': ended.get('ended_at'), 'winner': winner.get('label'),
455
+ 'winner_median': medians.get('winner'), 'zero_median': medians.get(
456
+ 'A0'), 'unit': medians.get('unit'), 'reason': (ended.get('reason')
457
+ or {}).get('text'), 'paired': paired.get('summary') if isinstance(
458
+ paired, dict) else None}
459
+
460
+ def stages(self, work):
461
+ """`[[stage, status, detail]]` for the search's stages."""
462
+
463
+ return [[name, status, detail] for name, status, detail, _ in
464
+ stages.collect(work)]
465
+
466
+ def validation(self, config):
467
+ """The external validation: its configuration and every round's
468
+ record from `validations/round-<N>.json`, oldest round first. None
469
+ when the search has neither, so the page draws nothing.
470
+
471
+ Reported, never gated on: nothing here feeds `on_frontier` or a
472
+ status.
473
+ """
474
+
475
+ block = config.get('external_validation')
476
+ directory = os.path.join(self.root, 'validations')
477
+ records = []
478
+
479
+ for name in (os.listdir(directory) if os.path.isdir(directory) else []):
480
+ match = re.fullmatch(r'round-(\d+)\.json', name)
481
+
482
+ if not match:
483
+ continue
484
+
485
+ number = match.group(1)
486
+ stem = name[:-len('.json')]
487
+
488
+ try:
489
+ with open(os.path.join(directory, name)) as infile:
490
+ record = json.load(infile)
491
+ except (OSError, ValueError):
492
+ continue
493
+
494
+ # The script's own validation.json may name units; the record
495
+ # autoopt.py writes does not carry them.
496
+ try:
497
+ with open(os.path.join(directory, stem,
498
+ 'validation.json')) as infile:
499
+ emitted = json.load(infile)
500
+ except (OSError, ValueError):
501
+ emitted = {}
502
+
503
+ records.append({
504
+ 'units': emitted.get('units') if isinstance(emitted, dict) else None,
505
+ 'round': record.get('round', int(number)),
506
+ 'iteration': record.get('iteration'),
507
+ 'measures': record.get('measures') or {},
508
+ 'ok': record.get('ok'),
509
+ 'note': record.get('note') or '',
510
+ 'seconds': record.get('seconds'),
511
+ 'exit_code': record.get('exit_code'),
512
+ 'created': record.get('created'),
513
+ })
514
+
515
+ if block is None and not records:
516
+ return None
517
+
518
+ block = block or {}
519
+ # Oldest first, so the sidebar's last record is the latest run.
520
+ records.sort(key=lambda record: (record['created'] or 0,
521
+ record['round'] or 0))
522
+
523
+ # The configured measures in their order, then any a record carries
524
+ # that the configuration does not name.
525
+ measures = list(block.get('measures') or [])
526
+ for record in records:
527
+ measures += [name for name in sorted(record['measures'])
528
+ if name not in measures]
529
+
530
+ # Units: config.json's `units`, then any a round's validation.json
531
+ # names, the newest round last. Strings only; anything else is dropped.
532
+ units = {}
533
+ for source in [block.get('units')] + [r.pop('units') for r in records]:
534
+ if isinstance(source, dict):
535
+ units.update({name: unit for name, unit in source.items()
536
+ if isinstance(unit, str) and unit})
537
+
538
+ return {
539
+ 'configured': bool(block),
540
+ 'measures': measures,
541
+ 'units': units,
542
+ 'note': block.get('note') or '',
543
+ 'approved': bool(block.get('approved')),
544
+ 'approved_on': block.get('approved_on'),
545
+ 'records': records,
546
+ }
547
+
548
+ ###
549
+ # One iteration
550
+ ###
551
+
552
+ def iterations(self, config):
553
+ out = []
554
+ ids = autoopt.iteration_ids(self.root)
555
+ budget = NOTES_CHARS if len(ids) <= MANY else NOTES_CHARS_LARGE
556
+
557
+ for identifier in ids:
558
+ # One malformed result.json costs its own row, not the scan: a
559
+ # failed snapshot freezes state.json for every iteration.
560
+ try:
561
+ row = self.iteration(identifier, config, budget)
562
+ except Exception as error:
563
+ row = self.unreadable(identifier, error)
564
+
565
+ if row is not None:
566
+ out.append(row)
567
+
568
+ self.diffstats(out)
569
+ return out
570
+
571
+ def diffstats(self, rows):
572
+ """Give every settled iteration with a parent its `diffstat`."""
573
+
574
+ repo = os.path.join(self.root, 'repo.git')
575
+ commits = {row['id']: row.get('commit') for row in rows}
576
+ spent = 0.0
577
+
578
+ for row in sorted(rows, key=lambda row: -row['id']):
579
+ base, head = commits.get(row.get('parent')), row.get('commit')
580
+ if row['status'] in ('running', 'unreadable') or not base or not head:
581
+ continue
582
+ key = (repo, base, head)
583
+ if key not in _DIFF_CACHE:
584
+ if spent >= DIFF_BUDGET:
585
+ continue
586
+ started = time.time()
587
+ _DIFF_CACHE[key] = diffstat(repo, base, head)
588
+ spent += time.time() - started
589
+ if _DIFF_CACHE[key] is not None:
590
+ row['diffstat'] = _DIFF_CACHE[key]
591
+
592
+ def abandoned(self, notes_chars=NOTES_CHARS):
593
+ """Iterations set aside without a measurement: `iterations/<id>.abandoned`,
594
+ an empty fork moved out of the way (references/resume.md). They
595
+ are kept out of `iterations`, so no count, frontier, tree or table sees
596
+ them; the page marks each on the objective chart at the baseline's value,
597
+ so a reader can see that the idea was tried and closed."""
598
+
599
+ directory = os.path.join(self.root, 'iterations')
600
+ out = []
601
+
602
+ for name in (os.listdir(directory) if os.path.isdir(directory) else []):
603
+ match = ABANDONED.match(name)
604
+ if not match:
605
+ continue
606
+
607
+ path = os.path.join(directory, name)
608
+ try:
609
+ with open(os.path.join(path, 'meta.json')) as handle:
610
+ meta = json.load(handle)
611
+ except (OSError, ValueError):
612
+ meta = {}
613
+ meta = meta if isinstance(meta, dict) else {}
614
+ identifier = int(match.group(1))
615
+ notes = read_text(os.path.join(path, 'README.md'), notes_chars)
616
+
617
+ out.append({'id': identifier,
618
+ 'parent': meta.get('parent'),
619
+ 'round': meta.get('round'),
620
+ 'title': meta.get('title') or '',
621
+ 'category': autoopt.category_of(dict(meta, id=identifier)) or 'MISC',
622
+ 'topic': meta.get('topic') or '',
623
+ 'created': meta.get('created'),
624
+ 'notes': notes,
625
+ 'has_readme': bool(notes),
626
+ 'status': 'abandoned'})
627
+
628
+ return sorted(out, key=lambda row: row['id'])
629
+
630
+ def unreadable(self, identifier, error):
631
+ """The row for an iteration whose files could not be read: status
632
+ 'unreadable', counted as settled, never on the frontier, with the
633
+ error in `error`."""
634
+
635
+ meta = autoopt.load_meta(self.root, identifier)
636
+ meta = meta if isinstance(meta, dict) else {}
637
+ parent = meta.get('parent')
638
+
639
+ return {'id': identifier,
640
+ 'parent': parent if isinstance(parent, int) else None,
641
+ 'round': None, 'title': '',
642
+ 'category': 'MISC', 'topic': '', 'branch': None, 'commit': None,
643
+ 'created': None, 'notes': '', 'has_readme': False, 'status': 'unreadable', 'stage': None,
644
+ 'n_runs': 0, 'value': None, 'objective': None, 'gates': {},
645
+ 'observers': {}, 'seconds': None,
646
+ 'error': '{}: {}'.format(type(error).__name__, error)[:300]}
647
+
648
+ def readmes(self, seen=None):
649
+ """The whole README.md of every iteration whose file changed since `seen`.
650
+
651
+ Returns {id: (mtime, text)}. The payload carries only an excerpt
652
+ (NOTES_CHARS), so the page fetches `readmes/<id>.json` when a tree node
653
+ is opened; `seen` ({id: mtime}) lets the writer rewrite only the files
654
+ that moved.
655
+ """
656
+
657
+ seen = seen or {}
658
+ changed = {}
659
+ for identifier in autoopt.iteration_ids(self.root):
660
+ path = os.path.join(autoopt.iteration_dir(self.root, identifier), 'README.md')
661
+ try:
662
+ mtime = os.path.getmtime(path)
663
+ except OSError:
664
+ continue
665
+ if seen.get(identifier) != mtime:
666
+ changed[identifier] = (mtime, read_text(path))
667
+ return changed
668
+
669
+ def diffs(self, rows, seen=None, budget=DIFF_BUDGET):
670
+ """The code change of every settled iteration with a parent, against
671
+ that parent, for the diff panel under the objective chart.
672
+
673
+ `rows` are the snapshot's iterations. Returns {id: (payload, pair)} for
674
+ the iterations whose (parent commit, commit) pair is not already in `seen` ({id: (base, head)}); the writer records what it
675
+ wrote there. A pair is asked of git once, newest iteration first, and
676
+ each call spends at most `budget` seconds (None: no limit, for the
677
+ export) on pairs it has not seen; the rest fill in on later calls.
678
+ The payload is `{id, parent, files}`, `files` from `parse_patch`."""
679
+
680
+ seen = seen if seen is not None else {}
681
+ repo = os.path.join(self.root, 'repo.git')
682
+ commits = {row['id']: row.get('commit') for row in rows}
683
+ rows = [row for row in rows
684
+ if row['status'] not in ('running', 'unreadable')]
685
+ out, spent = {}, 0.0
686
+
687
+ for row in sorted(rows, key=lambda row: -row['id']):
688
+ base, head = commits.get(row.get('parent')), row.get('commit')
689
+ if not base or not head or seen.get(row['id']) == (base, head):
690
+ continue
691
+ if budget is not None and spent >= budget:
692
+ break
693
+ started = time.time()
694
+ files = patch(repo, base, head)
695
+ spent += time.time() - started
696
+ if files is not None:
697
+ out[row['id']] = ({'id': row['id'], 'parent': row['parent'],
698
+ 'files': files}, (base, head))
699
+
700
+ return out
701
+
702
+ def iteration(self, identifier, config, notes_chars=NOTES_CHARS):
703
+ directory = autoopt.iteration_dir(self.root, identifier)
704
+ meta = autoopt.load_meta(self.root, identifier) or {}
705
+ result = autoopt.load_result(self.root, identifier)
706
+
707
+ if not meta and not result:
708
+ return None
709
+
710
+ notes, cut = read_excerpt(os.path.join(directory, 'README.md'),
711
+ notes_chars)
712
+
713
+ row = {
714
+ 'id': identifier,
715
+ 'parent': (result or meta).get('parent'),
716
+ 'round': (result or meta).get('round'),
717
+ 'title': (result or meta).get('title') or '',
718
+ 'category': autoopt.category_of(dict(result or meta,
719
+ id=identifier)) or 'MISC',
720
+ 'topic': (result or meta).get('topic') or '',
721
+ 'branch': (result or meta).get('branch'),
722
+ 'commit': (result or meta).get('commit'),
723
+ 'created': meta.get('created'),
724
+ # The idea miner's last finished stage when it was created (0 before
725
+ # any has finished).
726
+ 'mining_stage': meta.get('mining_stage'),
727
+ # `no` or `specific`, the answer to the brief's toolchain question.
728
+ 'toolchain': meta.get('toolchain'),
729
+ 'notes': notes,
730
+ 'has_readme': bool(notes),
731
+ }
732
+
733
+ # A same-code control is never on the frontier (autoopt.frontier_path).
734
+ if meta.get('control'):
735
+ row['control'] = True
736
+
737
+ # Only when true: the page's SHOW MORE fetches readmes/<id>.json.
738
+ if cut:
739
+ row['notes_cut'] = True
740
+
741
+ if result is None:
742
+ # Started but not settled. `elapsed` is what the summary band
743
+ # counts as "in flight" and what the tree draws hollow.
744
+ row.update({'status': 'running', 'stage': None, 'n_runs': 0,
745
+ 'value': None, 'objective': None, 'gates': {},
746
+ 'observers': {}, 'seconds': None,
747
+ 'elapsed': self.elapsed(directory, meta)})
748
+
749
+ return row
750
+
751
+ objective = result.get('objective') or {}
752
+
753
+ row.update({
754
+ 'status': result.get('status', '?'),
755
+ 'stage': result.get('stage'),
756
+ 'n_runs': result.get('n_runs') or 0,
757
+ 'n_failed': result.get('n_failed') or 0,
758
+ 'value': objective.get('median'),
759
+ 'objective': dict({key: objective.get(key) for key in
760
+ ('median', 'mean', 'std', 'min', 'max', 'values')},
761
+ ci=median_ci(objective.get('values') or [])),
762
+ 'gates': {name: {key: gate.get(key) for key in
763
+ ('op', 'threshold', 'worst', 'median', 'pass',
764
+ 'n_violations')}
765
+ for name, gate in (result.get('gates') or {}).items()},
766
+ 'observers': {name: {'median': observer.get('median'),
767
+ 'std': observer.get('std')}
768
+ for name, observer in (result.get('observers') or {}).items()},
769
+ 'seconds': result.get('seconds'),
770
+ # Every number a run recorded, for the per-run table. The note is
771
+ # the benchmark's own free text, clipped so one verbose run cannot
772
+ # bloat every snapshot.
773
+ 'runs': [{'seed': run.get('seed'),
774
+ 'objective': run.get('objective'),
775
+ 'seconds': run.get('seconds'),
776
+ 'dir': run.get('dir'),
777
+ 'gates': run.get('gates') or {},
778
+ 'observers': run.get('observers') or {},
779
+ 'note': str(run.get('note') or '')[:240]}
780
+ for run in (result.get('runs') or [])],
781
+ 'tests': (None if not isinstance(result.get('tests'), dict)
782
+ else bool(result['tests'].get('pass'))),
783
+ 'finished': result.get('finished'),
784
+ 'best_run': result.get('best_run'),
785
+ 'failures': result.get('failures') or [],
786
+ 'frontier_at_start': result.get('frontier_at_start'),
787
+ 'noise_band': result.get('noise_band'),
788
+ 'time': time_breakdown(directory, meta, result,
789
+ config.get('gpus_per_agent', 1) or 1),
790
+ })
791
+
792
+ # The runner finishes long before its subagent does: the subagent's
793
+ # own checks and validation come after result.json, and the README
794
+ # is written last. Until it exists the iteration is still being
795
+ # worked on, and `idle` says how long since anything in it changed.
796
+ # A subagent that died leaves no README either, so a silent hour ends
797
+ # the marker; the baseline never has one.
798
+ if not notes and identifier != 0:
799
+ idle = self.idle(directory)
800
+ if idle is not None and idle < WORKING_IDLE:
801
+ row['working'] = True
802
+ row['idle'] = idle
803
+
804
+ return row
805
+
806
+ def elapsed(self, directory, meta):
807
+ """Seconds since a running iteration last wrote anything.
808
+
809
+ Taken from the newest file under `runs/`, not from `created`: an
810
+ iteration forked an hour ago and started ten minutes ago has been
811
+ running for ten minutes.
812
+ """
813
+
814
+ newest = 0.0
815
+ runs = os.path.join(directory, 'runs')
816
+
817
+ for base, _, names in os.walk(runs):
818
+ for name in names:
819
+ try:
820
+ newest = max(newest,
821
+ os.path.getmtime(os.path.join(base, name)))
822
+ except OSError:
823
+ continue
824
+
825
+ if not newest:
826
+ try:
827
+ newest = os.path.getmtime(directory)
828
+ except OSError:
829
+ return None
830
+
831
+ return time.time() - newest
832
+
833
+ def idle(self, directory):
834
+ """Seconds since anything a subagent writes in an iteration changed:
835
+ probes, logs, validation, the report. Compiler caches and exported
836
+ source trees are skipped; they are large and not a sign of progress."""
837
+
838
+ newest, skip = 0.0, {'cache', '.numba-cache', '__pycache__', 'src', 'v'}
839
+
840
+ for base, dirs, names in os.walk(directory):
841
+ dirs[:] = [d for d in dirs if d not in skip]
842
+ for name in names:
843
+ try:
844
+ newest = max(newest,
845
+ os.path.getmtime(os.path.join(base, name)))
846
+ except OSError:
847
+ continue
848
+
849
+ return time.time() - newest if newest else None
850
+
851
+ ###
852
+ # Aggregates
853
+ ###
854
+
855
+ def counts(self, iterations, state):
856
+ settled = [row for row in iterations if row['status'] != 'running']
857
+
858
+ by_category, by_status = {}, {}
859
+
860
+ for row in settled:
861
+ by_category[row['category']] = by_category.get(row['category'],
862
+ 0) + 1
863
+ by_status[row['status']] = by_status.get(row['status'], 0) + 1
864
+
865
+ return {
866
+ 'iterations': len(settled),
867
+ 'running': len(iterations) - len(settled),
868
+ 'working': sum(1 for row in settled if row.get('working')),
869
+ 'runs': sum(row['n_runs'] for row in settled),
870
+ 'rounds': len(self.rounds()),
871
+ 'round': state.get('round'),
872
+ 'by_category': by_category,
873
+ 'by_status': by_status,
874
+ }
875
+
876
+ def rounds(self):
877
+ """The rounds that have been summarized, newest last."""
878
+
879
+ directory = os.path.join(self.root, 'rounds')
880
+ out = []
881
+
882
+ for name in sorted(os.listdir(directory)
883
+ if os.path.isdir(directory) else []):
884
+
885
+ if name.startswith('round-') and name.endswith('.md'):
886
+ number = name[len('round-'):-len('.md')]
887
+ out.append({'round': int(number) if number.isdigit() else 0,
888
+ 'path': os.path.join(directory, name)})
889
+
890
+ return sorted(out, key=lambda entry: entry['round'])
891
+
892
+ def frontier_block(self, path, settled, config):
893
+ """The frontier, and what each step of it bought.
894
+
895
+ `gain` is against the step before it, so the steps sum to `total`;
896
+ the baseline's own gain is zero by construction.
897
+ """
898
+
899
+ steps, previous = [], None
900
+
901
+ for row in path:
902
+ gain = None if previous is None else row['value'] - previous
903
+ relative = (None if previous in (None, 0)
904
+ else gain / abs(previous) * 100.0)
905
+
906
+ steps.append({'id': row['id'], 'value': row['value'],
907
+ 'title': row['title'], 'category': row['category'],
908
+ 'round': row['round'], 'gain': gain, 'percent': relative})
909
+
910
+ previous = row['value']
911
+
912
+ baseline = next((row for row in settled if row['id'] == 0), None)
913
+ base_value = baseline['value'] if baseline else None
914
+ best = steps[-1] if steps else None
915
+
916
+ return {
917
+ 'value': best['value'] if best else None,
918
+ 'id': best['id'] if best else None,
919
+ 'steps': steps,
920
+ 'baseline': base_value,
921
+ 'total_gain': (None if best is None or base_value is None
922
+ else best['value'] - base_value),
923
+ 'total_percent': (None if best is None or not base_value
924
+ else (best['value'] - base_value) / abs(base_value) * 100.0),
925
+ }
926
+
927
+ def stats(self, iterations, settled, config, path):
928
+ """The right-hand column: what the search has cost and bought."""
929
+
930
+ ok = [row for row in settled if row['status'] == 'ok']
931
+ gate_failed = [row for row in settled
932
+ if row['status'] == 'gate-failed']
933
+ errored = [row for row in settled if row['status'] == 'error']
934
+ partial = [row for row in settled if row['status'] == 'partial']
935
+
936
+ seconds = [row['seconds'] for row in settled if row['seconds']]
937
+ total_seconds = sum(seconds)
938
+ runs = sum(row['n_runs'] for row in settled)
939
+
940
+ # Wall clock of the search, from the first iteration's start to now.
941
+ created = [row['created'] for row in iterations if row.get('created')]
942
+ started = min(created) if created else None
943
+ wall = None
944
+
945
+ if started:
946
+ try:
947
+ wall = time.time() - time.mktime(time.strptime(started,
948
+ '%Y-%m-%dT%H:%M:%S'))
949
+ except ValueError:
950
+ wall = None
951
+
952
+ # What the staged evaluation did not spend: every iteration that
953
+ # stopped at the screening depth skipped the rest of the confirmation
954
+ # runs.
955
+ saved = 0
956
+ if config['staged']:
957
+ extra = config['confirm_runs'] - config['runs_per_iteration']
958
+ saved = extra * sum(1 for row in settled
959
+ if row.get('stage') == 'screen')
960
+
961
+ per_category = {}
962
+ for row in settled:
963
+ entry = per_category.setdefault(row['category'],
964
+ {'n': 0, 'ok': 0, 'best': None, 'frontier': 0})
965
+ entry['n'] += 1
966
+ entry['ok'] += row['status'] == 'ok'
967
+ entry['frontier'] += bool(row.get('on_frontier'))
968
+
969
+ if row['status'] == 'ok' and autoopt.better(row['value'],
970
+ entry['best'], config['objective']['direction']):
971
+ entry['best'] = row['value']
972
+
973
+ return {
974
+ 'n_ok': len(ok),
975
+ 'n_gate_failed': len(gate_failed),
976
+ 'n_error': len(errored),
977
+ 'n_partial': len(partial),
978
+ 'n_frontier': len(path),
979
+ 'runs': runs,
980
+ 'runs_saved': saved if config['staged'] else None,
981
+ 'compute_hours': total_seconds / 3600.0,
982
+ 'wall_hours': (wall / 3600.0) if wall else None,
983
+ 'iterations_per_hour': (len(settled) / (wall / 3600.0)
984
+ if wall and wall > 60 else None),
985
+ 'runs_per_hour': (runs / (wall / 3600.0)
986
+ if wall and wall > 60 else None),
987
+ 'seconds_per_run': (total_seconds / runs) if runs else None,
988
+ 'median_iteration_minutes': (statistics.median(seconds) / 60.0
989
+ if seconds else None),
990
+ 'gate_pass_rate': (len(ok) / (len(settled) - len(partial))
991
+ if len(settled) > len(partial) else None),
992
+ 'per_category': per_category,
993
+ 'rounds': self.rounds(),
994
+ }
995
+
996
+
997
+ def main(argv=None):
998
+ """Print a search's snapshot as JSON: the quickest way to tell a scanner
999
+ problem from a page problem.
1000
+
1001
+ python3 scan.py <root> | head
1002
+ """
1003
+
1004
+ import argparse
1005
+
1006
+ parser = argparse.ArgumentParser(description=main.__doc__)
1007
+ parser.add_argument('root', help='the autooptimize/ directory')
1008
+ args = parser.parse_args(argv)
1009
+
1010
+ scanner = RunScanner(args.root)
1011
+ payload = scanner.snapshot()
1012
+ # Flushed here, inside the handler below: a flush left to interpreter
1013
+ # exit reports a closed pipe as "Exception ignored" and cannot be caught.
1014
+ print(json.dumps(payload, indent='\t', default=lambda value: None),
1015
+ flush=True)
1016
+
1017
+ return 0
1018
+
1019
+
1020
+ if __name__ == '__main__':
1021
+ try:
1022
+ sys.exit(main())
1023
+ except BrokenPipeError:
1024
+ # `| head` closed the pipe: stop quietly, as a filter should, and keep
1025
+ # Python from reporting the flush at exit.
1026
+ os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
1027
+ sys.exit(0)
1028
+ except ValueError as error:
1029
+ print('error: {}'.format(error), file=sys.stderr)
1030
+ sys.exit(1)