flodl 0.5.3

floDl — a flow-graph deep learning framework built on libtorch
Documentation
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>floDl Training Dashboard</title>
<style>
*{margin:0;padding:0;box-sizing:border-box}
:root{--bg:#0f1117;--card:#1a1d27;--border:#2a2d3a;--text:#e4e6eb;--dim:#8b8fa3;
--accent:#6c8cff;--green:#34d399;--red:#f87171;--yellow:#fbbf24;--purple:#a78bfa}
body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;
background:var(--bg);color:var(--text);padding:0;min-height:100vh}

/* Header */
.header{background:var(--card);border-bottom:1px solid var(--border);padding:16px 24px;
display:flex;flex-direction:column;gap:8px}
.header-row{display:flex;align-items:center;gap:24px;flex-wrap:wrap}
.header h1{font-size:18px;font-weight:600;color:var(--accent);letter-spacing:-0.5px}
.header h1 span{color:var(--dim);font-weight:400}
.hw-info{color:var(--dim);font-size:11px;letter-spacing:0.3px;font-family:monospace}
.stat{display:flex;flex-direction:column;gap:2px}
.stat-label{font-size:10px;text-transform:uppercase;letter-spacing:0.5px;color:var(--dim)}
.stat-value{font-size:16px;font-weight:600;font-variant-numeric:tabular-nums}
.progress-bar{flex:1;min-width:120px;max-width:300px;height:6px;background:var(--border);
border-radius:3px;overflow:hidden}
.progress-fill{height:100%;background:var(--accent);border-radius:3px;transition:width 0.3s}

/* Layout */
.grid{display:grid;grid-template-columns:1fr 1fr;gap:16px;padding:16px 24px}
@media(max-width:900px){.grid{grid-template-columns:1fr}}
.card{background:var(--card);border:1px solid var(--border);border-radius:8px;padding:16px;overflow:hidden}
.card h2{font-size:13px;text-transform:uppercase;letter-spacing:0.5px;color:var(--dim);margin-bottom:12px}
.full-width{grid-column:1/-1}

/* Charts */
canvas{width:100%;height:260px;cursor:crosshair}
.legend{display:flex;flex-wrap:wrap;gap:10px;margin-top:10px}
.legend-item{display:flex;align-items:center;gap:5px;font-size:11px;color:var(--dim);cursor:pointer;
user-select:none;padding:2px 6px;border-radius:4px;transition:opacity 0.2s,background 0.15s}
.legend-item:hover{background:rgba(108,140,255,0.1)}
.legend-item.dimmed{opacity:0.3}
.legend-item.solo{background:rgba(108,140,255,0.15)}
.legend-dot{width:8px;height:8px;border-radius:50%}

/* Resource bars */
.res-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px}
.res-item{display:flex;flex-direction:column;gap:4px}
.res-label{display:flex;justify-content:space-between;font-size:11px;color:var(--dim)}
.res-bar{height:8px;background:var(--border);border-radius:4px;overflow:hidden}
.res-fill{height:100%;border-radius:4px;transition:width 0.5s}
.res-fill.cpu{background:var(--accent)}
.res-fill.ram{background:var(--purple)}
.res-fill.gpu{background:var(--green)}
.res-fill.vram{background:var(--yellow)}

/* Log table */
.log-wrap{max-height:300px;overflow-y:auto;scrollbar-width:thin;scrollbar-color:var(--border) transparent}
.log-wrap::-webkit-scrollbar{width:6px}
.log-wrap::-webkit-scrollbar-thumb{background:var(--border);border-radius:3px}
table{width:100%;border-collapse:collapse;font-size:12px;font-variant-numeric:tabular-nums}
th{text-align:left;color:var(--dim);font-weight:500;padding:6px 8px;
border-bottom:1px solid var(--border);position:sticky;top:0;background:var(--card)}
td{padding:5px 8px;border-bottom:1px solid var(--border)}
tr:hover td{background:rgba(108,140,255,0.05)}

