gpu-engine 0.0.0 → 0.0.1

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 (54) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +96 -2
  3. package/SPEC.md +988 -0
  4. package/THIRD_PARTY_NOTICES.md +29 -0
  5. package/dist/cli.d.mts +1 -0
  6. package/dist/cli.mjs +4 -0
  7. package/dist/harness.d.mts +132 -0
  8. package/dist/harness.mjs +1 -0
  9. package/dist/index.d.mts +98 -0
  10. package/dist/index.mjs +1 -0
  11. package/dist/load-o_thEAKC.mjs +258 -0
  12. package/dist/scaffold-CY5xhy-V.mjs +106 -0
  13. package/dist/types-BwigqFwr.d.mts +868 -0
  14. package/docs/apps.md +108 -0
  15. package/docs/cli.md +126 -0
  16. package/docs/data.md +101 -0
  17. package/docs/diagnostics.md +509 -0
  18. package/docs/harness.md +191 -0
  19. package/docs/layers.md +249 -0
  20. package/docs/measurements/auto-threshold.json +335 -0
  21. package/docs/measurements/auto-threshold.md +56 -0
  22. package/docs/measurements/real-gpu-2026-11-22.json +4718 -0
  23. package/docs/measurements/real-gpu-2026-11-22.md +75 -0
  24. package/docs/runtime.md +112 -0
  25. package/docs/sealed-test-set.md +107 -0
  26. package/docs/weights-format.md +138 -0
  27. package/llms.txt +24 -0
  28. package/package.json +68 -2
  29. package/skills/gpu-engine/SKILL.md +117 -0
  30. package/templates/common/AGENTS.md +27 -0
  31. package/templates/common/github/workflows/ci.yml +35 -0
  32. package/templates/common/gitignore +3 -0
  33. package/templates/common/package.template.json +27 -0
  34. package/templates/common/tsconfig.template.json +17 -0
  35. package/templates/pooled/NEW_MODEL_NAME.eval.ts +93 -0
  36. package/templates/pooled/NEW_MODEL_NAME.model.ts +11 -0
  37. package/templates/pooled/SPEC.md +31 -0
  38. package/templates/pooled/src/decode.ts +10 -0
  39. package/templates/pooled/src/index.ts +44 -0
  40. package/templates/pooled/src/weights.ts +4 -0
  41. package/templates/retrieve/NEW_MODEL_NAME.eval.ts +149 -0
  42. package/templates/retrieve/NEW_MODEL_NAME.model.ts +12 -0
  43. package/templates/retrieve/SPEC.md +33 -0
  44. package/templates/retrieve/data/table.jsonl +16 -0
  45. package/templates/retrieve/src/decode.ts +9 -0
  46. package/templates/retrieve/src/index.ts +45 -0
  47. package/templates/retrieve/src/table.ts +21 -0
  48. package/templates/retrieve/src/weights.ts +4 -0
  49. package/templates/tag/NEW_MODEL_NAME.eval.ts +114 -0
  50. package/templates/tag/NEW_MODEL_NAME.model.ts +11 -0
  51. package/templates/tag/SPEC.md +31 -0
  52. package/templates/tag/src/decode.ts +25 -0
  53. package/templates/tag/src/index.ts +44 -0
  54. package/templates/tag/src/weights.ts +4 -0
