-
Notifications
You must be signed in to change notification settings - Fork 111
Expand file tree
/
Copy pathbitgpt.html
More file actions
1515 lines (1290 loc) · 49.2 KB
/
bitgpt.html
File metadata and controls
1515 lines (1290 loc) · 49.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>BitGPT</title>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@4.22.0/dist/tf.min.js"></script>
<style>
:root {
--bg: #f6f8fb;
--panel: #ffffff;
--text: #1f2937;
--muted: #6b7280;
--accent: #2563eb;
--accent2: #ea580c;
--border: #dbe3ef;
--ok: #166534;
--warn: #92400e;
--err: #991b1b;
}
* { box-sizing: border-box; }
body {
margin: 0;
font-family: Inter, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
background: var(--bg);
color: var(--text);
}
.wrap {
max-width: 1600px;
margin: 0 auto;
padding: 18px;
}
h1, h2, h3 {
margin: 0 0 10px 0;
}
p {
line-height: 1.5;
margin: 0 0 10px 0;
}
.lead {
font-size: 1rem;
color: #334155;
margin-bottom: 8px;
}
.sublead {
color: var(--muted);
max-width: 1100px;
margin-bottom: 16px;
}
.heroNote {
margin-top: 10px;
padding: 12px 14px;
border-radius: 14px;
border: 1px solid var(--border);
background: linear-gradient(180deg, #fbfdff 0%, #f6faff 100%);
color: #334155;
}
.grid {
display: grid;
grid-template-columns: 420px 1fr;
gap: 16px;
align-items: start;
}
.panel {
background: var(--panel);
border: 1px solid var(--border);
border-radius: 16px;
box-shadow: 0 8px 26px rgba(15, 23, 42, 0.06);
padding: 16px;
}
.stack {
display: grid;
gap: 16px;
}
.row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
margin-bottom: 12px;
}
label {
display: block;
font-weight: 600;
margin-bottom: 6px;
}
select, input, textarea, button {
width: 100%;
font: inherit;
padding: 10px 12px;
border-radius: 10px;
border: 1px solid #cfd8e6;
background: #fff;
color: var(--text);
}
textarea {
min-height: 110px;
resize: vertical;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
button {
cursor: pointer;
font-weight: 700;
background: #f8fafc;
}
button.primary {
background: var(--accent);
color: white;
border-color: var(--accent);
}
button.secondary {
background: #eff6ff;
color: #1d4ed8;
border-color: #bfdbfe;
}
button.warn {
background: #fff7ed;
color: #9a3412;
border-color: #fed7aa;
}
.btnrow {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 10px;
margin-top: 10px;
}
.btnrow3 {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
margin-top: 10px;
}
.tiny {
color: var(--muted);
font-size: 0.92rem;
margin-top: 6px;
line-height: 1.45;
}
.pill {
display: inline-block;
padding: 5px 10px;
border-radius: 999px;
font-size: 0.85rem;
font-weight: 700;
margin-right: 6px;
border: 1px solid var(--border);
background: #f8fafc;
}
.ok { color: var(--ok); }
.warnText { color: var(--warn); }
.errText { color: var(--err); }
.graphs {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 12px;
}
.graphCard {
border: 1px solid var(--border);
border-radius: 14px;
overflow: hidden;
background: #fcfdff;
}
.graphHead {
padding: 10px 12px;
font-weight: 700;
border-bottom: 1px solid var(--border);
background: #f8fbff;
}
svg {
width: 100%;
height: 540px;
display: block;
background: linear-gradient(180deg, #ffffff 0%, #fafcff 100%);
}
table {
width: 100%;
border-collapse: collapse;
font-size: 0.92rem;
}
th, td {
border-bottom: 1px solid var(--border);
text-align: left;
padding: 8px 10px;
vertical-align: top;
}
th {
background: #f8fafc;
position: sticky;
top: 0;
z-index: 1;
}
.tableWrap {
max-height: 360px;
overflow: auto;
border: 1px solid var(--border);
border-radius: 12px;
}
pre.log {
white-space: pre-wrap;
word-break: break-word;
background: #0f172a;
color: #e2e8f0;
border-radius: 12px;
padding: 12px;
min-height: 180px;
max-height: 360px;
overflow: auto;
margin: 0;
font-size: 0.85rem;
}
.examples {
max-height: 240px;
overflow: auto;
border: 1px solid var(--border);
border-radius: 12px;
padding: 10px;
background: #fbfdff;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 0.9rem;
line-height: 1.45;
}
.mono {
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
.status {
padding: 10px 12px;
border-radius: 12px;
background: #f8fafc;
border: 1px solid var(--border);
font-weight: 600;
min-height: 44px;
}
.manualBox {
display: grid;
gap: 10px;
}
.manualResult {
padding: 10px 12px;
border-radius: 12px;
background: #fbfdff;
border: 1px solid var(--border);
min-height: 44px;
line-height: 1.45;
}
.footer {
margin-top: 14px;
text-align: right;
color: var(--muted);
font-size: 0.92rem;
}
@media (max-width: 1200px) {
.grid { grid-template-columns: 1fr; }
.graphs { grid-template-columns: 1fr; }
}
</style>
</head>
<body>
<div class="wrap">
<h1>BitGPT as a finite state machine</h1>
<p class="lead">
A tiny causal autoregressive transformer for next-bit prediction.
</p>
<p class="sublead">
This demo models a causal autoregressive generator of binary strings over the alphabet <span class="mono">{0,1}</span>. For a fixed context length <span class="mono">k</span>, it learns the conditional distribution of the next bit from the previous <span class="mono">k</span> bits, using one training family at a time, such as copy, invert, XOR, majority, or an empirical sequence. Since there are only <span class="mono">2<sup>k</sup></span> possible contexts, the problem can be viewed as a finite-state machine whose states are the length-<span class="mono">k</span> contexts and whose transitions are induced by appending the next bit and shifting the window. In that sense, GPT-style models can be seen as vastly larger learned autoregressive systems over much richer token alphabets and state representations.
</p>
<div class="sublead">
<strong>Computational perspective.</strong>
A transformer language model is not itself a Turing machine because it operates with finite parameters and a finite context window. In that sense it behaves like a very large learned state machine. However, if the generated sequence is treated as external memory and the model repeatedly reads and writes to it, the system can emulate arbitrary algorithms. For this reason transformer architectures are often described as computationally universal in principle.
</p>
<div class="sublead">
<strong>Architecture.</strong> The model is a single-block decoder-only transformer. Each input bit <span class="mono">x<sub>i</sub> ∈ {0,1}</span> is mapped to a learned token embedding and added to a learned positional embedding. The resulting length-<span class="mono">k</span> sequence is processed by masked multi-head self-attention, where the mask enforces that position <span class="mono">i</span> can attend only to positions <span class="mono">j ≤ i</span>. This is followed by a position-wise feed-forward MLP, with residual connections and layer normalisation around both sublayers. The hidden vector at the final position is then projected to two logits, which are converted by softmax into <span class="mono">P(x<sub>t+1</sub>=0 | x<sub>t-k+1:t</sub>)</span> and <span class="mono">P(x<sub>t+1</sub>=1 | x<sub>t-k+1:t</sub>)</span>.
</div>
<p class="tiny">
<strong>Usage.</strong> Choose a preset rule or sequence, set the context window, click <em>Build data</em>, then <em>Train model</em>. Compare the target and learned transition graphs and inspect the predicted next-bit probabilities for each context state.
</p>
<div class="grid" style="margin-top: 16px;">
<div class="stack">
<div class="panel">
<h2>Controls</h2>
<div class="row">
<div>
<label for="preset">Preset</label>
<select id="preset">
<option value="xor_rule">XOR / parity rule</option>
<option value="copy_rule">Copy last bit rule</option>
<option value="invert_rule">Invert last bit rule</option>
<option value="majority_rule">Majority rule</option>
<option value="alternating_seq">Alternating sequence 0101...</option>
<option value="blocks_seq">Block sequence 00110011...</option>
<option value="debruijn_seq">De Bruijn-like sequence</option>
<option value="noisy_seq">Noisy biased sequence</option>
<option value="custom_sequence">Custom bit sequence</option>
</select>
</div>
<div>
<label for="contextWindow">Context window</label>
<input id="contextWindow" type="number" min="1" max="6" value="2" />
</div>
</div>
<div class="row">
<div>
<label for="epochs">Epochs</label>
<input id="epochs" type="number" min="1" max="2000" value="300" />
</div>
<div>
<label for="learningRate">Learning rate</label>
<input id="learningRate" type="number" min="0.0001" max="0.1" step="0.0001" value="0.01" />
</div>
</div>
<div class="row">
<div>
<label for="embedDim">Embedding size</label>
<input id="embedDim" type="number" min="4" max="128" step="2" value="32" />
</div>
<div>
<label for="numHeads">Attention heads</label>
<input id="numHeads" type="number" min="1" max="8" step="1" value="4" />
</div>
</div>
<div>
<label for="sequenceInput">Bit sequence</label>
<textarea id="sequenceInput">0101010101010101</textarea>
<div class="tiny">
Used for sequence-based presets or custom sequence mode. Spaces and new lines are ignored.
</div>
<div class="tiny" id="presetInfoBox">
Current preset example: 0101010101010101
</div>
</div>
<div class="btnrow3">
<button id="applyPresetBtn" class="secondary">Apply preset</button>
<button id="buildBtn">Build data</button>
<button id="resetBtn" class="warn">Reset model</button>
</div>
<div class="btnrow">
<button id="trainBtn" class="primary">Train model</button>
<button id="sampleBtn">Sample sequence</button>
</div>
<div style="margin-top: 12px; display: grid; gap: 10px;">
<div class="status" id="statusBox">Ready.</div>
<div>
<span class="pill" id="modeBadge">Mode: rule</span>
<span class="pill" id="stateBadge">States: 4</span>
<span class="pill" id="exampleBadge">Examples: 4</span>
</div>
</div>
</div>
<div class="panel">
<h2>Manual autoregressive test</h2>
<div class="manualBox">
<div>
<label for="manualInput">Editable bit string</label>
<textarea id="manualInput">01</textarea>
<div class="tiny">
Type any bit string here. On each click, the model looks at the last <span class="mono">k</span> bits, predicts the next bit, and appends it.
</div>
</div>
<div class="btnrow">
<button id="predictNextBtn" class="primary">Predict next bit</button>
<button id="manualClearBtn">Clear / reset</button>
</div>
<div id="manualResultBox" class="manualResult">
No manual prediction yet.
</div>
</div>
</div>
<div class="panel">
<h2>Examples extracted from the current dataset</h2>
<div id="examplesBox" class="examples">No data built yet.</div>
</div>
<div class="panel">
<h2>Debug log</h2>
<pre class="log" id="logBox"></pre>
</div>
</div>
<div class="stack">
<div class="panel">
<h2>Transition graphs</h2>
<div class="tiny">
Each node is a context state. A coloured edge shows the probability of appending bit 0 or bit 1 and then shifting the context window forward. The target graph comes from the rule or sequence. The before and after graphs come from the transformer.
</div>
<div class="graphs" style="margin-top: 12px;">
<div class="graphCard">
<div class="graphHead">Target transition graph</div>
<svg id="targetGraph"></svg>
</div>
<div class="graphCard">
<div class="graphHead">Model before training</div>
<svg id="beforeGraph"></svg>
</div>
<div class="graphCard">
<div class="graphHead">Model after training</div>
<svg id="afterGraph"></svg>
</div>
</div>
</div>
<div class="panel">
<h2>Transition probability table</h2>
<div class="tableWrap">
<table>
<thead>
<tr>
<th>State</th>
<th>Target P(0)</th>
<th>Target P(1)</th>
<th>Before P(0)</th>
<th>Before P(1)</th>
<th>After P(0)</th>
<th>After P(1)</th>
</tr>
</thead>
<tbody id="probTableBody"></tbody>
</table>
</div>
</div>
<div class="panel">
<h2>Training summary and sampling</h2>
<div id="metricsBox" class="examples">No training yet.</div>
</div>
</div>
</div>
<div class="footer">(c) Fayyaz Minhas</div>
</div>
<script>
const appState = {
dataset: null,
model: null,
beforeProbs: null,
afterProbs: null,
trainingHistory: [],
lastSample: null,
};
const COLORS = {
bit0: '#2563eb',
bit1: '#ea580c',
node: '#0f172a',
label: '#334155',
bg: '#ffffff',
};
const NODE_RADIUS = 18;
const EDGE_PAD = 24;
const LOOP_R = 28;
function el(id) {
return document.getElementById(id);
}
function nowStamp() {
const d = new Date();
return d.toLocaleTimeString();
}
function appendLog(text) {
const box = el('logBox');
box.textContent += `[${nowStamp()}] ${text}\n`;
box.scrollTop = box.scrollHeight;
}
function formatError(err) {
if (!err) return 'Unknown error';
const msg = [];
if (err.name) msg.push(`name: ${err.name}`);
if (err.message) msg.push(`message: ${err.message}`);
if (err.stack) msg.push(`stack:\n${err.stack}`);
else msg.push(String(err));
return msg.join('\n');
}
function logError(context, err) {
appendLog(`ERROR in ${context}\n${formatError(err)}`);
setStatus(`Error in ${context}. See debug log for details.`, 'errText');
}
window.onerror = function(message, source, lineno, colno, error) {
logError(`window.onerror at ${source || 'unknown source'}:${lineno || '?'}:${colno || '?'}`, error || new Error(String(message)));
};
window.onunhandledrejection = function(event) {
logError('unhandled promise rejection', event.reason || new Error('Unknown promise rejection'));
};
function setStatus(text, cls = '') {
const box = el('statusBox');
box.className = `status ${cls}`.trim();
box.textContent = text;
}
function safeNumber(value, fallback) {
const x = Number(value);
return Number.isFinite(x) ? x : fallback;
}
function allBinaryStates(k) {
const out = [];
const n = Math.pow(2, k);
for (let i = 0; i < n; i++) {
out.push(i.toString(2).padStart(k, '0'));
}
return out;
}
function cleanBitString(raw) {
return String(raw || '').replace(/\s+/g, '');
}
function parseBitSequence(raw) {
const clean = cleanBitString(raw);
if (!clean.length) {
throw new Error('Sequence is empty after removing spaces and new lines.');
}
if (!/^[01]+$/.test(clean)) {
throw new Error(`Sequence contains characters other than 0 and 1. Received: ${JSON.stringify(clean)}`);
}
return clean.split('').map(ch => Number(ch));
}
function xorBit(bits) {
return bits.reduce((acc, b) => acc ^ b, 0);
}
function majorityBit(bits) {
const ones = bits.reduce((a, b) => a + b, 0);
return ones >= Math.ceil(bits.length / 2) ? 1 : 0;
}
function getPresetExample(name, k) {
const presets = {
alternating_seq: '01010101010101010101010101010101',
blocks_seq: '00110011001100110011001100110011',
debruijn_seq: '0001011100',
noisy_seq: '11110111101111011100111101110110',
};
if (name in presets) return presets[name];
if (name === 'custom_sequence') return el('sequenceInput').value;
if (name === 'xor_rule') return `Rule example with k=${k}: the next bit is the XOR of the previous ${k} bits`;
if (name === 'copy_rule') return `Rule example with k=${k}: the next bit copies the last observed bit`;
if (name === 'invert_rule') return `Rule example with k=${k}: the next bit flips the last observed bit`;
if (name === 'majority_rule') return `Rule example with k=${k}: the next bit is the majority among the previous ${k} bits}`;
return '';
}
function updatePresetInfo() {
const preset = el('preset').value;
const k = Math.max(1, Math.min(6, Math.floor(safeNumber(el('contextWindow').value, 2))));
const info = getPresetExample(preset, k);
el('presetInfoBox').textContent = `Current preset example: ${info}`;
}
function buildRuleDataset(ruleName, k) {
const states = allBinaryStates(k);
const examples = [];
const target = {};
for (const s of states) {
const bits = s.split('').map(Number);
let y;
if (ruleName === 'xor_rule') y = xorBit(bits);
else if (ruleName === 'copy_rule') y = bits[bits.length - 1];
else if (ruleName === 'invert_rule') y = 1 - bits[bits.length - 1];
else if (ruleName === 'majority_rule') y = majorityBit(bits);
else throw new Error(`Unknown rule preset: ${ruleName}`);
examples.push({ x: bits.slice(), y });
target[s] = { 0: y === 0 ? 1 : 0, 1: y === 1 ? 1 : 0, observed: true };
}
return {
mode: 'rule',
name: ruleName,
k,
sequenceText: getPresetExample(ruleName, k),
states,
examples,
target,
};
}
function buildSequenceDataset(sequenceBits, k) {
if (sequenceBits.length <= k) {
throw new Error(`Sequence length (${sequenceBits.length}) must be greater than context window (${k}).`);
}
const states = allBinaryStates(k);
const examples = [];
const counts = {};
for (const s of states) counts[s] = { 0: 0, 1: 0, observed: false };
for (let i = 0; i < sequenceBits.length - k; i++) {
const x = sequenceBits.slice(i, i + k);
const y = sequenceBits[i + k];
const s = x.join('');
examples.push({ x, y });
counts[s][y] += 1;
counts[s].observed = true;
}
const target = {};
for (const s of states) {
const c0 = counts[s][0];
const c1 = counts[s][1];
const total = c0 + c1;
if (total > 0) {
target[s] = { 0: c0 / total, 1: c1 / total, observed: true };
} else {
target[s] = { 0: null, 1: null, observed: false };
}
}
return {
mode: 'sequence',
name: 'sequence',
k,
sequenceText: sequenceBits.join(''),
states,
examples,
target,
};
}
function makeDatasetFromUI() {
const preset = el('preset').value;
const k = Math.max(1, Math.min(6, Math.floor(safeNumber(el('contextWindow').value, 2))));
el('contextWindow').value = String(k);
if (preset.endsWith('_rule')) {
return buildRuleDataset(preset, k);
}
const bits = parseBitSequence(el('sequenceInput').value);
return buildSequenceDataset(bits, k);
}
function updateExamplesBox(dataset) {
const lines = [];
lines.push(`Mode: ${dataset.mode}`);
lines.push(`Context window: ${dataset.k}`);
lines.push(`States: ${dataset.states.length}`);
lines.push(`Examples: ${dataset.examples.length}`);
lines.push('');
const maxShow = Math.min(dataset.examples.length, 120);
for (let i = 0; i < maxShow; i++) {
const ex = dataset.examples[i];
lines.push(`${String(i + 1).padStart(3, ' ')}: ${ex.x.join('')} -> ${ex.y}`);
}
if (dataset.examples.length > maxShow) {
lines.push('...');
}
el('examplesBox').textContent = lines.join('\n');
el('modeBadge').textContent = `Mode: ${dataset.mode}`;
el('stateBadge').textContent = `States: ${dataset.states.length}`;
el('exampleBadge').textContent = `Examples: ${dataset.examples.length}`;
}
function updateSequenceForPreset() {
try {
const preset = el('preset').value;
const k = Math.max(1, Math.min(6, Math.floor(safeNumber(el('contextWindow').value, 2))));
const text = getPresetExample(preset, k);
if (!preset.endsWith('_rule')) {
el('sequenceInput').value = text;
}
updatePresetInfo();
appendLog(`Applied preset ${preset} with context ${k}.`);
} catch (err) {
logError('updateSequenceForPreset', err);
}
}
function toXYArrays(dataset) {
const xs = dataset.examples.map(ex => ex.x);
const ys = dataset.examples.map(ex => ex.y);
return { xs, ys };
}
function randVar(shape, scale = 0.02, name = '') {
return tf.variable(tf.randomNormal(shape, 0, scale, 'float32'), true, name);
}
class TinyTransformerBitModel {
constructor(config) {
this.vocabSize = 2;
this.k = config.k;
this.dModel = config.dModel;
this.numHeads = config.numHeads;
if (this.dModel % this.numHeads !== 0) {
throw new Error(`Embedding size ${this.dModel} must be divisible by number of heads ${this.numHeads}.`);
}
this.headDim = this.dModel / this.numHeads;
this.ffDim = config.ffDim || (2 * this.dModel);
this.init();
}
init() {
this.tokenEmb = randVar([this.vocabSize, this.dModel], 0.08, 'tokenEmb');
this.posEmb = randVar([this.k, this.dModel], 0.08, 'posEmb');
this.Wq = randVar([this.dModel, this.dModel], 0.06, 'Wq');
this.Wk = randVar([this.dModel, this.dModel], 0.06, 'Wk');
this.Wv = randVar([this.dModel, this.dModel], 0.06, 'Wv');
this.Wo = randVar([this.dModel, this.dModel], 0.06, 'Wo');
this.ln1g = tf.variable(tf.ones([this.dModel]), true, 'ln1g');
this.ln1b = tf.variable(tf.zeros([this.dModel]), true, 'ln1b');
this.ln2g = tf.variable(tf.ones([this.dModel]), true, 'ln2g');
this.ln2b = tf.variable(tf.zeros([this.dModel]), true, 'ln2b');
this.W1 = randVar([this.dModel, this.ffDim], 0.06, 'W1');
this.b1 = tf.variable(tf.zeros([this.ffDim]), true, 'b1');
this.W2 = randVar([this.ffDim, this.dModel], 0.06, 'W2');
this.b2 = tf.variable(tf.zeros([this.dModel]), true, 'b2');
this.Wout = randVar([this.dModel, this.vocabSize], 0.06, 'Wout');
this.bout = tf.variable(tf.zeros([this.vocabSize]), true, 'bout');
}
dispose() {
const vars = [
this.tokenEmb, this.posEmb,
this.Wq, this.Wk, this.Wv, this.Wo,
this.ln1g, this.ln1b, this.ln2g, this.ln2b,
this.W1, this.b1, this.W2, this.b2,
this.Wout, this.bout,
];
vars.forEach(v => v.dispose());
}
layerNorm(x, g, b, eps = 1e-5) {
return tf.tidy(() => {
const mean = tf.mean(x, -1, true);
const variance = tf.mean(tf.square(x.sub(mean)), -1, true);
const g3 = g.reshape([1, 1, this.dModel]);
const b3 = b.reshape([1, 1, this.dModel]);
return x.sub(mean).div(tf.sqrt(variance.add(eps))).mul(g3).add(b3);
});
}
dense3d(x, W, b = null) {
return tf.tidy(() => {
const [B, T, C] = x.shape;
const x2 = x.reshape([B * T, C]);
let y2 = tf.matMul(x2, W);
if (b) y2 = y2.add(b);
const outDim = W.shape[1];
return y2.reshape([B, T, outDim]);
});
}
dense2d(x, W, b = null) {
return tf.tidy(() => {
let y = tf.matMul(x, W);
if (b) y = y.add(b);
return y;
});
}
causalMask(T) {
const arr = [];
for (let i = 0; i < T; i++) {
const row = [];
for (let j = 0; j < T; j++) {
row.push(j <= i ? 0 : -1e9);
}
arr.push(row);
}
return tf.tensor4d(arr.flat(), [1, 1, T, T], 'float32');
}
selfAttention(h) {
return tf.tidy(() => {
const [B, T, C] = h.shape;
const q = this.dense3d(h, this.Wq);
const k = this.dense3d(h, this.Wk);
const v = this.dense3d(h, this.Wv);
const qh = tf.transpose(tf.reshape(q, [B, T, this.numHeads, this.headDim]), [0, 2, 1, 3]);
const kh = tf.transpose(tf.reshape(k, [B, T, this.numHeads, this.headDim]), [0, 2, 1, 3]);
const vh = tf.transpose(tf.reshape(v, [B, T, this.numHeads, this.headDim]), [0, 2, 1, 3]);
const scores = tf.matMul(qh, kh, false, true).div(Math.sqrt(this.headDim));
const mask = this.causalMask(T);
const probs = tf.softmax(scores.add(mask), -1);
const ctx = tf.matMul(probs, vh);
const merged = tf.reshape(tf.transpose(ctx, [0, 2, 1, 3]), [B, T, C]);
return this.dense3d(merged, this.Wo);
});
}
ff(h) {
return tf.tidy(() => {
const hidden = tf.relu(this.dense3d(h, this.W1, this.b1));
return this.dense3d(hidden, this.W2, this.b2);
});
}
forward(xInt) {
return tf.tidy(() => {
const [B, T] = xInt.shape;
if (T !== this.k) {
throw new Error(`Model expected context length ${this.k}, but received ${T}.`);
}
const token = tf.gather(this.tokenEmb, xInt);
const pos = tf.tile(tf.expandDims(this.posEmb, 0), [B, 1, 1]);
const h0 = token.add(pos);
const a = this.layerNorm(h0, this.ln1g, this.ln1b);
const h1 = h0.add(this.selfAttention(a));
const b = this.layerNorm(h1, this.ln2g, this.ln2b);
const h2 = h1.add(this.ff(b));
const last = h2.slice([0, this.k - 1, 0], [-1, 1, -1]).squeeze([1]);
return this.dense2d(last, this.Wout, this.bout);
});
}
predictProbs(xInt) {
return tf.tidy(() => tf.softmax(this.forward(xInt), -1));
}
}
async function resetModelFromUI() {
try {
const dataset = appState.dataset || makeDatasetFromUI();
const dModel = Math.floor(safeNumber(el('embedDim').value, 32));
const numHeads = Math.floor(safeNumber(el('numHeads').value, 4));
if (appState.model) {
appState.model.dispose();
appState.model = null;
}
appState.model = new TinyTransformerBitModel({
k: dataset.k,
dModel,
numHeads,
ffDim: Math.max(8, 2 * dModel),
});
appendLog(`Initialised TinyTransformerBitModel with context=${dataset.k}, dModel=${dModel}, heads=${numHeads}.`);
setStatus('Model reset successfully.', 'ok');
} catch (err) {
logError('resetModelFromUI', err);
throw err;
}
}
async function evaluateModelOnAllStates(model, states, k) {
return tf.tidy(() => {
const xs = states.map(s => s.split('').map(Number));
const xTensor = tf.tensor2d(xs, [xs.length, k], 'int32');
const probs = model.predictProbs(xTensor);
const arr = probs.arraySync();
const out = {};
states.forEach((s, i) => {
out[s] = { 0: arr[i][0], 1: arr[i][1], observed: true };
});
return out;
});
}
function stateNext(s, bit) {
return s.slice(1) + String(bit);
}
function probText(x) {
if (x === null || x === undefined || Number.isNaN(x)) return '?';
return x.toFixed(3);
}
function clearSVG(svg) {
while (svg.firstChild) svg.removeChild(svg.firstChild);
}
function svgEl(name, attrs = {}) {
const node = document.createElementNS('http://www.w3.org/2000/svg', name);
for (const [k, v] of Object.entries(attrs)) node.setAttribute(k, String(v));
return node;
}
function drawArrowDefs(svg, suffix) {
const defs = svgEl('defs');
const mk0 = svgEl('marker', {
id: `arrow0_${suffix}`,
markerWidth: 10,
markerHeight: 10,
refX: 9,
refY: 3,
orient: 'auto',
markerUnits: 'strokeWidth',
});
mk0.appendChild(svgEl('path', { d: 'M0,0 L0,6 L9,3 z', fill: COLORS.bit0 }));
const mk1 = svgEl('marker', {
id: `arrow1_${suffix}`,
markerWidth: 10,
markerHeight: 10,
refX: 9,
refY: 3,
orient: 'auto',
markerUnits: 'strokeWidth',
});
mk1.appendChild(svgEl('path', { d: 'M0,0 L0,6 L9,3 z', fill: COLORS.bit1 }));
defs.appendChild(mk0);
defs.appendChild(mk1);
svg.appendChild(defs);
}
function nodePositions(states, width, height) {
const n = states.length;
const cx = width / 2;
const cy = height / 2;
const radius = Math.min(width, height) * 0.34;
const pos = {};
states.forEach((s, i) => {
const theta = -Math.PI / 2 + (2 * Math.PI * i) / n;
pos[s] = {
x: cx + radius * Math.cos(theta),
y: cy + radius * Math.sin(theta),
theta,
};
});
return pos;
}