/* SVG toggle */
.svg-toggle{cursor:pointer;user-select:none;display:flex;align-items:center;gap:6px}
.svg-toggle .arrow{transition:transform 0.2s;font-size:10px}
.svg-toggle.open .arrow{transform:rotate(90deg)}
.svg-container{max-height:0;overflow:hidden;transition:max-height 0.3s ease;background:#fff;border-radius:6px;margin-top:8px}
.svg-container svg{width:100%;height:auto}

/* Tooltip */
.tooltip{position:fixed;background:rgba(26,29,39,0.95);color:var(--text);padding:8px 12px;
border-radius:6px;font-size:11px;pointer-events:none;display:none;z-index:100;
border:1px solid var(--border);white-space:nowrap;backdrop-filter:blur(8px)}

/* Status */
.status{display:inline-flex;align-items:center;gap:6px;font-size:12px}
.status-dot{width:8px;height:8px;border-radius:50%;background:var(--green);
animation:pulse 2s ease-in-out infinite}
.status-dot.done{background:var(--dim);animation:none}
@keyframes pulse{0%,100%{opacity:1}50%{opacity:0.4}}

/* Tab bar */
.tab-bar{display:none;background:var(--card);border-bottom:1px solid var(--border);
padding:0 24px;gap:0;overflow-x:auto;white-space:nowrap}
.tab-bar.visible{display:flex}
.tab{padding:10px 18px;font-size:12px;color:var(--dim);cursor:pointer;
border-bottom:2px solid transparent;transition:color 0.15s,border-color 0.15s;
user-select:none;font-weight:500}
.tab:hover{color:var(--text)}
.tab.active{color:var(--accent);border-bottom-color:var(--accent)}
.tab-view{display:none}
.tab-view.active{display:block}

/* GPU summary (Home tab) */
.gpu-summary-wrap{max-height:280px;overflow-y:auto;scrollbar-width:thin;scrollbar-color:var(--border) transparent}
.gpu-summary-wrap::-webkit-scrollbar{width:6px}
.gpu-summary-wrap::-webkit-scrollbar-thumb{background:var(--border);border-radius:3px}
.gpu-summary{display:grid;gap:10px}
.gpu-row{display:flex;align-items:center;gap:12px;padding:8px 12px;
background:rgba(42,45,58,0.4);border-radius:6px;font-size:12px}
.gpu-row .gpu-name{min-width:100px;color:var(--dim);font-size:11px;white-space:nowrap;
overflow:hidden;text-overflow:ellipsis;max-width:180px}
.gpu-row .gpu-stat{display:flex;flex-direction:column;align-items:center;gap:1px;min-width:64px}
.gpu-row .gpu-stat-label{font-size:9px;text-transform:uppercase;color:var(--dim);letter-spacing:0.3px}
.gpu-row .gpu-stat-value{font-size:13px;font-weight:600;font-variant-numeric:tabular-nums}
.gpu-row .gpu-vram-bar{flex:1;height:8px;background:var(--border);border-radius:4px;
overflow:hidden;min-width:80px}
.gpu-row .gpu-vram-fill{height:100%;border-radius:4px;transition:width 0.5s}
.gpu-row.fastest .gpu-stat-value{color:var(--green)}
.gpu-row.slowest .gpu-stat-value.throughput-val{color:var(--yellow)}

/* Per-GPU tab layout */
.gpu-tab-grid{display:grid;grid-template-columns:1fr 1fr;gap:16px;padding:16px 24px}
@media(max-width:900px){.gpu-tab-grid{grid-template-columns:1fr}}
</style>
</head>
<body>

<div class="header">
  <div class="header-row">
    <h1>floDl <span>Training Dashboard</span></h1>
    <div class="status" id="status">
      <div class="status-dot" id="statusDot"></div>
      <span id="statusText">Waiting...</span>
    </div>
    <div class="stat">
      <div class="stat-label">Epoch</div>
      <div class="stat-value" id="epochNum"></div>
    </div>
    <div class="progress-bar"><div class="progress-fill" id="progressFill"></div></div>
    <div class="stat">
      <div class="stat-label">ETA</div>
      <div class="stat-value" id="etaDisplay"></div>
    </div>
    <div class="stat">
      <div class="stat-label">Elapsed</div>
      <div class="stat-value" id="elapsedDisplay"></div>
    </div>
  </div>
  <div class="hw-info" id="hwInfo" style="display:none"></div>
</div>

<div class="tab-bar" id="tabBar">
  <div class="tab active" data-tab="home" onclick="switchTab('home')">Home</div>
</div>

<div id="homeView" class="tab-view active">
<div class="grid">
  <div class="card">
    <h2>Training Metrics</h2>
    <canvas id="metricsChart"></canvas>
    <div class="legend" id="metricsLegend"></div>
  </div>

  <div class="card">
    <h2>Resources</h2>
    <canvas id="resourceChart"></canvas>
    <div class="legend" id="resourceLegend"></div>
    <div class="res-grid" id="resGrid">
      <div class="res-item"><div class="res-label"><span>CPU</span><span id="cpuVal"></span></div>
        <div class="res-bar"><div class="res-fill cpu" id="cpuBar" style="width:0"></div></div></div>
      <div class="res-item"><div class="res-label"><span>RAM</span><span id="ramVal"></span></div>
        <div class="res-bar"><div class="res-fill ram" id="ramBar" style="width:0"></div></div></div>
      <div class="res-item"><div class="res-label"><span>GPU</span><span id="gpuVal"></span></div>
        <div class="res-bar"><div class="res-fill gpu" id="gpuBar" style="width:0"></div></div></div>
      <div class="res-item"><div class="res-label"><span>VRAM</span><span id="vramVal"></span></div>
        <div class="res-bar"><div class="res-fill vram" id="vramBar" style="width:0"></div></div></div>
    </div>
  </div>

  <div class="card full-width">
    <h2>Epoch Log</h2>
    <div class="log-wrap" id="logWrap">
      <table>
        <thead><tr id="logHeader"><th>Epoch</th><th>Duration</th></tr></thead>
        <tbody id="logBody"></tbody>
      </table>
    </div>
  </div>

  <div class="card full-width" id="metaCard" style="display:none">
    <details>
      <summary style="cursor:pointer;color:var(--dim);font-size:13px;text-transform:uppercase;letter-spacing:0.5px">Training Configuration</summary>
      <pre id="metaPre" style="margin-top:12px;color:var(--text);font-size:12px;white-space:pre-wrap;word-break:break-word"></pre>
    </details>
  </div>

  <div class="card full-width" id="gpuSummaryCard" style="display:none">
    <h2>GPU Overview</h2>
    <div class="gpu-summary-wrap">
      <div class="gpu-summary" id="gpuSummary"></div>
    </div>
  </div>

  <div class="card full-width" id="svgCard" style="display:none">
    <div class="svg-toggle" id="svgToggle" onclick="toggleSvg()">
      <span class="arrow">&#9654;</span>
      <h2 style="margin:0">Graph Architecture</h2>
    </div>
    <div class="svg-container" id="svgContainer"></div>
  </div>
</div>
</div><!-- /homeView -->

<div id="gpuTabContainer"></div>

<div class="tooltip" id="tooltip"></div>

<script>
// State
const epochs=[];
const metricSeries={};  // name -> [values]
const resourceSeries={cpu:[],gpu:[],ram:[],vram:[]};
// Raw byte values for RAM/VRAM (for absolute-scale display when solo'd)
const resourceRaw={ram_used:[],ram_total:[],vram_alloc:[],vram_total:[]};
const COLORS=['#6c8cff','#f87171','#34d399','#fbbf24','#a78bfa','#fb923c','#67e8f9','#f472b6','#86efac','#fcd34d','#c4b5fd','#fdba74'];
const RES_COLORS={cpu:'#6c8cff',ram:'#a78bfa',gpu:'#34d399',vram:'#fbbf24'};
let metricNames=[];
let startTime=null;
let elapsedTimer=null;
// Solo filter: {chartId: seriesName|null}. null = show all.
const soloState={metricsChart:null,resourceChart:null};
let _skipDraw=false;

// Multi-GPU state
const gpuSeries={};   // deviceIndex -> {vram:[], throughput:[], chunk:[], util:[], name:''}
let gpuCount=0;
let activeTab='home';

// --- Epoch processing (shared by live SSE and archive replay) ---
function processEpoch(d){
  epochs.push(d);
  if(!startTime)startTime=Date.now()-(d.epoch*d.duration*1000);
  const names=Object.keys(d.metrics||{});
  names.forEach(n=>{
    if(!metricSeries[n]){metricSeries[n]=[];metricNames.push(n)}
    metricSeries[n].push(d.metrics[n]);
  });
  const r=d.resources||{};
  resourceSeries.cpu.push(r.cpu!=null?r.cpu:null);
  resourceSeries.gpu.push(r.gpu!=null?r.gpu:null);
  resourceSeries.ram.push(r.ram_used!=null&&r.ram_total?r.ram_used/r.ram_total*100:null);
  resourceSeries.vram.push(r.vram_alloc!=null&&r.vram_total?r.vram_alloc/r.vram_total*100:null);
  resourceRaw.ram_used.push(r.ram_used||null);
  resourceRaw.ram_total.push(r.ram_total||null);
  resourceRaw.vram_alloc.push(r.vram_alloc||null);
  resourceRaw.vram_total.push(r.vram_total||null);
  // GPU data extraction
  if(d.gpus&&d.gpus.length>0){
    if(gpuCount===0)initGpuTabs(d.gpus);
    d.gpus.forEach(g=>{
      const idx=g.dev!=null?g.dev:0;
      const s=gpuSeries[idx];
      if(!s)return;
      s.vram.push(g.vram_alloc!=null?g.vram_alloc:null);
      s.throughput.push(g.throughput!=null?g.throughput:null);
      s.chunk.push(g.chunk!=null?g.chunk*100:null);
      s.util.push(g.util!=null?g.util:null);
      if(g.name&&!s.name)s.name=g.name;
      s.vram_total=g.vram_total||s.vram_total||null;
    });
  }
  updateHeader(d);
  updateResources(r);
  updateLog(d);
  if(!_skipDraw){drawMetrics();drawResources();updateGpuSummary();drawGpuTabs()}
  ensureLogHeaders();
}
function markComplete(msg){
  document.getElementById('statusDot').classList.add('done');
  document.getElementById('statusText').textContent=msg||'Complete';
  if(elapsedTimer){clearInterval(elapsedTimer);elapsedTimer=null}
}
function showSvg(svg){
  document.getElementById('svgCard').style.display='block';
  const c=document.getElementById('svgContainer');
  c.innerHTML=svg;
  if(document.getElementById('svgToggle').classList.contains('open')){
    c.style.maxHeight=c.scrollHeight+'px';
  }
}

// --- Tab switching ---
function switchTab(id){
  activeTab=id;
  document.querySelectorAll('.tab').forEach(t=>t.classList.toggle('active',t.dataset.tab===id));
  document.getElementById('homeView').classList.toggle('active',id==='home');
  document.querySelectorAll('.gpu-tab-view').forEach(v=>v.classList.toggle('active',v.id==='gpu-view-'+id));
  if(id==='home'){drawMetrics();drawResources()}
  else{drawGpuTabs()}
}

// --- GPU tab initialization (called once on first epoch with gpus) ---
function initGpuTabs(gpus){
  if(gpuCount>0)return; // already initialized
  gpuCount=gpus.length;
  if(gpuCount<2)return; // single GPU: no tabs needed
  const bar=document.getElementById('tabBar');
  bar.classList.add('visible');
  const container=document.getElementById('gpuTabContainer');
  gpus.forEach((g,i)=>{
    const idx=g.dev!=null?g.dev:i;
    gpuSeries[idx]={vram:[],throughput:[],chunk:[],util:[],name:g.name||'GPU '+idx,vram_total:g.vram_total||null};
    // Tab button
    const tab=document.createElement('div');
    tab.className='tab';
    tab.dataset.tab='gpu'+idx;
    tab.textContent=g.name?shortGpuName(g.name):'GPU '+idx;
    tab.onclick=()=>switchTab('gpu'+idx);
    bar.appendChild(tab);
    // Tab view with 4 charts
    const view=document.createElement('div');
    view.id='gpu-view-gpu'+idx;
    view.className='gpu-tab-view tab-view';
    view.innerHTML=
      '<div class="gpu-tab-grid">'+
      '<div class="card"><h2>VRAM Usage</h2><canvas id="gpuVram'+idx+'" style="width:100%;height:260px"></canvas></div>'+
      '<div class="card"><h2>Utilization</h2><canvas id="gpuUtil'+idx+'" style="width:100%;height:260px"></canvas></div>'+
      '<div class="card"><h2>Throughput (samples/ms)</h2><canvas id="gpuThroughput'+idx+'" style="width:100%;height:260px"></canvas></div>'+
      '<div class="card"><h2>Batch Share (%)</h2><canvas id="gpuChunk'+idx+'" style="width:100%;height:260px"></canvas></div>'+
      '</div>';
    container.appendChild(view);
  });
  document.getElementById('gpuSummaryCard').style.display='block';
  updateGpuSummary();
}

function shortGpuName(name){
  return name.replace(/^NVIDIA\s+/i,'').replace(/GeForce\s+/i,'');
}

// --- GPU summary bar (Home tab) ---
function updateGpuSummary(){
  if(gpuCount<2)return;
  const el=document.getElementById('gpuSummary');
  // Find fastest/slowest by throughput
  let maxT=-1,minT=Infinity,maxIdx=-1,minIdx=-1;
  for(const idx in gpuSeries){
    const s=gpuSeries[idx];
    const last=s.throughput.length>0?s.throughput[s.throughput.length-1]:null;
    if(last!=null&&last>maxT){maxT=last;maxIdx=+idx}
    if(last!=null&&last<minT){minT=last;minIdx=+idx}
  }
  let html='';
  for(const idx in gpuSeries){
    const s=gpuSeries[idx];
    const lastVram=s.vram.length>0?s.vram[s.vram.length-1]:null;
    const lastThru=s.throughput.length>0?s.throughput[s.throughput.length-1]:null;
    const lastChunk=s.chunk.length>0?s.chunk[s.chunk.length-1]:null;
    const lastUtil=s.util.length>0?s.util[s.util.length-1]:null;
    const vramPct=lastVram!=null&&s.vram_total?(lastVram/s.vram_total*100):0;
    const vramColor=vramPct>95?'var(--red)':vramPct>80?'var(--yellow)':'var(--green)';
    const isFastest=+idx===maxIdx&&gpuCount>1;
    const isSlowest=+idx===minIdx&&gpuCount>1&&minIdx!==maxIdx;
    html+='<div class="gpu-row'+(isFastest?' fastest':'')+(isSlowest?' slowest':'')+'">';
    html+='<span class="gpu-name" title="'+s.name+'">'+(s.name?shortGpuName(s.name):'GPU '+idx)+'</span>';
    html+='<div class="gpu-vram-bar"><div class="gpu-vram-fill" style="width:'+vramPct.toFixed(1)+'%;background:'+vramColor+'"></div></div>';
    html+='<div class="gpu-stat"><span class="gpu-stat-label">VRAM</span><span class="gpu-stat-value">'+(lastVram!=null?fmtBytes(lastVram):'\u2014')+'</span></div>';
    html+='<div class="gpu-stat"><span class="gpu-stat-label">Util</span><span class="gpu-stat-value">'+(lastUtil!=null?lastUtil.toFixed(0)+'%':'\u2014')+'</span></div>';
    html+='<div class="gpu-stat"><span class="gpu-stat-label">Throughput</span><span class="gpu-stat-value throughput-val">'+(lastThru!=null?lastThru.toFixed(2):'\u2014')+'</span></div>';
    html+='<div class="gpu-stat"><span class="gpu-stat-label">Share</span><span class="gpu-stat-value">'+(lastChunk!=null?lastChunk.toFixed(1)+'%':'\u2014')+'</span></div>';
    html+='</div>';
  }
  el.innerHTML=html;
}

// --- Per-GPU tab charts ---
function drawGpuTabs(){
  if(gpuCount<2)return;
  for(const idx in gpuSeries){
    const tabId='gpu'+idx;
    if(activeTab!==tabId)continue;
    const s=gpuSeries[idx];
    // VRAM chart (bytes)
    const vramRef=s.vram_total?{value:s.vram_total,dotted:false,color:'rgba(248,113,113,0.7)',label:'Physical VRAM'}:null;
    drawChart('gpuVram'+idx,{vram:s.vram},[RES_COLORS.vram],['vram'],false,fmtBytes,vramRef);
    // Utilization chart (%)
    drawChart('gpuUtil'+idx,{util:s.util},[RES_COLORS.gpu],['util'],true,v=>v.toFixed(0)+'%');
    // Throughput chart
    drawChart('gpuThroughput'+idx,{throughput:s.throughput},[COLORS[0]],['throughput'],false);
    // Chunk ratio chart (%)
    drawChart('gpuChunk'+idx,{share:s.chunk},[COLORS[4]],['share'],true,v=>v.toFixed(1)+'%');
  }
}

// --- Data source: live SSE or archive replay ---
// ARCHIVE_DATA is injected by monitor.save_html(); if absent, connect live.
if(typeof ARCHIVE_DATA!=='undefined'){
  _skipDraw=true;
  let archiveErr=null;
  for(let i=0;i<ARCHIVE_DATA.length;i++){
    try{processEpoch(ARCHIVE_DATA[i])}
    catch(e){archiveErr=e;console.error('processEpoch failed at index '+i+':',e);break}
  }
  _skipDraw=false;
  try{drawMetrics();drawResources();updateGpuSummary();drawGpuTabs()}catch(e){console.error('drawMetrics/drawResources:',e);archiveErr=archiveErr||e}
  // Set elapsed from sum of epoch durations (wall-clock startTime is meaningless in archive)
  const totalElapsed=ARCHIVE_DATA.reduce((s,d)=>s+(d.duration||0),0);
  document.getElementById('elapsedDisplay').textContent=fmtDur(totalElapsed);
  markComplete(archiveErr?'Archive error — see console':(ARCHIVE_COMPLETE||'Complete'));
  if(typeof ARCHIVE_SVG==='string'){try{showSvg(ARCHIVE_SVG)}catch(e){console.error('showSvg:',e)}}
  // Re-render after layout to ensure correct canvas dimensions
  requestAnimationFrame(()=>{try{drawMetrics();drawResources();updateGpuSummary();drawGpuTabs()}catch(e){console.error('rAF redraw:',e)}});
  if(archiveErr){
    const d=document.createElement('div');
    d.style.cssText='position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);background:#1a1d27;color:#f87171;padding:24px;border-radius:8px;border:1px solid #f87171;z-index:999;font-family:monospace;max-width:80%;white-space:pre-wrap';
    d.textContent='Archive replay error at epoch '+(epochs.length+1)+':\n'+archiveErr.message+'\n\nCheck browser console (F12) for details.\nProcessed '+epochs.length+'/'+ARCHIVE_DATA.length+' epochs.';
    document.body.appendChild(d);
  }
}else{
  const es=new EventSource('/events');
  es.addEventListener('epoch',e=>processEpoch(JSON.parse(e.data)));
  es.addEventListener('complete',()=>markComplete());
  if(!elapsedTimer)elapsedTimer=setInterval(updateElapsed,1000);
  fetch('/graph.svg').then(r=>{if(r.ok)return r.text();throw 0}).then(showSvg).catch(()=>{});
}

// --- Label/Hash/Metadata ---
function applyLabelHash(label,hash){
  const h1=document.querySelector('.header h1');
  if(!h1)return;
  const short=hash?hash.substring(0,8):null;
  if(label&&short)h1.innerHTML='floDl <span>'+label+' ['+short+']</span>';
  else if(short)h1.innerHTML='floDl <span>['+short+']</span>';
  if(label||short){
    const t=label?(short?label+' ['+short+']':'['+short+']'):'floDl';
    document.title='floDl'+(label?' \u2014 '+label:'')+(short?' ['+short+']':'');
  }
}
function showMeta(meta){
  if(!meta)return;
  const card=document.getElementById('metaCard');
  const pre=document.getElementById('metaPre');
  if(!card||!pre)return;
  try{pre.textContent=typeof meta==='string'?meta:JSON.stringify(meta,null,2)}
  catch(e){pre.textContent=String(meta)}
  card.style.display='block';
}
function showHardware(hw){
  if(!hw)return;
  const el=document.getElementById('hwInfo');
  if(!el)return;
  el.textContent=hw;
  el.style.display='block';
}
// Apply from archive constants
if(typeof ARCHIVE_LABEL!=='undefined'||typeof ARCHIVE_HASH!=='undefined'){
  applyLabelHash(typeof ARCHIVE_LABEL!=='undefined'?ARCHIVE_LABEL:null,typeof ARCHIVE_HASH!=='undefined'?ARCHIVE_HASH:null);
}
if(typeof ARCHIVE_META!=='undefined'&&ARCHIVE_META!==null){showMeta(ARCHIVE_META)}
if(typeof ARCHIVE_HARDWARE!=='undefined'){showHardware(ARCHIVE_HARDWARE)}
// Apply from live server injection
if(typeof LIVE_LABEL!=='undefined'||typeof LIVE_HASH!=='undefined'){
  applyLabelHash(typeof LIVE_LABEL!=='undefined'?LIVE_LABEL:null,typeof LIVE_HASH!=='undefined'?LIVE_HASH:null);
}
if(typeof LIVE_HARDWARE!=='undefined'){showHardware(LIVE_HARDWARE)}
if(typeof LIVE_META!=='undefined'&&LIVE_META!==null){showMeta(LIVE_META)}
if(typeof LIVE_GPU_INIT!=='undefined'&&LIVE_GPU_INIT!==null){initGpuTabs(LIVE_GPU_INIT)}
if(typeof ARCHIVE_GPU_INIT!=='undefined'&&ARCHIVE_GPU_INIT!==null){initGpuTabs(ARCHIVE_GPU_INIT)}

// --- Header ---
function updateHeader(d){
  document.getElementById('epochNum').textContent=d.epoch+'/'+d.total;
  document.getElementById('progressFill').style.width=(d.epoch/d.total*100)+'%';
  document.getElementById('statusDot').classList.remove('done');
  document.getElementById('statusText').textContent='Training';
  if(d.eta!=null)document.getElementById('etaDisplay').textContent=fmtDur(d.eta);
  updateElapsed();
}

function updateElapsed(){
  if(!startTime)return;
  const s=(Date.now()-startTime)/1000;
  document.getElementById('elapsedDisplay').textContent=fmtDur(s);
}

// --- Resources ---
function updateResources(r){
  setBar('cpu',r.cpu);
  setBar('gpu',r.gpu);
  if(r.ram_used!=null&&r.ram_total){
    const pct=r.ram_used/r.ram_total*100;
    document.getElementById('ramBar').style.width=pct+'%';
    document.getElementById('ramVal').textContent=fmtBytes(r.ram_used)+'/'+fmtBytes(r.ram_total);
  }
  if(r.vram_alloc!=null){
    const total=r.vram_total||0;
    const pct=total>0?Math.min(r.vram_alloc/total*100,100):0;
    const spill=total>0&&r.vram_alloc>total?r.vram_alloc-total:0;
    const bar=document.getElementById('vramBar');
    bar.style.width=pct+'%';
    bar.style.background=spill>0?'var(--red)':'var(--yellow)';
    document.getElementById('vramVal').textContent=fmtBytes(r.vram_alloc)+' / '+fmtBytes(spill);
  }
}
function setBar(id,val){
  if(val==null)return;
  document.getElementById(id+'Bar').style.width=val+'%';
  document.getElementById(id+'Val').textContent=val.toFixed(0)+'%';
}

// --- Log table ---
var logHeadersSet=false;
function ensureLogHeaders(){
  if(logHeadersSet||metricNames.length===0)return;
  logHeadersSet=true;
  const hdr=document.getElementById('logHeader');
  metricNames.forEach(n=>{const th=document.createElement('th');th.textContent=n;hdr.appendChild(th)});
  const thRes=document.createElement('th');thRes.textContent='Resources';hdr.appendChild(thRes);
}
function updateLog(d){
  const body=document.getElementById('logBody');
  const tr=document.createElement('tr');
  let html='<td>'+d.epoch+'/'+d.total+'</td><td>'+fmtDur(d.duration)+'</td>';
  metricNames.forEach(n=>{
    const v=d.metrics&&d.metrics[n]!=null?fmtVal(d.metrics[n]):'';
    html+='<td>'+v+'</td>';
  });
  const r=d.resources||{};
  let res=[];
  if(r.cpu!=null)res.push('CPU:'+r.cpu.toFixed(0)+'%');
  if(r.gpu!=null)res.push('GPU:'+r.gpu.toFixed(0)+'%');
  if(r.vram_alloc!=null){
    const spill=r.vram_total&&r.vram_alloc>r.vram_total?r.vram_alloc-r.vram_total:0;
    res.push('VRAM:'+fmtBytes(r.vram_alloc)+'/'+fmtBytes(spill));
  }
  html+='<td style="color:var(--dim);font-size:11px">'+res.join(' ')+'</td>';
  tr.innerHTML=html;
  body.insertBefore(tr,body.firstChild);
}

// --- Charts ---
function drawChart(canvasId,series,colors,labels,isPercent,yFmt,refLine){
  const canvas=document.getElementById(canvasId);
  const ctx=canvas.getContext('2d');
  const dpr=window.devicePixelRatio||1;
  const rect=canvas.getBoundingClientRect();
  canvas.width=rect.width*dpr;canvas.height=rect.height*dpr;
  ctx.scale(dpr,dpr);
  const W=rect.width,H=rect.height;
  const M={top:10,right:12,bottom:24,left:yFmt?70:48};
  const pw=W-M.left-M.right,ph=H-M.top-M.bottom;
  ctx.clearRect(0,0,W,H);

  const allNames=Object.keys(series);
  if(allNames.length===0)return;
  const solo=soloState[canvasId]||null;
  const names=solo?allNames.filter(n=>n===solo):allNames;
  let maxEp=0,minV=Infinity,maxV=-Infinity;
  // Scale axes to visible series only
  names.forEach(n=>{
    const vals=series[n];
    maxEp=Math.max(maxEp,vals.length);
    vals.forEach(v=>{if(v!=null){minV=Math.min(minV,v);maxV=Math.max(maxV,v)}});
  });
  // maxEp from all series (so X axis stays stable)
  allNames.forEach(n=>{maxEp=Math.max(maxEp,series[n].length)});
  if(!isFinite(minV)){minV=0;maxV=1}
  if(minV===maxV){minV-=1;maxV+=1}
  if(isPercent){minV=Math.min(0,minV);maxV=Math.max(100,maxV)}
  if(refLine!=null){minV=Math.min(minV,refLine.value);maxV=Math.max(maxV,refLine.value)}
  const pad=(maxV-minV)*0.05;minV-=pad;maxV+=pad;
  const xScale=i=>M.left+(i/Math.max(1,maxEp-1))*pw;
  const yScale=v=>M.top+ph-(v-minV)/(maxV-minV)*ph;

  // Grid
  const yLabel=yFmt||fmtVal;
  ctx.strokeStyle='rgba(42,45,58,0.8)';ctx.lineWidth=1;
  const yTicks=4;
  for(let i=0;i<=yTicks;i++){
    const v=minV+(maxV-minV)*i/yTicks;
    const y=yScale(v);
    ctx.beginPath();ctx.moveTo(M.left,y);ctx.lineTo(W-M.right,y);ctx.stroke();
    ctx.fillStyle='#8b8fa3';ctx.font='10px -apple-system,sans-serif';ctx.textAlign='right';
    ctx.fillText(yLabel(v),M.left-6,y+3);
  }
  // X labels
  const xStep=Math.max(1,Math.floor(maxEp/8));
  ctx.textAlign='center';
  for(let i=0;i<maxEp;i+=xStep){
    ctx.fillStyle='#8b8fa3';ctx.font='10px -apple-system,sans-serif';
    ctx.fillText(''+(i+1),xScale(i),H-M.bottom+14);
  }

  // Reference line (e.g., physical VRAM limit)
  if(refLine!=null){
    const ry=yScale(refLine.value);
    if(ry>=M.top&&ry<=M.top+ph){
      ctx.save();
      ctx.strokeStyle=refLine.color||'#8b8fa3';
      ctx.lineWidth=1.5;
      if(refLine.dotted)ctx.setLineDash([6,4]);
      ctx.beginPath();ctx.moveTo(M.left,ry);ctx.lineTo(W-M.right,ry);ctx.stroke();
      ctx.setLineDash([]);
      if(refLine.label){
        ctx.fillStyle=refLine.color||'#8b8fa3';
        ctx.font='9px -apple-system,sans-serif';
        ctx.textAlign='right';
        ctx.fillText(refLine.label,W-M.right,ry-4);
      }
      ctx.restore();
    }
  }

  // Lines (filtered by solo state — names already filtered above)
  allNames.forEach((n,si)=>{
    if(solo&&solo!==n)return;
    const vals=series[n];
    const color=colors[si%colors.length];
    ctx.strokeStyle=color;ctx.lineWidth=solo?3:2;ctx.beginPath();
    let started=false;
    vals.forEach((v,i)=>{
      if(v==null)return;
      const x=xScale(i),y=yScale(v);
      if(!started){ctx.moveTo(x,y);started=true}else{ctx.lineTo(x,y)}
    });
    ctx.stroke();
    // Dots for last point
    if(vals.length>0){
      const last=vals[vals.length-1];
      if(last!=null){
        ctx.fillStyle=color;ctx.beginPath();
        ctx.arc(xScale(vals.length-1),yScale(last),3,0,Math.PI*2);ctx.fill();
      }
    }
  });

  // Store layout for tooltip
  canvas._layout={xScale,yScale,maxEp,minV,maxV,series,names:allNames,colors,solo,yFmt:yLabel};
}

function drawMetrics(){
  drawChart('metricsChart',metricSeries,COLORS,metricNames,false);
  updateLegend('metricsLegend',metricNames,COLORS,'metricsChart',drawMetrics);
}
function drawResources(){
  const resNames=['cpu','gpu','ram','vram'];
  const resLabels={cpu:'CPU',gpu:'GPU',ram:'RAM',vram:'VRAM'};
  const resColors=[RES_COLORS.cpu,RES_COLORS.gpu,RES_COLORS.ram,RES_COLORS.vram];
  const solo=soloState['resourceChart'];
  const lastTotal=resourceRaw.vram_total.length>0?resourceRaw.vram_total[resourceRaw.vram_total.length-1]:null;
  if(solo==='ram'){
    const byteSeries={};
    byteSeries['ram']=resourceRaw.ram_used;
    drawChart('resourceChart',byteSeries,[RES_COLORS.ram],['ram'],false,fmtBytes);
  }else if(solo==='vram'){
    // Solo VRAM: byte scale with solid physical-limit line
    const byteSeries={};
    byteSeries['vram']=resourceRaw.vram_alloc;
    const vramRef=lastTotal?{value:lastTotal,dotted:false,color:'rgba(248,113,113,0.7)',label:'Physical VRAM'}:null;
    drawChart('resourceChart',byteSeries,[RES_COLORS.vram],['vram'],false,fmtBytes,vramRef);
  }else if(solo==='cpu'||solo==='gpu'){
    // Solo percentage metric with % suffix on axis
    const pctSeries={};
    pctSeries[solo]=resourceSeries[solo];
    drawChart('resourceChart',pctSeries,
      [solo==='cpu'?RES_COLORS.cpu:RES_COLORS.gpu],
      [solo],true,v=>v.toFixed(0)+'%');
  }else{
    // Combined view: dotted VRAM limit at 100%
    const vramRef=lastTotal?{value:100,dotted:true,color:'rgba(248,113,113,0.4)',label:'VRAM limit'}:null;
    drawChart('resourceChart',resourceSeries,resColors,resNames,true,null,vramRef);
  }
  updateLegend('resourceLegend',resNames,resColors,'resourceChart',drawResources,resLabels);
}

function updateLegend(id,names,colors,chartId,redrawFn,labels){
  const el=document.getElementById(id);
  // Rebuild if count changed
  if(el.children.length!==names.length){
    el.innerHTML='';
    names.forEach((n,i)=>{
      const item=document.createElement('div');item.className='legend-item';
      item.dataset.name=n;
      const dot=document.createElement('div');dot.className='legend-dot';
      dot.style.background=colors[i%colors.length];
      const label=(labels&&labels[n])||n;
      item.appendChild(dot);item.appendChild(document.createTextNode(label));
      item.addEventListener('click',()=>{
        const cur=soloState[chartId];
        soloState[chartId]=(cur===n)?null:n;
        redrawFn();
      });
      el.appendChild(item);
    });
  }
  // Update visual state
  const solo=soloState[chartId];
  Array.from(el.children).forEach(item=>{
    const n=item.dataset.name;
    item.classList.toggle('solo',solo===n);
    item.classList.toggle('dimmed',solo!==null&&solo!==n);
  });
}

// --- Tooltip ---
['metricsChart','resourceChart'].forEach(id=>{
  const canvas=document.getElementById(id);
  canvas.addEventListener('mousemove',e=>{
    const L=canvas._layout;if(!L)return;
    const rect=canvas.getBoundingClientRect();
    const mx=e.clientX-rect.left;
    let best=Infinity,bestI=-1;
    for(let i=0;i<L.maxEp;i++){
      const d=Math.abs(L.xScale(i)-mx);
      if(d<best){best=d;bestI=i}
    }
    if(best>30){tooltip.style.display='none';return}
    let html='<b>Epoch '+(bestI+1)+'</b>';
    const tipFmt=L.yFmt||fmtVal;
    L.names.forEach((n,si)=>{
      if(L.solo&&L.solo!==n)return;
      const v=L.series[n][bestI];
      if(v!=null){
        const c=L.colors[si%L.colors.length];
        html+='<br><span style="color:'+c+'">&#9632;</span> '+n+': '+tipFmt(v);
      }
    });
    const tip=document.getElementById('tooltip');
    tip.innerHTML=html;tip.style.display='block';
    let tx=e.clientX+14,ty=e.clientY-10;
    const tw=tip.offsetWidth,th=tip.offsetHeight;
    if(tx+tw>window.innerWidth)tx=e.clientX-tw-14;
    if(ty+th>window.innerHeight)ty=e.clientY-th-10;
    tip.style.left=tx+'px';tip.style.top=ty+'px';
  });
  canvas.addEventListener('mouseleave',()=>{document.getElementById('tooltip').style.display='none'});
});

// --- SVG toggle ---
function toggleSvg(){
  const t=document.getElementById('svgToggle');
  const c=document.getElementById('svgContainer');
  const opening=!t.classList.contains('open');
  t.classList.toggle('open');
  if(opening){c.style.maxHeight=c.scrollHeight+'px'}
  else{c.style.maxHeight='0'}
}

// --- Formatters ---
function fmtDur(s){
  if(s<1)return Math.round(s*1000)+'ms';
  if(s<60){const w=Math.floor(s);const f=Math.floor((s-w)*10);return f>0?w+'.'+f+'s':w+'s'}
  const h=Math.floor(s/3600),m=Math.floor(s%3600/60),sec=Math.floor(s%60);
  if(h>0)return h+'h '+String(m).padStart(2,'0')+'m';
  return m+'m '+String(sec).padStart(2,'0')+'s';
}
function fmtBytes(b){
  const GB=1073741824,MB=1048576;
  if(b>=GB)return(b/GB).toFixed(1)+' GB';
  if(b>=MB)return Math.round(b/MB)+' MB';
  return Math.round(b/1024)+' KB';
}
function fmtVal(v){
  if(Math.abs(v)<0.001&&v!==0)return v.toExponential(2);
  if(Math.abs(v)>=1000)return v.toFixed(1);
  if(Math.abs(v)>=1)return v.toFixed(4);
  return v.toFixed(4);
}

// --- Resize ---
window.addEventListener('resize',()=>{
  if(activeTab==='home'){drawMetrics();drawResources()}
  else{drawGpuTabs()}
});
</script>
</body>
</html>