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,251 @@
1
+ ---
2
+ name: auto-optimize-code
3
+ description: >-
4
+ Search for a faster, leaner or smaller implementation of code by running
5
+ many small experiments and keeping what survives. Use when asked to
6
+ optimize, speed up or slim a function, a script, a command-line tool or a
7
+ library, or to search over implementations of it for speed, memory or output
8
+ size; to improve one number while another must not move ("faster, but
9
+ outputs match to 1e-5"); to check on a running search or read what one
10
+ found ("how is the search going", "what is on the frontier", "what did A7
11
+ try"); to end, resume or finish one; or to ship the winner ("ship it",
12
+ "open a PR with the result", "apply the change to my script"): written
13
+ into the original files, as a branch, or as an optimization PR, a
14
+ unit-test PR and a bug report on GitHub, reviewed before posting. Covers
15
+ the objective/gate/observer interview, a git worktree per iteration,
16
+ optimizing a copy of a GitHub repository, new unit tests as a gate, a setup
17
+ subagent for the benchmark and baseline, median-of-N-seeds against a noise
18
+ band, a tree search that promotes each kept change, generated briefs and
19
+ READMEs, the paired timing of the winner, shipping, the final report, and
20
+ the dashboard. Router skill: read the step's reference file under `references/`
21
+ before doing that step's work.
22
+ ---
23
+
24
+ # auto-optimize-code
25
+
26
+ Turn "make this better" into a search that runs itself: a benchmark that
27
+ emits numbers, a baseline, then one subagent at a time, each trying one
28
+ idea and reporting a median over seeds.
29
+
30
+ Developed at the [Programmable Genomics Laboratory](https://programmable-genomics.github.io) @ UMass Chan Medical School.
31
+
32
+ MUST, MUST NOT, SHOULD, SHOULD NOT and MAY are as in RFC 2119.
33
+
34
+ ## Only asked about a search?
35
+
36
+ A question about a search this session is not running, whether another
37
+ session started it or it has ended ("what won", "how far did it get", "what
38
+ did A7 try"), is answered from `references/reading-a-search.md` alone: its
39
+ commands only read, and nothing below applies. The main session of a running
40
+ search follows `references/main-session.md` for what it reads.
41
+
42
+ ## The three words
43
+
44
+ Used exactly, in this skill and with the user. Every other term (root,
45
+ frontier, keep rule, noise band, …) is defined in
46
+ `references/glossary.md`.
47
+
48
+ | Word | What it is | Who does it |
49
+ |---|---|---|
50
+ | **run** | one execution of the benchmark with one seed | `run_iteration.py` |
51
+ | **iteration** | one idea, measured by several runs, reduced to a median | one subagent |
52
+ | **round** | the iterations forked from one root, closed by a promotion; one summary each | the orchestrator |
53
+
54
+ "3 seeds" means 3 runs per iteration. One iteration is in flight at a time: the
55
+ next starts when its subagent reports, on the root the last promotion left.
56
+ A round ends when an iteration is promoted.
57
+
58
+ ## When this is the wrong tool
59
+
60
+ - **One measurement, not a search.** Timing a function or comparing two
61
+ implementations once needs a benchmark alone.
62
+ - **No measurable objective.** If no script can emit it as a number, fix that
63
+ first.
64
+ - **Improving a machine learning model's accuracy or training recipe.** This
65
+ skill optimizes code: speed, memory, output size, with the outputs gated.
66
+
67
+ ## Requirements
68
+
69
+ | For | Needs |
70
+ |---|---|
71
+ | everything | Linux, Python 3.9 or later, git. The core scripts use only the standard library |
72
+ | the orchestration | Claude Code's Agent (subagents) and AskUserQuestion tools; SendMessage and Monitor where available |
73
+ | a GPU search | `CUDA_VISIBLE_DEVICES`, set by the machine's GPU allocator, or by `env CUDA_VISIBLE_DEVICES=<index>` on a machine with none; either is recorded as `gpu_command` |
74
+ | the dashboard in a notebook | JupyterLab, IPython and plotly; psutil for the host and process panels |
75
+ | a static dashboard (`--export`) | plotly |
76
+ | the task's checks and the preflight, which export an iteration's tree | `tar` |
77
+
78
+ Linux-only commands (`flock`, `/proc`, `/sys`) are marked where used.
79
+
80
+ ## Paths in every command
81
+
82
+ ```bash
83
+ AO=${CLAUDE_SKILL_DIR}/scripts # ${CLAUDE_SKILL_DIR}: the directory holding this SKILL.md
84
+ WORK=<the search's directory: the one holding autooptimize/>
85
+ ```
86
+
87
+ Every reference file uses these. If `${CLAUDE_SKILL_DIR}` is not expanded,
88
+ write this file's directory as an absolute path. A brief gives both, absolute.
89
+
90
+ ## The steps
91
+
92
+ Steps 0 to 6 run in order. Read each step's file just before the step, not in
93
+ advance.
94
+
95
+ | Step | Do | Read |
96
+ |---|---|---|
97
+ | 0 | **REQUIRED first:** interview the user, choose the search directory, `init`, fill in `spec.md`, then spawn the setup subagent (`autoopt.py setup`); the idea miner follows when setup is done (`autoopt.py mine`), because it prices ideas against A0's profile | `references/step0-interview.md` |
98
+ | 1 | Repository mode, on a yes at step 0 only: write the new unit tests in a clone, passing on the base in every CI configuration, then `init` on it and spawn the setup subagent, and the miner once setup is done | `references/step1-unit-tests.md` |
99
+ | 2 | The setup subagent's: write the benchmark, check its seeding, prove its gates and checks, measure the width, run the baseline A0, seed the ledger, write A0's README, close with `setup --done`. The main session relays its questions to the user | the setup subagent: `references/step2-baseline.md`; the main session: `references/main-session.md` |
100
+ | 3 | Once setup and the miner's S1 are done, `autoopt.py loop` starts the orchestrator subagent, which runs the rounds and hands back with the round tables to show the user; start the next phase | `references/step3-rounds.md`, *The orchestrator subagent* |
101
+ | 4 | End the search on the record: `autoopt.py end` refuses while anything is in flight, pairs the winner with A0, writes the last round's summary, `ended.json` and `ended.md`, deletes the regenerable files and snapshots the dashboard. | `references/step4-final.md` |
102
+ | 5 | Ship, once the search is over: ask the user how (`ship.py plan`), then apply the change to the original files (plain mode), make a branch in the original repository, or open the GitHub documents they check (the optimization PR, the unit-test PR, the bug report), reviewed together and posted together | `references/step5-ship.md` |
103
+ | 6 | Finish: copy the winner out, write the final report, reclaim the disk once the user agrees | `references/step6-finish.md` |
104
+
105
+ | Not a step | Read |
106
+ |---|---|
107
+ | You are the setup subagent | `references/step2-baseline.md` |
108
+ | You are the main session, from step 2 on: setup questions, phases, the user's messages, ending the search, the cost | `references/main-session.md` |
109
+ | You are the orchestrator subagent | your prompt, then `references/step3-rounds.md` |
110
+ | You are a subagent running one iteration | `references/subagent.md` |
111
+ | You are the idea miner | `references/idea-miner.md` |
112
+ | The dashboard: start it, read it, fix it | `references/dashboard.md` |
113
+ | A search a previous session started | `references/resume.md` |
114
+ | A question about a search, not continuing it | `references/reading-a-search.md` |
115
+
116
+ ## By topic
117
+
118
+ | Topic | Read |
119
+ |---|---|
120
+ | What a term means | `references/glossary.md` |
121
+ | An error message, a refusal, or something that looks wrong | `references/symptoms.md` |
122
+ | Writing a subagent's brief: `autoopt.py brief` | `references/writing-briefs.md` |
123
+ | Where ideas come from: the idea miner, `autoopt.py mine`, the categories, `ideas.md` | `references/step3-rounds.md`, *Keeping the ideas*; the miner's own protocol, `references/idea-miner.md` |
124
+ | The task's checks: writing them at step 2, A0's cached outputs, `autoopt.py check`, the order the runner runs them in | `references/step2-baseline.md`, *Write the checks*; `references/subagent.md`, *Checks beyond the runner* |
125
+ | The knowledge ledger, shared tools, the checker library, a cached scratch build | `references/shared-knowledge.md` |
126
+ | Promotion (the runner's keep verdict, `promote: auto`), predicting what a change is worth | `references/promotion.md` |
127
+ | A relaxed gate, a changed objective or gate, starting the ideas over (`reset`) | `references/changes.md` |
128
+ | Checking the winner on inputs the search never measures | `references/external-validation.md` |
129
+ | Telling whether a change helped: profiling, paired timing (`scripts/paired.py`), compiler caches and `{cache}` | `references/measuring.md`; sweeps of variants: `references/subagent.md`, *Timing variants* |
130
+ | Speeding up or slimming an algorithm implementation: time and memory, synthetic input sizes, thread counts | `references/algorithm.md` |
131
+ | Optimizing code in a git repository without touching it: the copy, the harness, the unit-test gate | `references/repo-mode.md` |
132
+ | The checks `promote` makes without measuring: text, the `## Change` and `## Commit message` sections of `notes.md`, indentation, license markers, the oldest toolchain (`preflight.py`, `lint_text.py`) | `references/promotion.md`, *The preflight* |
133
+ | What is on disk, what the JSON files hold, the version fields | `references/layout.md` |
134
+ | Changing what the skill does: every setting, environment variable and hook, and where to edit the code when none fits | `references/extending.md` |
135
+ | Every script flag (the dashboard's are in `scripts/dashboard/README.md`) | `references/cli.md` |
136
+ | Reading a search without changing it: `autoopt.py table` and `show`, which file answers which question | `references/reading-a-search.md` |
137
+ | Ending the search, reopening it, an iteration made after the end (`--after-end`), what `end` leaves on disk | `references/step4-final.md` |
138
+ | What the GitHub documents carry and may not say; the stand-in numbers | `references/documents.md` |
139
+ | The optimization PR: its tables, prose, commit messages, `autoopt.py pr` | `references/pr-optimization.md` |
140
+ | The unit-test PR: its tables from step 1's files, the push | `references/pr-tests.md` |
141
+ | The bug report: bugs.tsv, verifying each reproduction, filing it | `references/issue-bugs.md` |
142
+ | Code compiled by numba: speed, exactness classes, compile time | `references/algorithm.md`, *Numba* |
143
+
144
+ ## Rules that hold everywhere
145
+
146
+ **Step 0 MUST come first.** Interview the user before writing a benchmark,
147
+ and ask what a gate means rather than guess: "the outputs must not change"
148
+ is bitwise identity, a tolerance, or a correlation.
149
+
150
+ **`$WORK/NOTES.md` is generated, never written.** `python3 $AO/stages.py
151
+ status $WORK` prints the six stages (interview, setup, search, final, ship,
152
+ finish)
153
+ as `not started`, `running` or `complete`, with the next command; `render`
154
+ writes the file, and `end` calls it.
155
+
156
+ **The search directory is chosen at step 0 and never moved.** Ask, offering
157
+ `~/auto-optimize/<YYYY-MM-DD>-<name>/` as the default. Moving it breaks
158
+ the absolute paths in git's worktree records, `config.json` and the harness.
159
+
160
+ **A running search MUST NOT wait on the user.** Once iterations are in
161
+ flight, do not end a turn on a question. Take the answer that does the least
162
+ damage if it is wrong, record it, and keep briefing the next iteration
163
+ (`references/step3-rounds.md`, *Questions while the search runs*).
164
+
165
+ **Rules live in `spec.md`, and briefs come from `autoopt.py brief`.** Record a
166
+ rule decided mid-search before using it: a setting with `autoopt.py config
167
+ --set … --reason "<the user's words>"`, which writes the dated line itself,
168
+ anything else as a dated line in the user's words under *Rules added during
169
+ the search*. `setup --answer` writes the line for a setup question's answer.
170
+
171
+ **Name an iteration with its label, everywhere: `A107`, never `107` or
172
+ `#107`.** Directories and branches keep the bare number (`iterations/107/`,
173
+ `autoopt/107`).
174
+
175
+ **The search ends once, on the record.** `autoopt.py end` (step 4) refuses
176
+ while an iteration is in flight or a phase is open, writes `ended.json`,
177
+ and deletes the regenerable files.
178
+ Afterwards `new`, `brief`, `loop` and `mine` refuse, except an iteration made
179
+ with `--after-end` (a notice, a fix, a clean-up), and
180
+ `--id best` is `ended.json`'s winner. `end --reopen` undoes the ending until
181
+ step 5 ships the winner (a hold in `reopen-lock.json`), never the clean-up
182
+ (`references/step4-final.md`).
183
+
184
+ **One subagent, one iteration.** A subagent implements one idea, measures
185
+ it, writes its README and stops. The orchestrator edits no iteration's code.
186
+
187
+ **The main session relays; it does not work the search.** It spawns the setup
188
+ subagent and the first idea miner; the orchestrator
189
+ subagent spawns iteration subagents and later miners and
190
+ runs the rounds in phases the main session starts (`references/step3-rounds.md`,
191
+ *The orchestrator subagent*). The main session reads only `status --brief` and
192
+ the phases' reports, relays questions to the user and shows round summaries.
193
+ It mines no ideas, measures nothing, promotes nothing, reads no code, logs,
194
+ READMEs or outputs, and writes no summary prose: its context is rewritten at
195
+ every wake-up. An iteration whose subagent is
196
+ gone goes to a new one (`references/step3-rounds.md`, *A subagent that goes
197
+ quiet*).
198
+
199
+ **No call lasts longer than four minutes**, for any agent: the prompt cache
200
+ lives five, and the turn after a longer call writes the whole context to it
201
+ again, at many times the price of reading it. A foreground command takes the Bash tool's `timeout: 240000`; one that may
202
+ pass that starts in the background and is watched with `autoopt.py wait <log>`
203
+ (it returns within 200 s with the new lines), repeated until it prints `wait:
204
+ finished`.
205
+ `end`, `final`, `validate`, `run_iteration.py`, `width` and `prove` take
206
+ `--background` (under a `gpu_command`, `validate` and `width` go through `bg`
207
+ whole, allocator included, since their own `--background` drops the lease); anything else is `autoopt.py bg $WORK <log> '<command>'` in the
208
+ main session and `(<command>; echo "exit $?") > <log> 2>&1 &` in a subagent.
209
+ **A turn never ends on a background command that nothing waits for**: the
210
+ next call is `autoopt.py wait <log>`.
211
+
212
+ **The dashboard publisher MUST start with the first iteration**, asked for or not
213
+ (`references/dashboard.md`), and the user is told how to see it: the notebook,
214
+ `$WORK/dashboard.ipynb`, or what that file gives for a machine without
215
+ JupyterLab.
216
+
217
+ **Every iteration of a GPU search holds its own GPUs for its whole length**,
218
+ and two iterations never share one (`references/step3-rounds.md`, *GPUs for
219
+ each iteration*).
220
+
221
+ **Only the runner's median is a result, and numbers are never retyped.**
222
+ Anything timed inside one process ranks variants and measures no gain. The
223
+ winner against A0 (`autoopt.py final`, run by `autoopt.py end`) is reported
224
+ beside the median, labeled "paired" (`references/measuring.md`).
225
+
226
+ **The README is the only channel for an iteration; `knowledge.md` is the
227
+ search's.** What a subagent noticed is lost unless it is in its `notes.md`,
228
+ and rediscovered by a later one unless it is also in
229
+ `autooptimize/knowledge.md` (`references/shared-knowledge.md`).
230
+
231
+ **External validation is optional, runs once a round, and gates nothing.**
232
+ Propose one; it MUST NOT run without the user's recorded sign-off, and a bad
233
+ result goes to them (`references/external-validation.md`).
234
+
235
+ **In repository mode, step 0 MUST ask "Do you want to add new unit tests?"**
236
+ and, on a yes, the scope (`references/step1-unit-tests.md`).
237
+
238
+ **Anything needed later lives under `$WORK`.** Scripts, scratch builds and
239
+ probe inputs go in `$WORK`, never in `/tmp` or a session's scratchpad, which
240
+ are not part of the search.
241
+
242
+ **The original repository MUST NOT be written to.** A repository search
243
+ copies it with `init --repo` (`references/repo-mode.md`). The one exception
244
+ is step 5, on the user's own choice there: `ship.py apply --yes` writes the
245
+ original files, `ship.py branch --yes` adds a branch to the original
246
+ repository, and `ship.py post` pushes and opens what they reviewed.
247
+
248
+ **Shipping starts with the user's answer, after the search is over.** Step 5
249
+ asks how to ship and records it (`after.ship`); nothing is applied, made or
250
+ posted before that answer, and GitHub documents are posted only together,
251
+ after the user reviewed all of them (`references/step5-ship.md`).
@@ -0,0 +1 @@
1
+ 1.0.0
@@ -0,0 +1,182 @@
1
+ # Optimizing an algorithm implementation
2
+
3
+ The search changes how a function computes its answer, not the answer itself:
4
+ a faster parser, a leaner aggregation, a kernel rewritten in numba. When
5
+ the code is in a git repository, set the search up in repository mode first
6
+ (`references/repo-mode.md`). `$AO` and `$WORK` are as in `SKILL.md`.
7
+
8
+ **When the algorithm uses numba (`@njit`, `prange`), read *Numba*, below,
9
+ before briefing the first subagent.** Its
10
+ optimizations are labeled bit-identical, machine-precision or close, so a
11
+ bitwise gate rules options out before they cost an iteration. `autoopt.py
12
+ brief` adds the numba note to every brief whose parent imports numba.
13
+
14
+ ## The objective is time or memory, and the other is always recorded
15
+
16
+ **Whichever of wall-clock seconds and peak memory is the objective, record
17
+ the other as an observer.** A 30% speedup that doubles peak memory is a
18
+ trade the user has to see, and an observer never recorded can be recovered
19
+ only by re-running every iteration.
20
+
21
+ | Objective | Observer | Gate |
22
+ |---|---|---|
23
+ | `seconds`, min | `peak_mb` | the outputs match the baseline's, in the form the user chose (`references/step0-interview.md`, *Gates*) |
24
+ | `peak_mb`, min | `seconds` | the same |
25
+
26
+ Every algorithm search also needs the output-identity gate: speed is easy to
27
+ buy by computing something else (`references/measuring.md`, *A suspiciously
28
+ large speedup is usually dead code*).
29
+
30
+ ## Measuring both in one run
31
+
32
+ Take time and memory from **separate calls**. `tracemalloc` slows Python-level
33
+ allocation several-fold on a loop of small numpy allocations, so a call
34
+ timed under it measures the tracer.
35
+
36
+ ```python
37
+ import time, tracemalloc
38
+
39
+ run(inputs) # warm up: JIT compiles, caches fill
40
+
41
+ start = time.perf_counter()
42
+ result = run(inputs) # the timed call, untraced
43
+ seconds = time.perf_counter() - start
44
+
45
+ tracemalloc.start()
46
+ run(inputs) # the memory call
47
+ peak_mb = tracemalloc.get_traced_memory()[1] / 1e6
48
+ tracemalloc.stop()
49
+ ```
50
+
51
+ | Measure | Sees | Misses |
52
+ |---|---|---|
53
+ | `tracemalloc` peak | Python and numpy allocations, and arrays numba allocates inside `@njit`, including per-thread scratch in a `prange` | memory allocated by C, C++ or Fortran libraries outside Python's allocator |
54
+ | `resource.getrusage(RUSAGE_SELF).ru_maxrss` | everything the process ever held, in kB on Linux | cannot be reset; it includes imports and numba's compiler, so it cannot isolate one call |
55
+ | `torch.cuda.max_memory_allocated()` | GPU tensors, after `torch.cuda.reset_peak_memory_stats()` | the caching allocator's reserve (`max_memory_reserved`) |
56
+
57
+ Name the measure in the observer (`peak_traced_mb`, `max_rss_mb`): two of
58
+ these on the same call can differ by the size of the interpreter.
59
+
60
+ ## Numba
61
+
62
+ **Decide the exactness class the gate allows before trying anything.** Under a
63
+ bitwise gate, try only bit-identical changes: anything else cannot pass, and a
64
+ pass on the benchmark's data alone is a coincidence.
65
+
66
+ | Class | Meaning | Typical sources |
67
+ |---|---|---|
68
+ | bit-identical | every output byte equal on every input | layout and loop-nest changes that keep each output's operations in order; integer regrouping; exact caching; skipping work proven to be +0.0 |
69
+ | machine-precision | differs only by floating-point rounding, which can accumulate | reordering or reassociating a float sum; `fastmath` without approximate functions; FMA contraction; multiplying by a precomputed reciprocal |
70
+ | close | an approximation with a bounded but visible error | float32 in place of float64; lookup tables; early termination; approximate `exp` or `log` |
71
+
72
+ A bit-identical label is often conditional ("no NaN or -0.0 in the data",
73
+ "while sums fit in int16"): prove the condition on all the data, or guard it
74
+ at runtime with a fallback (`references/measuring.md`, *Properties no gate
75
+ can see*).
76
+
77
+ - **A fresh `NUMBA_CACHE_DIR` for every variant and every cold measurement**,
78
+ never a deleted one: `cache=True` keys a library on the decorated function's
79
+ own file, so an edit to a callee in another file is served stale
80
+ (`references/measuring.md`, *A cached compile can outlive the edit*).
81
+ - **Every new argument type, dimensionality or memory layout is a new
82
+ signature**, compiled on its first call unless the cache already holds it;
83
+ warm up once per signature the benchmark uses.
84
+ - **Time the parallel path as well as one thread.** False sharing in
85
+ per-thread scratch can make the parallel path many times slower while every
86
+ single-thread gate passes (*Fix the thread count*, below).
87
+ - **Assert which copy of the code was imported**
88
+ (`sys.modules['<pkg>.<module>'].__file__`) before believing any timing.
89
+
90
+ ## Fix the thread count
91
+
92
+ For a parallel kernel (`prange`, BLAS, a thread pool), the thread count used
93
+ by the timed call is part of the objective's definition. Set it explicitly in
94
+ the harness (`n_jobs=8`, never a default like `-1` that means every core),
95
+ ask the user for it at step 0, and write it on `spec.md`'s *Thread counts
96
+ timed, tracking inputs* line. An iteration that changes it is a different search.
97
+
98
+ **When the objective is timed at one thread count, ask whether to observe
99
+ another.** A search timed at `n_jobs=1` only cannot see a change that makes
100
+ the parallel path many times slower; it passes every gate and every unit
101
+ test. If the code has a parallel path, propose an observer timed at the
102
+ thread count users run (`seconds_8_threads`), from a separate call in the
103
+ same run, and gate nothing on it.
104
+
105
+ ## Cold compile time
106
+
107
+ For code compiled at first call (numba, Triton, `torch.compile`), the
108
+ compile is paid once per machine and install, and no warmed-up timing sees
109
+ it. A cold first call can double over 100 iterations without anyone
110
+ noticing, and the unit-test gate slows with it: every iteration's tests
111
+ start from an empty cache, so they compile everything.
112
+
113
+ Step 2 writes `checks/first_call.py`, one call on a small input so the
114
+ compile dominates (`references/step2-baseline.md`, *Write the checks*). The
115
+ runner times it with `cold.py` on empty caches before each iteration's runs,
116
+ beside the parent's recorded value, on the `check:` line; a crash fails the
117
+ iteration before any run. A compile cost is the user's trade: bring a large
118
+ jump to them rather than rejecting the iteration. For numba, *Numba*, above,
119
+ says what invalidates the cache and what forces a second compile.
120
+
121
+ ## Track the objective across a range of inputs
122
+
123
+ At the end of every run, time the same function on several synthetic
124
+ datasets that span what the package actually receives, each recorded as an
125
+ **observer**, not a gate. The search optimizes one input size; these
126
+ observers show what each change did to small, large and irregular inputs. A
127
+ change that wins at the benchmark size and loses 3x on a single-element
128
+ input shows up here and nowhere else.
129
+
130
+ **Mine the unit tests for the cases**: they hold the inputs the package's authors
131
+ worried about. Read `tests/` for fixtures, parametrize lists and regression
132
+ cases, and turn each class into a generated dataset:
133
+
134
+ | Class | What it covers | Example: comparing queries with targets |
135
+ |---|---|---|
136
+ | tiny | the smallest input the API accepts | one query, one short target |
137
+ | much larger | several times the benchmark along each axis that scales: 10x for a linear algorithm, less when the baseline is super-linear | 10x the queries or the targets |
138
+ | irregular | sizes at both extremes, and mismatched shapes | query lengths 1 and 30+, targets shorter than the query |
139
+ | degenerate | inputs that create ties or repeated work | all-identical queries, queries of one repeated symbol |
140
+
141
+ A class the API rejects (an empty target that raises) is a unit test's job,
142
+ not a timing: leave it out and say so in `spec.md`.
143
+
144
+ - Generate the datasets once, before the baseline, from a fixed seed, and
145
+ store them in `autooptimize/reference/`.
146
+ - Warm up once per dataset when the code is JIT-compiled: a new dtype or
147
+ number of dimensions is a new numba signature, whose first call includes
148
+ the compile.
149
+ - Name each observer `<objective>_<dataset>` (`seconds_tiny`,
150
+ `seconds_wide_inputs`) and put the dataset's shape in `spec.md`.
151
+ - Budget it: the suite runs on every run, so its cost multiplies by
152
+ `runs_per_iteration`. Keep the large cases no larger than the question
153
+ needs; setup reports the per-run cost at step 2.
154
+ - Put the same identity gate on each dataset's output only if the user
155
+ wants the gate to cover all of them; ask at step 0.
156
+
157
+ These observers do not replace the external validation
158
+ (`references/external-validation.md`), which runs once a round and can be
159
+ slow.
160
+
161
+ ## The unit tests are a gate
162
+
163
+ When the package has tests, pass them to `init --tests`. The suite runs once
164
+ per iteration and a failure fails the iteration. Setup, the baseline rule and
165
+ the thread pinning a timing search needs are in `references/repo-mode.md`,
166
+ *The unit-test gate*.
167
+
168
+ ## What this adds to the interview
169
+
170
+ Rows for group 4 of `references/step0-interview.md`, *The questions*; record
171
+ "algorithm implementation" on `spec.md`'s *Kind of search* line, which makes
172
+ `setup --done` require the task's checks.
173
+
174
+ | Group | Question | Options to offer | Default | Recorded in `spec.md` |
175
+ |---|---|---|---|---|
176
+ | 4 | Which memory measure is recorded: as the observer when the objective is time, as the objective when it is memory? | `max_rss_mb`, which any program has (Recommended for compiled code); `peak_traced_mb` (Recommended for Python) | the recommended one for the language | Objective, Observers |
177
+ | 4 | At what thread count is the objective timed? This is also group 2's worker count: ask once | the count users run; 1 | none: always asked, since the code's own default is never taken | Thread counts timed, tracking inputs; `init --workers` |
178
+ | 4 | Track the synthetic dataset classes above, and gate their outputs too? | the classes proposed from the tests (Recommended); fewer; gate them as well | observe, do not gate | Thread counts timed, tracking inputs |
179
+ | 4 | Observe a second thread count? | yes, where the code has a parallel path (Recommended); no | yes, where it applies | Observers; Thread counts timed, tracking inputs |
180
+
181
+ The unit-test command and whether the baseline passes it belong to repository
182
+ mode (`references/repo-mode.md`), or to `init --tests` in plain mode.
@@ -0,0 +1,146 @@
1
+ # A second search, changing the terms, and starting over
2
+
3
+ | Situation | Do |
4
+ |---|---|
5
+ | A different premise or a rewrite, whose numbers should not be compared with the iterations so far | a **new search** seeded from the current winner (`init` it with the winner's code as its baseline) |
6
+ | The root reached `floor`: the benchmark is too small to resolve a further gain | a **new search** on a larger input, sized so that this root takes 20 to 50 times the floor; its baseline is this root's code, or the original code when the user wants the whole gain measured on the new input (ask which) |
7
+ | The objective moved tenfold, so the noise band does not fit | nothing: the next phase re-measures the band from the root (`references/step3-rounds.md`, *When the objective moves by an order of magnitude*) |
8
+ | A gate that may be too strict, explored while the strict search goes on | run a **second search** beside it |
9
+ | The objective, or how the benchmark computes it, turns out wrong, a benchmark bug included | a **new search** |
10
+ | A gate's threshold the user wants changed in place | `config --set`, then re-judge the stored runs (*Changing a gate in place*) |
11
+ | An observer added, or `runs_per_iteration` raised | `config --set` or `--add-observer`, and tell the user |
12
+ | The iterations so far are not worth keeping, the baseline is | **reset** (*Starting the ideas over*) |
13
+
14
+ ## A second search beside the first
15
+
16
+ When the constraint itself is the question, do not change the gate
17
+ mid-search. `init` a second search whose baseline is the first's current winner,
18
+ and run both:
19
+
20
+ | | |
21
+ |---|---|
22
+ | Each keeps its own frontier, spec and dashboard | neither contaminates the other |
23
+ | Both gate against the **same original reference** | their numbers stay commensurable |
24
+ | The strict one keeps producing a result that can be used | while the looser one explores |
25
+
26
+ - **Wins can flow back.** A change developed under the relaxed gate may turn
27
+ out bitwise exact and transplant into the strict search; check each looser
28
+ win for whether it is gate-clean.
29
+ - **A transplant is priced again, never assumed.** The same change can help
30
+ in one tree and hurt in the other; brief it with "measured at X there;
31
+ measure it here".
32
+ - **Halve each search's runs at once** (`gpus_per_agent`), so the total
33
+ concurrency is unchanged
34
+ (`references/step2-baseline.md`, *Measure what concurrency does to the
35
+ objective*).
36
+
37
+ ## Changing the objective or a gate
38
+
39
+ Every comparison already made was made under the definition in force before the change.
40
+
41
+ | Change | What it does to the record |
42
+ |---|---|
43
+ | a gate's threshold | every earlier `pass` and `FAIL` was judged differently; an iteration that failed may now pass and is still recorded as failed |
44
+ | the objective, or how the benchmark computes it | every median is a different measurement; the frontier means nothing |
45
+ | an observer added | harmless; earlier iterations have no value for it |
46
+ | `runs_per_iteration` raised | earlier iterations are `ok` with fewer runs; comparisons still hold. A gate against A0's output needs A0 to run the new seeds (`references/step2-baseline.md`, *A gate that compares against the baseline's output*) |
47
+
48
+ **A changed objective is a new search**: `init` a new `$WORK`, copy the
49
+ current winner's code in as its baseline, and tell the user the first search is
50
+ closed in favor of the new one, and why. When the new search keeps an
51
+ identity gate, copy the first search's `reference/` into it and compare against
52
+ that, so outputs are still checked against the original's rather than
53
+ drifting one search at a time. The only alternative is re-running every
54
+ iteration, at what the search cost. `config --set` refuses the objective and
55
+ `seed_base` for this reason, and the command once A0 has run; before that,
56
+ nothing was measured under the command, so it may be fixed.
57
+
58
+ ### Changing a gate in place
59
+
60
+ When the user asks for it:
61
+
62
+ ```bash
63
+ python3 $AO/autoopt.py config $WORK --set gates.max_abs_diff_vs_base.threshold=1e-4 \
64
+ --reason '<the user's words>'
65
+ python3 $AO/run_iteration.py $WORK/autooptimize/iterations/<id>
66
+ ```
67
+
68
+ `config` validates the change, writes `config.json` and appends the dated rule
69
+ with the reason to `spec.md`. A threshold changes no measurement, so nothing is
70
+ re-measured: running `run_iteration.py` on an iteration without `--rerun`
71
+ re-judges its stored runs under the new gate. Do it for the baseline and for
72
+ every iteration whose verdict the change could flip; one whose runs now pass
73
+ the gates runs the unit tests and the compare it had skipped. Iterations in
74
+ flight read `config.json` when they started and keep the gate they began under; re-judge
75
+ them once they settle. Tell the user.
76
+
77
+ With the task's checks, change `compare.py`'s rule to the new gate in the same
78
+ step. The next run of `run_iteration.py` caches A0's outputs again before any
79
+ compare, and every iteration it re-judges is compared again.
80
+
81
+ ## Starting the ideas over, keeping the baseline
82
+
83
+ The search is worth continuing but its iterations are not, such as a topic
84
+ split that turned out wrong or a round built on a premise the profile refuted.
85
+ The baseline is not paid for again. A bug in the
86
+ benchmark is not this case: it is in A0's code too, so it is a new search.
87
+
88
+ ```bash
89
+ python3 $AO/autoopt.py reset $WORK # report, change nothing
90
+ ```
91
+
92
+ Show the user the report and run `reset $WORK --apply` only after they agree:
93
+ it deletes records, not only artifacts. Copy anything worth keeping out
94
+ first, since a branch that reset drops takes its code with it:
95
+
96
+ ```bash
97
+ git -C $WORK/autooptimize/repo.git format-patch autoopt/0..autoopt/7 -o $WORK/finish/kept-ideas/
98
+ ```
99
+
100
+ | Kept | Removed |
101
+ |---|---|
102
+ | A0: worktree, branch, `result.json`, `runs/`, `README.md` | every other iteration's directory and branch |
103
+ | `config.json`, `spec.md`, `ideas.md`, `knowledge.md` | `rounds/*.md`, `validations/` |
104
+ | `reference/`, and anything else beside `iterations/` | the round counter and root history, reset to round 1 |
105
+ | | unreachable git objects, pruned with `gc --prune=now` |
106
+
107
+ What it puts back in order:
108
+
109
+ - **The root moves to `--new-root`**, and the round counter and root history
110
+ restart at round 1.
111
+ - **Every kept iteration's `meta.json` and `result.json` go back to round 1**;
112
+ A0 keeps round 0.
113
+ - **Unreachable git objects are pruned**, so the directory actually shrinks;
114
+ the bytes reclaimed are reported.
115
+
116
+ What it finds and leaves to the user:
117
+
118
+ - **A dashboard publisher watching this search** keeps serving the removed
119
+ iterations until it rescans. `reset` lists each pid, its output directory
120
+ and the command that stops it, and does not stop it: the window may be
121
+ somebody else's.
122
+ - **References in `ideas.md` and `knowledge.md` to iterations that will not
123
+ exist.** The files are kept, but a struck idea reading `A12: promoted`
124
+ against a missing A12 is a trap for the next reader, and once ids are reused it names
125
+ a new, unrelated iteration, so the ids are listed.
126
+
127
+ The objective, the gates and the reference are untouched, so iterations
128
+ measured before and after a reset are still comparable. Reset is not for a
129
+ changed objective: the measurements it keeps would be incommensurable with
130
+ every new one.
131
+
132
+ | Flag | Meaning |
133
+ |---|---|
134
+ | `--apply` | actually remove; without it, nothing is deleted |
135
+ | `--keep 0,7` | keep more than the baseline, comma separated |
136
+ | `--new-root 7` | which kept iteration becomes the root. Default: the lowest id in `--keep`; point it at a promoted winning iteration to carry the winner across |
137
+ | `--force` | remove iterations that have no `result.json`. They are running now or died mid-iteration, and removing a directory a live subagent writes into breaks that subagent |
138
+
139
+ It refuses, before touching anything, an id that does not exist and a `--keep`
140
+ naming an iteration with no `result.json`. Ids are reused afterwards: the next
141
+ free id is one past the highest kept id or directory set aside (`<id>.abandoned`),
142
+ and the report prints it.
143
+
144
+ **`reset` is not `prune`.** Prune deletes artifacts and keeps the record, so
145
+ the tables and the dashboard still show every iteration. Reset deletes the
146
+ record.