gpu-engine 0.0.0-stage → 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.
- package/LICENSE +21 -0
- package/README.md +96 -2
- package/SPEC.md +988 -0
- package/THIRD_PARTY_NOTICES.md +29 -0
- package/dist/cli.d.mts +1 -0
- package/dist/cli.mjs +4 -0
- package/dist/harness.d.mts +132 -0
- package/dist/harness.mjs +1 -0
- package/dist/index.d.mts +98 -0
- package/dist/index.mjs +1 -0
- package/dist/load-o_thEAKC.mjs +258 -0
- package/dist/scaffold-CY5xhy-V.mjs +106 -0
- package/dist/types-BwigqFwr.d.mts +868 -0
- package/docs/apps.md +108 -0
- package/docs/cli.md +126 -0
- package/docs/data.md +101 -0
- package/docs/diagnostics.md +509 -0
- package/docs/harness.md +191 -0
- package/docs/layers.md +249 -0
- package/docs/measurements/auto-threshold.json +335 -0
- package/docs/measurements/auto-threshold.md +56 -0
- package/docs/measurements/real-gpu-2026-11-22.json +4718 -0
- package/docs/measurements/real-gpu-2026-11-22.md +75 -0
- package/docs/runtime.md +112 -0
- package/docs/sealed-test-set.md +107 -0
- package/docs/weights-format.md +138 -0
- package/llms.txt +24 -0
- package/package.json +73 -3
- package/skills/gpu-engine/SKILL.md +117 -0
- package/templates/common/AGENTS.md +27 -0
- package/templates/common/github/workflows/ci.yml +35 -0
- package/templates/common/gitignore +3 -0
- package/templates/common/package.template.json +27 -0
- package/templates/common/tsconfig.template.json +17 -0
- package/templates/pooled/NEW_MODEL_NAME.eval.ts +93 -0
- package/templates/pooled/NEW_MODEL_NAME.model.ts +11 -0
- package/templates/pooled/SPEC.md +31 -0
- package/templates/pooled/src/decode.ts +10 -0
- package/templates/pooled/src/index.ts +44 -0
- package/templates/pooled/src/weights.ts +4 -0
- package/templates/retrieve/NEW_MODEL_NAME.eval.ts +149 -0
- package/templates/retrieve/NEW_MODEL_NAME.model.ts +12 -0
- package/templates/retrieve/SPEC.md +33 -0
- package/templates/retrieve/data/table.jsonl +16 -0
- package/templates/retrieve/src/decode.ts +9 -0
- package/templates/retrieve/src/index.ts +45 -0
- package/templates/retrieve/src/table.ts +21 -0
- package/templates/retrieve/src/weights.ts +4 -0
- package/templates/tag/NEW_MODEL_NAME.eval.ts +114 -0
- package/templates/tag/NEW_MODEL_NAME.model.ts +11 -0
- package/templates/tag/SPEC.md +31 -0
- package/templates/tag/src/decode.ts +25 -0
- package/templates/tag/src/index.ts +44 -0
- package/templates/tag/src/weights.ts +4 -0
package/SPEC.md
ADDED
|
@@ -0,0 +1,988 @@
|
|
|
1
|
+
# gpu-engine spec
|
|
2
|
+
|
|
3
|
+
This file is the source of truth. A behaviour change lands here first, then in a test, then in code. MUST, MUST NOT, SHOULD and MAY have their RFC 2119 meanings and mark real invariants only.
|
|
4
|
+
|
|
5
|
+
## 1. Goal
|
|
6
|
+
|
|
7
|
+
gpu-engine is a framework to build, tune, evaluate and ship tiny models that run locally.
|
|
8
|
+
|
|
9
|
+
- Tiny means a few kilobytes to about 1 MB of weights, trained from scratch in seconds to minutes.
|
|
10
|
+
- Browser first. The main runtime is WebGPU with hand-written WGSL.
|
|
11
|
+
- A CPU fallback runs the same weights in Node, on servers and in browsers without WebGPU.
|
|
12
|
+
- The shipped model has zero runtime dependencies.
|
|
13
|
+
|
|
14
|
+
One package holds two parts:
|
|
15
|
+
|
|
16
|
+
| Part | What it gives you |
|
|
17
|
+
| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
|
|
18
|
+
| Model kit | A featurizer, a closed layer catalog, a trainer with quantization, a weights format, a CPU and a WGSL runtime |
|
|
19
|
+
| Workflow harness | Commands and rules that take a model from definition to release: data, training, evaluation, a sealed test set, parity and ship checks |
|
|
20
|
+
|
|
21
|
+
## 2. Who this is for
|
|
22
|
+
|
|
23
|
+
The primary reader and user is a coding agent, with a developer directing it.
|
|
24
|
+
|
|
25
|
+
The API is deliberately low-level. The developer or agent chooses the layers, and `net` is always an explicit list. The library does not hide the model behind presets.
|
|
26
|
+
|
|
27
|
+
What the library owes its reader instead:
|
|
28
|
+
|
|
29
|
+
| It owes | What that means |
|
|
30
|
+
| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
31
|
+
| Precise layer docs | Every layer states what it does, its cost in bytes and multiply-adds, when it helps and when it does not |
|
|
32
|
+
| Definition-time errors with a fix | A layout that cannot work throws at define time and says how to fix it: a head that does not match the labels, a budget the layers already exceed |
|
|
33
|
+
| A shipped skill | Starting layouts and tuning advice (section 12) |
|
|
34
|
+
| A fast loop with an honest score | The layout is found by trying. `loop` scores on dev in under a minute, and the reported score comes from a sealed test set (section 7) |
|
|
35
|
+
|
|
36
|
+
## 3. Non-goals
|
|
37
|
+
|
|
38
|
+
- Not a general deep-learning framework.
|
|
39
|
+
- No autodiff. Every layer has a hand-written backward pass.
|
|
40
|
+
- No large or pretrained models.
|
|
41
|
+
- No hosted service. Nothing runs on a server you do not own.
|
|
42
|
+
- No graph-to-shader compiler. Each layer has its own WGSL template.
|
|
43
|
+
|
|
44
|
+
## 4. The pipeline
|
|
45
|
+
|
|
46
|
+
```
|
|
47
|
+
featurize -> net (closed layer catalog) -> head -> decode
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
| Step | Who writes it | Output |
|
|
51
|
+
| --------- | ---------------------------------------------- | ------------------------- |
|
|
52
|
+
| featurize | gpu-engine, configured by the model definition | Feature rows per token |
|
|
53
|
+
| net | gpu-engine, from the layer catalog | A hidden vector per token |
|
|
54
|
+
| head | gpu-engine, one of the head kinds | Tags or scores |
|
|
55
|
+
| decode | You, in plain code | Your typed result |
|
|
56
|
+
|
|
57
|
+
The decode step turns tags or scores into a typed result. It is always the developer's own plain code. gpu-engine never owns it.
|
|
58
|
+
|
|
59
|
+
Head kinds:
|
|
60
|
+
|
|
61
|
+
| Kind | Output | Version | Status |
|
|
62
|
+
| ---------- | ----------------------------------------------------------- | ------- | ----------- |
|
|
63
|
+
| `tag` | A label per token | v1 | Implemented |
|
|
64
|
+
| `pooled` | One output for the whole input: a class or a few numbers | v1 | Implemented |
|
|
65
|
+
| `retrieve` | A score for the input against each row of a candidate table | v1 | Implemented |
|
|
66
|
+
|
|
67
|
+
Implemented means forward, backward, gradient test, CPU and WGSL, trained through the generic trainer and run through `loadModel` (section 5, Layer catalog).
|
|
68
|
+
|
|
69
|
+
## 5. Model kit
|
|
70
|
+
|
|
71
|
+
### Featurizer
|
|
72
|
+
|
|
73
|
+
One featurizer is shared by the trainer and the runtime. The same code produces the same rows in both places.
|
|
74
|
+
|
|
75
|
+
- A tokenizer splits text into tokens.
|
|
76
|
+
- Each token gets feature rows: FNV-style hashed rows of its spelling, a word shape row, and flags the caller supplies.
|
|
77
|
+
- There is no learned vocabulary. Hashing maps any token to a fixed number of rows.
|
|
78
|
+
|
|
79
|
+
The trainer and the runtime MUST produce identical feature rows for the same input. The WebGPU runtime receives the rows the CPU featurizer computed; there is no second featurizer.
|
|
80
|
+
|
|
81
|
+
#### Tokenizer
|
|
82
|
+
|
|
83
|
+
`tokenize(text)` returns `{ text, start, end }[]`. Offsets are UTF-16 code units, half-open, so `token.text === text.slice(start, end)`. Case is kept and the text is not normalised, so offsets always point into the caller's string. The tokenizer walks code points and never splits a surrogate pair. Each code point has one class:
|
|
84
|
+
|
|
85
|
+
| Class | Unicode test | Effect |
|
|
86
|
+
| ------ | ----------------- | ----------------------------------------------------------------------- |
|
|
87
|
+
| letter | `\p{L}` | Joins the letter run before it, else starts one |
|
|
88
|
+
| digit | `\p{Nd}` | Joins the digit run before it, else starts one |
|
|
89
|
+
| mark | `\p{M}` | Joins the token before it, whatever its class; else starts a letter run |
|
|
90
|
+
| space | `\p{White_Space}` | Ends the current token and is never part of one |
|
|
91
|
+
| other | anything else | A token of its own (marks after it still join it) |
|
|
92
|
+
|
|
93
|
+
Consequences: `3km` is `3`, `km`; `don't` is `don`, `'`, `t`; `e-mail` is `e`, `-`, `mail`; a decomposed `é` stays one letter token; `❤️` (a symbol and a variation selector, which is a mark) is one token; a joiner (U+200D, class other) is its own token, so an emoji sequence joined by it is several tokens; `²` and `½` are `\p{N}` but not `\p{Nd}`, so each is a token of class other.
|
|
94
|
+
|
|
95
|
+
#### Feature rows
|
|
96
|
+
|
|
97
|
+
`features.tokens({ max, rows })` lists the feature rows of a model. Each row owns a block of consecutive embedding rows and a block of consecutive slots per token, in list order: a block starts where the block before it ends, the first at 0. `rowLayout(input)` returns `{ slots, rows, blocks }`: the slots per token, the embedding rows in total, and per row its first embedding row, embedding row count, first slot and slot count. A slot holds an absolute embedding row index (the block's first row plus a row inside the block) or `-1` when empty.
|
|
98
|
+
|
|
99
|
+
| Row | Slots | Embedding rows | Slot values |
|
|
100
|
+
| ------------------------------- | ----- | -------------- | ----------------------------------------------------------------------- |
|
|
101
|
+
| `features.shape()` | 2 | 13 | Slot 0: the character class, rows 0 to 7. Slot 1: 8 + the length bucket |
|
|
102
|
+
| `features.hash({ buckets, k })` | `k` | `buckets` | Slot `j`: the `j`-th distinct hashed row of the token |
|
|
103
|
+
| `features.flag({ name })` | 1 | 1 | Row 0 when the caller's flag is on for the token, else `-1` |
|
|
104
|
+
|
|
105
|
+
Character class of a token, slot 0 of a shape row:
|
|
106
|
+
|
|
107
|
+
| Row | Class | Rule |
|
|
108
|
+
| --- | ----------- | ------------------------------------------------------------------------------------ |
|
|
109
|
+
| 0 | lower | A letter token whose cased letters are all lowercase |
|
|
110
|
+
| 1 | upper | A letter token whose cased letters are all uppercase, including one uppercase letter |
|
|
111
|
+
| 2 | title | A letter token whose first cased letter is uppercase and every other one lowercase |
|
|
112
|
+
| 3 | mixed | Any other letter token with cased letters |
|
|
113
|
+
| 4 | caseless | A letter token without cased letters, such as CJK or Arabic script |
|
|
114
|
+
| 5 | digits | A digit token |
|
|
115
|
+
| 6 | punctuation | An other token whose first code point is `\p{P}` |
|
|
116
|
+
| 7 | other | Any other token: symbols, emoji, controls |
|
|
117
|
+
|
|
118
|
+
Uppercase letters are `\p{Lu}` and `\p{Lt}`, lowercase letters are `\p{Ll}`; marks and uncased letters (`\p{Lm}`, `\p{Lo}`) do not count. Rules are applied from row 0 down; a token with one uppercase letter is upper, not title.
|
|
119
|
+
|
|
120
|
+
Length bucket, slot 1 of a shape row, by code points of the token text: 1 is bucket 0, 2 is 1, 3 to 4 is 2, 5 to 7 is 3, 8 or more is 4.
|
|
121
|
+
|
|
122
|
+
Hashed rows. The key is the token text lowercased (`toLowerCase`, locale-independent), then normalised to NFC, then encoded as UTF-8. Slot `j` (0 to `k - 1`) hashes the key with 32-bit FNV-1a, `h = basis_j`, then for each byte `h = (h XOR byte) * 16777619 mod 2^32`, with `basis_j = (2166136261 + j * 2654435769) mod 2^32` (`basis_0` is the standard FNV offset basis). Its row inside the block is `h mod buckets`; while an earlier slot of the same token holds that row, the row moves to `(row + 1) mod buckets`. The `k` rows of one token are therefore distinct. The same two-lane hash, lanes `basis_0` and `basis_1` over raw bytes, written as 16 lowercase hex characters, lane 0 first, is `hashBytes`, the definition hash of the weights file.
|
|
123
|
+
|
|
124
|
+
Flags. A model input is `string | { text, flags? }`. `flags` maps a declared flag name to one boolean per token of `tokenize(text)`, counted before truncation. Only the object's own keys count, so a flag named `constructor` or `toString` is never read from the prototype. A flag the definition declares but the input leaves out is off for every token; a string input has every flag off. `featurize` throws `RUN_INPUT_INVALID` (the runtime returns it as the run's error) when the input is not a string or a `{ text }` object, when `flags` names a flag the definition does not declare, or when a flag list is not an array of booleans with one entry per token. The message names the flag and the counts, never the text.
|
|
125
|
+
|
|
126
|
+
Truncation. `featurize(input, value)` returns `{ count, slots, rows }` with `count = min(token count, max)` and `rows` an `Int32Array` of `count * slots`, where `rows[t * slots + s]` is slot `s` of token `t`. Tokens after the first `max` get no rows and no output. Empty text gives `count = 0`.
|
|
127
|
+
|
|
128
|
+
Definition checks. `rowLayout` throws `DEFINE_FEATURE_ROW` when the input is not an object of kind `tokens`, `max` is not a positive integer, `rows` is empty, a row has an unknown kind, `buckets` is not a positive integer, `k` is not an integer from 1 to `buckets`, a flag name is empty, there is more than one shape row, or two flag rows share a name. The builders return plain objects; the check runs wherever a layout is built, which includes `defineModel`. Their types keep what the arguments say: `features.flag(name)` keeps `name` as a literal type and `features.tokens` keeps its list of rows, so `defineEval` can tell whether a model declares flag rows (section 11).
|
|
129
|
+
|
|
130
|
+
#### Seeded random numbers
|
|
131
|
+
|
|
132
|
+
`createRandom(seed)` is mulberry32: the state starts at `seed` as an unsigned 32-bit integer, and each call adds `0x6d2b79f5` to it and mixes it into a number in [0, 1) with a resolution of 2^-32. The same seed gives the same sequence on every platform. Dataset generators and weight initialisation take it as `random`.
|
|
133
|
+
|
|
134
|
+
### Layer catalog
|
|
135
|
+
|
|
136
|
+
The catalog is closed. v1 has four layers:
|
|
137
|
+
|
|
138
|
+
| Layer | What it does |
|
|
139
|
+
| -------- | ----------------------------------------------------------------------------------------------------------- |
|
|
140
|
+
| `embed` | Sums the embedding rows of a token's features into one vector |
|
|
141
|
+
| `conv` | Mixes each token with its neighbours over a fixed number of taps |
|
|
142
|
+
| `biScan` | A bidirectional gated affine scan: `state[t] = gate[t] * state[t-1] + candidate[t]`, run in both directions |
|
|
143
|
+
| `dense` | A fully connected layer with an activation |
|
|
144
|
+
|
|
145
|
+
`biScan({ size })` in full, per direction and channel: `gate[t] = sigmoid(Wg x[t] + bg)`, `candidate[t] = (1 - gate[t]) * tanh(Wc x[t] + bc)`, `state[t] = gate[t] * state[t-1] + candidate[t]` with `state` starting at 0 before the first token. The forward direction runs `t = 0` to `n - 1`, the backward direction `t = n - 1` to `0`. The candidate term carries the factor `(1 - gate)`, so each state is a convex mix of the previous state and `tanh(...)` and stays in (-1, 1) for any length: a gate near 1 keeps the memory, a gate near 0 replaces it. Gate biases start spread evenly from 0 to 3 across the channels (every channel 0 when `size` is 1), so some channels keep a token for about one step and others for about twenty; candidate biases start at 0.
|
|
146
|
+
|
|
147
|
+
The `tag` head is a linear step to one logit per label for every token. Decode is the argmax per token (the first label on a tie); softmax stays on the CPU and is used only by the training loss, softmax cross-entropy per token averaged over the `n` tokens. Its gold is one head label per token of the tokenized text, counted before truncation: a label count other than the token count is `DATA_ROW_INVALID`, a label outside the head is `DATA_LABEL_UNKNOWN`, and labels for tokens cut at `input.max` are checked the same way, then dropped with their tokens.
|
|
148
|
+
|
|
149
|
+
The `pooled` head pools, then takes one linear step for the whole input. Over the `n` tokens of its input `x [n, in]`, `pooled[i]` is the mean of `x[t, i]` over the tokens and `pooled[in + i]` its max (both 0 when `n` is 0, so an empty input gives the bias), then `logits[o] = bias[o] + sum over j of weight[o, j] * pooled[j]`. The forward pass returns `out` values, not `n * out`. In the backward pass the mean half spreads its gradient evenly, `1 / n` to every token, and the max half sends its whole gradient to the token that holds the max; on a tie that is the first such token and no other. Its two forms differ only in loss, gold and decode:
|
|
150
|
+
|
|
151
|
+
- Class (`labels`): softmax cross-entropy over the labels. Gold is one head label, else `DATA_ROW_INVALID`; a label outside the head is `DATA_LABEL_UNKNOWN`. Decode is the argmax label (the first label on a tie).
|
|
152
|
+
- Values (`outputs`): mean squared error averaged over the outputs. Gold is an array of `outputs` finite numbers, else `DATA_ROW_INVALID`. Decode returns the logits as numbers.
|
|
153
|
+
|
|
154
|
+
On WGSL the pool is one pass, one invocation per channel, writing `2 * in` floats to `temp`, and the linear step a second pass, one invocation per output. A model whose `temp` holds fewer than `2 * in` floats has `maxTokens` 1, where mean and max both equal the one token, so it runs a single linear pass that reads the input directly.
|
|
155
|
+
|
|
156
|
+
The `retrieve` head scores an input against the rows of a table through one shared tower. The tower is the `net` and the head's op, which is the `pooled` pool and linear step with `out = size`, so any text becomes a vector of `size` floats. A table is a list of `{ id, text }` rows; each row's text goes through the same tower, giving the row vectors `table [rows, size]`. The score step is an op of its own, with no tensors: `score[r] = sum over i of query[i] * table[r, i]`, accumulated in doubles and stored as float32. Its backward pass sends `dQuery[i] = sum over r of dScore[r] * table[r, i]` to the input's tower and `dTable[r, i] = dScore[r] * query[i]` to each row's tower, so the gradient flows through both sides of the one tower.
|
|
157
|
+
|
|
158
|
+
- Gold is the array of the ids of the rows that answer the input: at least one, no id twice. Anything else is `DATA_ROW_INVALID`; an id that names no table row is `DATA_LABEL_UNKNOWN`. Train and dev ids are checked against the table in the data step, test ids when `promote` reads the test set.
|
|
159
|
+
- Training. The candidates of an example are its gold rows, then `train.negatives` other rows drawn without replacement from the seed's stream (every other row when the table has no more). The loss is softmax cross-entropy over the candidates' scores with every gold row counted as right: `loss = log sum over candidates of exp(score) - log sum over gold of exp(score)`. The input and each candidate run the forward pass with caches, and the backward walk runs once for the input and once per candidate. The default dev score is minus the mean of the same loss with the whole table as candidates.
|
|
160
|
+
- Decode ranks the rows: one `{ id, score }` per table row, the highest score first, table order on a tie.
|
|
161
|
+
- On WGSL the tower runs the `pooled` passes, then the score step is one pass, one invocation per table row, reading the input's vector from the tower's output and the row vectors from the weights buffer, where they follow the model's parameters.
|
|
162
|
+
|
|
163
|
+
Every layer MUST ship, in one change:
|
|
164
|
+
|
|
165
|
+
1. a forward pass,
|
|
166
|
+
2. a hand-written backward pass,
|
|
167
|
+
3. a finite-difference gradient test,
|
|
168
|
+
4. a CPU implementation,
|
|
169
|
+
5. a WGSL template.
|
|
170
|
+
|
|
171
|
+
The contract these five parts follow (data layout, what the backward pass may write, the fixed WGSL bindings) is written at the top of `src/kit/ops.ts`. Each layer's cost and use are in `docs/layers.md`.
|
|
172
|
+
|
|
173
|
+
`embed({ size })` computes `out[t] = bias + sum of table[r]` over the token's slots `r`: an empty slot (`-1`) adds nothing, and a row that appears in several slots adds once per slot. The table starts at zero, so a row that no training token reaches, such as an unseen hash bucket, adds nothing at run time. The bias starts uniform in [-0.1, 0.1): with the bias at zero too, every activation after `embed` starts at zero, a `relu` there passes no gradient, and the model cannot learn. `conv({ taps })` is depthwise, one kernel per channel: `out[t, i] = tanh(bias[i] + sum over j of kernel[j, i] * x[t + j - (taps - 1) / 2, i])`, where tokens before the first and after the last read as zero. Its centre tap starts at 1.
|
|
174
|
+
|
|
175
|
+
### Plan
|
|
176
|
+
|
|
177
|
+
`plan(definition)` (in `gpu-engine/harness`) turns a definition into the ordered ops (the `net` layers, then the head), each with its input width, output width, tensors and multiply-adds per token, plus the totals: `size` (parameters), `macsPerToken`, `slots`, `rows`, `maxTokens`, `outWidth` and the definition `hash`. All parameters live in one `Float32Array` of `size` values; each tensor is a `{ name, shape, offset, length }` slice of it, placed contiguously in the order of the table below, op after op. The plan owns this table, not the ops, so `defineModel` checks budgets before any layer runs.
|
|
178
|
+
|
|
179
|
+
`forward(plan, weights, rows, n)` walks the ops over `n` tokens of feature rows and returns the logits: `n * outWidth` values for a `tag` head, `outWidth` for a `pooled` or `retrieve` head. It is the only forward pass: the trainer and the CPU runtime both call it.
|
|
180
|
+
|
|
181
|
+
#### Tensors
|
|
182
|
+
|
|
183
|
+
A tensor's name in the plan and in the weights file is `<op index>.<kind>.<tensor>`, for example `0.embed.table` or `2.biScan.forward.gateWeight`. A matrix `[out, in]` is row-major: element `(o, i)` is at `offset + o * in + i`, and a linear step computes `y[o] = bias[o] + sum over i of weight[o, i] * x[i]`. `in` is the op's input width: `slots` for `embed`, the previous op's output width otherwise.
|
|
184
|
+
|
|
185
|
+
| Op | Tensors, in order | Output width | Multiply-adds per token |
|
|
186
|
+
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------- | -------------------------- |
|
|
187
|
+
| `embed({ size })` | `table [rows, size]`, `bias [size]` | `size` | `slots * size` |
|
|
188
|
+
| `conv({ taps })` | `kernel [taps, in]` (tap `j` reads token `t + j - (taps - 1) / 2`), `bias [in]` | `in` | `taps * in` |
|
|
189
|
+
| `biScan({ size })` | `forward.gateWeight [size, in]`, `forward.gateBias [size]`, `forward.candidateWeight [size, in]`, `forward.candidateBias [size]`, then the same four for `backward` | `2 * size`, forward channels first | `4 * size * in + 2 * size` |
|
|
190
|
+
| `dense({ size })` | `weight [size, in]`, `bias [size]` | `size` | `size * in` |
|
|
191
|
+
| `tag` head | `weight [labels, in]`, `bias [labels]` | `labels` | `in * labels` |
|
|
192
|
+
| `pooled` head | `weight [out, 2 * in]`, `bias [out]`, after mean then max pooling over tokens; `out` is the label count or `outputs` | `out` | `2 * in + 2 * in * out` |
|
|
193
|
+
| `retrieve` head | As `pooled`, with `out = size` | `size` | `2 * in + 2 * in * size` |
|
|
194
|
+
|
|
195
|
+
`rows` and `slots` come from the feature rows (Featurizer above). The linear step of a `pooled` or `retrieve` head runs once per input; it is counted in full per token, an upper bound. The `retrieve` score step has no tensors and costs `rows * size` multiply-adds per run for a table of `rows` rows, which `macsPerToken` does not count.
|
|
196
|
+
|
|
197
|
+
#### Definition-time checks
|
|
198
|
+
|
|
199
|
+
`defineModel` plans the definition and throws, each with a fix from `src/errors.ts`:
|
|
200
|
+
|
|
201
|
+
| Code | When |
|
|
202
|
+
| ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
203
|
+
| `DEFINE_NAME_INVALID` | `name` is not a lowercase name of letters, digits and `-` that starts with a letter, at most 64 characters (`^[a-z][a-z0-9-]{0,63}$`, the rule `gpu-engine new` applies), so `weights/<name>.bin` always stays inside `weights/` |
|
|
204
|
+
| `DEFINE_NET_ORDER` | `net` is empty, does not start with `embed`, or has a second `embed` |
|
|
205
|
+
| `DEFINE_LAYER_SHAPE` | A size is not a positive integer, `taps` is not an odd positive integer, an activation is not `relu`, `tanh` or `none`, or a layer kind is outside the catalog |
|
|
206
|
+
| `DEFINE_HEAD_LABELS` | Fewer than two labels, an empty or repeated label, both or neither of `labels` and `outputs` on a `pooled` head, `outputs` on a `tag` head, or an unknown head kind |
|
|
207
|
+
| `DEFINE_FEATURE_ROW` | The feature rows cannot be laid out (Featurizer above) |
|
|
208
|
+
| `DEFINE_BUDGET_EXCEEDED` | `macsPerToken` is above `budgets.macsPerToken`, or the packed int6 bytes of every tensor except the embedding table are above twice `budgets.brotliBytes` |
|
|
209
|
+
| `DEFINE_QUANT_INVALID` | `quant` is present and is not `{ kind: 'int6', qatFrom }` with `qatFrom` a finite number from 0 to 1 |
|
|
210
|
+
| `DEFINE_BUDGET_INVALID` | `budgets.brotliBytes` or `budgets.macsPerToken` is not a positive integer, so no comparison against it means anything |
|
|
211
|
+
|
|
212
|
+
The plan runs these checks, so the weights reader applies them to the definition a file carries too: a file whose definition breaks one, its name included, is `WEIGHTS_FORMAT_INVALID`.
|
|
213
|
+
|
|
214
|
+
The multiply-add check is exact. The byte check is a floor, so it never rejects a model that could fit. Measured with Brotli at quality 11 on packed int6 tensors (`test/kit/quant.test.ts`): Gaussian weights shrink to 0.97 of their packed size, Laplace weights to 0.87 and Student t weights (3 degrees of freedom) to 0.57, so no trained tensor reaches half. The embedding table is left out because hashed rows that no token reaches stay zero: a table with two thirds of its rows zero shrinks to 0.39. The real Brotli size is checked after training (`BUDGET_BYTES_EXCEEDED`).
|
|
215
|
+
|
|
216
|
+
### Quantization
|
|
217
|
+
|
|
218
|
+
- int6 quantization-aware training (QAT), switched on for the last part of the run (`qatFrom`).
|
|
219
|
+
- One symmetric scale per tensor: `scale = float32(max |w| / 31)` over the tensor, `level = clamp(round(w / scale), -31, 31)` (`round` is JavaScript `Math.round`, halves toward positive infinity), and the weight becomes `float32(level * scale)`. A tensor of zeros has scale 0 and every level 0.
|
|
220
|
+
- `quantizeInto(plan, source, target)` applies this tensor by tensor. QAT (straight-through) and the weights writer both use it, so the quantized weights the trainer scores are bitwise the weights the runtime decodes.
|
|
221
|
+
- The quantized model is the one that gets scored. Float scores are never reported as the model's score.
|
|
222
|
+
|
|
223
|
+
### Trainer
|
|
224
|
+
|
|
225
|
+
`train(definition, { train, dev, table? }, options, score?)` (in `gpu-engine/harness`) trains in TypeScript with the hand-written backward passes. It reads and writes no files: checkpoints come back as weights, and the harness writes them. A `retrieve` head needs `table`, its `{ id, text }` rows (`RUN_TABLE_MISSING` without), and `options.negatives`, a positive integer; other heads ignore both.
|
|
226
|
+
|
|
227
|
+
- Each example is featurized once. A step runs the one forward pass (`forward`, the CPU runtime's code) with caches, the head's `loss`, then each op's `backward` from the head back to `embed`. The trainer knows no head: a head supplies `encodeGold` and `loss`. The batch gradient is the mean of the examples' gradients. A `retrieve` head is the one exception: its loss needs a tower pass per candidate row, so the trainer runs the walk above for the input and for each candidate, joined by the score step (Layer catalog above). Table rows are featurized once.
|
|
228
|
+
- Optimizer: Adam (beta1 0.9, beta2 0.999, epsilon 1e-8, bias-corrected). Learning rate at step `k` of `total = epochs * ceil(train / batch)` planned steps, with `W = round(warmup * total)`: `learningRate * k / W` for `k <= W`, then `learningRate * (1 + cos(pi * (k - W) / (total - W))) / 2`, which reaches 0 at the last step. A run of one planned step has nothing to decay: its step uses `learningRate`. Since `warmup` is below 1, `W` is at most `total`.
|
|
229
|
+
- QAT, straight-through: from step `round(qatFrom * total)` on (counting from 0), forward and backward run on `quantizeInto` of the float weights and the step updates the float weights.
|
|
230
|
+
- Seeds run one after another. Seed `s` initialises every op from `createRandom(s)` in plan order and shuffles the train set from the same stream at each epoch start (a `retrieve` head also draws its negatives from it), so one seed gives the same weights, bit for bit, whenever the budget does not stop it.
|
|
231
|
+
- Budget: each seed gets an equal share of the time `budgetSeconds` has left when it starts. A seed that runs past its share stops after the current step, with `stoppedBy: 'budget'`.
|
|
232
|
+
- Dev scoring: at each epoch end, and once more for the final weights when the budget stops a run between epoch ends, the weights are quantized (when the definition has `quant`) and passed to `score`; higher is better. The default `score` is minus the mean dev loss. A seed's `best` checkpoint has the highest score it reached (the earliest on a tie) and its `last` checkpoint is its final weights, or after a divergence its last checkpoint with finite weights, so `best` is never worse than `last`. The result is the best checkpoint of the seed with the highest best score (the first seed on a tie), with every seed's score in `devBySeed` and every run's `best` and `last` in `runs`.
|
|
233
|
+
- Float scores are never reported: `score` only ever sees quantized weights when the definition has `quant`, and the returned weights are those quantized weights.
|
|
234
|
+
- Divergence: a seed whose summed batch loss is not finite at some step records that step as `divergedAt` in its run (the first such step, counting from 0), so the result reports it; a step after which a weight is not finite counts too, and the seed stops there, since such weights never recover. A checkpoint whose weights are not all finite is not scored or kept, so every checkpoint in a run, `last` included, can be written to a weights file. The default scorer gives a dev loss that is not finite a score of minus infinity, so such a checkpoint is never a seed's `best` while the seed has another. When a seed ends with no kept checkpoint above minus infinity, `train` throws `TRAIN_DIVERGED` naming the seed and the step.
|
|
235
|
+
- The options are checked as `defineEval` checks `train` (section 11), with the same code, `DEFINE_TRAIN_INVALID`; an empty train or dev set is `DATA_SET_TOO_SMALL`.
|
|
236
|
+
|
|
237
|
+
### Weights format
|
|
238
|
+
|
|
239
|
+
A documented binary format with a header, so an external trainer (for example PyTorch) can export into it. The file carries the canonical definition, so `loadModel(weights)` needs nothing else, and an exporter writes the definition JSON and the tensors of the table above. With `quant` every tensor is int6; without it every tensor is float32.
|
|
240
|
+
|
|
241
|
+
`encode(file)` writes it and `decode(bytes)` reads it; `encode(decode(bytes))` is byte-identical, because the reader rejects anything the writer would not write.
|
|
242
|
+
|
|
243
|
+
#### Byte layout
|
|
244
|
+
|
|
245
|
+
Format version 1. Little-endian. Every padding byte, reserved field and unused bit is zero. Offsets are from the start of the file.
|
|
246
|
+
|
|
247
|
+
| Offset | Bytes | Field |
|
|
248
|
+
| ------ | ----- | ----------------------------------------------------------------------------- |
|
|
249
|
+
| 0 | 4 | Magic, the ASCII bytes `GPEW` |
|
|
250
|
+
| 4 | 2 | u16 format version, `1` |
|
|
251
|
+
| 6 | 2 | u16 flags, `0` |
|
|
252
|
+
| 8 | 4 | u32 definition hash, lane 0 |
|
|
253
|
+
| 12 | 4 | u32 definition hash, lane 1 |
|
|
254
|
+
| 16 | 4 | u32 `D`, the byte length of the definition JSON |
|
|
255
|
+
| 20 | 4 | u32 `T`, the tensor count |
|
|
256
|
+
| 24 | `D` | The canonical definition JSON in UTF-8, then zero bytes up to a multiple of 4 |
|
|
257
|
+
| then | | `T` tensor records, in plan order |
|
|
258
|
+
| then | | `T` payloads, in the same order |
|
|
259
|
+
|
|
260
|
+
A tensor record:
|
|
261
|
+
|
|
262
|
+
| Bytes | Field |
|
|
263
|
+
| ------- | ------------------------------------------------------------------------------------------ |
|
|
264
|
+
| 2 | u16 `L`, the byte length of the name |
|
|
265
|
+
| `L` | The tensor name in UTF-8, then zero bytes up to a multiple of 4 from the start of the file |
|
|
266
|
+
| 1 | u8 bit width, `6` or `32` |
|
|
267
|
+
| 1 | u8 rank `R` |
|
|
268
|
+
| 2 | u16 reserved, `0` |
|
|
269
|
+
| `4 * R` | u32 dimensions, outermost first |
|
|
270
|
+
| 4 | f32 scale: the int6 scale, `1` for float32 tensors |
|
|
271
|
+
| 4 | u32 payload bytes `P`: `ceil(6 * count / 8)` for bit width 6, `4 * count` for 32 |
|
|
272
|
+
|
|
273
|
+
A payload is `P` bytes, then zero bytes up to a multiple of 4. A float32 payload holds the values as little-endian f32 in row-major order. An int6 payload holds each value as the code `level + 32` (1 to 63) in 6 bits, packed LSB first: value `k` occupies bits `6k` to `6k + 5` of the payload, where bit `b` is bit `b mod 8` of byte `floor(b / 8)`, and bit 0 of the code comes first. Code 0 is invalid. The weight is `float32(level * scale)`.
|
|
274
|
+
|
|
275
|
+
Canonical definition JSON: the object `{ head, input, name, net, quant }` (`quant` only when the definition has one; budgets are not part of it), keys sorted by code unit at every level, no whitespace, as `JSON.stringify` writes it. The definition hash is two FNV-1a 32-bit lanes over its UTF-8 bytes (no padding): lane `j` starts at `basis_j = (2166136261 + j * 2654435769) mod 2^32` (lane 0 `0x811c9dc5`, lane 1 `0x1f54177e`), then for each byte `h = (h XOR byte) * 16777619 mod 2^32`. As text it is the 16 lowercase hex characters of lane 0 then lane 1.
|
|
276
|
+
|
|
277
|
+
The reader fails with:
|
|
278
|
+
|
|
279
|
+
| Code | When |
|
|
280
|
+
| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
281
|
+
| `WEIGHTS_FORMAT_INVALID` | Wrong magic, a nonzero flag, padding or reserved byte, a length past the end or trailing bytes, invalid UTF-8 or JSON, JSON not in canonical form, a definition that fails a definition-time check other than the budget, a bit width other than 6 or 32, a payload size that does not match the shape, a non-finite or negative scale or float, a scale of `-0`, a float32 tensor whose scale is not `1`, or int6 code 0 |
|
|
282
|
+
| `WEIGHTS_VERSION_UNSUPPORTED` | The magic matches and the version is not 1 |
|
|
283
|
+
| `WEIGHTS_DEFINITION_MISMATCH` | The stored hash is not the hash of the stored JSON, or the tensor count, a name, a shape or a bit width differs from `plan(definition)` |
|
|
284
|
+
|
|
285
|
+
The TypeScript trainer is only proven on models of up to about 130,000 parameters, most of them embedding rows (section 14). Larger models SHOULD be trained elsewhere and exported into the weights format.
|
|
286
|
+
|
|
287
|
+
## 6. Workflow harness
|
|
288
|
+
|
|
289
|
+
| Stage | Feature | Version | Proven by |
|
|
290
|
+
| ------------------- | ------------------------------------------------------------------------- | ------- | -------------------------------------------------------------------------------------------------- |
|
|
291
|
+
| Define | `defineModel` with a typed config | v1 | `test/kit/define.test.ts`, `test/index.test.ts` |
|
|
292
|
+
| Define | Budgets for Brotli bytes and multiply-adds | v1 | `test/kit/define.test.ts`, `test/harness/gate.test.ts` |
|
|
293
|
+
| Data | `defineDataset` with seeded generators | v1 | `test/harness/dataset.test.ts` |
|
|
294
|
+
| Data | Splits by group, such as schema, domain or meaning | v1 | `test/harness/dataset.test.ts` |
|
|
295
|
+
| Data | Data hashes | v1 | `test/harness/dataset.test.ts`, `test/harness/gate.test.ts` |
|
|
296
|
+
| Data | A check that splits share no vocabulary | v1 | `test/harness/dataset.test.ts` |
|
|
297
|
+
| Data | Written or teacher data with provenance | later | |
|
|
298
|
+
| Data | Blind second labels | later | |
|
|
299
|
+
| Train | Adam, warm-up and cosine decay | v1 | `test/train/adam.test.ts` |
|
|
300
|
+
| Train | QAT | v1 | `test/train/trainer.test.ts`, `test/kit/quant.test.ts` |
|
|
301
|
+
| Train | Best and last checkpoints | v1 | `test/train/trainer.test.ts` |
|
|
302
|
+
| Train | A wall-clock budget | v1 | `test/train/trainer.test.ts` |
|
|
303
|
+
| Train | Multi-seed runs | v1 | `test/train/trainer.test.ts` |
|
|
304
|
+
| Train | Warm start and distillation | later | |
|
|
305
|
+
| Evaluate | Baselines and an oracle in the same table as the model | v1 | `test/harness/evaluate.test.ts`, `test/harness/report.test.ts` |
|
|
306
|
+
| Evaluate | Per-set floors against the last promoted model | v1 | `test/harness/gate.test.ts`, `test/harness/promote.test.ts` |
|
|
307
|
+
| Evaluate | A noise-tolerant gate | v1 | `test/harness/gate.test.ts` |
|
|
308
|
+
| Sealed test set | Only `promote` reads it (section 8) | v1 | `test/harness/sealed.test.ts`, `test/harness/sealed-e2e.test.ts`, `test/harness/callbacks.test.ts` |
|
|
309
|
+
| Tune loop | One command that runs in under a minute | v1 | `test/harness/loop.test.ts` |
|
|
310
|
+
| Tune loop | A tries log | v1 | `test/harness/tries.test.ts` |
|
|
311
|
+
| Tune loop | Sweeps inside size budgets | later | |
|
|
312
|
+
| Quantize and export | int6 weights in the weights format | v1 | `test/kit/quant.test.ts`, `test/kit/weights.test.ts` |
|
|
313
|
+
| Runtime | `loadModel` on WebGPU and CPU (section 9) | v1 | `test/runtime/load.test.ts`, `test/gpu/model.test.ts` |
|
|
314
|
+
| Parity | Trainer, CPU and WGSL agree (section 10) | v1 | `test/harness/parity.test.ts`, `test/gpu/*.test.ts` |
|
|
315
|
+
| Ship | `gpu-engine build`: one module that imports nothing, and its declarations | v1 | `test/harness/build.test.ts`, `test/harness/scaffold.test.ts` |
|
|
316
|
+
| Ship | Size check with the weights included | v1 | `test/harness/ship.test.ts` |
|
|
317
|
+
| Ship | Package check: zero dependencies, only allowed files | v1 | `test/harness/ship.test.ts` |
|
|
318
|
+
| Ship | MODEL_CARD and RESULTS generated from the promoted report | v1 | `test/harness/report.test.ts`, `test/harness/promote.test.ts` |
|
|
319
|
+
| Ship | CI runs the gate in verify mode with strict shell flags | v1 | `test/harness/scaffold.test.ts`, `test/harness/promote.test.ts` |
|
|
320
|
+
| Agent support | Scaffolded AGENTS.md, a shipped skill, docs (section 12) | v1 | `test/harness/scaffold.test.ts`, `test/docs.test.ts` |
|
|
321
|
+
|
|
322
|
+
Every v1 row is built. "Proven by" names the test files that check it; `pnpm test` runs them, and `pnpm test:gpu` runs `test/gpu`.
|
|
323
|
+
|
|
324
|
+
Every command but `new` loads the package first: the one `*.model.ts` and the one `*.eval.ts` in the folder, each imported with a plain dynamic import. No such file is `PROJECT_FILE_MISSING`, two are `PROJECT_FILE_AMBIGUOUS`, a default export that did not come from `defineModel` or `defineEval` is `PROJECT_EXPORT_INVALID`, and a file that throws while it is imported is `PROJECT_IMPORT_FAILED` with the file and the error's message (a `DEFINE_*` error thrown by `defineModel` or `defineEval` keeps its own code). The files the harness keeps for itself, `tries.jsonl` and `.gpu-engine/candidate.json`, are read against their schemas: a row or file that does not parse, or has another shape, such as a line a killed `loop` left half-written or a candidate written by an older version, is `PROJECT_STATE_INVALID` with the file and line, never a bare parse error.
|
|
325
|
+
|
|
326
|
+
### Datasets
|
|
327
|
+
|
|
328
|
+
`defineDataset({ seed, minSize, generate? })` describes a model's data. Every command that trains runs the data step first: generate, check, record.
|
|
329
|
+
|
|
330
|
+
- Generate. `generate.<set>` is `(random) => examples`. The harness runs the generator of each set whose folder holds no file, with `random = createRandom((seed + j * 2654435769) mod 2^32)` where `j` is 0 for train, 1 for dev and 2 for test, and writes one `JSON.stringify(example)` per line to the set's pattern with `*` read as `main` and `?` as `0`, such as `data/train/main.jsonl`. A folder that holds any file is never written, and the write creates the file or fails, so an existing set, above all the test set, is never rewritten. The same seed writes the same bytes. Writing the test set is not a read: nothing the generator returns reaches the command. Each generator is optional: a set without one is never generated, and its empty folder is `DATA_SET_MISSING`. The test generator has done its work once the first `loop` wrote the test set, and at level 3 it MUST be gone, since the generator and `seed` rebuild the sealed rows without the key (section 7, Level 3).
|
|
331
|
+
- Stale generators. A generator runs only into an empty folder, so an edit to it would otherwise be ignored and the loop would keep training on the old rows. So the data step (in `loop`, `promote` and `promote --seal`) runs the train and dev generators again in memory and compares the text they return now with the generated file, the one named by the set's pattern as above. A difference is `DATA_GENERATOR_CHANGED` with the file, the lock is not recorded, and the command exits 1 before training. A set whose generated file does not exist (its folder holds only other files) is not compared. While a set has a generator, its generated file is the generator's output: to edit rows by hand, put them in another file of the set or remove the generator. The test generator is never run again and never compared: the test set is written once. `doctor` runs no generator, so it does not make this check.
|
|
332
|
+
- Regenerate. `gpu-engine loop --regenerate train`, `dev` or `train,dev` accepts a generator change: before the data step it rewrites the generated file of each named set from its generator (the folder's other files stay) and deletes that set's entry from `data.lock.json`, so the data step records it again once every check passes. A named set without a generator, or `test`, is `CLI_FLAG_INVALID`; the test set is never regenerated. A candidate trained before is stale afterwards, and a promoted dev floor now measures another dev set.
|
|
333
|
+
- Check. The checks in section 7, each a pure function over hashes, counts and fingerprints. `minSize.<set>` is the least number of rows in each file of that set. A row's `vocab` lists its words that no two sets may share, such as the unit words when the test units must be unseen. Vocabulary is a declared row field, like `group`, and not a function: the checks run on the test set without calling any code the package supplies, so no user function ever receives a test row outside `promote` (section 8).
|
|
334
|
+
- Record. When every check passes, each set without an entry in `data.lock.json` gets one.
|
|
335
|
+
- Table. A `retrieve` head scores against `eval.table`, a JSONL file of `{ "id": string, "text": string }` rows outside the three set folders. It is an input, not a split: no overlap, group or vocabulary check compares it with the sets. The checks need it: no `eval.table` with a `retrieve` head, or no file there, is `DATA_SET_MISSING`; a row that is not JSON with a non-empty string `id` and a string `text`, or whose `id` an earlier row already used, is `DATA_ROW_INVALID`; and every gold id in train and dev must name a row, else `DATA_LABEL_UNKNOWN`. The lock records its SHA-256 and row count under `table`, recorded and compared like a set's files, so a change is `DATA_HASH_CHANGED`. The candidate and the report record that hash too, so a table changed after `loop` leaves the candidate stale and a table changed after `promote` fails the report checks, even when its lock entry was deleted and recorded again. Every command that loads the package reads it (`loadProject`), so scoring needs no data step.
|
|
336
|
+
|
|
337
|
+
`data.lock.json` records, per set, the SHA-256 and row count of each file; the test entry also keeps the test set's fingerprints (section 7, Reads and digests):
|
|
338
|
+
|
|
339
|
+
```json
|
|
340
|
+
{
|
|
341
|
+
"train": { "files": { "data/train/main.jsonl": { "sha256": "<64 hex>", "examples": 48 } } },
|
|
342
|
+
"dev": { "files": { "data/dev/main.jsonl": { "sha256": "<64 hex>", "examples": 16 } } },
|
|
343
|
+
"test": {
|
|
344
|
+
"files": { "data/test/main.jsonl": { "sha256": "<64 hex>", "examples": 16 } },
|
|
345
|
+
"fingerprints": { "inputs": ["<16 hex>"], "groups": ["<16 hex>"], "vocabulary": ["<16 hex>"] }
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
```
|
|
349
|
+
|
|
350
|
+
- The harness never rewrites an entry, except that `loop --regenerate` deletes the entries of the sets it rewrites. When a set's files differ from its entry (a hash, a file added or removed), every run reports `DATA_HASH_CHANGED`. To accept a change, delete that set's entry by hand and rerun. A `retrieve` package adds `"table": { "files": { "data/table.jsonl": { "sha256": "<64 hex>", "examples": 20 } } }`, which follows the same rule.
|
|
351
|
+
- At level 3 the test entry names the sealed files instead, each with a `plaintext` field (section 7, Level 3).
|
|
352
|
+
- When every test file matches its recorded hash, the checks take the test set's counts and fingerprints from the lock, and rows the digest cannot decode are not reported. A test set the guard cannot decode, or that is out of reach at level 3, is still checked against the other sets without a read. Train and dev fingerprints are computed from their files on every run.
|
|
353
|
+
- The recorded vocabulary fingerprints come from the test rows' `vocab` fields, so they change only with the test files.
|
|
354
|
+
|
|
355
|
+
### Scores
|
|
356
|
+
|
|
357
|
+
A score table has one column per named set (one file is one set, named after the file without `.jsonl`) and one row per method: the model, each baseline in `baselines`, and the oracle. For each example the reference is `expect` when the row has one, else `decode(gold, input)`; the model scores `metric(decode(output, input), reference)`, where `output` is what the head decodes from the CPU forward pass on the weights; a baseline scores `metric(baseline(input), reference)` and the oracle `metric(decode(gold, input), reference)`. Without `decode`, the head output and the gold are used as they are. For a `retrieve` head the gold ids first become the head's output shape, the ranking a perfect model gives: the gold rows in gold order with score 1, then every other row in table order with score 0. So `decode` and `metric` see the same shape for the model and the gold, and `(raw) => raw[0].id` decodes both to the top row. The table rows are encoded once per scoring call with the weights being scored. A set's score per method is the mean over its examples. The dev score is the mean of the model's scores over the dev sets. The model is always scored on its quantized weights, so a float score is never reported.
|
|
358
|
+
|
|
359
|
+
### Loop
|
|
360
|
+
|
|
361
|
+
`gpu-engine loop [--log "<idea>"] [--status kept|dropped] [--regenerate train|dev|train,dev]` runs one try:
|
|
362
|
+
|
|
363
|
+
1. The level 1 scan (section 7). Any finding is printed and the loop exits 1.
|
|
364
|
+
2. The data step (Datasets), after `--regenerate` rewrote its sets. Any diagnostic, `DATA_GENERATOR_CHANGED` included, is printed and the loop exits 1 before training.
|
|
365
|
+
3. Training on every train set together, with the dev score as the trainer's dev scorer, so each seed's `best` checkpoint is the one with the best dev score. When a seed finishes, the loop prints one progress line for it: `train: seed <seed> done (<i>/<n>), best dev <score> at epoch <epoch>, <steps> steps, <seconds> s, stopped by epochs|budget`.
|
|
366
|
+
4. The candidate is written to `.gpu-engine/`, replacing the last one: `candidate.bin` (the weights file of the chosen checkpoint, the best checkpoint of the best seed), `candidate.json`, and `checkpoints/seed-<seed>-best.bin` and `checkpoints/seed-<seed>-last.bin` for every seed. `candidate.json` holds `{ at, commit, dirty, definition, data, seeds, seed, checkpoint, steps, trainSeconds, stoppedBy, devBySeed, dev, devScore, devSpread, brotliBytes, macsPerToken }`, with `data` the SHA-256 of every train, dev and test file from `data.lock.json`, plus a `table` entry with the table's SHA-256 for a `retrieve` head, and `dev` the dev score table. `promote` refuses a candidate whose definition hash or data hashes, the table's included, no longer match (`PROMOTE_CANDIDATE_STALE`); the hashes are compared file by file, so the order of the keys in `candidate.json` does not matter. A `candidate.json` that does not parse or lacks a field is `PROJECT_STATE_INVALID`, and running `loop` again replaces it.
|
|
367
|
+
5. The dev table and the gate lines are printed. When a seed diverged (Trainer, section 5), one line `note: training diverged on seed <s> at step <k>, ...` names every such seed with its step and the fix (lower `train.learningRate`, raise `warmup`), before the table.
|
|
368
|
+
6. One row is appended to `tries.jsonl`, with `diverged` when a seed diverged.
|
|
369
|
+
7. The loop exits 0 when every gate line passes and 1 otherwise. The candidate and the try are written either way.
|
|
370
|
+
|
|
371
|
+
`gpu-engine loop --fail [--set <name>]` trains nothing and appends no try. After the data step it scores the candidate on dev, or on the one dev set `--set` names, and prints every dev example where the model scores below the oracle, with its input, the reference and the model's result. It exits 1 with `PROMOTE_CANDIDATE_MISSING` when there is no candidate and with `PROMOTE_CANDIDATE_STALE` when the candidate is stale. It never prints a test example: the test set is not read.
|
|
372
|
+
|
|
373
|
+
`gpu-engine loop --mark kept|dropped` trains nothing and appends no try. It records the decision on the last try once its dev score is known: it sets the `status` of the last row of `tries.jsonl` when that status is `null`, and leaves every other row and field as it was. With no try, or when the last try already has a status, it exits 1 with `CLI_FLAG_INVALID` and changes nothing. It takes no other `loop` flag but `--dir`.
|
|
374
|
+
|
|
375
|
+
### Tries log
|
|
376
|
+
|
|
377
|
+
`tries.jsonl` is append-only, one row per try, with this closed key list. The one edit is `loop --mark`, which sets a `null` status of the last row once:
|
|
378
|
+
|
|
379
|
+
```json
|
|
380
|
+
{
|
|
381
|
+
"at": "2026-11-21T12:00:00.000Z",
|
|
382
|
+
"commit": "<git HEAD, or none>",
|
|
383
|
+
"dirty": false,
|
|
384
|
+
"idea": "<--log, or an empty string>",
|
|
385
|
+
"status": "kept | dropped | null",
|
|
386
|
+
"definition": "<definition hash>",
|
|
387
|
+
"seeds": [1, 2, 3],
|
|
388
|
+
"dev": { "<dev set>": 0.94 },
|
|
389
|
+
"devScore": 0.94,
|
|
390
|
+
"devSpread": 0.01,
|
|
391
|
+
"brotliBytes": 1234,
|
|
392
|
+
"macsPerToken": 900,
|
|
393
|
+
"trainSeconds": 4.2,
|
|
394
|
+
"gate": "pass | fail"
|
|
395
|
+
}
|
|
396
|
+
```
|
|
397
|
+
|
|
398
|
+
`diverged` is the one optional key: present only on a try where a seed diverged, it maps each such seed to the step where its loss stopped being finite, such as `{ "2": 14 }`. `dirty` is true when the working tree has uncommitted changes, read after the data step, so a generated or regenerated data file that is not committed counts. The package's own `tries.jsonl` and `reads.jsonl` do not count: every command appends to them, so they would make every try dirty. `devSpread` is the highest minus the lowest seed's best dev score, 0 for one seed. `brotliBytes` is the weights file of the candidate compressed with Brotli at quality 11. A row with a key outside the list, or without a key of the list other than `diverged`, is refused, and a row with a key matching `/test/i` at any depth is refused with `DATA_TEST_PRINTED`, so a try can never carry a test score.
|
|
399
|
+
|
|
400
|
+
### Gate
|
|
401
|
+
|
|
402
|
+
`gate.json` is `{ level, promoted }`, with `promoted` null until the first promotion and then `{ at, commit, weights, definition, dev: { <set>: score }, test: { <set>: score } }`. A package without the file is at level 2 with nothing promoted; a file that does not parse is `GATE_FILE_INVALID`. The gate is a list of lines, each passing or failing with a code:
|
|
403
|
+
|
|
404
|
+
| Line | Passes when | Code |
|
|
405
|
+
| ------ | ---------------------------------------------------------------------------------------------------------------------------- | ------------------------ |
|
|
406
|
+
| Floor | One per scored set: the model's score is at least the promoted score minus `gate.noise`. A set with no promoted score passes | `GATE_FLOOR_FAILED` |
|
|
407
|
+
| Floor | A promoted set that has no score now fails, so removing a set cannot skip its floor | `GATE_FLOOR_FAILED` |
|
|
408
|
+
| Budget | The Brotli bytes of the weights file are at most `budgets.brotliBytes` | `BUDGET_BYTES_EXCEEDED` |
|
|
409
|
+
| Budget | `macsPerToken` is at most `budgets.macsPerToken` | `DEFINE_BUDGET_EXCEEDED` |
|
|
410
|
+
| Data | Every train, dev and test file matches its hash in `data.lock.json` | `DATA_HASH_CHANGED` |
|
|
411
|
+
|
|
412
|
+
`loop` gates the dev sets and `promote` the dev and test sets. On the first promotion every floor line passes. A score at exactly the floor passes. The floor line prints the seed spread next to `noise`: a spread wider than `noise` means the floor is inside the seed-to-seed variation.
|
|
413
|
+
|
|
414
|
+
### Promote
|
|
415
|
+
|
|
416
|
+
`gpu-engine promote` turns the candidate into the promoted model. It does not train.
|
|
417
|
+
|
|
418
|
+
1. At level 3, the CI and key checks before anything else (section 7, Level 3). Then the level 1 scan and the data step, as in `loop`. Any finding is printed and `promote` exits 1.
|
|
419
|
+
2. The candidate must be fresh: `PROMOTE_CANDIDATE_MISSING` without one, `PROMOTE_CANDIDATE_STALE` when its definition hash or its data hashes (a `retrieve` head's table included) no longer match the package. Nothing is read before this passes.
|
|
420
|
+
3. Every gate line that needs no test row, before the read: the candidate's weights file is scored on dev, then the dev floors, both budgets and the data line (Gate). When one fails, `promote` prints the dev table and those lines, reads nothing, writes nothing and exits 1, so a promotion that cannot pass costs no read.
|
|
421
|
+
4. One counted read of the test set (section 7, Reads and digests). Rows whose gold does not fit the head are `DATA_ROW_INVALID` or `DATA_LABEL_UNKNOWN`, with the set and the count of rows, by the same rules the data step applies to train and dev: for a `retrieve` head every gold id must name a row of the table, else `DATA_LABEL_UNKNOWN`. These diagnostics are scanned like every other string after the read (below).
|
|
422
|
+
5. The weights are scored on test (Scores). An error thrown by `metric`, `decode` or a baseline while a test set is scored, or raised as an unhandled promise rejection or an uncaught exception by the package's code from the read on, is `PROMOTE_SCORE_FAILED` with the set and its row count. The error's own message is dropped, since it can quote a test example. The package's output is muted (Output mute, below).
|
|
423
|
+
6. The gate lines for dev and test. When a line fails, `promote` prints the tables and the gate, writes nothing, and exits 1.
|
|
424
|
+
7. On a pass it writes `weights/<name>.bin` (the candidate's bytes), `src/weights.ts` (the same bytes as lowercase hex, `0-9a-f` only, so the generated text can never spell a word), `gate.json` (level kept, or 3 when the read decrypted sealed files; `promoted` replaced), `MODEL_CARD.md`, `RESULTS.md` and `report.json`, then prints the tables and the gate and exits 0. Each file goes first to a temporary file in `.gpu-engine/`; once all six are written they are renamed into place, `report.json` last. A promotion stopped before the renames changes none of them, and one stopped during them leaves the old `report.json`, which `--verify` then reports against the new files.
|
|
425
|
+
8. Last, after any read, pass or fail, it scans the files the promote workflow commits (section 7, Level 3): every file under `weights/`, `src/weights.ts`, `gate.json`, `report.json`, `MODEL_CARD.md`, `RESULTS.md`, `reads.jsonl` and `tries.jsonl`, each file's path included, with the test file paths themselves left out. A line of `reads.jsonl` or `tries.jsonl` that holds a test input is removed; any other file that holds one is put back to its version at git `HEAD`, or deleted when `HEAD` has none. Any hit is `DATA_TEST_PRINTED` with the number of inputs and files, and `promote` exits 1. This catches test inputs the package's code wrote into those files itself while it ran.
|
|
426
|
+
|
|
427
|
+
Every string `promote` prints or writes after the read, error messages included, is first scanned for the test inputs. An input is found when its text, lowercased with runs of whitespace collapsed and trimmed, appears in the string normalised the same way, or in the decoded value of a JSON string literal inside the string, so an input with quotes, backslashes or line breaks is found after `JSON.stringify` escaped them. A literal is read from every quote in the string, so an unmatched quote in the text around the JSON does not hide one. Inputs shorter than 8 characters after normalising are not scanned: they cannot be told apart from the numbers and words a report holds anyway. A hit aborts with `DATA_TEST_PRINTED` and the number of inputs found, before anything is printed or written. The test set leaves `promote` as per-set aggregates only.
|
|
428
|
+
|
|
429
|
+
`gpu-engine promote --scan` runs step 8 in a process of its own, so it also catches what the package's code wrote after `promote` returned. It imports neither the model nor the eval file. It takes the test files from the test entry of `data.lock.json` at git `HEAD` (the working tree's lock outside git), opens them inside the guard, checks each against its locked SHA-256, decrypts them in memory at level 3, where it needs `CI` and the key as `promote` does, and logs one `digest` row: only the number of inputs found leaves the guard. It exits 0 when nothing was found, and 3 after a repair. It refuses, changing nothing, when the lock names no test file (`PROMOTE_SCAN_FAILED`) and, at level 3, outside CI or without a well-formed key (`PROMOTE_OUTSIDE_CI`, `SEAL_KEY_MISSING`, `SEAL_KEY_INVALID`): `promote` refuses the same way before its read, so no row was in memory. When it cannot open the test set (a missing or changed test file, a key that does not decrypt), it puts every file it would scan but `reads.jsonl` back to `HEAD`, keeps in `reads.jsonl` the lines `HEAD` has plus each other line that is a well-formed reads row (the seven fields of section 7, Reads and digests, each of its type, every file a test file the lock names, with or without `.enc`), prints the reason with its code and exits 3. Exit 0 and exit 3 are the only codes that confirm the files are safe to commit: the promote workflow commits after either, and fails after 3. Any other code (a refusal exits 1, and so does an error the scan stops on) leaves the files unconfirmed, so the workflow commits nothing and fails with that code.
|
|
430
|
+
|
|
431
|
+
Output mute. Before `promote` imports the model and eval files, it replaces every `console` method that prints, `write` and `end` on `process.stdout` and `process.stderr`, `process._rawDebug`, and the `node:fs` functions that write to a file descriptor (`write`, `writeSync`, `writev`, `writevSync`, `writeFile`, `writeFileSync`, `appendFile`, `appendFileSync`) for descriptors 1 and 2, so a reference the package's code saves when it loads is the replacement too. The `fs` replacements pass every other descriptor and every path through. Until the counted read the replacements pass output through. From the read on they write nothing and count each attempt, and `promote` prints its own lines past them. From the read on `promote` also takes the `unhandledRejection` and `uncaughtException` events: listeners added before are detached until the mute ends, and each event is counted and its error dropped unprinted. After it scores each test set, and again before it writes anything and before it returns, `promote` lets pending microtasks, `process.nextTick` callbacks and zero-delay timers run, so output and errors the package code deferred are counted too. Any print attempt from the read on is `DATA_TEST_PRINTED` with the number of attempts, naming the set when it came while that set was scored, any unhandled error is `PROMOTE_SCORE_FAILED` the same way, nothing the package code tried to print is shown, and `promote` exits 1. An attempt or an error after the promotion was written still turns the exit code to 1. The `gpu-engine` process keeps the replacements and the error listeners until it exits: an attempt after `promote` returned prints `DATA_TEST_PRINTED`, an error `PROMOTE_SCORE_FAILED`, and either sets the exit code to 1. Called through the API (`runPromote`), `promote` restores the originals and the listeners when it returns.
|
|
432
|
+
|
|
433
|
+
### Report
|
|
434
|
+
|
|
435
|
+
`report.json` holds what the promotion measured, aggregates only:
|
|
436
|
+
|
|
437
|
+
```json
|
|
438
|
+
{
|
|
439
|
+
"name": "<model name>",
|
|
440
|
+
"date": "<ISO time of the promotion>",
|
|
441
|
+
"commit": "<git HEAD, or none>",
|
|
442
|
+
"definition": "<definition hash>",
|
|
443
|
+
"weights": { "sha256": "<64 hex>", "bytes": 1234, "brotliBytes": 1000 },
|
|
444
|
+
"params": 900,
|
|
445
|
+
"macsPerToken": 900,
|
|
446
|
+
"train": {
|
|
447
|
+
"seeds": [1, 2, 3],
|
|
448
|
+
"chosenSeed": 2,
|
|
449
|
+
"checkpoint": "best",
|
|
450
|
+
"steps": 600,
|
|
451
|
+
"seconds": 4.2,
|
|
452
|
+
"devBySeed": { "2": 0.94 }
|
|
453
|
+
},
|
|
454
|
+
"data": { "train": { "data/train/main.jsonl": { "sha256": "<64 hex>", "examples": 48 } }, "dev": {}, "test": {} },
|
|
455
|
+
"dev": { "<dev set>": { "examples": 16, "model": 0.94, "baselines": { "rules": 0.9 }, "oracle": 1 } },
|
|
456
|
+
"test": { "<test set>": { "examples": 16, "model": 0.93, "baselines": { "rules": 0.9 }, "oracle": 1 } },
|
|
457
|
+
"gate": [{ "name": "floor dev main", "pass": true, "detail": "<as printed>" }],
|
|
458
|
+
"testReads": 1,
|
|
459
|
+
"level": 2
|
|
460
|
+
}
|
|
461
|
+
```
|
|
462
|
+
|
|
463
|
+
`train.seeds` and `train.chosenSeed` take any safe integer, negative ones included, the same rule as `train.seeds` in `defineEval` and `seeds` and `seed` in `candidate.json`. `data` is the `data.lock.json` entry of every file at promotion. A `retrieve` head adds `"table": { "data/table.jsonl": { "sha256": "<64 hex>", "examples": 20 } }`, its lock entry, and the model card's data table lists it as `table`. A report written before reports recorded the table has no `table`, and its table is not compared. `testReads` is the number of `examples` rows in `reads.jsonl` after this promotion's read. `MODEL_CARD.md` and `RESULTS.md` are rendered from the report by pure functions (`renderModelCard(report, parity, definition)`, `renderResults(report)`), so `--verify` can regenerate them. The model card states the level and the test read count, and names the weights the scores come from: int6 when the definition has `quant`, float32 when it has none. Until `parity.json` exists for these weights (its `weights` is the report's weights SHA-256), it says parity has not run. Once it does, the card names the adapter, says when parity and speed figures come from a software adapter, with the rasterizer when the adapter name has one (`software adapter (llvmpipe)`), states the real GPU run as `parity.json` records it (`not run` until one is), and states `Real browser: not run`, since parity runs in Node.
|
|
464
|
+
|
|
465
|
+
### Verify
|
|
466
|
+
|
|
467
|
+
`gpu-engine promote --verify` is the CI gate. It reads no test data: the data checks take a digest, as in every other command, and nothing else touches the test files. It writes nothing but the digest row in `reads.jsonl`. It runs every check below, prints each failure with its code, and exits 1 when any fails.
|
|
468
|
+
|
|
469
|
+
| Check | Code |
|
|
470
|
+
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
|
|
471
|
+
| The level 1 scan | `DATA_TEST_READ` |
|
|
472
|
+
| `report.json` exists and parses | `VERIFY_REPORT_INVALID` |
|
|
473
|
+
| The section 7 data checks, and every train, dev and test file in `data.lock.json` has the hash `report.json` recorded (section 7, Level 3, for a report written before the seal) | `DATA_*`, `DATA_HASH_CHANGED` |
|
|
474
|
+
| The model file hashes to the report's `definition` | `WEIGHTS_DEFINITION_MISMATCH` |
|
|
475
|
+
| `weights/<name>.bin` has the report's SHA-256, bytes and Brotli bytes | `VERIFY_WEIGHTS_CHANGED` |
|
|
476
|
+
| Re-scoring the committed weights on dev gives the report's dev table exactly | `VERIFY_SCORE_CHANGED` |
|
|
477
|
+
| `gate.json` has the report's level, or level 3 over a report written before the seal, and its `promoted` entry has the report's time, commit, weights, definition and model score per set | `VERIFY_SCORE_CHANGED` |
|
|
478
|
+
| The budgets and the dev floors (Gate) | `BUDGET_BYTES_EXCEEDED`, `DEFINE_BUDGET_EXCEEDED`, `GATE_FLOOR_FAILED` |
|
|
479
|
+
| `reads.jsonl` has at least `testReads` rows of kind `examples` | `VERIFY_READS_MISSING` |
|
|
480
|
+
| `MODEL_CARD.md`, `RESULTS.md` and `src/weights.ts` regenerate byte-identical | `VERIFY_FILE_STALE` |
|
|
481
|
+
|
|
482
|
+
When the report records a `table`, the data check compares the table's hash in `data.lock.json` with it the same way (`DATA_HASH_CHANGED`), and so does doctor's report check.
|
|
483
|
+
|
|
484
|
+
A model file changed after the promotion fails verify with `WEIGHTS_DEFINITION_MISMATCH`: the committed weights no longer belong to the committed model, so CI fails until the tuned model is promoted. That state is expected while tuning; the fix is to promote once when the tuning is done, not after every try.
|
|
485
|
+
|
|
486
|
+
Verify cannot re-measure the test scores without a read, so it checks that the report, `gate.json` and the generated files agree on them. An edit to all of them together shows only in the repository history.
|
|
487
|
+
|
|
488
|
+
### Build
|
|
489
|
+
|
|
490
|
+
`gpu-engine build` (a package's `npm run build`) writes what the package ships. It loads the package like every other command, then:
|
|
491
|
+
|
|
492
|
+
1. For a `retrieve` head, it reads the table the eval names (`table`, the file the data step locks and `promote` scores against) and writes its rows to `src/table.ts`, one `JSON.stringify({ id, text })` per line, so the shipped entry imports the table the harness evaluated. A line that is not a `{ id, text }` row is `DATA_ROW_INVALID`, and a missing table `DATA_SET_MISSING`.
|
|
493
|
+
2. It bundles `src/index.ts` and everything it imports into `dist/index.mjs`: one ES module that imports nothing and runs in browsers and in Node. It strips the types of `.ts` files with Node's `stripTypeScriptTypes`, resolves installed packages through their `exports` (`browser`, `import`, `default`) to their real paths, so a package that two links reach (pnpm links a workspace package into each folder that depends on it) is bundled once, and wraps each module in a function in import order, so names never collide. It reads `import` and `export` with a tokenizer (the one the ship check uses), not by line: every static form, destructuring exports such as `export const [a, b] = pair`, and minified code all bundle, and text in comments, strings and templates is never taken for syntax. A dynamic `import()`, an import with attributes, a JSON file, a Node built-in, an absolute path and an import cycle are `BUILD_SOURCE_UNSUPPORTED`. The bundle reads each module's exports once, so it cannot follow a later assignment the way an ES module import does: an export that a top-level `let` or a `var` at any depth holds (a `var` in a block is module scope) in the package's own modules (not under `node_modules`) is `BUILD_SOURCE_UNSUPPORTED`; a string or a property key named `let` or `var` declares nothing, and an installed package is bundled as it is. Node parses the bundle as a module, without running it, before anything is written; a module that fails inside the function that wraps it, which is a top-level `await`, is `BUILD_SOURCE_UNSUPPORTED` naming that module. A path or package that does not resolve is `BUILD_IMPORT_UNRESOLVED`. The module starts with one `/*! ... */` comment that carries the licence of every bundled package (`LICENSE`) and the copyright lines of the third-party code it adapts (`THIRD_PARTY_NOTICES.md`), so the MIT notices ship with the code. gpu-engine's own `dist/` is minified when it is packed, so the runtime in every shipped model is minified; the package's own modules are bundled as written.
|
|
494
|
+
3. It writes `dist/index.d.mts`, the declarations of every export of `src/index.ts`, from TypeScript's checker: the package's `typescript`, else the one gpu-engine finds, with the package's `tsconfig.json`. Every type an export uses is declared in the same file by its name, gpu-engine's types included, so an app that installs the package with no other dependency typechecks with `strict` and `skipLibCheck: false`; types of the TypeScript standard library stay references. A conditional or a mapped type declares the names its branches use, and an anonymous `export default` is declared as `_default` (or `_default1`, `_default2` and so on when another declaration has that name) and exported as `default`. An anonymous default export re-exported under another name (`export { default as x } from './m.ts'`, or an imported default exported as `x`) is `BUILD_SOURCE_UNSUPPORTED`, since the bundle would export it as `x` and the declarations as `default`; the default needs a name where it is declared. Without TypeScript, with a type error in the package's own files, or with an export it cannot declare (a class, an enum or a namespace), the build is `BUILD_TYPES_FAILED`. The written file is then typechecked on its own, as an app would (`strict`, `skipLibCheck: false`, the ES2023 and DOM libraries); when it does not typecheck, such as a key that is a symbol the package does not export, the build is `BUILD_SOURCE_UNSUPPORTED`, so the file it writes always typechecks.
|
|
495
|
+
|
|
496
|
+
It prints each file it wrote with its bytes and Brotli bytes, writes nothing else, and exits 1 with the diagnostic on any failure, before writing `dist/`. A scaffolded `package.json` exports `dist/index.mjs` with `types` pointing at `dist/index.d.mts`.
|
|
497
|
+
|
|
498
|
+
### Ship
|
|
499
|
+
|
|
500
|
+
The shipped model is one module that imports nothing, with its declarations: `gpu-engine build` bundles `src/index.ts`, the gpu-engine runtime and the promoted weights into `dist/index.mjs` and writes `dist/index.d.mts` (Build). The ship checks look at the package the way npm would publish it. `gpu-engine doctor` runs them when the package has a `dist/` folder; CI builds first, so they run on every push. They read `package.json`, the files `npm pack --dry-run --json --ignore-scripts` lists and `weights/<name>.bin`, and write nothing. On Windows, where `npm` is the batch file `npm.cmd` that only a shell runs, the same command runs through the shell.
|
|
501
|
+
|
|
502
|
+
| Check | Code |
|
|
503
|
+
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- |
|
|
504
|
+
| `package.json` exists and parses, and `npm pack --dry-run --json` lists the packed files | `SHIP_PACKAGE_INVALID` |
|
|
505
|
+
| `package.json` has no `dependencies`, `peerDependencies`, `optionalDependencies`, `bundleDependencies` or `bundledDependencies` field, and no packed `.js`, `.mjs` or `.cjs` file loads a module: a static `import`, an `export ... from`, or an `import('x')` or `require('x')` call with a string, found by a tokenizer that skips comments, strings, template text and regular expressions and reads minified code | `SHIP_DEPENDENCY_FOUND` |
|
|
506
|
+
| Once `weights/<name>.bin` exists, a packed file holds it as lowercase hex, so the build includes the promoted weights | `SHIP_BUILD_STALE` |
|
|
507
|
+
| When `report.json` records a `table`, that file still has the recorded SHA-256 and a packed file holds its rows as the build writes them, so the shipped table is the one the promotion scored | `SHIP_BUILD_STALE` |
|
|
508
|
+
| Every packed file is `package.json`, which npm always packs, or a path listed in `ship.files` | `SHIP_FILE_NOT_ALLOWED` |
|
|
509
|
+
| The Brotli bytes (quality 11) of every packed file but `package.json`, summed, are at most `ship.brotliBytes` | `SHIP_SIZE_EXCEEDED` |
|
|
510
|
+
|
|
511
|
+
`ship.files` holds exact paths, such as `dist/index.mjs` and `dist/index.d.mts`. Without `ship` in the eval file the last two checks do not run, and doctor says so in a note.
|
|
512
|
+
|
|
513
|
+
The repository's CI runs the gate in verify mode in a `gate` job, under `set -euo pipefail`: it builds gpu-engine, then in every `examples/*` folder with a `report.json` it builds the example, runs `gpu-engine doctor` (so the ship checks run) and `gpu-engine promote --verify`. A folder without a report is skipped, and no examples at all pass. A scaffolded package's own workflow does the same for itself (section 12).
|
|
514
|
+
|
|
515
|
+
### Doctor
|
|
516
|
+
|
|
517
|
+
`gpu-engine doctor` runs every check that needs no training and no test read. It prints each finding with its code, why and fix, a `pass` or `note` line for every check that has nothing to report, and exits 1 on any finding, 0 when there is none.
|
|
518
|
+
|
|
519
|
+
| Check | Runs when | Code |
|
|
520
|
+
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
521
|
+
| The model and eval files load, with the definition-time checks (section 5) | Always. A package that does not load stops here | `PROJECT_*`, `DEFINE_*` |
|
|
522
|
+
| The level 1 scan | Always | `DATA_TEST_READ` |
|
|
523
|
+
| The section 7 data checks, the lock included, with a digest of the test set | Always | `DATA_*` |
|
|
524
|
+
| `gate.json` parses | The file exists | `GATE_FILE_INVALID` |
|
|
525
|
+
| The Brotli bytes of the promoted weights are within `budgets.brotliBytes` | `weights/<name>.bin` exists | `BUDGET_BYTES_EXCEEDED` |
|
|
526
|
+
| The report agrees with the package: it parses, the model file hashes to its `definition` (else a note, below), the weights file has its SHA-256 and sizes, the lock has its data hashes, `gate.json` has its level and promoted entry, `reads.jsonl` its read count, and the generated files regenerate byte-identical | `report.json` exists, or `gate.json` records a promotion | `VERIFY_REPORT_INVALID`, `VERIFY_WEIGHTS_CHANGED`, `DATA_HASH_CHANGED`, `VERIFY_SCORE_CHANGED`, `VERIFY_READS_MISSING`, `VERIFY_FILE_STALE` |
|
|
527
|
+
| The ship checks (Ship) | The package has a `dist/` folder | `SHIP_*` |
|
|
528
|
+
| The level 3 checks (section 7) | `gate.json` is at level 3 | `SEAL_PLAINTEXT_FOUND`, `SEAL_LOCK_INVALID`, `SEAL_WORKFLOW_MISSING`, `SEAL_GENERATOR_FOUND` |
|
|
529
|
+
|
|
530
|
+
Doctor writes no data file and no lock entry, and runs no generator: the only file it changes is `reads.jsonl`, where the guard's digest appends its `digest` row like every other guard call. It calls no function the package supplies (no metric, decode, baseline or generator), so no package code sees any row (section 8). That is why it does not re-score dev; `promote --verify` does.
|
|
531
|
+
|
|
532
|
+
A model file that no longer hashes to the report's `definition` is a note, not a finding: after a promotion every change to the model makes it so, and doctor must not push an agent to spend a test read after each try. The note names both hashes and says that `promote --verify`, and so CI, fails with `WEIGHTS_DEFINITION_MISMATCH` until the tuned model is promoted once. In that state doctor does not compare `MODEL_CARD.md`, which renders parts of the model file; every other report check runs.
|
|
533
|
+
|
|
534
|
+
A fresh package passes. A set whose folder holds no file at all, in a package whose `defineDataset` declares generators, is not missing: doctor prints a note that `loop` will generate it and reports no `DATA_SET_MISSING` for it. A set without an entry in `data.lock.json` gets a note that `loop` records it once every check passes. A check this version cannot run yet is skipped with a note, never a crash.
|
|
535
|
+
|
|
536
|
+
### Inspect
|
|
537
|
+
|
|
538
|
+
`gpu-engine inspect "<text>"` shows what the model does with one input, in this order:
|
|
539
|
+
|
|
540
|
+
1. The tokens of `tokenize(text)` with their offsets, and how many fall after `input.max`.
|
|
541
|
+
2. The feature rows of each kept token, per feature row in definition order: the embedding row of each slot, `-` for an empty one.
|
|
542
|
+
3. The raw output: the logits the forward pass returns, one per label for each token of a `tag` head, one per label or output for a `pooled` head, one per table row for a `retrieve` head.
|
|
543
|
+
4. The decoded result: the head output and `decode(output, text)`, or the head output alone when the eval has no `decode`.
|
|
544
|
+
5. The backend that ran.
|
|
545
|
+
6. The reason that chose it.
|
|
546
|
+
|
|
547
|
+
Before the raw output it prints the weights file it runs with its byte length, and `definition:` with the definition hash the file carries, the hash `report.json` and `tries.jsonl` record; when the model file hashes to another value, the line names that hash too. It runs the weights that belong to the model file: the candidate from the last `loop` when the definition hash it carries is the model file's, else `weights/<name>.bin` when that one's is. The candidate comes first because it is what the loop is tuning; when its bytes are the promoted file's (as right after `promote`), the line names the promoted file. When nothing is promoted it prints a note saying so. When neither file was trained from the model file, it runs the candidate, else the promoted file, and exits 1 with `WEIGHTS_DEFINITION_MISMATCH`, whose fix says that a changed model is expected while tuning: run `loop`, and promote once when done. Without either file it exits 1 with `PROMOTE_CANDIDATE_MISSING`. It loads the file with `loadModel(bytes, { backend: 'auto', definition })` and no WebGPU entry point, so in Node the reason names `auto` rule 1 and the CPU runs. The text runs with every flag off. A `retrieve` model scores against the rows of `table`, read and checked with the data step's table rules: no table is `DATA_SET_MISSING` and a bad or repeated row is `DATA_ROW_INVALID`, each exiting 1 before the model runs. Inspect opens no data file but the table and takes no digest: the test set is not touched and `reads.jsonl` gets no row. It exits 0 when the run succeeds and 1 with the run's error otherwise.
|
|
548
|
+
|
|
549
|
+
## 7. Data splits and enforcement
|
|
550
|
+
|
|
551
|
+
Every model has three sets:
|
|
552
|
+
|
|
553
|
+
| Set | Folder | What it is for |
|
|
554
|
+
| ----- | ------------- | ----------------------------------------------- |
|
|
555
|
+
| train | `data/train/` | What the model learns from |
|
|
556
|
+
| dev | `data/dev/` | What the loop tunes against, as often as needed |
|
|
557
|
+
| test | `data/test/` | Sealed. Only `promote` reads it |
|
|
558
|
+
|
|
559
|
+
Two sets are not enough. If the loop tunes against the set that produces the reported score, each kept try fits that set a little more, and the score moves without the model getting better.
|
|
560
|
+
|
|
561
|
+
For data that comes from logs over time, the split is by time: train on earlier windows, test on the latest.
|
|
562
|
+
|
|
563
|
+
The harness runs these checks:
|
|
564
|
+
|
|
565
|
+
| Check | When it runs | Code |
|
|
566
|
+
| ----------------------------------------------------------------------------------------- | ------------------- | -------------------- |
|
|
567
|
+
| All three sets exist | Before any training | `DATA_SET_MISSING` |
|
|
568
|
+
| Each set meets a minimum size | Before any training | `DATA_SET_TOO_SMALL` |
|
|
569
|
+
| Every row is a JSON `{ input, gold }` row with gold in the shape of the head | Before any training | `DATA_ROW_INVALID` |
|
|
570
|
+
| Every gold label is one of the head labels | Before any training | `DATA_LABEL_UNKNOWN` |
|
|
571
|
+
| No example appears in two sets, after normalising case and whitespace | Before any training | `DATA_SPLIT_OVERLAP` |
|
|
572
|
+
| No declared group, such as a schema, a site, a domain or a time window, is shared by sets | Before any training | `DATA_GROUP_SHARED` |
|
|
573
|
+
| No declared `vocab` word is shared by sets | Before any training | `DATA_VOCAB_SHARED` |
|
|
574
|
+
| Each train, dev and test file's hash matches the one in `data.lock.json` | Every run | `DATA_HASH_CHANGED` |
|
|
575
|
+
| No command other than `promote` reads the test set | Every run | `DATA_TEST_READ` |
|
|
576
|
+
| No report, log or comparison includes a test example or a test failure | Promotion | `DATA_TEST_PRINTED` |
|
|
577
|
+
|
|
578
|
+
Errors name the files and the count of offending examples. They MUST NOT print the examples.
|
|
579
|
+
|
|
580
|
+
The overlap, group and vocabulary checks compare fingerprints, so they count distinct shared values and name the files of both sets that hold them (every test file, since the digest does not say which). The test set's rows are checked through the digest, which counts the rows that do not decode (`DATA_ROW_INVALID`) and returns no labels: its labels are checked when `promote` reads it.
|
|
581
|
+
|
|
582
|
+
The test set is kept out of the loop at one of three levels:
|
|
583
|
+
|
|
584
|
+
| Level | Name | How |
|
|
585
|
+
| ----- | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
|
|
586
|
+
| 1 | Convention and lint | Code that names `data/test` fails the check, except the `sealed('data/test/...')` call in the eval file |
|
|
587
|
+
| 2 | Counted reads | Every test read is logged, and the count appears in the model card |
|
|
588
|
+
| 3 | Out of reach | The test set is encrypted in the repository with a key only CI holds, or lives outside the working tree, and `promote` runs only in CI |
|
|
589
|
+
|
|
590
|
+
Levels 1 and 2 are on by default. Level 3 is one command to turn on. It is the only real guarantee against an agent that can read every file.
|
|
591
|
+
|
|
592
|
+
### Reads and digests
|
|
593
|
+
|
|
594
|
+
The checks above need facts about the test set before any training, while only `promote` may read it. The harness separates two ways of touching the test files:
|
|
595
|
+
|
|
596
|
+
- A read decodes examples: inputs, gold, `expect` or groups leave the guard as data a command can use. Only `promote` reads, and every read is counted.
|
|
597
|
+
- A digest opens the files inside the guard and returns only SHA-256 file hashes, row counts, the number of rows that do not parse, and fingerprints, and for `promote --scan` the number of test inputs found in the files it scans. Any command may ask for one. No text, label or score leaves it, and it calls no function the package supplies: a test row passed to user code (a metric, a decode, a baseline, any hook) would be a read.
|
|
598
|
+
|
|
599
|
+
A fingerprint is the first 16 hex characters of the SHA-256 of a string after lowercasing, collapsing runs of whitespace to one space and trimming. The digest fingerprints each example's input text, its `group` and each word in its `vocab`, all declared row fields, so the overlap, group and vocabulary checks compare fingerprints, never text. `data.lock.json` keeps them, so a command can check the test set against the other sets without opening it again.
|
|
600
|
+
|
|
601
|
+
How the harness enforces it:
|
|
602
|
+
|
|
603
|
+
- One module opens data files (`src/harness/io.ts`). It refuses any path inside `data/test/`, after resolving `..` and symbolic links, with `DATA_TEST_READ`. Only the guard (`src/harness/sealed.ts`) holds the handle that opens test files.
|
|
604
|
+
- Level 1: `doctor` and every `loop` scan the package's code files (`.ts`, `.mts`, `.cts`, `.tsx`, `.js`, `.mjs`, `.cjs`, `.jsx`, `.vue`, `.svelte`, outside `node_modules`, `dist`, `.git` and `.gpu-engine`) for `data/test`, with either slash, and for the segments `'data', 'test'` passed side by side. The only allowed occurrence is the `sealed('data/test/...')` call in a `*.eval.ts` file. Anything else is `DATA_TEST_READ` with the file and line.
|
|
605
|
+
- Level 2: every call to the guard appends one row to `reads.jsonl`: `{ at, kind, command, commit, files, examples, outcome }`. `kind` is `digest` or `examples`; `examples` is the number of rows the call touched; `outcome` is `ok` or `failed`. Only `examples` rows are reads. A read is refused, and not logged, unless the command is `promote` without `--verify`.
|
|
606
|
+
|
|
607
|
+
Limit: a fingerprint is a membership oracle. Someone who guesses a test input, group or vocabulary word can hash the guess and look it up in `data.lock.json`. Fingerprints never reveal an example nobody guessed, but they do confirm a guess. Level 3 does not remove this; it is the price of checking overlap without a read.
|
|
608
|
+
|
|
609
|
+
### Level 3
|
|
610
|
+
|
|
611
|
+
`gpu-engine promote --seal [--key-out <path>]` turns level 3 on. It runs once per package and trains nothing.
|
|
612
|
+
|
|
613
|
+
1. It refuses with `SEAL_GENERATOR_FOUND`, and writes nothing, while `defineDataset` declares `generate.test`: with that generator and `seed`, anyone can rebuild the sealed rows without the key. Remove the test generator from the eval file first, or move it to a script outside the package; the test set it wrote stays. It refuses with `SEAL_REFUSED`, and writes nothing, when `gate.json` is already at level 3, when a sealed file or `.github/workflows/promote.yml` already exists, or when the key path is inside the package or its git working tree or names a file that exists. The key path is `--key-out`, resolved against the package folder, and by default `~/.gpu-engine/keys/<model name>.key`.
|
|
614
|
+
2. The data step, as in `loop`. Any diagnostic is printed and it exits 1. After it, `data.lock.json` holds the test set's hashes and fingerprints.
|
|
615
|
+
3. It draws a 256-bit key and writes it to the key path as 64 lowercase hex characters and a newline, with mode 0600. The key is never printed.
|
|
616
|
+
4. The guard encrypts each test file with AES-256-GCM to the same path with `.enc` appended, such as `data/test/main.jsonl.enc`. A sealed file is the 8 ASCII bytes `GPUESEAL`, a 12-byte random nonce, the ciphertext and the 16-byte tag. The additional authenticated data is the plaintext file's path relative to the package, so a sealed file renamed to another path does not decrypt. A test file whose SHA-256 is not the lock's is `DATA_HASH_CHANGED`, and nothing is sealed. The guard logs one `digest` row in `reads.jsonl`.
|
|
617
|
+
5. The lock's test entry names the sealed files: each with the SHA-256 of its bytes, the row count, and `plaintext`, the SHA-256 of the file it replaces. The fingerprints are kept, so the overlap, group and vocabulary checks still run.
|
|
618
|
+
6. `gate.json` gets `"level": 3`, with `promoted` kept, and it writes `.github/workflows/promote.yml`.
|
|
619
|
+
7. It deletes the plaintext test files, prints the sealed files, the key path and how to store the key as a CI secret, and exits 0.
|
|
620
|
+
8. When the package is in a git repository whose history holds a plaintext file in the test folder under any name it ever had there, renamed and deleted files included, and those on a merged branch whose ref is gone (`git log --all --full-history -- <test folder>` lists a commit, with the sealed `.enc` files left out), it prints `SEAL_HISTORY_PLAINTEXT` with the number of those paths and commits. It is a warning: the seal stands and the exit code stays 0. Anyone with a clone can read those rows from history, so purge them from every branch and clone or replace the test set with rows never committed in plaintext (`docs/sealed-test-set.md`).
|
|
621
|
+
|
|
622
|
+
```json
|
|
623
|
+
"test": {
|
|
624
|
+
"files": { "data/test/main.jsonl.enc": { "sha256": "<64 hex, of the sealed bytes>", "examples": 16, "plaintext": "<64 hex>" } },
|
|
625
|
+
"fingerprints": { "inputs": ["<16 hex>"], "groups": ["<16 hex>"], "vocabulary": ["<16 hex>"] }
|
|
626
|
+
}
|
|
627
|
+
```
|
|
628
|
+
|
|
629
|
+
At level 3:
|
|
630
|
+
|
|
631
|
+
- The digest needs no key. It lists the sealed files (the test pattern with `.enc` appended) beside the plaintext ones and hashes their bytes without decrypting them. Their row counts come from the lock, and so do the fingerprints when every test file matches it. A plaintext test file is not in the lock, so it is `DATA_HASH_CHANGED` in every command. A lock without a test entry while sealed files exist is `SEAL_LOCK_INVALID`, and the data step records no entry: a sealed set's fingerprints cannot be computed without the key.
|
|
632
|
+
- `promote` runs only in CI with the key. When `gate.json` is at level 3 or a sealed file exists, it checks, before anything else, that the environment variable `CI` is `true` (`PROMOTE_OUTSIDE_CI`), that `GPU_ENGINE_TEST_KEY` is set and not empty (`SEAL_KEY_MISSING`), and that it is 64 hex characters (`SEAL_KEY_INVALID`). The counted read decrypts each sealed file in memory and never writes the plaintext. A key that does not authenticate a file is `SEAL_KEY_INVALID` with the file's name, and the read is logged with outcome `failed`. The report records the lock entries of the sealed files and level 3, and so does the `gate.json` a pass writes, even when it was missing or below level 3 before: a promotion read from sealed files is a level 3 promotion.
|
|
633
|
+
- `promote --verify` and `doctor` need no key. A report written before the seal keeps its level and the plaintext hashes. Over such a report they accept `gate.json` at level 3, and they compare each test file the report names with the `plaintext` hash of its sealed file, so `data/test/main.jsonl` against the entry of `data/test/main.jsonl.enc`. A report written at level 3 names the sealed files and compares directly.
|
|
634
|
+
- `doctor` runs the level 3 checks when `gate.json` is at level 3. They read and decrypt nothing: no plaintext file matches the test pattern (`SEAL_PLAINTEXT_FOUND`); the lock's test entry names exactly the sealed files, each with a `plaintext` hash (`SEAL_LOCK_INVALID`); `.github/workflows/promote.yml` exists and names `GPU_ENGINE_TEST_KEY`, `gpu-engine promote` and `gpu-engine promote --scan` (`SEAL_WORKFLOW_MISSING`); and `defineDataset` declares no `generate.test` (`SEAL_GENERATOR_FOUND`).
|
|
635
|
+
|
|
636
|
+
The promote workflow. CI has no candidate, since `.gpu-engine/` is not committed, so the workflow trains one. On manual dispatch it checks out the branch, installs the package, runs `gpu-engine loop --log "promote workflow"` and then `gpu-engine promote` with `GPU_ENGINE_TEST_KEY` from the repository secret of that name, then `gpu-engine promote --scan` with the key (section 6, Promote), and commits whichever of `weights/`, `src/weights.ts`, `gate.json`, `report.json`, `MODEL_CARD.md`, `RESULTS.md`, `reads.jsonl` and `tries.jsonl` changed back to the branch. It commits after a failed `promote` too, and after a scan that repaired or reset the files (exit 3), since those files are then safe to commit, so a read that failed its gate is still counted; the job then fails with the scan's exit code. After any other nonzero scan code it commits nothing and fails with that code. The promoted weights are the ones CI trained from the committed code. Every shell step runs under `set -euo pipefail`. A package inside a larger repository moves the file to the repository's `.github/workflows/` and sets the working directory.
|
|
637
|
+
|
|
638
|
+
Level 3 assumes the eval file and the code it imports were reviewed before the workflow runs: that code runs in the CI job with the decrypted rows in memory. The mute and the scan of the committed files catch the ways it could print or commit a test input by accident, not every way a hostile change could send one elsewhere. The key is the guarantee; `CI=true` is a convention anyone can set. Anyone who can read the key file can decrypt the test set, so the key goes into the CI secret store (`gh secret set GPU_ENGINE_TEST_KEY < <key path>`) and the file is deleted from any machine an agent works on. A lost key loses the test set: keep a copy where no agent can read it. `docs/sealed-test-set.md` is the walkthrough.
|
|
639
|
+
|
|
640
|
+
The rules these checks enforce are the invariants in section 8.
|
|
641
|
+
|
|
642
|
+
## 8. The sealed test set (invariants)
|
|
643
|
+
|
|
644
|
+
- Only `promote` MAY read test data. A read is decoding examples (section 7, Reads and digests).
|
|
645
|
+
- No function the package supplies MAY be called with a test row outside `promote`. Generators that write the test set produce rows and read none.
|
|
646
|
+
- Any command MAY take a digest of the test set: hashes, counts and fingerprints only, never text.
|
|
647
|
+
- The loop and the tries log MUST record dev scores only.
|
|
648
|
+
- Test cases and test failures MUST NOT be printed or written to any file.
|
|
649
|
+
- Every read of the test set MUST be counted, and the count MUST be reported.
|
|
650
|
+
- Reports and comparison tools MUST NOT sample test cases.
|
|
651
|
+
- Data files MUST be hashed, and the gate MUST fail when a hash changes.
|
|
652
|
+
- At level 3 the test set MUST NOT exist in plaintext in the working tree, decrypted rows MUST stay in memory, and the key MUST NOT be printed or written inside the working tree.
|
|
653
|
+
- At level 3 the eval file MUST NOT declare a test generator: a generator and its seed rebuild the sealed rows without the key.
|
|
654
|
+
|
|
655
|
+
What level 2 covers and what it does not. `promote` mutes the package's output from the counted read until it returns, output deferred to a microtask, `process.nextTick` or a zero-delay timer included, and the `gpu-engine` process stays muted until it exits (section 6, Promote). Outside level 2, when `promote` runs through the API (`runPromote`) in a process that keeps running: output the package's code schedules with a longer delay, and references it saved when the process loaded it before `promote` did. Outside level 2 everywhere: writes through a file, a socket or a file descriptor the package's code opens itself (the files the promote workflow commits are scanned for test inputs, section 6, Promote, step 8), and stream methods called on `process.stdout` or `process.stderr` from their prototypes rather than the instance. Level 3 is the guarantee against both: the rows are decrypted only in memory, in the CI job, which runs the committed code and nothing else. Level 3 assumes that code was reviewed (section 7, Level 3).
|
|
656
|
+
|
|
657
|
+
Why: an agent that iterates against a check will fit it, so a test set it can see stops measuring anything. One leaked list of test failures is enough to tune against, so every path to the test set is closed, not most of them.
|
|
658
|
+
|
|
659
|
+
## 9. Runtime
|
|
660
|
+
|
|
661
|
+
```ts
|
|
662
|
+
const model = await loadModel(weights, { backend: 'auto' }) // 'auto' | 'webgpu' | 'cpu'
|
|
663
|
+
const [error, out] = await model.run(input)
|
|
664
|
+
model.inspect() // { backend, reason, bytes, macs, inputMax?, head? }
|
|
665
|
+
await model.destroy() // frees the GPU buffers and device
|
|
666
|
+
```
|
|
667
|
+
|
|
668
|
+
- Results are `[error, data]`. `run` never throws.
|
|
669
|
+
- `availability({ definition })` reports which backend `auto` would run a model of that definition on, before anything loads, in the spirit of the [Chrome Decisions API explainer](https://github.com/explainers-by-googlers/decisions-api).
|
|
670
|
+
- `inspect()` names the backend that ran and why, the weight bytes, the multiply-adds and the token limit.
|
|
671
|
+
- Browser first: WebGPU is the main path.
|
|
672
|
+
- `auto` MAY pick the CPU for inputs too small to pay for a GPU round trip. The threshold is measured, not assumed.
|
|
673
|
+
- The same weights file MUST run on every backend.
|
|
674
|
+
- The CPU forward pass MUST be the trainer's forward pass, the same code.
|
|
675
|
+
|
|
676
|
+
### Loading and running
|
|
677
|
+
|
|
678
|
+
- `loadModel(weights, { backend, definition?, gpu?, table? })` never rejects. `weights` is a `Uint8Array` or an `ArrayBuffer`; anything else is `WEIGHTS_FORMAT_INVALID`. The file carries its definition, so nothing else is needed to run it. A file the reader rejects returns `WEIGHTS_FORMAT_INVALID`, `WEIGHTS_VERSION_UNSUPPORTED` or `WEIGHTS_DEFINITION_MISMATCH`.
|
|
679
|
+
- `definition` types the result: a tag head's labels type the tags, a pooled class head's labels type the class. Its hash MUST equal the hash in the file, else `WEIGHTS_DEFINITION_MISMATCH`. Budgets are not part of the hash.
|
|
680
|
+
- `gpu` is a WebGPU entry point: `navigator.gpu`, or `create([])` from the `webgpu` package in Node. The public types declare it as `GpuEntryPoint`, a structural interface with only `requestAdapter`, so the declarations of `gpu-engine` name no WebGPU or DOM type, and a project compiled with `lib: ["es2023"]`, no `@webgpu/types` and `skipLibCheck: false` typechecks against them.
|
|
681
|
+
- Every error `run` returns, and every load error, has a run code: `WEIGHTS_FORMAT_INVALID`, `WEIGHTS_VERSION_UNSUPPORTED`, `WEIGHTS_DEFINITION_MISMATCH` or a `RUN_*` code. `RunError['code']` is that union, `RunCode`. A weights file whose own definition fails a definition check (`DEFINE_*`) does not load and returns `WEIGHTS_FORMAT_INVALID`; any other code thrown inside a run becomes `RUN_FAILED`, its message starting with the original code.
|
|
682
|
+
- There is no default backend. A missing or unknown `backend` is `RUN_BACKEND_UNAVAILABLE`.
|
|
683
|
+
- A model that failed to load still resolves. Every `run` returns the load error, and `inspect()` names it in `reason`.
|
|
684
|
+
- `run(input)` returns `[error, undefined]` or `[undefined, data]` and never throws. An input that is not a string or a `{ text, flags }` object, an undeclared flag, or a flag list without one boolean per token is `RUN_INPUT_INVALID`. Empty text runs and gives an empty result. Text longer than `input.max` tokens runs on its first `max` tokens; the tokens after them get no output. When a logit (a retrieve head: a score) is not finite, the head would decode it to a label chosen by accident or to `Infinity`, so `run` returns `RUN_OUTPUT_NONFINITE` instead of decoding. Any other failure inside the backend is `RUN_FAILED`.
|
|
685
|
+
- `inspect()` returns `{ backend, reason, bytes, macs, inputMax?, head? }`: the backend that runs, the rule that chose it, the byte length of the weights file, the multiply-adds per token from the plan (`macsPerToken`), the loaded definition's token limit (`input.max`) and its head kind (`tag`, `pooled` or `retrieve`). `inputMax` and `head` are absent if loading failed.
|
|
686
|
+
- A `retrieve` model needs `table`: a non-empty array of `{ id, text }` rows, each `id` a non-empty string no other row uses and each `text` a string. Without it, or with a row that breaks this, the model does not load and every `run` returns `RUN_TABLE_MISSING`, naming the row. At load the CPU encodes every row once with the one forward pass, so the row vectors are bitwise those the harness scored on dev, and the WebGPU backend uploads them after the weights. `run(input)` returns the ranking: one `{ id, score }` per table row, the highest score first, table order on a tie. The table types `id`: a table written inline or `as const` gives the union of its ids, any other table `string`. `runLogits` returns the scores in table order. Other heads ignore `table`.
|
|
687
|
+
- `availability({ definition, gpu? })` returns the `{ backend, reason }` that `auto` would choose for a model of that definition, without loading weights or opening a device (Backend rules).
|
|
688
|
+
- Runs on one model MAY overlap. Each returns the result it returns when the runs go one at a time; on WebGPU they share the model's buffers, so they run one at a time, in call order. Each run makes its own `auto` choice, and `inspect()` reports the choice of the latest run started.
|
|
689
|
+
- `destroy()` frees the model's WebGPU buffers and destroys its device once the runs already called have finished, and resolves then. It never rejects, and calling it again does nothing more. Every `run` called after it returns `RUN_MODEL_DESTROYED`. On the CPU it frees nothing and only ends the model's runs.
|
|
690
|
+
|
|
691
|
+
### Backend rules
|
|
692
|
+
|
|
693
|
+
A WebGPU entry point is the `gpu` option, else `navigator.gpu`. In Node, `gpu` is the `webgpu` package's `create([])`, which the caller keeps referenced while the model lives. Nothing in the runtime touches a WebGPU global at import time.
|
|
694
|
+
|
|
695
|
+
| Request | Backend | Reason names |
|
|
696
|
+
| -------- | ---------------------------------------------------------------------- | ----------------------------------------------------- |
|
|
697
|
+
| `cpu` | CPU | the request |
|
|
698
|
+
| `webgpu` | WebGPU; `RUN_BACKEND_UNAVAILABLE` without an entry point or an adapter | the request and the adapter, or why it is unavailable |
|
|
699
|
+
| `auto` | CPU or WebGPU by the first rule that applies, in the order below | the rule and its numbers |
|
|
700
|
+
|
|
701
|
+
`auto` rules, in order:
|
|
702
|
+
|
|
703
|
+
1. No WebGPU entry point: CPU.
|
|
704
|
+
2. `macsPerToken * input.max < AUTO_WEBGPU_MIN_MACS`: CPU, without opening a device, since no run of this model can reach the threshold.
|
|
705
|
+
3. The entry point finds no adapter (`no WebGPU adapter`), or the device or a pipeline fails to start (`WebGPU failed to start`): CPU.
|
|
706
|
+
4. Otherwise the model opens WebGPU and picks per run: the CPU when `macsPerToken * tokens < AUTO_WEBGPU_MIN_MACS`, WebGPU from there. `inspect()` reports the latest run's choice and its numbers.
|
|
707
|
+
|
|
708
|
+
`AUTO_WEBGPU_MIN_MACS` lives in `src/runtime/auto.ts` and is 51314688, measured by `scripts/bench-threshold.ts` and recorded in `docs/measurements/auto-threshold.json` (adapter, CPU, date, Node version, load average before, after each sweep and at the end, the table and the chosen value), which a test keeps equal to the constant. The script runs one fixed sweep (tag models of widths 8 to 256, inputs of 1 to 256 tokens) on both backends through `loadModel`, with Dawn (the `webgpu` package) as the entry point, and takes the median of warm runs per cell. It runs the whole sweep five times in a row, and each cell takes the median of its five sweep medians, so one burst of load from other jobs does not move a cell. The threshold is the smallest multiply-add count from which WebGPU beats the CPU in every measured cell; if the CPU won at the largest count, the threshold would be the largest count measured. It was measured on a software adapter (llvmpipe) on a shared 4-core VM under load from other jobs (load average 2.5 to 4.2 during the run), so it is noisy: the recorded run chose the largest count measured. WebGPU was faster in 6 cells below it, from 258048 multiply-adds up, but the CPU won the cell of width 128 at 256 tokens (13074432 multiply-adds, 23.9 ms against 26.9 ms), and the rule waits until every larger cell agrees. Earlier single-sweep runs of the same sweep chose 51314688, 12828672 and 13074432. On this machine `auto` therefore runs almost every input on the CPU. Real GPU: not run. Real browser: not run. The number is a placeholder for real devices. `availability({ definition, gpu? })` applies rules 1, 2 and the adapter half of rule 3 to the definition's plan, so for every model trained here it answers the CPU, as `auto` runs it. When none applies it answers WebGPU, and its reason says that `auto` picks per run and names the token count from which a run reaches the threshold. When there is an entry point, a missing definition or one that cannot be planned answers the CPU with its code in the reason; it never throws.
|
|
709
|
+
|
|
710
|
+
### WebGPU pipeline
|
|
711
|
+
|
|
712
|
+
- The CPU featurizes the input (the one featurizer) and uploads the feature rows. Every op of the plan runs its WGSL passes (`wgsl(op, io)`, section 5) in one command encoder, op `k` reading op `k - 1`'s output from one of two ping-pong scratch buffers sized `input.max * maxWidth`. One readback returns the logits; the head decodes them on the CPU, as on the CPU backend.
|
|
713
|
+
- The pipeline asks the op registries for each planned op's template and names no op itself, so a layer or head that ships a `wgsl` template runs on WebGPU without changes to the runtime.
|
|
714
|
+
- Weights upload once at load, as the same dequantized float32 array the CPU uses. Pipelines compile at load.
|
|
715
|
+
- A device or pipeline that fails at load, a validation error during a run, and a lost device are `RUN_GPU_FAILED`. After a device is lost every run on WebGPU returns `RUN_GPU_FAILED` (an `auto` run below the threshold still runs on the CPU); nothing throws.
|
|
716
|
+
- A run that fails frees its readback buffer, whether validation, mapping or the copy failed, so failed runs leak no GPU memory. The adapter is named by `adapter.info` (vendor, architecture, description), and `unnamed adapter` when the adapter has no `info`, as in browsers that leave it out.
|
|
717
|
+
- WebGPU logits MUST match the CPU logits within the model's parity tolerance and decode the same. The test suite checks a whole tag model on 50 inputs within 1e-3, a whole pooled model of each form (class labels, and values compared number by number) on 20 inputs within 1e-3, 24 concurrent runs against the same runs one at a time, and a whole retrieve model's scores against 100 rows on 30 inputs within 1e-3 with the same top score, on a software adapter (llvmpipe); real GPU: not run, real browser: not run.
|
|
718
|
+
- A `retrieve` model's pipeline appends the score step after the tower, with the row vectors after the weights in binding 0, and reads back one score per row.
|
|
719
|
+
|
|
720
|
+
## 10. Parity
|
|
721
|
+
|
|
722
|
+
Trainer equals CPU equals WGSL, within a stated tolerance, on fixtures.
|
|
723
|
+
|
|
724
|
+
| Pair | Tolerance | Where it runs |
|
|
725
|
+
| ------------------------------ | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
|
|
726
|
+
| Trainer and CPU | Identical: they share the forward pass | CI |
|
|
727
|
+
| CPU and WGSL, software adapter | Same decoded result on every fixture, logits within a tolerance stated per model | CI, on Dawn (the `webgpu` package) over lavapipe |
|
|
728
|
+
| CPU and WGSL, real GPU | Same as above | Locally, reported in the model card |
|
|
729
|
+
| CPU and WGSL, real browser | Same as above | Not run by `gpu-engine parity`, which runs in Node; `examples/browser-demo` runs it by hand (section 12) |
|
|
730
|
+
|
|
731
|
+
For a `retrieve` model the compared logits are its scores against the table, so the parity fixtures need the package's table, and the trainer side is the forward pass followed by the score step.
|
|
732
|
+
|
|
733
|
+
`gpu-engine parity` runs in the model package. It loads the promoted weights, `weights/<name>.bin`, which MUST have the SHA-256 that `report.json` records (`VERIFY_WEIGHTS_CHANGED`; no `report.json` is `VERIFY_REPORT_INVALID`). Its fixtures are every dev input, in file and line order, and four built-in edge inputs: empty text, one token, exactly `input.max` tokens and `input.max + 3` tokens. It never reads the test set: the dev files go through the one module that opens data files, and it takes no digest.
|
|
734
|
+
|
|
735
|
+
1. Trainer and CPU: the forward pass (section 5) on the weights the harness decodes, against `loadModel(weights, { backend: 'cpu' })`. The logits MUST be bitwise identical.
|
|
736
|
+
2. CPU and WGSL: `loadModel(weights, { backend: 'webgpu', gpu })`, where `gpu` comes from the `webgpu` package, resolved from the model package folder (a devDependency there) and imported only when parity runs. When it does not resolve, does not load or finds no adapter, parity fails with `PARITY_ADAPTER_MISSING`, whose fix names the install with npm (`npm install --save-dev webgpu@^0.6.2`), the package manager a scaffolded package uses. Parity names its adapter by vendor, architecture and description, and an adapter without `info`, which some browsers leave out, is `unnamed adapter`. It destroys both models it loads, on a pass and on a failure, so no GPU device outlives the command. On every fixture both backends MUST decode to the same result (`PARITY_DECODE_DIFFERS`), and the largest absolute logit difference over all fixtures MUST be within `eval.parity.tolerance` (`PARITY_TOLERANCE_EXCEEDED`). The decoded result is `eval.decode(output, input)`, or the head output when the eval has no decode. It is compared value by value, and the numbers in it (a values head, retrieve scores) within the tolerance.
|
|
737
|
+
3. A non-finite logit on either backend, and any trainer and CPU difference, also fail with `PARITY_TOLERANCE_EXCEEDED`.
|
|
738
|
+
|
|
739
|
+
The adapter is a software adapter when its name matches a software rasterizer (llvmpipe, lavapipe, SwiftShader, softpipe, WARP, or the word `software`); `MODEL_CARD.md` and parity share that one classification (`softwareAdapter` in `src/harness/report.ts`). On a software adapter parity prints `real GPU: not run` and names the software adapter. On any other adapter the CPU and WGSL result is a real GPU result: parity prints it as the real GPU line and records it in `realGpu` as `<adapter>: largest logit difference <d> (tolerance <t>), decoded results differ on <k> of <n> fixtures`.
|
|
740
|
+
|
|
741
|
+
On a pass it writes `parity.json` (date, weights SHA-256, adapter name, tolerance, fixture count, `trainerCpu: "identical"`, the largest difference, the number of decode differences, `realGpu` (`"not run"` on a software adapter, else the result above)) and regenerates `MODEL_CARD.md` from `report.json` and that file. Parity runs in Node, never in a browser, so nothing it writes records a browser run: the model card always states `Real browser: not run`. A `parity.json` written before this rule has a `realBrowser` field; it still reads, the field is ignored, and when only the date or that field would change the file keeps its bytes, so a second run changes no committed file. On a failure it prints every diagnostic, writes nothing and exits 1. The CI `gpu` job builds the package and runs `gpu-engine parity` in every `examples/*` folder that has a `report.json`; with none, the step passes.
|
|
742
|
+
|
|
743
|
+
Each layer and head is also checked on its own: its WGSL output equals its CPU forward pass within 1e-5 on random inputs for 1, 2 and the maximum number of tokens (`pnpm test:gpu`), and the `retrieve` score step equals its CPU scores within 1e-5. That run fails, rather than skips, when no adapter is found.
|
|
744
|
+
|
|
745
|
+
## 11. API
|
|
746
|
+
|
|
747
|
+
This is the API as built. The reference for each part is in `docs/`: `docs/runtime.md` (`loadModel`, `run`, `inspect`, `destroy`, `availability`), `docs/harness.md` (the model package and every command), `docs/cli.md` (every command and flag), `docs/layers.md` (the catalog), `docs/data.md` (bringing your own rows), `docs/apps.md` (using a built model package in an app), `docs/weights-format.md` and `docs/diagnostics.md`. `llms.txt` indexes them.
|
|
748
|
+
|
|
749
|
+
The package has two entry points:
|
|
750
|
+
|
|
751
|
+
| Entry | Where it runs | What it holds |
|
|
752
|
+
| -------------------- | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
753
|
+
| `gpu-engine` | Browser or Node | `defineModel`, `defineEval`, `defineDataset`, the builders, `tokenize`, `loadModel`, `availability`, `GpuEngineError`, and the types a model file, an eval file and an app use (below) |
|
|
754
|
+
| `gpu-engine/harness` | Node only | The commands (`runNew`, `runLoop`, `runPromote`, `runParity`, `runInspect`, `runDoctor`, `runBuild`), `loadProject`, `train`, `plan`, `forward`, the weights format (`encode`, `decode`, `dequantize`, `toWeightsFile`), the diagnostic registry, the `MODEL_CARD.md` and `RESULTS.md` renderers, and the harness types |
|
|
755
|
+
|
|
756
|
+
`gpu-engine` exports a fixed list of types, written out in `src/index.ts`: the definition (`ModelDefinition`, `TokensInput`, `FeatureRow`, `ShapeRow`, `HashRow`, `FlagRow`, `Layer`, `LayerKind`, `EmbedLayer`, `ConvLayer`, `BiScanLayer`, `DenseLayer`, `Activation`, `Head`, `HeadKind`, `TagHead`, `PooledClassHead`, `PooledValuesHead`, `RetrieveHead`, `Int6Quantization`, `Budgets`), the eval (`EvalDefinition`, `EvalInput`, `EvalSets`, `SealedSet`, `SetKind`, `DatasetDefinition`, `DatasetGenerator`, `Example`, `Gold`, `Random`, `TrainOptions`, `EvalGate`, `ParityOptions`, `ShipOptions`) and the runtime (`ModelInput`, `ModelOutput`, `HeadOutput`, `RetrieveMatch`, `TableRow`, `Token`, `LoadOptions`, `AvailabilityOptions`, `GpuEntryPoint`, `Model`, `RunResult`, `RunError`, `RunCode`, `Diagnostic`, `DiagnosticCode`, `Inspection`, `Availability`, `Backend`, `BackendRequest`). The types of the plan, the weights file, training and the harness files (`ModelPlan`, `CanonicalDefinition`, `WeightsFile`, `TrainResult`, `Project`, `CommandContext`, `TriesRow`, `ReadsRow`, `Report`, `ParityFile` and the rest) come from `gpu-engine/harness` only.
|
|
757
|
+
|
|
758
|
+
Nothing reachable from `gpu-engine` (`src/index.ts`) imports a `node:` module or another package: every runtime import uses a literal relative path inside `src/`, and `test/dependencies.test.ts` walks the graph to check it. That code is bundled into every shipped model and counts toward its `ship.brotliBytes`. The harness, the trainer and the CLI run only in Node, on the machine that trains, and MAY import the packages listed in `dependencies`. The package needs Node 24 or later (`engines.node`), and a Node built-in, such as `fs.glob`, comes before a package. The `gpu-engine` executable is the CLI below.
|
|
759
|
+
|
|
760
|
+
```ts
|
|
761
|
+
// my-model.model.ts
|
|
762
|
+
import { defineModel, features as f, heads as h, int6, layers as l } from 'gpu-engine'
|
|
763
|
+
|
|
764
|
+
export default defineModel({
|
|
765
|
+
name: 'my-model',
|
|
766
|
+
input: f.tokens({ max: 64, rows: [f.shape(), f.hash({ buckets: 128, k: 2 })] }),
|
|
767
|
+
net: [l.embed({ size: 20 }), l.conv({ taps: 3 }), l.biScan({ size: 20 }), l.dense({ size: 20, activation: 'relu' })],
|
|
768
|
+
head: h.tag({ labels: ['start', 'inside', 'none'] }),
|
|
769
|
+
quant: int6({ qatFrom: 0.7 }),
|
|
770
|
+
budgets: { brotliBytes: 5_000, macsPerToken: 3_200 },
|
|
771
|
+
})
|
|
772
|
+
|
|
773
|
+
// my-model.eval.ts
|
|
774
|
+
import { defineDataset, defineEval, sealed } from 'gpu-engine'
|
|
775
|
+
import model from './my-model.model.ts'
|
|
776
|
+
|
|
777
|
+
export default defineEval(model, {
|
|
778
|
+
sets: { train: 'data/train/*.jsonl', dev: 'data/dev/*.jsonl', test: sealed('data/test/*.jsonl') },
|
|
779
|
+
data: defineDataset({
|
|
780
|
+
seed: 1,
|
|
781
|
+
minSize: { train: 2_000, dev: 300, test: 300 },
|
|
782
|
+
generate: { train, dev, test }, // optional: seeded generators, each (random) => examples
|
|
783
|
+
}),
|
|
784
|
+
train: { seeds: [1, 2, 3], epochs: 20, batch: 32, learningRate: 0.01, warmup: 0.1, budgetSeconds: 40 }, // retrieve: also negatives
|
|
785
|
+
decode: (raw, input) => toResult(raw, input), // optional: head output to your typed result
|
|
786
|
+
metric: (pred, gold) => exactMatch(pred, gold),
|
|
787
|
+
baselines: { rules },
|
|
788
|
+
gate: { floors: 'promoted', noise: 0.05 },
|
|
789
|
+
parity: { tolerance: 1e-3 },
|
|
790
|
+
ship: { brotliBytes: 8_000, files: ['dist/index.mjs', 'dist/index.d.mts'] }, // optional
|
|
791
|
+
table: 'data/table.jsonl', // retrieve heads only
|
|
792
|
+
})
|
|
793
|
+
|
|
794
|
+
// in an app, browser or Node
|
|
795
|
+
const model = await loadModel(weights, { backend: 'auto', definition }) // also: gpu, table
|
|
796
|
+
const [error, out] = await model.run(input)
|
|
797
|
+
model.inspect() // { backend, reason, bytes, macs, inputMax?, head? }
|
|
798
|
+
await model.destroy() // frees the GPU buffers and device; later runs return RUN_MODEL_DESTROYED
|
|
799
|
+
```
|
|
800
|
+
|
|
801
|
+
Nothing in `defineEval` is defaulted: training, the gate and parity are always written out.
|
|
802
|
+
|
|
803
|
+
- `defineEval(model, definition)` takes the model definition first, the model file's default export, and types the eval from it, so an eval file writes no type arguments. `decode` receives `ModelOutput<typeof model>`, the head output: the tag labels per token, one pooled label, the pooled values or a retrieve ranking. The input that `decode` and each baseline receive is `EvalInput<typeof model>`: `string` for a model without flag rows, else `string | { text, flags? }` with the declared flag names. The result type is what `decode` returns, and it types `metric`, each baseline and the generators; without `decode` it is the head output, `ModelOutput<typeof model>`, so a `metric` or baseline written for another type does not typecheck, and an eval already typed with the head output as its result, whose `decode` is optional, is accepted; TypeScript reads an inline `decode` before an inline `metric` only when it comes first, so `decode` is written before `metric`. It returns `definition` unchanged after its checks; a first argument that is not a model definition, or a missing second one (the form without the model), is `DEFINE_EVAL_MODEL`. `loadProject` runs the same checks again on the model file's default export.
|
|
804
|
+
- For a model without flag rows the harness hands `decode` and the baselines the row's text, so a row written as `{ "input": { "text": ... } }` reaches them as a string; for a model with flag rows they get the input as the row holds it.
|
|
805
|
+
|
|
806
|
+
`defineEval` checks every option at define time, so a bad value never reaches training or scoring as an uncoded error. Each check throws with a fix from `src/runtime-errors.ts`:
|
|
807
|
+
|
|
808
|
+
| Code | When |
|
|
809
|
+
| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
810
|
+
| `DEFINE_SET_FOLDER` | A set path or `table` is outside its folder (below) |
|
|
811
|
+
| `DEFINE_DATA_INVALID` | `data.seed` is not a safe integer, `data.minSize.train`, `.dev` or `.test` is not a positive integer, or a `data.generate` entry is not a function |
|
|
812
|
+
| `DEFINE_TRAIN_INVALID` | `train.seeds` is empty, holds a value that is not a safe integer or repeats a seed; `epochs` or `batch` is not a positive integer; `learningRate` or `budgetSeconds` is not a finite number above 0; `warmup` is not a finite number from 0 up to, not including, 1; `negatives` is present and not a positive integer |
|
|
813
|
+
| `DEFINE_GATE_INVALID` | `gate.floors` is not `'promoted'`, or `gate.noise` is not a finite number of at least 0 |
|
|
814
|
+
| `DEFINE_PARITY_INVALID` | `parity` is not an object, or `parity.tolerance` is not a finite number of at least 0 |
|
|
815
|
+
| `DEFINE_SHIP_INVALID` | `ship` is present and `ship.brotliBytes` is not a positive integer, or `ship.files` is not a non-empty list of non-empty paths |
|
|
816
|
+
| `DEFINE_EVAL_INVALID` | `metric` is not a function, `decode` is present and not a function, or `baselines` is not an object of functions |
|
|
817
|
+
|
|
818
|
+
A `retrieve` model's `train` also needs `negatives` (`DEFINE_TRAIN_INVALID`). `loadProject` runs `defineEval` again on the eval file's export, so an object written without it gets the same checks, and the trainer applies the train checks again for callers of `train`, with the same code.
|
|
819
|
+
|
|
820
|
+
- `sets` MUST point inside `data/train/`, `data/dev/` and `data/test/`; any other folder throws `DEFINE_SET_FOLDER` at define time. A set path is written in normal form: no `.` or `..` segment, no empty segment and no leading `./`, so `data/train/../test/*.jsonl` is `DEFINE_SET_FOLDER`. One file is one named set. `table` MUST be a relative path inside the package that points outside those three folders once normalised (POSIX `normalize`, so `./data/test/main.jsonl` and `data/dev/../test/main.jsonl` count as `data/test/`), also `DEFINE_SET_FOLDER`. Set patterns support only `*` and `?` as wildcards; all other filename characters are literal. Wildcards MAY appear in the file name only, a wildcard in the folder is `DEFINE_SET_FOLDER`, and a wildcard does not match a leading `.`. Listing a folder reads names only and opens no file, so it is allowed on the test folder. A folder that holds any file, a dotfile included, counts as written for the data step.
|
|
821
|
+
- A data row is one JSON object per line: `{ "input": text | { text, flags }, "gold": tags[] | label | number[] | rowId[], "expect"?: result, "group"?: string, "vocab"?: string[] }`. `rowId[]` is the ids of the table rows that answer a `retrieve` input. `flags` holds one boolean per token for each declared flag row. `group` and `vocab` feed the group and vocabulary checks (section 7).
|
|
822
|
+
- Scores sit in one table per set: the model is `metric(decode(model(input)), expect ?? decode(gold))`, each baseline is `metric(baseline(input), ...)`, and the oracle is `metric(decode(gold), ...)`, the ceiling the decode step allows.
|
|
823
|
+
- `loadModel(weights, options)` never rejects. `options.backend` is `'auto' | 'webgpu' | 'cpu'`. `definition` types the result and is checked against the hash in the file. `gpu` is a WebGPU entry point for hosts without `navigator.gpu`, such as Node with the `webgpu` package. `table` holds the `{ id, text }` rows a retrieve head scores against, and its ids type the ranking `run` returns.
|
|
824
|
+
- `train.negatives` is the number of other table rows a `retrieve` head trains against per example. Only a `retrieve` head reads it, and it needs it.
|
|
825
|
+
|
|
826
|
+
```sh
|
|
827
|
+
gpu-engine new my-model --head tag # package, AGENTS.md, SPEC.md, skill
|
|
828
|
+
gpu-engine loop --log "hidden 12" # data, train, dev benchmark, appends a try
|
|
829
|
+
gpu-engine loop --fail # lists the dev examples the candidate gets wrong
|
|
830
|
+
gpu-engine loop --mark dropped # records kept or dropped on the last try
|
|
831
|
+
gpu-engine promote # the only command that reads the test set
|
|
832
|
+
gpu-engine promote --verify # the CI gate: checks the promotion without reading test data
|
|
833
|
+
gpu-engine promote --seal # level 3: encrypts the test set (section 7)
|
|
834
|
+
gpu-engine promote --scan # scans the files the promote workflow commits for test inputs
|
|
835
|
+
gpu-engine parity # trainer = CPU = WGSL
|
|
836
|
+
gpu-engine inspect "some input text" # tokens, features, tags, decoded result, backend
|
|
837
|
+
gpu-engine build # dist/index.mjs (imports nothing) and dist/index.d.mts
|
|
838
|
+
gpu-engine doctor # diagnostic codes, each with a fix
|
|
839
|
+
```
|
|
840
|
+
|
|
841
|
+
`gpu-engine --version` (or `-v`) prints the package version and exits 0. An argument that starts with `--`, and `-h`, is a flag; every argument after a lone `--` is a positional, so `gpu-engine inspect -- "--help me"` inspects that text. A flag that takes a value takes the next argument or the text after `=`; a next argument that would itself be a flag (`--...` or `-h`) is `CLI_FLAG_INVALID`, so `loop --log --fail` never logs `--fail` as the idea, and `--log=--fail` does.
|
|
842
|
+
|
|
843
|
+
Every command takes `--dir <path>`; `docs/cli.md` lists every flag. A flag the command would ignore or cannot combine is `CLI_FLAG_INVALID`, and nothing runs: `promote --verify` with `--seal` or `--key-out`, `promote --scan` with `--verify`, `--seal` or `--key-out`, `--key-out` without `--seal`, `loop --set` without `--fail`, `loop --fail` with `--log` or `--status`, `loop --mark` with any flag but `--dir`, and a flag given twice.
|
|
844
|
+
|
|
845
|
+
API style rules:
|
|
846
|
+
|
|
847
|
+
- `defineX()` functions are plain functions. They know nothing about the host app.
|
|
848
|
+
- The public surface stays small.
|
|
849
|
+
- Results are `[error, data]` and never throw at run time. Definition errors throw at define time.
|
|
850
|
+
- Diagnostic codes are named `<PREFIX>_<WHAT_FAILED>`, for example `DATA_SPLIT_OVERLAP`. Each has a why and a fix. The codes the runtime reports (`DEFINE_*`, `WEIGHTS_*`, `RUN_*`, and the `DATA_ROW_INVALID` and `DATA_LABEL_UNKNOWN` that head code throws) are registered in `src/runtime-errors.ts`, so a shipped model carries the text of those codes only, and a run-time error still has its why and fix. `src/errors.ts` adds every other code and is the full registry that the harness, the CLI and the docs read. `docs/diagnostics.md` lists every code with its why and fix; `pnpm docs:diagnostics` writes it from the registry, and a test fails when the two differ.
|
|
851
|
+
- Types are inferred from the definition. The labels of a head type the result.
|
|
852
|
+
- Every part of a model definition is written with one builder, and every builder takes one options object whose keys are the fields of the part it returns, named as in the definition JSON. A part with no fields takes no argument. The builders are `features.tokens({ max, rows })`, `features.shape()`, `features.hash({ buckets, k })`, `features.flag({ name })`, `layers.embed({ size })`, `layers.conv({ taps })`, `layers.biScan({ size })`, `layers.dense({ size, activation })`, `heads.tag({ labels })`, `heads.pooled({ labels })` or `heads.pooled({ outputs })`, `heads.retrieve({ size })` and `int6({ qatFrom })`. A builder returns `{ kind, ...fields }` with the fields in that order, the plain object the definition JSON holds, copies no key it does not name, fills in no default and checks nothing: `defineModel` checks the whole definition (Definition-time checks). No builder takes a positional argument, so a call names every number it sets, a model file reads the same as its definition JSON, and a new field never shifts an argument. A part written as a plain object is the same definition; templates, examples, the skill and the docs use the builders. `budgets` is a plain object, and `sealed(path)` marks a set path in the eval file, not a part of the model.
|
|
853
|
+
- A `pooled` head is one kind in both forms. The op, its tensors, its plan and its WGSL are the same; `labels` or `outputs` changes only the loss, the gold and the decode. `heads.pooled` takes exactly one of them: both or neither is a type error, and in plain JavaScript `DEFINE_HEAD_LABELS` at define time.
|
|
854
|
+
- `inspect` shows what would happen before or after it happens.
|
|
855
|
+
|
|
856
|
+
## 12. Agent support
|
|
857
|
+
|
|
858
|
+
- `gpu-engine new` writes an `AGENTS.md` that points at the model's `SPEC.md`.
|
|
859
|
+
- The npm package ships a skill (`skills/gpu-engine/SKILL.md`) and its docs as Markdown.
|
|
860
|
+
- The package ships `llms.txt` at its root, an index of the docs for agents.
|
|
861
|
+
- `llms.txt` and the skill link every Markdown file directly in `docs/`. The README links the site for the docs and has no docs index.
|
|
862
|
+
- The README, the skill, `docs/cli.md` and the steps `new` prints give one quick start, written for npm: `npx gpu-engine@latest new <name> --head <kind>`, install, `doctor`, `loop`, `promote`, `npm run build`. The README starts with what the library is, then the requirements (Node 24 or later for the harness and CLI; the CPU runtime is the v0.1 runtime and WebGPU is experimental), the quick start, how an app imports the built package, and the status in a few lines that link to the examples' `RESULTS.md`. `package.json` `homepage` is `https://gpu-engine.dev`.
|
|
863
|
+
|
|
864
|
+
### Docs site
|
|
865
|
+
|
|
866
|
+
- The site lives in `docs/`, a private Nuxt app with its own `package.json` and lockfile, outside the pnpm workspace and the published package. The package ships the library docs, `docs/*.md` and `docs/measurements/`, and nothing else from `docs/`.
|
|
867
|
+
- It is published at `https://gpu-engine.dev` on every push to `main`. Canonical links, the sitemap, `llms.txt` and the raw Markdown pages use that origin.
|
|
868
|
+
- The site is linked to the hosted console of its tooling, which edits its pages through the CMS. People that the console signs in to the site get a tools pill on every page, with a link that opens the site in the console. Nobody else can sign in: the site has no sign-in method of its own, and a visitor without a session sees no console link.
|
|
869
|
+
- `docs/layers.md` and `docs/diagnostics.md` stay the library's references. The site writes its Layers and Diagnostics pages from them at build time, without the sentences written for the library repository: how `docs/diagnostics.md` is generated, and the repository test files a claim names.
|
|
870
|
+
- A page that describes behaviour that is not implemented says so and names its milestone from section 15.
|
|
871
|
+
- The playground runs promoted examples from `examples/` in the browser on the CPU, through `playground/render.ts`, and gets only the runtime entry, never the harness or the CLI. It MUST NOT train or run `promote`, and MUST NOT list, open, export or print anything under `data/test/`. Its copies of the examples hold only the files `example.json` names, never `train.ts` or anything under `data/`.
|
|
872
|
+
|
|
873
|
+
### New
|
|
874
|
+
|
|
875
|
+
`gpu-engine new <name> --head tag|pooled|retrieve [--dir <path>]` writes a model package into `<dir>/<name>`, `--dir` defaulting to the working directory. The files come from the package's `templates/` folder: the files every package shares, then the starter of the head kind. It writes:
|
|
876
|
+
|
|
877
|
+
| File | What it holds |
|
|
878
|
+
| --------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
879
|
+
| `<name>.model.ts` | `defineModel` with a small net for the head and its budgets |
|
|
880
|
+
| `<name>.eval.ts` | `defineEval` with a seeded generator per set, a rule baseline, the metric, the decode, the gate, parity and ship options |
|
|
881
|
+
| `src/decode.ts` | the decode from the head output to the result, shared by the eval and the shipped entry |
|
|
882
|
+
| `src/index.ts` | the shipped entry: `load({ backend, gpu? })` loads the promoted weights and returns `run(text)`, which gives `[error, result]` after the decode, `inspect()` and `destroy()` |
|
|
883
|
+
| `src/weights.ts` | an empty `weightsHex` until `promote` writes the promoted weights there as lowercase hex |
|
|
884
|
+
| `AGENTS.md` | the five rules below, pointing at `SPEC.md` and the skill |
|
|
885
|
+
| `SPEC.md` | the model's task, data, metric, baseline and how it ships |
|
|
886
|
+
| `skills/gpu-engine/SKILL.md` | a copy of the skill this package ships |
|
|
887
|
+
| `.github/workflows/ci.yml` | the gate: build, `doctor`, then `promote --verify` once `report.json` exists, under `set -euo pipefail` |
|
|
888
|
+
| `package.json`, `tsconfig.json`, `.gitignore` | `private`, no `dependencies`, `gpu-engine` at the version that wrote it and `typescript` as devDependencies, `exports` with `types`, the `build` script (`gpu-engine build`) and the `typecheck` script (`tsc -p .`); `.gitignore` holds `node_modules`, `dist` and `.gpu-engine` |
|
|
889
|
+
| `data/table.jsonl`, `src/table.ts` | `retrieve` only: the table rows, and the same rows as a module for the shipped entry, which `gpu-engine build` rewrites from the eval's `table` |
|
|
890
|
+
|
|
891
|
+
It writes no data and no data folder: the generators run on the first `loop`, which writes `data/train/`, `data/dev/` and `data/test/`. It then prints the steps that work from there: `cd` into the package, install gpu-engine, `npx gpu-engine doctor` and `npx gpu-engine loop --log "starter"`. The install step is `npm install`, which installs the `gpu-engine` devDependency from npm. Each starter's three sets use their own sentence frames or their own domain as `group` and their own words as `vocab`, so the generated data passes every section 7 check, and a fresh package passes `doctor` and `loop`. `webgpu` is not a devDependency; `parity` names it in its fix when it is missing.
|
|
892
|
+
|
|
893
|
+
Each starter leaves room to tune. Its first `loop` trains at least two seeds and, on every dev set, scores the model at least 0.2 above each rule baseline and at most 0.95, because part of its data needs a layer the starter leaves out: the `tag` and `pooled` starters need words farther away than `conv` reaches (`biScan` adds them), and the `retrieve` starter needs the words next to a dish name (`conv` adds them). Its `gate.noise` is at or above the seed spread of that first loop. The first `loop` takes a few seconds.
|
|
894
|
+
|
|
895
|
+
npm drops `.gitignore` from a packed folder, so the templates hold it as `gitignore`, and `.github`, `package.json` and `tsconfig.json` as `github`, `package.template.json` and `tsconfig.template.json`, so they do not act on gpu-engine's own tools; `new` renames them on write. The model name must match `^[a-z][a-z0-9-]{0,63}$`, since it names the package, the files and the weights, else `NEW_NAME_INVALID`. `new` never overwrites: a target folder that holds any file is `NEW_TARGET_EXISTS`.
|
|
896
|
+
|
|
897
|
+
Rules for agents, written into every scaffolded `AGENTS.md` and the skill:
|
|
898
|
+
|
|
899
|
+
- Tune on dev.
|
|
900
|
+
- Read scores from the promoted report, never from memory.
|
|
901
|
+
- Make one change per try.
|
|
902
|
+
- Log every try, kept or dropped.
|
|
903
|
+
- Never open the test set.
|
|
904
|
+
|
|
905
|
+
### Examples and the playground runner
|
|
906
|
+
|
|
907
|
+
`examples/<id>/` holds a small trained model the docs show and run: `<id>.model.ts`, `train.ts` (exports `title`, `options`, `rows(split, random)` and, for a `retrieve` head, `table`), `input.txt` with one input per line, the trained `weights.bin`, and `example.json`, which names those files and holds `trained`, the fingerprint of the model file the weights came from. `pnpm examples [id ...]` trains each example with `train`, prints the weights' Brotli bytes next to `budgets.brotliBytes`, checks them on the built package, and writes `weights.bin` and `example.json`. An example whose weights exceed `budgets.brotliBytes` writes nothing, and the command exits 1. The weights are committed: a few kilobytes each, so the docs build trains nothing. A test fails when a committed model file no longer matches its weights.
|
|
908
|
+
|
|
909
|
+
`examples/browser-demo/` is a static page, with no framework and no runtime dependency, that runs the promoted `examples/tag` and `examples/retrieve` models in a browser on both backends, so CPU and WGSL can be compared on a real GPU in a real browser. `node build.ts` in that folder runs `gpu-engine build` in `examples/tag` and `examples/retrieve`, then bundles `src/page.ts` with the same bundler into `dist/page.mjs`, which `index.html` loads; the examples' entries import the root's built `dist/`. The page imports the two built packages by name (`unit-phrases` and `command-lookup`, linked as workspace packages, whose `exports` name `dist/index.mjs`), and every decoded result and timing comes from their `load` and `run`, the path an app runs. The public `run` returns a tag model's labels, not its logits, so for the logits and the head output the page loads each model a second time with `loadModel` and the internal `runLogits` (what `gpu-engine parity` compares) from the library source, on the weights and table the package bundles. The repository's `tsconfig.json` maps the two names to the examples' `src/index.ts`, as it maps `gpu-engine` to `src/`, so it typechecks before anything is built. `node serve.ts` serves the folder on `127.0.0.1`, a secure context, so `navigator.gpu` exists where the browser has WebGPU, and cross-origin isolated, so `performance.now` is fine enough to time one run.
|
|
910
|
+
|
|
911
|
+
- The page loads each model twice, `backend: 'cpu'` and `backend: 'webgpu'` with `navigator.gpu`, and runs a fixed list of 20 dev inputs per model through both; it never reads a test row, and a test checks that every input is the input of a dev row. It shows the adapter (`adapter.info` vendor, architecture and description), `navigator.userAgent`, each input's decoded results side by side, the largest logit difference (a retrieve model: the score of every table row), the load time, the first run and the median and total of the timed runs per backend, and a pass or fail per model.
|
|
912
|
+
- A model passes when both backends decode every input the same, every logit is finite, and the largest difference is within the example's parity tolerance (`parity.json`). Without WebGPU the CPU side still runs, and the model fails with the reason.
|
|
913
|
+
- The result is one JSON object: `window.result`, a "Copy JSON" button, and, when the URL has `?report`, a POST of the JSON to `/result`, which `serve.ts` writes to a file and prints, so an agent can read back a run in a browser it cannot script. A test runs the page's logic in Node on the CPU backend, and `pnpm test:gpu` runs it on both backends on the software adapter.
|
|
914
|
+
- A run on a real GPU is recorded in `docs/measurements/real-gpu-<date>.json`, the machine and the page's JSON of every run as it came back, and `real-gpu-<date>.md`, which names the machine, OS, browser and version, adapter, largest difference, decode differences and timings.
|
|
915
|
+
|
|
916
|
+
`playground/render.ts` exports `render(files): Promise<{ html, issues? }>`, where `files` maps a path in the example folder to text, or to bytes for the weights. It imports only the `gpu-engine` entry, reads nothing but `files`, and never throws.
|
|
917
|
+
|
|
918
|
+
- It runs each non-empty line of the input file on the CPU and returns HTML: tags per token for a `tag` head, the top 3 rows with their scores for a `retrieve` head, the class or the values for a `pooled` head. It picks the rendering from `model.inspect().head`, not from the shape of the output, so a tag line with no tokens renders as empty tags.
|
|
919
|
+
- An issue is `{ file?, line?, message }`. A missing or empty file, a table line that is not a `{ id, text }` row, a line longer than the loaded definition's `input.max` tokens (for any head), and a run error each give one; the lines that run still render. A retrieve example with no `table` setting gets an issue on `example.json`.
|
|
920
|
+
- The model file is not run, since the weights carry the definition. For declarative examples, the fingerprint ignores comments and formatting between source tokens, but preserves literal contents and token boundaries, including numeric literals. It recognizes division after a numeric literal. For ambiguous syntax such as other uses of `/`, interpolated templates, or unmatched quotes, it compares exact source text instead, so even comment or formatting edits can require retraining. When the fingerprint differs from `trained`, the result is one issue on the model file that says the model needs training, and the HTML shows that message instead of model output.
|
|
921
|
+
|
|
922
|
+
## 13. Prior art
|
|
923
|
+
|
|
924
|
+
- [vercel-labs/gpu-lexer](https://github.com/vercel-labs/gpu-lexer): a syntax lexer on WebGPU with one small model for every language. We take the CPU pass with hashed features, the bidirectional affine scans and 6-bit weights.
|
|
925
|
+
- [arikchakma/gpu-time](https://github.com/arikchakma/gpu-time): parses English time expressions on CPU or WebGPU, then resolves the predicted roles in TypeScript. We take tags followed by plain-code decoding, and an `auto` backend that picks the CPU for small batches.
|
|
926
|
+
- [manuschillerdev/gpu-cron](https://github.com/manuschillerdev/gpu-cron): turns English schedules into cron with an MLX-trained model on WebGPU. We take browser checks that compare WGSL outputs with quantized trainer fixtures.
|
|
927
|
+
- [safzanpirani/gpu-query](https://github.com/safzanpirani/gpu-query): parses search bar phrases into filters, with a TypeScript and a WGSL backend on the same int6 weights. We take one weights file for both backends and a measured CPU or GPU threshold.
|
|
928
|
+
- [AnandChowdhary/gpu-utils](https://github.com/AnandChowdhary/gpu-utils): a monorepo of tiny WebGPU packages with an internal shared runtime, a shared training package and a scaffold. The closest to a framework. We take shared layer families with parity-tested CPU and WGSL code, and `new` as a scaffold.
|
|
929
|
+
- [antfu/gpu-icons-search](https://github.com/antfu/gpu-icons-search): predicts related icon words on WebGPU by scoring a query against a word table. We take a promote step with ship gates and the query-against-table shape for `retrieve`.
|
|
930
|
+
- [arihantbansal/gpu-color](https://github.com/arihantbansal/gpu-color): turns color descriptions into hex codes in the browser, on CPU or WebGPU. We take it as an example of a whole-input-to-numbers model, the shape `pooled` covers.
|
|
931
|
+
- [aaronvanston/neural-flexbox](https://github.com/aaronvanston/neural-flexbox): a small learned approximation of one CSS flex row, compared with the browser's real layout. Another numeric output model, checked against a ground truth you can compute.
|
|
932
|
+
- [karpathy/autoresearch](https://github.com/karpathy/autoresearch): an agent edits only the training code while the evaluator stays read-only. We take that split as the reason the test set is sealed.
|
|
933
|
+
- [spaCy projects](https://spacy.io/usage/projects): a project config plus a lock file of checksums. We take data hashes that fail the gate when data changes.
|
|
934
|
+
- [fastText autotune](https://fasttext.cc/docs/en/autotune.html): hyperparameter search inside a model size limit. We take sweeps inside size budgets.
|
|
935
|
+
- [Chrome Decisions API explainer](https://github.com/explainers-by-googlers/decisions-api): on-device classification with an `availability()` check before creating a model. We take `availability()` for backends.
|
|
936
|
+
|
|
937
|
+
What is different here: each project above ships one model, and some share code between their own models. gpu-engine is a library for building your own, and the tool enforces the evaluation method (sealed test set, floors, data hashes, parity) instead of leaving it to each project's discipline.
|
|
938
|
+
|
|
939
|
+
## 14. Open questions
|
|
940
|
+
|
|
941
|
+
### Answered
|
|
942
|
+
|
|
943
|
+
- Does one harness cover the `retrieve` shape, where the input is scored against a table? Yes. It trains through `train`, is scored by `evaluate` and runs through `loadModel` with hooks every head could use: a `table` file in the eval with its own data checks and lock entry, `table` and `negatives` for `train`, and `table` for `loadModel`. No retrieve-only command or data layout was needed. The one retrieve-only path is inside the trainer, where a loss needs a tower pass per candidate row. `examples/retrieve` goes through the whole flow, `new` to `promote` and `parity`, like the other heads (milestone M6).
|
|
944
|
+
- What is the measured CPU or GPU threshold for single inputs? Measured for one device class only: a software adapter (llvmpipe) on a shared 4-core VM, where WebGPU beat the CPU in every cell only from 51314688 multiply-adds per run, the largest count measured (section 9, `docs/measurements/auto-threshold.md`). The measurement is noisy: earlier single-sweep runs gave 12828672 and 13074432.
|
|
945
|
+
- How far does the TypeScript trainer scale? Far enough for every model in this repository: the examples train 3,519 to 131,888 parameters (the larger one is `examples/retrieve`, most of it embedding rows) in 2 to 49 seconds of training per promote, all seeds included, on a shared 4-core VM. Larger models were not tried; they SHOULD be trained elsewhere and exported into the weights format (section 5).
|
|
946
|
+
- Do WGSL templates per layer stay enough? Yes at these sizes: every layer and head runs as its own template, every example passes `parity`, and on the software adapter WebGPU already beats the CPU in some cells from 258048 multiply-adds per run. No fused kernel was needed. On a real GPU (Apple M1 in Chrome, `docs/measurements/real-gpu-2026-11-22.md`) the CPU ran the tag and retrieve examples 6 to 14 times faster than WebGPU per run, as `auto` predicts for models this small; larger models on real GPUs were not measured.
|
|
947
|
+
|
|
948
|
+
### Still open
|
|
949
|
+
|
|
950
|
+
- The CPU or GPU threshold on real GPUs and in real browsers, per device class. The threshold sweep has not run on a real GPU; one real GPU and browser (Apple M1, Chrome) ran the browser demo's parity and timings only (`docs/measurements/real-gpu-2026-11-22.md`).
|
|
951
|
+
- Can browser parity run in CI, not only locally? Not done: parity runs in Node on Dawn over lavapipe only.
|
|
952
|
+
- Where the TypeScript trainer stops being enough, and whether fused kernels pay off on real GPUs for larger models.
|
|
953
|
+
|
|
954
|
+
### Ideas, not planned
|
|
955
|
+
|
|
956
|
+
These are parked. Neither is designed.
|
|
957
|
+
|
|
958
|
+
- App-local models: a `*.model.ts` file that lives inside an application, for example in a `models/` folder, and trains on that application's own data. A framework plugin would retrain it at build time.
|
|
959
|
+
- Models from logs: a model trained from an application's own logs and retrained on a schedule, with the gate deciding whether a new model replaces the old one. Navigation prediction for prefetching is the example.
|
|
960
|
+
|
|
961
|
+
## 15. Milestones
|
|
962
|
+
|
|
963
|
+
`scripts/milestones.ts` (`pnpm milestones`) holds one end-to-end check per milestone, run against the built CLI. CI runs it with `--require M1,M2,M3,M4,M5,M6`, so every milestone stays required on every push. Every command that writes into an example (`parity`, `promote --verify`, each appending to `reads.jsonl`) runs on a temporary copy of it, and a milestone fails when it leaves `git status` of `examples/` different from how it found it.
|
|
964
|
+
|
|
965
|
+
`pnpm milestones --only M4` runs the named milestones and prints `skip` for the others; a required milestone that `--only` skips fails the run.
|
|
966
|
+
|
|
967
|
+
M4 packs this repository and installs the tarball, then for each head (`tag`, `pooled`, `retrieve`) runs what a package author and an app author do, from that install:
|
|
968
|
+
|
|
969
|
+
1. `new`, install the tarball, `doctor`, `loop`.
|
|
970
|
+
2. `promote` with `budgets.brotliBytes` one byte below the candidate's Brotli bytes exits 1 with `BUDGET_BYTES_EXCEEDED`, leaves no `examples` line in `reads.jsonl` and writes no `report.json`; then `promote` with the budget put back counts exactly one read.
|
|
971
|
+
3. `npm run build` (`gpu-engine build`), then `doctor` again with the ship checks.
|
|
972
|
+
4. `npm pack`, and a second temporary app installs the packed model package by name.
|
|
973
|
+
5. That app's `main.ts` imports `load`, `LoadOptions`, `Loaded` and `Result` from the package and passes `tsc` with `strict`, `exactOptionalPropertyTypes` and `skipLibCheck: false`, once with `lib: ["es2023"]` and Node's types only and once with `lib: ["es2023", "dom"]` and no Node types.
|
|
974
|
+
6. `node main.ts` runs the first dev input (never a test row) on the CPU, and its decoded result equals what `gpu-engine inspect` decodes for the same input in the model package; `inspect()` names the head; a run after `destroy()` returns `RUN_MODEL_DESTROYED`.
|
|
975
|
+
|
|
976
|
+
The retrieve package moves its table to `data/menu.jsonl` with renamed ids before the first `loop`, so the shipped module must hold the configured table: `report.json` records that file's SHA-256, `dist/index.mjs` holds every renamed id, and the app's result is one of them.
|
|
977
|
+
|
|
978
|
+
M4 does not check `private` in `package.json`. Dropping it is the release decision that starts release PRs, and the release verifies the tagged commit by running these milestones, so a check on the flag would block every release.
|
|
979
|
+
|
|
980
|
+
| Milestone | Scope | Done when | Status | How it was checked |
|
|
981
|
+
| --------- | ---------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
982
|
+
| M0 | Repository skeleton, SPEC.md, AGENTS.md, public types | CI passes on `main` with check, typecheck, doctor, test and validate | Done | The `ci` job runs those five steps on every push |
|
|
983
|
+
| M1 | Model kit for `tag` on CPU: featurizer, layers, trainer, QAT, weights format | A `tag` model trains, quantizes, saves, loads and runs on the CPU, and every layer passes its gradient test | Done | `pnpm milestones` M1: a gradient test per layer and head, a QAT-trained tag model at >= 0.9 held-out accuracy through `loadModel`, byte-identical `encode(decode(bytes))` |
|
|
984
|
+
| M2 | Harness: datasets, loop, gate, sealed test set, promote | `loop` runs in under a minute, and tests prove only `promote` reads the test set | Done | `pnpm milestones` M2: `loop`, `promote` and `promote --verify` on a copy of `test/fixtures/project-tag`, and `test/harness` names every code section 7 names that `docs/diagnostics.md` documents |
|
|
985
|
+
| M3 | WGSL runtime and parity | `parity` passes in CI on Dawn over lavapipe for every layer and fixture | Done | `pnpm milestones` M3: `pnpm test:gpu` with a WGSL test per layer and head, and `parity` on a copy of every example with a `report.json`; the CI `gpu` job runs both on lavapipe |
|
|
986
|
+
| M4 | Scaffold, skill, docs, a shipped package | `new` makes a package that passes its checks, builds, packs and runs in an app; the pack has skills, `llms.txt` | Done | `pnpm milestones` M4, steps listed above the table: per head from the packed tarball, `new`, `loop`, a budget-failed promote with no reads, `promote`, `build`, `npm pack`, then an app installs the package, passes strict `tsc` for Node and DOM, runs one dev input, then destroys it |
|
|
987
|
+
| M5 | `pooled` head | A `pooled` example model goes through the whole pipeline to promote and parity | Done | `pnpm milestones` M5 on `examples/pooled`: report rows, the model above every baseline on dev, then `promote --verify` and `parity` on a copy; the CI `gate` job runs `doctor` and `promote --verify` there |
|
|
988
|
+
| M6 | `retrieve` head | A `retrieve` example model goes through the whole pipeline (section 14: one harness covers it) | Done | `pnpm milestones` M6 on `examples/retrieve`, the same checks as M5 |
|