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.
- auto_optimize/__init__.py +3 -0
- auto_optimize/__main__.py +5 -0
- auto_optimize/cli.py +651 -0
- auto_optimize/skills/auto-optimize-code/LICENSE +21 -0
- auto_optimize/skills/auto-optimize-code/SKILL.md +251 -0
- auto_optimize/skills/auto-optimize-code/VERSION +1 -0
- auto_optimize/skills/auto-optimize-code/references/algorithm.md +182 -0
- auto_optimize/skills/auto-optimize-code/references/changes.md +146 -0
- auto_optimize/skills/auto-optimize-code/references/cli.md +206 -0
- auto_optimize/skills/auto-optimize-code/references/dashboard.md +203 -0
- auto_optimize/skills/auto-optimize-code/references/documents.md +55 -0
- auto_optimize/skills/auto-optimize-code/references/extending.md +87 -0
- auto_optimize/skills/auto-optimize-code/references/external-validation.md +98 -0
- auto_optimize/skills/auto-optimize-code/references/glossary.md +134 -0
- auto_optimize/skills/auto-optimize-code/references/idea-miner.md +108 -0
- auto_optimize/skills/auto-optimize-code/references/issue-bugs.md +182 -0
- auto_optimize/skills/auto-optimize-code/references/layout.md +300 -0
- auto_optimize/skills/auto-optimize-code/references/main-session.md +45 -0
- auto_optimize/skills/auto-optimize-code/references/measuring.md +208 -0
- auto_optimize/skills/auto-optimize-code/references/pr-optimization.md +127 -0
- auto_optimize/skills/auto-optimize-code/references/pr-tests.md +254 -0
- auto_optimize/skills/auto-optimize-code/references/promotion.md +133 -0
- auto_optimize/skills/auto-optimize-code/references/reading-a-search.md +65 -0
- auto_optimize/skills/auto-optimize-code/references/repo-mode.md +224 -0
- auto_optimize/skills/auto-optimize-code/references/resume.md +81 -0
- auto_optimize/skills/auto-optimize-code/references/shared-knowledge.md +114 -0
- auto_optimize/skills/auto-optimize-code/references/step0-interview.md +298 -0
- auto_optimize/skills/auto-optimize-code/references/step1-unit-tests.md +136 -0
- auto_optimize/skills/auto-optimize-code/references/step2-baseline.md +708 -0
- auto_optimize/skills/auto-optimize-code/references/step3-rounds.md +350 -0
- auto_optimize/skills/auto-optimize-code/references/step4-final.md +121 -0
- auto_optimize/skills/auto-optimize-code/references/step5-ship.md +220 -0
- auto_optimize/skills/auto-optimize-code/references/step6-finish.md +67 -0
- auto_optimize/skills/auto-optimize-code/references/subagent.md +467 -0
- auto_optimize/skills/auto-optimize-code/references/symptoms.md +67 -0
- auto_optimize/skills/auto-optimize-code/references/writing-briefs.md +117 -0
- auto_optimize/skills/auto-optimize-code/scripts/attribution.py +156 -0
- auto_optimize/skills/auto-optimize-code/scripts/autoopt.py +12863 -0
- auto_optimize/skills/auto-optimize-code/scripts/check_seeding.py +334 -0
- auto_optimize/skills/auto-optimize-code/scripts/cold.py +90 -0
- auto_optimize/skills/auto-optimize-code/scripts/dashboard/README.md +165 -0
- auto_optimize/skills/auto-optimize-code/scripts/dashboard/autoopt_monitor.py +850 -0
- auto_optimize/skills/auto-optimize-code/scripts/dashboard/gpu_scan.py +954 -0
- auto_optimize/skills/auto-optimize-code/scripts/dashboard/monitor_writer.py +684 -0
- auto_optimize/skills/auto-optimize-code/scripts/dashboard/scan.py +1030 -0
- auto_optimize/skills/auto-optimize-code/scripts/dashboard/static/dashboard.css +775 -0
- auto_optimize/skills/auto-optimize-code/scripts/dashboard/static/dashboard.js +3652 -0
- auto_optimize/skills/auto-optimize-code/scripts/dashboard/static/index.html +191 -0
- auto_optimize/skills/auto-optimize-code/scripts/issue_body.py +2118 -0
- auto_optimize/skills/auto-optimize-code/scripts/lint_text.py +448 -0
- auto_optimize/skills/auto-optimize-code/scripts/opt_pr_body.py +894 -0
- auto_optimize/skills/auto-optimize-code/scripts/opt_pr_tables.py +367 -0
- auto_optimize/skills/auto-optimize-code/scripts/paired.py +188 -0
- auto_optimize/skills/auto-optimize-code/scripts/preflight.py +280 -0
- auto_optimize/skills/auto-optimize-code/scripts/probe_run.py +72 -0
- auto_optimize/skills/auto-optimize-code/scripts/publish.py +385 -0
- auto_optimize/skills/auto-optimize-code/scripts/run_iteration.py +1382 -0
- auto_optimize/skills/auto-optimize-code/scripts/ship.py +1193 -0
- auto_optimize/skills/auto-optimize-code/scripts/stages.py +651 -0
- auto_optimize/skills/auto-optimize-code/scripts/tests_pr_body.py +1267 -0
- auto_optimize/skills/auto-optimize-code/scripts/tests_pr_push.py +426 -0
- auto_optimize/skills/auto-optimize-code/scripts/tests_pr_tables.py +779 -0
- auto_optimize-1.0.0.dist-info/METADATA +610 -0
- auto_optimize-1.0.0.dist-info/RECORD +67 -0
- auto_optimize-1.0.0.dist-info/WHEEL +4 -0
- auto_optimize-1.0.0.dist-info/entry_points.txt +2 -0
- auto_optimize-1.0.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Find out whether the benchmark's seed controls what it should.
|
|
3
|
+
|
|
4
|
+
python3 check_seeding.py autooptimize/iterations/0
|
|
5
|
+
|
|
6
|
+
Two things have to be true before a search means anything, and they pull in
|
|
7
|
+
opposite directions:
|
|
8
|
+
|
|
9
|
+
1. **The same seed gives the same answer.** Whatever is left over when the
|
|
10
|
+
seed is held fixed is noise no amount of averaging attributes to an
|
|
11
|
+
idea.
|
|
12
|
+
2. **A different seed gives a different answer.** If it does not, the runs
|
|
13
|
+
are one number repeated, the noise band comes out at zero, and every
|
|
14
|
+
keep verdict after that is made on a single sample counted
|
|
15
|
+
as several.
|
|
16
|
+
|
|
17
|
+
So this runs the benchmark twice on one seed and twice more on two others,
|
|
18
|
+
and reports the two spreads side by side. What matters is their ratio: a
|
|
19
|
+
same-seed spread near zero means the seed controls everything; a same-seed
|
|
20
|
+
spread as large as the between-seed spread means it controls nothing that
|
|
21
|
+
matters and the search cannot tell an idea from a rerun.
|
|
22
|
+
|
|
23
|
+
It also reads the benchmark's source for the usual unseeded sources of
|
|
24
|
+
randomness, which is where the answer usually is when the numbers come out
|
|
25
|
+
wrong.
|
|
26
|
+
|
|
27
|
+
Runs are written under `<iteration>/runs/seedcheck-*` and do not disturb the
|
|
28
|
+
iteration's own results. They share one compiler cache, `{cache}`, at
|
|
29
|
+
`<iteration>/cache/seedcheck`, emptied before the check and removed after it
|
|
30
|
+
unless `--keep`.
|
|
31
|
+
|
|
32
|
+
Exit codes:
|
|
33
|
+
0 OK: same seed reproduces, or its spread is small (also --scan-only)
|
|
34
|
+
1 WARNING: repeating a seed moves the objective by half or more of what
|
|
35
|
+
changing it does
|
|
36
|
+
2 FAIL: different seeds gave identical answers
|
|
37
|
+
3 refused or could not run: bad arguments, no GPU lease, a run failed
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
import os
|
|
41
|
+
import re
|
|
42
|
+
import sys
|
|
43
|
+
import shutil
|
|
44
|
+
import argparse
|
|
45
|
+
|
|
46
|
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
47
|
+
sys.path.insert(0, HERE)
|
|
48
|
+
|
|
49
|
+
import autoopt
|
|
50
|
+
import run_iteration
|
|
51
|
+
from autoopt import fail, fmt
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
# Sources of randomness worth naming, and the call that seeds each. Written
|
|
55
|
+
# without `\b`, which does not fire next to an underscore.
|
|
56
|
+
SOURCES = [
|
|
57
|
+
('python `random`', r'(?<![a-z0-9_])random\.(random|randint|randrange|choice|choices|shuffle|sample|uniform|gauss|normalvariate)\(',
|
|
58
|
+
r'random\.seed\('),
|
|
59
|
+
('numpy legacy global', r'(?<![a-z0-9_])(numpy|np)\.random\.(rand|randn|randint|random|random_sample|choice|shuffle|permutation|normal|standard_normal|uniform|binomial|poisson|exponential|beta|gamma|bytes)\(',
|
|
60
|
+
r'(numpy|np)\.random\.seed\('),
|
|
61
|
+
('numpy Generator', r'default_rng\(|(?<![a-z0-9_])(rng|generator|gen)\.(integers|random|normal|choice|permutation|shuffle|standard_normal|uniform)\(', r'default_rng\(\s*[^)\s]'),
|
|
62
|
+
('torch CPU', r'torch\.(rand|randn|randint|randperm|normal|bernoulli|multinomial|rand_like|randn_like|randint_like)\(|(?<![a-z0-9_])(?:F|torch\.nn\.functional)\.dropout\d?d?\(|nn\.Dropout',
|
|
63
|
+
r'torch\.manual_seed\('),
|
|
64
|
+
('torch CUDA', r'\.(cuda|to\([\'"]?cuda)', r'torch\.cuda\.manual_seed(_all)?\('),
|
|
65
|
+
('DataLoader shuffling', r'DataLoader\(', r'(worker_init_fn|generator)\s*='),
|
|
66
|
+
('scikit-learn', r'(train_test_split|KFold|RandomForest|KMeans)\(',
|
|
67
|
+
r'random_state\s*='),
|
|
68
|
+
]
|
|
69
|
+
|
|
70
|
+
# Randomness that cannot be seeded at all. Any of these in a benchmark puts a
|
|
71
|
+
# floor under the same-seed spread that no amount of seeding removes.
|
|
72
|
+
UNSEEDABLE = re.compile(r'SystemRandom\(|os\.urandom\(|uuid4\(|'
|
|
73
|
+
r'seed\s*=\s*(time\.time|int\(time)')
|
|
74
|
+
|
|
75
|
+
# A seeding call handed a literal, such as `random.seed(0)` in a benchmark
|
|
76
|
+
# that takes `--seed`. CONSTANT_SEED does not match this call form.
|
|
77
|
+
SEED_CALL = re.compile(
|
|
78
|
+
r'(?<![a-z0-9_])((?:random|numpy|np|torch|torch\.cuda)\.)?'
|
|
79
|
+
r'(manual_seed_all|manual_seed|default_rng|seed)\(\s*(\d+)\s*\)')
|
|
80
|
+
|
|
81
|
+
# A seed parameter handed a constant, such as `random_state=0`.
|
|
82
|
+
CONSTANT_SEED = re.compile(
|
|
83
|
+
r'(random_state|seed|random_seed)\s*=\s*(\d+)(?![\w.])')
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def strip_prose(text):
|
|
87
|
+
"""Blank out comments and string literals, keeping line numbers."""
|
|
88
|
+
|
|
89
|
+
out = re.sub(r'("""|\'\'\')(?:.|\n)*?\1',
|
|
90
|
+
lambda m: '\n' * m.group(0).count('\n'), text)
|
|
91
|
+
out = re.sub(r'#[^\n]*', '', out)
|
|
92
|
+
out = re.sub(r'"[^"\n]*"|\'[^\'\n]*\'', "''", out)
|
|
93
|
+
|
|
94
|
+
return out
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def scan(directory):
|
|
98
|
+
"""Read the benchmark's source for randomness it may not be seeding."""
|
|
99
|
+
|
|
100
|
+
findings, constants, unseedable = [], [], []
|
|
101
|
+
|
|
102
|
+
for base, _, names in os.walk(directory):
|
|
103
|
+
if '.git' in base.split(os.sep) or 'runs' in base.split(os.sep):
|
|
104
|
+
continue
|
|
105
|
+
|
|
106
|
+
for name in sorted(names):
|
|
107
|
+
if not name.endswith('.py'):
|
|
108
|
+
continue
|
|
109
|
+
|
|
110
|
+
path = os.path.join(base, name)
|
|
111
|
+
|
|
112
|
+
try:
|
|
113
|
+
with open(path) as infile:
|
|
114
|
+
text = infile.read()
|
|
115
|
+
except OSError:
|
|
116
|
+
continue
|
|
117
|
+
|
|
118
|
+
# A comment or docstring that mentions torch.cuda is not a use
|
|
119
|
+
# of it, so prose is blanked before the scan.
|
|
120
|
+
text = strip_prose(text)
|
|
121
|
+
relative = os.path.relpath(path, directory)
|
|
122
|
+
|
|
123
|
+
for label, uses, seeds in SOURCES:
|
|
124
|
+
if re.search(uses, text) and not re.search(seeds, text):
|
|
125
|
+
findings.append((relative, label))
|
|
126
|
+
|
|
127
|
+
for pattern in (CONSTANT_SEED, SEED_CALL):
|
|
128
|
+
for match in pattern.finditer(text):
|
|
129
|
+
line = text[:match.start()].count('\n') + 1
|
|
130
|
+
constants.append((relative, line, match.group(0)))
|
|
131
|
+
|
|
132
|
+
for match in UNSEEDABLE.finditer(text):
|
|
133
|
+
line = text[:match.start()].count('\n') + 1
|
|
134
|
+
unseedable.append((relative, line,
|
|
135
|
+
match.group(0).rstrip('(')))
|
|
136
|
+
|
|
137
|
+
return findings, constants, unseedable
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def one_run(config, iteration, seed, label, cache):
|
|
141
|
+
"""Run the benchmark once into its own directory, and read the result."""
|
|
142
|
+
|
|
143
|
+
run_dir = os.path.join(iteration, 'runs', label)
|
|
144
|
+
shutil.rmtree(run_dir, ignore_errors=True)
|
|
145
|
+
|
|
146
|
+
code, seconds = run_iteration.execute(config['command'], iteration, seed,
|
|
147
|
+
run_dir, config.get('timeout_seconds'),
|
|
148
|
+
src=autoopt.checkout_dir(autoopt.resolve(os.path.dirname(
|
|
149
|
+
os.path.dirname(iteration))), os.path.basename(iteration), config),
|
|
150
|
+
cache=cache)
|
|
151
|
+
|
|
152
|
+
record, error = run_iteration.load_metrics(run_dir, config)
|
|
153
|
+
|
|
154
|
+
if code != 0 or record is None:
|
|
155
|
+
fail('the run with seed {} failed ({}); see {}/log.txt'.format(seed,
|
|
156
|
+
error or 'exit code {}'.format(code), run_dir))
|
|
157
|
+
|
|
158
|
+
return record['objective'], seconds
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def main(argv=None):
|
|
162
|
+
parser = argparse.ArgumentParser(description=__doc__,
|
|
163
|
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
164
|
+
|
|
165
|
+
parser.add_argument('iteration', help='autooptimize/iterations/<id>, '
|
|
166
|
+
'usually the baseline')
|
|
167
|
+
parser.add_argument('--seed', type=int, help='the seed to repeat '
|
|
168
|
+
'(default: the search\'s first seed)')
|
|
169
|
+
parser.add_argument('--repeats', type=int, default=2,
|
|
170
|
+
help='runs on the repeated seed (default: %(default)s)')
|
|
171
|
+
parser.add_argument('--others', type=int, default=2,
|
|
172
|
+
help='runs on further seeds (default: %(default)s)')
|
|
173
|
+
parser.add_argument('--scan-only', action='store_true',
|
|
174
|
+
help='read the source and stop, running nothing')
|
|
175
|
+
parser.add_argument('--keep', action='store_true',
|
|
176
|
+
help='keep the runs/seedcheck-* directories')
|
|
177
|
+
|
|
178
|
+
args = parser.parse_args(argv)
|
|
179
|
+
|
|
180
|
+
iteration = os.path.abspath(os.path.expanduser(args.iteration))
|
|
181
|
+
|
|
182
|
+
if not os.path.isdir(iteration):
|
|
183
|
+
fail('not a directory: {}'.format(iteration))
|
|
184
|
+
|
|
185
|
+
root = autoopt.resolve(os.path.dirname(os.path.dirname(iteration)))
|
|
186
|
+
config = autoopt.load_config(root)
|
|
187
|
+
seed = args.seed if args.seed is not None else config['seed_base']
|
|
188
|
+
|
|
189
|
+
# In repository mode the benchmark is the harness; the package in src/
|
|
190
|
+
# takes its seed from the harness, and scanning its tests would cry wolf.
|
|
191
|
+
source = os.path.join(root, 'harness') if config.get('repo') else iteration
|
|
192
|
+
|
|
193
|
+
print('reading {} for unseeded randomness'.format(source))
|
|
194
|
+
findings, constants, unseedable = scan(source)
|
|
195
|
+
|
|
196
|
+
for relative, label in findings:
|
|
197
|
+
print(' ? {}: uses {} and never seeds it'.format(relative, label))
|
|
198
|
+
|
|
199
|
+
for relative, line, name in unseedable:
|
|
200
|
+
print(' ? {}:{}: `{}` cannot be seeded at all, so it puts a floor '
|
|
201
|
+
'under the same-seed spread below.'.format(relative, line, name))
|
|
202
|
+
|
|
203
|
+
if not (findings or unseedable):
|
|
204
|
+
print(' every source it recognizes is seeded')
|
|
205
|
+
|
|
206
|
+
for relative, line, text in constants:
|
|
207
|
+
print(' ? {}:{}: `{}` is a literal. If that is the run seed it has '
|
|
208
|
+
'to come from --seed, or every run is the same run.'.format(
|
|
209
|
+
relative, line, text))
|
|
210
|
+
|
|
211
|
+
if args.scan_only:
|
|
212
|
+
return 0
|
|
213
|
+
|
|
214
|
+
run_iteration.check_lease(config)
|
|
215
|
+
|
|
216
|
+
print('\nrunning seed {} {} times, then {} further seed(s)'.format(seed,
|
|
217
|
+
args.repeats, args.others))
|
|
218
|
+
|
|
219
|
+
# One cache for every run of the check: they all run the same code, and
|
|
220
|
+
# a fresh one keeps a cache from before an edit out of the comparison.
|
|
221
|
+
cache = os.path.join(iteration, 'cache', 'seedcheck')
|
|
222
|
+
shutil.rmtree(cache, ignore_errors=True)
|
|
223
|
+
os.makedirs(cache)
|
|
224
|
+
|
|
225
|
+
same = []
|
|
226
|
+
for index in range(args.repeats):
|
|
227
|
+
value, seconds = one_run(config, iteration, seed,
|
|
228
|
+
'seedcheck-same-{}'.format(index), cache)
|
|
229
|
+
same.append(value)
|
|
230
|
+
print(' seed {} (run {}): {} in {:.1f} min'.format(seed, index + 1,
|
|
231
|
+
fmt(value), seconds / 60.0))
|
|
232
|
+
|
|
233
|
+
others = []
|
|
234
|
+
for index in range(args.others):
|
|
235
|
+
other = seed + 1 + index
|
|
236
|
+
value, seconds = one_run(config, iteration, other,
|
|
237
|
+
'seedcheck-other-{}'.format(index), cache)
|
|
238
|
+
others.append(value)
|
|
239
|
+
print(' seed {}: {} in {:.1f} min'.format(other, fmt(value),
|
|
240
|
+
seconds / 60.0))
|
|
241
|
+
|
|
242
|
+
same_spread = (max(same) - min(same)) if len(same) > 1 else 0.0
|
|
243
|
+
across = same[:1] + others
|
|
244
|
+
across_spread = (max(across) - min(across)) if len(across) > 1 else 0.0
|
|
245
|
+
|
|
246
|
+
print('\nsame-seed spread {}'.format(fmt(same_spread)))
|
|
247
|
+
print('between-seed spread {}'.format(fmt(across_spread)))
|
|
248
|
+
|
|
249
|
+
verdict = 0
|
|
250
|
+
runs = 'from {} runs on one seed and {} distinct seeds'.format(
|
|
251
|
+
args.repeats, args.others + 1)
|
|
252
|
+
|
|
253
|
+
if across_spread == 0:
|
|
254
|
+
print('\nFAIL: different seeds gave identical answers. The seed is '
|
|
255
|
+
'not reaching the randomness, so the runs are one number '
|
|
256
|
+
'repeated and the noise band will be zero. Find what is still '
|
|
257
|
+
'fixed -- a hard-coded random_state is the usual cause -- before '
|
|
258
|
+
'running the baseline.')
|
|
259
|
+
verdict = 2
|
|
260
|
+
elif same_spread == 0:
|
|
261
|
+
print('\nOK: the same seed reproduces exactly, and different seeds '
|
|
262
|
+
'move the objective. Differences between iterations are '
|
|
263
|
+
'attributable to the idea.')
|
|
264
|
+
else:
|
|
265
|
+
ratio = same_spread / across_spread
|
|
266
|
+
|
|
267
|
+
print('\nRepeating a seed moves the objective by {:.0%} of what '
|
|
268
|
+
'changing it does ({}).'.format(ratio, runs))
|
|
269
|
+
|
|
270
|
+
if ratio >= 0.5:
|
|
271
|
+
print('\nWARNING: that is most of the variation, so the seed '
|
|
272
|
+
'controls less than half of what moves the objective. A '
|
|
273
|
+
'median over seeds is then averaging noise the search cannot '
|
|
274
|
+
'attribute to any idea. If the seed is meant to vary the '
|
|
275
|
+
'result, look for the unseeded source; either way, expect to '
|
|
276
|
+
'need more runs per iteration.')
|
|
277
|
+
verdict = 1
|
|
278
|
+
elif ratio > 0.2:
|
|
279
|
+
print('\nWorth chasing before the search starts: it widens the '
|
|
280
|
+
'noise band, and the noise band is the keep rule\'s margin.')
|
|
281
|
+
else:
|
|
282
|
+
print('\nOK: most of what varies is the seed, so differences '
|
|
283
|
+
'between iterations are attributable to the idea.')
|
|
284
|
+
|
|
285
|
+
# references/step2-baseline.md: on a fixed input the ratio is chance.
|
|
286
|
+
print('\nIf the benchmark runs a fixed input, so the seed changes '
|
|
287
|
+
'nothing (a timing harness), both spreads are machine noise and '
|
|
288
|
+
'this verdict is about noise, not the seed. The noise band is '
|
|
289
|
+
'still right; say so in the README. Letting the seed choose the '
|
|
290
|
+
'input or its order makes the runs independent repeats.')
|
|
291
|
+
|
|
292
|
+
print('\nBoth spreads are estimated from a handful of runs and are '
|
|
293
|
+
'themselves noisy. Near the line, re-run with --repeats 5 '
|
|
294
|
+
'--others 5 before believing either.')
|
|
295
|
+
|
|
296
|
+
if not args.keep:
|
|
297
|
+
for name in os.listdir(os.path.join(iteration, 'runs')):
|
|
298
|
+
if name.startswith('seedcheck-'):
|
|
299
|
+
shutil.rmtree(os.path.join(iteration, 'runs', name),
|
|
300
|
+
ignore_errors=True)
|
|
301
|
+
shutil.rmtree(cache, ignore_errors=True)
|
|
302
|
+
|
|
303
|
+
return verdict
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def logged():
|
|
307
|
+
"""main(), its output copied into setup/seeding.log when it checks the
|
|
308
|
+
baseline, as step 2 does."""
|
|
309
|
+
|
|
310
|
+
target = next((arg for arg in sys.argv[1:] if not arg.startswith('-')), '')
|
|
311
|
+
target = os.path.abspath(os.path.expanduser(target))
|
|
312
|
+
root = os.path.dirname(os.path.dirname(target))
|
|
313
|
+
|
|
314
|
+
# Every exit that is not a verdict -- argparse's 2, fail()'s 1 -- becomes
|
|
315
|
+
# 3, so 1 and 2 only ever mean WARNING and FAIL.
|
|
316
|
+
def verdict():
|
|
317
|
+
try:
|
|
318
|
+
return main()
|
|
319
|
+
except SystemExit as error:
|
|
320
|
+
return 3 if error.code not in (0, None) else 0
|
|
321
|
+
|
|
322
|
+
if os.path.basename(target) != '0' or not os.path.exists(os.path.join(
|
|
323
|
+
root, 'config.json')):
|
|
324
|
+
return verdict()
|
|
325
|
+
|
|
326
|
+
with autoopt.StepLog(root, 'seeding') as log:
|
|
327
|
+
code = verdict()
|
|
328
|
+
if code:
|
|
329
|
+
raise SystemExit(code)
|
|
330
|
+
return code
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
if __name__ == '__main__':
|
|
334
|
+
sys.exit(logged())
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Cold first-call time of one or more versions, each run on an empty cache.
|
|
3
|
+
|
|
4
|
+
python3 cold.py --side b120=DIR_A --side b126=DIR_B \\
|
|
5
|
+
--cmd 'python3 first_call.py --src {src}' --scratch $DIR/cold --reps 2
|
|
6
|
+
|
|
7
|
+
Every run gets a new, empty compiler cache created under `--scratch` (not
|
|
8
|
+
`/tmp`, which another process may clean mid-run) and passed as
|
|
9
|
+
`NUMBA_CACHE_DIR`, `TRITON_CACHE_DIR` and `TORCHINDUCTOR_CACHE_DIR`. Nothing
|
|
10
|
+
is deleted: the caches stay in `--scratch`. The runner's, under
|
|
11
|
+
`iterations/<id>/check/cold/`, are reclaimed by `autoopt.py prune`.
|
|
12
|
+
The sides alternate order each repetition, so a slow moment does not land on
|
|
13
|
+
one side.
|
|
14
|
+
|
|
15
|
+
The command prints the first call's seconds as the last number on its last
|
|
16
|
+
line of stdout. A single cold run is noisy by seconds: take two or more
|
|
17
|
+
repetitions.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
import os
|
|
21
|
+
import sys
|
|
22
|
+
import json
|
|
23
|
+
import argparse
|
|
24
|
+
import tempfile
|
|
25
|
+
import statistics
|
|
26
|
+
|
|
27
|
+
from probe_run import run_probe
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def main(argv=None):
|
|
31
|
+
parser = argparse.ArgumentParser(description=__doc__,
|
|
32
|
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
33
|
+
parser.add_argument('--side', action='append', required=True,
|
|
34
|
+
help='NAME=DIRECTORY; repeat for each version')
|
|
35
|
+
parser.add_argument('--cmd', required=True, help='{src} and {side} are '
|
|
36
|
+
'substituted')
|
|
37
|
+
parser.add_argument('--scratch', required=True, help='a directory inside '
|
|
38
|
+
'the iteration directory for the empty caches')
|
|
39
|
+
parser.add_argument('--reps', type=int, default=2)
|
|
40
|
+
parser.add_argument('--env', action='append', default=[],
|
|
41
|
+
help='KEY=VALUE for every run; repeatable')
|
|
42
|
+
parser.add_argument('--regex', help='a pattern whose first group is the '
|
|
43
|
+
'seconds on the command\'s last line (default: its last number)')
|
|
44
|
+
parser.add_argument('--json', action='store_true')
|
|
45
|
+
args = parser.parse_args(argv)
|
|
46
|
+
|
|
47
|
+
sides = []
|
|
48
|
+
|
|
49
|
+
for item in args.side:
|
|
50
|
+
name, _, directory = item.partition('=')
|
|
51
|
+
|
|
52
|
+
if not name or not os.path.isdir(directory):
|
|
53
|
+
sys.exit('--side takes NAME=DIRECTORY; got {!r}'.format(item))
|
|
54
|
+
|
|
55
|
+
sides.append((name, os.path.abspath(directory)))
|
|
56
|
+
|
|
57
|
+
os.makedirs(args.scratch, exist_ok=True)
|
|
58
|
+
times = {name: [] for name, _ in sides}
|
|
59
|
+
|
|
60
|
+
for rep in range(args.reps):
|
|
61
|
+
order = sides if rep % 2 == 0 else sides[::-1]
|
|
62
|
+
|
|
63
|
+
for name, directory in order:
|
|
64
|
+
cache = tempfile.mkdtemp(prefix='cold-{}-'.format(name),
|
|
65
|
+
dir=os.path.abspath(args.scratch))
|
|
66
|
+
|
|
67
|
+
if os.listdir(cache):
|
|
68
|
+
sys.exit('{} is not empty'.format(cache))
|
|
69
|
+
|
|
70
|
+
times[name].append(run_probe(args.cmd, directory, name, cache,
|
|
71
|
+
args.env, args.regex))
|
|
72
|
+
print('rep {} {:>12} {:.4g} s'.format(rep + 1, name,
|
|
73
|
+
times[name][-1]), flush=True)
|
|
74
|
+
|
|
75
|
+
result = {name: {'runs': runs, 'median': statistics.median(runs)}
|
|
76
|
+
for name, runs in times.items()}
|
|
77
|
+
|
|
78
|
+
if args.json:
|
|
79
|
+
print(json.dumps(result, indent='\t'))
|
|
80
|
+
else:
|
|
81
|
+
for name, record in result.items():
|
|
82
|
+
print('{:>12} median {:.4g} s runs {}'.format(name,
|
|
83
|
+
record['median'], ', '.join('{:.4g}'.format(t)
|
|
84
|
+
for t in record['runs'])))
|
|
85
|
+
|
|
86
|
+
return 0
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
if __name__ == '__main__':
|
|
90
|
+
sys.exit(main())
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
# auto-optimize-code dashboard
|
|
2
|
+
|
|
3
|
+
Operating it: `references/dashboard.md`, under the skill root two levels
|
|
4
|
+
above this directory.
|
|
5
|
+
|
|
6
|
+
Requirements: IPython for `show()`; plotly for the page's charts and for
|
|
7
|
+
`--export`; psutil optional (without it the host summary and process table
|
|
8
|
+
say so).
|
|
9
|
+
|
|
10
|
+
## Files
|
|
11
|
+
|
|
12
|
+
| File | Owns |
|
|
13
|
+
|---|---|
|
|
14
|
+
| `scan.py` | `RunScanner`: `snapshot()` (state.json), `readmes()` (readmes/<id>.json), `diffs()` (diffs/<id>.json), `hardware.resources()` (resources.json), and `classify`/`target(cmdline, pid)` for the process table. `scan.py <root>` prints the snapshot |
|
|
15
|
+
| `gpu_scan.py` | GPUs (three queries run side by side through one NVML session per publisher, `libnvidia-ml.so.1` by ctypes, since a new nvidia-smi process stalls cudaMalloc in every CUDA process on the host; nvidia-smi only where NVML will not load, or where `GPU_SCAN_NVML` names a file that does not; the power limit read once per session and per-process SM once a minute, since those NVML calls also hold cudaMalloc while they run; each query shared by every publisher of this user on the host through `shared_sample()` in `/dev/shm/dashboard-monitor-<uid>/`, keyed by the nvidia-smi path; an answer is dated when its call started, a publisher waits up to `SHARED_WAIT` (1.5 s) for a call under way, and a failed call keeps the last good answer), host and its name, lease holders (`GPU_LEASE_DIR`, optional), this search's processes; `autoopt_monitor.py` is in `SELF_MARKERS` |
|
|
16
|
+
| `monitor_writer.py` | the scan loop, the hardware thread, asset install, rounding, `writer.pid`, the writer index, the per-directory writer lock (`claim()`, in the same `/dev/shm` directory: one writer per payload directory on a host, released by the kernel at exit), and the heartbeat `writer.host` beside the payload for writers on other hosts (`yields_to()`). `monitor_writer.py <root> --out DIR [--interval 20] [--resource-interval 3] [--skip-unchanged]`, started by `autoopt_monitor.py`. `--skip-unchanged` (off) rewrites `state.json` only when a scan changed it; the page's pulse still reads `state.json`'s `generated`, so the flag stays off until the page reads `writer.scanned` in `resources.json` (the time of the last good scan) instead |
|
|
17
|
+
| `autoopt_monitor.py` | `show()`, `make_notebook()`, `--start/--status/--stop/--export`; the notebook entry point |
|
|
18
|
+
| `static/index.html`, `dashboard.css`, `dashboard.js` | the page, in matching `==== SECTION: <name> ====` blocks |
|
|
19
|
+
|
|
20
|
+
`dashboard.js` sections: `core` through `gpu` are the generic monitor
|
|
21
|
+
(`plots` holds `categoryChips`); `lineage-tree` and `expandable-log` are
|
|
22
|
+
generic widgets; `search`, `objective`, `observers`, `validation`,
|
|
23
|
+
`run-table`, `log`, `tree`, `summary-autoopt`, `sidebar-autoopt` and
|
|
24
|
+
`polling` are this dashboard's. `CATCH_ALL` is
|
|
25
|
+
`MISC`. The page is an ES module and must stay one.
|
|
26
|
+
|
|
27
|
+
## The page
|
|
28
|
+
|
|
29
|
+
| Panel | Reads | Behavior to keep |
|
|
30
|
+
|---|---|---|
|
|
31
|
+
| Summary band | `result.json`, `resources.json` | settled, frontier, gain, rounds, frontier steps, runs per iteration, GPUs in use, subagents working |
|
|
32
|
+
| Category chips | `categories` | `ROOT`, then the categories `autoopt.py` allows (`autoopt.categories_for`), empty ones included, and any other an iteration used. Ten hues (`--cat-0` to `--cat-9`), one for each of the idea miner's ten categories, since shape carries status; `MISC` is the grey catch-all. A click emphasizes (several may be on; a second click clears); the `.eye` dot hides the category from charts and log and dims it in the tree |
|
|
33
|
+
| GPUs | `gpu_scan` | one card per device: utilization sparkline, lease holder, this search's processes. A sample with no GPUs after one with GPUs keeps the last cards; a reading older than 30 s (or three hardware cadences) dims them and the host summary gives its age (`gpu_sampled_at`). The strip's height only grows while mounted, and its drag bar is left alone while the strip is not laid out. Its Live toggle (off on every load) writes `live.json` beside the payload every 3 s through the Contents API while the tab is showing and polls every second; while that file is under 10 s old the publisher samples every second, straight from NVML without the shared cache (nvidia-smi keeps it), and reports `writer.live`. Per-process SM stays on its 60 s clock, and the sparkline history on the slow one |
|
|
34
|
+
| Objective by iteration | `result.json`, `meta.json` | medians, the frontier staircase, in-flight iterations on the floor. *Stage boundaries* (on): a purple dashed line between neighbors whose idea-miner stage (`mining_stage`; the baseline is 0) differs, so a bump after a fresh batch of ideas shows; in a search with no stages, a *depth boundary* between neighbors whose tree generation differs, and the legend says which. *Confidence intervals* (off): a capped dotted whisker from `scan.median_ci` (95% percentile bootstrap of the median, 2,000 resamples, seed 0), none under two runs. *All runs*: every seed, size 4, opacity 0.3, muted hue. The hover adds the code change: `lines` `+`/`−` and each nonzero file count, in the diff colors, and the miner stage |
|
|
35
|
+
| Abandoned iterations | `iterations/<id>.abandoned/meta.json`, `README.md` | an empty fork set aside (`references/resume.md`): a thin ✕ (`x-thin-open`) in its category's hue at its own x and the baseline's value, keyed in the legend; follows the chips and *hide failed*; in no count, tree, table or log (scan.py `abandoned`) |
|
|
36
|
+
| Subagent working | `result.json`, `README.md`, mtimes | measured, no `README.md`, a file written within the hour: larger point, thick ring in its category's color, counted in the summary band |
|
|
37
|
+
| Every run | `result.json` | one row per seed, failed ones included; a broken gate is red; `note` cut at 240 characters; sortable, searchable, status and type filters, 40 rows a page, newest first |
|
|
38
|
+
| Observers | `result.json` | one chart each, reordered by its grip |
|
|
39
|
+
| External validation | `config.json`, `validations/round-<N>.json` | one small multiple per numeric measure over rounds; string measures only in the sidebar card. "Not a gate" above the panels, in the card and in every hover. Follows neither selection nor chips |
|
|
40
|
+
| Search tree | `meta.json` parents, `readmes/<id>.json` | one lineage, a generation strip; height follows the drag handle (double-click: 430 px); a node click opens its README and numbers, a second closes it |
|
|
41
|
+
| Iteration log | `meta.json`, `result.json`, `README.md`, `unit-tests/result.json`, `validation/record.json`, `repo.git` | newest first. An open entry leads with its code change against its parent (`diffstat`: lines `+`/`−`, files modified, added, deleted, in `--diff-add`, `--diff-del`, `--diff-mod`, GitHub's dark-theme colors), then the README excerpt; a cut excerpt (`notes_cut`) ends in SHOW MORE, which fetches `readmes/<id>.json` and shows it without the title, metadata line and run table, until SHOW LESS. The detail's GATE, OBS and SEED labels take `--tag-gate`, `--tag-obs`, `--tag-seed`. Time split: total (`created` to the last of those files and `report.txt`), runs (summed, divided by GPUs shared), unit tests, validation, and subagent work as the remainder |
|
|
42
|
+
| Processes | psutil | pid, kind, iteration, CPU, RSS, elapsed |
|
|
43
|
+
| Ended line and stage strip | `after` in the snapshot (`RunScanner.after`): `ended.json`, `final.json`, `stages.collect` | the topbar's ended line (hidden while the search runs) and the six-stage strip under the chips; plain text. The `toolchain` row of an open log entry comes from `meta.json` (`references/dashboard.md`) |
|
|
44
|
+
|
|
45
|
+
| Mark | Means |
|
|
46
|
+
|---|---|
|
|
47
|
+
| hue | category |
|
|
48
|
+
| full-strength hue | frontier (2 px larger on a chart), root (tree), selected or emphasized; `MISC` strong is `--cat-other-strong` |
|
|
49
|
+
| circle / ✕ / hollow circle / hollow square | passed / gate failed / a run errored / fewer runs than `runs_per_iteration` |
|
|
50
|
+
| hollow diamond on the floor, dashed ring in the tree | running |
|
|
51
|
+
| dotted pink staircase | the frontier |
|
|
52
|
+
| `+N` dashed tally | condensed off-frontier iterations; hover gives passed count and best |
|
|
53
|
+
| muted green / red validation point | that round's script reported `ok` true / false |
|
|
54
|
+
|
|
55
|
+
Lasso or box-select links every chart and dims the tree; **Clear selection**
|
|
56
|
+
or a double-click drops it. A click on a tree node, an observer chart's
|
|
57
|
+
point or an opened log entry pins that iteration: its rows in *Every run* are
|
|
58
|
+
outlined and scrolled to, and a second click drops the pin. A click on a point
|
|
59
|
+
of the objective chart (a median or a run's dot) opens that iteration's code
|
|
60
|
+
change under the chart, and pins nothing: a second click, or *close*, shuts it.
|
|
61
|
+
`x log` / `y log`
|
|
62
|
+
override the automatic log axis and count the points it hides; the
|
|
63
|
+
objective chart's `x log` is manual only (`(1 hidden)`: the baseline at x = 0).
|
|
64
|
+
|
|
65
|
+
Scale (`LINEAGE_MANY`, `markStyle`, `DENSITY_LIMIT`): past 120 iterations
|
|
66
|
+
the lineage draws roots, the frontier path, anything running and the 12
|
|
67
|
+
newest, the rest one `+N` per parent and generation, nodes at least 34 px
|
|
68
|
+
apart. Past 500 points markers are size 5 at opacity 0.3; past 5,000 medians
|
|
69
|
+
become a density and *All runs* is not drawn. Hover README excerpts shrink
|
|
70
|
+
from 600 to 160 characters.
|
|
71
|
+
|
|
72
|
+
## The payload
|
|
73
|
+
|
|
74
|
+
| File | Written | Page fetches |
|
|
75
|
+
|---|---|---|
|
|
76
|
+
| `state.json` | every full scan (`interval`, 20 s) | every state poll |
|
|
77
|
+
| `resources.json` | every hardware sample (`resource_interval`, 3 s, or as long as the GPU query takes), on its own thread | every hardware poll |
|
|
78
|
+
| `readmes/<id>.json` | when that iteration's `README.md` mtime moves; the whole file, where `state.json` carries an excerpt | when its tree node's panel opens, and again when the excerpt changes |
|
|
79
|
+
| `diffs/<id>.json` | once per (parent commit, commit) pair, newest iteration first, at most `DIFF_BUDGET` seconds of git per scan; settled iterations with a parent only | when its point on the objective chart is clicked; a failed read is tried again after 10 s |
|
|
80
|
+
|
|
81
|
+
`state.json` carries every iteration (its `objective.ci` is `median_ci`'s
|
|
82
|
+
bootstrap interval, cached per set of run values), the root, round and roots,
|
|
83
|
+
the frontier and its steps, and `categories`, the fixed list from
|
|
84
|
+
`autoopt.py`, which fixes each category's color: sorted, `MISC` the gray
|
|
85
|
+
catch-all, `ROOT` (iteration 0, whatever its `meta.json` says) a fixed light
|
|
86
|
+
neutral outside the slots. The lineage is built and condensed in the page from
|
|
87
|
+
`iterations`; the payload carries no tree. `validation` is None for a
|
|
88
|
+
search without an external validation, else its configured `measures`,
|
|
89
|
+
`units` (config.json's, then each round's `validation.json`), `note`,
|
|
90
|
+
`approved` and one record per `validations/round-<N>.json`, oldest
|
|
91
|
+
first.
|
|
92
|
+
|
|
93
|
+
An iteration whose files raise in the scanner (a malformed `result.json`)
|
|
94
|
+
becomes a row with `status` `unreadable` and its `error`, counted as
|
|
95
|
+
settled and never on the frontier; `state.json`'s `unreadable` lists them
|
|
96
|
+
as `{id, error}`.
|
|
97
|
+
|
|
98
|
+
`resources.json` carries `psutil` (False when it is not installed),
|
|
99
|
+
`gpu_sampled_at` (when the last GPU query that answered started; older than
|
|
100
|
+
`timestamp` while the query is slow or failing, and a history sample repeats
|
|
101
|
+
no reading), `hostname` (the host the GPUs are on, which the host summary
|
|
102
|
+
leads with), and `writer`, the writer's report on itself: `interval`,
|
|
103
|
+
`resource_interval`, `state_cadence` and `resource_cadence` (the longest of
|
|
104
|
+
the last five measured gaps, in seconds, None until two have happened),
|
|
105
|
+
and `scan_error` with `scan_error_at`, the last failed scan's reason
|
|
106
|
+
(including the message `autoopt.fail()` prints before its SystemExit),
|
|
107
|
+
cleared by the next good scan. The page's pulse ages `state.json` alone
|
|
108
|
+
against `max(interval, state_cadence)`: live under 2.5 of those, stale
|
|
109
|
+
under 10, down beyond. A `scan_error` turns it stale and is shown beside
|
|
110
|
+
it with the writer log; unreadable iterations are named there too.
|
|
111
|
+
|
|
112
|
+
`writer.pid` holds five lines: PID, search, code stamp, the two intervals,
|
|
113
|
+
and the process start time (`/proc/<pid>/stat` field 22, else psutil's
|
|
114
|
+
`create_time`). `writer_info` accepts it only while that PID's command line
|
|
115
|
+
names `monitor_writer.py` and its start time matches, so a PID the kernel
|
|
116
|
+
reused is never signaled. It is written whole (a temporary file, then a
|
|
117
|
+
rename). SIGTERM raises out of a scan or a sleep; in `finally` the pidfile
|
|
118
|
+
and index entry are removed only while the pidfile still names this
|
|
119
|
+
process. The index entry is
|
|
120
|
+
`~/.cache/autoopt-monitor/<out_dir slug>-<8 hex of its SHA-1>.writer`.
|
|
121
|
+
`autoopt.py status` (`live_publishers`) reads the pidfiles and, where /proc
|
|
122
|
+
exists, also finds writers of the search by process, so a writer whose
|
|
123
|
+
pidfile is gone still counts as running.
|
|
124
|
+
|
|
125
|
+
`start_writer` first stops every writer into the directory but the
|
|
126
|
+
pidfile's (`writers_into`: by process, from any copy of the script) and
|
|
127
|
+
every writer of the search into another directory (`publishers`, the same
|
|
128
|
+
way), and returns once the new writer's `state.json` and `resources.json`
|
|
129
|
+
both exist, so it blocks for one hardware sample. When its writer loses the
|
|
130
|
+
lock to a start racing it, it returns the winner's pid. `--start`
|
|
131
|
+
without `--out` takes the directory a live writer of the search publishes
|
|
132
|
+
into, so a second `--start` reports that writer. A
|
|
133
|
+
handover to another search deletes `state.json` and `resources.json` and
|
|
134
|
+
renames `readmes/` and `diffs/` to `readmes.<YYYYmmdd-HHMMSS>-<pid>` and
|
|
135
|
+
`diffs.<…>`; nothing deletes those.
|
|
136
|
+
The page fetches `readmes/<id>.json` only for a row with `has_readme`.
|
|
137
|
+
|
|
138
|
+
`diffs/<id>.json` is `{id, parent, files}`, `files` from `scan.parse_patch`:
|
|
139
|
+
`path`, `old` (before a rename), `status` (A, D, M, R), `binary`, `additions`,
|
|
140
|
+
`deletions`, `truncated` and `hunks` (`{old, new, head, rows}`, a row
|
|
141
|
+
`[' '|'+'|'-', text]`). The patch is `git diff -M` from the merge base, as
|
|
142
|
+
`diffstat` is. A line is cut at `PATCH_LINE_CHARS` (1,000); a file past
|
|
143
|
+
`PATCH_FILE_ROWS` (2,000) rows, or after `PATCH_BYTES` (400,000) bytes of
|
|
144
|
+
earlier files, keeps its counts and no hunks. The page draws it in two
|
|
145
|
+
columns, old on the left and new on the right, with no syntax highlighting;
|
|
146
|
+
below 640 px wide the table scrolls sideways.
|
|
147
|
+
|
|
148
|
+
A settled row with a parent carries `diffstat`, `[lines added, lines
|
|
149
|
+
deleted, files added, files deleted, files modified]`, from `git diff --raw
|
|
150
|
+
--numstat -M <parent commit>...<commit>` in `repo.git`: counted from the
|
|
151
|
+
merge base; a rename or mode change is a modification,
|
|
152
|
+
a binary file adds no lines. The baseline, in-flight iterations and a pair git
|
|
153
|
+
cannot read have none. Each pair is cached for the writer's life; a scan
|
|
154
|
+
spends at most `DIFF_BUDGET` (2 s) on new pairs, newest first, so a long
|
|
155
|
+
search fills in over a few polls. `notes_cut` is present, and true, only
|
|
156
|
+
when the excerpt was cut.
|
|
157
|
+
`show()` URL-encodes each segment of the payload directory.
|
|
158
|
+
|
|
159
|
+
Without `/proc` (macOS) writer discovery uses psutil, and finds nothing
|
|
160
|
+
without it. Jupyter servers are read from
|
|
161
|
+
`jupyter_core.paths.jupyter_runtime_dir()`, `~/.local/share/jupyter/runtime`
|
|
162
|
+
and `$JUPYTER_RUNTIME_DIR`.
|
|
163
|
+
|
|
164
|
+
`SOURCES` in `monitor_writer.py` includes `../autoopt.py`, so a change to the
|
|
165
|
+
runner's scoring replaces a running writer.
|