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.
Files changed (54) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +96 -2
  3. package/SPEC.md +988 -0
  4. package/THIRD_PARTY_NOTICES.md +29 -0
  5. package/dist/cli.d.mts +1 -0
  6. package/dist/cli.mjs +4 -0
  7. package/dist/harness.d.mts +132 -0
  8. package/dist/harness.mjs +1 -0
  9. package/dist/index.d.mts +98 -0
  10. package/dist/index.mjs +1 -0
  11. package/dist/load-o_thEAKC.mjs +258 -0
  12. package/dist/scaffold-CY5xhy-V.mjs +106 -0
  13. package/dist/types-BwigqFwr.d.mts +868 -0
  14. package/docs/apps.md +108 -0
  15. package/docs/cli.md +126 -0
  16. package/docs/data.md +101 -0
  17. package/docs/diagnostics.md +509 -0
  18. package/docs/harness.md +191 -0
  19. package/docs/layers.md +249 -0
  20. package/docs/measurements/auto-threshold.json +335 -0
  21. package/docs/measurements/auto-threshold.md +56 -0
  22. package/docs/measurements/real-gpu-2026-11-22.json +4718 -0
  23. package/docs/measurements/real-gpu-2026-11-22.md +75 -0
  24. package/docs/runtime.md +112 -0
  25. package/docs/sealed-test-set.md +107 -0
  26. package/docs/weights-format.md +138 -0
  27. package/llms.txt +24 -0
  28. package/package.json +73 -3
  29. package/skills/gpu-engine/SKILL.md +117 -0
  30. package/templates/common/AGENTS.md +27 -0
  31. package/templates/common/github/workflows/ci.yml +35 -0
  32. package/templates/common/gitignore +3 -0
  33. package/templates/common/package.template.json +27 -0
  34. package/templates/common/tsconfig.template.json +17 -0
  35. package/templates/pooled/NEW_MODEL_NAME.eval.ts +93 -0
  36. package/templates/pooled/NEW_MODEL_NAME.model.ts +11 -0
  37. package/templates/pooled/SPEC.md +31 -0
  38. package/templates/pooled/src/decode.ts +10 -0
  39. package/templates/pooled/src/index.ts +44 -0
  40. package/templates/pooled/src/weights.ts +4 -0
  41. package/templates/retrieve/NEW_MODEL_NAME.eval.ts +149 -0
  42. package/templates/retrieve/NEW_MODEL_NAME.model.ts +12 -0
  43. package/templates/retrieve/SPEC.md +33 -0
  44. package/templates/retrieve/data/table.jsonl +16 -0
  45. package/templates/retrieve/src/decode.ts +9 -0
  46. package/templates/retrieve/src/index.ts +45 -0
  47. package/templates/retrieve/src/table.ts +21 -0
  48. package/templates/retrieve/src/weights.ts +4 -0
  49. package/templates/tag/NEW_MODEL_NAME.eval.ts +114 -0
  50. package/templates/tag/NEW_MODEL_NAME.model.ts +11 -0
  51. package/templates/tag/SPEC.md +31 -0
  52. package/templates/tag/src/decode.ts +25 -0
  53. package/templates/tag/src/index.ts +44 -0
  54. package/templates/tag/src/weights.ts +4 -0