@@ -0,0 +1,868 @@
1
+ /** The codes a load or a run returns (SPEC.md section 9): the weights file codes and every `RUN_*` code. */
2
+ declare const runCodes: readonly ["WEIGHTS_FORMAT_INVALID", "WEIGHTS_VERSION_UNSUPPORTED", "WEIGHTS_DEFINITION_MISMATCH", "RUN_BACKEND_UNAVAILABLE", "RUN_GPU_FAILED", "RUN_INPUT_INVALID", "RUN_OUTPUT_NONFINITE", "RUN_FAILED", "RUN_MODEL_DESTROYED", "RUN_TABLE_MISSING"];
3
+ /** A code `loadModel` and `run` return. */
4
+ type RunCode = (typeof runCodes)[number];
5
+ /** Where a diagnostic points, when it points at a file. */
6
+ interface DiagnosticLocation {
7
+ readonly file?: string;
8
+ readonly line?: number;
9
+ }
10
+ /** Thrown at define time and by harness commands. Run-time code returns `[error, data]` instead. */
11
+ declare class GpuEngineError extends Error {
12
+ readonly diagnostic: Diagnostic;
13
+ constructor(entry: Diagnostic);
14
+ get code(): DiagnosticCode;
15
+ }
16
+ /** The full registry: the run-time codes, then the codes only the harness, the trainer and the CLI report. */
17
+ declare const diagnostics: {
18
+ PROJECT_FILE_MISSING: {
19
+ readonly why: "The folder has no `*.model.ts` or no `*.eval.ts` file.";
20
+ readonly fix: "Run the command in the model package folder, pass `--dir <path>`, or create the file with `gpu-engine new`.";
21
+ };
22
+ PROJECT_FILE_AMBIGUOUS: {
23
+ readonly why: "The folder has more than one `*.model.ts` or more than one `*.eval.ts` file.";
24
+ readonly fix: "Keep one model file and one eval file per package, or pass `--dir` to the package you mean.";
25
+ };
26
+ PROJECT_EXPORT_INVALID: {
27
+ readonly why: "The model or eval file does not default-export the result of `defineModel` or `defineEval`.";
28
+ readonly fix: "Write `export default defineModel({ ... })` in the model file and `export default defineEval(model, { ... })` in the eval file.";
29
+ };
30
+ PROJECT_IMPORT_FAILED: {
31
+ readonly why: "The model or eval file threw while it was imported: a syntax error, a missing import, or code at the top level that fails.";
32
+ readonly fix: "Run `node <file>` to see the full error, fix the file, then run the command again.";
33
+ };
34
+ PROJECT_STATE_INVALID: {
35
+ readonly why: "A file the harness keeps for itself, `tries.jsonl` or `.gpu-engine/candidate.json`, does not parse or has another shape: a line a killed `loop` left half-written, a hand edit, or a file written by an older version.";
36
+ readonly fix: "For `tries.jsonl`, restore it from git or delete the broken line; the harness only appends to it. For `.gpu-engine/candidate.json`, run `gpu-engine loop` to write a fresh candidate.";
37
+ };
38
+ DATA_SET_MISSING: {
39
+ readonly why: "One of the train, dev or test sets has no files.";
40
+ readonly fix: "Add JSONL files to the set folder, or declare a generator in `defineDataset` and run `gpu-engine loop` to write them.";
41
+ };
42
+ DATA_SET_TOO_SMALL: {
43
+ readonly why: "A set has fewer examples than `minSize` asks for.";
44
+ readonly fix: "Add examples or raise the generator count. Lower `minSize` only when the smaller set still measures the model.";
45
+ };
46
+ DATA_SPLIT_OVERLAP: {
47
+ readonly why: "The same example, after normalising case and whitespace, appears in two sets, so a score there measures memory.";
48
+ readonly fix: "Remove the shared examples from one of the sets. Change the test set only by hand, then delete its lock entry and rerun.";
49
+ };
50
+ DATA_GROUP_SHARED: {
51
+ readonly why: "A declared group appears in more than one set, so the split does not test anything new.";
52
+ readonly fix: "Move every example of the group into one set.";
53
+ };
54
+ DATA_VOCAB_SHARED: {
55
+ readonly why: "A declared vocabulary word appears in more than one set, so the model can pass by memorising words.";
56
+ readonly fix: "Split the vocabulary so each word belongs to one set, or drop the word from the `vocab` field of those rows when sharing it is intended.";
57
+ };
58
+ DATA_HASH_CHANGED: {
59
+ readonly why: "A data file no longer matches the hash recorded in `data.lock.json`.";
60
+ readonly fix: "Restore the file. If the change is intended, delete that set from `data.lock.json` by hand and rerun to record the new hash.";
61
+ };
62
+ DATA_GENERATOR_CHANGED: {
63
+ readonly why: "A train or dev generator no longer writes the file it wrote before. Generators only run into an empty folder, so without this check `loop` would keep training on the old rows and ignore the edit.";
64
+ readonly fix: "Run `gpu-engine loop --regenerate train` (or `dev`, or `train,dev`) to rewrite the file and its lock entry, or undo the generator change. The test set is never regenerated.";
65
+ };
66
+ DATA_TEST_READ: {
67
+ readonly why: "Something other than `promote` read or referenced the sealed test set.";
68
+ readonly fix: "Remove the reference. Only the `sealed('data/test/...')` call in the eval file may name the test folder, and only `gpu-engine promote` reads it.";
69
+ };
70
+ DATA_TEST_PRINTED: {
71
+ readonly why: "A test example or a test-only field was about to be printed or written to a file, or the package code wrote one into a file the promote workflow commits.";
72
+ readonly fix: "Report test results as per-set aggregates only. Tries rows hold dev scores only. Never print or write from `metric`, `decode` or a baseline.";
73
+ };
74
+ BUDGET_BYTES_EXCEEDED: {
75
+ readonly why: "The Brotli-compressed weights are larger than `budgets.brotliBytes`.";
76
+ readonly fix: "Shrink the model (hash buckets, layer sizes) or raise the budget.";
77
+ };
78
+ GATE_FLOOR_FAILED: {
79
+ readonly why: "A set scored below the last promoted score minus the gate noise.";
80
+ readonly fix: "Keep tuning on dev with `gpu-engine loop` until every set is back above its floor.";
81
+ };
82
+ GATE_FILE_INVALID: {
83
+ readonly why: "`gate.json` is not `{ level, promoted }` with `promoted` null or a promoted entry with dev and test scores.";
84
+ readonly fix: "Restore `gate.json` from history. Only `gpu-engine promote` and `promote --seal` write it.";
85
+ };
86
+ TRAIN_DIVERGED: {
87
+ readonly why: "Every checkpoint of a seed holds a weight that is not finite, or scores a dev loss that is not finite: the loss stopped being finite and training never recovered, so there are no weights to keep.";
88
+ readonly fix: "Lower `train.learningRate` or raise `train.warmup`, then run `gpu-engine loop` again.";
89
+ };
90
+ PROMOTE_CANDIDATE_MISSING: {
91
+ readonly why: "There is no candidate to promote.";
92
+ readonly fix: "Run `gpu-engine loop` first. It writes the candidate that `promote` scores.";
93
+ };
94
+ PROMOTE_CANDIDATE_STALE: {
95
+ readonly why: "The model definition or the data changed after the candidate was trained.";
96
+ readonly fix: "Run `gpu-engine loop` to train a fresh candidate, then promote.";
97
+ };
98
+ PROMOTE_SCORE_FAILED: {
99
+ readonly why: "`metric`, `decode` or a baseline threw while `promote` scored a test set, or the package code raised an unhandled promise rejection or an uncaught exception after the read. Its message is not shown, since it can quote a test example.";
100
+ readonly fix: "Make `metric`, `decode` and the baselines return a value for every input and gold the head can produce and start no promise they leave unhandled, check them on dev with `gpu-engine loop --fail`, then promote again.";
101
+ };
102
+ PROMOTE_OUTSIDE_CI: {
103
+ readonly why: "The test set is sealed at level 3, so `promote` only runs in CI.";
104
+ readonly fix: "Run the `promote` workflow in CI. It holds the key in the `GPU_ENGINE_TEST_KEY` secret.";
105
+ };
106
+ SEAL_KEY_MISSING: {
107
+ readonly why: "The test set is encrypted and no key was given.";
108
+ readonly fix: "Set `GPU_ENGINE_TEST_KEY` in the CI secret store. The key never goes into the repository.";
109
+ };
110
+ SEAL_KEY_INVALID: {
111
+ readonly why: "The key is not 64 hex characters, or it does not decrypt the sealed test set.";
112
+ readonly fix: "Set `GPU_ENGINE_TEST_KEY` to the key written by `gpu-engine promote --seal`.";
113
+ };
114
+ SEAL_REFUSED: {
115
+ readonly why: "`promote --seal` cannot seal this package: it is already at level 3, a sealed file or `.github/workflows/promote.yml` already exists, or the key path is inside the working tree or names a file that exists.";
116
+ readonly fix: "Seal once per package. Pass `--key-out` with a new file outside the repository, and move an existing promote workflow aside first.";
117
+ };
118
+ SEAL_PLAINTEXT_FOUND: {
119
+ readonly why: "The package is sealed at level 3, but a plaintext test file is in the test folder, where any agent can read it.";
120
+ readonly fix: "Delete the plaintext file. The sealed `.enc` file beside it holds the test set, and only the promote workflow in CI decrypts it.";
121
+ };
122
+ SEAL_LOCK_INVALID: {
123
+ readonly why: "The test entry of `data.lock.json` does not describe the sealed files: it is missing, names a file that is not sealed, or lacks a `plaintext` hash. A sealed set cannot be fingerprinted again without the key.";
124
+ readonly fix: "Restore `data.lock.json` and the `.enc` files from the commit that sealed them.";
125
+ };
126
+ SEAL_GENERATOR_FOUND: {
127
+ readonly why: "The eval file declares `generate.test`. With that generator and `seed`, anyone who can read the eval file rebuilds the sealed test rows without the key, so level 3 guarantees nothing.";
128
+ readonly fix: "Remove `test` from `defineDataset({ generate })`, or move the generator to a script outside the package, then seal or run `doctor` again. The test set it already wrote stays.";
129
+ };
130
+ SEAL_WORKFLOW_MISSING: {
131
+ readonly why: "The package is sealed at level 3, but `.github/workflows/promote.yml` is missing or does not run `gpu-engine promote` and `gpu-engine promote --scan` with `GPU_ENGINE_TEST_KEY`, so nothing can promote it safely.";
132
+ readonly fix: "Restore `.github/workflows/promote.yml` from the commit that sealed the test set. A workflow written before `promote --scan` existed: move it aside and run `promote --seal` on a fresh copy, or add the scan step before the commit step by hand.";
133
+ };
134
+ SEAL_HISTORY_PLAINTEXT: {
135
+ readonly why: "The test set is sealed now, but git history still holds the plaintext test files, so anyone with a clone can read the rows from an old commit.";
136
+ readonly fix: "Purge the plaintext files from every branch (`git filter-repo --invert-paths --path <file>`), force-push and replace every clone, or write a new test set that was never committed in plaintext and seal that. `docs/sealed-test-set.md` shows both.";
137
+ };
138
+ PROMOTE_SCAN_FAILED: {
139
+ readonly why: "`data.lock.json` at git `HEAD` (or in the working tree outside git) names no test file, so `promote --scan` has nothing to scan the committed files with. It changed nothing.";
140
+ readonly fix: "Run `gpu-engine loop` so the data step records the test set in `data.lock.json`, commit the lock, then scan again.";
141
+ };
142
+ VERIFY_SCORE_CHANGED: {
143
+ readonly why: "Re-scoring the committed weights on dev does not give the scores in `report.json`.";
144
+ readonly fix: "Run `gpu-engine promote` again to write a report for these weights. Never edit `report.json` by hand.";
145
+ };
146
+ VERIFY_WEIGHTS_CHANGED: {
147
+ readonly why: "The committed weights do not match the hash in `report.json`.";
148
+ readonly fix: "Restore the promoted weights, or run `gpu-engine promote` again.";
149
+ };
150
+ VERIFY_FILE_STALE: {
151
+ readonly why: "A generated file (`MODEL_CARD.md`, `RESULTS.md`, `src/weights.ts`) does not match what the report regenerates.";
152
+ readonly fix: "Run `gpu-engine promote` again. Never edit generated files by hand.";
153
+ };
154
+ VERIFY_READS_MISSING: {
155
+ readonly why: "`reads.jsonl` has fewer test reads than the report counts.";
156
+ readonly fix: "Restore `reads.jsonl` from history. The read log is append-only.";
157
+ };
158
+ VERIFY_REPORT_INVALID: {
159
+ readonly why: "`report.json` is missing or is not the report `gpu-engine promote` writes.";
160
+ readonly fix: "Run `gpu-engine promote` to write it, or restore it from history. Never edit `report.json` by hand.";
161
+ };
162
+ PARITY_ADAPTER_MISSING: {
163
+ readonly why: "No WebGPU adapter was found, so the WGSL output cannot be compared.";
164
+ readonly fix: "Install the `webgpu` package in the model package (`npm install --save-dev webgpu@^0.6.2`) and a Vulkan driver (on Linux, `apt-get install mesa-vulkan-drivers` for lavapipe).";
165
+ };
166
+ PARITY_DECODE_DIFFERS: {
167
+ readonly why: "The WGSL and CPU outputs decode to different results on a fixture.";
168
+ readonly fix: "Find the layer that diverges with the layer tests in `test/gpu`, and fix its WGSL template.";
169
+ };
170
+ PARITY_TOLERANCE_EXCEEDED: {
171
+ readonly why: "The largest logit difference between WGSL and CPU is above `parity.tolerance`.";
172
+ readonly fix: "Fix the diverging WGSL template. Raise `parity.tolerance` only with a measured reason.";
173
+ };
174
+ SHIP_SIZE_EXCEEDED: {
175
+ readonly why: "The built model package, with its weights, is larger than `ship.brotliBytes` after Brotli.";
176
+ readonly fix: "Shrink the model or the decode code, or raise `ship.brotliBytes`.";
177
+ };
178
+ SHIP_PACKAGE_INVALID: {
179
+ readonly why: "The ship checks read what the package ships from `package.json` and `npm pack --dry-run --json`, and one of them is missing, does not parse or failed.";
180
+ readonly fix: "Run doctor in the model package folder, fix `package.json` until `npm pack --dry-run` lists its files, and check that `npm` is on the PATH.";
181
+ };
182
+ SHIP_DEPENDENCY_FOUND: {
183
+ readonly why: "The model package declares a runtime dependency (`dependencies`, `peerDependencies`, `optionalDependencies` or `bundleDependencies`), or a shipped script imports another module. The shipped model must have zero runtime dependencies.";
184
+ readonly fix: "Move the package to `devDependencies` and bundle what the model needs into the build with `npm run build`.";
185
+ };
186
+ SHIP_BUILD_STALE: {
187
+ readonly why: "The package has promoted weights, or a report that records a retrieve table, but no packed file holds those weights or that table, so the build predates the promotion and would ship another model than the one measured.";
188
+ readonly fix: "Run `npm run build` (`gpu-engine build`) after `gpu-engine promote` or a table change, then run doctor again.";
189
+ };
190
+ SHIP_FILE_NOT_ALLOWED: {
191
+ readonly why: "The packed model package contains a file outside `ship.files`.";
192
+ readonly fix: "Add the file to `files` in package.json only if it must ship, and list it in `ship.files`; otherwise exclude it.";
193
+ };
194
+ BUILD_SOURCE_UNSUPPORTED: {
195
+ readonly why: "`gpu-engine build` bundles static ES module syntax into one module that runs in browsers, and a bundled file uses something it cannot bundle: a dynamic `import()`, an import with attributes, a JSON file, a Node built-in, an absolute path, an import cycle, TypeScript syntax that has no erasable form, an export a `let` or `var` holds (the bundle reads it once), or a top-level `await` (each module runs inside a function); or the declarations it wrote for an exported type would not typecheck.";
196
+ readonly fix: "Import with a static `import` from a relative path or an installed package, export data from a `.ts` file instead of JSON, export a `const` (or a function that returns the current value), move an `await` into an async function, keep Node-only code out of `src/index.ts` and what it imports, and export the types and symbols an exported type names.";
197
+ };
198
+ BUILD_IMPORT_UNRESOLVED: {
199
+ readonly why: "A module that `src/index.ts` reaches imports a file that does not exist or a package that is not installed, or the package exports no ES module entry for that path.";
200
+ readonly fix: "Check the path, with its `.ts` extension, or run `npm install`.";
201
+ };
202
+ BUILD_TYPES_FAILED: {
203
+ readonly why: "`gpu-engine build` writes `dist/index.d.mts` with the TypeScript checker, and TypeScript is not installed, the package has a type error, or an export is a kind the declarations cannot hold (a class, an enum or a namespace).";
204
+ readonly fix: "Install TypeScript (`npm install --save-dev typescript`), fix what `npx tsc -p .` reports, and export functions, constants, interfaces and type aliases from `src/index.ts`.";
205
+ };
206
+ NEW_NAME_INVALID: {
207
+ readonly why: "The model name becomes the package name, the file names and the weights file name, so it must be a lowercase npm package name without a scope.";
208
+ readonly fix: "Use lowercase letters, digits and `-`, starting with a letter, at most 64 characters, such as `unit-phrases`.";
209
+ };
210
+ NEW_TARGET_EXISTS: {
211
+ readonly why: "`gpu-engine new` writes a fresh package and never overwrites a file, and the target folder already holds files.";
212
+ readonly fix: "Pick another name, pass `--dir` to create the package somewhere else, or remove the folder first.";
213
+ };
214
+ CLI_COMMAND_UNKNOWN: {
215
+ readonly why: "The command is not one of `new`, `loop`, `promote`, `parity`, `inspect`, `doctor` or `build`.";
216
+ readonly fix: "Run `gpu-engine --help` to see the commands.";
217
+ };
218
+ CLI_FLAG_INVALID: {
219
+ readonly why: "A flag is unknown for this command, is missing its value, is given twice, would be ignored, or cannot be combined with another flag given, or a required argument is missing.";
220
+ readonly fix: "Run `gpu-engine <command> --help` to see its arguments and flags.";
221
+ };
222
+ DEFINE_NET_ORDER: {
223
+ readonly why: "`net` must start with exactly one `embed` layer, and `embed` may not appear anywhere else.";
224
+ readonly fix: "Put one `layers.embed({ size })` first in `net` and remove any other `embed` layer.";
225
+ };
226
+ DEFINE_LAYER_SHAPE: {
227
+ readonly why: "A layer has a size, tap count or activation it cannot run with.";
228
+ readonly fix: "Use positive integer sizes, an odd `taps` of at least 1, and an activation from `relu`, `tanh` or `none`.";
229
+ };
230
+ DEFINE_FEATURE_ROW: {
231
+ readonly why: "The token input cannot be featurized: it is not `features.tokens(...)`, `max` or `buckets` is not a positive integer, `k` is outside 1 to `buckets`, `rows` is empty or has an unknown kind, a flag name is empty, or a shape row or a flag name repeats.";
232
+ readonly fix: "Give `features.tokens` a positive integer `max` and at least one row, keep `k` between 1 and `buckets`, use one `features.shape()` and distinct non-empty flag names.";
233
+ };
234
+ DEFINE_HEAD_LABELS: {
235
+ readonly why: "The head cannot be built from its labels: fewer than two labels, a duplicate label, or both or neither of `labels` and `outputs`.";
236
+ readonly fix: "Give the head two or more distinct `labels`, or for a pooled values head only `outputs`.";
237
+ };
238
+ DEFINE_BUDGET_EXCEEDED: {
239
+ readonly why: "The layers already exceed a budget before any training: multiply-adds per token, or a packed int6 size that cannot fit the Brotli budget.";
240
+ readonly fix: "Shrink a layer (embed size, scan size, dense size, hash buckets) or raise the budget in `budgets`.";
241
+ };
242
+ DEFINE_QUANT_INVALID: {
243
+ readonly why: "`quant` is not int6 quantization with `qatFrom` a finite share of the run from 0 to 1.";
244
+ readonly fix: "Write `quant: int6({ qatFrom })` with `qatFrom` from 0 to 1, such as 0.7, or leave `quant` out for float32 weights.";
245
+ };
246
+ DEFINE_BUDGET_INVALID: {
247
+ readonly why: "A budget is not a positive integer, so no size or multiply-add count can be compared against it.";
248
+ readonly fix: "Give `budgets.brotliBytes` and `budgets.macsPerToken` positive integers, such as `{ brotliBytes: 5_000, macsPerToken: 3_200 }`.";
249
+ };
250
+ DEFINE_NAME_INVALID: {
251
+ readonly why: "The model name names the weights file, `weights/<name>.bin`, and the package, so it must be a lowercase name that cannot leave the `weights/` folder.";
252
+ readonly fix: "Use lowercase letters, digits and `-`, starting with a letter, at most 64 characters, such as `unit-phrases`.";
253
+ };
254
+ DEFINE_DATA_INVALID: {
255
+ readonly why: "`data` cannot generate or check the sets: `seed` is not a safe integer, a `minSize` count is not a positive integer, or a `generate` entry is not a function.";
256
+ readonly fix: "Write `defineDataset({ seed: 1, minSize: { train, dev, test } })` with positive integer counts, and give `generate` only functions `(random) => examples`.";
257
+ };
258
+ DEFINE_TRAIN_INVALID: {
259
+ readonly why: "`train` cannot run: `seeds` is empty, repeats a seed or holds a non-integer, `epochs` or `batch` is not a positive integer, `learningRate` or `budgetSeconds` is not a finite number above 0, `warmup` is outside 0 up to 1, or `negatives` is not a positive integer (a retrieve head needs it).";
260
+ readonly fix: "Write every option out, such as `{ seeds: [1, 2, 3], epochs: 20, batch: 32, learningRate: 0.01, warmup: 0.1, budgetSeconds: 40 }`, and add `negatives: 8` for a retrieve head.";
261
+ };
262
+ DEFINE_GATE_INVALID: {
263
+ readonly why: "`gate` cannot compare scores: `floors` is not `promoted`, or `noise` is not a finite number of at least 0.";
264
+ readonly fix: "Write `gate: { floors: 'promoted', noise }` with `noise` at or above the measured seed spread, such as 0.05.";
265
+ };
266
+ DEFINE_PARITY_INVALID: {
267
+ readonly why: "`parity` is not an object, or its `tolerance` is not a finite number of at least 0, so no logit difference can be compared with it.";
268
+ readonly fix: "Write `parity: { tolerance: 1e-3 }`, and raise it only with a measured reason.";
269
+ };
270
+ DEFINE_SHIP_INVALID: {
271
+ readonly why: "`ship` is present, and `brotliBytes` is not a positive integer or `files` is not a non-empty list of paths.";
272
+ readonly fix: "Write `ship: { brotliBytes: 40_000, files: ['dist/index.mjs'] }`, or leave `ship` out.";
273
+ };
274
+ DEFINE_EVAL_INVALID: {
275
+ readonly why: "The eval cannot score: `metric` is not a function, `decode` is not a function, or `baselines` is not an object of functions.";
276
+ readonly fix: "Give `metric: (pred, gold) => number`, an optional `decode: (raw, input) => result`, and `baselines` as named functions `(input) => result` (`{}` for none).";
277
+ };
278
+ DEFINE_SET_FOLDER: {
279
+ readonly why: "Each set must live in its own folder: train in `data/train/`, dev in `data/dev/`, test in `data/test/`, each path written plainly, without `.` or `..` segments. The retrieve table lives inside the package, outside those folders.";
280
+ readonly fix: "Move the files and point `sets` at `data/train/*.jsonl`, `data/dev/*.jsonl` and `sealed('data/test/*.jsonl')`.";
281
+ };
282
+ DEFINE_EVAL_MODEL: {
283
+ readonly why: "`defineEval` takes the model definition first, so it can type the decode, the baselines and the metric from the head, and the eval definition second.";
284
+ readonly fix: "Import the model file's default export in the eval file and write `export default defineEval(model, { ... })`.";
285
+ };
286
+ WEIGHTS_FORMAT_INVALID: {
287
+ readonly why: "The bytes are not a gpu-engine weights file: the magic, a length or a tensor record is wrong.";
288
+ readonly fix: "Load the `weights/<name>.bin` file written by `gpu-engine promote`, or re-export it with the byte layout in SPEC.md section 5.";
289
+ };
290
+ WEIGHTS_VERSION_UNSUPPORTED: {
291
+ readonly why: "The weights file uses a format version this runtime does not read.";
292
+ readonly fix: "Upgrade gpu-engine, or re-export the weights with the format version this runtime reads.";
293
+ };
294
+ WEIGHTS_DEFINITION_MISMATCH: {
295
+ readonly why: "The definition hash or a tensor shape in the file does not match the definition the file carries.";
296
+ readonly fix: "Load weights trained from this definition. In a model package a changed model file is expected while tuning: run `gpu-engine loop` to train a candidate from it, and promote once when the tuning is done, not after every try.";
297
+ };
298
+ RUN_BACKEND_UNAVAILABLE: {
299
+ readonly why: "The requested backend cannot run here: WebGPU is missing or no adapter was found.";
300
+ readonly fix: "Use `backend: 'auto'` or `'cpu'`, or pass a WebGPU entry point as `gpu` (in Node, the `webgpu` package).";
301
+ };
302
+ RUN_GPU_FAILED: {
303
+ readonly why: "The GPU device was lost or reported a validation error while running the model.";
304
+ readonly fix: "Retry with `backend: 'cpu'`, and run `gpu-engine parity` to check the WGSL output.";
305
+ };
306
+ RUN_INPUT_INVALID: {
307
+ readonly why: "The input is not a string or a `{ text, flags }` object, or a flag list does not have one entry per token.";
308
+ readonly fix: "Pass a string, or `{ text, flags }` where each flag array has one boolean per token of `text`.";
309
+ };
310
+ RUN_OUTPUT_NONFINITE: {
311
+ readonly why: "The model produced a logit or a score that is not a finite number, so decoding it would give a label chosen by accident or `Infinity`.";
312
+ readonly fix: "Check the weights file with `gpu-engine parity`; weights this large overflow float32, so retrain with a lower `train.learningRate`.";
313
+ };
314
+ RUN_FAILED: {
315
+ readonly why: "The model loaded, but running it failed for a reason no other run code covers, such as an op that throws.";
316
+ readonly fix: "Run `gpu-engine inspect \"<text>\"` on the same input to see which step fails, and report it with the weights file.";
317
+ };
318
+ RUN_MODEL_DESTROYED: {
319
+ readonly why: "The model was destroyed with `model.destroy()`, which freed its GPU buffers and device, so it cannot run again.";
320
+ readonly fix: "Call `destroy()` only when the model is no longer needed, or load the weights again with `loadModel`.";
321
+ };
322
+ RUN_TABLE_MISSING: {
323
+ readonly why: "A retrieve model needs a table of rows to score the input against.";
324
+ readonly fix: "Pass `table` to `loadModel`: the `{ id, text }` rows the model ranks.";
325
+ };
326
+ DATA_ROW_INVALID: {
327
+ readonly why: "A data row is not valid JSON or does not have the `{ input, gold }` shape the head needs.";
328
+ readonly fix: "Write one JSON object per line with `input` (text or `{ text, flags }`) and `gold` in the shape of the head.";
329
+ };
330
+ DATA_LABEL_UNKNOWN: {
331
+ readonly why: "A gold label is not one of the head labels.";
332
+ readonly fix: "Fix the label in the data, or add it to the head `labels` in the model file.";
333
+ };
334
+ };
335
+ type DiagnosticCode = keyof typeof diagnostics;
336
+ /** Builds a diagnostic for `code` with its registered why and fix. `message` names files and counts, never examples. */
337
+ declare function diagnostic(code: DiagnosticCode, message: string, location?: DiagnosticLocation): Diagnostic;
338
+ /** Shorthand for `new GpuEngineError(diagnostic(code, message, location))`. */
339
+ declare function engineError(code: DiagnosticCode, message: string, location?: DiagnosticLocation): GpuEngineError;
340
+ /** Formats a diagnostic the way the CLI prints it. */
341
+ declare function formatDiagnostic(entry: Diagnostic): string;
342
+ /** Character class and length bucket of a token. */
343
+ interface ShapeRow {
344
+ readonly kind: 'shape';
345
+ }
346
+ /** `k` distinct hashed rows of the lowercased token among `buckets` embedding rows. */
347
+ interface HashRow {
348
+ readonly kind: 'hash';
349
+ readonly buckets: number;
350
+ readonly k: number;
351
+ }
352
+ /** One embedding row, on for a token when the caller's flag `name` is true for it. */
353
+ interface FlagRow<Name extends string = string> {
354
+ readonly kind: 'flag';
355
+ readonly name: Name;
356
+ }
357
+ /** One feature row computed for every token by the shared featurizer. */
358
+ type FeatureRow = ShapeRow | HashRow | FlagRow;
359
+ /** Token input: the text is split into at most `max` tokens, each with the given feature rows. */
360
+ interface TokensInput<Rows extends readonly FeatureRow[] = readonly FeatureRow[]> {
361
+ readonly kind: 'tokens';
362
+ readonly max: number;
363
+ readonly rows: Rows;
364
+ }
365
+ /** The closed layer catalog of the first version. */
366
+ type LayerKind = 'embed' | 'conv' | 'biScan' | 'dense';
367
+ type Activation = 'relu' | 'tanh' | 'none';
368
+ interface EmbedLayer {
369
+ readonly kind: 'embed';
370
+ readonly size: number;
371
+ }
372
+ interface ConvLayer {
373
+ readonly kind: 'conv';
374
+ readonly taps: number;
375
+ }
376
+ interface BiScanLayer {
377
+ readonly kind: 'biScan';
378
+ readonly size: number;
379
+ }
380
+ interface DenseLayer {
381
+ readonly kind: 'dense';
382
+ readonly size: number;
383
+ readonly activation: Activation;
384
+ }
385
+ type Layer = EmbedLayer | ConvLayer | BiScanLayer | DenseLayer;
386
+ type HeadKind = 'tag' | 'pooled' | 'retrieve';
387
+ /** A label for every token. */
388
+ interface TagHead<Labels extends readonly string[] = readonly string[]> {
389
+ readonly kind: 'tag';
390
+ readonly labels: Labels;
391
+ }
392
+ /** One class for the whole input. */
393
+ interface PooledClassHead<Labels extends readonly string[] = readonly string[]> {
394
+ readonly kind: 'pooled';
395
+ readonly labels: Labels;
396
+ }
397
+ /** A fixed number of values for the whole input. */
398
+ interface PooledValuesHead {
399
+ readonly kind: 'pooled';
400
+ readonly outputs: number;
401
+ }
402
+ /** One score for the input against each row of a table, through one shared tower. */
403
+ interface RetrieveHead {
404
+ readonly kind: 'retrieve';
405
+ readonly size: number;
406
+ }
407
+ type Head = TagHead | PooledClassHead | PooledValuesHead | RetrieveHead;
408
+ /** int6 quantization-aware training, starting at `qatFrom` (a share of the run, 0 to 1). */
409
+ interface Int6Quantization {
410
+ readonly kind: 'int6';
411
+ readonly qatFrom: number;
412
+ }
413
+ interface Budgets {
414
+ readonly brotliBytes: number;
415
+ readonly macsPerToken: number;
416
+ }
417
+ interface ModelDefinition {
418
+ readonly name: string;
419
+ readonly input: TokensInput;
420
+ readonly net: readonly Layer[];
421
+ readonly head: Head;
422
+ readonly quant?: Int6Quantization;
423
+ readonly budgets: Budgets;
424
+ }
425
+ /** The part of a definition the weights file carries and hashes. Budgets are not part of it. */
426
+ type CanonicalDefinition = Omit<ModelDefinition, 'budgets'>;
427
+ /** One table row in a retrieve head's ranking. */
428
+ interface RetrieveMatch<Id extends string = string> {
429
+ readonly id: Id;
430
+ readonly score: number;
431
+ }
432
+ /**
433
+ * The raw output a head produces, inferred from the definition: labels type the result. A retrieve head ranks every
434
+ * table row, highest score first; the table's ids type `id`.
435
+ */
436
+ type HeadOutput<H extends Head, Id extends string = string> = H extends TagHead<infer Labels> ? Labels[number][] : H extends PooledClassHead<infer Labels> ? Labels[number] : H extends RetrieveHead ? RetrieveMatch<Id>[] : number[];
437
+ type ModelOutput<D extends ModelDefinition, Id extends string = string> = HeadOutput<D['head'], Id>;
438
+ /** What a model runs on: text, or text with one boolean per token for each declared flag. */
439
+ type ModelInput = string | {
440
+ readonly text: string;
441
+ readonly flags?: Readonly<Record<string, readonly boolean[]>>;
442
+ };
443
+ /** The names of the flag rows a definition declares; `never` when it declares none. */
444
+ type FlagNames<D extends ModelDefinition> = Extract<D['input']['rows'][number], FlagRow>['name'];
445
+ /**
446
+ * The input an eval's `decode` and baselines receive for model `D`: the text for a model without flag rows, else the
447
+ * input as the data row holds it, text or `{ text, flags? }` with the declared flag names (SPEC.md section 11). A
448
+ * definition whose flag names are not known (`string`) gets `ModelInput`.
449
+ */
450
+ type EvalInput<D extends ModelDefinition = ModelDefinition> = [FlagNames<D>] extends [never] ? string : string extends FlagNames<D> ? ModelInput : string | {
451
+ readonly text: string;
452
+ readonly flags?: Readonly<Partial<Record<FlagNames<D>, readonly boolean[]>>>;
453
+ };
454
+ interface Token {
455
+ readonly text: string;
456
+ readonly start: number;
457
+ readonly end: number;
458
+ }
459
+ /** The block of embedding rows and slots one feature row owns. */
460
+ interface FeatureBlock {
461
+ readonly feature: FeatureRow;
462
+ /** First embedding row of this block. */
463
+ readonly row: number;
464
+ readonly rows: number;
465
+ /** First slot of this block in a token's slot list. */
466
+ readonly slot: number;
467
+ readonly slots: number;
468
+ }
469
+ interface RowLayout {
470
+ /** Slots per token. */
471
+ readonly slots: number;
472
+ /** Embedding rows in total. */
473
+ readonly rows: number;
474
+ readonly blocks: readonly FeatureBlock[];
475
+ }
476
+ /** Featurizer output: `rows[t * slots + s]` is an embedding row index, `-1` for an empty slot. */
477
+ interface FeatureRows {
478
+ readonly count: number;
479
+ readonly slots: number;
480
+ readonly rows: Int32Array;
481
+ }
482
+ /** A seeded source of uniform numbers in [0, 1). */
483
+ type Random = () => number;
484
+ /** Everything one op can be planned from: a layer or a head. */
485
+ type OpSpec = Layer | Head;
486
+ type OpKind = OpSpec['kind'];
487
+ /** A tensor shape an op asks for, before the plan places it. */
488
+ interface TensorShape {
489
+ readonly name: string;
490
+ readonly shape: readonly number[];
491
+ }
492
+ /** A tensor placed in the one `Float32Array` of all parameters. */
493
+ interface TensorSpec extends TensorShape {
494
+ readonly offset: number;
495
+ readonly length: number;
496
+ }
497
+ interface OpPlan<S extends OpSpec = OpSpec> {
498
+ readonly index: number;
499
+ readonly spec: S;
500
+ readonly inWidth: number;
501
+ readonly outWidth: number;
502
+ readonly tensors: readonly TensorSpec[];
503
+ /** Multiply-adds per token. */
504
+ readonly macs: number;
505
+ }
506
+ interface ModelPlan {
507
+ readonly definition: CanonicalDefinition;
508
+ readonly layout: RowLayout;
509
+ /** Net layers in order, then the head's op. */
510
+ readonly ops: readonly OpPlan[];
511
+ /** Parameter count: the length of the weights array. */
512
+ readonly size: number;
513
+ readonly macsPerToken: number;
514
+ readonly slots: number;
515
+ readonly rows: number;
516
+ readonly maxTokens: number;
517
+ /** Width of the logits per token (per input for pooled and retrieve heads). */
518
+ readonly outWidth: number;
519
+ /** Definition hash, as written in the weights file header. */
520
+ readonly hash: string;
521
+ }
522
+ /** One tensor as stored: int6 levels (-31..31) with a scale, or raw float32 values. */
523
+ interface EncodedTensor {
524
+ readonly name: string;
525
+ readonly shape: readonly number[];
526
+ readonly bitWidth: 6 | 32;
527
+ readonly scale: number;
528
+ readonly values: Int8Array | Float32Array;
529
+ }
530
+ /** A decoded weights file. `encode(decode(bytes))` is byte-identical. */
531
+ interface WeightsFile {
532
+ readonly version: number;
533
+ readonly hash: string;
534
+ readonly definition: CanonicalDefinition;
535
+ readonly tensors: readonly EncodedTensor[];
536
+ }
537
+ /** A test set that only `promote` may read. */
538
+ interface SealedSet {
539
+ readonly kind: 'sealed';
540
+ readonly path: string;
541
+ }
542
+ type SetKind = 'train' | 'dev' | 'test';
543
+ interface EvalSets {
544
+ readonly train: string;
545
+ readonly dev: string;
546
+ readonly test: SealedSet;
547
+ }
548
+ /** Gold in the shape of the head: tags per token, one label, values, or table row ids. */
549
+ type Gold = readonly string[] | string | readonly number[];
550
+ /** One data row. Scores compare against `expect` when present, else against `decode(gold)`. */
551
+ interface Example<Output = unknown> {
552
+ readonly input: ModelInput;
553
+ readonly gold: Gold;
554
+ readonly expect?: Output;
555
+ readonly group?: string;
556
+ /** Words no two sets may share (`DATA_VOCAB_SHARED`), such as the unit words when the test units must be unseen. */
557
+ readonly vocab?: readonly string[];
558
+ }
559
+ /** Generates the examples of one set from a seeded random source. */
560
+ type DatasetGenerator<Output = unknown> = (random: Random) => readonly Example<Output>[];
561
+ interface DatasetDefinition<Output = unknown> {
562
+ readonly seed: number;
563
+ readonly minSize: Readonly<Record<SetKind, number>>;
564
+ /** A generator per set, each optional. At level 3 there is no `test` generator (SPEC.md section 7, Level 3). */
565
+ readonly generate?: Readonly<Partial<Record<SetKind, DatasetGenerator<Output>>>>;
566
+ }
567
+ interface TrainOptions {
568
+ readonly seeds: readonly number[];
569
+ readonly epochs: number;
570
+ readonly batch: number;
571
+ readonly learningRate: number;
572
+ /** Share of the planned steps spent on linear warm-up, 0 to 1. */
573
+ readonly warmup: number;
574
+ /** Wall-clock budget for all seeds together. */
575
+ readonly budgetSeconds: number;
576
+ /** Retrieve heads only, and required there: other table rows each example trains against, drawn per step. */
577
+ readonly negatives?: number;
578
+ }
579
+ interface EvalGate {
580
+ readonly floors: 'promoted';
581
+ readonly noise: number;
582
+ }
583
+ interface ParityOptions {
584
+ /** Largest allowed absolute logit difference between CPU and WGSL. */
585
+ readonly tolerance: number;
586
+ }
587
+ interface ShipOptions {
588
+ readonly brotliBytes: number;
589
+ readonly files: readonly string[];
590
+ }
591
+ /**
592
+ * An eval definition. `defineEval(model, ...)` fills the type parameters from the model: `Output` is the result type,
593
+ * `Input` is `EvalInput<typeof model>`, `Raw` is `ModelOutput<typeof model>`.
594
+ */
595
+ interface EvalDefinition<Output = unknown, Input = ModelInput, Raw = unknown> {
596
+ readonly sets: EvalSets;
597
+ readonly data: DatasetDefinition<Output>;
598
+ readonly train: TrainOptions;
599
+ readonly metric: (pred: Output, gold: Output) => number;
600
+ /** Turns the head output (or gold in the same shape) into the typed result. */
601
+ readonly decode?: (raw: Raw, input: Input) => Output;
602
+ readonly baselines: Readonly<Record<string, (input: Input) => Output>>;
603
+ readonly gate: EvalGate;
604
+ readonly parity: ParityOptions;
605
+ readonly ship?: ShipOptions;
606
+ /** Table rows for a retrieve head, `{ id, text }` per line. An input, not a split. */
607
+ readonly table?: string;
608
+ }
609
+ /** A loaded model package: the folder, its two files and their default exports. */
610
+ interface Project {
611
+ readonly dir: string;
612
+ readonly modelFile: string;
613
+ readonly evalFile: string;
614
+ readonly model: ModelDefinition;
615
+ readonly evaluation: EvalDefinition;
616
+ /**
617
+ * A retrieve head's table rows from `evaluation.table`, the rows that parse; `undefined` for other heads or when the
618
+ * file is missing. The data step reports what is wrong with the file.
619
+ */
620
+ readonly table?: readonly TableRow[];
621
+ }
622
+ /** The weights a dev scorer judges: quantized when the definition has `quant`, so float scores are never reported. */
623
+ interface ScoredModel {
624
+ readonly plan: ModelPlan;
625
+ readonly weights: Float32Array;
626
+ }
627
+ /**
628
+ * Scores weights on dev; higher is better. `train` calls it at every epoch end and picks checkpoints by it. The default
629
+ * is minus the mean dev loss of the quantized weights.
630
+ */
631
+ type DevScorer = (model: ScoredModel) => number | Promise<number>;
632
+ /** Weights at one point of a run, with their dev score. Quantized when the definition has `quant`. */
633
+ interface TrainCheckpoint {
634
+ readonly weights: Float32Array;
635
+ readonly dev: number;
636
+ /** Optimizer steps taken when the checkpoint was scored. */
637
+ readonly step: number;
638
+ /** Epochs completed when the checkpoint was scored. */
639
+ readonly epoch: number;
640
+ }
641
+ /** One seed's run. `best` is never worse than `last` on dev. */
642
+ interface SeedRun {
643
+ readonly seed: number;
644
+ readonly best: TrainCheckpoint;
645
+ readonly last: TrainCheckpoint;
646
+ readonly steps: number;
647
+ readonly seconds: number;
648
+ readonly stoppedBy: 'epochs' | 'budget';
649
+ /** The first step whose summed batch loss was not finite, when the run diverged. */
650
+ readonly divergedAt?: number;
651
+ }
652
+ interface TrainResult {
653
+ readonly plan: ModelPlan;
654
+ /** The chosen checkpoint: the best one of the seed with the best dev score, quantized when the definition has `quant`. */
655
+ readonly weights: Float32Array;
656
+ readonly seed: number;
657
+ /** `last` when the chosen checkpoint is the run's final weights, else `best`. */
658
+ readonly checkpoint: 'best' | 'last';
659
+ /** Steps of the chosen seed's run. */
660
+ readonly steps: number;
661
+ /** Wall-clock seconds for all seeds. */
662
+ readonly seconds: number;
663
+ /** `budget` when any seed stopped on the wall-clock budget. */
664
+ readonly stoppedBy: 'epochs' | 'budget';
665
+ /** Best dev score per seed, on quantized weights, keyed by the seed. The harness reports their spread. */
666
+ readonly devBySeed: Readonly<Record<string, number>>;
667
+ /** Every seed's run in `options.seeds` order, with its best and last checkpoints. Nothing is written to disk. */
668
+ readonly runs: readonly SeedRun[];
669
+ }
670
+ type Backend = 'webgpu' | 'cpu';
671
+ type BackendRequest = 'auto' | Backend;
672
+ /** A diagnostic: a code with why and fix, and a message that names files and counts, never examples. */
673
+ interface Diagnostic {
674
+ readonly code: DiagnosticCode;
675
+ readonly message: string;
676
+ readonly why: string;
677
+ readonly fix: string;
678
+ readonly file?: string;
679
+ readonly line?: number;
680
+ }
681
+ /** A run-time failure: a load error or a run error, always with a run code (`WEIGHTS_*` or `RUN_*`). */
682
+ interface RunError extends Diagnostic {
683
+ readonly code: RunCode;
684
+ }
685
+ /** Run-time results never throw: `[error, undefined]` or `[undefined, data]`. */
686
+ type RunResult<Data> = readonly [error: RunError, data: undefined] | readonly [error: undefined, data: Data];
687
+ /** What `inspect()` reports about the last run. */
688
+ interface Inspection {
689
+ readonly backend: Backend;
690
+ readonly reason: string;
691
+ readonly bytes: number;
692
+ readonly macs: number;
693
+ readonly inputMax?: number;
694
+ /** The loaded definition's head kind. Absent when loading failed. */
695
+ readonly head?: Head['kind'];
696
+ }
697
+ /** Which backend would run, before anything loads. */
698
+ interface Availability {
699
+ readonly backend: Backend;
700
+ readonly reason: string;
701
+ }
702
+ /** One row a retrieve head scores against. */
703
+ interface TableRow<Id extends string = string> {
704
+ readonly id: Id;
705
+ readonly text: string;
706
+ }
707
+ /**
708
+ * A WebGPU entry point: `navigator.gpu`, or `create([])` from the `webgpu` package in Node. Typed by the one method
709
+ * the runtime calls, so these declarations need no WebGPU or DOM types.
710
+ */
711
+ interface GpuEntryPoint {
712
+ requestAdapter(): Promise<object | null>;
713
+ }
714
+ interface LoadOptions<D extends ModelDefinition = ModelDefinition, Id extends string = string> {
715
+ readonly backend: BackendRequest;
716
+ /**
717
+ * The definition the weights were trained from. It types the result (the head labels), and the loader checks
718
+ * that its hash matches the file (`WEIGHTS_DEFINITION_MISMATCH`). Without it the result is untyped.
719
+ */
720
+ readonly definition?: D;
721
+ /** A WebGPU entry point for hosts without `navigator.gpu`, such as Node with the `webgpu` package. */
722
+ readonly gpu?: GpuEntryPoint;
723
+ /**
724
+ * Rows a retrieve head scores the input against, encoded once at load. Required for a retrieve head
725
+ * (`RUN_TABLE_MISSING`), ignored by other heads. Its ids type the ranking `run` returns.
726
+ */
727
+ readonly table?: readonly TableRow<Id>[];
728
+ }
729
+ interface AvailabilityOptions {
730
+ /** The definition of the model `auto` would run: its multiply-adds per token and `input.max` decide the rules. */
731
+ readonly definition: ModelDefinition;
732
+ readonly gpu?: GpuEntryPoint;
733
+ }
734
+ interface Model<D extends ModelDefinition = ModelDefinition, Id extends string = string> {
735
+ /** Runs may overlap: on WebGPU they go one at a time, in call order, and each gets its own result. */
736
+ run(input: ModelInput): Promise<RunResult<ModelOutput<D, Id>>>;
737
+ inspect(): Inspection;
738
+ /**
739
+ * Frees the WebGPU buffers and device once the runs already called have finished. Every later `run` returns
740
+ * `RUN_MODEL_DESTROYED`. Never rejects; calling it again does nothing more.
741
+ */
742
+ destroy(): Promise<void>;
743
+ }
744
+ type CommandName = 'new' | 'loop' | 'promote' | 'parity' | 'inspect' | 'doctor' | 'build';
745
+ /** Created once per CLI call in src/cli/main.ts and passed to every harness step. */
746
+ interface CommandContext {
747
+ readonly command: CommandName;
748
+ /** The model package folder: `--dir`, else the working directory. */
749
+ readonly dir: string;
750
+ readonly positionals: readonly string[];
751
+ readonly flags: Readonly<Record<string, string | boolean>>;
752
+ readonly print: (line: string) => void;
753
+ readonly printError: (line: string) => void;
754
+ /**
755
+ * True when the command runs as the `gpu-engine` process, which exits once it returns: `promote` then keeps the
756
+ * package's output muted until the process exits (SPEC.md section 6, Output mute).
757
+ */
758
+ readonly ownsProcess?: boolean;
759
+ }
760
+ /** A harness command. Resolves to the process exit code. */
761
+ type Command = (ctx: CommandContext) => Promise<number>;
762
+ /** Scores for one named set: the model, each baseline and the oracle, in one row. Aggregates only. */
763
+ interface SetScores {
764
+ readonly examples: number;
765
+ readonly model: number;
766
+ readonly baselines: Readonly<Record<string, number>>;
767
+ readonly oracle: number;
768
+ }
769
+ /** Set name (one file = one named set) to its scores. */
770
+ type ScoreTable = Readonly<Record<string, SetScores>>;
771
+ interface GateLine {
772
+ readonly name: string;
773
+ readonly pass: boolean;
774
+ readonly detail: string;
775
+ readonly code?: DiagnosticCode;
776
+ }
777
+ type SealLevel = 1 | 2 | 3;
778
+ interface PromotedEntry {
779
+ readonly at: string;
780
+ readonly commit: string;
781
+ readonly weights: string;
782
+ readonly definition: string;
783
+ readonly dev: Readonly<Record<string, number>>;
784
+ readonly test: Readonly<Record<string, number>>;
785
+ }
786
+ interface GateFile {
787
+ readonly level: SealLevel;
788
+ readonly promoted: PromotedEntry | null;
789
+ }
790
+ /** One row of `tries.jsonl`. The key list is closed and holds dev scores only. */
791
+ interface TriesRow {
792
+ readonly at: string;
793
+ readonly commit: string;
794
+ readonly dirty: boolean;
795
+ readonly idea: string;
796
+ readonly status: 'kept' | 'dropped' | null;
797
+ readonly definition: string;
798
+ readonly seeds: readonly number[];
799
+ readonly dev: Readonly<Record<string, number>>;
800
+ readonly devScore: number;
801
+ readonly devSpread: number;
802
+ readonly brotliBytes: number;
803
+ readonly macsPerToken: number;
804
+ readonly trainSeconds: number;
805
+ readonly gate: 'pass' | 'fail';
806
+ /** Only on a try where a seed diverged: the seed to the step where its loss stopped being finite. */
807
+ readonly diverged?: Readonly<Record<string, number>>;
808
+ }
809
+ /** One row of `reads.jsonl`. `examples` rows are counted reads of the test set. */
810
+ interface ReadsRow {
811
+ readonly at: string;
812
+ readonly kind: 'digest' | 'examples';
813
+ readonly command: CommandName;
814
+ readonly commit: string;
815
+ readonly files: readonly string[];
816
+ readonly examples: number;
817
+ readonly outcome: 'ok' | 'failed';
818
+ }
819
+ interface SetData {
820
+ readonly sha256: string;
821
+ readonly examples: number;
822
+ }
823
+ interface Report {
824
+ readonly name: string;
825
+ readonly date: string;
826
+ readonly commit: string;
827
+ readonly definition: string;
828
+ readonly weights: {
829
+ readonly sha256: string;
830
+ readonly bytes: number;
831
+ readonly brotliBytes: number;
832
+ };
833
+ readonly params: number;
834
+ readonly macsPerToken: number;
835
+ readonly train: {
836
+ readonly seeds: readonly number[];
837
+ readonly chosenSeed: number;
838
+ readonly checkpoint: 'best' | 'last';
839
+ readonly steps: number;
840
+ readonly seconds: number;
841
+ readonly devBySeed: Readonly<Record<string, number>>;
842
+ };
843
+ /**
844
+ * Per split kind, per named set: file hash and example count. A retrieve head's `table` file adds its hash and row
845
+ * count; a report written before the table was recorded has none.
846
+ */
847
+ readonly data: Readonly<Record<SetKind, Readonly<Record<string, SetData>>>> & {
848
+ readonly table?: Readonly<Record<string, SetData>>;
849
+ };
850
+ readonly dev: ScoreTable;
851
+ readonly test: ScoreTable;
852
+ readonly gate: readonly GateLine[];
853
+ readonly testReads: number;
854
+ readonly level: SealLevel;
855
+ }
856
+ interface ParityFile {
857
+ readonly date: string;
858
+ readonly weights: string;
859
+ readonly adapter: string;
860
+ readonly tolerance: number;
861
+ readonly fixtures: number;
862
+ readonly trainerCpu: 'identical';
863
+ readonly maxDifference: number;
864
+ readonly decodeDiffers: number;
865
+ /** `not run` unless a real GPU run is recorded. Parity runs in Node, so no browser run is ever recorded here. */
866
+ readonly realGpu: string;
867
+ }
868
+ export { PooledClassHead as $, GateFile as A, TriesRow as At, Layer as B, EvalSets as C, TensorShape as Ct, FeatureRows as D, TrainCheckpoint as Dt, FeatureRow as E, TokensInput as Et, Head as F, engineError as Ft, ModelInput as G, LoadOptions as H, HeadKind as I, formatDiagnostic as It, OpKind as J, ModelOutput as K, HeadOutput as L, GpuEngineError as Lt, Gold as M, DiagnosticCode as Mt, GpuEntryPoint as N, diagnostic as Nt, FlagNames as O, TrainOptions as Ot, HashRow as P, diagnostics as Pt, ParityOptions as Q, Inspection as R, RunCode as Rt, EvalInput as S, TagHead as St, FeatureBlock as T, Token as Tt, Model as U, LayerKind as V, ModelDefinition as W, OpSpec as X, OpPlan as Y, ParityFile as Z, Diagnostic as _, SetKind as _t, BackendRequest as a, Report as at, EvalDefinition as b, ShipOptions as bt, CanonicalDefinition as c, RowLayout as ct, CommandName as d, ScoreTable as dt, PooledValuesHead as et, ConvLayer as f, ScoredModel as ft, DevScorer as g, SetData as gt, DenseLayer as h, SeedRun as ht, Backend as i, ReadsRow as it, GateLine as j, WeightsFile as jt, FlagRow as k, TrainResult as kt, Command as l, RunError as lt, DatasetGenerator as m, SealedSet as mt, Availability as n, PromotedEntry as nt, BiScanLayer as o, RetrieveHead as ot, DatasetDefinition as p, SealLevel as pt, ModelPlan as q, AvailabilityOptions as r, Random as rt, Budgets as s, RetrieveMatch as st, Activation as t, Project as tt, CommandContext as u, RunResult as ut, EmbedLayer as v, SetScores as vt, Example as w, TensorSpec as wt, EvalGate as x, TableRow as xt, EncodedTensor as y, ShapeRow as yt, Int6Quantization as z };