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,367 @@
1
+ #!/usr/bin/env python3
2
+ """Write the optimization PR's tables from an ended search.
3
+
4
+ python3 opt_pr_tables.py WORK [--id best] [--out DIR]
5
+
6
+ DIR defaults to `WORK/ship/pr-optimization`. Everything comes from what the
7
+ search recorded; nothing is measured again:
8
+
9
+ branch.json the branch the PR targets, the commit it builds on, the
10
+ kept changes in order, the documents chosen at step 5
11
+ changes.tsv one row per kept change: id, title, files, +, -
12
+ files.tsv one row per file the PR changes: path, +, -
13
+ performance.tsv the objective and each observer: medians and ranges of
14
+ the first measurement and of the kept code, and runs
15
+ gates.tsv each output check: name, op, threshold, worst, runs
16
+ checks.json the compare check's summary and the first-call times
17
+ paired.json the paired timing at the end, or null
18
+ machine.json the machine the search ran on, or null
19
+ fragments.json each kept change's own name and description
20
+ (`## Change` in its notes.md), for the prose template
21
+ tests.json the unit-test record of the kept code and its counts,
22
+ read from its log (`--tests-format` for another runner)
23
+ messages/<id>.txt the commit message of each kept change, from its
24
+ `## Commit message` with `after.commit_trailer`; an
25
+ existing file is kept, a missing message is a skeleton
26
+
27
+ `opt_pr_body.py DIR --template` then writes the prose skeleton. Standard
28
+ library only.
29
+ """
30
+
31
+ import os
32
+ import re
33
+ import sys
34
+ import json
35
+ import argparse
36
+ import statistics
37
+
38
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
39
+
40
+ import autoopt
41
+ import publish
42
+
43
+ KEYS = ('passed', 'skipped', 'failed', 'errors')
44
+ # Test-runner summaries, tried in order; the first that matches a line of
45
+ # the log gives the counts. Each regex has one group, an integer, and the
46
+ # integers of every matching line are added.
47
+ LOG_FORMATS = (
48
+ ('pytest', {'passed': r'\b(\d+) passed\b', 'failed': r'\b(\d+) failed\b',
49
+ 'skipped': r'\b(\d+) skipped\b', 'errors': r'\b(\d+) errors?\b'},
50
+ r'^=+ .*\b(passed|failed|errors?)\b.* in [0-9.]+s'),
51
+ ('testthat', {'passed': r'\bPASS (\d+)\b', 'failed': r'\bFAIL (\d+)\b',
52
+ 'skipped': r'\bSKIP (\d+)\b'}, r'\[ FAIL \d+ \|'),
53
+ ('shell', {'passed': r'(?i)\b(\d+) (?:tests? )?passed\b',
54
+ 'failed': r'(?i)\b(\d+) (?:failures?|failed)\b',
55
+ 'skipped': r'(?i)\b(\d+) skipped\b', 'errors': r'(?i)\b(\d+) errors?\b'},
56
+ r'(?i)\b\d+ (?:tests? )?passed\b'),
57
+ )
58
+ SKELETON = ('<<FILL: an imperative subject of at most 72 characters, no '
59
+ 'closing period>>\n\n<<FILL: what this change does and what stays the '
60
+ 'same, wrapped at 72 columns>>\n')
61
+
62
+
63
+ def given_format(items):
64
+ """`--tests-format KEY=REGEX` items as one LOG_FORMATS entry, KEY one of
65
+ KEYS or `total` (passed is then total less failed, errors and skipped);
66
+ each REGEX has one group, an integer. `fail`s on a malformed item."""
67
+
68
+ patterns = {}
69
+
70
+ for item in items:
71
+ key, equals, pattern = item.partition('=')
72
+
73
+ if not equals or key not in KEYS + ('total',):
74
+ autoopt.fail('--tests-format takes KEY=REGEX, KEY one of {} or '
75
+ 'total; got {!r}'.format(', '.join(KEYS), item))
76
+
77
+ try:
78
+ if re.compile(pattern).groups != 1:
79
+ raise re.error('it needs exactly one group, the count')
80
+ except re.error as error:
81
+ autoopt.fail('--tests-format {}: {}'.format(key, error))
82
+
83
+ patterns[key] = pattern
84
+
85
+ return ('given', patterns, '|'.join('(?:{})'.format(pattern) for pattern
86
+ in patterns.values()))
87
+
88
+
89
+ def log_counts(text, formats=LOG_FORMATS):
90
+ """`(format, {passed, skipped, failed, errors})` from a test log's
91
+ summary lines, or `(None, None)` when no known summary is in it."""
92
+
93
+ for name, patterns, marker in formats:
94
+ marked = [line for line in text.splitlines() if re.search(marker,
95
+ line)]
96
+
97
+ if not marked:
98
+ continue
99
+
100
+ # A summary printed several times (a runner that reports as it goes)
101
+ # counts once: the last line is the final one.
102
+ lines = marked[-1:] if name in ('pytest', 'testthat') else marked
103
+ totals = {key: 0 for key in KEYS + ('total',)}
104
+
105
+ for line in lines:
106
+ for key, pattern in patterns.items():
107
+ for found in re.finditer(pattern, line):
108
+ totals[key] += int(found.group(1))
109
+
110
+ if 'total' in patterns and 'passed' not in patterns:
111
+ totals['passed'] = totals['total'] - totals['failed'] - \
112
+ totals['errors'] - totals['skipped']
113
+
114
+ del totals['total']
115
+
116
+ return name, totals
117
+
118
+ return None, None
119
+
120
+
121
+ def tree(bare, ref):
122
+ return autoopt.git('-C', bare, 'rev-parse', ref + '^{tree}').strip()
123
+
124
+
125
+ def numstat(bare, before, after, exclude=()):
126
+ """`[(path, added, deleted)]` from `before` to `after` (commits or
127
+ trees), leaving out the paths in `exclude`; binary files count 0."""
128
+
129
+ specs = ['--', '.'] + [':(exclude){}'.format(name) for name in exclude]
130
+ rows = []
131
+
132
+ for line in autoopt.git('-C', bare, 'diff', '--numstat', '--no-renames',
133
+ before, after, *specs).splitlines():
134
+ added, deleted, path = line.split('\t', 2)
135
+ rows.append((path, int(added) if added.isdigit() else 0,
136
+ int(deleted) if deleted.isdigit() else 0))
137
+
138
+ return rows
139
+
140
+
141
+ def spread(values):
142
+ values = [value for value in values or [] if isinstance(value, (int,
143
+ float))]
144
+
145
+ if not values:
146
+ return None, None, None, 0
147
+
148
+ return statistics.median(values), min(values), max(values), len(values)
149
+
150
+
151
+ def write_tsv(path, header, rows):
152
+ publish.write(path, '\n'.join(['\t'.join(header)] + ['\t'.join(str(value)
153
+ for value in row) for row in rows]) + '\n')
154
+
155
+
156
+ def number(value):
157
+ return '' if value is None else repr(float(value))
158
+
159
+
160
+ def main(argv=None):
161
+ parser = argparse.ArgumentParser(description=__doc__,
162
+ formatter_class=argparse.RawDescriptionHelpFormatter)
163
+ parser.add_argument('work')
164
+ parser.add_argument('--id', default='best')
165
+ parser.add_argument('--out', help='default WORK/ship/pr-optimization')
166
+ parser.add_argument('--tests-format', action='append', default=[],
167
+ metavar='KEY=REGEX', help='the unit-test log\'s summary, for a runner '
168
+ 'whose summary is not pytest\'s, testthat\'s or "N passed": KEY one '
169
+ 'of passed, failed, skipped, errors or total, REGEX with one group, '
170
+ 'the count; repeat for each key. Without it, or when nothing matches, '
171
+ 'the PR gives no counts')
172
+ args = parser.parse_args(argv)
173
+ formats = (given_format(args.tests_format),) if args.tests_format else \
174
+ LOG_FORMATS
175
+
176
+ work = os.path.abspath(os.path.expanduser(args.work))
177
+
178
+ if os.path.basename(work) == 'autooptimize':
179
+ work = os.path.dirname(work)
180
+
181
+ root = os.path.join(work, 'autooptimize')
182
+ config = autoopt.load_config(root)
183
+
184
+ if not config.get('repo'):
185
+ autoopt.fail('this search was made with `init --copy`: a plain search '
186
+ 'ships with `ship.py apply`, not a PR')
187
+
188
+ ended = autoopt.load_ended(root)
189
+
190
+ if ended is None:
191
+ autoopt.fail('the search has not ended: `autoopt.py end` first')
192
+
193
+ identifier = autoopt.resolve_id(root, config, args.id)
194
+ problem = autoopt.measured_problem(root, config, identifier)
195
+
196
+ if problem:
197
+ autoopt.fail(problem)
198
+
199
+ out = os.path.abspath(os.path.expanduser(args.out or autoopt.work_path(work,
200
+ 'ship', autoopt.SHIP_FOLDERS['optimization'])))
201
+ os.makedirs(os.path.join(out, 'messages'), exist_ok=True)
202
+
203
+ bare = os.path.join(root, 'repo.git')
204
+ original = autoopt.original_of(work, config)
205
+ start = config['repo']['commit']
206
+ strip = autoopt.outputs_stripper(root, config)
207
+ head = autoopt.branch_of(root, identifier)
208
+ chain = autoopt.lineage(root, identifier)
209
+ tree_of = lambda i: strip(tree(bare, autoopt.branch_of(root, i)))
210
+ steps = autoopt.winning_steps(root, chain, tree_of, strip(tree(bare,
211
+ start)))
212
+
213
+ if not steps:
214
+ autoopt.fail('{} changes nothing in the repository'.format(
215
+ autoopt.label(root, identifier)))
216
+
217
+ suite = original.get('suite')
218
+ owned = [name for name in autoopt.git('-C', bare, 'diff', '-z',
219
+ '--name-only', original['commit'], start).split('\0') if name] if \
220
+ suite else []
221
+
222
+ # Each kept change: the files it changed against the one before it.
223
+ rows, before = [], strip(tree(bare, start))
224
+
225
+ for step, step_tree in steps:
226
+ changed = numstat(bare, before, step_tree, owned)
227
+ rows.append((step, ((autoopt.load_result(root, step) or {}).get('title')
228
+ or '').replace('\t', ' '), ','.join(path for path, _, _ in changed),
229
+ sum(a for _, a, _ in changed), sum(d for _, _, d in changed)))
230
+ before = step_tree
231
+
232
+ write_tsv(os.path.join(out, 'changes.tsv'), ('id', 'title', 'files',
233
+ 'added', 'deleted'), rows)
234
+ files = numstat(bare, strip(tree(bare, start)), tree_of(identifier), owned)
235
+ write_tsv(os.path.join(out, 'files.tsv'), ('path', 'added', 'deleted'),
236
+ files)
237
+
238
+ # The objective and every observer, first measurement against the kept
239
+ # code: each run's value, so the table can say how many and how far apart.
240
+ zero = autoopt.load_result(root, 0) or {}
241
+ kept = autoopt.load_result(root, identifier) or {}
242
+ objective = config['objective']
243
+ performance = []
244
+
245
+ def measure(name, role, unit, first, last):
246
+ a = spread(first)
247
+ b = spread(last)
248
+
249
+ if a[0] is None or b[0] is None:
250
+ return
251
+
252
+ performance.append((name, role, unit, number(a[0]), number(a[1]),
253
+ number(a[2]), a[3], number(b[0]), number(b[1]), number(b[2]), b[3]))
254
+
255
+ measure(objective['name'], 'objective', objective.get('unit') or '',
256
+ (zero.get('objective') or {}).get('values'), (kept.get('objective') or
257
+ {}).get('values'))
258
+
259
+ for observer in config.get('observers') or []:
260
+ name = observer['name']
261
+ measure(name, 'observer', '', ((zero.get('observers') or {}).get(name)
262
+ or {}).get('values'), ((kept.get('observers') or {}).get(name) or
263
+ {}).get('values'))
264
+
265
+ write_tsv(os.path.join(out, 'performance.tsv'), ('measure', 'role', 'unit',
266
+ 'first_median', 'first_min', 'first_max', 'first_runs', 'kept_median',
267
+ 'kept_min', 'kept_max', 'kept_runs'), performance)
268
+
269
+ gates = []
270
+
271
+ for gate in config.get('gates') or []:
272
+ record = (kept.get('gates') or {}).get(gate['name']) or {}
273
+ values = [value for value in record.get('values') or [] if value is not
274
+ None]
275
+ gates.append((gate['name'], gate['op'], gate.get('threshold'),
276
+ record.get('worst'), len(values)))
277
+
278
+ write_tsv(os.path.join(out, 'gates.tsv'), ('name', 'op', 'threshold',
279
+ 'worst', 'runs'), gates)
280
+
281
+ check = kept.get('check') or {}
282
+ compare = check.get('compare') or {}
283
+ cold_kept = (check.get('cold') or {}).get('seconds')
284
+ cold_first = ((zero.get('check') or {}).get('cold') or {}).get('seconds')
285
+ publish.write_json(os.path.join(out, 'checks.json'), {
286
+ 'compare': {'verdict': compare.get('verdict'), 'summary':
287
+ compare.get('summary')} if compare else None,
288
+ 'cold': {'first': cold_first, 'kept': cold_kept} if cold_kept is not
289
+ None else None})
290
+
291
+ final = ended.get('paired') if isinstance(ended.get('paired'), dict) else \
292
+ None
293
+ paired = None
294
+
295
+ if final and final.get('winner') == identifier:
296
+ paired = {key: final.get(key) for key in ('paired', 'threads')}
297
+
298
+ publish.write_json(os.path.join(out, 'paired.json'), paired)
299
+ publish.write_json(os.path.join(out, 'machine.json'), ended.get('machine'))
300
+
301
+ # The unit tests that ran on the kept code, and their counts from the log.
302
+ record = kept.get('tests')
303
+ tests = None
304
+
305
+ if record:
306
+ log = os.path.join(autoopt.iteration_dir(root, identifier),
307
+ record.get('log') or os.path.join('unit-tests', 'log.txt'))
308
+
309
+ try:
310
+ with open(log, encoding='utf-8', errors='replace') as handle:
311
+ form, counts = log_counts(handle.read(), formats)
312
+ except OSError:
313
+ form, counts = None, None
314
+
315
+ tests = {'pass': bool(record.get('pass')), 'scope': record.get('scope'),
316
+ 'format': form, 'counts': counts}
317
+
318
+ publish.write_json(os.path.join(out, 'tests.json'), tests)
319
+
320
+ # A message the writer has edited is kept; one the iteration wrote fills
321
+ # a missing file; otherwise a skeleton to fill.
322
+ trailer = autoopt.commit_trailer(root)
323
+ skeletons = []
324
+
325
+ for step, _ in steps:
326
+ path = os.path.join(out, 'messages', '{}.txt'.format(step))
327
+
328
+ if os.path.exists(path):
329
+ continue
330
+
331
+ message = autoopt.change_fragment(root, step).get('message')
332
+
333
+ if not message:
334
+ skeletons.append(autoopt.label(root, step))
335
+
336
+ publish.write(path, autoopt.with_trailer(message or SKELETON, trailer))
337
+
338
+ # What each kept change's subagent wrote about it, for the prose template.
339
+ publish.write_json(os.path.join(out, 'fragments.json'), {str(step): {
340
+ key: autoopt.change_fragment(root, step).get(key) for key in ('name',
341
+ 'change')} for step, _ in steps})
342
+ publish.write_json(os.path.join(out, 'branch.json'), {
343
+ 'id': identifier, 'label': autoopt.label(root, identifier),
344
+ 'target': original.get('branch'), 'base': original['commit'] if suite
345
+ else start, 'remote_url': original.get('remote_url'),
346
+ 'suite': bool(suite), 'suite_files': len(owned),
347
+ 'steps': [step for step, _ in steps],
348
+ 'step_labels': [autoopt.label(root, step) for step, _ in steps],
349
+ 'labels': [autoopt.label(root, i) for i in autoopt.iteration_ids(root)],
350
+ 'objective': {'name': objective['name'], 'unit': objective.get('unit')
351
+ or '', 'direction': objective['direction']},
352
+ 'documents': list((dict(autoopt.AFTER_DEFAULTS, **(config.get('after')
353
+ or {}))).get('ship_documents') or [])})
354
+
355
+ print('wrote the tables in {}: {} kept change(s), {} file(s), {} row(s) of '
356
+ 'performance, {} output check(s)'.format(out, len(steps), len(files),
357
+ len(performance), len(gates)))
358
+
359
+ if skeletons:
360
+ print('commit messages to write (skeletons in messages/): {}'.format(
361
+ ', '.join(skeletons)))
362
+
363
+ return 0
364
+
365
+
366
+ if __name__ == '__main__':
367
+ sys.exit(main())
@@ -0,0 +1,188 @@
1
+ #!/usr/bin/env python3
2
+ """Paired separate-process timing of two versions, with a stopping rule.
3
+
4
+ python3 paired.py --a DIR_A --b DIR_B --cmd 'python3 probe.py --src {src}'
5
+
6
+ Each pair runs the command once for each side, in a fresh process, alternating
7
+ which side goes first (the side run first in a pair can be the slower one,
8
+ so a fixed order hands the second a fake win). Each side keeps its
9
+ own compiler cache, `<DIR>/.paired-cache`, warmed by one unrecorded run before
10
+ the first pair, so no pair times a compile.
11
+
12
+ The command prints the seconds it measured as the last number on its last
13
+ line of stdout, and exits non-zero if its output is wrong; any failure stops
14
+ the comparison. `{src}` is the side's directory and `{side}` its name, `a` or
15
+ `b`.
16
+
17
+ After `--min-pairs` pairs, and after each pair from then on, an exact
18
+ two-sided sign test on the paired differences is checked; the comparison
19
+ stops as soon as p < `--alpha`, and otherwise runs to `--max-pairs`. With the
20
+ defaults a unanimous result stops at 9 pairs and a close call runs all 24.
21
+
22
+ The two unrecorded runs also price the comparison: `priced` in the log gives
23
+ a pair's seconds and the hours `--min-pairs` and `--max-pairs` take. With
24
+ `--cap-hours`, a comparison whose `--min-pairs` would pass the cap exits 3
25
+ before the first pair. Every later run is killed past `--run-timeout` seconds
26
+ (default: ten times that side's unrecorded run, plus 60), and that exits 4.
27
+
28
+ Looking after every pair raises the chance of a false difference above the
29
+ per-look alpha. With alpha 0.005 and looks from pair 8 to 24 it is 1.2%
30
+ under no real difference (simulated, 200,000 trials); at alpha 0.01 it would
31
+ be 2.2%. Deciding by eye on 10 wins of 12 pairs has a 3.9% false-positive
32
+ rate.
33
+ """
34
+
35
+ import os
36
+ import sys
37
+ import json
38
+ import math
39
+ import time
40
+ import argparse
41
+ import statistics
42
+
43
+ from probe_run import run_probe
44
+
45
+
46
+ def sign_test(wins, losses):
47
+ """Exact two-sided sign test; ties are dropped before calling."""
48
+
49
+ n = wins + losses
50
+
51
+ if n == 0:
52
+ return 1.0
53
+
54
+ k = min(wins, losses)
55
+ tail = sum(math.comb(n, i) for i in range(k + 1)) / 2 ** n
56
+
57
+ return min(1.0, 2 * tail)
58
+
59
+
60
+ def run_once(args, side, directory, timeout=None):
61
+ return run_probe(args.cmd, directory, side, os.path.join(directory,
62
+ '.paired-cache'), args.env, args.regex, timeout)
63
+
64
+
65
+ def price(warm, min_pairs, max_pairs):
66
+ """`(seconds a pair, hours at min_pairs, hours at max_pairs)` from the
67
+ wall seconds of each side's unrecorded run."""
68
+
69
+ pair = warm['a'] + warm['b']
70
+
71
+ return pair, min_pairs * pair / 3600, max_pairs * pair / 3600
72
+
73
+
74
+ def main(argv=None):
75
+ parser = argparse.ArgumentParser(description=__doc__,
76
+ formatter_class=argparse.RawDescriptionHelpFormatter)
77
+ parser.add_argument('--a', required=True, help='directory of version A')
78
+ parser.add_argument('--b', required=True, help='directory of version B')
79
+ parser.add_argument('--cmd', required=True, help='the timing command; '
80
+ '{src} and {side} are substituted')
81
+ parser.add_argument('--env', action='append', default=[],
82
+ help='KEY=VALUE for every run, e.g. NUMBA_NUM_THREADS=1; repeatable')
83
+ parser.add_argument('--min-pairs', type=int, default=8)
84
+ parser.add_argument('--max-pairs', type=int, default=24)
85
+ parser.add_argument('--alpha', type=float, default=0.005)
86
+ parser.add_argument('--direction', choices=('min', 'max'), default='min',
87
+ help='min: smaller is better (seconds); max: larger is better')
88
+ parser.add_argument('--log', help='append one line per run to this file')
89
+ parser.add_argument('--regex', help='a pattern whose first group is the '
90
+ 'seconds on the command\'s last line (default: its last number)')
91
+ parser.add_argument('--cap-hours', type=float, help='exit 3 before the '
92
+ 'first pair when --min-pairs would take longer than this, and kill '
93
+ 'an unrecorded run that passes it')
94
+ parser.add_argument('--run-timeout', type=float, help='seconds after '
95
+ 'which a recorded run is killed (default: ten times that side\'s '
96
+ 'unrecorded run, plus 60)')
97
+ parser.add_argument('--json', action='store_true')
98
+ args = parser.parse_args(argv)
99
+
100
+ if args.max_pairs < 1 or args.max_pairs < args.min_pairs:
101
+ parser.error('--max-pairs ({}) must be at least 1 and at least '
102
+ '--min-pairs ({})'.format(args.max_pairs, args.min_pairs))
103
+
104
+ sides = {'a': os.path.abspath(args.a), 'b': os.path.abspath(args.b)}
105
+
106
+ for side, directory in sides.items():
107
+ if not os.path.isdir(directory):
108
+ sys.exit('--{} {} is not a directory'.format(side, directory))
109
+
110
+ log = open(args.log, 'a') if args.log else None
111
+
112
+ warm = {}
113
+
114
+ for side in ('a', 'b'): # fill both caches, not counted
115
+ start = time.time()
116
+ run_once(args, side, sides[side], args.cap_hours * 3600 if
117
+ args.cap_hours else None)
118
+ warm[side] = time.time() - start
119
+
120
+ pair, least, most = price(warm, args.min_pairs, args.max_pairs)
121
+ line = ('priced: a pair is about {:.0f} s (a {:.0f} s, b {:.0f} s); {} to '
122
+ '{} pairs take {:.2f} to {:.2f} h'.format(pair, warm['a'], warm['b'],
123
+ args.min_pairs, args.max_pairs, least, most))
124
+
125
+ if log:
126
+ log.write(line + '\n')
127
+ log.flush()
128
+
129
+ if args.cap_hours and least > args.cap_hours:
130
+ print('over the cap of {:g} h: {}'.format(args.cap_hours, line),
131
+ file=sys.stderr)
132
+ return 3
133
+
134
+ limit = {side: args.run_timeout or 10 * warm[side] + 60 for side in warm}
135
+
136
+ diffs, p, stopped = [], 1.0, 'max-pairs'
137
+
138
+ for index in range(args.max_pairs):
139
+ order = ('a', 'b') if index % 2 == 0 else ('b', 'a')
140
+ seconds = {}
141
+
142
+ for side in order:
143
+ seconds[side] = run_once(args, side, sides[side], limit[side])
144
+
145
+ if log:
146
+ log.write('pair {} {} {:.9g}\n'.format(index + 1, side,
147
+ seconds[side]))
148
+ log.flush()
149
+
150
+ diffs.append(seconds['b'] - seconds['a'])
151
+ better = [d < 0 if args.direction == 'min' else d > 0 for d in diffs]
152
+ wins = sum(better)
153
+ ties = sum(d == 0 for d in diffs)
154
+ p = sign_test(wins, len(diffs) - wins - ties)
155
+
156
+ if len(diffs) >= args.min_pairs and p < args.alpha:
157
+ stopped = 'sign test'
158
+ break
159
+
160
+ if log:
161
+ log.close()
162
+
163
+ wins = sum(d < 0 if args.direction == 'min' else d > 0 for d in diffs)
164
+ median = statistics.median(diffs)
165
+
166
+ if p < args.alpha:
167
+ verdict = 'B better' if (median < 0) == (args.direction == 'min') \
168
+ else 'B worse'
169
+ else:
170
+ verdict = 'no difference resolved'
171
+
172
+ result = {'pairs': len(diffs), 'median_b_minus_a': median,
173
+ 'mean_b_minus_a': statistics.mean(diffs), 'b_better_in': wins,
174
+ 'p': p, 'alpha': args.alpha, 'stopped_by': stopped,
175
+ 'verdict': verdict, 'diffs': diffs}
176
+
177
+ if args.json:
178
+ print(json.dumps(result, indent='\t'))
179
+ else:
180
+ print('paired, B - A: median {:+.3g}, B better in {}/{}, sign test '
181
+ 'p = {:.3g} -> {} (stopped by {})'.format(median, wins,
182
+ len(diffs), p, verdict, stopped))
183
+
184
+ return 0
185
+
186
+
187
+ if __name__ == '__main__':
188
+ sys.exit(main())