relu-trace 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +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 +88 -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,88 @@
|
|
|
1
|
+
export const inspectorCSS = `
|
|
2
|
+
:host {
|
|
3
|
+
display: block;
|
|
4
|
+
min-width: 0;
|
|
5
|
+
container-type: inline-size;
|
|
6
|
+
/* Each public --relu-* token is read with a fallback, so a value set on the host or inherited from any ancestor applies. */
|
|
7
|
+
--_bg: var(--relu-bg, #131815);
|
|
8
|
+
--_surface: var(--relu-surface, #1b221e);
|
|
9
|
+
--_panel: var(--relu-panel, #191f1b);
|
|
10
|
+
--_ink: var(--relu-ink, #eaece6);
|
|
11
|
+
--_muted: var(--relu-muted, #a4afa7);
|
|
12
|
+
--_accent: var(--relu-accent, #c6f57b);
|
|
13
|
+
--_rule: var(--relu-rule, #303632);
|
|
14
|
+
--_mono: var(--relu-mono, ui-monospace, SFMono-Regular, Consolas, monospace);
|
|
15
|
+
--_font: var(--relu-font, 15px/1.45 system-ui, sans-serif);
|
|
16
|
+
--_control-font: var(--relu-control-font, 600 13px/1.2 system-ui, sans-serif);
|
|
17
|
+
--_heading-font: var(--relu-heading-font, 700 15px/1.45 system-ui, sans-serif);
|
|
18
|
+
--_radius: var(--relu-radius, 12px);
|
|
19
|
+
/* Control fills are mixed from ink and background, so a theme only sets the tokens above. */
|
|
20
|
+
--_control: color-mix(in srgb, var(--_ink) 8%, var(--_bg));
|
|
21
|
+
--_control-rule: color-mix(in srgb, var(--_ink) 26%, var(--_bg));
|
|
22
|
+
--_control-hover: color-mix(in srgb, var(--_ink) 17%, var(--_bg));
|
|
23
|
+
--_control-hover-rule: color-mix(in srgb, var(--_ink) 55%, var(--_bg));
|
|
24
|
+
color: var(--_ink);
|
|
25
|
+
}
|
|
26
|
+
.inspector {
|
|
27
|
+
font: var(--_font);
|
|
28
|
+
background: var(--_bg);
|
|
29
|
+
border: 1px solid var(--_rule);
|
|
30
|
+
border-radius: var(--_radius);
|
|
31
|
+
overflow: hidden;
|
|
32
|
+
text-align: left;
|
|
33
|
+
}
|
|
34
|
+
* { box-sizing: border-box; }
|
|
35
|
+
.toolbar, .comparison, .panel-head, .panel-body, .panel-foot, .state { padding: 12px 16px; }
|
|
36
|
+
.toolbar, .actions, .meter, .panel-head, .panel-foot, .comparison { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
|
37
|
+
.toolbar, .panel-head { justify-content: space-between; }
|
|
38
|
+
.toolbar { background: var(--_surface); }
|
|
39
|
+
button, select { font: var(--_control-font); border: 1px solid var(--_control-rule); border-radius: min(5px, var(--_radius)); padding: 8px 12px; background: var(--_control); color: var(--_ink); min-height: 34px; }
|
|
40
|
+
button:not(:disabled) { cursor: pointer; }
|
|
41
|
+
button:hover:not(:disabled), select:hover:not(:disabled) { background: var(--_control-hover); border-color: var(--_control-hover-rule); }
|
|
42
|
+
button:focus-visible, select:focus-visible { outline: 2px solid var(--_accent); outline-offset: 2px; }
|
|
43
|
+
button:disabled, select:disabled { color: color-mix(in srgb, var(--_ink) 53%, var(--_bg)); border-color: var(--_control-hover); background: transparent; }
|
|
44
|
+
button.primary:not(:disabled) { color: var(--_bg); background: var(--_accent); border-color: var(--_accent); }
|
|
45
|
+
button.primary:hover:not(:disabled) { background: color-mix(in srgb, var(--_accent) 70%, white); }
|
|
46
|
+
button[hidden] { display: none; }
|
|
47
|
+
.meter { font: 13px/1.2 var(--_mono); color: var(--_muted); }
|
|
48
|
+
#status { font: var(--_control-font); font-weight: 700; font-size: 12px; padding: 5px 8px; border-radius: min(4px, var(--_radius)); background: color-mix(in srgb, var(--_accent) 18%, var(--_bg)); color: var(--_accent); }
|
|
49
|
+
#status[data-kind="halt"] { color: #b6ead9; background: #233d35; }
|
|
50
|
+
#status[data-kind="budget"], .comparison[data-kind="diff"] strong { color: #ffcf8e; }
|
|
51
|
+
#status[data-kind="invalid"], .comparison[data-kind="error"] strong, .error { color: #ffb0a2; }
|
|
52
|
+
.comparison { background: color-mix(in srgb, var(--_accent) 4%, var(--_bg)); border-top: 1px solid var(--_rule); font-size: 13px; column-gap: 12px; overflow-wrap: anywhere; }
|
|
53
|
+
.comparison[hidden] { display: none; }
|
|
54
|
+
.comparison strong { font: 600 11px/1.2 var(--_mono); letter-spacing: .08em; color: var(--_accent); }
|
|
55
|
+
.comparison[data-kind="diff"] { background: #292216; }
|
|
56
|
+
.comparison[data-kind="error"] { background: #2c1a19; }
|
|
57
|
+
.panels { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); border-top: 1px solid var(--_rule); }
|
|
58
|
+
.panel { display: flex; flex-direction: column; }
|
|
59
|
+
.panel + .panel { border-left: 1px solid var(--_rule); }
|
|
60
|
+
.panel-head { background: var(--_panel); min-height: 58px; border-bottom: 1px solid var(--_rule); }
|
|
61
|
+
.panel-body { flex: 1; overflow-wrap: anywhere; }
|
|
62
|
+
.panel-body:has(> .muted:only-child) { min-height: 112px; }
|
|
63
|
+
.panel-foot { border-top: 1px solid var(--_rule); }
|
|
64
|
+
.state { border-top: 1px solid var(--_rule); background: var(--_panel); overflow-wrap: anywhere; }
|
|
65
|
+
.state h3 span { display: inline-block; font-size: .8em; font-weight: 400; color: var(--_muted); margin-left: 4px; }
|
|
66
|
+
.state dl { grid-template-columns: max-content 1fr; }
|
|
67
|
+
.bank-value { display: flex; align-items: baseline; gap: 8px; flex-wrap: wrap; }
|
|
68
|
+
.bank-toggle { padding: 3px 8px; min-height: 26px; font-size: 11px; }
|
|
69
|
+
h3 { font: var(--_heading-font); margin: 0; }
|
|
70
|
+
h4 { margin: 12px 0 5px; color: var(--_muted); font: 600 11px/1.4 var(--_mono); text-transform: uppercase; letter-spacing: .08em; }
|
|
71
|
+
p { margin: 0; }
|
|
72
|
+
label { display: flex; align-items: center; gap: 6px; color: var(--_muted); font-size: 12px; min-width: 0; }
|
|
73
|
+
select { max-width: min(32ch, 63cqw); color-scheme: dark; }
|
|
74
|
+
.muted { color: var(--_muted); }
|
|
75
|
+
.small { font-size: 13px; }
|
|
76
|
+
.equation { font: 600 16px/1.4 var(--_mono); color: var(--_accent); margin-bottom: 5px; }
|
|
77
|
+
dl { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 4px 12px; margin: 0; font: 13px/1.4 var(--_mono); }
|
|
78
|
+
dt { color: color-mix(in srgb, var(--_ink) 50%, var(--_muted)); } dd { margin: 0; }
|
|
79
|
+
table { width: 100%; border-collapse: collapse; text-align: left; margin-top: 12px; font: 13px/1.4 var(--_mono); }
|
|
80
|
+
th, td { border-bottom: 1px solid var(--_rule); padding: 6px 8px 6px 0; }
|
|
81
|
+
th { color: var(--_muted); font-weight: 500; font-size: 11px; }
|
|
82
|
+
/* Headings and numbers stay whole; a long signal name is the cell that wraps. */
|
|
83
|
+
th, td:not(:first-child) { white-space: nowrap; }
|
|
84
|
+
@container (max-width: 700px) {
|
|
85
|
+
.panels { grid-template-columns: minmax(0, 1fr); }
|
|
86
|
+
.panel + .panel { border-left: none; border-top: 1px solid var(--_rule); }
|
|
87
|
+
}
|
|
88
|
+
`;
|