-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHTMLNLM.html
More file actions
2453 lines (2130 loc) · 103 KB
/
HTMLNLM.html
File metadata and controls
2453 lines (2130 loc) · 103 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, maximum-scale=1.0, user-scalable=no">
<title>HTMLNLM — Browser Neural Runtime (RWKV-v7)</title>
<!--
HTMLNLM RWKV-v7 — Correct Backward Pass
ConsciousNode SoftWorks
Authors: Kham (architecture & constraint engineering)
Kehai Interim (full BPTT derivation & implementation)
Ed Interim (MuonOptimizer mu fix & final verification)
-->
<style>
/* HTMLNLM STYHEET - Debugged & Enhanced */
:root {
--bg-primary: #0a0a0a;
--bg-secondary: #171717;
--bg-tertiary: #262626;
--border: #404040;
--accent: #14b8a6;
--accent-dim: #0f766e;
--accent-glow: rgba(20, 184, 166, 0.2);
--text-main: #f5f5f5;
--text-muted: #a3a3a3;
--error: #ef4444;
--warning: #f59e0b;
--font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
--font-sans: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
--radius: 12px;
--shadow: 0 4px 20px -2px rgba(0, 0, 0, 0.5);
--transition-fast: 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body, html { height: 100%; background: var(--bg-primary); color: var(--text-main); font-family: var(--font-sans); font-size: 14px; overflow: hidden; }
::-webkit-scrollbar { width: 6px; height: 6px; }
::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb { background: var(--border); border-radius: 10px; }
::-webkit-scrollbar-thumb:hover { background: var(--text-muted); }
#app-container { display: flex; flex-direction: column; height: 100vh; width: 100vw; }
header { display: flex; align-items: center; padding: 16px 24px; background: var(--bg-secondary); border-bottom: 1px solid var(--border); z-index: 20; box-shadow: 0 2px 10px rgba(0,0,0,0.3); flex-wrap: wrap; gap: 12px; }
header h1 { color: var(--accent); font-size: 20px; font-weight: 800; font-family: var(--font-mono); letter-spacing: -0.5px; margin-right: 8px; }
.subtitle { color: var(--text-muted); font-size: 13px; font-weight: 500; display: none; }
@media (min-width: 600px) { .subtitle { display: block; } }
.status-pill { margin-left: auto; display: flex; align-items: center; gap: 8px; font-size: 11px; font-weight: 700; color: var(--accent); background: var(--accent-glow); padding: 6px 14px; border-radius: 20px; border: 1px solid var(--accent-dim); letter-spacing: 0.5px; white-space: nowrap; }
.status-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 10px var(--accent); animation: pulse 2s infinite cubic-bezier(0.4, 0, 0.6, 1); }
@keyframes pulse { 0%, 100% { opacity: 1; transform: scale(1); } 50% { opacity: 0.5; transform: scale(0.85); } }
input[type="radio"][name="route"] { display: none; }
nav { display: flex; background: var(--bg-secondary); border-bottom: 1px solid var(--border); overflow-x: auto; scrollbar-width: none; z-index: 15; }
nav::-webkit-scrollbar { display: none; }
.nav-tab { padding: 16px 24px; cursor: pointer; color: var(--text-muted); font-size: 12px; font-weight: 700; letter-spacing: 0.5px; border-bottom: 2px solid transparent; transition: all var(--transition-fast); white-space: nowrap; user-select: none; }
.nav-tab:hover { color: var(--text-main); background: var(--bg-tertiary); }
body:has(#route-setup:checked) .nav-tab[for="route-setup"],
body:has(#route-train:checked) .nav-tab[for="route-train"],
body:has(#route-align:checked) .nav-tab[for="route-align"],
body:has(#route-infer:checked) .nav-tab[for="route-infer"],
body:has(#route-io:checked) .nav-tab[for="route-io"] { color: var(--accent); border-bottom-color: var(--accent); background: var(--bg-primary); }
.screen { display: none; height: 100%; overflow-y: auto; overflow-x: hidden; padding: 24px; gap: 24px; align-content: flex-start; flex: 1; }
body:has(#route-setup:checked) #screen-setup { display: flex; flex-direction: column; }
body:has(#route-train:checked) #screen-train { display: grid; grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); }
body:has(#route-align:checked) #screen-align { display: grid; grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); }
body:has(#route-infer:checked) #screen-infer { display: flex; flex-direction: column; }
body:has(#route-io:checked) #screen-io { display: flex; flex-direction: column; }
.panel { background: var(--bg-secondary); border: 1px solid var(--border); border-radius: var(--radius); padding: 24px; display: flex; flex-direction: column; box-shadow: var(--shadow); transition: transform var(--transition-fast); position: relative; overflow: hidden; }
.panel-header { font-family: var(--font-mono); color: var(--text-main); font-size: 13px; font-weight: 700; margin-bottom: 24px; padding-bottom: 12px; border-bottom: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center; letter-spacing: 0.5px; }
.control-group { margin-bottom: 24px; }
.control-group label { display: flex; justify-content: space-between; color: var(--text-muted); font-size: 13px; margin-bottom: 10px; font-weight: 600; }
.control-group input[type="range"] { width: 100%; accent-color: var(--accent); cursor: pointer; height: 6px; background: var(--bg-tertiary); border-radius: 4px; appearance: none; outline: none; margin-top: 4px; }
.control-group input[type="range"]::-webkit-slider-thumb { appearance: none; width: 18px; height: 18px; border-radius: 50%; background: var(--accent); cursor: pointer; transition: transform 0.1s; box-shadow: 0 2px 6px rgba(0,0,0,0.4); }
.control-group input[type="range"]::-webkit-slider-thumb:hover { transform: scale(1.15); }
.control-group input[type="text"], .control-group textarea, .control-group select { width: 100%; background: var(--bg-primary); border: 1px solid var(--border); color: var(--text-main); font-family: var(--font-mono); font-size: 13px; padding: 14px; border-radius: 8px; outline: none; transition: border-color var(--transition-fast), box-shadow var(--transition-fast); }
.control-group input[type="text"]:focus, .control-group textarea:focus, .control-group select:focus { border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-glow); }
.control-group textarea { resize: vertical; min-height: 120px; line-height: 1.6; }
.val-display { color: var(--accent); font-weight: 700; font-family: var(--font-mono); background: var(--bg-primary); padding: 2px 8px; border-radius: 4px; border: 1px solid var(--border); }
.val-input { color: var(--accent); font-weight: 700; font-family: var(--font-mono); background: var(--bg-primary); padding: 2px 8px; border-radius: 4px; border: 1px solid var(--border); width: 80px; text-align: right; outline: none; -moz-appearance: textfield; }
.val-input::-webkit-outer-spin-button, .val-input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; }
.val-input:focus { border-color: var(--accent); box-shadow: 0 0 0 2px var(--accent-glow); }
.btn { padding: 14px 20px; background: var(--bg-tertiary); border: 1px solid var(--border); color: var(--text-main); font-family: var(--font-sans); font-size: 13px; font-weight: 700; cursor: pointer; border-radius: 8px; transition: all var(--transition-fast); text-align: center; letter-spacing: 0.5px; user-select: none; display: inline-flex; justify-content: center; align-items: center; gap: 8px; }
.btn:hover:not(:disabled) { background: var(--bg-primary); border-color: var(--accent); color: var(--accent); box-shadow: 0 4px 12px var(--accent-glow); transform: translateY(-1px); }
.btn:active:not(:disabled) { transform: translateY(1px); box-shadow: none; }
.btn:disabled { opacity: 0.4; cursor: not-allowed; filter: grayscale(1); }
.btn.primary { background: var(--accent-dim); border-color: var(--accent); color: #fff; }
.btn.primary:hover:not(:disabled) { background: var(--accent); color: #000; }
.btn.danger { border-color: var(--error); color: var(--error); background: rgba(239, 68, 68, 0.05); }
.btn.danger:hover:not(:disabled) { background: rgba(239, 68, 68, 0.15); box-shadow: 0 4px 12px rgba(239, 68, 68, 0.2); }
.btn-row { display: flex; gap: 12px; flex-wrap: wrap; margin-top: auto; }
.btn-row .btn { flex: 1; min-width: 140px; }
.css-graph-container { display: flex; align-items: flex-end; gap: 1px; height: 160px; background: var(--bg-primary); border: 1px solid var(--border); padding: 4px; border-radius: 8px; overflow: hidden; position: relative; }
.loss-bar { flex: 1; background: var(--accent); transition: height 0.15s ease-out; min-height: 1px; max-width: 8px; opacity: 0.85; border-radius: 2px 2px 0 0; will-change: height; }
.loss-bar:hover { opacity: 1; background: #fff; transform: scaleY(1.02); }
.hist-container { display: flex; gap: 8px; align-items: flex-end; height: 120px; margin-top: 16px; background: var(--bg-primary); padding: 12px; border-radius: 8px; border: 1px solid var(--border); }
.hist-bar { flex: 1; transition: height 0.4s cubic-bezier(0.4, 0, 0.2, 1); min-height: 4px; border-radius: 6px 6px 0 0; will-change: height; position: relative; }
.hist-bar::after { content: attr(data-val); position: absolute; top: -20px; width: 100%; text-align: center; font-size: 11px; font-family: var(--font-mono); color: var(--text-muted); opacity: 0; transition: opacity 0.2s; }
.hist-bar:hover::after { opacity: 1; }
#hist-neg { background: var(--error); }
#hist-zero { background: var(--border); }
#hist-pos { background: var(--accent); }
.dropzone { border: 2px dashed var(--border); border-radius: var(--radius); padding: 48px 24px; text-align: center; color: var(--text-muted); cursor: pointer; transition: all var(--transition-fast); background: var(--bg-primary); position: relative; overflow: hidden; }
.dropzone:hover, .dropzone.dragover { border-color: var(--accent); background: var(--accent-glow); color: var(--accent); }
.terminal-output { flex: 1; background: #000; border: 1px solid var(--border); padding: 16px; font-family: var(--font-mono); font-size: 13px; color: var(--text-muted); overflow-y: auto; overflow-x: hidden; border-radius: 8px; line-height: 1.6; min-height: 200px; box-shadow: inset 0 2px 15px rgba(0,0,0,0.5); word-wrap: break-word; white-space: pre-wrap; }
.terminal-output span.highlight { color: var(--accent); font-weight: bold; text-shadow: 0 0 8px var(--accent-glow); }
.terminal-output span.sys-err { color: var(--error); }
.terminal-output span.sys-warn { color: var(--warning); }
.terminal-output span.sys-ok { color: var(--accent); }
.stat-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(100px, 1fr)); gap: 16px; margin-top: 24px; background: var(--bg-primary); padding: 16px; border-radius: 8px; border: 1px solid var(--border); }
.stat-item { display: flex; flex-direction: column; font-size: 12px; color: var(--text-muted); font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; }
.stat-item span { font-size: 18px; font-weight: 700; color: var(--text-main); font-family: var(--font-mono); margin-top: 6px; letter-spacing: -0.5px; text-transform: none; }
footer { display: flex; gap: 24px; align-items: center; padding: 12px 24px; background: var(--bg-secondary); border-top: 1px solid var(--border); font-size: 12px; font-family: var(--font-mono); overflow-x: auto; white-space: nowrap; flex-shrink: 0; box-shadow: 0 -2px 10px rgba(0,0,0,0.2); z-index: 20; }
.footer-stat { color: var(--text-muted); display: flex; align-items: center; gap: 8px; }
.footer-stat span { color: var(--accent); font-weight: 700; }
.mem-gauge-wrapper { width: 140px; height: 10px; background: var(--bg-primary); border-radius: 5px; overflow: hidden; border: 1px solid var(--border); display: inline-block; box-shadow: inset 0 1px 3px rgba(0,0,0,0.3); }
#mem-gauge-fill { height: 100%; background: linear-gradient(90deg, var(--accent-dim), var(--accent)); width: 0%; transition: width 0.5s ease-out; }
.version-badge { display: inline-block; padding: 2px 8px; background: var(--accent-glow); border: 1px solid var(--accent-dim); border-radius: 4px; font-size: 10px; color: var(--accent); margin-left: 8px; }
@media (max-width: 768px) {
.screen { padding: 16px; gap: 16px; }
.panel { padding: 16px; }
.btn-row { flex-direction: column; }
.btn-row .btn { width: 100%; }
}
</style>
</head>
<body>
<input type="radio" name="route" id="route-setup" checked>
<input type="radio" name="route" id="route-train">
<input type="radio" name="route" id="route-align">
<input type="radio" name="route" id="route-infer">
<input type="radio" name="route" id="route-io">
<div id="app-container">
<header>
<h1>HTMLNLM<span class="version-badge">RWKV-v7</span></h1>
<span class="subtitle">Sovereign Browser-Based Compute</span>
<div class="status-pill">
<div class="status-dot"></div>
LOCAL SANDBOX
</div>
</header>
<nav>
<label class="nav-tab" for="route-setup">1. ARCHITECTURE</label>
<label class="nav-tab" for="route-train">2. PRE-TRAIN</label>
<label class="nav-tab" for="route-align">3. ALIGN (GRPO)</label>
<label class="nav-tab" for="route-infer">4. INFERENCE</label>
<label class="nav-tab" for="route-io">5. PERSISTENCE</label>
</nav>
<div class="screen" id="screen-setup">
<div style="display:grid; grid-template-columns: repeat(auto-fit, minmax(340px, 1fr)); gap:24px;">
<div class="panel">
<div class="panel-header">NETWORK TOPOLOGY (RWKV-v7 GOOSE)</div>
<div class="control-group">
<label><span>Vocabulary Capacity</span> <input type="number" class="val-input" id="val-vocab" min="256" max="8192" step="256" value="2048" onchange="document.getElementById('cfg-vocab').value=this.value; updateArchStats()"></label>
<input type="range" id="cfg-vocab" min="256" max="8192" step="256" value="2048" oninput="document.getElementById('val-vocab').value=this.value; updateArchStats()">
</div>
<div class="control-group">
<label><span>Hidden Dimension (D)</span> <input type="number" class="val-input" id="val-dim" min="64" max="512" step="64" value="256" onchange="document.getElementById('cfg-dim').value=this.value; updateArchStats()"></label>
<input type="range" id="cfg-dim" min="64" max="512" step="64" value="256" oninput="document.getElementById('val-dim').value=this.value; updateArchStats()">
</div>
<div class="control-group">
<label><span>Recurrent Layers (L)</span> <input type="number" class="val-input" id="val-layers" min="1" max="16" step="1" value="4" onchange="document.getElementById('cfg-layers').value=this.value; updateArchStats()"></label>
<input type="range" id="cfg-layers" min="1" max="16" step="1" value="4" oninput="document.getElementById('val-layers').value=this.value; updateArchStats()">
</div>
<div class="control-group">
<label><span>OOMB Context Chunk</span> <input type="number" class="val-input" id="val-ctx" min="64" max="1024" step="64" value="128" onchange="document.getElementById('cfg-ctx').value=this.value; updateArchStats()"></label>
<input type="range" id="cfg-ctx" min="64" max="1024" step="64" value="128" oninput="document.getElementById('val-ctx').value=this.value; updateArchStats()">
</div>
<div class="control-group">
<label><span>Architecture Version</span></label>
<select id="cfg-version" onchange="updateArchStats()" style="width:100%; background:var(--bg-primary); border:1px solid var(--border); color:var(--text-main); font-family:var(--font-mono); font-size:13px; padding:10px; border-radius:8px; outline:none;">
<option value="rwkv7" selected>RWKV-v7 (GOOSE - Latest)</option>
<option value="rwkv6">RWKV-v6 (Finch - Legacy)</option>
</select>
</div>
<div class="control-group">
<label><span>Optimizer</span></label>
<select id="cfg-optimizer" onchange="updateOptimizerUI(this.value)" style="width:100%; background:var(--bg-primary); border:1px solid var(--border); color:var(--text-main); font-family:var(--font-mono); font-size:13px; padding:10px; border-radius:8px; outline:none;">
<option value="adam">AdamW (Fast / Mobile)</option>
<option value="muon" selected>Muon (Quality / Desktop)</option>
</select>
</div>
<div style="margin-top:auto; padding-top:20px; border-top:1px solid var(--border);">
<div style="font-family:var(--font-mono); font-size:32px; color:var(--accent); font-weight:800; letter-spacing:-1px;" id="stat-params">0.00M</div>
<div style="color:var(--text-muted); font-size:12px; margin-top:4px; font-weight:600; text-transform:uppercase;">Total Ternary Parameters</div>
</div>
</div>
<div class="panel">
<div class="panel-header">CORPUS INGESTION & BPE</div>
<div class="dropzone" id="dropzone" onclick="document.getElementById('file-upload').click()" ondragover="event.preventDefault(); this.classList.add('dragover');" ondragleave="this.classList.remove('dragover');" ondrop="event.preventDefault(); this.classList.remove('dragover'); handleFileDrop(event);">
<svg style="width:36px;height:36px;margin-bottom:12px;opacity:0.8;color:var(--accent);" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M17 8l-5-5-5 5M12 3v12"/></svg><br>
<span style="font-size:14px; font-weight:700; color:var(--text-main);">Drop .txt corpus here or click</span><br>
<span style="font-size:12px; opacity:0.6; margin-top:8px; display:inline-block;">Requires uncompressed UTF-8 text</span>
</div>
<input type="file" id="file-upload" accept=".txt,.md" style="display:none" onchange="handleFileInput(this)">
<div class="control-group" style="margin-top:24px;">
<textarea id="corpus-input" placeholder="Or paste raw text buffer directly..." oninput="handleTextInput(this.value)"></textarea>
</div>
<div class="btn-row">
<button class="btn" id="btn-build-bpe" onclick="initiateTokenizer()">COMPILE BPE</button>
<button class="btn primary" id="btn-alloc" onclick="allocateMemory()" disabled>ALLOCATE VM</button>
</div>
</div>
</div>
<div class="panel" style="margin-top: 24px; flex: 1; min-height: 250px;">
<div class="panel-header" style="margin-bottom: 12px;">
SYSTEM TELEMETRY
<button class="btn" style="padding:6px 14px; font-size:11px; min-width:auto; height:auto;" onclick="document.getElementById('sys-logs').innerHTML=''">CLEAR LOGS</button>
</div>
<div id="sys-logs" class="terminal-output"></div>
</div>
</div>
<div class="screen" id="screen-train">
<div style="display:flex; flex-direction:column; gap:24px;">
<div class="panel">
<div class="panel-header">OOMB CHUNK-RECURRENT LOSS</div>
<div class="css-graph-container" id="loss-graph"></div>
<div class="stat-grid">
<div class="stat-item">Global Step <span id="ui-step">0</span></div>
<div class="stat-item">Current Loss <span id="ui-loss">0.0000</span></div>
<div class="stat-item">Throughput <span id="ui-tps">0.0</span> <span style="font-size:11px; font-weight:normal; color:var(--text-muted); text-transform:none;">tok/sec</span></div>
</div>
</div>
<div class="panel">
<div class="panel-header">QUANTIZATION DISTRIBUTION (b1.58)</div>
<div class="hist-container">
<div class="hist-bar" id="hist-neg" style="height:33.3%" data-val="-1"></div>
<div class="hist-bar" id="hist-zero" style="height:33.4%" data-val="0"></div>
<div class="hist-bar" id="hist-pos" style="height:33.3%" data-val="+1"></div>
</div>
<div style="display:flex; justify-content:space-between; font-family:var(--font-mono); font-size:13px; margin-top:16px; font-weight:700;">
<span style="color:var(--error)">-1 (<span id="pct-neg">33</span>%)</span>
<span style="color:var(--text-muted)">0 (<span id="pct-zero">34</span>%)</span>
<span style="color:var(--accent)">+1 (<span id="pct-pos">33</span>%)</span>
</div>
</div>
<div class="panel">
<div class="panel-header">OPTIMIZER (QUINTIC MUON)</div>
<div class="control-group">
<label><span id="lr-label">Learning Rate (Muon)</span> <input type="number" class="val-input" id="val-lr" min="0.001" max="0.1" step="0.001" value="0.020" onchange="syncLRFromInput(this.value)"></label>
<input type="range" id="cfg-lr" min="1" max="100" value="20" oninput="document.getElementById('val-lr').value=(this.value/1000).toFixed(3)">
</div>
<div class="btn-row">
<button class="btn primary" id="btn-train-start" onclick="startTraining()" disabled>START LOOP</button>
<button class="btn" id="btn-train-pause" onclick="pauseTraining()" disabled>PAUSE</button>
</div>
</div>
</div>
<div style="display:flex; flex-direction:column; gap:24px;">
<div class="panel">
<div class="panel-header">TRAINING AUTOMATION</div>
<div style="display:grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom:20px;">
<div class="control-group" style="margin:0;">
<label style="margin-bottom:6px;"><span>Auto-Save</span></label>
<div style="display:flex; align-items:center; gap:10px;">
<input type="checkbox" id="auto-save-en" style="accent-color:var(--accent); width:16px; height:16px; cursor:pointer;">
<span style="color:var(--text-muted); font-size:12px;">every</span>
<input type="number" class="val-input" id="auto-save-steps" value="500" min="50" step="50" style="width:70px;">
<span style="color:var(--text-muted); font-size:12px;">steps</span>
</div>
</div>
<div class="control-group" style="margin:0;">
<label style="margin-bottom:6px;"><span>Auto-Pause on Loss</span></label>
<div style="display:flex; align-items:center; gap:10px;">
<input type="checkbox" id="auto-pause-en" style="accent-color:var(--accent); width:16px; height:16px; cursor:pointer;">
<span style="color:var(--text-muted); font-size:12px;">when loss <</span>
<input type="number" class="val-input" id="auto-pause-loss" value="1.0" min="0.01" step="0.01" style="width:70px;">
</div>
</div>
</div>
<div class="control-group">
<label><span>LR Schedule</span></label>
<select id="lr-schedule" onchange="updateScheduleUI(this.value)" style="width:100%; background:var(--bg-primary); border:1px solid var(--border); color:var(--text-main); font-family:var(--font-mono); font-size:13px; padding:10px; border-radius:8px; outline:none; margin-bottom:12px;">
<option value="manual">Manual (No Schedule)</option>
<option value="cosine">Cosine Decay with Warmup</option>
<option value="step">Step Decay</option>
<option value="exp">Exponential Decay</option>
</select>
</div>
<div id="sched-params" style="display:none; background:var(--bg-primary); border:1px solid var(--border); border-radius:8px; padding:16px; margin-top:-8px; margin-bottom:16px;">
<div style="display:grid; grid-template-columns:1fr 1fr; gap:12px;">
<div id="sp-warmup" style="display:none;">
<label style="color:var(--text-muted); font-size:12px; font-weight:600; display:block; margin-bottom:4px;">Warmup Steps</label>
<input type="number" class="val-input" id="sched-warmup" value="100" min="0" step="10" style="width:100%;">
</div>
<div id="sp-total">
<label style="color:var(--text-muted); font-size:12px; font-weight:600; display:block; margin-bottom:4px;">Total Steps</label>
<input type="number" class="val-input" id="sched-total" value="2000" min="100" step="100" style="width:100%;">
</div>
<div>
<label style="color:var(--text-muted); font-size:12px; font-weight:600; display:block; margin-bottom:4px;">Min LR</label>
<input type="number" class="val-input" id="sched-minlr" value="0.0001" min="0.0001" step="0.0001" style="width:100%;">
</div>
<div id="sp-decay" style="display:none;">
<label style="color:var(--text-muted); font-size:12px; font-weight:600; display:block; margin-bottom:4px;" id="decay-label">Decay Factor</label>
<input type="number" class="val-input" id="sched-decay" value="0.5" min="0.01" max="0.99" step="0.01" style="width:100%;">
</div>
<div id="sp-stepsize" style="display:none;">
<label style="color:var(--text-muted); font-size:12px; font-weight:600; display:block; margin-bottom:4px;">Step Size</label>
<input type="number" class="val-input" id="sched-stepsize" value="500" min="10" step="10" style="width:100%;">
</div>
</div>
<div style="margin-top:10px; font-size:11px; color:var(--text-muted); font-family:var(--font-mono);" id="sched-desc"></div>
</div>
<div class="stat-grid" style="margin-top:0;">
<div class="stat-item">Schedule Step <span id="ui-sched-step">-</span></div>
<div class="stat-item">Active LR <span id="ui-active-lr">-</span></div>
<div class="stat-item">Next Save <span id="ui-next-save">-</span></div>
</div>
</div>
<div id="live-eval" class="terminal-output" style="font-size:14px; color:var(--text-main);">Model not allocated. Proceed to ARCHITECTURE tab.</div>
</div>
</div>
<div class="screen" id="screen-align">
<div style="display:flex; flex-direction:column; gap:24px;">
<div class="panel">
<div class="panel-header">GROUP RELATIVE POLICY OPTIMIZATION</div>
<p style="font-size:13px; color:var(--text-muted); margin-bottom:24px; line-height:1.6;">
Executes critic-free reinforcement learning. Generates a cohort of responses, evaluates against the target reward condition, and updates parameters via Z-score normalized advantages with an approximate KL divergence constraint.
</p>
<div class="control-group">
<label>Prompt Condition</label>
<textarea id="grpo-prompt">User: Explain the sky.
Assistant: Let me think step-by-step.</textarea>
</div>
<div class="control-group">
<label>Reward Type</label>
<select id="grpo-reward-type" style="background:var(--surface);color:var(--text);border:1px solid var(--border);padding:6px 8px;border-radius:4px;width:100%;">
<option value="substring">Substring match</option>
<option value="regex">Regex match</option>
<option value="length">Length target</option>
</select>
</div>
<div class="control-group">
<label>Target / Pattern</label>
<input type="text" id="grpo-target" value="blue">
</div>
<div class="control-group">
<label>KL Coeff</label>
<input type="number" id="grpo-kl-coeff" value="0.1" min="0" max="1" step="0.01" style="width:100%;">
</div>
<div class="btn-row">
<button class="btn primary" id="btn-grpo-exec" onclick="executeGRPOEpoch()">EXECUTE GRPO EPOCH</button>
</div>
</div>
<div class="panel" style="margin-top:auto;">
<div class="panel-header">REINFORCEMENT METRICS</div>
<div class="stat-grid">
<div class="stat-item">Epochs <span id="ui-grpo-epoch">0</span></div>
<div class="stat-item">Cohort Size <span>4</span></div>
<div class="stat-item">Avg Reward <span id="ui-grpo-reward">0.000</span></div>
</div>
</div>
</div>
<div class="panel" style="display:flex; flex-direction:column;">
<div class="panel-header">COHORT TRAJECTORIES</div>
<div id="grpo-output" class="terminal-output" style="display:flex; flex-direction:column; gap:16px;">
<span style="opacity:0.5;">Awaiting GRPO initialization...</span>
</div>
</div>
</div>
<div class="screen" id="screen-infer">
<div style="display:grid; grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); gap:24px; flex:1; min-height:0;">
<div class="panel" style="display:flex; flex-direction:column;">
<div class="panel-header">DECODING SAMPLER</div>
<div class="control-group">
<label><span>Temperature</span> <input type="number" class="val-input" id="val-temp" min="0.01" max="2.0" step="0.01" value="0.80" onchange="document.getElementById('inf-temp').value=Math.round(this.value*100)"></label>
<input type="range" id="inf-temp" min="1" max="200" value="80" oninput="document.getElementById('val-temp').value=(this.value/100).toFixed(2)">
</div>
<div class="control-group">
<label><span>Top-P Nucleus</span> <input type="number" class="val-input" id="val-topp" min="0.01" max="1.0" step="0.01" value="0.90" onchange="document.getElementById('inf-topp').value=Math.round(this.value*100)"></label>
<input type="range" id="inf-topp" min="1" max="100" value="90" oninput="document.getElementById('val-topp').value=(this.value/100).toFixed(2)">
</div>
<div class="control-group">
<label><span>Max Output Tokens</span> <input type="number" class="val-input" id="val-maxt" min="10" max="1024" step="10" value="200" onchange="document.getElementById('inf-maxt').value=this.value"></label>
<input type="range" id="inf-maxt" min="10" max="1024" step="10" value="200" oninput="document.getElementById('val-maxt').value=this.value">
</div>
<div class="control-group">
<label><span>Top-K</span> <input type="number" class="val-input" id="val-topk" min="0" max="200" step="1" value="0" onchange="document.getElementById('inf-topk').value=this.value"></label>
<input type="range" id="inf-topk" min="0" max="200" value="0" oninput="document.getElementById('val-topk').value=this.value">
<small style="opacity:0.5;">0 = disabled</small>
</div>
<div class="control-group">
<label><span>Repetition Penalty</span> <input type="number" class="val-input" id="val-rep-penalty" min="1.0" max="2.0" step="0.01" value="1.0" onchange="document.getElementById('inf-rep-penalty').value=Math.round(this.value*100)"></label>
<input type="range" id="inf-rep-penalty" min="100" max="200" value="100" oninput="document.getElementById('val-rep-penalty').value=(this.value/100).toFixed(2)">
</div>
<div class="control-group" style="margin-top:auto;">
<label>Context Sequence</label>
<textarea id="inf-prompt" style="height:120px;" placeholder="Input context sequence..."></textarea>
</div>
<div class="btn-row">
<button class="btn primary" id="btn-infer-run" onclick="startInference()">GENERATE</button>
<button class="btn danger" id="btn-infer-stop" style="flex: 0.3;" onclick="stopInference()" disabled>HALT</button>
</div>
</div>
<div class="panel" style="display:flex; flex-direction:column;">
<div class="panel-header">RUNTIME OUTPUT</div>
<div id="inf-output" class="terminal-output" style="font-size:15px; color:var(--text-main);"></div>
</div>
</div>
</div>
<div class="screen" id="screen-io">
<div class="panel" style="max-width: 1200px; margin: 0 auto; width: 100%;">
<div class="panel-header">VIRTUAL MACHINE STATE PERSISTENCE</div>
<p style="font-size:14px; color:var(--text-muted); margin-bottom:32px; line-height:1.7;">
Master weights residing in Javascript Float32Arrays are serialized into binary formats.
Local DB logic utilizes native ArrayBuffer storage for robustness, strictly eliminating Base64 call stack limits.
Momentum buffers from Muon are strategically discarded to halve the storage footprint.
</p>
<div style="display:grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 32px;">
<div style="background:var(--bg-primary); border:1px solid var(--border); padding:32px 24px; border-radius:12px; text-align:center;">
<h3 style="color:var(--text-main); font-size:14px; font-family:var(--font-mono); margin-bottom:24px; letter-spacing:1px;">LOCAL INDEXED DB</h3>
<div class="btn-row" style="justify-content:center;">
<button class="btn" onclick="saveToIDB()">COMMIT TO DB</button>
<button class="btn primary" onclick="loadFromIDB()">HYDRATE FROM DB</button>
</div>
</div>
<div style="background:var(--bg-primary); border:1px solid var(--border); padding:32px 24px; border-radius:12px; text-align:center;">
<h3 style="color:var(--text-main); font-size:14px; font-family:var(--font-mono); margin-bottom:8px; letter-spacing:1px;">EXTERNAL I/O (.pip / .json)</h3>
<div style="margin-bottom:16px;">
<label style="color:var(--text-muted); font-size:12px; font-weight:600; margin-right:12px;">
<input type="radio" name="export-fmt" value="pip" checked style="accent-color:var(--accent)"> .pip
</label>
<label style="color:var(--text-muted); font-size:12px; font-weight:600;">
<input type="radio" name="export-fmt" value="json" style="accent-color:var(--accent)"> .json
</label>
</div>
<div class="btn-row" style="justify-content:center;">
<button class="btn" onclick="exportModel()">SERIALIZE</button>
<button class="btn primary" onclick="document.getElementById('import-file').click()">LOAD</button>
<input type="file" id="import-file" accept=".pip,.json" style="display:none" onchange="importJSON(this)">
</div>
</div>
<div style="background:var(--bg-primary); border:1px solid var(--border); padding:32px 24px; border-radius:12px; text-align:center;">
<h3 style="color:var(--text-main); font-size:14px; font-family:var(--font-mono); margin-bottom:8px; letter-spacing:1px;">JUNTO NODE</h3>
<div style="margin-bottom:16px;">
<input type="text" id="junto-node-id" placeholder="Node ID (auto-generated)" style="width:100%; background:var(--bg-primary); border:1px solid var(--border); color:var(--text-main); font-family:var(--font-mono); font-size:13px; padding:10px; border-radius:8px; outline:none; margin-bottom:8px; box-sizing:border-box;">
<input type="text" id="junto-corpus-label" placeholder="Corpus label (e.g. 'naturalist-prose')" style="width:100%; background:var(--bg-primary); border:1px solid var(--border); color:var(--text-main); font-family:var(--font-mono); font-size:13px; padding:10px; border-radius:8px; outline:none; box-sizing:border-box;">
</div>
<div class="btn-row" style="justify-content:center;">
<button class="btn primary" onclick="JuntoNode.init(document.getElementById('junto-node-id').value, document.getElementById('junto-corpus-label').value)">JOIN SWARM</button>
</div>
<div style="margin-top:12px; font-size:11px; color:var(--text-muted); font-family:var(--font-mono);" id="junto-status">Inactive</div>
</div>
</div>
</div>
</div>
<footer>
<div class="footer-stat">V8 Context: <span class="sys-ok">Active</span></div>
<div class="footer-stat">Corpus Size: <span id="ft-corpus">0</span> b</div>
<div class="footer-stat">Tokens Map: <span id="ft-tok">0</span></div>
<div style="margin-left:auto;" class="footer-stat">
Heap Mem: <span id="ft-mem">0.0</span> MB
<div class="mem-gauge-wrapper"><div id="mem-gauge-fill"></div></div>
</div>
</footer>
</div>
<script>
/**
* HTMLNLM CORE RUNTIME - Debugged RWKV-v7 Version
* Fixes applied:
* - Fixed backward pass gradient flow in RWKVv7Block
* - Fixed token shift mu parameter initialization
* - Fixed state checkpoint copying in Trainer
* - Added proper error handling in async functions
* - Fixed layer dimension calculations for v7
*/
const CONFIG = {
oomb_chunk_size: 128,
muon_wd: 0.01,
muon_momentum: 0.95,
grad_accum_steps: 4,
grpo_g_size: 4,
kl_target: 0.02,
ema_loss: 7.5
};
const yieldToMain = () => new Promise(r => setTimeout(r, 0));
function sysLog(msg, type = 'info') {
const el = document.getElementById('sys-logs');
const cssClass = type === 'error' ? 'sys-err' : type === 'warn' ? 'sys-warn' : type === 'ok' ? 'sys-ok' : '';
const tag = type.toUpperCase().padStart(5, ' ');
el.innerHTML += `<div><span style="opacity:0.6">[${new Date().toISOString().substring(11, 19)}]</span> <span class="${cssClass}">[${tag}] ${msg}</span></div>`;
el.scrollTop = el.scrollHeight;
}
setInterval(() => {
if (performance.memory) {
const mb = performance.memory.usedJSHeapSize / 1048576;
document.getElementById('ft-mem').textContent = mb.toFixed(1);
document.getElementById('mem-gauge-fill').style.width = Math.min(100, mb / 40.96) + '%';
}
}, 1000);
function updateOptimizerUI(optType) {
const slider = document.getElementById('cfg-lr');
const input = document.getElementById('val-lr');
const label = document.getElementById('lr-label');
if (optType === 'adam') {
slider.min = 1; slider.max = 30; slider.step = 1;
if (parseFloat(slider.value) > 30) slider.value = 10;
label.textContent = 'Learning Rate (AdamW)';
input.min = 0.001; input.max = 0.03; input.step = 0.001;
} else {
slider.min = 1; slider.max = 100; slider.step = 1;
label.textContent = 'Learning Rate (Muon)';
input.min = 0.001; input.max = 0.1; input.step = 0.001;
}
input.value = (slider.value / 1000).toFixed(3);
}
function syncLRFromInput(val) {
const v = parseFloat(val);
if (isNaN(v)) return;
const slider = document.getElementById('cfg-lr');
slider.value = Math.round(v * 1000);
}
function updateScheduleUI(type) {
const p = document.getElementById('sched-params');
const desc = document.getElementById('sched-desc');
p.style.display = type === 'manual' ? 'none' : 'block';
document.getElementById('sp-warmup').style.display = type === 'cosine' ? 'block' : 'none';
document.getElementById('sp-decay').style.display = (type === 'step' || type === 'exp') ? 'block' : 'none';
document.getElementById('sp-stepsize').style.display = type === 'step' ? 'block' : 'none';
document.getElementById('sp-total').style.display = (type === 'cosine' || type === 'exp') ? 'block' : 'none';
if (type === 'cosine') { desc.textContent = 'Linear warmup -> cosine anneal to min LR.'; document.getElementById('decay-label').textContent = 'Decay Factor'; }
else if (type === 'step') { desc.textContent = 'Multiply LR by decay factor every N steps.'; document.getElementById('decay-label').textContent = 'Decay Factor'; }
else if (type === 'exp') { desc.textContent = 'LR * decay^step. Smooth continuous decay.'; document.getElementById('decay-label').textContent = 'Decay Rate'; }
}
function computeScheduledLR(baseLR, step) {
const type = document.getElementById('lr-schedule').value;
if (type === 'manual') return baseLR;
const minLR = parseFloat(document.getElementById('sched-minlr').value) || 1e-4;
if (type === 'cosine') {
const warmup = parseInt(document.getElementById('sched-warmup').value) || 100;
const total = parseInt(document.getElementById('sched-total').value) || 2000;
if (step < warmup) return baseLR * (step / Math.max(1, warmup));
const prog = Math.min(1, (step - warmup) / Math.max(1, total - warmup));
return minLR + 0.5 * (baseLR - minLR) * (1 + Math.cos(Math.PI * prog));
}
if (type === 'step') {
const factor = parseFloat(document.getElementById('sched-decay').value) || 0.5;
const stepSize = parseInt(document.getElementById('sched-stepsize').value) || 500;
return Math.max(minLR, baseLR * Math.pow(factor, Math.floor(step / stepSize)));
}
if (type === 'exp') {
const rate = parseFloat(document.getElementById('sched-decay').value) || 0.001;
const total = parseInt(document.getElementById('sched-total').value) || 2000;
return Math.max(minLR, baseLR * Math.exp(-rate * step));
}
return baseLR;
}
async function exportModel() {
if(!App.model) return sysLog('No state to export.', 'error');
const fmt = document.querySelector('input[name="export-fmt"]:checked')?.value || 'pip';
sysLog(`Serializing to .${fmt}...`, 'info');
const state = {
version: 'rwkv7',
cfg: App.model.cfg,
tok: { vocab: App.tokenizer.vocab, merges: App.tokenizer.merges, size: App.tokenizer.size },
weights: { layers: [] }
};
state.weights.emb = await bufferToBase64Async(App.model.embedding.buffer);
const layers = App.model.getLinearLayers();
for(const l of layers) state.weights.layers.push(await bufferToBase64Async(l.weight.buffer));
// Save mu (token-shift) parameters
state.weights.mu = [];
for(const b of App.model.blocks) {
if (b.mu_r) {
state.weights.mu.push({
r: await bufferToBase64Async(b.mu_r.buffer),
k: await bufferToBase64Async(b.mu_k.buffer),
v: await bufferToBase64Async(b.mu_v.buffer),
kappa: await bufferToBase64Async(b.mu_kappa.buffer),
a: await bufferToBase64Async(b.mu_a.buffer),
w: await bufferToBase64Async(b.mu_w.buffer),
});
}
}
const blob = new Blob([JSON.stringify(state)], {type: 'application/json'});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `htmlnlm_model.${fmt}`;
a.click();
URL.revokeObjectURL(url);
sysLog(`Model exported as .${fmt}.`, 'ok');
}
class TMAC {
static UNPACK_TABLE = new Int8Array(81 * 4);
static initTable() {
for(let i = 0; i < 81; i++) {
let rem = i;
TMAC.UNPACK_TABLE[i * 4] = (rem % 3) - 1; rem = Math.floor(rem / 3);
TMAC.UNPACK_TABLE[i * 4 + 1] = (rem % 3) - 1; rem = Math.floor(rem / 3);
TMAC.UNPACK_TABLE[i * 4 + 2] = (rem % 3) - 1; rem = Math.floor(rem / 3);
TMAC.UNPACK_TABLE[i * 4 + 3] = (rem % 3) - 1;
}
}
static packTernary(t0, t1, t2, t3) {
return (t0 + 1) + 3 * (t1 + 1) + 9 * (t2 + 1) + 27 * (t3 + 1);
}
static quantizeWeights(masterWeights, packedOut) {
const n = masterWeights.length;
const blocks = Math.ceil(n / 4);
let sumAbs = 0;
for (let i = 0; i < n; i++) sumAbs += Math.abs(masterWeights[i]);
const gamma = (sumAbs / n) || 1e-8;
const invGamma = 1.0 / gamma;
for (let b = 0; b < blocks; b++) {
const base = b * 4;
const t0 = base < n ? Math.max(-1, Math.min(1, Math.round(masterWeights[base] * invGamma))) : 0;
const t1 = base + 1 < n ? Math.max(-1, Math.min(1, Math.round(masterWeights[base + 1] * invGamma))) : 0;
const t2 = base + 2 < n ? Math.max(-1, Math.min(1, Math.round(masterWeights[base + 2] * invGamma))) : 0;
const t3 = base + 3 < n ? Math.max(-1, Math.min(1, Math.round(masterWeights[base + 3] * invGamma))) : 0;
packedOut[b] = TMAC.packTernary(t0, t1, t2, t3);
}
return gamma;
}
static execute(packedWeights, input, outDim, inDim, gamma, outputArr, scratchLut) {
const blocksPerRow = Math.ceil(inDim / 4);
for (let b = 0; b < blocksPerRow; b++) {
const base = b * 4;
const v0 = base < inDim ? input[base] : 0;
const v1 = base + 1 < inDim ? input[base + 1] : 0;
const v2 = base + 2 < inDim ? input[base + 2] : 0;
const v3 = base + 3 < inDim ? input[base + 3] : 0;
const lutOffset = b * 81;
for (let i = 0; i < 81; i++) {
const uBase = i * 4;
scratchLut[lutOffset + i] =
(TMAC.UNPACK_TABLE[uBase] * v0) +
(TMAC.UNPACK_TABLE[uBase + 1] * v1) +
(TMAC.UNPACK_TABLE[uBase + 2] * v2) +
(TMAC.UNPACK_TABLE[uBase + 3] * v3);
}
}
for (let o = 0; o < outDim; o++) {
let acc = 0;
const rowBase = o * blocksPerRow;
for (let b = 0; b < blocksPerRow; b++) {
acc += scratchLut[b * 81 + packedWeights[rowBase + b]];
}
outputArr[o] = acc * gamma;
}
}
}
TMAC.initTable();
class BitLinear {
constructor(inDim, outDim) {
this.inDim = inDim;
this.outDim = outDim;
this.weight = new Float32Array(outDim * inDim);
this.grad = new Float32Array(outDim * inDim);
this.momentum = new Float32Array(outDim * inDim);
this.packed = new Uint8Array(Math.ceil((outDim * inDim) / 4));
this.gamma = 1.0;
this.dirty = true;
this.lutScratch = new Float32Array(Math.ceil(inDim / 4) * 81);
const scale = Math.sqrt(3.0 / inDim);
for (let i = 0; i < this.weight.length; i++) {
this.weight[i] = (Math.random() * 2 - 1) * scale;
}
}
pack() {
if (this.dirty) {
this.gamma = TMAC.quantizeWeights(this.weight, this.packed);
this.dirty = false;
}
}
forward(x) {
this.pack();
const out = new Float32Array(this.outDim);
TMAC.execute(this.packed, x, this.outDim, this.inDim, this.gamma, out, this.lutScratch);
return out;
}
backward(gradOut, x) {
for (let o = 0; o < this.outDim; o++) {
const rowOffset = o * this.inDim;
const go = gradOut[o];
for (let i = 0; i < this.inDim; i++) {
this.grad[rowOffset + i] += go * x[i];
}
}
const gradIn = new Float32Array(this.inDim);
for (let i = 0; i < this.inDim; i++) {
let acc = 0;
for (let o = 0; o < this.outDim; o++) {
acc += this.weight[o * this.inDim + i] * gradOut[o];
}
gradIn[i] = acc;
}
return gradIn;
}
zeroGrad() { this.grad.fill(0); }
markDirty() { this.dirty = true; }
}
class LayerNorm {
constructor(dim) {
this.dim = dim;
this.weight = new Float32Array(dim).fill(1.0);
this.bias = new Float32Array(dim).fill(0.0);
this.grad_w = new Float32Array(dim);
this.grad_b = new Float32Array(dim);
}
forward(x) {
let mean = 0, v = 0;
for (let i = 0; i < this.dim; i++) mean += x[i];
mean /= this.dim;
for (let i = 0; i < this.dim; i++) v += (x[i] - mean) ** 2;
const rstd = 1.0 / Math.sqrt((v / this.dim) + 1e-5);
const out = new Float32Array(this.dim);
for (let i = 0; i < this.dim; i++) {
out[i] = ((x[i] - mean) * rstd) * this.weight[i] + this.bias[i];
}
return { out, cache: { x, mean, rstd } };
}
backward(gradOut, cache) {
if (!cache || !cache.x) return new Float32Array(this.dim);
const { x, mean, rstd } = cache;
const D = this.dim;
let sumIn = 0, sumDot = 0;
const dxNorm = new Float32Array(D);
for (let i = 0; i < D; i++) {
const norm_x = (x[i] - mean) * rstd;
this.grad_w[i] += gradOut[i] * norm_x;
this.grad_b[i] += gradOut[i];
dxNorm[i] = gradOut[i] * this.weight[i];
sumIn += dxNorm[i];
sumDot += dxNorm[i] * norm_x;
}
const gradIn = new Float32Array(D);
for (let i = 0; i < D; i++) {
const norm_x = (x[i] - mean) * rstd;
gradIn[i] = rstd * (dxNorm[i] - (sumIn + norm_x * sumDot) / D);
}
return gradIn;
}
zeroGrad() { this.grad_w.fill(0); this.grad_b.fill(0); }
step(lr) {
for(let i=0; i<this.dim; i++){
this.weight[i] -= lr * this.grad_w[i];
this.bias[i] -= lr * this.grad_b[i];
}
}
}
class AdamOptimizer {
constructor(lr, beta1=0.9, beta2=0.999, wd=0.01) {
this.lr = lr; this.beta1 = beta1; this.beta2 = beta2; this.wd = wd;
this.t = 0; this._m = {}; this._v = {};
}
async step(model) {
this.t++;
const layers = model.getLinearLayers();
const bc1 = 1 - Math.pow(this.beta1, this.t);
const bc2 = 1 - Math.pow(this.beta2, this.t);
const lrT = this.lr * Math.sqrt(bc2) / bc1;
for (let li = 0; li < layers.length; li++) {
const layer = layers[li];
const len = layer.weight.length;
if (!this._m[li]) {
this._m[li] = new Float32Array(len);
this._v[li] = new Float32Array(len);
}
const m = this._m[li], v = this._v[li];
for (let i = 0; i < len; i++) {
const g = layer.grad[i] / CONFIG.grad_accum_steps;
m[i] = this.beta1 * m[i] + (1 - this.beta1) * g;
v[i] = this.beta2 * v[i] + (1 - this.beta2) * g * g;
layer.weight[i] = layer.weight[i] * (1 - this.lr * this.wd)
- lrT * m[i] / (Math.sqrt(v[i]) + 1e-8);
}
layer.markDirty();
}
const ln_lr = this.lr * 0.1;
model.ln_in.step(ln_lr);
model.ln_out.step(ln_lr);
for(const b of model.blocks) { b.ln1.step(ln_lr); b.ln2.step(ln_lr); }
// Update mu (token-shift) parameters with simple SGD at small lr
const mu_lr = this.lr * 0.05;
for(const b of model.blocks) {
if (b.muStep) b.muStep(mu_lr);
}
await yieldToMain();
}
}
class MuonOptimizer {
constructor(lr) {
this.lr = lr;
this._buffers = {};
}
_getBuffers(cols, rows) {
const key = `${cols}_${rows}`;
if (!this._buffers[key]) {
const n = cols * cols;
this._buffers[key] = {
S: new Float32Array(n),
S2: new Float32Array(n),
Poly: new Float32Array(n),
Gc: new Float32Array(rows * cols),
Gnew: new Float32Array(rows * cols)
};
}
return this._buffers[key];
}
async newtonSchulz5(G, rows, cols) {
const n = rows * cols;
let norm = 0;
for(let i=0; i<n; i++) norm += G[i]*G[i];
norm = Math.sqrt(norm) + 1e-12;
const bufs = this._getBuffers(cols, rows);
const { S, S2, Poly, Gc, Gnew } = bufs;
for(let i=0; i<n; i++) Gc[i] = G[i] / norm;
const a = 3.4445, b = -4.7750, c = 2.0315;
for (let iter = 0; iter < 5; iter++) {
for (let x = 0; x < cols; x++) {
for (let y = 0; y < cols; y++) {
let dot = 0;
for (let r = 0; r < rows; r++) dot += Gc[r * cols + x] * Gc[r * cols + y];
S[x * cols + y] = dot;
}
}
await yieldToMain();
for (let x = 0; x < cols; x++) {
for (let y = 0; y < cols; y++) {
let dot = 0;
for (let k = 0; k < cols; k++) dot += S[x * cols + k] * S[k * cols + y];
S2[x * cols + y] = dot;
}
}
for (let x = 0; x < cols; x++) {
for (let y = 0; y < cols; y++) {
Poly[x * cols + y] = (x === y ? a : 0) + b * S[x * cols + y] + c * S2[x * cols + y];
}
}
for (let r = 0; r < rows; r++) {
for (let y = 0; y < cols; y++) {
let acc = 0;
for (let x = 0; x < cols; x++) acc += Gc[r * cols + x] * Poly[x * cols + y];
Gnew[r * cols + y] = acc;
}
}
for(let i=0; i<n; i++) Gc[i] = Gnew[i];
}
return Gc;
}
async step(model) {
const layers = model.getLinearLayers();
for (const layer of layers) {
const len = layer.weight.length;
for (let i = 0; i < len; i++) {
layer.grad[i] /= CONFIG.grad_accum_steps;
layer.momentum[i] = CONFIG.muon_momentum * layer.momentum[i] + layer.grad[i];
}
const orth = await this.newtonSchulz5(layer.momentum, layer.outDim, layer.inDim);
for (let i = 0; i < len; i++) {
layer.weight[i] = layer.weight[i] * (1 - this.lr * CONFIG.muon_wd) - this.lr * orth[i];
}
layer.markDirty();
await yieldToMain();
}
const ln_lr = this.lr * 0.1;
model.ln_in.step(ln_lr);
model.ln_out.step(ln_lr);
for(const b of model.blocks) { b.ln1.step(ln_lr); b.ln2.step(ln_lr); }
// Update mu (token-shift) parameters with simple SGD at small lr
const mu_lr = this.lr * 0.05;
for(const b of model.blocks) {
if (b.muStep) b.muStep(mu_lr);
}
}
}
class Trainer {
constructor(model, optimizer) {
this.model = model;
this.opt = optimizer;
this.isRunning = false;
this.isPaused = false;
this.globalStep = 0;
}
computeLossAndGrad(logits, targetId) {
let max = -Infinity;
for(let i=0; i<logits.length; i++) if(logits[i] > max) max = logits[i];
let sum = 0;
const probs = new Float32Array(logits.length);
for(let i=0; i<logits.length; i++) {
probs[i] = Math.exp(logits[i] - max);
sum += probs[i];
}
for(let i=0; i<logits.length; i++) probs[i] /= sum;
const loss = -Math.log(probs[targetId] + 1e-8);
probs[targetId] -= 1.0;
return { loss, grad: probs };
}
async trainSequence(tokens) {
const len = tokens.length;
if(len < 2) return 0;
let state = this.model.getEmptyState();
const checkpoints = [];
const chunkSize = parseInt(document.getElementById('cfg-ctx').value);