Repository navigation
Expand file tree
/
Copy pathdashboard.html
More file actions
1014 lines (933 loc) · 45.3 KB
/
Copy pathdashboard.html
File metadata and controls
1014 lines (933 loc) · 45.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HexGo</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/gif.js@0.2.0/dist/gif.js"></script>
<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
:root {
--bg: #080b0f;
--surface: #0e1318;
--panel: #111820;
--border: #1c2430;
--border2: #243040;
--text: #c9d1d9;
--dim: #586374;
--dim2: #7d8fa3;
--accent: #2f7cdb;
--green: #2ea043;
--green2: #3fb950;
--orange: #c07c16;
--red: #da3633;
--red2: #f85149;
--purple: #8957e5;
--teal: #1b7c83;
--p1: #c93030;
--p2: #2060c0;
--font: 'Courier New', monospace;
}
html, body { height: 100%; overflow: hidden; }
body { background: var(--bg); color: var(--text); font-family: var(--font); font-size: 12px; display: flex; flex-direction: column; }
/* ── Tab bar ──────────────────────────────────────────────────────────── */
#tabbar {
display: flex; align-items: center;
border-bottom: 1px solid var(--border); background: var(--surface);
padding: 0 16px; gap: 0; flex-shrink: 0; height: 38px;
}
.tab {
padding: 0 18px; height: 38px; display: flex; align-items: center;
cursor: pointer; border-bottom: 2px solid transparent;
color: var(--dim); font-size: 11px; letter-spacing: 1px;
transition: color .1s, border-color .1s; user-select: none;
}
.tab:hover { color: var(--dim2); }
.tab.active { color: var(--text); border-bottom-color: var(--accent); }
#branding { margin-left: auto; color: var(--dim); letter-spacing: 4px; font-size: 10px; }
/* ── Tab panels ───────────────────────────────────────────────────────── */
.tabpanel { display: none; flex: 1; overflow: hidden; min-height: 0; }
.tabpanel.active { display: flex; flex-direction: column; }
/* ── Layout primitives ────────────────────────────────────────────────── */
.panel {
background: var(--panel);
border: 1px solid var(--border);
border-radius: 3px;
}
.panel-hd {
padding: 8px 12px;
border-bottom: 1px solid var(--border);
color: var(--dim); font-size: 10px; letter-spacing: 1.5px;
display: flex; align-items: center; justify-content: space-between;
flex-shrink: 0;
}
.panel-body { padding: 10px 12px; }
.row { display: flex; gap: 8px; }
.col { display: flex; flex-direction: column; gap: 8px; }
/* ── Stat rows ────────────────────────────────────────────────────────── */
.sr { display: flex; justify-content: space-between; align-items: baseline; padding: 3px 0; border-bottom: 1px solid var(--border); }
.sr:last-child { border-bottom: none; }
.sr-k { color: var(--dim2); font-size: 11px; }
.sr-v { color: var(--text); font-variant-numeric: tabular-nums; }
.sr-v.good { color: var(--green2); }
.sr-v.warn { color: var(--orange); }
.sr-v.bad { color: var(--red2); }
/* ── Pill badges ──────────────────────────────────────────────────────── */
.pill {
display: inline-flex; align-items: center; gap: 4px;
padding: 2px 8px; border-radius: 2px; font-size: 10px; letter-spacing: 1px;
}
.pill-idle { background: #1a2030; color: var(--dim); border: 1px solid var(--border); }
.pill-running { background: #0d2010; color: var(--green2); border: 1px solid #1a4020; }
.pill-warn { background: #2a1a00; color: var(--orange); border: 1px solid #3a2a00; }
.dot { width: 6px; height: 6px; border-radius: 50%; background: currentColor; }
/* ── Buttons ──────────────────────────────────────────────────────────── */
button {
background: var(--surface); color: var(--dim2);
border: 1px solid var(--border2); border-radius: 2px;
padding: 5px 12px; cursor: pointer; font-family: var(--font); font-size: 11px;
letter-spacing: .5px; transition: background .1s, color .1s;
}
button:hover { background: var(--border); color: var(--text); }
button.primary { background: #112040; border-color: var(--accent); color: var(--accent); }
button.primary:hover { background: #182c58; }
button.danger { background: #200c0c; border-color: var(--red); color: var(--red2); }
button.danger:hover { background: #2c1010; }
button.export { background: #0d2020; border-color: var(--teal); color: #26a6ae; }
button.export:hover { background: #123030; }
button:disabled { opacity: .35; cursor: not-allowed; }
.icon-btn { padding: 3px 7px; font-size: 12px; }
/* ── Form inputs ──────────────────────────────────────────────────────── */
input[type=number], input[type=text], select {
background: var(--bg); border: 1px solid var(--border); color: var(--text);
border-radius: 2px; padding: 4px 7px; font-family: var(--font); font-size: 11px; width: 100%;
}
input:focus, select:focus { outline: none; border-color: var(--accent); }
label { color: var(--dim2); font-size: 10px; letter-spacing: .5px; margin-bottom: 3px; display: block; }
input[type=range] { accent-color: var(--accent); width: 100%; }
/* ── Chart wrapper ────────────────────────────────────────────────────── */
.chart-wrap { flex: 1; min-height: 0; position: relative; }
.chart-wrap canvas { position: absolute; inset: 0; width: 100% !important; height: 100% !important; }
/* ── Log ──────────────────────────────────────────────────────────────── */
#log-tail {
color: var(--dim2); font-size: 10px; line-height: 1.5;
overflow-y: auto; flex: 1; min-height: 0;
white-space: pre-wrap; margin: 0; padding: 8px 12px;
}
#log-tail .err { color: var(--red2); }
#log-tail .warn { color: var(--orange); }
#log-tail .ok { color: var(--green2); }
/* ── Training tab layout ──────────────────────────────────────────────── */
#tab-training { padding: 8px; gap: 8px; }
.train-top { display: flex; gap: 8px; flex-shrink: 0; }
.train-charts { display: flex; gap: 8px; flex: 1; min-height: 0; }
.train-bottom { flex: 0 0 130px; display: flex; gap: 8px; min-height: 0; }
/* ── Config tab ───────────────────────────────────────────────────────── */
#tab-config { padding: 8px; overflow-y: auto; gap: 8px; }
</style>
</head>
<body>
<div id="tabbar">
<div class="tab active" data-tab="training">TRAINING</div>
<div class="tab" data-tab="replay">REPLAY</div>
<div class="tab" data-tab="config">CONFIG</div>
<div id="branding">HEXGO</div>
</div>
<!-- ═══════════════════════════════ TRAINING TAB ════════════════════════════ -->
<div class="tabpanel active" id="tab-training">
<!-- row 1: controls | status | last gen | health -->
<div class="train-top">
<!-- controls -->
<div class="panel col" style="flex:0 0 172px;">
<div class="panel-hd">CONTROLS</div>
<div class="panel-body col" style="gap:7px; flex:1;">
<div><label>GENERATIONS</label><input type="number" id="c-gens" value="50" min="1" max="9999"></div>
<div><label>GAMES / GEN</label><input type="number" id="c-games" value="64" min="1" max="200"></div>
<div style="margin-top:2px; display:flex; gap:6px;">
<button class="primary" id="btn-start" onclick="trainStart()" style="flex:1;">▶ START</button>
<button class="danger" id="btn-stop" onclick="trainStop()" style="flex:1;" disabled>■ STOP</button>
</div>
<button class="export" onclick="exportData()" style="margin-top:2px;">↓ EXPORT</button>
</div>
</div>
<!-- status -->
<div class="panel" style="flex:1;">
<div class="panel-hd">STATUS</div>
<div class="panel-body">
<div style="margin-bottom:8px;"><span id="status-pill" class="pill pill-idle"><span class="dot"></span>IDLE</span></div>
<div id="status-stats"></div>
</div>
</div>
<!-- last gen -->
<div class="panel" style="flex:1;">
<div class="panel-hd">LAST GENERATION</div>
<div class="panel-body" id="last-gen-stats" style="display:grid; grid-template-columns:1fr 1fr; gap:0 16px;"></div>
</div>
<!-- health indicators -->
<div class="panel" style="flex:1;">
<div class="panel-hd">HEALTH</div>
<div class="panel-body" id="health-stats"></div>
</div>
</div>
<!-- row 2: charts 2×4 -->
<div class="train-charts">
<div class="panel" style="flex:1; display:flex; flex-direction:column;">
<div class="panel-hd" id="hd-loss">TOTAL LOSS</div>
<div class="panel-body chart-wrap" style="padding:6px;"><canvas id="chart-loss"></canvas></div>
</div>
<div class="panel" style="flex:1; display:flex; flex-direction:column;">
<div class="panel-hd" id="hd-lossv">VALUE LOSS</div>
<div class="panel-body chart-wrap" style="padding:6px;"><canvas id="chart-lossv"></canvas></div>
</div>
<div class="panel" style="flex:1; display:flex; flex-direction:column;">
<div class="panel-hd" id="hd-lossp">POLICY LOSS</div>
<div class="panel-body chart-wrap" style="padding:6px;"><canvas id="chart-lossp"></canvas></div>
</div>
<div class="panel" style="flex:1; display:flex; flex-direction:column;">
<div class="panel-hd">ENTROPY</div>
<div class="panel-body chart-wrap" style="padding:6px;"><canvas id="chart-ent"></canvas></div>
</div>
</div>
<div class="train-charts" style="flex: 0 0 0; min-height:130px;">
<div class="panel" style="flex:1; display:flex; flex-direction:column;">
<div class="panel-hd">GAMES / SEC</div>
<div class="panel-body chart-wrap" style="padding:6px;"><canvas id="chart-gps"></canvas></div>
</div>
<div class="panel" style="flex:1; display:flex; flex-direction:column;">
<div class="panel-hd">SELF-PLAY TIME</div>
<div class="panel-body chart-wrap" style="padding:6px;"><canvas id="chart-spt"></canvas></div>
</div>
<div class="panel" style="flex:1; display:flex; flex-direction:column;">
<div class="panel-hd">SIMS (curriculum)</div>
<div class="panel-body chart-wrap" style="padding:6px;"><canvas id="chart-sims"></canvas></div>
</div>
<div class="panel" style="flex:1; display:flex; flex-direction:column;">
<div class="panel-hd">LEARNING RATE</div>
<div class="panel-body chart-wrap" style="padding:6px;"><canvas id="chart-lr"></canvas></div>
</div>
</div>
<!-- row 3: log -->
<div class="panel train-bottom" style="flex-direction:column;">
<div class="panel-hd">
TRAIN LOG
<button class="icon-btn" onclick="refreshLog()" title="Refresh">↻</button>
</div>
<pre id="log-tail"></pre>
</div>
</div>
<!-- ═══════════════════════════════ REPLAY TAB ══════════════════════════════ -->
<div class="tabpanel" id="tab-replay" style="padding:8px; gap:8px;">
<div class="row" style="flex:1; min-height:0; overflow:hidden;">
<div class="panel" style="flex:0 0 180px; display:flex; flex-direction:column; overflow:hidden;">
<div class="panel-hd">
REPLAYS
<button class="icon-btn" onclick="loadReplayList()" title="Refresh">↻</button>
</div>
<div id="replay-list" style="overflow-y:auto; flex:1; padding:6px; display:flex; flex-direction:column; gap:2px;"></div>
</div>
<div class="panel" style="flex:1; display:flex; flex-direction:column; overflow:hidden;">
<div class="panel-hd" id="replay-title">SELECT A REPLAY</div>
<div class="chart-wrap" style="flex:1;"><canvas id="replay-canvas"></canvas></div>
</div>
<div class="panel col" style="flex:0 0 180px; overflow-y:auto;">
<div class="panel-hd">PLAYBACK</div>
<div class="panel-body col" style="gap:6px; flex:1;">
<div id="replay-info">
<div class="sr"><span class="sr-k">Move</span><span class="sr-v" id="r-move">—</span></div>
<div class="sr"><span class="sr-k">Player</span><span class="sr-v" id="r-player">—</span></div>
<div class="sr"><span class="sr-k">Winner</span><span class="sr-v" id="r-winner">—</span></div>
<div class="sr"><span class="sr-k">Total</span><span class="sr-v" id="r-total">—</span></div>
<div class="sr"><span class="sr-k">Gen</span><span class="sr-v" id="r-gen">—</span></div>
</div>
<div style="margin-top:4px;"><label>SPEED ms/move</label><input type="number" id="r-speed" value="300" min="50" max="2000"></div>
<input type="range" id="r-scrub" min="0" value="0">
<div class="row" style="flex-wrap:wrap; gap:4px; margin-top:2px; justify-content:center;">
<button onclick="replayStep(-1)">◀</button>
<button onclick="replayTogglePlay()" id="r-playbtn">▶▶</button>
<button onclick="replayStep(1)">▶</button>
<button onclick="replayReset()">↺</button>
</div>
<button id="r-gifbtn" onclick="replayExportGif()" style="margin-top:8px;width:100%;padding:6px;font-size:11px;">Download GIF</button>
</div>
</div>
</div>
</div>
<!-- ═══════════════════════════════ CONFIG TAB ══════════════════════════════ -->
<div class="tabpanel" id="tab-config">
<div style="padding:8px; gap:8px; display:flex; flex-wrap:wrap; align-items:flex-start; overflow-y:auto; flex:1;">
<div class="panel col" style="flex:1; min-width:260px;">
<div class="panel-hd">
HYPERPARAMETERS
<span id="config-status" style="color:var(--dim); font-size:10px;"></span>
</div>
<div class="panel-body">
<div id="config-fields" class="col" style="gap:8px; max-height:60vh; overflow-y:auto; padding-right:4px;"></div>
<div class="row" style="margin-top:12px; gap:6px;">
<button class="primary" onclick="configApply()">✓ APPLY</button>
<button onclick="configReset()">↺ RESET</button>
</div>
<div style="margin-top:6px; color:var(--dim); font-size:10px; line-height:1.6;">Changes staged until APPLY. Takes effect on next run.</div>
</div>
</div>
<div class="panel" style="flex:1; min-width:260px;">
<div class="panel-hd">PARAMETER GUIDE</div>
<div class="panel-body" id="config-guide" style="color:var(--dim2); font-size:11px; line-height:1.8;"></div>
</div>
</div>
</div>
<script>
'use strict';
// ── Tab switching ──────────────────────────────────────────────────────────
document.querySelectorAll('.tab').forEach(t => {
t.addEventListener('click', () => {
document.querySelectorAll('.tab').forEach(x => x.classList.remove('active'));
document.querySelectorAll('.tabpanel').forEach(x => x.classList.remove('active'));
t.classList.add('active');
document.getElementById('tab-' + t.dataset.tab).classList.add('active');
if (t.dataset.tab === 'replay') loadReplayList();
if (t.dataset.tab === 'config') loadConfig();
});
});
// ── API helper ─────────────────────────────────────────────────────────────
async function api(path, opts = {}) {
const r = await fetch(path, opts);
if (!r.ok) throw new Error(await r.text());
return r.json();
}
// ── Chart factory ──────────────────────────────────────────────────────────
const GRID = '#1c2430';
const TICK = { color: '#586374', font: { family: 'Courier New', size: 9 } };
function makeChart(id, datasets, yMin, yMax) {
return new Chart(document.getElementById(id), {
type: 'line',
data: { labels: [], datasets },
options: {
animation: false, responsive: true, maintainAspectRatio: false,
plugins: { legend: { display: datasets.length > 1, labels: { color: '#7d8fa3', font: { family: 'Courier New', size: 9 }, boxWidth: 10, padding: 8 } } },
scales: {
x: { ticks: TICK, grid: { color: GRID } },
y: {
ticks: TICK, grid: { color: GRID },
...(yMin !== undefined ? { min: yMin } : {}),
...(yMax !== undefined ? { max: yMax } : {}),
}
}
}
});
}
function ds(label, color, fill) {
return { label, data: [], borderColor: color,
backgroundColor: fill ? color + '18' : 'transparent',
borderWidth: 1.5, pointRadius: 1.5, pointHoverRadius: 3,
tension: 0.2, fill: !!fill };
}
const charts = {
loss: makeChart('chart-loss', [ds('total','#2f7cdb', true)]),
lossv: makeChart('chart-lossv', [ds('value','#3fb950', true)]),
lossp: makeChart('chart-lossp', [ds('policy','#d29922', true)]),
ent: makeChart('chart-ent', [ds('entropy','#8957e5', true)], 0),
gps: makeChart('chart-gps', [ds('games/s','#26a6ae', true)], 0),
spt: makeChart('chart-spt', [ds('sp_time','#e07060', true)], 0),
sims: makeChart('chart-sims', [ds('sims','#3fb950', true)], 0),
lr: makeChart('chart-lr', [ds('lr','#586374', false)]),
};
// ── Metrics store ──────────────────────────────────────────────────────────
let _allMetrics = [];
function pushMetric(d) {
// deduplicate by gen — replace if exists
const idx = _allMetrics.findIndex(m => m.gen === d.gen);
if (idx >= 0) _allMetrics[idx] = d; else _allMetrics.push(d);
_allMetrics.sort((a, b) => a.gen - b.gen);
rebuildCharts();
renderLastGen(_allMetrics[_allMetrics.length - 1]);
renderHealth(_allMetrics[_allMetrics.length - 1]);
}
function rebuildCharts() {
const labels = _allMetrics.map(d => String(d.gen));
function setChart(c, key) {
c.data.labels = labels;
c.data.datasets[0].data = _allMetrics.map(d => d[key] ?? null);
c.update('none');
}
setChart(charts.loss, 'avg_loss');
setChart(charts.lossv, 'avg_loss_v');
setChart(charts.lossp, 'avg_loss_p');
// Update headers with derivative (delta from previous gen)
function lossDerivative(key) {
const n = _allMetrics.length;
if (n < 2) return null;
const v0 = _allMetrics[n - 2][key], v1 = _allMetrics[n - 1][key];
if (v0 == null || v1 == null) return null;
return v1 - v0;
}
function derivTag(key) {
const d = lossDerivative(key);
if (d == null) return '';
const sign = d >= 0 ? '+' : '';
const color = d <= 0 ? '#3fb950' : '#e06060';
return ` <span style="color:${color};font-size:9px;margin-left:6px;">${sign}${d.toFixed(4)}/gen</span>`;
}
document.getElementById('hd-loss').innerHTML = 'TOTAL LOSS' + derivTag('avg_loss');
document.getElementById('hd-lossv').innerHTML = 'VALUE LOSS' + derivTag('avg_loss_v');
document.getElementById('hd-lossp').innerHTML = 'POLICY LOSS' + derivTag('avg_loss_p');
setChart(charts.ent, 'avg_ent');
setChart(charts.gps, 'games_per_s');
setChart(charts.spt, 'sp_time_s');
setChart(charts.sims, 'sims');
setChart(charts.lr, 'lr');
}
function fmt(v, digits = 4) {
if (v == null) return '—';
if (typeof v === 'number') return v.toFixed ? v.toFixed(digits) : v;
return String(v);
}
function renderLastGen(d) {
if (!d) return;
const el = document.getElementById('last-gen-stats');
const rows = [
['Gen', d.gen, 0],
['Games/s', d.games_per_s, 2],
['Positions', d.positions, 0],
['SP time', d.sp_time_s != null ? d.sp_time_s + 's' : null, 0],
['TR time', d.tr_time_s != null ? d.tr_time_s + 's' : null, 0],
['Buffer', d.buffer_size, 0],
['Sims', d.sims, 0],
['Max moves', d.max_moves, 0],
];
el.innerHTML = rows.map(([k, v, dig]) =>
`<div class="sr"><span class="sr-k">${k}</span><span class="sr-v">${v == null ? '—' : (typeof v === 'number' && dig ? v.toFixed(dig) : v)}</span></div>`
).join('');
}
function renderHealth(d) {
if (!d) return;
const checks = [];
// Loss trend (good if decreasing)
if (_allMetrics.length >= 2) {
const prev = _allMetrics[_allMetrics.length - 2];
const decreasing = d.avg_loss != null && prev.avg_loss != null && d.avg_loss <= prev.avg_loss;
checks.push({ label: 'Loss trend', ok: decreasing, val: decreasing ? 'decreasing' : 'increasing' });
} else {
checks.push({ label: 'Loss trend', ok: d.avg_loss != null && d.avg_loss < 10, val: fmt(d.avg_loss) });
}
// Policy loss trend
if (_allMetrics.length >= 2) {
const prev = _allMetrics[_allMetrics.length - 2];
const decreasing = d.avg_loss_p != null && prev.avg_loss_p != null && d.avg_loss_p <= prev.avg_loss_p;
checks.push({ label: 'Policy loss', ok: decreasing, val: fmt(d.avg_loss_p) });
} else {
checks.push({ label: 'Policy loss', ok: d.avg_loss_p != null, val: fmt(d.avg_loss_p) });
}
// Value loss
const vlOk = d.avg_loss_v != null && d.avg_loss_v < 0.25;
checks.push({ label: 'Value loss', ok: vlOk, val: fmt(d.avg_loss_v) });
// Entropy not collapsed
const entOk = d.avg_ent != null && d.avg_ent > 1.5 && d.avg_ent < 4.5;
checks.push({ label: 'Entropy healthy', ok: entOk, val: fmt(d.avg_ent, 3) });
document.getElementById('health-stats').innerHTML = checks.map(c =>
`<div class="sr">
<span class="sr-k">${c.label}</span>
<span class="sr-v ${c.ok ? 'good' : 'bad'}">${c.ok ? '✓' : '✗'} ${c.val}</span>
</div>`
).join('');
}
// Load history on startup
api('/api/metrics').then(arr => { arr.forEach(pushMetric); }).catch(() => {});
// ── SSE ────────────────────────────────────────────────────────────────────
let _es = null;
function connectSSE() {
if (_es) { _es.close(); _es = null; }
const es = new EventSource('/events');
_es = es;
es.onmessage = e => {
try {
const msg = JSON.parse(e.data);
if (msg.type === 'metrics') pushMetric(msg.data);
if (msg.type === 'status') updateStatus(msg.data);
} catch (_) {}
};
es.onerror = () => { es.close(); setTimeout(connectSSE, 3000); };
}
connectSSE();
// ── Status ─────────────────────────────────────────────────────────────────
function updateStatus(s) {
const pill = document.getElementById('status-pill');
const stats = document.getElementById('status-stats');
const start = document.getElementById('btn-start');
const stop = document.getElementById('btn-stop');
if (s.state === 'running') {
pill.className = 'pill pill-running';
pill.innerHTML = '<span class="dot"></span>RUNNING';
start.disabled = true; stop.disabled = false;
stats.innerHTML =
`<div class="sr"><span class="sr-k">PID</span><span class="sr-v">${s.pid}</span></div>` +
`<div class="sr"><span class="sr-k">Elapsed</span><span class="sr-v">${s.elapsed_s}s</span></div>`;
} else {
pill.className = 'pill pill-idle';
pill.innerHTML = '<span class="dot"></span>IDLE';
start.disabled = false; stop.disabled = true;
stats.innerHTML = s.returncode !== undefined
? `<div class="sr"><span class="sr-k">Exit</span><span class="sr-v ${s.returncode === 0 ? 'good' : 'bad'}">${s.returncode}</span></div>` : '';
}
}
setInterval(() => api('/api/status').then(updateStatus).catch(() => {}), 5000);
api('/api/status').then(updateStatus).catch(() => {});
// ── Training controls ──────────────────────────────────────────────────────
async function trainStart() {
const gens = document.getElementById('c-gens').value;
const games = document.getElementById('c-games').value;
try {
await api('/api/train/start', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ gens: parseInt(gens), games: parseInt(games) })
});
} catch (e) { alert('Start failed: ' + e.message); }
}
async function trainStop() {
try { await api('/api/train/stop', { method: 'POST' }); }
catch (e) { alert('Stop failed: ' + e.message); }
}
// ── Log ────────────────────────────────────────────────────────────────────
async function refreshLog() {
try {
const data = await api('/api/log?n=80');
const el = document.getElementById('log-tail');
el.innerHTML = data.lines.map(l => {
if (/ERROR|error/.test(l)) return `<span class="err">${escHtml(l)}</span>`;
if (/WARNING|warn/.test(l)) return `<span class="warn">${escHtml(l)}</span>`;
if (/Generation \d+ done|win_rate/.test(l)) return `<span class="ok">${escHtml(l)}</span>`;
return escHtml(l);
}).join('\n');
el.scrollTop = el.scrollHeight;
} catch (_) {}
}
function escHtml(s) { return s.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'); }
setInterval(refreshLog, 3000);
refreshLog();
// ── Export ─────────────────────────────────────────────────────────────────
async function exportData() {
try {
const [metrics, status] = await Promise.all([
api('/api/metrics'),
api('/api/status'),
]);
const payload = {
exported_at: new Date().toISOString(),
status,
metrics,
summary: {
total_gens: metrics.length,
latest: metrics[metrics.length - 1] || null,
min_loss_v: Math.min(...metrics.filter(m => m.avg_loss_v != null).map(m => m.avg_loss_v)),
}
};
const blob = new Blob([JSON.stringify(payload, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `hexgo_export_${new Date().toISOString().slice(0,19).replace(/[:.]/g,'-')}.json`;
a.click();
URL.revokeObjectURL(url);
} catch (e) { alert('Export failed: ' + e.message); }
}
// ── Config tab ─────────────────────────────────────────────────────────────
const CONFIG_GUIDE = {
LR: 'Adam learning rate',
WEIGHT_DECAY: 'L2 regularisation weight',
BATCH_SIZE: 'Training batch size',
SIMS: 'Full MCTS sim budget',
SIMS_MIN: 'Reduced sim budget floor — keep << SIMS',
CAP_FULL_FRAC: 'Fraction of games using full SIMS (0 = all cheap)',
CPUCT: 'PUCT exploration constant',
DIRICHLET_ALPHA: 'Root noise concentration (10/|ZoI| ≈ 0.09)',
DIRICHLET_EPS: 'Root noise weight',
ZOI_MARGIN: 'Zone-of-interest radius (min 5 for 6-in-a-row)',
ZOI_LOOKBACK: 'Recent moves defining ZOI focus',
GUMBEL_SELECTION: 'Gumbel argmax root selection',
TD_GAMMA: 'TD-lambda discount for value targets',
TEMP_HORIZON: 'Cosine temp annealing full-life (moves)',
WEIGHT_SYNC_BATCHES: 'Batches between inference server weight sync',
RECENCY_WEIGHT: 'Fraction of batch from recent half of buffer',
TRUNK_BLOCKS: 'Residual blocks in trunk',
TRUNK_CHANNELS: 'Hidden channels throughout trunk',
VALUE_LOSS_WEIGHT: 'Multiplier on MSE value loss',
ENTROPY_REG: 'Policy entropy regularisation weight',
AUX_LOSS_OWN: 'Ownership head loss weight',
AUX_LOSS_THREAT: 'Threat head loss weight',
UNC_LOSS_WEIGHT: 'Value uncertainty (Gaussian NLL) loss weight',
};
let _cfgStaged = null;
async function loadConfig() {
try {
const cfg = await api('/api/config');
_cfgStaged = Object.assign({}, cfg);
const fields = document.getElementById('config-fields');
fields.innerHTML = '';
document.getElementById('config-guide').innerHTML =
Object.entries(CONFIG_GUIDE).map(([k, v]) =>
`<div><span style="color:var(--text)">${k}</span> <span style="color:var(--dim)">—</span> ${v}</div>`
).join('');
for (const [k, v] of Object.entries(cfg)) {
const wrap = document.createElement('div');
wrap.innerHTML = `<label>${k}</label>
<input type="text" id="cfg-${k}" value="${v}" data-key="${k}" oninput="cfgStage(this)">`;
fields.appendChild(wrap);
}
} catch (_) {}
}
function cfgStage(el) {
const key = el.dataset.key;
const raw = el.value.trim();
if (raw === '') return;
const num = Number(raw);
_cfgStaged[key] = (!isNaN(num) && raw !== '') ? num : raw;
document.getElementById('config-status').textContent = '● unsaved';
}
function configReset() { loadConfig(); document.getElementById('config-status').textContent = ''; }
async function configApply() {
try {
await api('/api/config', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(_cfgStaged) });
document.getElementById('config-status').textContent = '✓ saved';
setTimeout(() => document.getElementById('config-status').textContent = '', 2000);
} catch (e) {
document.getElementById('config-status').textContent = '✗ ' + e.message;
}
}
// ── Replay tab ─────────────────────────────────────────────────────────────
let _replayData = null, _replayIdx = 0, _replayBoard = {}, _replayTimer = null, _replayPlaying = false;
let _replayZoom = 1.0, _replayPanX = 0, _replayPanY = 0;
let _replayDragging = false, _replayDragStartX = 0, _replayDragStartY = 0, _replayPanStartX = 0, _replayPanStartY = 0;
function resetReplayView() {
_replayZoom = 1.0;
_replayPanX = 0;
_replayPanY = 0;
}
// Mouse wheel zoom
(function() {
const canvas = document.getElementById('replay-canvas');
canvas.addEventListener('wheel', e => {
e.preventDefault();
const delta = e.deltaY > 0 ? -0.1 : 0.1;
_replayZoom = Math.max(0.3, Math.min(5.0, _replayZoom + delta));
if (_replayData) replayDraw();
}, { passive: false });
// Mouse drag to pan
canvas.addEventListener('mousedown', e => {
_replayDragging = true;
_replayDragStartX = e.clientX;
_replayDragStartY = e.clientY;
_replayPanStartX = _replayPanX;
_replayPanStartY = _replayPanY;
canvas.style.cursor = 'grabbing';
});
window.addEventListener('mousemove', e => {
if (!_replayDragging) return;
_replayPanX = _replayPanStartX + (e.clientX - _replayDragStartX);
_replayPanY = _replayPanStartY + (e.clientY - _replayDragStartY);
if (_replayData) replayDraw();
});
window.addEventListener('mouseup', () => {
if (_replayDragging) {
_replayDragging = false;
document.getElementById('replay-canvas').style.cursor = '';
}
});
})();
async function loadReplayList() {
try {
const list = await api('/api/replays');
const el = document.getElementById('replay-list');
el.innerHTML = '';
// Build tree: { folderName: { subFolder: { ... files }, _files: [...] } }
const tree = { _files: [] };
list.forEach(path => {
const parts = path.split('/');
const file = parts.pop();
let node = tree;
parts.forEach(dir => {
if (!node[dir]) node[dir] = { _files: [] };
node = node[dir];
});
node._files.push(path);
});
// Sort folder names: "decisive" and special dirs first, then gen folders by number desc
function sortedDirs(node) {
return Object.keys(node).filter(k => k !== '_files').sort((a, b) => {
const aGen = a.match(/^gen(\d+)$/) ? parseInt(a.match(/\d+/)[0]) : null;
const bGen = b.match(/^gen(\d+)$/) ? parseInt(b.match(/\d+/)[0]) : null;
if (aGen !== null && bGen !== null) return bGen - aGen;
if (aGen !== null) return 1;
if (bGen !== null) return -1;
return a.localeCompare(b);
});
}
function makeFileBtn(path) {
const btn = document.createElement('div');
const fname = path.split('/').pop();
let label = fname.replace('game_','').replace('.json','').replace(/_\d{8}_\d{6}$/, '');
const isW1 = fname.includes('_w1_') || fname.includes('_w1');
const isW2 = fname.includes('_w2_') || fname.includes('_w2');
if (isW1) label = '● ' + label;
else if (isW2) label = '● ' + label;
else label = '○ ' + label;
btn.textContent = label;
btn.title = path;
btn.style.cssText = `padding:3px 6px;cursor:pointer;border-radius:2px;font-size:10px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;transition:background .1s;color:${isW1 ? '#e06060' : isW2 ? '#6090e0' : 'var(--dim2)'};`;
btn.onmouseenter = () => btn.style.background = 'var(--border)';
btn.onmouseleave = () => btn.style.background = '';
btn.onclick = () => {
el.querySelectorAll('.replay-item-active').forEach(d => { d.classList.remove('replay-item-active'); d.style.background = ''; });
btn.style.background = 'var(--border)';
btn.classList.add('replay-item-active');
loadReplay(path);
};
return btn;
}
function countFiles(node) {
let n = (node._files || []).length;
Object.keys(node).filter(k => k !== '_files').forEach(k => { n += countFiles(node[k]); });
return n;
}
function renderFolder(node, name, depth) {
const folder = document.createElement('div');
folder.style.cssText = `margin-top:${depth === 0 ? 6 : 2}px;`;
const header = document.createElement('div');
const indent = depth * 10;
header.style.cssText = `padding:4px 7px;padding-left:${7+indent}px;cursor:pointer;color:var(--dim);font-size:10px;letter-spacing:1px;display:flex;align-items:center;gap:4px;user-select:none;`;
const total = countFiles(node);
const icon = name === 'decisive' ? '⚔' : name === 'vs_greedy' ? '🆚' : '📁';
const displayName = name.toUpperCase().replace(/_/g, ' ');
header.innerHTML = `<span class="folder-arrow" style="font-size:8px;transition:transform .1s;">▶</span> ${icon} ${displayName} <span style="color:var(--border2);margin-left:auto;">${total}</span>`;
const items = document.createElement('div');
items.style.cssText = 'display:none;';
header.onclick = () => {
const open = items.style.display !== 'none';
items.style.display = open ? 'none' : 'block';
header.querySelector('.folder-arrow').style.transform = open ? '' : 'rotate(90deg)';
};
// Render subdirectories first
sortedDirs(node).forEach(subName => {
items.appendChild(renderFolder(node[subName], subName, depth + 1));
});
// Then files in this folder, grouped by gen if applicable
const files = node._files || [];
if (files.length > 0) {
// Group by gen number within this folder
const genMap = {};
files.forEach(path => {
const m = path.match(/gen(\d+)/);
const gen = m ? parseInt(m[1]) : -1;
if (!genMap[gen]) genMap[gen] = [];
genMap[gen].push(path);
});
const genKeys = Object.keys(genMap).map(Number).sort((a, b) => b - a);
// If there are multiple gens, sub-group them; otherwise list flat
if (genKeys.length > 1 && files.length > 8) {
genKeys.forEach(gen => {
const subFolder = document.createElement('div');
subFolder.style.cssText = 'margin-top:2px;';
const subHeader = document.createElement('div');
subHeader.style.cssText = `padding:3px 7px;padding-left:${17+indent}px;cursor:pointer;color:var(--dim);font-size:9px;letter-spacing:1px;display:flex;align-items:center;gap:4px;user-select:none;`;
const genLabel = gen >= 0 ? `GEN ${String(gen).padStart(3,'0')}` : 'OTHER';
subHeader.innerHTML = `<span class="folder-arrow" style="font-size:7px;transition:transform .1s;">▶</span> ${genLabel} <span style="color:var(--border2);margin-left:auto;">${genMap[gen].length}</span>`;
const subItems = document.createElement('div');
subItems.style.cssText = `display:none;padding-left:${12+indent}px;`;
subHeader.onclick = (e) => {
e.stopPropagation();
const open = subItems.style.display !== 'none';
subItems.style.display = open ? 'none' : 'block';
subHeader.querySelector('.folder-arrow').style.transform = open ? '' : 'rotate(90deg)';
};
genMap[gen].forEach(path => subItems.appendChild(makeFileBtn(path)));
subFolder.appendChild(subHeader);
subFolder.appendChild(subItems);
items.appendChild(subFolder);
});
} else {
const fileContainer = document.createElement('div');
fileContainer.style.cssText = `padding-left:${12+indent}px;`;
files.forEach(path => fileContainer.appendChild(makeFileBtn(path)));
items.appendChild(fileContainer);
}
}
folder.appendChild(header);
folder.appendChild(items);
return folder;
}
// Render root-level files (not in any subfolder) grouped by gen
const rootFiles = tree._files || [];
if (rootFiles.length > 0) {
const rootNode = { _files: rootFiles };
el.appendChild(renderFolder(rootNode, 'self-play', 0));
}
// Render each top-level subfolder
sortedDirs(tree).forEach(dirName => {
el.appendChild(renderFolder(tree[dirName], dirName, 0));
});
// Auto-expand first folder
const firstHeader = el.querySelector('div div');
if (firstHeader) firstHeader.click();
} catch (_) {}
}
async function loadReplay(filename) {
try {
_replayData = await api('/api/replay/' + filename);
_replayIdx = 0; _replayBoard = {};
replayStopPlay();
resetReplayView();
const total = _replayData.moves.length;
document.getElementById('r-total').textContent = total;
document.getElementById('r-gen').textContent = _replayData.gen ?? '—';
document.getElementById('r-winner').textContent =
_replayData.winner === 1 ? 'X (P1)' : _replayData.winner === 2 ? 'O (P2)' : 'draw';
document.getElementById('replay-title').textContent =
filename.replace('game_','').replace('.json','');
const scrub = document.getElementById('r-scrub');
scrub.max = total; scrub.value = 0;
scrub.oninput = () => replayJump(parseInt(scrub.value));
replayDraw();
} catch (_) {}
}
function replayJump(idx) {
if (!_replayData) return;
_replayIdx = Math.max(0, Math.min(idx, _replayData.moves.length));
_replayBoard = {};
let cur = 1, placed = 0;
for (let i = 0; i < _replayIdx; i++) {
const [q, r] = _replayData.moves[i];
_replayBoard[`${q},${r}`] = cur;
placed++;
if (placed >= (i < 1 ? 1 : 2)) { cur = 3 - cur; placed = 0; }
}
document.getElementById('r-scrub').value = _replayIdx;
replayDraw();
}
function replayStep(d) { if (_replayData) replayJump(_replayIdx + d); }
function replayReset() { replayJump(0); }
function replayTogglePlay() {
if (_replayPlaying) { replayStopPlay(); return; }
_replayPlaying = true;
document.getElementById('r-playbtn').textContent = '⏸';
(function tick() {
if (!_replayPlaying || !_replayData) return;
if (_replayIdx >= _replayData.moves.length) { replayStopPlay(); return; }
replayStep(1);
_replayTimer = setTimeout(tick, parseInt(document.getElementById('r-speed').value) || 300);
})();
}
function replayStopPlay() {
_replayPlaying = false;
document.getElementById('r-playbtn').textContent = '▶▶';
if (_replayTimer) { clearTimeout(_replayTimer); _replayTimer = null; }
}
function replayExportGif() {
if (!_replayData || !_replayData.moves.length) return;
const btn = document.getElementById('r-gifbtn');
btn.disabled = true; btn.textContent = 'Rendering...';
replayStopPlay();
const savedIdx = _replayIdx;
const canvas = document.getElementById('replay-canvas');
const w = canvas.width, h = canvas.height;
const delay = parseInt(document.getElementById('r-speed').value) || 300;
const gif = new GIF({ workers: 2, quality: 10, width: w, height: h,
workerScript: 'https://cdn.jsdelivr.net/npm/gif.js@0.2.0/dist/gif.worker.js' });
// Render each move as a frame
const total = _replayData.moves.length;
for (let i = 0; i <= total; i++) {
replayJump(i);
gif.addFrame(canvas, { copy: true, delay: i === total ? delay * 3 : delay });
}
gif.on('finished', blob => {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
const label = _replayData.label || 'replay';
const gen = _replayData.gen != null ? `gen${String(_replayData.gen).padStart(4,'0')}` : '';
a.download = `hexgo_${label}_${gen}.gif`;
a.click();
URL.revokeObjectURL(url);
btn.disabled = false; btn.textContent = 'Download GIF';
});
gif.on('error', () => {
btn.disabled = false; btn.textContent = 'Download GIF';
});
// Restore original position
replayJump(savedIdx);
gif.render();
}
// ── Hex renderer ───────────────────────────────────────────────────────────
function replayDraw() {
const canvas = document.getElementById('replay-canvas');
const ctx = canvas.getContext('2d');
const W = canvas.width = canvas.parentElement.clientWidth || 600;
const H = canvas.height = canvas.parentElement.clientHeight || 400;
ctx.fillStyle = '#080b0f'; ctx.fillRect(0, 0, W, H);
if (!_replayData) return;
const allMoves = _replayData.moves;
if (!allMoves.length) return;
const qs = allMoves.map(m => m[0]), rs = allMoves.map(m => m[1]);
const qMin = Math.min(...qs) - 1, qMax = Math.max(...qs) + 1;
const rMin = Math.min(...rs) - 1, rMax = Math.max(...rs) + 1;
const cols = qMax - qMin + 1, rows = rMax - rMin + 1;
const baseSz = Math.max(8, Math.min(28, Math.floor(Math.min(W / (cols * 1.6), H / (rows * 1.2)))));
const sz = baseSz * _replayZoom;
const ox = W / 2 - sz * 1.5 * ((qMin + qMax) / 2) + _replayPanX;
const oy = H / 2 - sz * Math.sqrt(3) * ((rMin + rMax) / 2 + (qMin + qMax) / 4) + _replayPanY;
function toXY(q, r) { return [ox + sz * 1.5 * q, oy + sz * Math.sqrt(3) * (r + q / 2)]; }
function hexPath(cx, cy, s) {
ctx.beginPath();
for (let i = 0; i < 6; i++) {
const a = Math.PI / 3 * i;
const x = cx + (s - 1) * Math.cos(a), y = cy + (s - 1) * Math.sin(a);
i === 0 ? ctx.moveTo(x, y) : ctx.lineTo(x, y);
}
ctx.closePath();
}
const lastMove = _replayIdx > 0 ? _replayData.moves[_replayIdx - 1] : null;
for (let q = qMin; q <= qMax; q++) {
for (let r = rMin; r <= rMax; r++) {
const [cx, cy] = toXY(q, r);
// Cull off-screen hexes
if (cx < -sz || cx > W + sz || cy < -sz || cy > H + sz) continue;
const key = `${q},${r}`, p = _replayBoard[key];
const isLast = lastMove && lastMove[0] === q && lastMove[1] === r;
hexPath(cx, cy, sz);
if (p == null) {
ctx.fillStyle = '#0a0e14'; ctx.strokeStyle = '#151e2a'; ctx.lineWidth = 0.5;
} else if (p === 1) {
// Player 1 (X): red family
ctx.fillStyle = '#6a1515';
ctx.strokeStyle = isLast ? '#ffffff' : '#e84040';
ctx.lineWidth = isLast ? 2 : 1;
} else {
// Player 2 (O): blue family
ctx.fillStyle = '#0a2a5a';
ctx.strokeStyle = isLast ? '#ffffff' : '#3080e0';
ctx.lineWidth = isLast ? 2 : 1;
}
ctx.fill(); ctx.stroke();
if (p != null) {
ctx.fillStyle = p === 1 ? '#ff6060' : '#60a0ff';
ctx.font = `bold ${Math.max(7, Math.floor(sz * 0.55))}px Courier New`;
ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.fillText(p === 1 ? 'X' : 'O', cx, cy);
}
}
}
// move counter
document.getElementById('r-move').textContent = _replayIdx;