Repository navigation
Expand file tree
/
Copy pathtime_calculation.py
More file actions
2442 lines (2140 loc) · 91.6 KB
/
Copy pathtime_calculation.py
File metadata and controls
2442 lines (2140 loc) · 91.6 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
import math
import os
import sys
import config
import shutil
import itertools
from typing import Optional
# import numpy as np
from parallelism import Parallelism
from topology import Topology
from simulate import Graph
import util
from hw_component import Core, MemoryHierarchy, Network, DRAM
from astrasim_lib import run_cache_astrasim
from model import Model_LSTM, Model_GEMM, Model_LLM
from tile import TiledGEMM, formatBytes
algByte = False # algorithmic ops false
proj = False # consider projection layer, turn off for end-2-end validation, as baeline model does not have projection layer
validating_v100 = False
class NetworkModel:
def __init__(self, hw_config, precision, kernel_overhead, roofline_cb, astra_policy: Optional[str] = None):
self.hw_config = hw_config
self.precision = precision
self.O = kernel_overhead
self._roofline = roofline_cb
self._astra_policy = astra_policy or "analytical"
def _astra_collective(self, kind: str, participants: int, size_bytes: int) -> float:
part = int(participants)
if part <= 1 or size_bytes <= 0:
return 0.0
byte_count = int(math.ceil(size_bytes))
_, max_sec = run_cache_astrasim(
self.hw_config,
comm=kind,
npus_count=part,
size_bytes=byte_count,
astra_config_dir="./astra_cache",
cache_path="./astra_cache/cache.json",
)
return float(max_sec)
def collective(
self,
*,
kind: str,
size_bytes: float,
participants: int,
ib: float,
ll: float,
local_bytes: float = 0.0,
local_ops: float = 0.0,
debug_label: str = "",
) -> float:
if size_bytes <= 0:
return 0.0
# Pipeline and point-to-point operations now handled through unified path
if participants is None:
return 0.0
part = int(participants)
if part <= 1:
return 0.0
collective_ops = {"all_reduce", "reduce_scatter", "all_gather", "all_to_all"}
network_bytes = float(math.ceil(size_bytes))
local_bytes_int = int(math.ceil(local_bytes)) if local_bytes else 0
if self._astra_policy in {"hybrid", "full"}:
if kind in collective_ops or kind == "pipeline":
# Pipeline uses 2 NPUs for point-to-point, others use part
npus = 2 if kind == "pipeline" else part
network_time = self._astra_collective(kind, npus, network_bytes)
else:
raise ValueError(f"Unsupported collective operation: {kind}")
else:
network_time = self._analytical_collective(
kind=kind,
size_bytes=network_bytes,
participants=part,
ib=ib,
ll=ll,
debug_label=debug_label,
)
# TODO TODO TODO
# We want to ignore this in the future. Skipping it directly so that we match astrasim for now.
# FIX THIS (FIGURE OUT IF WE WANT TO SKIP OR NOT)
local_time = 0.0
overhead_kinds = {"all_reduce", "reduce_scatter", "all_gather"}
overhead = self.O if (network_bytes and kind in overhead_kinds) else 0.0
return network_time + local_time + overhead
def _analytical_collective(
self,
*,
kind: str,
size_bytes: float,
participants: int,
ib: float,
ll: float,
debug_label: str,
) -> float:
if kind == "all_reduce":
return self._analytical_all_reduce(size_bytes, participants, ib, ll, debug_label)
if kind == "reduce_scatter":
return self._analytical_reduce_scatter(size_bytes, participants, ib, ll, debug_label)
if kind == "all_gather":
return self._analytical_all_gather(size_bytes, participants, ib, ll, debug_label)
if kind == "all_to_all":
return self._analytical_all_to_all(size_bytes, participants, ib, ll, debug_label)
if kind == "pipeline":
return self._analytical_point_to_point(size_bytes, ib, ll)
# Default fallback for unknown patterns
raise ValueError(f"Unsupported collective operation: {kind}")
def _analytical_all_reduce(self, size_bytes, participants, ib, ll, label):
if ib == 0:
return float("inf")
per_rank = size_bytes / participants
mem_access = self._roofline(
0,
int(math.ceil(2 * size_bytes / participants)),
name=f"{label}-mem",
)
data_transfer = ((per_rank / ib) + mem_access + ll) * 2 * (participants - 1)
prep_comp = per_rank
prep_mem = int(math.ceil(3 * size_bytes / participants))
data_prep = (
self._roofline(prep_comp, prep_mem, name=f"{label}-prep") + self.O
) * (participants - 1)
return data_transfer + data_prep
def _analytical_reduce_scatter(self, size_bytes, participants, ib, ll, label):
if ib == 0:
return float("inf")
per_rank = size_bytes / participants
mem_access = self._roofline(
0,
int(math.ceil(2 * size_bytes / participants)),
name=f"{label}-mem",
)
data_transfer = ((per_rank / ib) + mem_access + ll) * (participants - 1)
prep_comp = per_rank
prep_mem = int(math.ceil(3 * size_bytes / participants))
data_prep = (
self._roofline(prep_comp, prep_mem, name=f"{label}-prep") + self.O
) * (participants - 1)
return data_transfer + data_prep
def _analytical_all_gather(self, size_bytes, participants, ib, ll, label):
if ib == 0:
return float("inf")
mem_access = self._roofline(
0,
int(math.ceil(2 * size_bytes / participants)),
name=f"{label}-mem",
)
data_transfer = ((size_bytes / ib) + mem_access + ll) * (participants - 1)
return data_transfer
def _analytical_all_to_all(self, size_bytes, participants, ib, ll, label):
if ib == 0:
return float("inf")
return ((size_bytes / participants) / ib + ll) * (participants - 1)
def _analytical_point_to_point(self, size_bytes, ib, ll):
if size_bytes <= 0:
return 0.0
if ib == 0:
return float("inf")
return size_bytes / ib + ll
class TimeCalculation:
def __init__(self, hw_config, model_config, mode, *, astra_policy_override: Optional[str] = None):
# Mode parameter
# Software Parameters
self.O = hw_config.sw_config.kernel_launch_overhead
self.precision = hw_config.sw_config.precision
self.precision_bytes = self.precision.activations
# TimeCalculation only uses activations precision for everything
# If we want proper backported LSTM support we need to fix this at *some* point.
self.h2d_bandwidth = getattr(hw_config.sw_config, "h2d_bandwidth", -1)
self.zero_stage = getattr(hw_config.sw_config, "dp_zero_stage", 0)
self.attached = True
# Hardware Parameters
self.hw_config = hw_config
self.core = Core(hw_config)
self.th = self.core.getThroughput()
self.FMA_dims = self.core.FMA_dims # (FMA_x, FMA_y)
self.dataflow = self.core.dataflow
self.memoryHierarchy = MemoryHierarchy(hw_config)
self.num_levels = self.memoryHierarchy.num_levels
self.memLayer = self.memoryHierarchy.memLayer
self.tileSpace = None
# TODO: move this to config file
self.H2Dbw = self.h2d_bandwidth
# System Parameters
self.num_wafer = hw_config.system_config.num_wafers
self.num_workers = hw_config.system_config.num_workers
level = 0
mem_config = hw_config.memory_hierarchy.mem_hr[level]
self.DRAM = DRAM(hw_config, mem_config, level)
self.memory_capacity = self.DRAM.size * self.num_workers# in bytes
# self.memory_capacity = hw_config.perimeter_breakdown.DRAM
self.network = Network(hw_config)
intra_throughput, inter_throughput = self.network.calcThroughput()
intra_latency, inter_latency = self.network.calcLatency()
inter_derate = hw_config.system_config.inter_derate
intra_derate = hw_config.system_config.intra_derate
par2cross = hw_config.system_config.par2cross
derated_inter_throughput = -1
derated_intra_throughput = -1
# inter-wafer communications will pass through intra links too
if self.num_wafer > 1 and self.num_workers > 1:
if intra_derate != 0:
derated_inter_throughput = min(
intra_throughput / intra_derate, inter_throughput / inter_derate
)
# print(f'intra_throughput / intra_derate: {intra_throughput / intra_derate}, inter_throughput / inter_derate: {inter_throughput / inter_derate}')
else:
derated_inter_throughput = inter_throughput / inter_derate
# print(f'inter_throughput / inter_derate: {inter_throughput / inter_derate}')
else:
derated_inter_throughput = 0
if self.num_workers > 1 and intra_derate != 0:
derated_intra_throughput = intra_throughput / intra_derate
else:
derated_intra_throughput = 0
self.IBK1, self.LLK1 = (
(derated_inter_throughput, inter_latency)
if par2cross["kp1"]
else (derated_intra_throughput, intra_latency)
)
self.IBK2, self.LLK2 = (
(derated_inter_throughput, inter_latency)
if par2cross["kp2"]
else (derated_intra_throughput, intra_latency)
)
self.IBD, self.LLD = ( #interconnect bandwidth and latency for data parallelism
(derated_inter_throughput, inter_latency)
if par2cross["dp"]
else (derated_intra_throughput, intra_latency)
)
self.IBL, self.LLL = (
(derated_inter_throughput, inter_latency)
if par2cross["lp"]
else (derated_intra_throughput, intra_latency)
)
self.IBTP, self.LLTP = (
(derated_inter_throughput, inter_latency)
if par2cross["tp"]
else (derated_intra_throughput, intra_latency)
)
# Scheduling Parameters
par = Parallelism(hw_config)
par.findParallelStrategy()
self.mode = mode
self.autoPar = par.autoPar
self.lp = par.lp
self.mb = par.mb
self.kp_hidden_dim1 = par.kp_hidden_dim1
self.kp_softmax_dim1 = par.kp_softmax_dim1
self.kp_embedding_dim1 = par.kp_embedding_dim1
self.kp_projection_dim1 = par.kp_projection_dim1
self.kp_hidden_dim2 = par.kp_hidden_dim2
self.kp_softmax_dim2 = par.kp_softmax_dim2
self.kp_embedding_dim2 = par.kp_embedding_dim2
self.kp_projection_dim2 = par.kp_projection_dim2
self.dp = par.dp
self.kp_hidden_type = par.kp_hidden_type # 1: CR, 2: RC
self.kp_softmax_type = par.kp_softmax_type # 1: CR, 2: RC
self.kp_embedding_type = par.kp_embedding_type # 1: CR, 2: RC
self.kp_projection_type = par.kp_projection_type # 1: CR, 2: RC
self.t = par.t if self.mode != "LLM" else None
tp_value = par.tp if par.tp not in (None, 0) else 1
try:
self.tp = int(tp_value)
except (TypeError, ValueError) as exc:
raise ValueError("scheduling_param.tp must be an integer") from exc
if self.tp < 1:
raise ValueError("scheduling_param.tp must be >= 1")
cp_value = par.cp if par.cp not in (None, 0) else 1
try:
self.cp = int(cp_value)
except (TypeError, ValueError) as exc:
raise ValueError("scheduling_param.cp must be an integer") from exc
if self.cp < 1:
raise ValueError("scheduling_param.cp must be >= 1")
self.tp_sp = par.tp_sp
if self.mode != "LLM":
self.kp1 = par.kp1 # first parallelism parameter
self.kp2 = par.kp2 # second parallelism parameter
self.updateParParams(self.t, self.kp1, self.kp2)
else:
self.kp1 = None
self.kp2 = None
run_type = model_config.model_config.run_type
if run_type == "inference":
if self.cp > 1:
raise ValueError(
"Context parallelism (cp) is not supported for LLM inference. "
"Please set scheduling_param.cp to 1 for inference runs."
)
if self.mb > 1:
print(f"[WARNING]: LLM inference configured with mb={self.mb} (>1). \n Pipeline micro-batching is ill-defined for autoregressive decode and should be avoided.")
if self.mode == "LLM":
expected_workers = self.tp * self.cp * self.dp * self.lp
label = f"tp({self.tp}) * cp({self.cp}) * dp({self.dp}) * lp({self.lp})"
else:
kp1 = int(self.kp1) if self.kp1 else 1
kp2 = int(self.kp2) if self.kp2 else 1
expected_workers = self.dp * self.lp * kp1 * kp2
label = f"dp({self.dp}) * lp({self.lp}) * kp1({kp1}) * kp2({kp2})"
if expected_workers != self.num_workers:
raise ValueError(
f"Parallelism mismatch: {label} = {expected_workers}, "
f"but system_hierarchy reports num_workers={self.num_workers}."
)
# Statistics Param
self.tot_flop = 0
self.tot_mem = 0
self.tot_time = 0
self.debug = False
default_policy = 'analytical'
eb = getattr(hw_config, "execution_backend", None)
if eb and getattr(eb, "model", "analytical") == "astra":
default_policy = 'hybrid'
self._astra_policy = astra_policy_override or default_policy
self.network_model = NetworkModel(
hw_config,
self.precision_bytes,
self.O,
self.roofline,
astra_policy=self._astra_policy,
)
# Dynamically select and instantiate the model class
model_class = self.get_model_class(mode)
self.model = model_class(model_config) # Instantiate the model class
# Model Parameters
# self.model = self.get_model_class(mode)
if mode == "LSTM":
self.B = self.model.batch_size
self.V = self.model.vocab_size
self.L = self.model.num_layers
self.D = self.model.hidden_dim
self.projection = self.model.projection
self.S = self.model.seq_len
self.G = self.model.num_gates
self.NL = self.model.num_non_linear
self.A = self.model.num_add
self.P = self.model.num_pointwise
# Define miniBatch size
self.miniB = math.ceil(self.B / self.dp)
if mode == "GEMM":
self.M = self.model.M
self.K = self.model.K
self.N = self.model.N
if mode == "LLM":
self.batch_size = self.model.batch_size
self.vocab_size = self.model.vocab_size
self.num_layers = self.model.num_layers
self.hidden_dim = self.model.hidden_dim
self.seq_len = self.model.seq_len
self.num_heads = self.model.num_heads
self.intermediate_size = self.model.intermediate_size
self.n_tokens = self.model.n_tokens
if self.batch_size % self.dp != 0:
raise ValueError("Batch size must be divisible by data parallelism degree")
self.miniB = math.ceil(self.batch_size / self.dp) # mini-batch size for each data parallel node
if self.miniB % self.mb != 0:
print(f"miniB: {self.miniB}, mb: {self.mb}")
raise ValueError("Batch size must be divisible by micro-batch size")
self.microB = math.ceil(self.miniB / self.mb) if self.lp > 1 else self.miniB # micro-batch size for each pipeline stage
self.attention_type = self.model.attention_type
self.flash_attention = getattr(self.model, 'use_flashattention', False)
self.kv_heads = self.model.kv_heads if hasattr(self.model, 'kv_heads') else self.num_heads
self.attention_tile_size = getattr(self.model, 'attention_tile_size', None)
raw_num_experts = getattr(self.model, "moe_num_experts", 1)
raw_top_k = getattr(self.model, "moe_top_k", 1)
self.moe_num_experts = max(1, int(raw_num_experts))
self.moe_top_k = max(1, int(raw_top_k))
if self.moe_top_k > self.moe_num_experts:
raise ValueError("model_param.top_k cannot exceed model_param.num_experts")
self.use_moe = self.moe_num_experts > 1
def get_model_class(self, model_type):
"""Return the appropriate model class based on the model type."""
model_classes = {
"LSTM": Model_LSTM,
"GEMM": Model_GEMM,
"LLM": Model_LLM,
# Add other model types here as needed
}
if model_type not in model_classes:
raise ValueError(f"Unsupported model type: {model_type}")
return model_classes[model_type]
def updateParParams(
self,
t,
kp1,
kp2,
):
self.kp_hidden_dim1 = kp1 if kp1 != None else self.kp_hidden_dim1
# self.kp_hidden_dim1 = kp1 if kp1 != None else self.kp_hidden_dim1
self.kp_hidden_dim2 = kp2 if kp2 != None else self.kp_hidden_dim2
self.kp_hidden_type = (
2 if t == "RC" else (1 if t == "CR" else self.kp_hidden_type)
)
# TODO: decide if we want kp1, kp2 to control other layers besides hidden layer
self.kp_softmax_dim1 = kp1 if kp1 != None else self.kp_softmax_dim1
self.kp_softmax_dim2 = kp2 if kp2 != None else self.kp_softmax_dim2
self.kp_softmax_type = (
2 if t == "RC" else (1 if t == "CR" else self.kp_softmax_type)
)
self.kp_embedding_dim1 = kp1 if kp1 != None else self.kp_embedding_dim1
self.kp_embedding_dim2 = kp2 if kp2 != None else self.kp_embedding_dim2
self.kp_embedding_type = (
2 if t == "RC" else (1 if t == "CR" else self.kp_embedding_type)
)
self.kp_projection_dim1 = kp1 if kp1 != None else self.kp_projection_dim1
self.kp_projection_dim2 = kp2 if kp2 != None else self.kp_projection_dim2
self.kp_projection_type = (
2 if t == "RC" else (1 if t == "CR" else self.kp_projection_type)
)
# TODO: need to change all equations to be a function of m,n and k
# self.D = n//4
# print("kp1: {}".format(self.kp_hidden_dim1))
# print("kp2: {}".format(self.kp_hidden_dim2))
# TODO: It is a hacky way of capturing assymetry across links within V100
# move this to network topology and distinguish between inter and intra network
if validating_v100:
self.IBK1 = util.scale_down(self.IBK1, self.kp_hidden_dim1, "kp1")
self.IBK2 = util.scale_down(self.IBK2, self.kp_hidden_dim2, "kp2")
self.IBD = util.scale_down(self.IBD, self.dp, "dp")
self.IBL = util.scale_down(self.IBL, self.lp, "lp")
if getattr(self, "tp", None):
self.IBTP = util.scale_down(self.IBTP, self.tp, "tp")
# Keep tensor-parallel interconnect parameters aligned with configured tensor-parallel links.
def updateParams(
self,
debug,
m,
n,
k,
t,
kp1,
kp2,
dp,
lp,
batch_size,
hidden_dim,
seq_len,
vocab_size,
num_layer,
):
self.B = batch_size
self.D = hidden_dim
self.S = seq_len
self.V = vocab_size
self.L = num_layer
# Define miniBatch size
self.dp = dp if dp != None else self.dp
self.miniB = math.ceil(self.B / self.dp)
self.debug = debug
self.lp = lp if lp != None else self.lp
self.kp_hidden_dim1 = kp1 if kp1 != None else self.kp_hidden_dim1
# self.kp_hidden_dim1 = kp1 if kp1 != None else self.kp_hidden_dim1
self.kp_hidden_dim2 = kp2 if kp2 != None else self.kp_hidden_dim2
self.kp_hidden_type = (
2 if t == "RC" else (1 if t == "CR" else self.kp_hidden_type)
)
# TODO: decide if we want kp1, kp2 to control other layers besides hidden layer
self.kp_softmax_dim1 = kp1 if kp1 != None else self.kp_softmax_dim1
self.kp_softmax_dim2 = kp2 if kp2 != None else self.kp_softmax_dim2
self.kp_softmax_type = (
2 if t == "RC" else (1 if t == "CR" else self.kp_softmax_type)
)
self.kp_embedding_dim1 = kp1 if kp1 != None else self.kp_embedding_dim1
self.kp_embedding_dim2 = kp2 if kp2 != None else self.kp_embedding_dim2
self.kp_embedding_type = (
2 if t == "RC" else (1 if t == "CR" else self.kp_embedding_type)
)
self.kp_projection_dim1 = kp1 if kp1 != None else self.kp_projection_dim1
self.kp_projection_dim2 = kp2 if kp2 != None else self.kp_projection_dim2
self.kp_projection_type = (
2 if t == "RC" else (1 if t == "CR" else self.kp_projection_type)
)
# TODO: need to change all equations to be a function of m,n and k
# self.D = n//4
# print("kp1: {}".format(self.kp_hidden_dim1))
# print("kp2: {}".format(self.kp_hidden_dim2))
# TODO: It is a hacky way of capturing assymetry across links within V100
# move this to network topology and distinguish between inter and intra network
if validating_v100:
self.IBK1 = util.scale_down(self.IBK1, self.kp_hidden_dim1, "kp1")
self.IBK2 = util.scale_down(self.IBK2, self.kp_hidden_dim2, "kp2")
self.IBD = util.scale_down(self.IBD, self.dp, "dp")
self.IBL = util.scale_down(self.IBL, self.lp, "lp")
# Number of parameters
def tot_param(self):
embedding = self.V * self.D
hidden = (2 * self.D + 1) * (self.G * self.D) * self.L
projection = self.D * self.projection
softmax = ((self.projection if proj else self.D) + 1) * self.V
tot_param = embedding + hidden + projection + softmax
return tot_param
def printSysConfig(self, exp_hw_config, exp_model_config, output_file):
kiloByte = 1024
megaByte = kiloByte * 1024
gigaByte = megaByte * 1024
teraByte = gigaByte * 1024
with open(output_file, "w") as f:
f.write("==========================\n")
f.write("Hardware Configuration\n")
f.write("==========================\n")
f.write(
"Throughput: {:.5f} Tflops\n".format(
self.core.operating_throughput / 1e12
)
)
for i in range(self.num_levels - 1, -1, -1):
mem_bw = self.memLayer[i].dynamic_throughput
mem_size = self.memLayer[i].size
if mem_bw < 1e3 * gigaByte:
f.write(
"L{:} Bandwidth: {:.1f} GB/s\n".format(i, mem_bw / (gigaByte))
)
else:
f.write(
"L{:} Bandwidth: {:.1f} TB/s\n".format(i, mem_bw / (teraByte))
)
if mem_size < 1e3 * megaByte:
f.write("L{:} Size: {:.10f} MB\n".format(i, mem_size / (megaByte)))
elif mem_size < 1e3 * gigaByte:
f.write("L{:} Size: {:.1f} GB\n".format(i, mem_size / (gigaByte)))
else:
f.write("L{:} Size: {:.1f} TB\n".format(i, mem_size / (teraByte)))
f.write(
"Intra-node Bandwidth: {:.1f} GB/s\n".format(
self.network.intra_network.throughput / (gigaByte)
)
)
f.write(
"Inter-node Bandwidth: {:.1f} GB/s\n".format(
self.network.inter_network.throughput / (gigaByte)
)
)
M = self.memLayer[self.num_levels - 1].size
(
tot_mem,
embedding_mem,
hidden_mem,
softmax_mem,
projection_mem,
wt_mem,
act_mem,
point_mem,
) = util.getTotMemReq(
exp_hw_config,
exp_model_config,
batch_size=self.B,
hidden_dim=self.D,
vocab_size=self.V,
seq_len=self.S,
num_layer=self.L,
dp=self.dp,
lp=self.lp,
kp1=self.kp_hidden_dim1,
kp2=self.kp_hidden_dim2,
kp_type=self.kp_hidden_type,
)
f.write("\n\n===========================================\n")
f.write("Memory Requirement Breakdown per Data Shard\n")
f.write("===========================================\n")
f.write(
"Total Memory: {:.1f} GB\n"
"Embedding Memory: {:.1f} GB\n"
"Hidden Memory: {:.1f} GB\n"
"Softmax Memory: {:.1f} GB\n"
"Projection Memory: {:.1f} GB\n".format(
tot_mem / gigaByte,
embedding_mem / gigaByte,
hidden_mem / gigaByte,
softmax_mem / gigaByte,
projection_mem / gigaByte,
)
)
f.write(
"\nTotal Memory: {:.1f} GB\n"
"Weight Memory: {:.1f} GB\n"
"Activation Memory: {:.1f} GB\n"
"Pointwise Memory: {:.1f} GB\n".format(
tot_mem / gigaByte,
wt_mem / gigaByte,
act_mem / gigaByte,
point_mem / gigaByte,
)
)
f.write(
"\nMemory Overflow Rate (Total Memory Required per Data Shard / Memory capacity per node): {:.1f}\n".format(
float("inf") if M == 0 else tot_mem / M
)
)
(
tot_mem,
embedding_mem,
hidden_mem,
softmax_mem,
projection_mem,
wt_mem,
act_mem,
point_mem,
) = util.getMemUsagePerCore(
exp_hw_config,
exp_model_config,
batch_size=self.B,
hidden_dim=self.D,
vocab_size=self.V,
seq_len=self.S,
num_layer=self.L,
dp=self.dp,
lp=self.lp,
kp1=self.kp_hidden_dim1,
kp2=self.kp_hidden_dim2,
kp_type=self.kp_hidden_type,
)
f.write("\n\n===========================================================\n")
f.write("Memory Requirement Breakdown per Data Shard Per Model Shard\n")
f.write("===========================================================\n")
f.write(
"Total Memory: {:.1f} GB\n"
"Embedding Memory: {:.1f} GB\n"
"Hidden Memory: {:.1f} GB\n"
"Softmax Memory: {:.1f} GB\n"
"Projection Memory: {:.1f} GB".format(
tot_mem / gigaByte,
embedding_mem / gigaByte,
hidden_mem / gigaByte,
softmax_mem / gigaByte,
projection_mem / gigaByte,
)
)
f.write(
"\nMemory Overflow Rate (Total Memory Required per Data Shard Per Model Shard/ Memory capacity per node): {:.5f}\n".format(
float("inf") if M == 0 else tot_mem / M
)
)
f.write(
"\nTotal Memory: {:.1f} GB\n"
"Weight Memory: {:.1f} GB\n"
"Activation Memory: {:.1f} GB\n"
"Pointwise Memory: {:.1f} GB\n".format(
tot_mem / gigaByte,
wt_mem / gigaByte,
act_mem / gigaByte,
point_mem / gigaByte,
)
)
f.write("\n\n====================\n")
f.write("Parallelism Strategy\n")
f.write("====================\n")
f.write(
"dp: {}, lp: {}, kp_hidden_dim1: {}, kp_hidden_dim2: {},"
"kp_softmax_dim1: {}, kp_softmax_dim2: {}, kp_embedding1: {}, kp_embedding2: {},"
"kp_projection_dim1: {}, kp_proejction_dim2: {}\n".format(
self.dp,
self.lp,
self.kp_hidden_dim1,
self.kp_hidden_dim2,
self.kp_softmax_dim1,
self.kp_softmax_dim2,
self.kp_embedding_dim1,
self.kp_embedding_dim2,
self.kp_projection_dim1,
self.kp_projection_dim2,
)
)
f.write(
"\n\n==============================================================================\n"
)
f.write("Hardware Component Stats\n")
f.write(
"==============================================================================\n"
)
self.core.printStats(f)
for i in range(0, self.num_levels):
self.memLayer[i].printStats(f)
self.network.printStats(f)
def roofline(self, flop, mem_access_, name="", info=False, mem_level=None, flashattn_enable=False):
# print("Roofline: entered {}".format(name))
# Parse mem_access_ into consistent format
if isinstance(mem_access_, int):
mem_access = [mem_access_]
elif isinstance(mem_access_, float):
mem_access = [int(mem_access_)]
elif isinstance(mem_access_, list):
mem_access = mem_access_
else:
print(mem_access_)
print("mem_access_ should be integer or list, wrong input", flush=True)
sys.exit(0)
# Determine which levels to compute
if mem_level is not None:
# Single level mode
levels_to_compute = [(mem_level, mem_access[0])]
else:
# Multi-level mode (original behavior)
num_level = len(mem_access)
try:
if not flashattn_enable:
assert mem_access[num_level - 1] > 0, "last_level_mem = 0"
except Exception as e:
print(
"{}: Number of accesses to the last level of memory hierarchy cannot be zero:\n {}".format(
name, e
),
flush=True,
)
sys.exit(0)
levels_to_compute = [(i, mem_access[i]) for i in range(num_level)]
# Compute roofline time for each level
times = []
for level_idx, num_mem in levels_to_compute:
mem_bw = self.memLayer[level_idx].getThroughput()
mem_latency = self.memLayer[level_idx].getLatency()
inflection_point = float("inf") if mem_bw == 0 else self.th / mem_bw
# print(f"Level {level_idx}: mem_bw={mem_bw}, mem_latency={mem_latency}, inflection_point={inflection_point}", flush=True)
comp_int = float("inf") if num_mem == 0 else flop / num_mem
if comp_int < inflection_point: # mem-bound
level_time = (float("inf") if (mem_bw == 0 or num_mem == 0) else (num_mem / mem_bw)) + mem_latency
else: # compute-bound
level_time = float("inf") if (self.th == 0) else (flop / self.th)
times.append(level_time)
max_time = max(times)
# print("Roofline: exited {}".format(name))
return max_time
def getGEMMTime(self, dim1, dim2, dim3, name,
flashattn_enable=False, disable_overhead=False, read_bytes_l2=0, write_bytes_l2=0, original=False):
# Streaming best selection to avoid building large dicts
best_time = float("inf")
best_choice = None # type: Optional[tuple]
best_mem_access = None # type: Optional[tuple]
best_gemm = None # type: Optional[TiledGEMM]
best_metric = float("inf")
# Iterate directly over candidates from tile module; no string orders
for gemm in TiledGEMM.enumerate_candidates(self.core, self.memLayer, dim1, dim2, dim3, self.precision_bytes, original=False):
if self.debug:
print("===============================================================")
print(f"inner_code: {gemm._inner_code}")
print("===============================================================")
GEMM_flop = gemm.GEMM_flop
mem_access = gemm.mem_accesses
if flashattn_enable:
mem_access = list(mem_access)
mem_access[3] = 0 # no HBM accesses
mem_access[2] = read_bytes_l2 + write_bytes_l2 # explicitly set L2 accesses
mem_access = tuple(mem_access)
# Adjust shared accesses per effective SMs
mem_access_per_sm = list(mem_access)
reuse_M = (dim1 + gemm.l2_M - 1) // gemm.l2_M
reuse_K = (dim2 + gemm.l2_K - 1) // gemm.l2_K
reuse_N = (dim3 + gemm.l2_N - 1) // gemm.l2_N
eff_sm = min(self.core.num_bundle, reuse_M * reuse_K * reuse_N)
if eff_sm > 0:
mem_access_per_sm[1] = mem_access_per_sm[1] / eff_sm
GEMM_time = self.roofline(GEMM_flop, mem_access_per_sm, name, flashattn_enable=flashattn_enable)
if flashattn_enable or disable_overhead:
pass
else:
GEMM_time = GEMM_time + self.O
tile_dims = (
(gemm.l0_M, gemm.l0_K, gemm.l0_N),
(gemm.l1_M, gemm.l1_K, gemm.l1_N),
(gemm.l2_M, gemm.l2_K, gemm.l2_N),
)
key = (gemm._inner_code, tile_dims)
# Tie-breaker metric identical to previous selection: hypot(dram, l2)
metric = math.hypot(mem_access[3], mem_access[2])
if (GEMM_time < best_time) or (GEMM_time == best_time and metric < best_metric):
best_time = GEMM_time
best_choice = key
best_mem_access = mem_access
best_gemm = gemm
best_metric = metric
# best_choice, best_mem_access must be set if there was at least one candidate
mem_access = best_mem_access # type: ignore
if self.debug:
print(repr(best_gemm))
print(
f"{name}: Best Time: {best_time * 1e3:,} ms, Best Inner: {best_choice[0]}, Best Tile: {best_choice[1]}\n"
)
# Inner code mapping for loop order (no strings):
# 0 -> inner 'm' (weight stationary)
# 1 -> inner 'k' (output stationary)
# 2 -> inner 'n' (activation stationary)
best_inner_code = best_choice[0] # type: ignore[index]
best_tile_dims = best_choice[1] # type: ignore[index]
return best_time, best_inner_code, best_tile_dims, mem_access
def generateTileSpace(self, dim1=None, dim2=None, dim3=None, original=False):
tile_space = []
tiles = [None] * self.num_levels
for level in range(0, self.num_levels - 1):
memory = self.memLayer[level]
# tiles[level] = self.getTileDims(memory)
if not original and level == 2:
tiles[level] = memory.getGEMMBasedTileDims(dim1, dim2, dim3)
else:
tiles[level] = memory.getTileDims()
if self.num_levels == 1:
tile_space = []
elif self.num_levels == 2:
tile_space = tiles[0]
elif self.num_levels == 3:
tile_space = [(x, y) for x in tiles[0] for y in tiles[1]]
elif self.num_levels == 4:
tile_space = []
for x in tiles[2]:
t1, t2, t3 = x
if not original:
tiles[1] = self.memLayer[1].getGEMMBasedTileDims(t1, t2, t3)
tile_strategy = [
(x, y, z) for y in tiles[1] for z in tiles[2]
]
tile_space.extend(tile_strategy)
else:
raise NotImplementedError()
return tile_space
def getTileSize(self, lid):
memory = self.memLayer[lid]
memory.calcTileDim()
tile_dim = memory.getTileDim()
return tile_dim, tile_dim, tile_dim
# Count the number of accesses from level-1 to level
# input matrix A(dim1, dim2) and B(dim2, dim3)
# output matrix C(dim1, dim3)
def getNumAccesses(self, level, dim1, dim2, dim3, tile_dim, num_repeat, name, r):
# tile1,tile2,tile3 = self.getTileSize(level-1)
# print("dim1= ", dim1, "dim2= ", dim2, "dim3 = ", dim3)
tile1, tile2, tile3 = tile_dim
# print("BEFORE: level = ", level, "|tile1= ", tile1, "tile2= ", tile2, "tile3 = ", tile3) ###############
orig_size = tile1 * tile2 + tile1 * tile3 + tile2 * tile3
short_tile_cond = [0, 0, 0]
if tile1 > dim1:
tile1 = dim1
short_tile_cond[0] = 1
if tile2 > dim2:
tile2 = dim2
short_tile_cond[1] = 1
if tile3 > dim3:
tile3 = dim3
short_tile_cond[2] = 1
# print("AFTER: level= ", level ,"|tile1= ", tile1, "tile2= ", tile2, "tile3 = ", tile3) ###############
if short_tile_cond[2] == 0 and (short_tile_cond[0] | short_tile_cond[1]) == 1:
if level <= 1:
tile3 = math.floor((orig_size - tile1 * tile2) / (tile1 + tile2))
else:
# store bypasses cache, directly goes to memory
tile3 = math.floor((orig_size - tile1 * tile2) / tile2)
if tile3 > dim3:
tile3 = dim3
# Uncomment if tile3 needs to be pow of 2
# tile3 = int(math.pow(2, math.floor(math.log2(tile3))))
elif short_tile_cond[0] == 0 and (short_tile_cond[1] | short_tile_cond[2]) == 1:
if level <= 1:
tile1 = math.floor((orig_size - tile3 * tile2) / (tile3 + tile2))
else:
# store bypasses cache, directly goes to memory
tile1 = math.floor((orig_size - tile3 * tile2) / tile2)
if tile1 > dim1:
tile1 = dim1
elif short_tile_cond[1] == 0 and (short_tile_cond[0] & short_tile_cond[2]) == 1:
if level <= 1:
tile2 = math.floor((orig_size - tile3 * tile1) / (tile3 + tile1))
else:
tile2 = math.floor((orig_size) / (tile1 + tile3))
if tile2 > dim2:
tile2 = dim2
# print("FINAL: level= ", level ,"|tile1= ", tile1, "tile2= ", tile2, "tile3 = ", tile3) ###############
reload_A = 1
reload_B = 1
reload_C = 1
if tile1 > 0 and tile2 > 0 and tile3 > 0:
reload_A = math.ceil(dim3 / tile3)
reload_B = math.ceil(dim1 / tile1)