relu-trace 0.0.0-stage → 0.1.0
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 +39 -2
- package/dist/browser.d.ts +11 -0
- package/dist/browser.js +389 -0
- package/dist/builder.d.ts +6 -0
- package/dist/builder.js +16 -0
- package/dist/compare.d.ts +7 -0
- package/dist/compare.js +23 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +4 -0
- package/dist/inspector-css.d.ts +1 -0
- package/dist/inspector-css.js +77 -0
- package/dist/model.d.ts +125 -0
- package/dist/model.js +169 -0
- package/dist/runtime.d.ts +19 -0
- package/dist/runtime.js +157 -0
- package/docs/contribute.md +17 -0
- package/docs/explore.md +11 -0
- package/docs/integrate.md +52 -0
- package/docs/machine-v1.md +36 -0
- package/package.json +59 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Daniel Rodríguez
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,40 @@
|
|
|
1
|
-
#
|
|
1
|
+
# ReLU Trace
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**A browser debugger for hand-built ReLU state machines.** Step the actual circuit, inspect the numbers that drove a branch, and replay from the same state with one activation set to zero.
|
|
4
|
+
|
|
5
|
+
The circuit's weights specify the rule; the registers and RAM supply the values the rule operates on. On each tick, the host reads the old state, evaluates a named block of sparse affine + ReLU gates, and applies the outputs as register updates, RAM writes, and a next instruction or halt. ReLU Trace shows both the computation and what it changed.
|
|
6
|
+
|
|
7
|
+
## Start here
|
|
8
|
+
|
|
9
|
+
- [Open the public playground](https://sadasant.github.io/ReLU-Trace/): no install or GitHub sign-in required. Follow the [Explore guide](docs/explore.md) to change a branch without changing its RAM write.
|
|
10
|
+
- [Integrate the package](docs/integrate.md): build a machine or map an existing graph, mount a debugger, and run a Node assertion over the same machine.
|
|
11
|
+
- [Contribute a fixture](docs/contribute.md): follow a tick through the runtime and add a test that would catch a wrong transition.
|
|
12
|
+
- [Machine format and tick semantics](docs/machine-v1.md): the contract shared by the builder, runtime, and debugger.
|
|
13
|
+
|
|
14
|
+
To serve the playground locally with Node 22+ and Python 3:
|
|
15
|
+
|
|
16
|
+
```sh
|
|
17
|
+
npm ci
|
|
18
|
+
npm test
|
|
19
|
+
npm run build:playground
|
|
20
|
+
python3 -m http.server 8080 --bind 127.0.0.1 --directory site
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Open `http://127.0.0.1:8080/`. For static hosting, publish the generated `site/` directory as a unit. No backend, transpiler in the browser, or telemetry is required.
|
|
24
|
+
|
|
25
|
+
To update the public site, wait for `Check` on `main` to pass, then run **Publish playground** from `main` in **Actions**. The workflow uploads only `site/`. The built browser JavaScript and example data are public; repository access is unchanged.
|
|
26
|
+
|
|
27
|
+
## What you can use
|
|
28
|
+
|
|
29
|
+
| Import | What it gives you |
|
|
30
|
+
| --- | --- |
|
|
31
|
+
| `relu-trace` | ESM builder, deterministic runtime (`createSession`, `Session`), named traces, structured `ReluTraceError` codes, and a reference comparison helper. Node and browser, no DOM or runtime dependencies. |
|
|
32
|
+
| `relu-trace/browser` | A Trusted-Types-safe, themeable Shadow DOM inspector with step/run/pause/run-to-end/reset, speed control, signal breakdowns, reference comparison, single-activation clamp & clear, expandable RAM banks, and lifecycle callbacks. |
|
|
33
|
+
|
|
34
|
+
Want just the runtime? Give it a machine definition and a starting snapshot. The builder is optional. The inspector opens a separate session and does not attach to a live app. This is for small, designed circuits with bounded integer state, not for training models, importing checkpoints, proving all executions correct, or replacing a tensor runtime.
|
|
35
|
+
|
|
36
|
+
## Supported and checked
|
|
37
|
+
|
|
38
|
+
CI runs linting, TypeScript checks, `npm audit`, the headless API test suite, and an installation of the packed package on Node 22, 24, and 26. It exercises the playground (including custom JSON loading) and installed package in Chromium, Firefox, and WebKit, including exact trace parity for the examples. WebKit in CI is not a test on an Apple device. Run `npm run test:package` to verify the tarball, or see the [contributor guide](docs/contribute.md) for browser setup.
|
|
39
|
+
|
|
40
|
+
**Release & license:** MIT licensed ([`LICENSE`](LICENSE)). Tagged `v*.*.*` releases publish to npm with provenance via [`.github/workflows/release.yml`](.github/workflows/release.yml); locally, run `npm pack` to install a tarball directly.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { Machine, Reference, Snapshot, Status, Trace } from './index.js';
|
|
2
|
+
export type InspectorOptions = {
|
|
3
|
+
machine: Machine;
|
|
4
|
+
initial: Snapshot;
|
|
5
|
+
limit?: number;
|
|
6
|
+
reference?: Reference;
|
|
7
|
+
onTick?: (trace: Trace, snapshot: Snapshot) => void;
|
|
8
|
+
onStatusChange?: (status: Status, snapshot: Snapshot) => void;
|
|
9
|
+
};
|
|
10
|
+
/** Mount a separate debug session. The returned function removes it and stops the clock. */
|
|
11
|
+
export declare function mountInspector(container: HTMLElement, options: InspectorOptions): () => void;
|
package/dist/browser.js
ADDED
|
@@ -0,0 +1,389 @@
|
|
|
1
|
+
import { compareTick, createSession } from './index.js';
|
|
2
|
+
import { cloneInput, inRange, requireRecord } from './model.js';
|
|
3
|
+
import { inspectorCSS } from './inspector-css.js';
|
|
4
|
+
const PREVIEW_CELLS = 16;
|
|
5
|
+
function attachStyles(doc, root) {
|
|
6
|
+
const Sheet = doc.defaultView?.CSSStyleSheet ?? globalThis.CSSStyleSheet;
|
|
7
|
+
if (typeof Sheet === 'function' && 'adoptedStyleSheets' in root && 'replaceSync' in Sheet.prototype) {
|
|
8
|
+
const sheet = new Sheet();
|
|
9
|
+
sheet.replaceSync(inspectorCSS);
|
|
10
|
+
root.adoptedStyleSheets = [sheet];
|
|
11
|
+
return;
|
|
12
|
+
}
|
|
13
|
+
const style = doc.createElement('style');
|
|
14
|
+
style.textContent = inspectorCSS;
|
|
15
|
+
root.append(style);
|
|
16
|
+
}
|
|
17
|
+
/** Mount a separate debug session. The returned function removes it and stops the clock. */
|
|
18
|
+
export function mountInspector(container, options) {
|
|
19
|
+
requireRecord(options, 'Inspector options');
|
|
20
|
+
const { machine, initial, limit = 128, reference, onTick, onStatusChange } = options;
|
|
21
|
+
inRange(limit, { min: 1, max: 1000 }, 'Inspector tick limit', 'VALIDATION_ERROR', 'Inspector options.limit');
|
|
22
|
+
const definition = cloneInput(machine, 'Machine');
|
|
23
|
+
const start = cloneInput(initial, 'Snapshot');
|
|
24
|
+
const fresh = (clamp) => createSession(definition, start, { limit, clamp });
|
|
25
|
+
let session = fresh();
|
|
26
|
+
let lastStatus = session.status;
|
|
27
|
+
let history = [];
|
|
28
|
+
let selected;
|
|
29
|
+
let signal = '';
|
|
30
|
+
let timer;
|
|
31
|
+
let intervalMs = 350;
|
|
32
|
+
let referenceFinding;
|
|
33
|
+
let referenceError;
|
|
34
|
+
let intervention;
|
|
35
|
+
let replayFinding;
|
|
36
|
+
const expandedBanks = new Set();
|
|
37
|
+
const doc = container.ownerDocument;
|
|
38
|
+
const host = doc.createElement('div');
|
|
39
|
+
const root = host.attachShadow({ mode: 'open' });
|
|
40
|
+
attachStyles(doc, root);
|
|
41
|
+
function element(tag, text, css, attrs) {
|
|
42
|
+
const node = doc.createElement(tag);
|
|
43
|
+
if (text !== undefined)
|
|
44
|
+
node.textContent = text;
|
|
45
|
+
if (css)
|
|
46
|
+
node.className = css;
|
|
47
|
+
if (attrs) {
|
|
48
|
+
for (const [key, value] of Object.entries(attrs))
|
|
49
|
+
node.setAttribute(key, value);
|
|
50
|
+
}
|
|
51
|
+
return node;
|
|
52
|
+
}
|
|
53
|
+
function buttonEl(label, css) {
|
|
54
|
+
const node = element('button', label, css);
|
|
55
|
+
node.type = 'button';
|
|
56
|
+
return node;
|
|
57
|
+
}
|
|
58
|
+
function option(id, label) {
|
|
59
|
+
const node = element('option', label);
|
|
60
|
+
node.value = id;
|
|
61
|
+
return node;
|
|
62
|
+
}
|
|
63
|
+
// Build Shadow DOM without innerHTML for Trusted Types and strict CSP compatibility.
|
|
64
|
+
const inspector = element('div', undefined, 'inspector', { role: 'region', 'aria-label': 'ReLU Trace inspector' });
|
|
65
|
+
const toolbar = element('div', undefined, 'toolbar');
|
|
66
|
+
const actions = element('div', undefined, 'actions', { role: 'group', 'aria-label': 'Execution controls' });
|
|
67
|
+
const step = buttonEl('Step', 'primary');
|
|
68
|
+
const run = buttonEl('Run');
|
|
69
|
+
const pause = buttonEl('Pause');
|
|
70
|
+
const runToEnd = buttonEl('Run to end');
|
|
71
|
+
const reset = buttonEl('Reset');
|
|
72
|
+
const selectSpeed = element('select');
|
|
73
|
+
selectSpeed.append(option('350', '1×'), option('100', '3×'), option('20', 'Fast'));
|
|
74
|
+
selectSpeed.value = String(intervalMs);
|
|
75
|
+
const speedLabel = element('label');
|
|
76
|
+
speedLabel.append('Speed ', selectSpeed);
|
|
77
|
+
actions.append(step, run, pause, runToEnd, reset, speedLabel);
|
|
78
|
+
const meter = element('div', undefined, 'meter');
|
|
79
|
+
const statusEl = element('strong', undefined, undefined, { id: 'status', role: 'status' });
|
|
80
|
+
const countEl = element('span');
|
|
81
|
+
meter.append(statusEl, countEl);
|
|
82
|
+
toolbar.append(actions, meter);
|
|
83
|
+
const comparison = element('div', undefined, 'comparison', { role: 'status' });
|
|
84
|
+
const panels = element('div', undefined, 'panels');
|
|
85
|
+
const tracePanel = element('section', undefined, 'panel', { 'aria-labelledby': 'trace-title' });
|
|
86
|
+
const traceHead = element('div', undefined, 'panel-head');
|
|
87
|
+
const traceTitle = element('h3', 'Tick trace', undefined, { id: 'trace-title' });
|
|
88
|
+
const selectTick = element('select');
|
|
89
|
+
const historyLabel = element('label');
|
|
90
|
+
historyLabel.append('History ', selectTick);
|
|
91
|
+
traceHead.append(traceTitle, historyLabel);
|
|
92
|
+
const traceBody = element('div', undefined, 'panel-body');
|
|
93
|
+
tracePanel.append(traceHead, traceBody);
|
|
94
|
+
const gatePanel = element('section', undefined, 'panel', { 'aria-labelledby': 'gate-title' });
|
|
95
|
+
const gateHead = element('div', undefined, 'panel-head');
|
|
96
|
+
const gateTitle = element('h3', 'Activation', undefined, { id: 'gate-title' });
|
|
97
|
+
const selectSignal = element('select');
|
|
98
|
+
const signalLabel = element('label');
|
|
99
|
+
signalLabel.append('Signal ', selectSignal);
|
|
100
|
+
gateHead.append(gateTitle, signalLabel);
|
|
101
|
+
const gateBody = element('div', undefined, 'panel-body');
|
|
102
|
+
const gateFoot = element('div', undefined, 'panel-foot');
|
|
103
|
+
const clamp = buttonEl('Clamp to zero & replay');
|
|
104
|
+
const clearClamp = buttonEl('Clear clamp');
|
|
105
|
+
clearClamp.hidden = true;
|
|
106
|
+
gateFoot.append(clamp, clearClamp);
|
|
107
|
+
gatePanel.append(gateHead, gateBody, gateFoot);
|
|
108
|
+
panels.append(tracePanel, gatePanel);
|
|
109
|
+
const stateSection = element('section', undefined, 'state', { 'aria-labelledby': 'state-title' });
|
|
110
|
+
const stateTitle = element('h3', 'Session state ', undefined, { id: 'state-title' });
|
|
111
|
+
const stateCount = element('span');
|
|
112
|
+
stateTitle.append(stateCount);
|
|
113
|
+
const stateBody = element('div');
|
|
114
|
+
stateSection.append(stateTitle, stateBody);
|
|
115
|
+
inspector.append(toolbar, comparison, panels, stateSection);
|
|
116
|
+
root.append(inspector);
|
|
117
|
+
const instructions = (id) => id ?? 'Halt';
|
|
118
|
+
function notifyStatus(snapshot) {
|
|
119
|
+
if (session.status !== lastStatus) {
|
|
120
|
+
lastStatus = session.status;
|
|
121
|
+
onStatusChange?.(session.status, snapshot);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
function termsTable(rows) {
|
|
125
|
+
const table = element('table');
|
|
126
|
+
const [columns, ...body] = rows;
|
|
127
|
+
const header = table.createTHead().insertRow();
|
|
128
|
+
header.append(...columns.map(text => {
|
|
129
|
+
const th = element('th', text);
|
|
130
|
+
th.scope = 'col';
|
|
131
|
+
return th;
|
|
132
|
+
}));
|
|
133
|
+
const tbody = table.createTBody();
|
|
134
|
+
for (const row of body)
|
|
135
|
+
tbody.insertRow().append(...row.map(text => element('td', text)));
|
|
136
|
+
return table;
|
|
137
|
+
}
|
|
138
|
+
function group(parent, title, rows, empty = 'None') {
|
|
139
|
+
const list = element('dl');
|
|
140
|
+
for (const [name, value] of rows) {
|
|
141
|
+
const dd = element('dd');
|
|
142
|
+
if (typeof value === 'string')
|
|
143
|
+
dd.textContent = value;
|
|
144
|
+
else
|
|
145
|
+
dd.append(value);
|
|
146
|
+
list.append(element('dt', name), dd);
|
|
147
|
+
}
|
|
148
|
+
parent.append(element('h4', title), rows.length ? list : element('p', empty, 'muted small'));
|
|
149
|
+
}
|
|
150
|
+
function setTick(tick) {
|
|
151
|
+
selected = tick;
|
|
152
|
+
const gates = tick?.gates ?? [];
|
|
153
|
+
const branch = tick?.branch?.signal;
|
|
154
|
+
signal = branch && gates.some(gate => gate.id === branch) ? branch : (gates.at(-1)?.id ?? '');
|
|
155
|
+
selectSignal.replaceChildren(...(gates.length ? gates.map(gate => option(gate.id, gate.id)) : [option('', 'No activation')]));
|
|
156
|
+
selectSignal.value = signal;
|
|
157
|
+
selectTick.value = String(tick?.tick ?? '');
|
|
158
|
+
}
|
|
159
|
+
function renderSignal() {
|
|
160
|
+
const gate = selected?.gates.find(entry => entry.id === signal);
|
|
161
|
+
gateBody.replaceChildren();
|
|
162
|
+
selectSignal.disabled = !selected?.gates.length;
|
|
163
|
+
clamp.disabled = !gate || timer !== undefined || intervention !== undefined;
|
|
164
|
+
clearClamp.hidden = intervention === undefined;
|
|
165
|
+
clearClamp.disabled = timer !== undefined;
|
|
166
|
+
if (!gate) {
|
|
167
|
+
gateBody.append(element('p', selected ? 'No activation was evaluated on this tick.' : 'Inspect a named ReLU after stepping. Its weighted inputs, bias and actual output appear here.', 'muted'));
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
const overridden = intervention?.tick === selected?.tick && intervention?.signal === signal;
|
|
171
|
+
const equation = `ReLU(${gate.bias}${gate.terms.map(t => ` ${t.product < 0 ? '−' : '+'} ${Math.abs(t.product)}`).join('')}) = ${gate.activation}`;
|
|
172
|
+
gateBody.append(element('p', equation, 'equation'), element('p', overridden ? `Clamped output: ${gate.output}` : `Signal output: ${gate.output}`, 'muted small'));
|
|
173
|
+
gateBody.append(termsTable([['Input', 'Value', 'Weight', 'Product'], ...gate.terms.map(t => [t.from, String(t.input), String(t.weight), String(t.product)])]));
|
|
174
|
+
}
|
|
175
|
+
function renderTrace() {
|
|
176
|
+
traceBody.replaceChildren();
|
|
177
|
+
if (!selected) {
|
|
178
|
+
traceBody.append(element('p', 'No ticks yet. Step executes one instruction; Run starts the clock.', 'muted'));
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
const { instruction, inputs, reads, branch } = selected;
|
|
182
|
+
if (selected.outcome === 'invalid')
|
|
183
|
+
traceBody.append(element('p', `${instruction}: ${selected.error}. No changes committed.`, 'error'));
|
|
184
|
+
else {
|
|
185
|
+
const { next, changes, writes } = selected.transition;
|
|
186
|
+
traceBody.append(element('p', `${instruction} → ${instructions(next)}`, 'equation'));
|
|
187
|
+
traceBody.append(element('p', branch ? `${branch.signal} = ${branch.value} selected the branch.` : 'Unconditional transition.', 'muted small'));
|
|
188
|
+
group(traceBody, 'RAM writes', writes.map(w => [`${w.bank}[${w.address}]`, `${w.before} → ${w.value}`]));
|
|
189
|
+
group(traceBody, 'Register changes', Object.entries(changes).map(([name, v]) => [name, `${v.before} → ${v.value}`]));
|
|
190
|
+
}
|
|
191
|
+
group(traceBody, 'Pre-tick inputs', [
|
|
192
|
+
...inputs.map(({ id, register, value }) => [id === register ? id : `${id} (${register})`, String(value)]),
|
|
193
|
+
...reads.map(({ id, bank, address, value }) => [`${id} (${bank}[${address}])`, String(value)]),
|
|
194
|
+
]);
|
|
195
|
+
}
|
|
196
|
+
function renderBankValue(bank, cells) {
|
|
197
|
+
if (cells.length <= PREVIEW_CELLS)
|
|
198
|
+
return cells.join(' · ');
|
|
199
|
+
const expanded = expandedBanks.has(bank);
|
|
200
|
+
const wrap = element('span', undefined, 'bank-value');
|
|
201
|
+
const text = expanded
|
|
202
|
+
? cells.join(' · ')
|
|
203
|
+
: `${cells.slice(0, PREVIEW_CELLS).join(' · ')} … (${cells.length} cells)`;
|
|
204
|
+
const toggle = buttonEl(expanded ? `Show first ${PREVIEW_CELLS}` : `Show all (${cells.length})`, 'bank-toggle');
|
|
205
|
+
toggle.onclick = () => {
|
|
206
|
+
if (expanded)
|
|
207
|
+
expandedBanks.delete(bank);
|
|
208
|
+
else
|
|
209
|
+
expandedBanks.add(bank);
|
|
210
|
+
render();
|
|
211
|
+
};
|
|
212
|
+
wrap.append(element('span', text), toggle);
|
|
213
|
+
return wrap;
|
|
214
|
+
}
|
|
215
|
+
function render() {
|
|
216
|
+
const snapshot = session.snapshot();
|
|
217
|
+
const running = timer !== undefined;
|
|
218
|
+
const at = session.status === 'running' ? (running ? 'Running' : 'Paused') :
|
|
219
|
+
{ halt: 'Halted', budget: 'Budget reached', invalid: 'Invalid' }[session.status];
|
|
220
|
+
statusEl.textContent = at;
|
|
221
|
+
statusEl.dataset.kind = session.status;
|
|
222
|
+
countEl.textContent = `Tick ${session.ticks} / ${limit}`;
|
|
223
|
+
stateCount.textContent = `after tick ${session.ticks}`;
|
|
224
|
+
step.disabled = run.disabled = runToEnd.disabled = running || session.status !== 'running';
|
|
225
|
+
pause.disabled = !running;
|
|
226
|
+
selectTick.disabled = history.length === 0;
|
|
227
|
+
const finding = intervention ? replayFinding : referenceFinding;
|
|
228
|
+
const label = intervention ? `CLAMP / ${intervention.signal} at tick ${intervention.tick}` : 'REFERENCE';
|
|
229
|
+
comparison.dataset.kind = !intervention && referenceError ? 'error' : finding ? 'diff' : '';
|
|
230
|
+
comparison.hidden = !intervention && !reference;
|
|
231
|
+
const summary = finding ? `First difference · tick ${finding.tick} · ${finding.diff.field}: ${finding.diff.expected} → ${finding.diff.actual}`
|
|
232
|
+
: intervention ? 'No observable transition changed within the tick limit.'
|
|
233
|
+
: referenceError ? `Reference failed: ${referenceError}`
|
|
234
|
+
: session.ticks ? 'No difference in the observed ticks.' : 'Waiting for the first tick.';
|
|
235
|
+
comparison.replaceChildren(element('strong', label), element('span', summary));
|
|
236
|
+
if (finding?.sameWrites)
|
|
237
|
+
comparison.append(element('span', 'RAM writes unchanged at that tick.', 'muted'));
|
|
238
|
+
renderTrace();
|
|
239
|
+
renderSignal();
|
|
240
|
+
const banks = Object.entries(snapshot.ram).map(([bank, cells]) => [bank, renderBankValue(bank, cells)]);
|
|
241
|
+
stateBody.replaceChildren();
|
|
242
|
+
group(stateBody, 'Next & registers', [['Next instruction', instructions(snapshot.instruction)], ...Object.entries(snapshot.registers).map(([k, v]) => [k, String(v)])]);
|
|
243
|
+
group(stateBody, 'RAM (address 0 onward)', banks);
|
|
244
|
+
}
|
|
245
|
+
const tickOption = (tick) => option(String(tick.tick), `${tick.tick} · ${tick.instruction}`);
|
|
246
|
+
function loadHistory(records) {
|
|
247
|
+
history = records;
|
|
248
|
+
selectTick.replaceChildren(...(history.length ? history.map(tickOption) : [option('', 'No ticks')]));
|
|
249
|
+
setTick(history.at(-1));
|
|
250
|
+
}
|
|
251
|
+
function stopClock() {
|
|
252
|
+
clearInterval(timer);
|
|
253
|
+
timer = undefined;
|
|
254
|
+
}
|
|
255
|
+
function stepOnce() {
|
|
256
|
+
const before = reference && !referenceFinding && !referenceError ? session.snapshot() : undefined;
|
|
257
|
+
const tick = session.step();
|
|
258
|
+
if (!tick)
|
|
259
|
+
return undefined;
|
|
260
|
+
if (before && reference) {
|
|
261
|
+
try {
|
|
262
|
+
const diff = compareTick(reference(before), tick);
|
|
263
|
+
if (diff)
|
|
264
|
+
referenceFinding = { tick: tick.tick, diff };
|
|
265
|
+
}
|
|
266
|
+
catch (error) {
|
|
267
|
+
referenceError = error instanceof Error ? error.message : String(error);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
if (!history.length)
|
|
271
|
+
selectTick.replaceChildren();
|
|
272
|
+
history.push(tick);
|
|
273
|
+
selectTick.append(tickOption(tick));
|
|
274
|
+
const snapshot = session.snapshot();
|
|
275
|
+
onTick?.(tick, snapshot);
|
|
276
|
+
notifyStatus(snapshot);
|
|
277
|
+
return tick;
|
|
278
|
+
}
|
|
279
|
+
function advance() {
|
|
280
|
+
if (!host.isConnected) {
|
|
281
|
+
stopClock();
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
284
|
+
const tick = stepOnce();
|
|
285
|
+
if (!tick) {
|
|
286
|
+
stopClock();
|
|
287
|
+
render();
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
setTick(tick);
|
|
291
|
+
if (session.status !== 'running')
|
|
292
|
+
stopClock();
|
|
293
|
+
render();
|
|
294
|
+
}
|
|
295
|
+
step.onclick = advance;
|
|
296
|
+
run.onclick = () => {
|
|
297
|
+
if (timer !== undefined || session.status !== 'running')
|
|
298
|
+
return;
|
|
299
|
+
timer = setInterval(advance, intervalMs);
|
|
300
|
+
render();
|
|
301
|
+
};
|
|
302
|
+
pause.onclick = () => { stopClock(); render(); };
|
|
303
|
+
runToEnd.onclick = () => {
|
|
304
|
+
if (timer !== undefined || session.status !== 'running')
|
|
305
|
+
return;
|
|
306
|
+
let last;
|
|
307
|
+
while (session.status === 'running') {
|
|
308
|
+
const tick = stepOnce();
|
|
309
|
+
if (!tick)
|
|
310
|
+
break;
|
|
311
|
+
last = tick;
|
|
312
|
+
}
|
|
313
|
+
if (last)
|
|
314
|
+
setTick(last);
|
|
315
|
+
render();
|
|
316
|
+
};
|
|
317
|
+
selectSpeed.onchange = () => {
|
|
318
|
+
intervalMs = Number(selectSpeed.value);
|
|
319
|
+
if (timer !== undefined) {
|
|
320
|
+
stopClock();
|
|
321
|
+
timer = setInterval(advance, intervalMs);
|
|
322
|
+
}
|
|
323
|
+
};
|
|
324
|
+
reset.onclick = () => {
|
|
325
|
+
stopClock();
|
|
326
|
+
session = fresh();
|
|
327
|
+
intervention = replayFinding = referenceFinding = referenceError = undefined;
|
|
328
|
+
loadHistory([]);
|
|
329
|
+
notifyStatus(session.snapshot());
|
|
330
|
+
render();
|
|
331
|
+
};
|
|
332
|
+
selectTick.onchange = () => { setTick(history[Number(selectTick.value) - 1]); render(); };
|
|
333
|
+
selectSignal.onchange = () => { signal = selectSignal.value; renderSignal(); };
|
|
334
|
+
clamp.onclick = () => {
|
|
335
|
+
if (!selected || !signal)
|
|
336
|
+
return;
|
|
337
|
+
intervention = { tick: selected.tick, instruction: selected.instruction, signal };
|
|
338
|
+
const baseline = fresh().run({ trace: true });
|
|
339
|
+
session = fresh(intervention);
|
|
340
|
+
const replay = session.run({ trace: true });
|
|
341
|
+
for (const expected of baseline) {
|
|
342
|
+
const actual = replay[expected.tick - 1];
|
|
343
|
+
// A run can only end earlier after a previous difference in target or outcome.
|
|
344
|
+
if (!actual)
|
|
345
|
+
break;
|
|
346
|
+
const diff = expected.outcome === 'committed' ? compareTick(expected.transition, actual)
|
|
347
|
+
: actual.outcome === 'invalid' && expected.error === actual.error ? undefined
|
|
348
|
+
: { field: 'Outcome', expected: expected.error, actual: actual.outcome === 'invalid' ? actual.error : 'Committed' };
|
|
349
|
+
if (diff) {
|
|
350
|
+
const sameWrites = expected.outcome === 'committed' && actual.outcome === 'committed' &&
|
|
351
|
+
expected.transition.writes.length > 0 &&
|
|
352
|
+
JSON.stringify(expected.transition.writes) === JSON.stringify(actual.transition.writes);
|
|
353
|
+
replayFinding = { tick: actual.tick, diff, sameWrites };
|
|
354
|
+
break;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
loadHistory(replay);
|
|
358
|
+
setTick(replay[(replayFinding?.tick ?? intervention.tick) - 1]);
|
|
359
|
+
if (selected?.tick === intervention.tick && selected.gates.some(g => g.id === intervention.signal)) {
|
|
360
|
+
selectSignal.value = signal = intervention.signal;
|
|
361
|
+
}
|
|
362
|
+
notifyStatus(session.snapshot());
|
|
363
|
+
render();
|
|
364
|
+
};
|
|
365
|
+
clearClamp.onclick = () => {
|
|
366
|
+
if (!intervention || timer !== undefined)
|
|
367
|
+
return;
|
|
368
|
+
const targetTick = selected?.tick ?? intervention.tick;
|
|
369
|
+
const targetSignal = signal;
|
|
370
|
+
session = fresh();
|
|
371
|
+
intervention = replayFinding = referenceFinding = referenceError = undefined;
|
|
372
|
+
history = [];
|
|
373
|
+
selectTick.replaceChildren(option('', 'No ticks'));
|
|
374
|
+
for (let i = 0; i < targetTick && session.status === 'running'; i++) {
|
|
375
|
+
stepOnce();
|
|
376
|
+
}
|
|
377
|
+
const restored = history[targetTick - 1] ?? history.at(-1);
|
|
378
|
+
setTick(restored);
|
|
379
|
+
if (restored?.gates.some(g => g.id === targetSignal)) {
|
|
380
|
+
selectSignal.value = signal = targetSignal;
|
|
381
|
+
}
|
|
382
|
+
notifyStatus(session.snapshot());
|
|
383
|
+
render();
|
|
384
|
+
};
|
|
385
|
+
loadHistory([]);
|
|
386
|
+
render();
|
|
387
|
+
container.append(host);
|
|
388
|
+
return () => { stopClock(); host.remove(); };
|
|
389
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { type Bank, type Gate, type Instruction, type Machine, type Range } from './model.js';
|
|
2
|
+
/** One shot: make a fresh definition from named instruction blocks. */
|
|
3
|
+
export declare function defineMachine(registers: Record<string, Range>, banks: Record<string, Bank>, instructions: Record<string, Instruction>, entry: string): Machine;
|
|
4
|
+
export declare function relu(id: string, bias: number, weights: Record<string, number>): Gate;
|
|
5
|
+
/** 1 if left > right, else 0, for integer inputs. Emits three ordered gates. */
|
|
6
|
+
export declare function greaterThan(id: string, left: string, right: string): Gate[];
|
package/dist/builder.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { parseMachine } from './model.js';
|
|
2
|
+
/** One shot: make a fresh definition from named instruction blocks. */
|
|
3
|
+
export function defineMachine(registers, banks, instructions, entry) {
|
|
4
|
+
return parseMachine({ version: 1, entry, registers, banks, instructions });
|
|
5
|
+
}
|
|
6
|
+
export function relu(id, bias, weights) {
|
|
7
|
+
return { id, bias, terms: Object.entries(weights).map(([from, weight]) => ({ from, weight })) };
|
|
8
|
+
}
|
|
9
|
+
/** 1 if left > right, else 0, for integer inputs. Emits three ordered gates. */
|
|
10
|
+
export function greaterThan(id, left, right) {
|
|
11
|
+
const difference = `${id}_difference`;
|
|
12
|
+
const excess = `${id}_excess`;
|
|
13
|
+
const weights = left === right ? {} : { [left]: 1, [right]: -1 };
|
|
14
|
+
return [relu(difference, 0, weights), relu(excess, -1, { [difference]: 1 }),
|
|
15
|
+
relu(id, 0, { [difference]: 1, [excess]: -1 })];
|
|
16
|
+
}
|
package/dist/compare.js
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export function compareTick(expected, actual) {
|
|
2
|
+
if (actual.outcome === 'invalid')
|
|
3
|
+
return { field: 'Outcome', expected: 'Committed', actual: actual.error };
|
|
4
|
+
const result = actual.transition;
|
|
5
|
+
if (expected.next !== result.next)
|
|
6
|
+
return { field: 'Next instruction', expected: expected.next ?? 'Halt', actual: result.next ?? 'Halt' };
|
|
7
|
+
for (let i = 0; i < Math.max(expected.writes.length, result.writes.length); i++) {
|
|
8
|
+
const a = expected.writes[i];
|
|
9
|
+
const b = result.writes[i];
|
|
10
|
+
if (a?.bank !== b?.bank || a?.address !== b?.address || a?.value !== b?.value) {
|
|
11
|
+
const formatWrite = (write) => write ? `${write.bank}[${write.address}] ← ${write.value}` : 'No write';
|
|
12
|
+
return { field: `RAM write ${i + 1}`, expected: formatWrite(a), actual: formatWrite(b) };
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
for (const reg of [...new Set([...Object.keys(expected.changes), ...Object.keys(result.changes)])].sort()) {
|
|
16
|
+
const exp = Object.hasOwn(expected.changes, reg) ? expected.changes[reg] : undefined;
|
|
17
|
+
const act = Object.hasOwn(result.changes, reg) ? result.changes[reg] : undefined;
|
|
18
|
+
const a = exp && exp.before !== exp.value ? exp.value : undefined;
|
|
19
|
+
const b = act && act.before !== act.value ? act.value : undefined;
|
|
20
|
+
if (a !== b)
|
|
21
|
+
return { field: `Register ${reg}`, expected: String(a ?? 'Unchanged'), actual: String(b ?? 'Unchanged') };
|
|
22
|
+
}
|
|
23
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export type { Bank, Clamp, Control, ErrorCode, Gate, GateTrace, Instruction, Machine, Range, Reference, Snapshot, Status, Target, Term, Trace, Transition, Write } from './model.js';
|
|
2
|
+
export { MAX_BANK_SIZE, parseMachine, ReluTraceError } from './model.js';
|
|
3
|
+
export { defineMachine, greaterThan, relu } from './builder.js';
|
|
4
|
+
export { createSession, type Session, type SessionOptions } from './runtime.js';
|
|
5
|
+
export { compareTick, type Difference } from './compare.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const inspectorCSS: string;
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
export const inspectorCSS = `
|
|
2
|
+
:host {
|
|
3
|
+
display: block;
|
|
4
|
+
min-width: 0;
|
|
5
|
+
container-type: inline-size;
|
|
6
|
+
--relu-bg: #131815;
|
|
7
|
+
--relu-surface: #1b221e;
|
|
8
|
+
--relu-panel: #191f1b;
|
|
9
|
+
--relu-ink: #eaece6;
|
|
10
|
+
--relu-muted: #a4afa7;
|
|
11
|
+
--relu-accent: #c6f57b;
|
|
12
|
+
--relu-rule: #303632;
|
|
13
|
+
--relu-mono: ui-monospace, SFMono-Regular, Consolas, monospace;
|
|
14
|
+
--relu-font: 15px/1.45 system-ui, sans-serif;
|
|
15
|
+
color: var(--relu-ink);
|
|
16
|
+
}
|
|
17
|
+
.inspector {
|
|
18
|
+
font: var(--relu-font);
|
|
19
|
+
background: var(--relu-bg);
|
|
20
|
+
border: 1px solid var(--relu-rule);
|
|
21
|
+
border-radius: 12px;
|
|
22
|
+
overflow: hidden;
|
|
23
|
+
text-align: left;
|
|
24
|
+
}
|
|
25
|
+
* { box-sizing: border-box; }
|
|
26
|
+
.toolbar, .comparison, .panel-head, .panel-body, .panel-foot, .state { padding: 12px 16px; }
|
|
27
|
+
.toolbar, .actions, .meter, .panel-head, .panel-foot, .comparison { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
|
28
|
+
.toolbar, .panel-head { justify-content: space-between; }
|
|
29
|
+
.toolbar { background: var(--relu-surface); }
|
|
30
|
+
button, select { font: 600 13px/1.2 system-ui, sans-serif; border: 1px solid #48554c; border-radius: 5px; padding: 8px 12px; background: #222b25; color: var(--relu-ink); min-height: 34px; }
|
|
31
|
+
button:not(:disabled) { cursor: pointer; }
|
|
32
|
+
button:hover:not(:disabled), select:hover:not(:disabled) { background: #344438; border-color: #899e8c; }
|
|
33
|
+
button:focus-visible, select:focus-visible { outline: 2px solid var(--relu-accent); outline-offset: 2px; }
|
|
34
|
+
button:disabled, select:disabled { color: #858f86; border-color: #373f39; background: transparent; }
|
|
35
|
+
button.primary:not(:disabled) { color: #151e12; background: var(--relu-accent); border-color: var(--relu-accent); }
|
|
36
|
+
button.primary:hover:not(:disabled) { background: #dcffa7; }
|
|
37
|
+
button[hidden] { display: none; }
|
|
38
|
+
.meter { font: 13px/1.2 var(--relu-mono); color: var(--relu-muted); }
|
|
39
|
+
#status { font: 700 12px/1.2 system-ui, sans-serif; padding: 5px 8px; border-radius: 4px; background: #303e32; color: var(--relu-accent); }
|
|
40
|
+
#status[data-kind="halt"] { color: #b6ead9; background: #233d35; }
|
|
41
|
+
#status[data-kind="budget"], .comparison[data-kind="diff"] strong { color: #ffcf8e; }
|
|
42
|
+
#status[data-kind="invalid"], .comparison[data-kind="error"] strong, .error { color: #ffb0a2; }
|
|
43
|
+
.comparison { background: #18221a; border-top: 1px solid var(--relu-rule); font-size: 13px; column-gap: 12px; overflow-wrap: anywhere; }
|
|
44
|
+
.comparison[hidden] { display: none; }
|
|
45
|
+
.comparison strong { font: 600 11px/1.2 var(--relu-mono); letter-spacing: .08em; color: var(--relu-accent); }
|
|
46
|
+
.comparison[data-kind="diff"] { background: #292216; }
|
|
47
|
+
.comparison[data-kind="error"] { background: #2c1a19; }
|
|
48
|
+
.panels { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); border-top: 1px solid var(--relu-rule); }
|
|
49
|
+
.panel { display: flex; flex-direction: column; }
|
|
50
|
+
.panel + .panel { border-left: 1px solid var(--relu-rule); }
|
|
51
|
+
.panel-head { background: var(--relu-panel); min-height: 58px; border-bottom: 1px solid var(--relu-rule); }
|
|
52
|
+
.panel-body { flex: 1; overflow-wrap: anywhere; }
|
|
53
|
+
.panel-body:has(> .muted:only-child) { min-height: 112px; }
|
|
54
|
+
.panel-foot { border-top: 1px solid var(--relu-rule); }
|
|
55
|
+
.state { border-top: 1px solid var(--relu-rule); background: var(--relu-panel); overflow-wrap: anywhere; }
|
|
56
|
+
.state h3 span { font-size: 12px; font-weight: 400; color: var(--relu-muted); margin-left: 4px; }
|
|
57
|
+
.state dl { grid-template-columns: max-content 1fr; }
|
|
58
|
+
.bank-value { display: flex; align-items: baseline; gap: 8px; flex-wrap: wrap; }
|
|
59
|
+
.bank-toggle { padding: 3px 8px; min-height: 26px; font-size: 11px; }
|
|
60
|
+
h3 { font-size: 15px; margin: 0; }
|
|
61
|
+
h4 { margin: 12px 0 5px; color: var(--relu-muted); font: 600 11px/1.4 var(--relu-mono); text-transform: uppercase; letter-spacing: .08em; }
|
|
62
|
+
p { margin: 0; }
|
|
63
|
+
label { display: flex; align-items: center; gap: 6px; color: var(--relu-muted); font-size: 12px; min-width: 0; }
|
|
64
|
+
select { max-width: min(32ch, 63cqw); color-scheme: dark; }
|
|
65
|
+
.muted { color: var(--relu-muted); }
|
|
66
|
+
.small { font-size: 13px; }
|
|
67
|
+
.equation { font: 600 16px/1.4 var(--relu-mono); color: var(--relu-accent); margin-bottom: 5px; }
|
|
68
|
+
dl { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 4px 12px; margin: 0; font: 13px/1.4 var(--relu-mono); }
|
|
69
|
+
dt { color: #b7c7ba; } dd { margin: 0; }
|
|
70
|
+
table { width: 100%; border-collapse: collapse; text-align: left; margin-top: 12px; font: 13px/1.4 var(--relu-mono); }
|
|
71
|
+
th, td { border-bottom: 1px solid var(--relu-rule); padding: 6px 8px 6px 0; }
|
|
72
|
+
th { color: var(--relu-muted); font-weight: 500; font-size: 11px; }
|
|
73
|
+
@container (max-width: 700px) {
|
|
74
|
+
.panels { grid-template-columns: minmax(0, 1fr); }
|
|
75
|
+
.panel + .panel { border-left: none; border-top: 1px solid var(--relu-rule); }
|
|
76
|
+
}
|
|
77
|
+
`;
|
package/dist/model.d.ts
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
export type ErrorCode = 'VALIDATION_ERROR' | 'ARITHMETIC_OVERFLOW' | 'OUT_OF_RANGE' | 'INVALID_CONDITION' | 'INVALID_ADDRESS';
|
|
2
|
+
export declare class ReluTraceError extends Error {
|
|
3
|
+
readonly code: ErrorCode;
|
|
4
|
+
readonly path?: string;
|
|
5
|
+
constructor(code: ErrorCode, message: string, path?: string);
|
|
6
|
+
}
|
|
7
|
+
export declare const MAX_BANK_SIZE = 1048576;
|
|
8
|
+
export type Range = {
|
|
9
|
+
min: number;
|
|
10
|
+
max: number;
|
|
11
|
+
};
|
|
12
|
+
export type Bank = Range & {
|
|
13
|
+
size: number;
|
|
14
|
+
};
|
|
15
|
+
export type Term = {
|
|
16
|
+
from: string;
|
|
17
|
+
weight: number;
|
|
18
|
+
};
|
|
19
|
+
export type Gate = {
|
|
20
|
+
id: string;
|
|
21
|
+
bias: number;
|
|
22
|
+
terms: Term[];
|
|
23
|
+
};
|
|
24
|
+
export type Target = string | null;
|
|
25
|
+
export type Control = Target | {
|
|
26
|
+
test: string;
|
|
27
|
+
yes: Target;
|
|
28
|
+
no: Target;
|
|
29
|
+
};
|
|
30
|
+
export type Instruction = {
|
|
31
|
+
inputs?: Record<string, string>;
|
|
32
|
+
reads?: {
|
|
33
|
+
id: string;
|
|
34
|
+
bank: string;
|
|
35
|
+
address: string;
|
|
36
|
+
}[];
|
|
37
|
+
gates: Gate[];
|
|
38
|
+
next: Control;
|
|
39
|
+
set?: Record<string, string>;
|
|
40
|
+
writes?: {
|
|
41
|
+
bank: string;
|
|
42
|
+
address: string;
|
|
43
|
+
value: string;
|
|
44
|
+
when?: string;
|
|
45
|
+
}[];
|
|
46
|
+
};
|
|
47
|
+
export type Machine = {
|
|
48
|
+
version: 1;
|
|
49
|
+
entry: string;
|
|
50
|
+
registers: Record<string, Range>;
|
|
51
|
+
banks: Record<string, Bank>;
|
|
52
|
+
instructions: Record<string, Instruction>;
|
|
53
|
+
};
|
|
54
|
+
export type Snapshot = {
|
|
55
|
+
instruction: Target;
|
|
56
|
+
registers: Record<string, number>;
|
|
57
|
+
ram: Record<string, number[]>;
|
|
58
|
+
};
|
|
59
|
+
export type Write = {
|
|
60
|
+
bank: string;
|
|
61
|
+
address: number;
|
|
62
|
+
before: number;
|
|
63
|
+
value: number;
|
|
64
|
+
};
|
|
65
|
+
export type Transition = {
|
|
66
|
+
next: Target;
|
|
67
|
+
changes: Record<string, {
|
|
68
|
+
before: number;
|
|
69
|
+
value: number;
|
|
70
|
+
}>;
|
|
71
|
+
writes: Write[];
|
|
72
|
+
};
|
|
73
|
+
export type Reference = (before: Snapshot) => Transition;
|
|
74
|
+
export type Clamp = {
|
|
75
|
+
tick: number;
|
|
76
|
+
instruction: string;
|
|
77
|
+
signal: string;
|
|
78
|
+
};
|
|
79
|
+
export type GateTrace = {
|
|
80
|
+
id: string;
|
|
81
|
+
bias: number;
|
|
82
|
+
terms: (Term & {
|
|
83
|
+
input: number;
|
|
84
|
+
product: number;
|
|
85
|
+
})[];
|
|
86
|
+
sum: number;
|
|
87
|
+
activation: number;
|
|
88
|
+
output: number;
|
|
89
|
+
};
|
|
90
|
+
export type Trace = {
|
|
91
|
+
tick: number;
|
|
92
|
+
instruction: string;
|
|
93
|
+
inputs: {
|
|
94
|
+
id: string;
|
|
95
|
+
register: string;
|
|
96
|
+
value: number;
|
|
97
|
+
}[];
|
|
98
|
+
reads: {
|
|
99
|
+
id: string;
|
|
100
|
+
bank: string;
|
|
101
|
+
address: number;
|
|
102
|
+
value: number;
|
|
103
|
+
}[];
|
|
104
|
+
gates: GateTrace[];
|
|
105
|
+
branch?: {
|
|
106
|
+
signal: string;
|
|
107
|
+
value: 0 | 1;
|
|
108
|
+
};
|
|
109
|
+
} & ({
|
|
110
|
+
outcome: 'committed';
|
|
111
|
+
transition: Transition;
|
|
112
|
+
} | {
|
|
113
|
+
outcome: 'invalid';
|
|
114
|
+
error: string;
|
|
115
|
+
code: ErrorCode;
|
|
116
|
+
});
|
|
117
|
+
export type Status = 'running' | 'halt' | 'invalid' | 'budget';
|
|
118
|
+
export declare function requireThat(ok: unknown, message: string, code?: ErrorCode, path?: string): asserts ok;
|
|
119
|
+
export declare function integer(value: unknown, label: string, code?: ErrorCode, path?: string): number;
|
|
120
|
+
export declare function inRange(input: unknown, { min, max }: Range, label: string, code?: ErrorCode, path?: string): number;
|
|
121
|
+
export declare function requireRecord(value: unknown, path: string): asserts value is Record<string, unknown>;
|
|
122
|
+
export declare function requireAllowedKeys(record: Record<string, unknown>, allowed: readonly string[], path: string): void;
|
|
123
|
+
export declare function cloneInput<T>(value: T, label: string): T;
|
|
124
|
+
/** Copy and validate a portable v1 definition, including objects from JSON.parse. */
|
|
125
|
+
export declare function parseMachine(definition: unknown): Machine;
|
package/dist/model.js
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
export class ReluTraceError extends Error {
|
|
2
|
+
code;
|
|
3
|
+
path;
|
|
4
|
+
constructor(code, message, path) {
|
|
5
|
+
super(message);
|
|
6
|
+
this.name = 'ReluTraceError';
|
|
7
|
+
this.code = code;
|
|
8
|
+
if (path !== undefined)
|
|
9
|
+
this.path = path;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
export const MAX_BANK_SIZE = 1_048_576;
|
|
13
|
+
const idPattern = /^[A-Za-z_][A-Za-z0-9_-]*$/;
|
|
14
|
+
export function requireThat(ok, message, code = 'VALIDATION_ERROR', path) {
|
|
15
|
+
if (!ok)
|
|
16
|
+
throw new ReluTraceError(code, message, path);
|
|
17
|
+
}
|
|
18
|
+
export function integer(value, label, code = 'VALIDATION_ERROR', path) {
|
|
19
|
+
requireThat(typeof value === 'number' && Number.isSafeInteger(value), `${label} must be a safe integer`, code, path);
|
|
20
|
+
return value === 0 ? 0 : value;
|
|
21
|
+
}
|
|
22
|
+
export function inRange(input, { min, max }, label, code = 'VALIDATION_ERROR', path) {
|
|
23
|
+
const value = integer(input, label, code, path);
|
|
24
|
+
requireThat(value >= min && value <= max, `${label} ${value} is outside [${min}, ${max}]`, code, path);
|
|
25
|
+
return value;
|
|
26
|
+
}
|
|
27
|
+
export function requireRecord(value, path) {
|
|
28
|
+
requireThat(value !== null && typeof value === 'object' && [Object.prototype, null].includes(Object.getPrototypeOf(value)), `${path} must be an object`, 'VALIDATION_ERROR', path);
|
|
29
|
+
}
|
|
30
|
+
export function requireAllowedKeys(record, allowed, path) {
|
|
31
|
+
for (const key of Object.keys(record)) {
|
|
32
|
+
requireThat(allowed.includes(key), `${path}: unexpected property ${key}`, 'VALIDATION_ERROR', `${path}.${key}`);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
export function cloneInput(value, label) {
|
|
36
|
+
try {
|
|
37
|
+
return structuredClone(value);
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
throw new ReluTraceError('VALIDATION_ERROR', `${label} must be structured-cloneable`, label);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/** Copy and validate a portable v1 definition, including objects from JSON.parse. */
|
|
44
|
+
export function parseMachine(definition) {
|
|
45
|
+
const input = cloneInput(definition, 'Machine');
|
|
46
|
+
validate(input);
|
|
47
|
+
return input;
|
|
48
|
+
}
|
|
49
|
+
const machineKeys = ['version', 'entry', 'registers', 'banks', 'instructions'];
|
|
50
|
+
const rangeKeys = ['min', 'max'];
|
|
51
|
+
const bankKeys = ['min', 'max', 'size'];
|
|
52
|
+
const instructionKeys = ['inputs', 'reads', 'gates', 'next', 'set', 'writes'];
|
|
53
|
+
const readKeys = ['id', 'bank', 'address'];
|
|
54
|
+
const gateKeys = ['id', 'bias', 'terms'];
|
|
55
|
+
const termKeys = ['from', 'weight'];
|
|
56
|
+
const controlKeys = ['test', 'yes', 'no'];
|
|
57
|
+
const writeKeys = ['bank', 'address', 'value', 'when'];
|
|
58
|
+
function validate(machine) {
|
|
59
|
+
requireRecord(machine, 'Machine');
|
|
60
|
+
requireAllowedKeys(machine, machineKeys, 'Machine');
|
|
61
|
+
requireThat(machine.version === 1, 'Expected machine definition version 1', 'VALIDATION_ERROR', 'version');
|
|
62
|
+
function object(value, path) {
|
|
63
|
+
requireRecord(value, path);
|
|
64
|
+
return value;
|
|
65
|
+
}
|
|
66
|
+
function list(value, path) {
|
|
67
|
+
requireThat(Array.isArray(value), `${path} must be an ordered array`, 'VALIDATION_ERROR', path);
|
|
68
|
+
return value;
|
|
69
|
+
}
|
|
70
|
+
function id(name, path) {
|
|
71
|
+
requireThat(typeof name === 'string' && idPattern.test(name), `${path} must be an identifier matching [A-Za-z_][A-Za-z0-9_-]*`, 'VALIDATION_ERROR', path);
|
|
72
|
+
}
|
|
73
|
+
const registers = object(machine.registers, 'registers');
|
|
74
|
+
const banks = object(machine.banks, 'banks');
|
|
75
|
+
const instructions = object(machine.instructions, 'instructions');
|
|
76
|
+
function named(value, names, path) {
|
|
77
|
+
id(value, path);
|
|
78
|
+
requireThat(Object.hasOwn(names, value), `${path}: unknown name ${value}`, 'VALIDATION_ERROR', path);
|
|
79
|
+
}
|
|
80
|
+
function range(value, path, allowed) {
|
|
81
|
+
const bounds = object(value, path);
|
|
82
|
+
requireAllowedKeys(bounds, allowed, path);
|
|
83
|
+
const min = integer(bounds.min, `${path}.min`, 'VALIDATION_ERROR', `${path}.min`);
|
|
84
|
+
const max = integer(bounds.max, `${path}.max`, 'VALIDATION_ERROR', `${path}.max`);
|
|
85
|
+
requireThat(min <= max, `${path}: minimum exceeds maximum`, 'VALIDATION_ERROR', path);
|
|
86
|
+
bounds.min = min;
|
|
87
|
+
bounds.max = max;
|
|
88
|
+
return bounds;
|
|
89
|
+
}
|
|
90
|
+
for (const [name, value] of Object.entries(registers)) {
|
|
91
|
+
id(name, 'Register name');
|
|
92
|
+
range(value, `registers.${name}`, rangeKeys);
|
|
93
|
+
}
|
|
94
|
+
for (const [name, value] of Object.entries(banks)) {
|
|
95
|
+
id(name, 'Bank name');
|
|
96
|
+
const bank = range(value, `banks.${name}`, bankKeys);
|
|
97
|
+
bank.size = inRange(bank.size, { min: 1, max: MAX_BANK_SIZE }, `banks.${name}.size`, 'VALIDATION_ERROR', `banks.${name}.size`);
|
|
98
|
+
}
|
|
99
|
+
named(machine.entry, instructions, 'entry');
|
|
100
|
+
for (const [name, value] of Object.entries(instructions)) {
|
|
101
|
+
id(name, 'Instruction name');
|
|
102
|
+
const at = `instructions.${name}`;
|
|
103
|
+
const block = object(value, at);
|
|
104
|
+
requireAllowedKeys(block, instructionKeys, at);
|
|
105
|
+
const signals = new Set();
|
|
106
|
+
function add(signal, path) {
|
|
107
|
+
id(signal, path);
|
|
108
|
+
requireThat(!signals.has(signal), `${path}: duplicate signal ${signal}`, 'VALIDATION_ERROR', path);
|
|
109
|
+
signals.add(signal);
|
|
110
|
+
}
|
|
111
|
+
function use(signal, path) {
|
|
112
|
+
id(signal, path);
|
|
113
|
+
requireThat(signals.has(signal), `${path}: unknown or forward signal ${signal}`, 'VALIDATION_ERROR', path);
|
|
114
|
+
}
|
|
115
|
+
for (const [signal, source] of Object.entries(block.inputs === undefined ? {} : object(block.inputs, `${at}.inputs`))) {
|
|
116
|
+
const path = `${at}.inputs.${signal}`;
|
|
117
|
+
named(source, registers, path);
|
|
118
|
+
add(signal, path);
|
|
119
|
+
}
|
|
120
|
+
for (const [i, value] of (block.reads === undefined ? [] : list(block.reads, `${at}.reads`)).entries()) {
|
|
121
|
+
const path = `${at}.reads[${i}]`;
|
|
122
|
+
const read = object(value, path);
|
|
123
|
+
requireAllowedKeys(read, readKeys, path);
|
|
124
|
+
named(read.bank, banks, `${path}.bank`);
|
|
125
|
+
use(read.address, `${path}.address`);
|
|
126
|
+
add(read.id, `${path}.id`);
|
|
127
|
+
}
|
|
128
|
+
for (const [i, value] of list(block.gates, `${at}.gates`).entries()) {
|
|
129
|
+
const path = `${at}.gates[${i}]`;
|
|
130
|
+
const gate = object(value, path);
|
|
131
|
+
requireAllowedKeys(gate, gateKeys, path);
|
|
132
|
+
gate.bias = integer(gate.bias, `${path}.bias`, 'VALIDATION_ERROR', `${path}.bias`);
|
|
133
|
+
for (const [j, value] of list(gate.terms, `${path}.terms`).entries()) {
|
|
134
|
+
const termPath = `${path}.terms[${j}]`;
|
|
135
|
+
const term = object(value, termPath);
|
|
136
|
+
requireAllowedKeys(term, termKeys, termPath);
|
|
137
|
+
use(term.from, `${termPath}.from`);
|
|
138
|
+
term.weight = integer(term.weight, `${termPath}.weight`, 'VALIDATION_ERROR', `${termPath}.weight`);
|
|
139
|
+
}
|
|
140
|
+
add(gate.id, `${path}.id`);
|
|
141
|
+
}
|
|
142
|
+
if (block.next !== null && typeof block.next === 'object') {
|
|
143
|
+
const next = object(block.next, `${at}.next`);
|
|
144
|
+
requireAllowedKeys(next, controlKeys, `${at}.next`);
|
|
145
|
+
use(next.test, `${at}.next.test`);
|
|
146
|
+
if (next.yes !== null)
|
|
147
|
+
named(next.yes, instructions, `${at}.next.yes`);
|
|
148
|
+
if (next.no !== null)
|
|
149
|
+
named(next.no, instructions, `${at}.next.no`);
|
|
150
|
+
}
|
|
151
|
+
else if (block.next !== null)
|
|
152
|
+
named(block.next, instructions, `${at}.next`);
|
|
153
|
+
for (const [dest, signal] of Object.entries(block.set === undefined ? {} : object(block.set, `${at}.set`))) {
|
|
154
|
+
const path = `${at}.set.${dest}`;
|
|
155
|
+
named(dest, registers, path);
|
|
156
|
+
use(signal, path);
|
|
157
|
+
}
|
|
158
|
+
for (const [i, value] of (block.writes === undefined ? [] : list(block.writes, `${at}.writes`)).entries()) {
|
|
159
|
+
const path = `${at}.writes[${i}]`;
|
|
160
|
+
const write = object(value, path);
|
|
161
|
+
requireAllowedKeys(write, writeKeys, path);
|
|
162
|
+
named(write.bank, banks, `${path}.bank`);
|
|
163
|
+
use(write.address, `${path}.address`);
|
|
164
|
+
use(write.value, `${path}.value`);
|
|
165
|
+
if (write.when !== undefined)
|
|
166
|
+
use(write.when, `${path}.when`);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { Clamp, ErrorCode, Machine, Snapshot, Status, Trace } from './model.js';
|
|
2
|
+
export type SessionOptions = {
|
|
3
|
+
limit: number;
|
|
4
|
+
clamp?: Clamp;
|
|
5
|
+
};
|
|
6
|
+
export type Session = {
|
|
7
|
+
readonly status: Status;
|
|
8
|
+
readonly ticks: number;
|
|
9
|
+
readonly error: string | undefined;
|
|
10
|
+
readonly errorCode: ErrorCode | undefined;
|
|
11
|
+
snapshot: () => Snapshot;
|
|
12
|
+
step: (options?: {
|
|
13
|
+
trace?: boolean;
|
|
14
|
+
}) => Trace | undefined;
|
|
15
|
+
run: (options?: {
|
|
16
|
+
trace?: boolean;
|
|
17
|
+
}) => Trace[];
|
|
18
|
+
};
|
|
19
|
+
export declare function createSession(definition: Machine, initial: Snapshot, options: SessionOptions): Session;
|
package/dist/runtime.js
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { cloneInput, inRange, integer, parseMachine, ReluTraceError, requireAllowedKeys, requireRecord, requireThat } from './model.js';
|
|
2
|
+
const snapshotKeys = ['instruction', 'registers', 'ram'];
|
|
3
|
+
const sessionOptionKeys = ['limit', 'clamp'];
|
|
4
|
+
const clampKeys = ['tick', 'instruction', 'signal'];
|
|
5
|
+
function copyInitial(machine, initial) {
|
|
6
|
+
const copy = cloneInput(initial, 'Snapshot');
|
|
7
|
+
requireRecord(copy, 'Snapshot');
|
|
8
|
+
requireAllowedKeys(copy, snapshotKeys, 'Snapshot');
|
|
9
|
+
const { instruction, registers, ram } = copy;
|
|
10
|
+
requireRecord(registers, 'Snapshot registers');
|
|
11
|
+
requireRecord(ram, 'Snapshot RAM');
|
|
12
|
+
requireThat(instruction === null || (typeof instruction === 'string' && Object.hasOwn(machine.instructions, instruction)), `Unknown initial instruction: ${instruction}`, 'VALIDATION_ERROR', 'Snapshot.instruction');
|
|
13
|
+
requireThat(Object.keys(registers).length === Object.keys(machine.registers).length &&
|
|
14
|
+
Object.keys(ram).length === Object.keys(machine.banks).length, 'Snapshot must contain exactly the declared registers and RAM banks', 'VALIDATION_ERROR', 'Snapshot');
|
|
15
|
+
for (const [id, range] of Object.entries(machine.registers)) {
|
|
16
|
+
requireThat(Object.hasOwn(registers, id), `Missing register ${id}`, 'VALIDATION_ERROR', `Snapshot.registers.${id}`);
|
|
17
|
+
registers[id] = inRange(registers[id], range, `Register ${id}`, 'VALIDATION_ERROR', `Snapshot.registers.${id}`);
|
|
18
|
+
}
|
|
19
|
+
for (const [id, bank] of Object.entries(machine.banks)) {
|
|
20
|
+
requireThat(Object.hasOwn(ram, id) && Array.isArray(ram[id]) && ram[id].length === bank.size, `RAM ${id} must have exactly ${bank.size} cells`, 'VALIDATION_ERROR', `Snapshot.ram.${id}`);
|
|
21
|
+
for (let i = 0; i < bank.size; i++) {
|
|
22
|
+
ram[id][i] = inRange(ram[id][i], bank, `${id}[${i}]`, 'VALIDATION_ERROR', `Snapshot.ram.${id}[${i}]`);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
return { instruction: instruction, registers: registers, ram: ram };
|
|
26
|
+
}
|
|
27
|
+
export function createSession(definition, initial, options) {
|
|
28
|
+
const machine = parseMachine(definition);
|
|
29
|
+
requireRecord(options, 'Session options');
|
|
30
|
+
requireAllowedKeys(options, sessionOptionKeys, 'Session options');
|
|
31
|
+
const limit = integer(options.limit, 'Tick limit', 'VALIDATION_ERROR', 'Session options.limit');
|
|
32
|
+
requireThat(limit > 0, 'Tick limit must be positive', 'VALIDATION_ERROR', 'Session options.limit');
|
|
33
|
+
let intervention;
|
|
34
|
+
if (options.clamp !== undefined) {
|
|
35
|
+
const clonedClamp = cloneInput(options.clamp, 'Clamp');
|
|
36
|
+
requireRecord(clonedClamp, 'Clamp');
|
|
37
|
+
requireAllowedKeys(clonedClamp, clampKeys, 'Clamp');
|
|
38
|
+
const tick = integer(clonedClamp.tick, 'Clamp tick', 'VALIDATION_ERROR', 'Clamp.tick');
|
|
39
|
+
requireThat(tick >= 1 && tick <= limit, 'Clamp tick is outside the session limit', 'VALIDATION_ERROR', 'Clamp.tick');
|
|
40
|
+
requireThat(typeof clonedClamp.instruction === 'string' &&
|
|
41
|
+
typeof clonedClamp.signal === 'string' &&
|
|
42
|
+
Object.hasOwn(machine.instructions, clonedClamp.instruction) &&
|
|
43
|
+
machine.instructions[clonedClamp.instruction].gates.some(gate => gate.id === clonedClamp.signal), `Clamp must name a gate: ${clonedClamp.instruction}.${clonedClamp.signal}`, 'VALIDATION_ERROR', 'Clamp');
|
|
44
|
+
intervention = { tick, instruction: clonedClamp.instruction, signal: clonedClamp.signal };
|
|
45
|
+
}
|
|
46
|
+
const state = copyInitial(machine, initial);
|
|
47
|
+
let attempted = 0;
|
|
48
|
+
let status = state.instruction === null ? 'halt' : 'running';
|
|
49
|
+
let error;
|
|
50
|
+
let errorCode;
|
|
51
|
+
function step({ trace = true } = {}) {
|
|
52
|
+
if (status !== 'running' || state.instruction === null)
|
|
53
|
+
return;
|
|
54
|
+
const instruction = state.instruction;
|
|
55
|
+
const block = machine.instructions[instruction];
|
|
56
|
+
const tick = ++attempted;
|
|
57
|
+
const record = trace ? { tick, instruction, inputs: [], reads: [], gates: [] } : undefined;
|
|
58
|
+
const signals = new Map();
|
|
59
|
+
// Definitions are validated once. Every signal use must follow its definition.
|
|
60
|
+
const value = (id) => signals.get(id);
|
|
61
|
+
function condition(id) {
|
|
62
|
+
const bit = value(id);
|
|
63
|
+
requireThat(bit === 0 || bit === 1, `${id} must be 0 or 1 (got ${bit})`, 'INVALID_CONDITION', id);
|
|
64
|
+
return bit;
|
|
65
|
+
}
|
|
66
|
+
function address(bank, id) {
|
|
67
|
+
return inRange(value(id), { min: 0, max: machine.banks[bank].size - 1 }, `RAM ${bank} address`, 'INVALID_ADDRESS', bank);
|
|
68
|
+
}
|
|
69
|
+
let next;
|
|
70
|
+
const changes = {};
|
|
71
|
+
const writes = [];
|
|
72
|
+
try {
|
|
73
|
+
for (const [id, register] of Object.entries(block.inputs ?? {})) {
|
|
74
|
+
const input = state.registers[register];
|
|
75
|
+
signals.set(id, input);
|
|
76
|
+
record?.inputs.push({ id, register, value: input });
|
|
77
|
+
}
|
|
78
|
+
for (const read of block.reads ?? []) {
|
|
79
|
+
const index = address(read.bank, read.address);
|
|
80
|
+
const input = state.ram[read.bank][index];
|
|
81
|
+
signals.set(read.id, input);
|
|
82
|
+
record?.reads.push({ id: read.id, bank: read.bank, address: index, value: input });
|
|
83
|
+
}
|
|
84
|
+
for (const gate of block.gates) {
|
|
85
|
+
const terms = record ? [] : undefined;
|
|
86
|
+
let sum = gate.bias;
|
|
87
|
+
for (const { from, weight } of gate.terms) {
|
|
88
|
+
const input = value(from);
|
|
89
|
+
const product = integer(input * weight, `${gate.id} product`, 'ARITHMETIC_OVERFLOW', gate.id);
|
|
90
|
+
sum = integer(sum + product, `${gate.id} partial sum`, 'ARITHMETIC_OVERFLOW', gate.id);
|
|
91
|
+
terms?.push({ from, weight, input, product });
|
|
92
|
+
}
|
|
93
|
+
const activation = Math.max(0, sum);
|
|
94
|
+
const output = intervention?.tick === tick && intervention.instruction === instruction && intervention.signal === gate.id
|
|
95
|
+
? 0 : activation;
|
|
96
|
+
signals.set(gate.id, output);
|
|
97
|
+
if (record && terms)
|
|
98
|
+
record.gates.push({ id: gate.id, bias: gate.bias, terms, sum, activation, output });
|
|
99
|
+
}
|
|
100
|
+
if (block.next !== null && typeof block.next === 'object') {
|
|
101
|
+
const bit = condition(block.next.test);
|
|
102
|
+
next = bit ? block.next.yes : block.next.no;
|
|
103
|
+
if (record)
|
|
104
|
+
record.branch = { signal: block.next.test, value: bit };
|
|
105
|
+
}
|
|
106
|
+
else
|
|
107
|
+
next = block.next;
|
|
108
|
+
for (const [dest, id] of Object.entries(block.set ?? {})) {
|
|
109
|
+
const updated = inRange(value(id), machine.registers[dest], `Register ${dest}`, 'OUT_OF_RANGE', dest);
|
|
110
|
+
const before = state.registers[dest];
|
|
111
|
+
if (before !== updated)
|
|
112
|
+
Object.defineProperty(changes, dest, { value: { before, value: updated }, enumerable: true });
|
|
113
|
+
}
|
|
114
|
+
for (const write of block.writes ?? []) {
|
|
115
|
+
if (write.when !== undefined && condition(write.when) === 0)
|
|
116
|
+
continue;
|
|
117
|
+
const index = address(write.bank, write.address);
|
|
118
|
+
const updated = inRange(value(write.value), machine.banks[write.bank], `RAM ${write.bank}[${index}]`, 'OUT_OF_RANGE', `${write.bank}[${index}]`);
|
|
119
|
+
writes.push({ bank: write.bank, address: index, before: state.ram[write.bank][index], value: updated });
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
catch (reason) {
|
|
123
|
+
status = 'invalid';
|
|
124
|
+
error = reason instanceof Error ? reason.message : String(reason);
|
|
125
|
+
errorCode = reason instanceof ReluTraceError ? reason.code : 'VALIDATION_ERROR';
|
|
126
|
+
return record && { ...record, outcome: 'invalid', error, code: errorCode };
|
|
127
|
+
}
|
|
128
|
+
// Only commit after every condition, address and result has been validated.
|
|
129
|
+
for (const [dest, change] of Object.entries(changes))
|
|
130
|
+
state.registers[dest] = change.value;
|
|
131
|
+
for (const write of writes)
|
|
132
|
+
state.ram[write.bank][write.address] = write.value;
|
|
133
|
+
state.instruction = next;
|
|
134
|
+
if (next === null)
|
|
135
|
+
status = 'halt';
|
|
136
|
+
else if (tick === limit)
|
|
137
|
+
status = 'budget';
|
|
138
|
+
return record && { ...record, outcome: 'committed', transition: { next, changes, writes } };
|
|
139
|
+
}
|
|
140
|
+
return {
|
|
141
|
+
get status() { return status; },
|
|
142
|
+
get ticks() { return attempted; },
|
|
143
|
+
get error() { return error; },
|
|
144
|
+
get errorCode() { return errorCode; },
|
|
145
|
+
snapshot: () => structuredClone(state),
|
|
146
|
+
step,
|
|
147
|
+
run({ trace = false } = {}) {
|
|
148
|
+
const history = [];
|
|
149
|
+
while (status === 'running') {
|
|
150
|
+
const record = step({ trace });
|
|
151
|
+
if (record)
|
|
152
|
+
history.push(record);
|
|
153
|
+
}
|
|
154
|
+
return history;
|
|
155
|
+
},
|
|
156
|
+
};
|
|
157
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# Contribute: add an independently checkable fixture
|
|
2
|
+
|
|
3
|
+
Run `npm ci`, `npm test`, and `npm run build:playground` from a clean checkout. The package uses TypeScript and the test suite uses Node's built-in test runner. No app framework or runtime dependency is needed.
|
|
4
|
+
|
|
5
|
+
## Follow one tick
|
|
6
|
+
|
|
7
|
+
1. `src/model.ts` defines the portable machine and validates name resolution, operand order, and ranges. `src/builder.ts` only emits that same representation.
|
|
8
|
+
2. `src/runtime.ts` owns the clock boundary: capture pre-tick sources, evaluate ReLUs, validate all proposed writes and the target conditions, then commit. Trace fields are populated during that evaluation, not by re-evaluating the circuit later.
|
|
9
|
+
3. `src/compare.ts` finds the first differing field. `src/browser.ts` owns playback and presentation, not ReLU evaluation. `playground/main.mjs` mounts the same browser entry point that an external app imports.
|
|
10
|
+
|
|
11
|
+
## Add a case worth keeping
|
|
12
|
+
|
|
13
|
+
Start by writing ordinary code for a single reference transition. For example, a guarded write could store `from + edge` in `distance[to]` only when it is strictly smaller than the current distance. Declare how large the distance and address can be. Include an improving case with unequal operands, a tie that must not write, and a non-improving case. Assert the written address and value, not just that the machine halted.
|
|
14
|
+
|
|
15
|
+
Then emit the gate definition, start a `createSession`, and call `compareTick(reference(before), tick)` using a pre-tick snapshot. In the existing relaxation fixture, temporarily change the second write's `value` from `oldPred` to `source`: the intended mismatch assertion in `test/runtime.test.mjs` must fail locally. Revert that temporary mutation before contributing. Add a new playground entry only if it teaches a different debugging question, not just another circuit of the same shape.
|
|
16
|
+
|
|
17
|
+
Before proposing a change, run `npm run lint`, `npm run typecheck`, `npm test`, and `npm run build:playground`. `npm run test:package` installs the tarball into an independent consumer and compiles the Integrate guide's snippets. For browser changes, install the test browsers (`npx playwright install chromium firefox webkit`; on Linux add `--with-deps` if system libraries are missing), then run `npm run test:e2e` (set `PLAYWRIGHT_SITE_PORT` / `PLAYWRIGHT_CONSUMER_PORT` if ports `4173`/`4174` are busy). The suite serves the playground and the packed consumer separately using Python 3 and drives the same controls a user sees. It also compares installed browser and Node traces for all the examples. Keep new assertions on observable transitions rather than on how a tick is implemented.
|
package/docs/explore.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# Explore: change a branch without changing a write
|
|
2
|
+
|
|
3
|
+
Open a hosted ReLU Trace playground. If you are starting from the source checkout, use the [local playground instructions](../README.md#start-here).
|
|
4
|
+
|
|
5
|
+
1. Select **Pointer chase**. RAM holds `1 → 4`, `4 → 2`, and `2 → 0`. A _register_ holds a named number, such as the current position. A _RAM bank_ is a numbered row of cells. A _tick_ executes one named instruction. Before touching the controls, predict where the first tick goes.
|
|
6
|
+
2. Press **Step** once. Session state moves from tick 0 to tick 1; **Tick trace** shows `follow → follow`. It reads `pointers[1] = 4` and writes `visits[0]` from `0` to `1`. The trace shows the old `position = 1`; **Session state** shows the new `position = 4`.
|
|
7
|
+
3. Look at **Activation**, with `hasNext` selected. A ReLU keeps the positive part of its weighted sum. The two terms here are `4 × 1` and `3 × −1`; with bias zero the result is `1`, a yes signal. The circuit uses two earlier gates to turn any positive pointer into one, not four.
|
|
8
|
+
4. Press **Clamp to zero & replay**. It doesn't edit the weights or starting RAM. It forces only this activation at this tick to output zero. The first difference is `follow → Halt`; `visits[0]` is still written with `1`. The intervention changed control flow, not the logging rule.
|
|
9
|
+
5. Press **Reset**, then **Run** to completion. The ordinary run halts with the visits `1 · 4 · 2` at the start of its visit bank. Use **History** to inspect tick 1 without modifying the final state.
|
|
10
|
+
|
|
11
|
+
Try **Shortest-path relaxation** next. The distance improves from 12 to 6, so checking only the distance would pass. The reference shows the second write should set `predecessor[1]` to `2`, but the machine writes `0`. Then run **Pointer cycle** and step **Invalid pointer**: a budget stop still has a next instruction; an invalid tick commits nothing.
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
# Integrate: use the same machine in Node and the browser
|
|
2
|
+
|
|
3
|
+
From a source checkout, `npm ci` then `npm pack`. In a separate Node 22+ ESM project, install the tarball with `npm install /path/to/relu-trace-0.1.0.tgz`. The code below uses TypeScript; JavaScript consumers can use the same exports without the type-only import and annotations.
|
|
4
|
+
|
|
5
|
+
Save the shared definition as `machine.ts`. The first ReLU increments a counter; the host commits that value and halts because `next` is `null`.
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { defineMachine, relu, type Snapshot } from 'relu-trace';
|
|
9
|
+
|
|
10
|
+
export const machine = defineMachine({ count: { min: 0, max: 8 } }, {}, {
|
|
11
|
+
add: {
|
|
12
|
+
inputs: { old: 'count' },
|
|
13
|
+
gates: [relu('incremented', 1, { old: 1 })],
|
|
14
|
+
set: { count: 'incremented' },
|
|
15
|
+
next: null,
|
|
16
|
+
},
|
|
17
|
+
}, 'add');
|
|
18
|
+
|
|
19
|
+
export const initial: Snapshot = { instruction: machine.entry, registers: { count: 2 }, ram: {} };
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Put this in `check.ts`. Compile both files with your TypeScript setup (for example `tsc --strict --target es2022 --module nodenext machine.ts check.ts`) and run `node --test check.js`.
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
import { createSession } from 'relu-trace';
|
|
26
|
+
import { machine, initial } from './machine.js';
|
|
27
|
+
|
|
28
|
+
const session = createSession(machine, initial, { limit: 4 });
|
|
29
|
+
const tick = session.step();
|
|
30
|
+
if (tick?.outcome !== 'committed' || tick.transition.changes.count?.value !== 3 || session.status !== 'halt') {
|
|
31
|
+
throw new Error('Expected one committed increment followed by halt');
|
|
32
|
+
}
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Put this in a browser module such as `browser.ts`. Add `<div id="debugger"></div>` to your page and load the module after the element exists. Use your app's bundler to resolve the package imports, or use an import map that serves the installed `dist/index.js` and `dist/browser.js` with their relative dependencies, as [the playground](../playground/index.html) does.
|
|
36
|
+
|
|
37
|
+
```ts
|
|
38
|
+
import { mountInspector } from 'relu-trace/browser';
|
|
39
|
+
import { machine, initial } from './machine.js';
|
|
40
|
+
|
|
41
|
+
const target = document.querySelector<HTMLElement>('#debugger');
|
|
42
|
+
if (!target) throw new Error('Missing debugger element');
|
|
43
|
+
export const unmount = mountInspector(target, { machine, initial, limit: 4 });
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
The inspector shows `count = 2` before you start and `count = 3` after one step. Call `unmount()` on route or component cleanup (active playback timers also stop automatically if the host element is removed from the DOM). Optional `onTick(trace, snapshot)` and `onStatusChange(status, snapshot)` callbacks let host apps observe execution without touching internal state. For an app that already runs a machine, pass a copy from your session's `snapshot()` at the point you want to investigate; your live app's clocks and memory are not touched. Mount behind a development route when snapshots contain application data. The inspector builds its Shadow DOM without `innerHTML` and applies styles via `adoptedStyleSheets` (with a `<style>` fallback), making it compatible with Trusted Types and strict-CSP hosts. Host pages can theme it by setting `--relu-bg`, `--relu-surface`, `--relu-panel`, `--relu-ink`, `--relu-muted`, `--relu-accent`, `--relu-rule`, `--relu-mono`, or `--relu-font` on the mounted container.
|
|
47
|
+
|
|
48
|
+
## Bring your own definition
|
|
49
|
+
|
|
50
|
+
You can replace `defineMachine(...)` above with a plain `Machine` object. Keep registers, RAM, and instruction boundaries explicit: map pre-tick inputs to names, topologically order the weighted ReLUs, then bind outputs to register destinations, condition bits, or write ports. Pass the resulting object to both `createSession` and `mountInspector`. See the [v1 contract](machine-v1.md) and [raw relaxation definition](../examples/machines.mjs) for a guarded-write example. Do not round floating-point weights or silently translate unsupported ops.
|
|
51
|
+
|
|
52
|
+
An optional `reference(before)` callback returns the expected next instruction, changed registers, and ordered RAM writes. It runs over a detached pre-tick snapshot and never affects execution. For headless tests, compare the output of the same callback with `compareTick(expected, actual)`. Stop at the first difference; a later comparison on an already-diverged state does not measure the original failure.
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# Portable machine definition v1
|
|
2
|
+
|
|
3
|
+
`Machine` is a plain, JSON-serializable object. Builder and raw definitions meet at this boundary; the runtime does not run functions embedded in a definition. For parsed JSON, call `parseMachine(JSON.parse(text))` to get a detached, typed definition. Unknown properties, invalid shapes, and invalid bindings throw `ReluTraceError` (`code: 'VALIDATION_ERROR'`) naming the field that failed validation; `-0` values are normalized to `0`. RAM bank sizes are bounded by `MAX_BANK_SIZE` (`1,048,576` cells). Definitions and snapshots are trusted local inputs, not a hardened interchange format for untrusted uploads.
|
|
4
|
+
|
|
5
|
+
```json
|
|
6
|
+
{
|
|
7
|
+
"version": 1,
|
|
8
|
+
"entry": "add",
|
|
9
|
+
"registers": { "count": { "min": 0, "max": 8 } },
|
|
10
|
+
"banks": {},
|
|
11
|
+
"instructions": {
|
|
12
|
+
"add": {
|
|
13
|
+
"inputs": { "old": "count" },
|
|
14
|
+
"gates": [{ "id": "incremented", "bias": 1, "terms": [{ "from": "old", "weight": 1 }] }],
|
|
15
|
+
"set": { "count": "incremented" },
|
|
16
|
+
"next": null
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
`entry` is the conventional starting instruction. An explicit snapshot has `instruction` (a defined instruction name, or `null` for already halted), `registers` (all declared names with initial values), and `ram` (all declared banks with dense arrays of exactly `size` cells each). Identifiers match `[A-Za-z_][A-Za-z0-9_-]*`. Signal identifiers are unique within their instruction. The stable identity of an activation is `(instruction, signal)`; its occurrence adds the one-based tick number. Definitions and starting state are copied on session creation; `snapshot()` returns a detached copy.
|
|
23
|
+
|
|
24
|
+
## One tick
|
|
25
|
+
|
|
26
|
+
1. Resolve `inputs` as **signal name → register name**, using the old state. Evaluate optional `reads` in array order. A read has `{ id, bank, address }`; `address` names a register input or an earlier read signal. All reads see pre-tick RAM. If you need a read address computed by gates, put the address into a register and read on the next instruction.
|
|
27
|
+
2. Evaluate `gates` in array order. Each term references an earlier signal (`from`), multiplied by its integer `weight`; terms are added in array order starting with `bias`. The result is `max(0, sum)`. If an intervention matches this tick, instruction, and gate, consumers see zero instead; the trace preserves both computed activation and effective output.
|
|
28
|
+
3. Resolve `next`: an instruction name, `null` to halt, or `{ test, yes, no }`. `test` names a bit signal; `yes` is selected for `1`. Resolve optional `set` as **register destination → signal name**. Each optional `writes` entry has `{ bank, address, value, when? }`; `address`, `value`, and `when` are signal names. Omitted `when` enables the write; `0` skips it, including dynamic address/value checks. Conditions are exactly `0` or `1`, never JS truthiness.
|
|
29
|
+
4. Validate every proposed update before committing any. Enabled writes commit in array order; if two target the same address, the later one wins. Each traced write's `before` records the pre-tick cell. Enabled writes of an unchanged value are still recorded. `changes` lists only registers whose values changed. Failed ticks leave all state, including the instruction, untouched.
|
|
30
|
+
|
|
31
|
+
## Numbers, stopping, and evidence
|
|
32
|
+
|
|
33
|
+
- **Checked integers:** inclusive register and RAM cell bounds; addresses between `0` and `size - 1`. Integers must be exactly representable safe JS integers. Every product and partial sum must also be a safe integer; cancellation after an overflow does not make it valid. There is no rounding/clipping to Float32. Negative gates' pre-activations are allowed; ReLU output is nonnegative. This is dynamic checking of attempted execution, not static proof of all reachable values.
|
|
34
|
+
- **Construction vs execution:** an invalid definition, snapshot, limit or clamp option throws `ReluTraceError` (`code: 'VALIDATION_ERROR'`) on creation. A dynamic arithmetic (`ARITHMETIC_OVERFLOW`), bit (`INVALID_CONDITION`), address (`INVALID_ADDRESS`) or bounds (`OUT_OF_RANGE`) failure sets `status = 'invalid'`; `error` and `errorCode` are available even with tracing off, and invalid trace records include `code`. The failed attempt counts as a tick. `halt` means the machine chose `null` (including on its last allowed tick); `budget` means the last permitted tick committed and left a next instruction. After any terminal outcome, `step` does not advance.
|
|
35
|
+
- **Tracing:** `step()` returns one trace by default (or `undefined` after a terminal outcome). `step({ trace: false })` executes without collecting explanatory records; `run()` returns an empty history by default. `run({ trace: true })` returns the traces of the remaining attempted ticks. The core never keeps a hidden history. `mountInspector` keeps history for its own bounded session (default 128 ticks, configurable up to 1,000); it previews the first 16 cells per bank with an expand toggle for larger banks and shows any traced read/write address. The browser replays synchronously, intended for small machines.
|
|
36
|
+
- **Comparison:** `compareTick` compares committed next instruction, then ordered writes (bank/address/value), then changed register values, with register names sorted (no-op `{ before, value }` entries where `before === value` in `expected.changes` are treated as unchanged). The browser highlights the earliest differing tick. It stops consulting the reference after a difference, because the actual state may now differ from the reference's. A clamp is one counterfactual with the same snapshot, not a proof that a signal is necessary in all contexts.
|
package/package.json
CHANGED
|
@@ -1,6 +1,61 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "relu-trace",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "A browser debugger for hand-built ReLU state machines",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "Daniel Rodríguez",
|
|
7
|
+
"keywords": [
|
|
8
|
+
"relu",
|
|
9
|
+
"state-machine",
|
|
10
|
+
"debugger",
|
|
11
|
+
"circuit",
|
|
12
|
+
"neural-network",
|
|
13
|
+
"trace",
|
|
14
|
+
"inspector"
|
|
15
|
+
],
|
|
16
|
+
"homepage": "https://sadasant.github.io/ReLU-Trace/",
|
|
17
|
+
"bugs": {
|
|
18
|
+
"url": "https://github.com/sadasant/ReLU-Trace/issues"
|
|
19
|
+
},
|
|
20
|
+
"repository": {
|
|
21
|
+
"type": "git",
|
|
22
|
+
"url": "git+https://github.com/sadasant/ReLU-Trace.git"
|
|
23
|
+
},
|
|
24
|
+
"type": "module",
|
|
25
|
+
"sideEffects": false,
|
|
26
|
+
"engines": {
|
|
27
|
+
"node": ">=22"
|
|
28
|
+
},
|
|
29
|
+
"exports": {
|
|
30
|
+
".": {
|
|
31
|
+
"types": "./dist/index.d.ts",
|
|
32
|
+
"default": "./dist/index.js"
|
|
33
|
+
},
|
|
34
|
+
"./browser": {
|
|
35
|
+
"types": "./dist/browser.d.ts",
|
|
36
|
+
"default": "./dist/browser.js"
|
|
37
|
+
}
|
|
38
|
+
},
|
|
39
|
+
"files": [
|
|
40
|
+
"LICENSE",
|
|
41
|
+
"dist",
|
|
42
|
+
"docs"
|
|
43
|
+
],
|
|
44
|
+
"scripts": {
|
|
45
|
+
"build": "tsc -p tsconfig.json",
|
|
46
|
+
"typecheck": "npm run build && tsc -p tsconfig.check.json",
|
|
47
|
+
"lint": "biome lint .",
|
|
48
|
+
"format": "biome format --write .",
|
|
49
|
+
"build:playground": "npm run build && node scripts/build-playground.mjs",
|
|
50
|
+
"test": "npm run build && node --test test/*.test.mjs",
|
|
51
|
+
"test:package": "npm run build && node scripts/check-package.mjs",
|
|
52
|
+
"test:e2e": "npm run build:playground && node scripts/check-package.mjs && playwright test",
|
|
53
|
+
"prepack": "npm run build"
|
|
54
|
+
},
|
|
55
|
+
"devDependencies": {
|
|
56
|
+
"@biomejs/biome": "2.6.9",
|
|
57
|
+
"@playwright/test": "1.65.2",
|
|
58
|
+
"@types/node": "26.6.11",
|
|
59
|
+
"typescript": "7.0.2"
|
|
60
|
+
}
|
|
61
|
+
}
|