-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtrain-visualization.js
More file actions
1605 lines (1396 loc) · 60.4 KB
/
Copy pathtrain-visualization.js
File metadata and controls
1605 lines (1396 loc) · 60.4 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
// Training Memory Visualization
// Shows memory consumption during LLM training: weights, gradients, optimizer states, and activations
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')
const lossCanvas = document.getElementById('lossCanvas')
const lossCtx = lossCanvas.getContext('2d')
// Set canvas size
function resizeCanvas() {
canvas.width = window.innerWidth
canvas.height = window.innerHeight
}
resizeCanvas()
window.addEventListener('resize', resizeCanvas)
// Training state
let isTraining = false
let currentStep = 0
let maxSteps = 100000
let trainingSpeed = 50
// Initial loss based on real GPT-2 training: starts ~10-11, drops to ~4
let currentLoss = 10.8 // Realistic starting loss for GPT-2
let lossHistory = []
// Model configurations for training
const models = [
// Real GPT-2 124M parameters from actual training data
{ name: 'GPT-2-124M', params: 0.124, layers: 12, hidden: 768, heads: 12 }, // Actual: 123.69M params
{ name: 'GPT-2-345M', params: 0.345, layers: 24, hidden: 1024, heads: 16 },
{ name: 'GPT-2-762M', params: 0.762, layers: 36, hidden: 1280, heads: 20 },
{ name: 'GPT-2-1.5B', params: 1.5, layers: 48, hidden: 1600, heads: 25 },
{ name: 'Llama-3.2-1B', params: 1.2, layers: 16, hidden: 2048, heads: 32 },
{ name: 'Phi-3.5-mini', params: 3.8, layers: 32, hidden: 3072, heads: 32 },
{ name: 'Llama-3.1-8B', params: 8, layers: 32, hidden: 4096, heads: 32 },
{ name: 'Mistral-7B', params: 7, layers: 32, hidden: 4096, heads: 32 },
{ name: 'Llama-3.1-70B', params: 70, layers: 80, hidden: 8192, heads: 64 },
{ name: 'Llama-3.1-405B', params: 405, layers: 126, hidden: 16384, heads: 128 },
{ name: 'Qwen3-Next-80B', params: 80, layers: 48, hidden: 2048, heads: 16 },
{ name: 'Qwen3-Omni-30B', params: 30, layers: 36, hidden: 4096, heads: 32 },
]
// Set initial model based on default GPU (H100 80G should get a larger model)
function getDefaultModelForGPU(gpuKey) {
const gpu = gpuConfigs[gpuKey]
if (!gpu) {
console.error('GPU not found:', gpuKey)
return 4 // Default to Llama-3.2-1B
}
const gpuMemory = gpu.memory
if (gpuMemory >= 384) return 8 // Llama-3.1-70B for GB200
if (gpuMemory >= 192) return 7 // Mistral-7B for B200/MI300X
if (gpuMemory >= 80) return 6 // Llama-3.1-8B for H100/H200/B100
if (gpuMemory >= 40) return 4 // Llama-3.2-1B for A100/W7900
if (gpuMemory >= 24) return 2 // GPT-2-762M for RTX 4090
if (gpuMemory >= 16) return 1 // GPT-2-345M for Tesla T4
return 0 // GPT-2-117M for very small GPUs
}
// Default training parameters based on real GPT-2 W7900 training data
let currentModelIndex = 0 // Start with GPT-2-124M (matches real training)
let batchSize = 32 // Real batch size from actual training
let sequenceLength = 1024 // Real block size from actual training
let accumulationSteps = 4 // Real gradient accumulation (effective batch = 128)
// Optimizer configurations
const optimizers = {
SGD: { memoryFactor: 0 }, // No additional memory
Adam: { memoryFactor: 2 }, // 2x model size for momentum + variance
AdamW: { memoryFactor: 2 }, // Same as Adam
Lion: { memoryFactor: 1 }, // 1x model size for momentum only
AdaFactor: { memoryFactor: 0.5 }, // Factorized second moments
}
let currentOptimizer = 'AdamW'
// Training optimizations matching real GPT-2 W7900 training
let gradientCheckpointing = false // Not used in the real training
let mixedPrecision = true // Enabled in real training (CONFIG_MIXED_PRECISION=y)
let zeroOptimization = 0 // 0=off, 1=ZeRO-1, 2=ZeRO-2, 3=ZeRO-3
let fullyShardedDataParallel = false // Single GPU training
let gradientAccumulation = true // Enabled (gradient-accumulation 4)
// GPU configurations
const gpuConfigs = {
'Tesla T4 16G': { memory: 16, bandwidth: 300, compute: 8.1 },
'RTX 4090 24G': { memory: 24, bandwidth: 1008, compute: 82.6 },
'AMD W7900 48G': { memory: 48, bandwidth: 864, compute: 61.3 },
'A100 40G': { memory: 40, bandwidth: 1555, compute: 19.5 },
'A100 80G': { memory: 80, bandwidth: 2039, compute: 19.5 },
'H100 80G': { memory: 80, bandwidth: 3350, compute: 67 },
'H200 141G': { memory: 141, bandwidth: 4800, compute: 67 },
'B100 80G': { memory: 80, bandwidth: 8000, compute: 140 },
'B200 192G': { memory: 192, bandwidth: 8000, compute: 140 },
'GB200 384G': { memory: 384, bandwidth: 16000, compute: 280 },
'MI300X 192G': { memory: 192, bandwidth: 5300, compute: 163 },
}
// Default configuration
let currentGPU = 'AMD W7900 48G' // Default GPU
let gpuCount = 1 // Number of GPUs for distributed training
const validGPUCounts = [1, 2, 4, 8, 16, 32, 64, 128]
let useHighSpeedInterconnect = false // Will be set based on GPU
let currentInterconnect = 'pcie5' // Default to best PCIe generation available
// Famous training datacenter configurations
const worldDatacenters = {
none: {
name: 'None',
gpus: null,
gpu: null,
model: null,
batch: null,
seq: null,
optimizer: null,
interconnect: null,
},
dgx_h100: {
name: 'DGX H100',
gpus: 8,
gpu: 'H100 80G',
model: 'Llama-3.1-8B',
batch: 8,
seq: 2048,
optimizer: 'AdamW',
interconnect: 'nvlink',
},
dgx_pod: {
name: 'DGX SuperPOD',
gpus: 32,
gpu: 'H100 80G',
model: 'Llama-3.1-70B',
batch: 4,
seq: 2048,
optimizer: 'AdamW',
interconnect: 'nvlink',
},
meta_rsc: {
name: 'Meta Training',
gpus: 128,
gpu: 'A100 80G',
model: 'Llama-3.1-70B',
batch: 2,
seq: 2048,
optimizer: 'AdamW',
interconnect: 'nvlink',
},
openai_gpt: {
name: 'OpenAI GPT-4',
gpus: 64,
gpu: 'A100 40G',
model: 'Llama-3.1-8B',
batch: 4,
seq: 2048,
optimizer: 'AdamW',
interconnect: 'nvlink',
},
aws_p5: {
name: 'AWS P5 Train',
gpus: 8,
gpu: 'H100 80G',
model: 'Llama-3.1-8B',
batch: 8,
seq: 2048,
optimizer: 'AdamW',
interconnect: 'nvlink',
},
gcp_tpu: {
name: 'GCP TPU v5e',
gpus: 8,
gpu: 'TPU v5e 16G',
model: 'Llama-3.2-1B',
batch: 8,
seq: 1024,
optimizer: 'AdaFactor',
interconnect: 'tpu',
},
azure_nd: {
name: 'Azure ND A100',
gpus: 8,
gpu: 'A100 40G',
model: 'Mistral-7B',
batch: 8,
seq: 2048,
optimizer: 'AdamW',
interconnect: 'nvlink',
},
lambda_train: {
name: 'Lambda Train',
gpus: 8,
gpu: 'A100 80G',
model: 'Llama-3.1-8B',
batch: 8,
seq: 2048,
optimizer: 'Lion',
interconnect: 'nvlink',
},
budget_train: {
name: 'Budget T4',
gpus: 4,
gpu: 'Tesla T4 16G',
model: 'Llama-3.2-1B',
batch: 2,
seq: 1024,
optimizer: 'AdamW',
interconnect: 'pcie',
},
// Removed WL900 cluster - WL900 is a GPU model not an interconnect type
single_gpu: {
name: 'Single GPU',
gpus: 1,
gpu: 'H100 80G',
model: 'Llama-3.2-1B',
batch: 8,
seq: 2048,
optimizer: 'AdamW',
interconnect: 'none',
},
anthropic_claude: {
name: 'Anthropic',
gpus: 16,
gpu: 'H100 80G',
model: 'Llama-3.1-8B',
batch: 4,
seq: 4096,
optimizer: 'AdamW',
interconnect: 'nvlink',
},
stability_sd: {
name: 'Stability AI',
gpus: 8,
gpu: 'A100 80G',
model: 'Mistral-7B',
batch: 4,
seq: 2048,
optimizer: 'AdamW',
interconnect: 'nvlink',
},
cohere_train: {
name: 'Cohere Train',
gpus: 16,
gpu: 'H100 80G',
model: 'Llama-3.1-8B',
batch: 4,
seq: 2048,
optimizer: 'AdamW',
interconnect: 'nvlink',
},
}
let currentDatacenter = 'none'
// Memory calculation functions
function calculateModelWeightsMemory(model, dtype = 'fp32') {
const bytesPerParam = dtype === 'fp16' || dtype === 'bf16' ? 2 : 4
return (model.params * 1e9 * bytesPerParam) / 1024 ** 3 // GiB
}
function calculateGradientsMemory(model, dtype = 'fp32') {
// Gradients are same size as weights
const bytesPerParam = dtype === 'fp16' || dtype === 'bf16' ? 2 : 4
// Gradients accumulate during forward pass, clear after backward
const accumulation = isTraining ? 0.8 + Math.sin(Date.now() * 0.002) * 0.2 : 1
return (model.params * 1e9 * bytesPerParam * accumulation) / 1024 ** 3 // GiB
}
function calculateOptimizerMemory(model, optimizer, dtype = 'fp32') {
const baseWeightsMemory = calculateModelWeightsMemory(model, dtype)
const optimizerConfig = optimizers[optimizer]
// ZeRO optimization reduces optimizer memory
let reductionFactor = 1
if (zeroOptimization === 1) reductionFactor = 0.5 // ZeRO-1: shard optimizer states
if (zeroOptimization === 2) reductionFactor = 0.25 // ZeRO-2: shard optimizer + gradients
if (zeroOptimization === 3) reductionFactor = 0.125 // ZeRO-3: shard everything
return baseWeightsMemory * optimizerConfig.memoryFactor * reductionFactor
}
function calculateActivationsMemory(model, batchSize, sequenceLength, dtype = 'fp32') {
// Training needs to store activations for backprop
// Based on real W7900 data: GPT-2 124M uses ~24.8GB total with batch=32, seq=1024
const bytesPerValue = dtype === 'fp16' || dtype === 'bf16' ? 2 : 4
// Calibrated to match real memory usage
// Real data shows ~5.3GB allocated, ~24.8GB reserved with mixed precision
let factor = 18 // Adjusted based on actual measurements
if (gradientCheckpointing) {
factor = 5 // Reduces activation memory significantly
}
// Add dynamic variation during training (activations vary based on batch)
const variation = isTraining ? 1 + Math.sin(Date.now() * 0.001) * 0.2 : 1
const activationBytes =
batchSize * sequenceLength * model.layers * model.hidden * factor * bytesPerValue * variation
return activationBytes / 1024 ** 3 // GiB
}
function getTotalTrainingMemory() {
const model = models[currentModelIndex]
const dtype = mixedPrecision ? 'fp16' : 'fp32'
let weightsMemory = calculateModelWeightsMemory(model, dtype)
let gradientsMemory = calculateGradientsMemory(model, dtype)
let activationsMemory = calculateActivationsMemory(model, batchSize, sequenceLength, dtype)
// Mixed precision: FP16 compute weights + FP32 master weights + optimizer states
let optimizerMemory
if (mixedPrecision) {
// With mixed precision we need:
// 1. FP16 weights for computation (already in weightsMemory)
// 2. FP32 master weights
// 3. FP32 optimizer states (momentum + variance for AdamW)
const masterWeights = calculateModelWeightsMemory(model, 'fp32')
const optimizerStates = masterWeights * optimizers[currentOptimizer].memoryFactor
// Add master weights to total
weightsMemory = weightsMemory + masterWeights
// Optimizer memory is the optimizer states only
optimizerMemory = optimizerStates
} else {
optimizerMemory = calculateOptimizerMemory(model, currentOptimizer, dtype)
}
// FSDP shards everything across GPUs
if (fullyShardedDataParallel && gpuCount > 1) {
weightsMemory /= gpuCount
gradientsMemory /= gpuCount
optimizerMemory /= gpuCount
}
// Data parallel distributes activations and gradients
else if (gpuCount > 1 && !fullyShardedDataParallel) {
// In data parallel, each GPU has full model but batch is split
activationsMemory /= gpuCount
// Gradients are accumulated then synchronized
// Each GPU still needs full gradient memory
}
return {
weights: weightsMemory,
gradients: gradientsMemory,
optimizer: optimizerMemory,
activations: activationsMemory,
total: weightsMemory + gradientsMemory + optimizerMemory + activationsMemory,
}
}
// Calculate learning rate with schedule
function getLearningRate(step) {
const warmupSteps = 1000
const baseLR = 5e-5
if (step < warmupSteps) {
// Linear warmup
return baseLR * (step / warmupSteps)
} else {
// Cosine decay
const progress = (step - warmupSteps) / (maxSteps - warmupSteps)
return baseLR * 0.5 * (1 + Math.cos(Math.PI * progress))
}
}
// Draw multi-GPU cluster for distributed training
function drawMultiGPUCluster() {
const memory = getTotalTrainingMemory()
const memPerGPU = memory.total / gpuCount
const gpuMemory = gpuConfigs[currentGPU].memory
// Determine grid layout based on GPU count
let cols, rows
if (gpuCount === 2) {
cols = 2
rows = 1
} else if (gpuCount === 4) {
cols = 2
rows = 2
} else if (gpuCount === 8) {
cols = 4
rows = 2
} else if (gpuCount === 16) {
cols = 4
rows = 4
} else if (gpuCount === 32) {
cols = 8
rows = 4
} else if (gpuCount === 64) {
cols = 8
rows = 8
} else if (gpuCount === 128) {
cols = 16
rows = 8
} else {
cols = Math.ceil(Math.sqrt(gpuCount))
rows = Math.ceil(gpuCount / cols)
}
// Scale GPU size based on count - aggressive scaling for large clusters
let scaleFactor = 0.8
if (gpuCount > 8) scaleFactor = 0.6
if (gpuCount > 16) scaleFactor = 0.4
if (gpuCount > 32) scaleFactor = 0.25
if (gpuCount > 64) scaleFactor = 0.15
if (gpuCount >= 128) scaleFactor = 0.08 // Ultra compact for massive clusters
const maxGPUSize = Math.min(120, Math.min(canvas.width / (cols + 1), canvas.height / (rows + 1)))
const gpuSize = Math.max(gpuCount >= 128 ? 6 : 8, maxGPUSize * scaleFactor) // Even smaller for 128+ GPUs
const gpuSpacing = Math.max(gpuSize + 2, maxGPUSize * (gpuCount >= 128 ? 0.6 : gpuCount > 16 ? 0.9 : 1.1))
// Center the grid with better positioning
const gridWidth = (cols - 1) * gpuSpacing
const gridHeight = (rows - 1) * gpuSpacing
const offsetX = (canvas.width - gridWidth) / 2
const offsetY = (canvas.height - gridHeight) / 2 + 20 // Small offset from top
// Calculate training-specific interconnect bandwidth utilization
let interconnectBW = 64 // PCIe 5.0 default
let interconnectType = 'PCIe 5.0'
// Training synchronization traffic (gradient sync + all-reduce patterns)
const gradientSyncTraffic = memory.gradients * 1024 * Math.log2(gpuCount) // All-reduce for gradients
const activationSyncTraffic = memory.activations * 1024 * (gpuCount / 4) // Activation sharding
// Add training dynamics for multi-GPU sync
let syncPhaseFactor = 1.0
if (isTraining) {
// Multi-GPU has distinct sync phases
const syncPhase = Date.now() / 600
const phase = syncPhase % 3
if (phase < 1) {
// Forward pass - minimal sync
syncPhaseFactor = 0.3 + Math.sin(syncPhase * 3) * 0.1
} else if (phase < 2) {
// Gradient all-reduce - peak sync traffic
syncPhaseFactor = 1.3 + Math.sin(syncPhase * 2) * 0.2
} else {
// Optimizer update sync
syncPhaseFactor = 0.7 + Math.sin(syncPhase * 4) * 0.1
}
}
const totalSyncTraffic = (gradientSyncTraffic + activationSyncTraffic) * syncPhaseFactor
// Use the selected interconnect type (works for both single and multi-GPU)
const currentDC = worldDatacenters[currentDatacenter]
let interconnectSpec = currentDC?.interconnect || currentInterconnect
// Set interconnect bandwidth and type based on spec
switch (interconnectSpec) {
case 'pcie3':
interconnectType = 'PCIe 3.0'
interconnectBW = 16 // GB/s for PCIe 3.0 x16
break
case 'pcie4':
interconnectType = 'PCIe 4.0'
interconnectBW = 32 // GB/s for PCIe 4.0 x16
break
case 'pcie5':
interconnectType = 'PCIe 5.0'
interconnectBW = 64 // GB/s for PCIe 5.0 x16
break
case 'nvlink':
interconnectType = 'NVLink 4.0'
interconnectBW = 900 // GB/s for NVLink
break
case 'tpu':
interconnectType = 'TPU Interconnect'
interconnectBW = 600 // GB/s for TPU interconnect
break
default:
interconnectType = 'PCIe 5.0'
interconnectBW = 64 // GB/s for PCIe 5.0
break
}
const bandwidthUtilization = Math.min(1.0, totalSyncTraffic / (interconnectBW * 1000))
// Draw enhanced interconnect lines with data flow
if (gpuCount > 1) {
const connections = []
// Create connection list - sample evenly across all rows for large clusters
const maxConnections = gpuCount >= 128 ? 96 : Math.min(gpuCount, 64)
if (gpuCount >= 128) {
// For massive clusters, sample more evenly across columns and rows
const samplingInterval = Math.max(2, Math.floor(cols / 6)) // Sample every ~6 columns
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col += samplingInterval) {
const i = row * cols + col
const row1 = Math.floor(i / cols)
const col1 = i % cols
const x1 = offsetX + col1 * gpuSpacing
const y1 = offsetY + row1 * gpuSpacing
// Connect to neighbors
if (col1 < cols - 1) {
// Right neighbor
connections.push({
x1: x1 + gpuSize,
y1: y1 + gpuSize / 2,
x2: x1 + gpuSpacing,
y2: y1 + gpuSize / 2,
})
}
if (row1 < rows - 1) {
// Bottom neighbor
connections.push({
x1: x1 + gpuSize / 2,
y1: y1 + gpuSize,
x2: x1 + gpuSize / 2,
y2: y1 + gpuSpacing,
})
}
}
}
} else {
// Standard approach for smaller clusters
for (let i = 0; i < maxConnections; i++) {
const row1 = Math.floor(i / cols)
const col1 = i % cols
const x1 = offsetX + col1 * gpuSpacing
const y1 = offsetY + row1 * gpuSpacing
// Connect to neighbors
if (col1 < cols - 1) {
// Right neighbor
connections.push({
x1: x1 + gpuSize,
y1: y1 + gpuSize / 2,
x2: x1 + gpuSpacing,
y2: y1 + gpuSize / 2,
})
}
if (row1 < rows - 1) {
// Bottom neighbor
connections.push({
x1: x1 + gpuSize / 2,
y1: y1 + gpuSize,
x2: x1 + gpuSize / 2,
y2: y1 + gpuSpacing,
})
}
}
}
// Draw connections with bandwidth visualization
connections.forEach((conn) => {
const { x1, y1, x2, y2 } = conn
// Base line with thickness based on utilization
const lineWidth = 1 + bandwidthUtilization * 3
ctx.strokeStyle =
bandwidthUtilization > 0.8 ? '#FF4444' : bandwidthUtilization > 0.5 ? '#FFA500' : '#4CAF50'
ctx.lineWidth = lineWidth
ctx.beginPath()
ctx.moveTo(x1, y1)
ctx.lineTo(x2, y2)
ctx.stroke()
// Animate gradient sync particles (show even when not training for demo)
if (bandwidthUtilization > 0.05 || gpuCount > 1) {
const particleCount = Math.min(3, Math.max(1, Math.ceil(bandwidthUtilization * 5)))
for (let p = 0; p < particleCount; p++) {
const time = Date.now() / (500 - Math.min(bandwidthUtilization * 300, 400))
const offset = (time + p / particleCount) % 1
const particleX = x1 + (x2 - x1) * offset
const particleY = y1 + (y2 - y1) * offset
// Gradient particle (orange for gradients)
ctx.fillStyle = isTraining ? '#FF8C00' : '#4CAF50'
ctx.globalAlpha = 0.6 + Math.sin(offset * Math.PI * 2) * 0.2
ctx.beginPath()
ctx.arc(particleX, particleY, 2 + Math.max(bandwidthUtilization * 2, 1), 0, Math.PI * 2)
ctx.fill()
}
}
})
ctx.globalAlpha = 1.0
}
// Debug for large GPU counts
if (gpuCount >= 128) {
console.log(`Drawing ${gpuCount} GPUs: gpuSize=${gpuSize}px, spacing=${gpuSpacing}px, grid=${cols}×${rows}`)
}
// Draw GPUs
for (let i = 0; i < gpuCount; i++) {
const row = Math.floor(i / cols)
const col = i % cols
const x = offsetX + col * gpuSpacing
const y = offsetY + row * gpuSpacing
// GPU background gradient
const gradient = ctx.createLinearGradient(x, y, x, y + gpuSize)
gradient.addColorStop(0, 'rgba(30, 15, 15, 0.9)')
gradient.addColorStop(1, 'rgba(50, 20, 20, 0.9)')
ctx.fillStyle = gradient
ctx.fillRect(x, y, gpuSize, gpuSize * 0.75)
// GPU border - color based on memory usage
const memUsage = memPerGPU / gpuMemory
ctx.strokeStyle = memUsage > 0.9 ? '#FF4444' : memUsage > 0.7 ? '#FFA500' : '#4CAF50'
ctx.lineWidth = 2
ctx.strokeRect(x, y, gpuSize, gpuSize * 0.75)
// Memory blocks visualization (simplified for small GPUs)
if (gpuSize > 40) {
const blockSize = Math.max(4, gpuSize / 10)
const blocksPerRow = Math.floor(gpuSize / (blockSize + 1))
const blocksPerCol = Math.floor((gpuSize * 0.75) / (blockSize + 1))
const totalBlocks = blocksPerRow * blocksPerCol
const weightsBlocks = Math.floor(totalBlocks * (memory.weights / memory.total))
const gradientsBlocks = Math.floor(totalBlocks * (memory.gradients / memory.total))
const optimizerBlocks = Math.floor(totalBlocks * (memory.optimizer / memory.total))
const activationsBlocks = Math.floor(totalBlocks * (memory.activations / memory.total))
let blockIndex = 0
for (let by = 0; by < blocksPerCol; by++) {
for (let bx = 0; bx < blocksPerRow; bx++) {
const blockX = x + bx * (blockSize + 1) + 1
const blockY = y + by * (blockSize + 1) + 1
if (blockIndex < weightsBlocks) {
ctx.fillStyle = 'rgba(156, 39, 176, 0.8)' // Purple
} else if (blockIndex < weightsBlocks + gradientsBlocks) {
ctx.fillStyle = 'rgba(255, 152, 0, 0.8)' // Orange
} else if (blockIndex < weightsBlocks + gradientsBlocks + optimizerBlocks) {
ctx.fillStyle = 'rgba(244, 67, 54, 0.8)' // Red
} else if (blockIndex < weightsBlocks + gradientsBlocks + optimizerBlocks + activationsBlocks) {
ctx.fillStyle = 'rgba(76, 175, 80, 0.8)' // Green
} else {
ctx.fillStyle = 'rgba(50, 50, 50, 0.3)' // Empty
}
ctx.fillRect(blockX, blockY, blockSize, blockSize)
blockIndex++
}
}
}
// GPU label for smaller counts
if (gpuCount <= 16 && gpuSize > 30) {
ctx.fillStyle = '#FFF'
ctx.font = `${Math.max(10, gpuSize / 8)}px monospace`
ctx.textAlign = 'center'
ctx.fillText(`GPU ${i}`, x + gpuSize / 2, y - 5)
}
}
// Show total cluster info at bottom-left (to avoid controls at bottom)
ctx.fillStyle = '#FFF'
ctx.font = 'bold 14px monospace'
ctx.textAlign = 'left'
const interconnectText = useHighSpeedInterconnect ? 'NVLink' : 'PCIe'
const clusterText = fullyShardedDataParallel
? `${gpuCount}× ${currentGPU} (FSDP)`
: `${gpuCount}× ${currentGPU} (Data Parallel)`
ctx.fillText(clusterText, 20, canvas.height - 50)
const memText = `Memory: ${memPerGPU.toFixed(1)} GiB/GPU | Interconnect: ${interconnectText}`
ctx.font = '12px monospace'
ctx.fillText(memText, 20, canvas.height - 30)
// Draw interconnect bandwidth meter at bottom
const meterX = 20
const meterY = canvas.height - 100
const meterWidth = 200
const meterHeight = 20
// Meter background
ctx.fillStyle = 'rgba(0, 0, 0, 0.5)'
ctx.fillRect(meterX, meterY, meterWidth, meterHeight)
// Meter fill based on utilization
const fillWidth = meterWidth * bandwidthUtilization
const meterColor = bandwidthUtilization > 0.8 ? '#FF4444' : bandwidthUtilization > 0.5 ? '#FFA500' : '#4CAF50'
ctx.fillStyle = meterColor
ctx.fillRect(meterX, meterY, fillWidth, meterHeight)
// Meter border
ctx.strokeStyle = '#666'
ctx.lineWidth = 1
ctx.strokeRect(meterX, meterY, meterWidth, meterHeight)
// Meter label
ctx.fillStyle = '#FFF'
ctx.font = '12px monospace'
ctx.textAlign = 'left'
ctx.fillText(`${interconnectType} Bandwidth`, meterX, meterY - 5)
// Utilization percentage
ctx.font = '10px monospace'
ctx.fillStyle = '#CCC'
ctx.fillText(
`${(bandwidthUtilization * 100).toFixed(1)}% (${(totalSyncTraffic / 1024).toFixed(1)} GB sync)`,
meterX,
meterY + meterHeight + 15,
)
// Show bottleneck warning
if (bandwidthUtilization > 0.8) {
const pulse = Math.sin(Date.now() / 200) * 0.3 + 0.7
ctx.fillStyle = `rgba(255, 68, 68, ${pulse})`
ctx.font = 'bold 14px monospace'
ctx.textAlign = 'center'
ctx.fillText('⚠️ TRAINING BOTTLENECK ⚠️', canvas.width / 2, 30)
ctx.fillStyle = '#FF8888'
ctx.font = '11px monospace'
ctx.fillText(`${interconnectType} saturated - training will slow down!`, canvas.width / 2, 45)
}
// Update training performance metrics box
updateTrainingPerformanceMetrics(bandwidthUtilization, interconnectType, totalSyncTraffic, interconnectBW)
}
// Draw single GPU memory visualization
function drawGPUMemory() {
const centerX = canvas.width / 2
const centerY = canvas.height / 2
const gpuWidth = 400
const gpuHeight = 300
const gpuX = centerX - gpuWidth / 2
const gpuY = centerY - gpuHeight / 2
// GPU background
const gradient = ctx.createLinearGradient(gpuX, gpuY, gpuX, gpuY + gpuHeight)
gradient.addColorStop(0, 'rgba(30, 15, 15, 0.9)')
gradient.addColorStop(1, 'rgba(50, 20, 20, 0.9)')
ctx.fillStyle = gradient
ctx.fillRect(gpuX, gpuY, gpuWidth, gpuHeight)
// GPU border
ctx.strokeStyle = 'rgba(255, 100, 100, 0.5)'
ctx.lineWidth = 2
ctx.strokeRect(gpuX, gpuY, gpuWidth, gpuHeight)
// Memory segments visualization
const memory = getTotalTrainingMemory()
const gpuMemory = gpuConfigs[currentGPU].memory
const memoryUsage = memory.total / gpuMemory
// Draw memory blocks
const blockSize = 20
const blocksX = Math.floor(gpuWidth / (blockSize + 2))
const blocksY = Math.floor(gpuHeight / (blockSize + 2))
const totalBlocks = blocksX * blocksY
const usedBlocks = Math.floor(totalBlocks * memoryUsage) // Only fill blocks based on actual usage
const weightsBlocks = Math.floor(usedBlocks * (memory.weights / memory.total))
const gradientsBlocks = Math.floor(usedBlocks * (memory.gradients / memory.total))
const optimizerBlocks = Math.floor(usedBlocks * (memory.optimizer / memory.total))
const activationsBlocks = Math.floor(usedBlocks * (memory.activations / memory.total))
let blockIndex = 0
for (let y = 0; y < blocksY; y++) {
for (let x = 0; x < blocksX; x++) {
const blockX = gpuX + x * (blockSize + 2) + 2
const blockY = gpuY + y * (blockSize + 2) + 2
if (blockIndex < weightsBlocks) {
ctx.fillStyle = 'rgba(156, 39, 176, 0.8)' // Purple for weights
} else if (blockIndex < weightsBlocks + gradientsBlocks) {
ctx.fillStyle = 'rgba(255, 152, 0, 0.8)' // Orange for gradients
} else if (blockIndex < weightsBlocks + gradientsBlocks + optimizerBlocks) {
ctx.fillStyle = 'rgba(244, 67, 54, 0.8)' // Red for optimizer
} else if (blockIndex < weightsBlocks + gradientsBlocks + optimizerBlocks + activationsBlocks) {
ctx.fillStyle = 'rgba(76, 175, 80, 0.8)' // Green for activations
} else {
ctx.fillStyle = 'rgba(50, 50, 50, 0.3)' // Empty
}
ctx.fillRect(blockX, blockY, blockSize, blockSize)
blockIndex++
}
}
// Draw utilization indicator
const utilX = centerX
const utilY = gpuY + gpuHeight + 40
ctx.fillStyle = memoryUsage > 0.9 ? '#FF4444' : memoryUsage > 0.7 ? '#FFA500' : '#4CAF50'
ctx.font = 'bold 14px monospace'
ctx.textAlign = 'center'
ctx.fillText(`GPU Memory: ${(memoryUsage * 100).toFixed(1)}%`, utilX, utilY)
// Training progress bar
const progressWidth = 300
const progressHeight = 10
const progressX = centerX - progressWidth / 2
const progressY = utilY + 20
ctx.fillStyle = 'rgba(255, 255, 255, 0.1)'
ctx.fillRect(progressX, progressY, progressWidth, progressHeight)
const progress = currentStep / maxSteps
ctx.fillStyle = 'rgba(76, 175, 80, 0.8)'
ctx.fillRect(progressX, progressY, progressWidth * progress, progressHeight)
// Step counter
ctx.fillStyle = '#EAF2FF'
ctx.font = '12px monospace'
ctx.fillText(`Step ${currentStep.toLocaleString()} / ${maxSteps.toLocaleString()}`, centerX, progressY + 25)
// Draw interconnect bandwidth meter for single GPU (ALL GPUs use PCIe!)
try {
const memory = getTotalTrainingMemory()
// Realistic and STABLE data transfer calculation for single GPU training
// PCIe bandwidth usage depends on model size and training configuration
// For single GPU, main PCIe usage:
// 1. Data loading from CPU (continuous during training)
// 2. Gradient checkpointing if enabled
// 3. Periodic model checkpointing
// Training requires significant data movement:
// - Loading training data from CPU to GPU continuously
// - Gradient synchronization
// - Optimizer state updates
// - Checkpointing
// Training is EXTREMELY IO intensive - constantly moving data
const modelSizeGB = memory.total // Use TOTAL memory, not just weights
// Very aggressive base rate - training constantly streams data
// Real training can easily saturate PCIe bandwidth
let baseTransferRate = modelSizeGB * 0.8 // 80% of total memory per second!
// Batch size has huge impact on data loading
const batchFactor = Math.sqrt(batchSize) // Direct batch scaling
// Gradient checkpointing actually INCREASES bandwidth needs (more recomputation)
const gcOverhead = gradientCheckpointing ? 1.5 : 1.0
// Add realistic training dynamics - bandwidth varies during training phases
let trainingPhaseFactor = 1.0
if (isTraining) {
// Training has phases: data load -> forward -> backward -> optimizer update
const phaseTime = Date.now() / 500 // Phase changes every 500ms
const phase = phaseTime % 4
if (phase < 1) {
// Data loading phase - high bandwidth
trainingPhaseFactor = 1.2 + Math.sin(phaseTime * 2) * 0.1
} else if (phase < 2) {
// Forward pass - moderate bandwidth
trainingPhaseFactor = 0.6 + Math.sin(phaseTime * 3) * 0.05
} else if (phase < 3) {
// Backward pass - high bandwidth for gradients
trainingPhaseFactor = 1.1 + Math.sin(phaseTime * 2.5) * 0.08
} else {
// Optimizer update - burst of bandwidth
trainingPhaseFactor = 0.8 + Math.sin(phaseTime * 4) * 0.15
}
}
// DEBUG: Log to see what's happening
if (Math.random() < 0.01) {
// Log occasionally
console.log('Bandwidth calc:', {
memory: memory.total,
baseRate: baseTransferRate,
batchFactor,
gcOverhead,
trainingPhaseFactor,
dataTransferRate: baseTransferRate * batchFactor * gcOverhead * trainingPhaseFactor,
interconnectBW,
interconnectType,
})
}
// Final calculation with training dynamics
const dataTransferRate = baseTransferRate * batchFactor * gcOverhead * trainingPhaseFactor
// Get interconnect bandwidth based on current selection
let interconnectBW = 64 // PCIe 5.0 default
let interconnectType = 'PCIe 5.0'
if (typeof currentInterconnect !== 'undefined') {
switch (currentInterconnect) {
case 'pcie3':
interconnectBW = 16
interconnectType = 'PCIe 3.0'
break
case 'pcie4':
interconnectBW = 32
interconnectType = 'PCIe 4.0'
break
case 'pcie5':
default:
interconnectBW = 64
interconnectType = 'PCIe 5.0'
break
}
}
const bandwidthUtilization = Math.min(1.0, dataTransferRate / interconnectBW)
// Draw interconnect bandwidth meter at bottom (same style as multi-GPU)
const meterX = 20
const meterY = canvas.height - 100
const meterWidth = 200
const meterHeight = 20
// Meter background
ctx.fillStyle = 'rgba(0, 0, 0, 0.5)'
ctx.fillRect(meterX, meterY, meterWidth, meterHeight)
// Meter fill based on utilization
const fillWidth = meterWidth * bandwidthUtilization
const meterColor = bandwidthUtilization > 0.8 ? '#FF4444' : bandwidthUtilization > 0.5 ? '#FFA500' : '#4CAF50'
ctx.fillStyle = meterColor
ctx.fillRect(meterX, meterY, fillWidth, meterHeight)
// Meter border
ctx.strokeStyle = '#666'
ctx.lineWidth = 1
ctx.strokeRect(meterX, meterY, meterWidth, meterHeight)
// Meter label
ctx.fillStyle = '#FFF'
ctx.font = '12px monospace'
ctx.textAlign = 'left'
ctx.fillText(`${interconnectType} Bandwidth`, meterX, meterY - 5)
// Show actual achieved bandwidth (capped by interconnect limit)
const actualBandwidth = Math.min(dataTransferRate, interconnectBW)
ctx.font = '10px monospace'
// Show different text based on whether we're bottlenecked
if (bandwidthUtilization > 1.0) {
// Bottlenecked - show capped rate and what we need
ctx.fillStyle = '#FF8888'
ctx.fillText(
`100% SATURATED (${actualBandwidth.toFixed(1)} GB/s capped, need ${dataTransferRate.toFixed(1)} GB/s)`,
meterX,
meterY + meterHeight + 15,
)
} else {
// Not bottlenecked - show normal utilization
ctx.fillStyle = '#CCC'
ctx.fillText(
`${(bandwidthUtilization * 100).toFixed(1)}% (${actualBandwidth.toFixed(1)} GB/s)`,
meterX,
meterY + meterHeight + 15,
)
}
// Show bottleneck warning
if (bandwidthUtilization > 0.8) {
const pulse = Math.sin(Date.now() / 200) * 0.3 + 0.7
ctx.fillStyle = `rgba(255, 68, 68, ${pulse})`
ctx.font = 'bold 14px monospace'
ctx.textAlign = 'center'
ctx.fillText('⚠️ TRAINING BOTTLENECK ⚠️', canvas.width / 2, 30)
ctx.fillStyle = '#FF8888'
ctx.font = '11px monospace'
ctx.fillText(`${interconnectType} saturated - training will slow down!`, canvas.width / 2, 45)
}
// Update single GPU interconnect metrics
updateSingleGPUInterconnectMetrics(bandwidthUtilization, interconnectType, dataTransferRate, interconnectBW)
} catch (error) {
// Silent fail - don't break the visualization
console.log('Bandwidth meter error:', error)
}
}
// Draw training loss curve
function drawLossCurve() {
lossCtx.clearRect(0, 0, lossCanvas.width, lossCanvas.height)
if (lossHistory.length < 2) return
// Find min and max loss for auto-scaling
const minLoss = Math.min(...lossHistory)
const maxLoss = Math.max(...lossHistory)
const lossRange = maxLoss - minLoss || 1
// Draw axes
lossCtx.strokeStyle = 'rgba(255, 255, 255, 0.3)'
lossCtx.lineWidth = 1
lossCtx.beginPath()
lossCtx.moveTo(20, 10)
lossCtx.lineTo(20, 90)
lossCtx.lineTo(240, 90)
lossCtx.stroke()
// Draw Y-axis labels
lossCtx.fillStyle = 'rgba(255, 255, 255, 0.5)'
lossCtx.font = '9px monospace'
lossCtx.textAlign = 'right'
lossCtx.fillText(maxLoss.toFixed(2), 18, 15)
lossCtx.fillText(minLoss.toFixed(2), 18, 88)
// Draw loss curve