@@ -0,0 +1,117 @@
1
+ ---
2
+ name: gpu-engine
3
+ description: Build, tune, evaluate and ship a tiny gpu-engine model package. Use when working in a package made by `gpu-engine new`, when choosing its layers, reading `tries.jsonl` or `report.json`, or fixing a gpu-engine diagnostic code.
4
+ ---
5
+
6
+ # gpu-engine
7
+
8
+ A model package holds one tiny model: `<name>.model.ts` (input, `net`, head, budgets), `<name>.eval.ts` (`defineEval(model, { ... })`: data, training, decode, metric, baselines, gate), `src/decode.ts` (your decode step) and three data sets. The eval takes the model first and infers every type from it and from `decode`, so it needs no type arguments; keep `decode` before `metric`. You find the layout by trying: change one thing, run `loop`, read the dev score, keep or revert. `promote` measures the result once on the sealed test set.
9
+
10
+ The package's `SPEC.md` says what this model is for; read it first. The library's docs are in `node_modules/gpu-engine/`: `docs/layers.md` (what each layer costs and when it helps), `docs/data.md` (bringing your own rows, splitting, the lock), `docs/harness.md`, `docs/cli.md`, `docs/runtime.md`, `docs/apps.md` (using the built package in an app), `docs/sealed-test-set.md`, `docs/weights-format.md` and `docs/diagnostics.md` (every code with its fix).
11
+
12
+ ## Start
13
+
14
+ ```sh
15
+ npx gpu-engine@latest new my-model --head tag # or pooled, or retrieve
16
+ cd my-model
17
+ npm install
18
+ npx gpu-engine doctor
19
+ npx gpu-engine loop --log "starter"
20
+ ```
21
+
22
+ ## Rules
23
+
24
+ - Tune on dev.
25
+ - Read scores from the promoted report, never from memory.
26
+ - Make one change per try.
27
+ - Log every try, kept or dropped.
28
+ - Never open the test set.
29
+
30
+ What they mean in practice:
31
+
32
+ - Every decision comes from the dev table `loop` prints. Test scores exist only in `report.json`, `MODEL_CARD.md` and `RESULTS.md`; quote them from there, with the file name.
33
+ - One change per try: one layer added or removed, one size, one training number. Two changes in one try cannot tell you which one helped.
34
+ - Run every try through `npx gpu-engine loop --log "<the change>"`, which appends it to `tries.jsonl`. Then keep the change or revert it, and record which with `npx gpu-engine loop --mark kept` or `--mark dropped`. Never edit or delete rows of `tries.jsonl`, `reads.jsonl` or `data.lock.json`, and never edit `report.json`, `gate.json`, `MODEL_CARD.md` or `RESULTS.md`.
35
+ - Commit before a try when you can: the row records the commit and `dirty`, so the try can be traced to its code.
36
+
37
+ ## The loop
38
+
39
+ ```sh
40
+ npx gpu-engine doctor # static checks; fix every finding first
41
+ npx gpu-engine loop --log "starter" # train, dev table, gate, one row in tries.jsonl
42
+ npx gpu-engine loop --fail # the dev examples the candidate gets wrong
43
+ npx gpu-engine inspect "some input" # tokens, features, logits, decoded result for one input
44
+ npx gpu-engine loop --mark kept # after reading the score: record kept or dropped on that try
45
+ npx gpu-engine promote # once, when dev says the model is done
46
+ npx gpu-engine parity # trainer = CPU = WGSL; needs the webgpu devDependency
47
+ npm run build # gpu-engine build: dist/index.mjs (no imports) and dist/index.d.mts
48
+ ```
49
+
50
+ `loop` exits 1 when a gate line fails: a dev score below the promoted floor, a budget, or a changed data file. The candidate and the try are written either way.
51
+
52
+ After a promotion, keep tuning the same way. Once the model file changes, `inspect` runs the candidate trained from it, `doctor` prints a note, and `promote --verify` (so CI) fails with `WEIGHTS_DEFINITION_MISMATCH`. That is expected while tuning: promote once when dev says the new model is done, never just to clear the message.
53
+
54
+ ## Changing the data
55
+
56
+ Generators write a set only into an empty folder, so `loop` checks that the train and dev files are still what their generators write. After you edit a generator, `loop` stops with `DATA_GENERATOR_CHANGED`. Accept the change with:
57
+
58
+ ```sh
59
+ npx gpu-engine loop --regenerate train --log "<the data change>" # or dev, or train,dev
60
+ ```
61
+
62
+ It rewrites the named files from their generators, drops their entries from `data.lock.json`, records the new hashes and trains. Commit the new files and lock with the change. A changed dev set moves every dev score, so compare tries only within one dev set, and a promoted floor measured on the old dev set may fail. The test set is never regenerated: to change it, write new rows by hand in new groups, delete its lock entry, and say so in `SPEC.md`. Rows you write by hand go in another file of the set, never in the generated one.
63
+
64
+ ## Starting layouts
65
+
66
+ Every `net` is an explicit list; there are no presets. Start from the row that matches the task, run `loop`, then tune. All rows use `rows: [f.shape(), f.hash({ buckets: 256, k: 2 })]` and `quant: int6({ qatFrom: 0.7 })`, with `f`, `l`, `h` and `int6` from `gpu-engine` (`features`, `layers`, `heads`). Costs are from `plan()`: multiply-adds per token, and int6 bytes before Brotli (the trained file is smaller, since unused hash rows stay zero).
67
+
68
+ | Task | `max` | `net` | `head` | Multiply-adds | Bytes |
69
+ | -------------------------------------------------- | ----- | ---------------------------------------------------------------------------------------------------------------- | -------------------------------- | ------------- | ----- |
70
+ | Tag tokens, label set by the next or previous word | 16 | `[l.embed({ size: 16 }), l.conv({ taps: 3 }), l.dense({ size: 16, activation: 'relu' })]` | `h.tag({ labels })`, 3 labels | 416 | 3531 |
71
+ | Tag tokens, label set by words farther away | 16 | `[l.embed({ size: 16 }), l.conv({ taps: 3 }), l.biScan({ size: 8 }), l.dense({ size: 16, activation: 'relu' })]` | `h.tag({ labels })`, 3 labels | 944 | 3939 |
72
+ | One class per input, marker words decide | 12 | `[l.embed({ size: 12 }), l.conv({ taps: 3 }), l.dense({ size: 12, activation: 'relu' })]` | `h.pooled({ labels })`, 3 labels | 324 | 2640 |
73
+ | One class per input, word order decides | 12 | `[l.embed({ size: 12 }), l.conv({ taps: 3 }), l.biScan({ size: 8 }), l.dense({ size: 12, activation: 'relu' })]` | `h.pooled({ labels })`, 3 labels | 772 | 2988 |
74
+ | A few numbers per input | 16 | `[l.embed({ size: 16 }), l.biScan({ size: 8 }), l.dense({ size: 16, activation: 'tanh' })]` | `h.pooled({ outputs: 2 })` | 944 | 3902 |
75
+ | Rank the rows of a table | 12 | `[l.embed({ size: 16 }), l.dense({ size: 16, activation: 'tanh' })]` | `h.retrieve({ size: 16 })` | 864 | 3840 |
76
+
77
+ The `gpu-engine new` starters use the first (tag), third (pooled, 2 labels, `max` 16) and last (retrieve) rows. On their generated data each first `loop` trains three seeds in under five seconds and beats its rule baseline with room left: part of each starter's data needs the layer its row leaves out (`biScan` for tag and pooled, `conv` for retrieve), as its `SPEC.md` says. Set `max` above the longest input you expect: tokens past it get no output.
78
+
79
+ ## Tuning
80
+
81
+ Read the dev table first. It has three rows: the model, each baseline, and the oracle (the gold run through your decode step).
82
+
83
+ | What you see | What to try |
84
+ | ------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
85
+ | The oracle is below 1 | The decode or the gold loses information. Fix `src/decode.ts` or the data; no layer can beat the oracle |
86
+ | The model is at or below the rule baseline | Run `loop --fail` and read the misses. If they need context, add `conv({ taps: 3 })`; if they need words farther away, add `biScan` |
87
+ | Misses on words dev has and train does not | Unseen words land on hash rows that stayed zero, so only `shape` and the neighbours carry them. Add context layers or vary the training words; more buckets do not help |
88
+ | Seed spread above `gate.noise` | The score is inside seed noise. Add a seed, lower `learningRate`, or add epochs |
89
+ | `stopped by budget` in the train line | The run did not finish its epochs. Raise `budgetSeconds` or shrink the model |
90
+ | Brotli bytes over budget | Lower `buckets` or `embed` size first: the `embed` table is most of the bytes |
91
+ | Multiply-adds over budget | Shrink `biScan` or `dense` sizes: they grow with `size * in` |
92
+ | A `relu` model stalls | Try `tanh` on that `dense`, or a lower `learningRate` |
93
+
94
+ Prefer the smallest model that holds the dev score: a try that keeps the score with fewer bytes or multiply-adds is a kept try. `docs/layers.md` gives each layer's cost formula and when it does not help.
95
+
96
+ ## Reading tries.jsonl
97
+
98
+ One JSON row per try. Compare `devScore` (the mean over dev sets) with the best kept try, and read `devSpread` (best minus worst seed) against `gate.noise`: a gain smaller than the spread is noise. `definition` changes whenever the model file changes, so rows with the same hash are the same layout. `brotliBytes`, `macsPerToken` and `trainSeconds` are the cost. `gate` is `pass` or `fail`. `diverged`, present only when a seed's loss stopped being finite, maps the seed to the step: lower `learningRate` or raise `warmup` before reading that try's score. There is never a test score in it.
99
+
100
+ ## Reading the promoted report
101
+
102
+ `report.json` (and `RESULTS.md`, rendered from it): `test.<set>` holds `model`, `baselines` and `oracle` for each test set, `dev.<set>` the same for dev; `testReads` counts every read of the test set; `level` is 2 (counted reads) or 3 (sealed); `gate` lists the lines the promotion passed. `MODEL_CARD.md` adds the parity result and the adapter it ran on. When parity ran on a software adapter (llvmpipe), say so; real GPU and real browser results are `not run` until someone runs them.
103
+
104
+ Report a model's quality as the test row of the last promotion, next to its baseline and oracle, and the read count.
105
+
106
+ ## The test set
107
+
108
+ - Never open, print, list, copy or grep any file under the test folder, and never write code that names it. The only allowed mention is the `sealed(...)` call in the eval file; `doctor` and `loop` fail on any other (`DATA_TEST_READ`).
109
+ - Never promote to see how a change does. Each `promote` is a counted test read; promote once, when dev says the model is done.
110
+ - Never move rows between sets, edit a set to change its score, or delete a lock entry to hide a changed file.
111
+ - Never add a key with `test` in its name to a try or a log.
112
+ - If the test set was seen, say so plainly and replace it with new groups before the next promotion.
113
+ - For a guarantee instead of a rule, seal it: remove the test generator from the eval file, then `npx gpu-engine promote --seal` (`docs/sealed-test-set.md`).
114
+
115
+ ## Diagnostics
116
+
117
+ Every failure prints `CODE: message`, then `why:` and `fix:`. Do what the fix says; `docs/diagnostics.md` lists all codes. Never weaken a check, raise `gate.noise` or `parity.tolerance`, or raise a budget without a measured reason written in the package's `SPEC.md`.
@@ -0,0 +1,27 @@
1
+ # NEW_MODEL_NAME
2
+
3
+ A tiny model built with gpu-engine. [SPEC.md](./SPEC.md) is the source of truth for what this model does, its data, its baseline and how it is judged. Read it before changing anything. A change to what the model does lands in SPEC.md first.
4
+
5
+ [skills/gpu-engine/SKILL.md](./skills/gpu-engine/SKILL.md) explains the library: the layers, the heads, the commands and the diagnostic codes.
6
+
7
+ ## Rules
8
+
9
+ - Tune on dev.
10
+ - Read scores from the promoted report, never from memory.
11
+ - Make one change per try.
12
+ - Log every try, kept or dropped.
13
+ - Never open the test set.
14
+
15
+ What they mean here:
16
+
17
+ - `npx gpu-engine loop --log "<the one change>"` trains, scores dev and appends the try to `tries.jsonl`. Once its dev score is in, mark it with `npx gpu-engine loop --mark kept` or `--mark dropped`. Never edit `tries.jsonl` by hand.
18
+ - Dev scores come from `loop`. Test scores exist only in `report.json`, `MODEL_CARD.md` and `RESULTS.md`, written by `npx gpu-engine promote`, the one command that reads the test set. Quote them from those files.
19
+ - Code never names the test folder. The only allowed mention is the `sealed(...)` call in the eval file; `doctor` and `loop` fail on any other.
20
+ - Data comes from the generators in the eval file. After editing a train or dev generator, `loop` stops with `DATA_GENERATOR_CHANGED`; run `npx gpu-engine loop --regenerate train` (or `dev`, or `train,dev`) to rewrite those files and their lock entries, and commit them with the change. The test set is never regenerated.
21
+ - After a promotion, a changed model file is expected while tuning: `inspect` runs the new candidate, and `promote --verify` fails with `WEIGHTS_DEFINITION_MISMATCH` until you promote once, when dev says the model is done.
22
+ - `npx gpu-engine doctor` runs every static check and prints each finding with its code, why and fix.
23
+ - `npx gpu-engine parity` compares the CPU and WebGPU outputs. It needs a WebGPU adapter; in Node that is the `webgpu` package (`npm install --save-dev webgpu@^0.6.2`), which this package does not install by default.
24
+
25
+ ## Ship
26
+
27
+ `npx gpu-engine promote` writes the weights, then `npm run build` (`gpu-engine build`) bundles `src/index.ts`, the runtime and the weights into `dist/index.mjs`, one module with no dependencies, and writes its types to `dist/index.d.mts`. `npm run typecheck` checks the package. CI runs `doctor` and `promote --verify`.
@@ -0,0 +1,35 @@
1
+ name: ci
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+
8
+ permissions:
9
+ contents: read
10
+
11
+ jobs:
12
+ gate:
13
+ runs-on: ubuntu-latest
14
+ timeout-minutes: 20
15
+ steps:
16
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
17
+ with:
18
+ persist-credentials: false
19
+ - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
20
+ with:
21
+ node-version: 24
22
+ - run: npm install --no-audit --no-fund
23
+ # The gate: every static check, then the promotion checked without reading test data. Strict shell flags, so
24
+ # any failing step fails the job. Before the first promotion there is no report.json and nothing to verify.
25
+ - name: gate
26
+ shell: bash
27
+ run: |
28
+ set -euo pipefail
29
+ npm run build
30
+ npx --no-install gpu-engine doctor
31
+ if [ -f report.json ]; then
32
+ npx --no-install gpu-engine promote --verify
33
+ else
34
+ echo "promote --verify: nothing promoted yet"
35
+ fi
@@ -0,0 +1,3 @@
1
+ node_modules
2
+ dist
3
+ .gpu-engine
@@ -0,0 +1,27 @@
1
+ {
2
+ "name": "NEW_MODEL_NAME",
3
+ "version": "0.0.0",
4
+ "private": true,
5
+ "files": ["dist"],
6
+ "type": "module",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.mts",
10
+ "import": "./dist/index.mjs"
11
+ }
12
+ },
13
+ "scripts": {
14
+ "build": "gpu-engine build",
15
+ "typecheck": "tsc -p .",
16
+ "doctor": "gpu-engine doctor",
17
+ "loop": "gpu-engine loop",
18
+ "promote": "gpu-engine promote",
19
+ "verify": "gpu-engine promote --verify",
20
+ "parity": "gpu-engine parity"
21
+ },
22
+ "devDependencies": {
23
+ "@types/node": "^24.19.2",
24
+ "gpu-engine": "GPU_ENGINE_VERSION",
25
+ "typescript": "^6.0.3"
26
+ }
27
+ }
@@ -0,0 +1,17 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "es2023",
4
+ "lib": ["es2023", "dom"],
5
+ "module": "nodenext",
6
+ "moduleResolution": "nodenext",
7
+ "strict": true,
8
+ "noUncheckedIndexedAccess": true,
9
+ "verbatimModuleSyntax": true,
10
+ "erasableSyntaxOnly": true,
11
+ "allowImportingTsExtensions": true,
12
+ "skipLibCheck": true,
13
+ "noEmit": true,
14
+ "types": ["node"]
15
+ },
16
+ "include": ["*.ts", "src"]
17
+ }
@@ -0,0 +1,93 @@
1
+ // How the model is trained and judged. The generators write each set the first time `loop` runs. Every set talks about
2
+ // its own domain (its group) and its own subjects (its vocab), so dev and test hold subjects the model never trained
3
+ // on; the clause words, the opinion words, `not` and `but` are shared.
4
+ import { defineDataset, defineEval, sealed, tokenize } from 'gpu-engine'
5
+ import type { Example, Random } from 'gpu-engine'
6
+ import { decode } from './src/decode.ts'
7
+ import type { Label, Result } from './src/decode.ts'
8
+ import model from './NEW_MODEL_NAME.model.ts'
9
+
10
+ const good = ['great', 'nice', 'lovely', 'fine', 'good', 'perfect']
11
+ const bad = ['awful', 'bad', 'poor', 'broken', 'terrible', 'slow']
12
+
13
+ function pick<T>(random: Random, items: readonly T[]): T {
14
+ const item = items[Math.floor(random() * items.length)]
15
+ if (item === undefined) throw new Error('pick from an empty list')
16
+ return item
17
+ }
18
+
19
+ const verbs = ['was', 'is', 'seemed', 'felt']
20
+ const tails = [
21
+ ['at', 'first'],
22
+ ['for', 'now'],
23
+ ['all', 'day'],
24
+ ['this', 'week'],
25
+ ['so', 'far'],
26
+ ]
27
+
28
+ /** One clause: `the soup was not good at first`. The two-word tail keeps `but` out of reach of a 3-token window. */
29
+ function clause(random: Random, subject: string, positive: boolean, negated: boolean): string[] {
30
+ const words = ['the', subject, pick(random, verbs)]
31
+ if (negated) words.push('not')
32
+ words.push(pick(random, positive ? good : bad), ...pick(random, tails))
33
+ return words
34
+ }
35
+
36
+ /**
37
+ * Short opinions about one domain's subjects. `not` flips a clause in about a third of the clauses. Two rows in five
38
+ * change their mind with `but`: the clause before it says the opposite, and the label is the clause after it.
39
+ */
40
+ function opinions(domain: string, subjects: readonly string[], size: number) {
41
+ return (random: Random): Example<Result>[] =>
42
+ Array.from({ length: size }, () => {
43
+ const subject = pick(random, subjects)
44
+ const negated = random() < 0.35
45
+ const positive = random() < 0.5
46
+ const meaning = positive !== negated
47
+ const words = clause(random, subject, positive, negated)
48
+ const vocab = [subject]
49
+ if (random() < 0.4) {
50
+ const other = pick(random, subjects)
51
+ const flip = random() < 0.35
52
+ words.unshift(...clause(random, other, meaning === flip, flip), 'but')
53
+ if (other !== subject) vocab.push(other)
54
+ }
55
+ const gold: Label = meaning ? 'positive' : 'negative'
56
+ return { input: words.join(' '), gold, group: domain, vocab }
57
+ })
58
+ }
59
+
60
+ /** The rule baseline: more good words than bad ones is positive. It does not see `not`. */
61
+ function rules(input: string): Result {
62
+ let score = 0
63
+ for (const { text } of tokenize(input)) {
64
+ const word = text.toLowerCase()
65
+ if (good.includes(word)) score++
66
+ if (bad.includes(word)) score--
67
+ }
68
+ return score >= 0 ? 'positive' : 'negative'
69
+ }
70
+
71
+ export default defineEval(model, {
72
+ sets: { train: 'data/train/*.jsonl', dev: 'data/dev/*.jsonl', test: sealed('data/test/*.jsonl') },
73
+ data: defineDataset<Result>({
74
+ seed: 1,
75
+ minSize: { train: 600, dev: 120, test: 120 },
76
+ generate: {
77
+ train: opinions(
78
+ 'home',
79
+ ['soup', 'chair', 'phone', 'jacket', 'lamp', 'movie', 'bus', 'bread', 'garden', 'laptop', 'song', 'room'],
80
+ 600,
81
+ ),
82
+ dev: opinions('travel', ['bike', 'hotel', 'park', 'train', 'beach', 'camera'], 120),
83
+ test: opinions('work', ['desk', 'printer', 'meeting', 'office', 'badge', 'monitor'], 120),
84
+ },
85
+ }),
86
+ train: { seeds: [1, 2, 3], epochs: 12, batch: 16, learningRate: 0.02, warmup: 0.1, budgetSeconds: 30 },
87
+ decode,
88
+ metric: (pred, gold) => (pred === gold ? 1 : 0),
89
+ baselines: { rules },
90
+ gate: { floors: 'promoted', noise: 0.05 },
91
+ parity: { tolerance: 1e-3 },
92
+ ship: { brotliBytes: 40_000, files: ['dist/index.mjs', 'dist/index.d.mts'] },
93
+ })
@@ -0,0 +1,11 @@
1
+ // The model: what it reads, its layers and its head. SPEC.md says what it is for; a change to that lands there first.
2
+ import { defineModel, features as f, heads as h, int6, layers as l } from 'gpu-engine'
3
+
4
+ export default defineModel({
5
+ name: 'NEW_MODEL_NAME',
6
+ input: f.tokens({ max: 16, rows: [f.shape(), f.hash({ buckets: 256, k: 2 })] }),
7
+ net: [l.embed({ size: 12 }), l.conv({ taps: 3 }), l.dense({ size: 12, activation: 'relu' })],
8
+ head: h.pooled({ labels: ['positive', 'negative'] }),
9
+ quant: int6({ qatFrom: 0.7 }),
10
+ budgets: { brotliBytes: 6_000, macsPerToken: 1_000 },
11
+ })
@@ -0,0 +1,31 @@
1
+ # NEW_MODEL_NAME spec
2
+
3
+ This file is the source of truth for this model. A change to what it does lands here first, then in the eval, then in the model or the data.
4
+
5
+ ## Task
6
+
7
+ Read a short opinion and return `positive` or `negative`. When the opinion changes its mind with `but`, the clause after `but` decides.
8
+
9
+ | Input | Result |
10
+ | --------------------------------------------------------- | ---------- |
11
+ | `the soup was great at first` | `positive` |
12
+ | `the phone is not good so far` | `negative` |
13
+ | `the bus was slow all day but the bus is not bad for now` | `positive` |
14
+
15
+ The model is a `pooled` head: one label for the whole input. `src/decode.ts` returns it as the result.
16
+
17
+ ## Data
18
+
19
+ `NEW_MODEL_NAME.eval.ts` generates three sets with a fixed seed the first time `gpu-engine loop` runs: train, dev and the sealed test set. Each set talks about its own domain, recorded as the row's `group`, and its own subjects, recorded as the row's `vocab`, so the data checks prove that dev and test hold subjects the model never trained on. The clause words, the opinion words, `not` and `but` are shared by every set.
20
+
21
+ ## Judged by
22
+
23
+ - Metric: 1 when the label is right, else 0. The set score is the mean.
24
+ - Rule baseline `rules`: more good words than bad ones is `positive`. It does not see `not` or `but`.
25
+ - The model must beat the baseline on dev before a promotion is worth it. The oracle row shows the ceiling the decode step allows.
26
+ - The gate: each set's score at least the promoted score minus `noise`, within the budgets in `NEW_MODEL_NAME.model.ts`.
27
+ - Room to tune: the starter model reads one word to each side (`conv`), then pools the whole input, so it cannot tell which clause came after `but`, and the first `loop` misses many of the rows that change their mind. Adding `biScan` lets each token read the whole sentence.
28
+
29
+ ## Ship
30
+
31
+ `gpu-engine promote` writes `weights/NEW_MODEL_NAME.bin` and `src/weights.ts`. `npm run build` writes `dist/index.mjs` and its types, `dist/index.d.mts`; the module exports `load({ backend, gpu? })`; `run(text)` returns `[error, result]` and never throws.
@@ -0,0 +1,10 @@
1
+ // Turns the head's label into the result an app uses. The eval scores this result, and the shipped entry returns it.
2
+ import type model from '../NEW_MODEL_NAME.model.ts'
3
+
4
+ export type Label = (typeof model)['head']['labels'][number]
5
+
6
+ export type Result = Label
7
+
8
+ export function decode(label: Label): Result {
9
+ return label
10
+ }
@@ -0,0 +1,44 @@
1
+ // The shipped entry: the promoted weights, the runtime and the decode step. `npm run build` bundles it into
2
+ // dist/index.mjs, one module with no imports, that runs in browsers and in Node.
3
+ import { loadModel } from 'gpu-engine'
4
+ import type { BackendRequest, GpuEntryPoint, Inspection, RunResult } from 'gpu-engine'
5
+ import type model from '../NEW_MODEL_NAME.model.ts'
6
+ import { decode } from './decode.ts'
7
+ import type { Result } from './decode.ts'
8
+ import { weightsHex } from './weights.ts'
9
+
10
+ export type { Result } from './decode.ts'
11
+
12
+ export interface LoadOptions {
13
+ /** `auto` picks WebGPU or the CPU per run; `inspect()` says which and why. */
14
+ readonly backend: BackendRequest
15
+ /** A WebGPU entry point where `navigator.gpu` is missing, such as Node with the `webgpu` package. */
16
+ readonly gpu?: GpuEntryPoint
17
+ }
18
+
19
+ export interface Loaded {
20
+ /** Never throws: `[error, undefined]` or `[undefined, result]`. */
21
+ run(text: string): Promise<RunResult<Result>>
22
+ inspect(): Inspection
23
+ /** Frees the GPU buffers and device once started runs finish; later runs return `RUN_MODEL_DESTROYED`. */
24
+ destroy(): Promise<void>
25
+ }
26
+
27
+ function bytes(hex: string): Uint8Array {
28
+ return Uint8Array.from({ length: hex.length / 2 }, (_, index) =>
29
+ Number.parseInt(hex.slice(index * 2, index * 2 + 2), 16),
30
+ )
31
+ }
32
+
33
+ /** Loads the promoted model. Never rejects: a model that cannot load returns its error from every `run`. */
34
+ export async function load(options: LoadOptions): Promise<Loaded> {
35
+ const runtime = await loadModel<typeof model>(bytes(weightsHex), options)
36
+ return {
37
+ async run(text) {
38
+ const [error, label] = await runtime.run(text)
39
+ return error === undefined ? [undefined, decode(label)] : [error, undefined]
40
+ },
41
+ inspect: () => runtime.inspect(),
42
+ destroy: () => runtime.destroy(),
43
+ }
44
+ }
@@ -0,0 +1,4 @@
1
+ // Replaced by `gpu-engine promote` with the promoted weights. Until then the shipped entry has no model to load.
2
+
3
+ /** The promoted weights file, lowercase hex. Empty until the first promotion. */
4
+ export const weightsHex: string = ''
@@ -0,0 +1,149 @@
1
+ // How the model is trained and judged. The table in data/table.jsonl is the list of rows a query is matched to. The
2
+ // generators write each set the first time `loop` runs: requests for one row, in sentence frames each set has to
3
+ // itself (its groups), with filler words each set has to itself (its vocab), so dev and test ask in ways the model
4
+ // never trained on. A request names a dish by its words or by the plural of its ingredient, and some name a second
5
+ // dish they do not want with `instead of` or `not ... but`, words every set shares. Gold is the id of the row asked for.
6
+ import { readFileSync } from 'node:fs'
7
+ import { defineDataset, defineEval, sealed, tokenize } from 'gpu-engine'
8
+ import type { Example, Random, TableRow } from 'gpu-engine'
9
+ import { decode } from './src/decode.ts'
10
+ import type { Result } from './src/decode.ts'
11
+ import model from './NEW_MODEL_NAME.model.ts'
12
+
13
+ type Frames = Readonly<Record<string, readonly string[]>>
14
+
15
+ function tableRow(line: string): TableRow {
16
+ const row: unknown = JSON.parse(line)
17
+ if (typeof row !== 'object' || row === null || !('id' in row) || !('text' in row)) {
18
+ throw new Error('data/table.jsonl: every line must be { "id": string, "text": string }')
19
+ }
20
+ const { id, text } = row
21
+ if (typeof id !== 'string' || typeof text !== 'string') {
22
+ throw new Error('data/table.jsonl: every line must be { "id": string, "text": string }')
23
+ }
24
+ return { id, text }
25
+ }
26
+
27
+ const table: readonly TableRow[] = readFileSync(new URL('data/table.jsonl', import.meta.url), 'utf8')
28
+ .split('\n')
29
+ .filter((line) => line.trim() !== '')
30
+ .map(tableRow)
31
+
32
+ function pick<T>(random: Random, items: readonly T[]): T {
33
+ const item = items[Math.floor(random() * items.length)]
34
+ if (item === undefined) throw new Error('pick from an empty list')
35
+ return item
36
+ }
37
+
38
+ function words(text: string): string[] {
39
+ return tokenize(text).map((token) => token.text.toLowerCase())
40
+ }
41
+
42
+ /** The plural of each ingredient: a request may say `soup with tomatoes` for the row `tomato soup`. */
43
+ const plurals: ReadonlyMap<string, string> = new Map([
44
+ ['tomato', 'tomatoes'],
45
+ ['onion', 'onions'],
46
+ ['pea', 'peas'],
47
+ ['mushroom', 'mushrooms'],
48
+ ['potato', 'potatoes'],
49
+ ['bean', 'beans'],
50
+ ['egg', 'eggs'],
51
+ ['apple', 'apples'],
52
+ ['cherry', 'cherries'],
53
+ ['carrot', 'carrots'],
54
+ ['lemon', 'lemons'],
55
+ ['banana', 'bananas'],
56
+ ])
57
+
58
+ /** How a request names a row: its own words, or its dish with the plural ingredient (`soup with tomatoes`). */
59
+ function dish(random: Random, row: TableRow): string[] {
60
+ const [ingredient = '', kind = ''] = words(row.text)
61
+ const plural = plurals.get(ingredient)
62
+ return plural !== undefined && random() < 0.5 ? [kind, 'with', plural] : [ingredient, kind]
63
+ }
64
+
65
+ /**
66
+ * Requests for one table row. `{row}` is how the request names it and `{filler}` one of the set's own filler words. A
67
+ * frame with `{other}` also names a second row, the one not wanted: only the words next to each name tell them apart.
68
+ */
69
+ function requests(frames: Frames, fillers: readonly string[], size: number) {
70
+ return (random: Random): Example<Result>[] =>
71
+ Array.from({ length: size }, () => {
72
+ const [group, frame] = pick(random, Object.entries(frames))
73
+ const row = pick(random, table)
74
+ const other = pick(
75
+ random,
76
+ table.filter(({ id }) => id !== row.id),
77
+ )
78
+ const filler = pick(random, fillers)
79
+ const text = frame.flatMap((slot) =>
80
+ slot === '{row}'
81
+ ? dish(random, row)
82
+ : slot === '{other}'
83
+ ? dish(random, other)
84
+ : slot === '{filler}'
85
+ ? [filler]
86
+ : [slot],
87
+ )
88
+ return { input: text.join(' '), gold: [row.id], group, vocab: [filler] }
89
+ })
90
+ }
91
+
92
+ /** The rule baseline: the row sharing the most words with the request, the first on a tie. */
93
+ function overlap(input: string): Result {
94
+ const seen = new Set(words(input))
95
+ let best = table[0]?.id ?? ''
96
+ let most = -1
97
+ for (const row of table) {
98
+ const shared = words(row.text).filter((word) => seen.has(word)).length
99
+ if (shared > most) {
100
+ most = shared
101
+ best = row.id
102
+ }
103
+ }
104
+ return best
105
+ }
106
+
107
+ export default defineEval(model, {
108
+ sets: { train: 'data/train/*.jsonl', dev: 'data/dev/*.jsonl', test: sealed('data/test/*.jsonl') },
109
+ data: defineDataset<Result>({
110
+ seed: 1,
111
+ minSize: { train: 400, dev: 80, test: 80 },
112
+ generate: {
113
+ train: requests(
114
+ {
115
+ 'train-want': ['I', 'want', '{filler}', '{row}'],
116
+ 'train-give': ['give', 'me', '{row}', '{filler}'],
117
+ 'train-instead': ['{row}', 'instead', 'of', '{other}', '{filler}'],
118
+ 'train-not': ['not', '{other}', 'but', '{row}', '{filler}'],
119
+ },
120
+ ['now', 'quickly', 'again', 'too', 'tonight', 'here'],
121
+ 400,
122
+ ),
123
+ dev: requests(
124
+ {
125
+ 'dev-like': ['I', 'would', 'like', '{row}', '{filler}'],
126
+ 'dev-instead': ['{filler}', 'bring', '{row}', 'instead', 'of', '{other}'],
127
+ },
128
+ ['soon', 'later'],
129
+ 80,
130
+ ),
131
+ test: requests(
132
+ {
133
+ 'test-can': ['can', 'I', 'have', '{row}', '{filler}'],
134
+ 'test-not': ['for', '{filler}', 'not', '{other}', 'but', '{row}'],
135
+ },
136
+ ['lunch', 'dinner'],
137
+ 80,
138
+ ),
139
+ },
140
+ }),
141
+ train: { seeds: [1, 2, 3], epochs: 15, batch: 16, learningRate: 0.02, warmup: 0.1, budgetSeconds: 30, negatives: 6 },
142
+ decode,
143
+ metric: (pred, gold) => (pred === gold ? 1 : 0),
144
+ baselines: { overlap },
145
+ gate: { floors: 'promoted', noise: 0.05 },
146
+ parity: { tolerance: 1e-3 },
147
+ ship: { brotliBytes: 40_000, files: ['dist/index.mjs', 'dist/index.d.mts'] },
148
+ table: 'data/table.jsonl',
149
+ })
@@ -0,0 +1,12 @@
1
+ // The model: what it reads, its layers and its head. SPEC.md says what it is for; a change to that lands there first.
2
+ // A retrieve head scores the input against every row of the table with one shared tower.
3
+ import { defineModel, features as f, heads as h, int6, layers as l } from 'gpu-engine'
4
+
5
+ export default defineModel({
6
+ name: 'NEW_MODEL_NAME',
7
+ input: f.tokens({ max: 12, rows: [f.shape(), f.hash({ buckets: 256, k: 2 })] }),
8
+ net: [l.embed({ size: 16 }), l.dense({ size: 16, activation: 'tanh' })],
9
+ head: h.retrieve({ size: 16 }),
10
+ quant: int6({ qatFrom: 0.7 }),
11
+ budgets: { brotliBytes: 8_000, macsPerToken: 1_000 },
12
+ })
@@ -0,0 +1,33 @@
1
+ # NEW_MODEL_NAME spec
2
+
3
+ This file is the source of truth for this model. A change to what it does lands here first, then in the eval, then in the model or the data.
4
+
5
+ ## Task
6
+
7
+ Read a request for one dish and return the id of its row in `data/table.jsonl`. A request may name the dish by the plural of its ingredient, and may name a second dish it does not want.
8
+
9
+ | Input | Result |
10
+ | ------------------------------------------ | ------------- |
11
+ | `I want now tomato soup` | `tomato-soup` |
12
+ | `give me pie with cherries again` | `cherry-pie` |
13
+ | `not lemon cake but salad with beans here` | `bean-salad` |
14
+
15
+ The model is a `retrieve` head: one tower encodes the request and every table row, and the score of a row is the dot product of the two. `run` returns every row ranked; `src/decode.ts` keeps the best row's id.
16
+
17
+ ## Data
18
+
19
+ `data/table.jsonl` holds the rows, one `{ "id", "text" }` per line. It is an input, not a split, and its hash is locked like the sets. The build copies it into `src/table.ts` for the shipped entry.
20
+
21
+ `NEW_MODEL_NAME.eval.ts` generates three sets with a fixed seed the first time `gpu-engine loop` runs: train, dev and the sealed test set. Each set uses its own sentence frames, recorded as the row's `group`, and its own filler words, recorded as the row's `vocab`, so the data checks prove that dev and test ask in ways the model never trained on. The dish words, their plurals, `with`, `instead of` and `not ... but` are shared by every set.
22
+
23
+ ## Judged by
24
+
25
+ - Metric: 1 when the best row is the row asked for, else 0. The set score is the mean (recall at 1).
26
+ - Rule baseline `overlap`: the row sharing the most words with the request, the first on a tie. It misses a plural ingredient and cannot tell the wanted dish from the unwanted one.
27
+ - The model must beat the baseline on dev before a promotion is worth it. The oracle row shows the ceiling the decode step allows.
28
+ - The gate: each set's score at least the promoted score minus `noise`, within the budgets in `NEW_MODEL_NAME.model.ts`.
29
+ - Room to tune: the starter tower reads each word on its own, so `tomato soup instead of onion soup` and `onion soup instead of tomato soup` look the same to it, and the first `loop` misses many of the requests that name two dishes. Adding `conv({ taps: 3 })` after `embed` lets each word see `of` or `not` next to it.
30
+
31
+ ## Ship
32
+
33
+ `gpu-engine promote` writes `weights/NEW_MODEL_NAME.bin` and `src/weights.ts`. `npm run build` writes `src/table.ts` from the eval's table, `dist/index.mjs` and its types, `dist/index.d.mts`; the module exports `load({ backend, gpu? })`; `run(text)` returns `[error, result]` and never throws.