Repository navigation
Expand file tree
/
Copy pathhtml_builder.py
More file actions
2081 lines (1841 loc) · 87.9 KB
/
Copy pathhtml_builder.py
File metadata and controls
2081 lines (1841 loc) · 87.9 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
"""
html_builder.py — HTML/CSS/JS template builder for the LLM visualizer.
Generates the self-contained HTML page with embedded Three.js 3D visualization,
architecture strip, step panels, and all interactive components.
"""
import json
def build_html(config: dict, data: dict | None, state: str = "idle") -> str:
"""
state: "idle" | "processing" | "complete"
config: always has model config (num_layers, etc.)
data: None for idle/processing, dict for complete
"""
config_json = json.dumps(config)
data_json = json.dumps(data) if data else "null"
return f"""
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@300;400;500;700&family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/controls/OrbitControls.js"></script>
<style>
* {{ margin:0; padding:0; box-sizing:border-box; }}
body {{
background: #0d1117;
color: #c9d1d9;
font-family: 'Inter', sans-serif;
overflow-x: hidden;
}}
.mono {{ font-family: 'JetBrains Mono', monospace; }}
/* ===== HEADER ===== */
.header {{
text-align: center;
padding: 16px 24px 12px;
background: linear-gradient(180deg, #111820 0%, #0d1117 100%);
border-bottom: 1px solid #1e2a3a;
}}
.header h1 {{ font-size: 22px; font-weight: 700; color: #e6edf3; margin-bottom: 4px; }}
.header .stats {{
font-family: 'JetBrains Mono', monospace;
font-size: 11px; color: #6e7681; letter-spacing: 1px;
}}
.header .stats span {{ color: #58a6ff; font-weight: 500; }}
/* ===== INPUT BAR ===== */
.input-section {{
padding: 12px 24px;
border-bottom: 1px solid #1e2a3a;
display: flex;
align-items: center;
gap: 12px;
}}
.input-label {{
font-size: 11px; color: #8b949e; text-transform: uppercase;
letter-spacing: 2px; font-weight: 600; white-space: nowrap;
}}
.input-text {{
font-family: 'JetBrains Mono', monospace;
font-size: 16px; color: #e6edf3; font-weight: 500;
}}
.input-text.idle {{ color: #484f58; font-style: italic; font-weight: 400; font-size: 14px; }}
/* ===== ARCHITECTURE STRIP ===== */
.arch-section {{
padding: 12px 0;
border-bottom: 1px solid #1e2a3a;
background: #0a0e14;
}}
.arch-title {{
padding: 0 24px 8px;
font-size: 11px; color: #8b949e; text-transform: uppercase;
letter-spacing: 2px; font-weight: 600;
display: flex; align-items: center; gap: 8px;
}}
.arch-title .hint {{
font-size: 10px; color: #484f58; letter-spacing: 1px;
text-transform: none; font-weight: 400;
}}
.arch-scroll {{
overflow-x: auto; overflow-y: hidden;
padding: 10px 24px 14px;
display: flex; align-items: center; gap: 0;
scrollbar-width: thin; scrollbar-color: #1e2a3a transparent;
}}
.arch-scroll::-webkit-scrollbar {{ height: 6px; }}
.arch-scroll::-webkit-scrollbar-track {{ background: transparent; }}
.arch-scroll::-webkit-scrollbar-thumb {{ background: #1e2a3a; border-radius: 3px; }}
.a-block {{
flex-shrink: 0;
border: 1px solid; border-radius: 5px;
padding: 6px 10px; text-align: center;
font-family: 'JetBrains Mono', monospace;
font-size: 9px; font-weight: 500;
letter-spacing: 1px; text-transform: uppercase;
cursor: pointer; transition: all 0.25s;
}}
.a-block:hover {{ transform: scale(1.08); z-index: 10; }}
.a-block .blabel {{ font-size: 9px; white-space: nowrap; }}
.a-block .bdetail {{ font-size: 7px; opacity: 0.5; text-transform: none; letter-spacing: 0; margin-top: 1px; white-space: nowrap; }}
.a-block.embed {{ background: rgba(88,166,255,0.10); border-color: rgba(88,166,255,0.4); color: #58a6ff; }}
.a-block.ln {{ background: rgba(63,185,80,0.06); border-color: rgba(63,185,80,0.25); color: #3fb950; padding: 4px 6px; }}
.a-block.attn {{ background: rgba(188,140,255,0.10); border-color: rgba(188,140,255,0.4); color: #bc8cff; }}
.a-block.mlp {{ background: rgba(240,136,62,0.10); border-color: rgba(240,136,62,0.4); color: #f0883e; }}
.a-block.out {{ background: rgba(57,210,192,0.10); border-color: rgba(57,210,192,0.4); color: #39d2c0; }}
.a-block.active {{ transform: scale(1.1); z-index: 10; box-shadow: 0 0 18px rgba(188,140,255,0.3); border-color: #bc8cff !important; }}
/* Processing glow animation */
.a-block.processing {{
animation: procGlow 2s ease-in-out infinite;
}}
@keyframes procGlow {{
0%, 100% {{ filter: brightness(1); }}
50% {{ filter: brightness(1.8); }}
}}
.layer-grp {{
flex-shrink: 0;
display: flex; align-items: center; gap: 0;
padding: 2px 4px;
border: 1px solid transparent; border-radius: 6px;
position: relative; cursor: pointer; transition: all 0.25s;
}}
.layer-grp:hover {{ border-color: #2d3a4a; background: rgba(255,255,255,0.01); }}
.layer-grp.active {{ border-color: rgba(188,140,255,0.3); background: rgba(188,140,255,0.04); }}
.layer-grp .ltag {{
position: absolute; top: -9px; left: 50%; transform: translateX(-50%);
background: #0a0e14; padding: 0 4px;
font-family: 'JetBrains Mono', monospace;
font-size: 7px; color: #484f58; letter-spacing: 1px; white-space: nowrap;
}}
/* Processing wave on layer groups */
.layer-grp.wave {{
animation: layerWave 0.6s ease-out forwards;
}}
@keyframes layerWave {{
0% {{ border-color: transparent; background: transparent; }}
30% {{ border-color: #bc8cff88; background: rgba(188,140,255,0.15); }}
100% {{ border-color: transparent; background: transparent; }}
}}
.arrow {{
flex-shrink: 0; width: 14px; height: 2px;
background: linear-gradient(90deg, #3fb95055, #3fb95020);
position: relative;
}}
.arrow::after {{
content: ''; position: absolute; right: 0; top: -3px;
border-left: 5px solid #3fb95033;
border-top: 4px solid transparent;
border-bottom: 4px solid transparent;
}}
/* Processing: animated flow dots on arrows */
.arrow.flow::before {{
content: '';
position: absolute; top: -2px; left: 0;
width: 6px; height: 6px;
background: #3fb950; border-radius: 50%;
box-shadow: 0 0 8px #3fb950;
animation: flowDot 0.8s ease-in-out infinite;
}}
@keyframes flowDot {{
0% {{ left: 0; opacity: 1; }}
100% {{ left: 14px; opacity: 0; }}
}}
.arrow-inner {{
flex-shrink: 0; width: 5px; height: 1px; background: #ffffff0d;
}}
/* ===== PANELS ===== */
.panels-grid {{
display: grid; grid-template-columns: 1fr 1fr;
gap: 14px; padding: 16px 24px 24px;
}}
.panel {{
background: #111927; border: 1px solid #1e2a3a;
border-radius: 8px; padding: 16px 20px; transition: border-color 0.3s;
}}
.panel:hover {{ border-color: #2d3a4a; }}
.panel-step {{
font-family: 'JetBrains Mono', monospace;
font-size: 10px; font-weight: 700; letter-spacing: 2px;
text-transform: uppercase;
display: flex; align-items: center; gap: 8px;
}}
.panel-step .dot {{ width: 7px; height: 7px; border-radius: 50%; }}
.panel-title {{ font-size: 15px; font-weight: 600; color: #e6edf3; margin: 2px 0 4px; }}
.panel-desc {{ font-size: 12px; color: #8b949e; line-height: 1.5; margin-bottom: 12px; }}
.panel-desc em {{ color: #58a6ff; font-style: normal; font-weight: 500; }}
/* Idle panel placeholder */
.panel-idle {{
text-align: center; padding: 30px 20px; color: #2d3a4a;
font-family: 'JetBrains Mono', monospace; font-size: 12px;
letter-spacing: 1px;
}}
.panel-idle .idle-icon {{ font-size: 28px; margin-bottom: 8px; opacity: 0.4; }}
/* Processing panel */
.panel-proc {{
text-align: center; padding: 30px 20px;
font-family: 'JetBrains Mono', monospace; font-size: 12px;
letter-spacing: 1px; color: #8b949e;
}}
.panel-proc .mini-spin {{
width: 24px; height: 24px; margin: 0 auto 10px;
border: 2px solid #1e2a3a; border-top-color: #bc8cff;
border-radius: 50%; animation: spin 1s linear infinite;
}}
/* Tokens */
.token-flow {{ display: flex; flex-wrap: wrap; gap: 6px; }}
.token-chip {{
background: #161b26; border: 1px solid #252d3a;
padding: 6px 10px 4px; border-radius: 5px; text-align: center;
animation: chipIn 0.4s ease-out backwards;
}}
.token-chip .tword {{ font-family: 'JetBrains Mono', monospace; font-size: 13px; color: #e6edf3; font-weight: 500; }}
.token-chip .tid {{ font-family: 'JetBrains Mono', monospace; font-size: 8px; color: #484f58; margin-top: 2px; }}
@keyframes chipIn {{ from {{ transform: translateY(8px); opacity: 0; }} to {{ transform: translateY(0); opacity: 1; }} }}
/* Attention */
.attn-controls {{ display: flex; align-items: center; gap: 10px; margin-bottom: 10px; }}
.attn-controls button {{
background: #1e2a3a; border: 1px solid #2d3a4a; color: #8b949e;
padding: 4px 12px; border-radius: 4px; cursor: pointer;
font-family: 'JetBrains Mono', monospace; font-size: 12px; transition: all 0.2s;
}}
.attn-controls button:hover {{ background: #2d3a4a; color: #e6edf3; }}
.attn-controls .lnum {{ font-family: 'JetBrains Mono', monospace; font-size: 13px; color: #bc8cff; font-weight: 700; min-width: 100px; text-align: center; }}
.heatmap-wrap {{ overflow-x: auto; padding-bottom: 8px; }}
.heatmap-grid {{ display: grid; gap: 2px; width: fit-content; }}
.hm-label {{ font-family: 'JetBrains Mono', monospace; font-size: 9px; color: #484f58; text-align: center; overflow: hidden; white-space: nowrap; }}
.hm-labels {{ display: flex; gap: 2px; margin-bottom: 3px; }}
.hm-cell {{ width: 34px; height: 34px; border-radius: 3px; cursor: crosshair; transition: transform 0.15s; }}
.hm-cell:hover {{ transform: scale(1.3); z-index: 10; }}
.tooltip {{
display: none; position: fixed;
background: #1c2333; border: 1px solid #3d4a5c; border-radius: 5px;
padding: 6px 10px; font-family: 'JetBrains Mono', monospace; font-size: 11px;
color: #e6edf3; z-index: 9999; pointer-events: none; white-space: nowrap;
box-shadow: 0 4px 12px rgba(0,0,0,0.4);
}}
/* Predictions */
.pred-row {{ display: flex; align-items: center; gap: 10px; margin-bottom: 6px; animation: barIn 0.5s ease-out backwards; }}
.pred-rank {{ font-family: 'JetBrains Mono', monospace; font-size: 9px; color: #484f58; width: 18px; text-align: right; }}
.pred-word {{ font-family: 'JetBrains Mono', monospace; width: 90px; text-align: right; font-size: 12px; color: #e6edf3; font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }}
.pred-bar-bg {{ flex: 1; height: 20px; background: #161b26; border-radius: 4px; overflow: hidden; }}
.pred-bar {{ height: 100%; border-radius: 4px; transition: width 0.8s cubic-bezier(0.22,1,0.36,1); }}
.pred-pct {{ font-family: 'JetBrains Mono', monospace; width: 55px; font-size: 11px; color: #6e7681; }}
@keyframes barIn {{ from {{ transform: translateX(-10px); opacity: 0; }} to {{ transform: translateX(0); opacity: 1; }} }}
/* Energy */
.energy-chart {{ width: 100%; height: 55px; }}
.energy-label {{ font-family: 'JetBrains Mono', monospace; font-size: 9px; color: #484f58; margin-top: 4px; text-align: center; }}
/* Response */
.response-box {{
background: #0a0e14; border: 1px solid #1e2a3a; border-radius: 6px;
padding: 16px 18px; font-size: 14px; color: #e6edf3; line-height: 1.7;
max-height: 220px; overflow-y: auto; font-family: 'Inter', sans-serif;
}}
.cursor-blink {{
display: inline-block; width: 9px; height: 16px; background: #58a6ff;
animation: blink 1s step-end infinite; vertical-align: text-bottom;
margin-left: 2px; border-radius: 1px;
}}
@keyframes blink {{ 50% {{ opacity: 0; }} }}
/* Softmax detail panel */
.softmax-overlay {{
display: none;
background: #111927; border: 1px solid #39d2c066;
border-radius: 8px; padding: 20px 24px;
margin: 0 24px 4px;
animation: slideDown 0.3s ease-out;
}}
.softmax-overlay.show {{ display: block; }}
@keyframes slideDown {{ from {{ opacity:0; transform:translateY(-10px); }} to {{ opacity:1; transform:translateY(0); }} }}
.softmax-title {{ font-size: 14px; font-weight: 600; color: #39d2c0; margin-bottom: 4px; }}
.softmax-desc {{ font-size: 12px; color: #8b949e; margin-bottom: 14px; line-height: 1.5; }}
.softmax-desc em {{ color: #39d2c0; font-style: normal; font-weight: 500; }}
.sm-grid {{ display: grid; grid-template-columns: 90px 1fr 40px 20px 1fr 55px; gap: 4px 8px; align-items: center; }}
.sm-word {{ font-family: 'JetBrains Mono', monospace; font-size: 12px; color: #e6edf3; text-align: right; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }}
.sm-bar-bg {{ height: 18px; background: #161b26; border-radius: 3px; overflow: hidden; }}
.sm-bar {{ height: 100%; border-radius: 3px; transition: width 0.6s cubic-bezier(0.22,1,0.36,1); }}
.sm-val {{ font-family: 'JetBrains Mono', monospace; font-size: 10px; color: #6e7681; }}
.sm-arrow {{ font-size: 12px; color: #39d2c0; text-align: center; }}
.sm-header {{ font-family: 'JetBrains Mono', monospace; font-size: 9px; color: #484f58; letter-spacing: 1px; text-transform: uppercase; padding-bottom: 4px; border-bottom: 1px solid #1e2a3a; margin-bottom: 2px; }}
.sm-close {{ float: right; background: none; border: 1px solid #2d3a4a; color: #8b949e; padding: 2px 10px; border-radius: 4px; cursor: pointer; font-size: 11px; font-family: 'JetBrains Mono', monospace; }}
.sm-close:hover {{ background: #2d3a4a; color: #e6edf3; }}
@keyframes spin {{ to {{ transform: rotate(360deg); }} }}
/* Dots block for hidden layers */
.dots-block {{
flex-shrink: 0;
display: flex; align-items: center; gap: 6px;
padding: 8px 14px;
font-family: 'JetBrains Mono', monospace;
font-size: 13px; font-weight: 600;
color: #6e7681; letter-spacing: 3px;
border: 1px dashed #2d3a4a; border-radius: 6px;
background: rgba(30, 42, 58, 0.3);
animation: dotsPulse 2.5s ease-in-out infinite;
cursor: default;
white-space: nowrap;
}}
.dots-block .dots-count {{
font-size: 10px; color: #484f58;
letter-spacing: 1px; font-weight: 400;
}}
@keyframes dotsPulse {{
0%, 100% {{ opacity: 0.6; }}
50% {{ opacity: 1; }}
}}
::-webkit-scrollbar {{ width: 6px; }}
::-webkit-scrollbar-track {{ background: transparent; }}
::-webkit-scrollbar-thumb {{ background: #1e2a3a; border-radius: 3px; }}
</style>
</head>
<body>
<div class="tooltip" id="tooltip"></div>
<div class="header">
<h1>🧠 Inside an AI's Brain</h1>
<div class="stats" id="stats"></div>
</div>
<div id="app"></div>
<script>
const CFG = {config_json};
const DATA = {data_json};
const STATE = "{state}";
let currentLayer = 0;
function init() {{
const fmt = CFG.num_params > 1e9 ? (CFG.num_params/1e9).toFixed(1)+'B' : (CFG.num_params/1e6).toFixed(0)+'M';
let statusText = STATE === 'idle' ? 'Ready — type a prompt in the terminal'
: STATE === 'processing' ? '<span style="color:#bc8cff;">⚡ Processing...</span>'
: 'Visualization active';
document.getElementById('stats').innerHTML =
`SmolLM2 — <span>${{fmt}} params</span> · <span>${{CFG.num_layers}} layers</span> · <span>${{CFG.num_heads}} heads</span> · <span>hidden ${{CFG.hidden_size}}</span> · ${{statusText}}`;
if (DATA) currentLayer = CFG.num_layers - 1; // default to last (visible) layer
render();
if (STATE === 'processing') startProcessingAnim();
}}
function render() {{
let h = '';
// Input bar
if (DATA) {{
h += `<div class="input-section">
<div class="input-label">Your Input</div>
<div class="input-text">${{esc(DATA.tokens.join(''))}}</div>
</div>`;
}} else if (STATE === 'processing') {{
h += `<div class="input-section">
<div class="input-label">Your Input</div>
<div class="input-text" style="color:#bc8cff;">Processing...</div>
</div>`;
}} else {{
h += `<div class="input-section">
<div class="input-label">Your Input</div>
<div class="input-text idle">Waiting for input from terminal...</div>
</div>`;
}}
// Architecture strip (ALWAYS rendered)
h += renderArch();
h += renderSoftmaxPanel();
// Panels
h += '<div class="panels-grid">';
if (DATA) {{
h += renderStep1();
h += renderStep2();
h += renderStep3();
h += renderStep4();
}} else if (STATE === 'processing') {{
h += procPanel('Step 1', '58a6ff', 'Reading the Words', 'Tokenizing input...');
h += procPanel('Step 2', 'bc8cff', 'Connecting the Dots', 'Computing attention...');
h += procPanel('Step 3', '39d2c0', 'What Comes Next?', 'Ranking predictions...');
h += procPanel('Step 4', '3fb950', 'The AI Speaks', 'Generating response...');
}} else {{
h += idlePanel('Step 1', '58a6ff', 'Reading the Words', 'The AI breaks your sentence into tokens', '📝');
h += idlePanel('Step 2', 'bc8cff', 'Connecting the Dots', 'See which words the AI connects', '🔗');
h += idlePanel('Step 3', '39d2c0', 'What Comes Next?', 'Watch the AI rank its word predictions', '📊');
h += idlePanel('Step 4', '3fb950', 'The AI Speaks', 'The AI builds a response token by token', '💬');
}}
h += '</div>';
document.getElementById('app').innerHTML = h;
if (DATA) attachEvents();
}}
function idlePanel(step, color, title, desc, icon) {{
return `<div class="panel">
<div class="panel-step"><span class="dot" style="background:#${{color}};"></span>${{step}}</div>
<div class="panel-title">${{title}}</div>
<div class="panel-idle"><div class="idle-icon">${{icon}}</div>${{desc}}</div>
</div>`;
}}
function procPanel(step, color, title, msg) {{
return `<div class="panel">
<div class="panel-step"><span class="dot" style="background:#${{color}};"></span>${{step}}</div>
<div class="panel-title">${{title}}</div>
<div class="panel-proc"><div class="mini-spin"></div>${{msg}}</div>
</div>`;
}}
/* ─── PROCESSING ANIMATION ─── */
function startProcessingAnim() {{
const groups = document.querySelectorAll('.layer-grp');
const arrows = document.querySelectorAll('.arrow');
let idx = 0;
// Add flow to all arrows
arrows.forEach(a => a.classList.add('flow'));
// Wave through layers sequentially
function wave() {{
if (idx < groups.length) {{
const currentIndex = idx; // Capture idx in the closure for the timeout callback
groups[currentIndex].classList.add('wave');
// Also pulse the blocks inside
groups[currentIndex].querySelectorAll('.a-block').forEach(b => b.classList.add('processing'));
setTimeout(() => {{
if (groups[currentIndex]) {{
groups[currentIndex].querySelectorAll('.a-block').forEach(b => b.classList.remove('processing'));
}}
}}, 500);
idx++;
setTimeout(wave, 80);
}} else {{
// Loop
setTimeout(() => {{
groups.forEach(g => g.classList.remove('wave'));
idx = 0;
wave();
}}, 800);
}}
}}
wave();
}}
/* ─── ARCHITECTURE STRIP ─── */
function renderArch() {{
let h = '<div class="arch-section">';
h += '<div class="arch-title">Full Neural Network Architecture <span class="hint">← scroll to explore all ' + CFG.num_layers + ' layers' + (DATA ? ' · click to inspect' : '') + ' →</span></div>';
h += '<div class="arch-scroll" id="arch-scroll">';
h += ab('embed','Embed',CFG.hidden_size+'d',false);
h += aw();
const SHOW_THRESHOLD = 5;
const SHOW_START = 3; // first N layers to show
const SHOW_END = 2; // last N layers to show
const shouldCollapse = CFG.num_layers > SHOW_THRESHOLD;
const hiddenCount = shouldCollapse ? CFG.num_layers - SHOW_START - SHOW_END : 0;
function renderLayerBlock(i) {{
const act = DATA ? (i === currentLayer) : false;
let s = `<div class="layer-grp ${{act?'active':''}}" ${{DATA ? 'onclick="selectLayer('+i+')"' : ''}}>`;
s += `<div class="ltag">L${{i}}</div>`;
s += ab('ln','LN','',act);
s += ai();
s += ab('attn','Attn',CFG.num_heads+'h',act);
s += ai();
s += ab('ln','LN','',act);
s += ai();
s += ab('mlp','MLP','',act);
s += '</div>';
return s;
}}
if (shouldCollapse) {{
// First SHOW_START layers
for (let i = 0; i < SHOW_START; i++) {{
h += renderLayerBlock(i);
h += aw();
}}
// Dots
h += `<div class="dots-block">⋯ <span class="dots-count">${{hiddenCount}} hidden layers</span> ⋯</div>`;
h += aw();
// Last SHOW_END layers
for (let i = CFG.num_layers - SHOW_END; i < CFG.num_layers; i++) {{
h += renderLayerBlock(i);
if (i < CFG.num_layers - 1) h += aw();
}}
}} else {{
for (let i = 0; i < CFG.num_layers; i++) {{
h += renderLayerBlock(i);
if (i < CFG.num_layers - 1) h += aw();
}}
}}
h += aw();
h += ab('ln','LN','final',false);
h += aw();
h += ab('out','Softmax',CFG.vocab_size.toLocaleString(),false, true);
h += '</div></div>';
return h;
}}
function ab(c,l,d,a,isSoftmax) {{
const click = isSoftmax && DATA ? ' onclick="toggleSoftmax()"' : '';
return `<div class="a-block ${{c}} ${{a?'active':''}}"${{click}}><div class="blabel">${{l}}</div>${{d?'<div class="bdetail">'+d+'</div>':''}}</div>`;
}}
function aw() {{ return '<div class="arrow"></div>'; }}
function ai() {{ return '<div class="arrow-inner"></div>'; }}
function selectLayer(i) {{
currentLayer = i;
render();
setTimeout(() => {{
const el = document.querySelector('.layer-grp.active');
if (el) el.scrollIntoView({{behavior:'smooth',inline:'center',block:'nearest'}});
}}, 50);
}}
/* ─── STEP 1 ─── */
function renderStep1() {{
let h = '<div class="panel">';
h += '<div class="panel-step"><span class="dot" style="background:#58a6ff;"></span>Step 1</div>';
h += '<div class="panel-title">Reading the Words</div>';
h += '<div class="panel-desc">The AI breaks your sentence into pieces called <em>tokens</em> and converts each to a number. It knows <em>' + CFG.vocab_size.toLocaleString() + ' words</em>.</div>';
h += '<div class="token-flow">';
DATA.tokens.forEach((t,i) => {{
h += `<div class="token-chip" style="animation-delay:${{i*0.08}}s"><div class="tword">${{esc(t||'·')}}</div><div class="tid">${{DATA.token_ids[i]}}</div></div>`;
}});
h += '</div></div>';
return h;
}}
/* ─── STEP 2 ─── */
function renderStep2() {{
let h = '<div class="panel" style="grid-column: 1 / -1;">';
h += '<div class="panel-step"><span class="dot" style="background:#bc8cff;"></span>Step 2</div>';
h += '<div class="panel-title">Full Transformer Architecture — 3D View</div>';
h += '<div class="panel-desc">The entire <em>' + CFG.num_layers + '-layer</em> transformer with <em>' + CFG.num_heads + ' attention heads</em> per layer. Each layer: <em>LN → Attention (heads fan out) → LN → MLP</em>. Drag to rotate, scroll to zoom, right-drag to pan.</div>';
h += '<div class="attn-controls">';
h += '<button onclick="resetCam()">⟲ Reset Camera</button>';
h += '<button onclick="toggleFullscreen()" style="margin-left: 10px;">⛶ Fullscreen</button>';
h += '</div>';
h += '<div id="three-container" style="position:relative;border:1px solid #1e2a3a;border-radius:6px;overflow:hidden;background:#080b10;height:600px;"></div>';
h += '</div>';
return h;
}}
/* ─── Three.js 3D Attention Head Viewer ─── */
let threeScene, threeCamera, threeRenderer, threeControls, threeAnimId;
let defaultCamPos = null;
function resetCam() {{
if (threeCamera && defaultCamPos) {{
threeCamera.position.copy(defaultCamPos);
threeCamera.lookAt(0, 0, 0);
if (threeControls) threeControls.reset();
}}
}}
function toggleFullscreen() {{
const container = document.getElementById('three-container');
if (!container) return;
if (!document.fullscreenElement) {{
if (container.requestFullscreen) container.requestFullscreen();
else if (container.webkitRequestFullscreen) container.webkitRequestFullscreen();
else if (container.msRequestFullscreen) container.msRequestFullscreen();
}} else {{
if (document.exitFullscreen) document.exitFullscreen();
else if (document.webkitExitFullscreen) document.webkitExitFullscreen();
else if (document.msExitFullscreen) document.msExitFullscreen();
}}
}}
function initHeadCanvas() {{
if (!DATA || typeof THREE === 'undefined') return;
const container = document.getElementById('three-container');
if (!container) return;
// Cleanup previous
if (threeAnimId) cancelAnimationFrame(threeAnimId);
if (threeRenderer) {{
threeRenderer.dispose();
container.innerHTML = '';
}}
const w = container.clientWidth;
const h = container.clientHeight;
// Scene
threeScene = new THREE.Scene();
threeScene.background = new THREE.Color(0x080b10);
// Camera
threeCamera = new THREE.PerspectiveCamera(50, w / h, 0.1, 2000);
// Renderer
threeRenderer = new THREE.WebGLRenderer({{ antialias: true, alpha: true }});
threeRenderer.setPixelRatio(window.devicePixelRatio);
threeRenderer.setSize(w, h);
container.appendChild(threeRenderer.domElement);
// Controls
threeControls = new THREE.OrbitControls(threeCamera, threeRenderer.domElement);
threeControls.enableDamping = true;
threeControls.dampingFactor = 0.08;
threeControls.rotateSpeed = 0.6;
threeControls.zoomSpeed = 1.2;
threeControls.panSpeed = 3.0;
threeControls.screenSpacePanning = true;
threeControls.minDistance = 1;
threeControls.maxDistance = 2000;
// Lighting
const ambientLight = new THREE.AmbientLight(0xffffff, 0.6);
threeScene.add(ambientLight);
const dirLight = new THREE.DirectionalLight(0xffffff, 0.4);
dirLight.position.set(5, 10, 7);
threeScene.add(dirLight);
// Build the full architecture scene
buildFullArchScene();
// Window resize handler
function onWindowResize() {{
if (!threeCamera || !threeRenderer) return;
const cw = container.clientWidth;
const ch = container.clientHeight;
threeCamera.aspect = cw / ch;
threeCamera.updateProjectionMatrix();
threeRenderer.setSize(cw, ch);
}}
window.addEventListener('resize', onWindowResize);
// Animate loop
function animate() {{
threeAnimId = requestAnimationFrame(animate);
threeControls.update();
threeRenderer.render(threeScene, threeCamera);
}}
animate();
}}
function buildFullArchScene() {{
if (!DATA || !threeScene) return;
// Clear old objects
const toRemove = [];
threeScene.traverse(child => {{ if (child.userData.arch) toRemove.push(child); }});
toRemove.forEach(c => threeScene.remove(c));
const numLayers = CFG.num_layers;
const numHeads = CFG.num_heads;
const seqLen = DATA.tokens.length;
// Layout constants
const layerSpacing = 16; // distance between layers along X
const blockH = 1.0; // height of LN/MLP blocks
const blockW = 1.5; // width
const blockD = 1.0; // depth
const headPlaneSize = 1.2; // size of each attention head plane
const headDepthSpacing = headPlaneSize + 0.15; // Z spacing — tile side by side
const subSpacing = 5.5; // spacing within a layer (between LN, Attn, MLP)
const totalX = (numLayers + 2) * layerSpacing;
let cursor = -totalX / 2;
// Helper: create a labeled box
function addBox(x, y, z, w, h, d, color, label) {{
const geo = new THREE.BoxGeometry(w, h, d);
const mat = new THREE.MeshPhongMaterial({{
color: color,
transparent: true,
opacity: 0.85,
shininess: 30,
}});
const mesh = new THREE.Mesh(geo, mat);
mesh.position.set(x, y, z);
mesh.userData.arch = true;
threeScene.add(mesh);
// Edges
const edges = new THREE.EdgesGeometry(geo);
const lineMat = new THREE.LineBasicMaterial({{ color: 0xffffff, transparent: true, opacity: 0.15 }});
const wire = new THREE.LineSegments(edges, lineMat);
wire.position.copy(mesh.position);
wire.userData.arch = true;
threeScene.add(wire);
// Label sprite
if (label) {{
const lc = document.createElement('canvas');
const lcCtx = lc.getContext('2d');
const lcFs = 48;
lcCtx.font = 'bold ' + lcFs + 'px JetBrains Mono, monospace';
const lcMetrics = lcCtx.measureText(label);
lc.width = Math.max(lcMetrics.width + 40, 128);
lc.height = lcFs + 20;
const lcCtx2 = lc.getContext('2d');
lcCtx2.font = 'bold ' + lcFs + 'px JetBrains Mono, monospace';
lcCtx2.fillStyle = '#ffffff';
lcCtx2.textAlign = 'center';
lcCtx2.fillText(label, lc.width / 2, lcFs);
const lt = new THREE.CanvasTexture(lc);
const sm = new THREE.SpriteMaterial({{ map: lt, transparent: true }});
const sp = new THREE.Sprite(sm);
sp.position.set(x, y + h / 2 + 0.5, z);
sp.scale.set(2.5, 0.5, 1);
sp.userData.arch = true;
threeScene.add(sp);
}}
return mesh;
}}
// Helper: connect two points (thick, solid lines)
function addLine(p1, p2, color) {{
const geo = new THREE.BufferGeometry().setFromPoints([p1, p2]);
const mat = new THREE.LineBasicMaterial({{ color: color || 0x3fb950, transparent: true, opacity: 0.75, linewidth: 2 }});
const line = new THREE.Line(geo, mat);
line.userData.arch = true;
threeScene.add(line);
}}
// Helper: create attention head texture plane
function addHeadPlane(x, y, z, headIdx, layerIdx) {{
const heads = DATA.attention[layerIdx];
if (!heads || !heads[headIdx]) return;
const headData = heads[headIdx];
const sl = headData.length;
const texSz = Math.max(sl * 4, 32);
const hc = document.createElement('canvas');
hc.width = texSz;
hc.height = texSz;
const cx = hc.getContext('2d');
const cp = texSz / sl;
for (let r = 0; r < sl; r++) {{
for (let c = 0; c < sl; c++) {{
const v = Math.min(1, Math.max(0, headData[r][c]));
cx.fillStyle = `rgb(${{Math.round(30+v*150)}},${{Math.round(20+v*70)}},${{Math.round(60+v*195)}})`;
cx.fillRect(c * cp, r * cp, cp, cp);
}}
}}
const tex = new THREE.CanvasTexture(hc);
tex.magFilter = THREE.NearestFilter;
tex.minFilter = THREE.NearestFilter;
const geo = new THREE.PlaneGeometry(headPlaneSize, headPlaneSize);
const mat = new THREE.MeshBasicMaterial({{ map: tex, side: THREE.DoubleSide, transparent: true, opacity: 0.9 }});
const mesh = new THREE.Mesh(geo, mat);
mesh.position.set(x, y, z);
mesh.rotation.x = -Math.PI / 2; // lay flat, face up
mesh.userData.arch = true;
threeScene.add(mesh);
// Edge
const edg = new THREE.EdgesGeometry(geo);
const lm = new THREE.LineBasicMaterial({{ color: 0xbc8cff, transparent: true, opacity: 0.3 }});
const wf = new THREE.LineSegments(edg, lm);
wf.position.copy(mesh.position);
wf.rotation.copy(mesh.rotation);
wf.userData.arch = true;
threeScene.add(wf);
}}
// ═══ EMBEDDING BLOCK — DETAILED ═══
const embedStartX = cursor;
let embedOutEdgeX = embedStartX + blockW * 0.6;
function addTextSprite(x, y, z, text, color, fontSize, scaleW, scaleH) {{
const c = document.createElement('canvas');
const ctx = c.getContext('2d');
// Use 2x the requested font size for high-res rendering
const renderFs = Math.max(fontSize * 2, 48);
ctx.font = 'bold ' + renderFs + 'px JetBrains Mono, monospace';
const metrics = ctx.measureText(text);
c.width = Math.max(metrics.width + 40, 128);
c.height = renderFs + 30;
// Re-set font after canvas resize
const ctx2 = c.getContext('2d');
ctx2.font = 'bold ' + renderFs + 'px JetBrains Mono, monospace';
ctx2.fillStyle = '#ffffff';
ctx2.textAlign = 'center';
ctx2.fillText(text, c.width / 2, renderFs);
const tex = new THREE.CanvasTexture(c);
const mat = new THREE.SpriteMaterial({{ map: tex, transparent: true }});
const sprite = new THREE.Sprite(mat);
sprite.position.set(x, y, z);
// Always auto-calculate width from canvas aspect ratio to prevent overlap
const sh = scaleH || 0.75;
const sw = sh * c.width / c.height;
sprite.scale.set(sw, sh, 1);
sprite.userData.arch = true;
threeScene.add(sprite);
return sprite;
}}
if (DATA.tokens && DATA.token_ids) {{
const numTokens = Math.min(DATA.tokens.length, 12);
const zStep = 1.2;
const totalZ = (numTokens - 1) * zStep;
const colTokX = embedStartX - 2;
const colIdxX = colTokX + 3.5;
const colMatrixX = colIdxX + 4;
const colEmbX = colMatrixX + 4;
const embedFnX = colEmbX + 7;
embedOutEdgeX = embedFnX + blockW * 0.75;
addTextSprite(colTokX, 2, 0, 'Token', '#e6edf3', 22);
addTextSprite(colIdxX, 2, 0, 'ID', '#d2a8ff', 22);
addTextSprite(colEmbX, 3.5, 0, 'Token Embedding', '#58a6ff', 22);
addTextSprite(colMatrixX, 3.5, 0, 'Embedding Matrix', '#8b949e', 22);
addTextSprite(colMatrixX, 2.5, 0, 'W_e', '#8b949e', 18, 1.5, 0.4);
// Explanatory labels at the bottom
// We create a custom high-res canvas sprite to prevent blurriness on long text
const baseLineY = -2.5; // Shared baseline under all matrix/token items
function addDescLabel(x, text, yDrop) {{
const dCanvas = document.createElement('canvas');
const dCtx = dCanvas.getContext('2d');
const dFs = 48; // Huge font size for sharp resolution
dCtx.font = 'bold ' + dFs + 'px JetBrains Mono, monospace';
const metrics = dCtx.measureText(text);
dCanvas.width = metrics.width + 20;
dCanvas.height = dFs + 20;
// Re-fetch context after resizing
const ctx = dCanvas.getContext('2d');
ctx.font = 'bold ' + dFs + 'px JetBrains Mono, monospace';
ctx.fillStyle = '#e6edf3'; // Bright, highly readable off-white
ctx.textAlign = 'center';
ctx.fillText(text, dCanvas.width / 2, dFs);
const dTex = new THREE.CanvasTexture(dCanvas);
const dMat = new THREE.SpriteMaterial({{ map: dTex, transparent: true }});
const dSpr = new THREE.Sprite(dMat);
// Scale down the giant sprite so it fits in the 3D world but remains sharp
const sprH = 0.5;
dSpr.scale.set(sprH * dCanvas.width / dCanvas.height, sprH, 1);
const finalY = baseLineY - yDrop;
dSpr.position.set(x, finalY, 0);
dSpr.userData.arch = true;
threeScene.add(dSpr);
// Draw pointer line linking the staggered text UP to the column baseline
addLine(new THREE.Vector3(x, finalY + sprH/2, 0), new THREE.Vector3(x, baseLineY + 0.5, 0), 0xffffff);
}}
// Stagger dropping them down to prevent overlap
addDescLabel(colTokX, '1. Split text into tokens', 0.0);
addDescLabel(colIdxX, '2. Map to vocabulary IDs', 1.0);
addDescLabel(colMatrixX, '3. Lookup vector by ID', 2.0);
addDescLabel(colEmbX, '4. Extract Word Vectors', 3.0);
// Draw the Embedding Matrix as a cool glowing tech-grid
const matZSize = totalZ + 2.0;
const mCanvas = document.createElement('canvas');
const mRows = DATA.embed_sample ? DATA.embed_sample.length : 20;
const mCols = DATA.embed_sample ? DATA.embed_sample[0].length : 20;
const cellSize = 16;
mCanvas.width = mCols * cellSize;
mCanvas.height = mRows * cellSize;
const mCtx = mCanvas.getContext('2d');
// Dark background for matrix
mCtx.fillStyle = '#0d1117';
mCtx.fillRect(0, 0, mCanvas.width, mCanvas.height);
for (let r = 0; r < mRows; r++) {{
for (let c = 0; c < mCols; c++) {{
let val = DATA.embed_sample ? DATA.embed_sample[r][c] : (Math.random() - 0.5);
// Cool neon colors based on weight values
const alpha = Math.min(1.0, Math.abs(val) * 5.0 + 0.1);
if (val > 0) {{
mCtx.fillStyle = `rgba(57, 210, 192, ${{alpha}})`; // neon teal
}} else {{
mCtx.fillStyle = `rgba(188, 140, 255, ${{alpha}})`; // neon purple
}}
mCtx.fillRect(c * cellSize + 1, r * cellSize + 1, cellSize - 2, cellSize - 2);
}}
}}
const matTex = new THREE.CanvasTexture(mCanvas);
matTex.magFilter = THREE.NearestFilter; // keep it sharp and blocky
// Give it slight thickness instead of flat plane
const matGeometry = new THREE.BoxGeometry(0.6, 4.0, matZSize);
const matMaterial = new THREE.MeshBasicMaterial({{
map: matTex,
transparent: true,
opacity: 0.9,
}});
const matBox = new THREE.Mesh(matGeometry, matMaterial);
matBox.position.set(colMatrixX, 0, 0);
matBox.userData.arch = true;
threeScene.add(matBox);
// Add glowing wireframe edges
const edges = new THREE.EdgesGeometry(matGeometry);
const lineMat = new THREE.LineBasicMaterial({{ color: 0x58a6ff, opacity: 0.8, transparent: true }});
const matEdges = new THREE.LineSegments(edges, lineMat);
matBox.add(matEdges);
for (let i = 0; i < numTokens; i++) {{
const zPos = -totalZ / 2 + i * zStep;
const tokStr = ('"' + DATA.tokens[i] + '"').slice(0, 12);
addTextSprite(colTokX, 0, zPos, tokStr, '#e6edf3', 18);
const idStr = DATA.token_ids[i].toString();
addTextSprite(colIdxX, 0, zPos, idStr, '#d2a8ff', 16);
// Line from Token -> ID
addLine(new THREE.Vector3(colTokX+1.5, 0, zPos), new THREE.Vector3(colIdxX-1.0, 0, zPos), 0x484f58);
// Line from ID -> Matrix
addLine(new THREE.Vector3(colIdxX+1.0, 0, zPos), new THREE.Vector3(colMatrixX-0.1, 0, zPos), 0x484f58);
// Line from Matrix -> Word Vector
addLine(new THREE.Vector3(colMatrixX+0.1, 0, zPos), new THREE.Vector3(colEmbX-2.0, 0, zPos), 0x58a6ff);
// Embedding vector sprite (actual values)
if (DATA.token_embeddings && DATA.token_embeddings[i]) {{
const w = DATA.token_embeddings[i];
const lines = [
(w[0] >= 0 ? '+' : '') + w[0].toFixed(3),
(w[1] >= 0 ? '+' : '') + w[1].toFixed(3),
(w[2] >= 0 ? '+' : '') + w[2].toFixed(3),
' \u22ef',
(w[3] >= 0 ? '+' : '') + w[3].toFixed(3),
(w[4] >= 0 ? '+' : '') + w[4].toFixed(3)
];
const vc = document.createElement('canvas');
const fs = 14;
const lh = fs + 4;
const cW = 120, cH = lines.length * lh + 8;
vc.width = cW; vc.height = cH;
const vx = vc.getContext('2d');
vx.font = 'bold ' + fs + 'px JetBrains Mono, monospace';
// Brackets
vx.strokeStyle = '#58a6ff'; vx.lineWidth = 1.5;
vx.beginPath(); vx.moveTo(12, 4); vx.lineTo(6, 4); vx.lineTo(6, cH-4); vx.lineTo(12, cH-4); vx.stroke();
vx.beginPath(); vx.moveTo(cW-12, 4); vx.lineTo(cW-6, 4); vx.lineTo(cW-6, cH-4); vx.lineTo(cW-12, cH-4); vx.stroke();
for (let li = 0; li < lines.length; li++) {{
const val = parseFloat(lines[li]);
vx.fillStyle = isNaN(val) ? '#6e7681' : (val >= 0 ? '#58a6ff' : '#f85149');
vx.textAlign = 'center';
vx.fillText(lines[li], cW/2, (li+1) * lh);
}}
const vTex = new THREE.CanvasTexture(vc);
const vMat = new THREE.SpriteMaterial({{ map: vTex, transparent: true }});
const vSpr = new THREE.Sprite(vMat);
const sprH = 1.0;
vSpr.scale.set(sprH * cW / cH, sprH, 1);
vSpr.position.set(colEmbX, 0, zPos);
vSpr.userData.arch = true;
threeScene.add(vSpr);
}} else {{
// Fallback box if data is missing
addBox(colEmbX, 0, zPos, 2.5, 0.3, 0.8, 0x58a6ff);
}}
// We no longer draw individual lines from tokens to the Embedding Output matrix
// because the new Matrix visualization is a single unified block representing the whole sequence.
}}
// Draw one single centered connecting line from the middle of the Token Embeddings stack to the Embed Output Matrix
addLine(new THREE.Vector3(colEmbX + 1.2, 0, 0), new THREE.Vector3(embedFnX - 2.5, 0, 0), 0x58a6ff);
// ═══ Sequence Embedding Output Matrix ═══
// Instead of a single box, show a stacked block representing (SeqLen, HiddenSize)
const eoRows = numTokens;
// We'll show first 3 and last 2 columns
const numColsToShow = DATA.token_embeddings && DATA.token_embeddings[0] ? DATA.token_embeddings[0].length : 5;