-
Notifications
You must be signed in to change notification settings - Fork 118
/
Copy pathKernelWriter.py
5500 lines (4899 loc) · 271 KB
/
KernelWriter.py
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
################################################################################
#
# Copyright (C) 2022-2025 Advanced Micro Devices, Inc. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
################################################################################
from rocisa import rocIsa, countInstruction, countGlobalRead, \
countLocalRead, countLocalWrite, countDSStoreB256
from rocisa.code import Module, TextBlock, StructuredModule, KernelBody
from rocisa.container import RegisterContainer
from rocisa.label import LabelManager
from rocisa.asmpass import rocIsaPass, rocIsaPassOption
from rocisa.instruction import SLongBranchPositive
from .TensileInstructions import replaceHolder, \
Dump, RegisterPool, Assert, \
SBranch, SCBranchSCC0, SCBranchSCC1
from .TensileInstructions.Instructions import *
from .KernelWriterModules import *
from .TensilePass import TensilePass, TensilePassOptions, TensilePassGetCycles
from .Component import Component, LraTileProperties
from .Components.Signature import UserArgumentsInfo
from .SolutionStructs import Solution, isPackedIndex
from .AsmMemoryInstruction import MemoryInstruction
from .Activation import ActivationModule
from .Common import printWarning, roundUp, print2, DebugConfig, DataDirection, \
INDEX_CHARS, IsaVersion
from Tensile.SolutionStructs.Naming import getKernelNameMin
from Tensile.Toolchain.Component import Assembler
import abc
import os
import shutil
import sys
import collections
from copy import deepcopy
from dataclasses import dataclass, field
from typing import Dict, List, NamedTuple, Optional,Tuple, Type
from math import ceil
# Make const values immutable
@dataclass(frozen=True)
class ConstValues():
initLdsValue:int = 0xFFFFFFFF # Value to use for LDS Init, if enabled
initSgprValue:int = 0x0 # Value to use for Sgpr Init, if enabled
initVgprValue:int = 0xFFFFFFFF # Value to use for Vgpr Init, if enabled
maxOccupancy: int = 10
ldsOOB: int = 0xF00000
@dataclass
class MatrixInfo:
numVgprValu: int = -1
numVgprValuPack: int = -1
startVgprValu: int = -1
startVgprValuPack: int = -1
startVgprValuPackTemp: int = -1
numSgprStrides: int = -1
@dataclass
class ABMatrixInfo(MatrixInfo):
numVgprValuPerBlock: int = -1
numVgprG2L: int = -1
numVgprG2LAllocated: int = -1
startVgprG2L: Optional[int] = None
numVgprLocalReadAddr:int = -1
startVgprLocalReadAddr: int = -1
numVgprLocalWriteAddr: int = -1
startVgprLocalWriteAddr: int = -1
numVgprGlobalReadOffsets: int = -1
startVgprGlobalReadOffset: int = -1
numSgprGlobalReadIncs: int = -1
# States
@dataclass
class StateValues:
version: Tuple[int, int, int]
kernel: dict
kernelName: str
language: str = "ASM"
asmCaps: dict = field(init=False)
archCaps: dict = field(init=False)
regCaps: dict = field(init=False)
laneSGPRCount: int = field(init=False)
# These values may differ between platforms, so put them here.
# registers per global address
rpga = 2 # 64-bit
# registers per local address
rpla = 1 # 32-bit
# registers per global 32-bit offset (some intructions only support 32-bit offset)
rpgo = 1 # 32-bit
# registers per element
bpr: int = 4 # all registers are 32bit
# default setup
# AB=DataType / Cexternal=DestDataType / Cinternal=Accumulation (MAC or MFMA)
bpeAB: int = field(init=False)
bpeE: int = field(init=False)
# Cexternal = the "current" kernel output type,
# - default: the "current" kernel is a non-GSU-kernel,
# Cexternal (= DestDataType) and is the final gemm result
#
# - For GSU: the "current" kernel is a GSU-kernel,
# this kernel returns a temp buffer with same type as Cinternal.
# Later, another kernel will accumulate this buffer
# and convert the final result to Cexternal (= DestDataType) as the gemm result
bpeCexternalGSU1: int = field(init=False)
bpeCexternal: int = field(init=False)
# already covers: dgemm, cgemm, zgemm, sgemm
# : hgemm + !HPA ([H/H/H] compute = internal = f16)
# : hgemm + HPA ([H/H/S] or [H/S/S] compute = internal = f32)
# : bfgemm + HPA ([B/B/S] or [H/S/S] compute = internal = f32)
# : int8x4-gemm (internal = i32)
bpeCinternal: int = field(init=False)
# KernelWriter
inTailLoop: bool = False
overflowedResources: int = 0
## Schedule
scheduleGlobalRead: int = 0
scheduleLocalWrite: int = 0
scheduleIterAlg: int = 0
## ShadowInit
doShadowInit: int = 0
## Loop
actualSummationLoops: int = 0
otherSummationLoops: int = 0
otherSummations: int = 0
indexChars: List[int] = field(init=False)
unrollIdx: int = -1
unrollChar: str = ""
tileChar0: str = ""
tileChar1: str = ""
numItersPLR: int = 0
numVgprBuffer: int = 0
numVgprBufferPackA: int = 0
numVgprBufferPackB: int = 0
numVgprBufferPackMetadata: int = 0
lrvwTileA: int = 0
lrvwTileB: int = 0
lrvwTileMetadata: int = 0 # For Sparse Metadat
lrvwUnrollA: int = 0
lrvwUnrollB: int = 0
lrvwUnrollMetadata: int = 0 # For Sparse Metadat
numMfmaPerIter: int = 0
numReadsIterCoalescedA: int = 0
numReadsIterCoalescedB: int = 0
numReadsIterCoalescedMetadata: int = 0
numIterPerCoalescedReadA: int = 0
numIterPerCoalescedReadB: int = 0
numIterPerCoalescedReadMetadata: int = 0
numReadsPerUnrollA: int = 0
numReadsPerUnrollB: int = 0
numReadsPerUnrollMetadata: int = 0
# KernelWriterAssembly
mixinst: Optional[Type[Instruction]] = None
globalReadIncsUseVgpr: bool = False
groOffsetInMacroTile: int = 0
use64bShadowLimit: bool = True
preventVgprOverflowDuringNewTile: int = -1
interleaveStoreVmcnt: bool = False
srdShiftLeft:dict = field(init=False)
checkGRO: bool = False
combineLocalAddresses: bool = False # Debug
unifiedVgprRegs: bool = False
useAtomicAdd: bool = False
serializedStore: bool = False
a: ABMatrixInfo = field(default_factory=ABMatrixInfo)
b: ABMatrixInfo = field(default_factory=ABMatrixInfo)
c: MatrixInfo = field(default_factory=MatrixInfo)
d: MatrixInfo = field(default_factory=MatrixInfo)
e: MatrixInfo = field(default_factory=MatrixInfo)
bias: MatrixInfo = field(default_factory=MatrixInfo)
m: ABMatrixInfo = field(default_factory=ABMatrixInfo) # For Sparse Metadata
totalAgprs: int = 0
maxLimitAgprs: int = 0
totalMixedAgprs: int = 0
totalVgprs: int = 0
totalSgprs: int = 0
lastValuAB: int = 0
lastVgprForReads: int = 0
startVgpr: int = 0
startVgprAddressDbg: int = -1
startVgprAlphaTmp: int = -1
startVgprSerial: int = -1
startVgprCvt: int = -1
numSgprSizesSum: int = 0
numSgprSizesFree: int = 0
numActivationTypeArgSize: int = 0
numActivationArgSize: int = 0
numactivationArgTotalSize: int = 0
numSgprAddressScaleA: int = 0
numSgprAddressScaleB: int = 0
numSgprAddressScaleC: int = 0
numSgprAddressScaleD: int = 0
numSgprAddressDbg: int = 0
firstInitSgpr: int = -1
nonPostLoopSgpr: List[str] = field(init=False)
userArgsInfo: UserArgumentsInfo = field(default_factory=UserArgumentsInfo)
numSgprToLoad: int = 0 # For kernel args
preloadGuard: List[int] = field(init=False) # For preload kernel args guard
numSgprPreload: int = 0 # For kernel args
numSgprAlpha: int = 0 # For user arguments
numSgprBeta: int = 0 # For user arguments
numStoreSgprNames: List[str] = field(init=False) # For post-loop kernel args
numStoreSgprNameSizes: List[int] = field(init=False) # For post-loop kernel args
numStoreSgprToLoad: int = 0 # For post-loop kernel args
numStoreSgprNames2: List[str] = field(init=False) # For post-loop kernel args
numStoreSgprNameSizes2: List[int] = field(init=False) # For post-loop kernel args
numStoreSgprToLoad2: int = 0 # For post-loop kernel args
numStoreSgprInst: int = 0 # For pose-loop kernel args
numStoreSgprInstExt: int = 0 # For pose-loop kernel args
numSgprAddressBias: int = 0
numSgprAddressGSUSync: int = 0
numSgprStreamK: int = 0
BiasType: int = 0
BiasStride: int = 0
FactorDim: int = 0
numReadsPerIterA: int = 0
numReadsPerIterB: int = 0
numReadsPerIterMetadata: int = 0
localReadDoCntA: int = 0
localReadDoCntB: int = 0
localReadDoCntMetadata: int = 0
savedLocalReadDoCntA: int = 0
savedLocalReadDoCntB: int = 0
savedLocalReadDoCntMetadata: int = 0
dtvKIntervalA: int = 1
dtvKIntervalB: int = 1
## MFMA
miLatency: int = 0
miLatencyLeft: int = 0
miDependency: int = 0
numMfmaForLR: int = 1
grEndMfmaIndex: int = -1
sync1LdsMfmaIndex: int = -1
lwStartMfmaIndex: int = -1
lwEndMfmaIndex: int = -1
numMfmaForNextLoopLR: int = -1
syncPlrMfmaIndex: int = -1
numGlobalReadInsPerMfma: int = 0
numLocalWriteModPerMfma: int = 0
HHH_WMMA: bool = False
perIterLocalWriteCanSkip: List[int] = field(init=False)
lraTileProperties: Dict[int, LraTileProperties] = field(init=False)
# Epilogue states
preloadScaleA = False
preloadScaleB = False
useBias = DataDirection.NONE
needBiasType = False
def __post_init__(self):
""" How many SGPRs does it take to have one bit per lane? """
self.laneSGPRCount = 2
if "WavefrontSize" in self.kernel and self.kernel["WavefrontSize"] == 32:
self.laneSGPRCount = 1
self.indexChars = [] # Workaround
self.srdShiftLeft = {} # Workaround
self.perIterLocalWriteCanSkip = []
self.lraTileProperties = {} # Workaround
self.numStoreSgprNames = []
self.numStoreSgprNameSizes = []
self.nonPostLoopSgpr = []
self.preloadGuard = []
@dataclass
class StateVgprs:
coord0: int = -1
coord1: int = -1
# StoreRemapVectorWidth
storeRemapLW: int = -1
storeRemapLR: int = -1
storeRemapCoord0: int = -1
storeRemapCoord1: int = -1
storeRemapOffsetCoord1: int = -1
# BufferStore
cinRowPtr: int = -1
coutRowPtrBias: int = -1
coutRowPtrE: int = -1
coutRowPtrD: int = -1
# FlatStore
addrE: int = -1
addrD: int = -1
addrC: int = -1
addrBias: int = -1
globalReadRegisters: Dict[str, int] = field(init=False)
def __post_init__(self):
self.globalReadRegisters = {}
self.globalReadRegisters['A'] = []
self.globalReadRegisters['B'] = []
@dataclass
class CodeModules:
accVgprRead: Optional[Module] = None
accVgprWrite: Optional[Module] = None
mulAlphaMultipleBuffer: Optional[Module] = None
mulAlphaOther: Optional[Module] = None
localWriteA: Optional[Module] = None
localWriteB: Optional[Module] = None
dtlsM0UpdateA: Optional[Module] = None
dtlsM0UpdateB: Optional[Module] = None
globalReadA: Optional[Module] = None
globalReadB: Optional[Module] = None
globalReadIncrements: Optional[Module] = None
## MFMA
unrollLoopHeader: Optional[Module] = None
perIterGlobalRead: Optional[List[Module]] = None
perIterLocalWrite: Optional[List[Module]] = None
perIterLocalWriteCodeNGLL: Optional[Module] = None
@dataclass
class ExternClasses:
activation: ActivationModule = ActivationModule()
biasSumUnroll: Optional[Component.SumUnroll] = None
################################################################################
# Kernel Writer
################################################################################
class KernelWriter(metaclass=abc.ABCMeta):
#__metaclass__=abc.ABCMeta
##############################################################################
# Init
##############################################################################
def __init__(
self,
assembler: Assembler,
debugConfig: DebugConfig,
):
self.assembler = assembler
self.debugConfig = debugConfig
self.do = {}
self.do["PreLoop"] = True
self.do["GlobalReadA"] = True
self.do["GlobalReadB"] = True
self.do["GlobalInc"] = True
self.do["LocalWriteA"] = True
self.do["LocalWriteB"] = True
self.do["LocalWriteMetadata"] = True
self.do["LocalWriteCVT"] = True
self.do["LocalReadA"] = True
self.do["LocalReadB"] = True
self.do["LocalReadMetadata"] = True
self.do["Wait"] = True
self.do["Sync"] = True
self.do["MAC"] = True
self.do["PostLoop"] = True
self.do["ApplyAlpha"] = True
self.do["GlobalWrite"] = True
self.do["EdgeWrite"] = True
self.do["KeepDirectToLdsAlloc"] = False # If true, keep regs used for LDS alloc even if not used
self.do["OptimizeNumItersPLR0"] = True
self.do["AutoSplitDsWrite"] = True
self.do["executeToInitEnd"] = 0
self.do["executeToPrefetchEnd"] = 0
self.do["executeToLoopEnd"] = 0
# Various debug flags and modes
self.db = {}
self.db["EnableAsserts"] = self.debugConfig.enableAsserts # Enable assertion codegen. Requires 2 SGPR.
self.db["DebugKernelMaxItems"] = 16 # Capture first N(=16) print values, ignore subsequent. If -1, debug writing is faster but writing more than 16 values is undefined.
# Chicken bit to add conservative synchronization at strategic points:
# 0x01 = waitcnt + barrier after vector load
# 0x02 = waitcnt at self._wait() for globalRead
# 0x04 = waitcnt at self._wait() for localWrite
# 0x08 = waitcnt at self._wait() for localRead
# 0x10 = waitcnt after summation iteration, this can catch lingering ds or vm activity from summation loop
# 0x20 = waitcnt before each write batch
# 0x40 = waitcnt after each write batch
self.db["ConservativeWaitCnt"] = 0x00
self.db["InitLds"] = False # Initialize LDS at start of kernel
# InitSgpr and InitVgpr can initialize at various points:
# 0x1: Init at kernel start
# 0x2: Init at end of summation loop (after tail too) - this is just before store loop
self.db["InitSgpr"] = 0x0 # init SGPRs
self.db["InitVgpr"] = 0x0 # init VGPRs
# Debug and Check flags:
# Check A and B values loaded from memory to ensure they are 1
# Requires DataInitTypeAB=1.
# Only works if the problem uses full tiles (no edges)
# Mismatches will assert (generate GPUVM fault)
self.db["CheckValue1A"] = self.debugConfig.enableDebugA
self.db["CheckValue1B"] = self.debugConfig.enableDebugB
self.db["CheckValue1Metadata"] = False
# Check value in C matrix.
# Caveats:
# - Only works for single, or Half/BF with HPA.
# - Checks after alpha calc for each element. Later elements (in the TT) will not yet have applied their alpha.
# - Only works if matrix is integral multiple of macro-tile (no edges) - check is dumb so doesn't know
# which work-items are outside the valid edge.
# - Does not work in OptNoLoadLoop
self.db["CheckValueC"] = self.debugConfig.enableDebugC
# value expected if CheckValueC is set. Use '.' for FP.
# For example could be 16.0 if U=8 and alpha=2
self.db["ValueCExpectedValue"] = self.debugConfig.expectedValueC
# Force an expected value for all C outputs.
# May be useful for checking store path
# See same caveats as CheckValueC
self.db["ForceExpectedValue"] = self.debugConfig.forceCExpectedValue
# Force VSerial value into the output, this will
# not match reference but can be useful to see which work-items are
# storing which values
# See same caveats as CheckValueC
self.db["ForceVSerial"] = False
# can't do both of these since they both override output
assert (not (self.db["ForceExpectedValue"] and self.db["ForceVSerial"]))
self.db["ForceInputValueA"] = False
self.db["ForceInputValueB"] = False
self.db["ForceInputValueMetadata"] = False
self.db["ForceValueA"] = 1.0
self.db["ForceValueB"] = 1.0
self.db["ForceValueMetadata"] = 1.0
self.db["CheckStoreC"] = -1 # -1 disables, reload and verify output data. Specify expected constant value.
#self.db["CheckStoreC"] = 1024.0 # possible value
self.db["ForceEdgeStores"] = 0 # 1=force use of edge store path for all tiles, 2=add assert in non-edge stores
self.db["AssertNoEdge"] = 0 # Add assert in edge store code so crashes if executed
# print vgpr register pool checkins and checkouts
self.db["PrintRP"] = 0
self.db["AssertOnSgprOverflow"] = False
self.db["PrintStoreRegisterDb"] = False
self.dumpData = Dump("DebugKernelItems", "AddressDbg", self.db["DebugKernelMaxItems"], \
self.debugConfig.debugKernel)
self.labels = LabelManager()
# KernelWriter values
self.consts = ConstValues()
self.states = StateValues((0,0,0), {}, "")
self.vgprs = StateVgprs()
self.exclasses = ExternClasses()
##############################################################################
# makeSchedule: Schedule work into interations.
# Tensile uses a two-level scheduler. This the first-level, which
# schedules global reads, global incs, and local writes into iteration.
# Then makeSubIterSchedule schedules the instructions within the iteration.
#
# Inputs:
# localWriteEndIter: loop iteration where last writes should be inserted
# If scheduleLocalWrite=0, all writes will be be placed in this iteration.
# If scheduleLocalWrite=1, the scheduler will work backwards from this
# iteration.
#
# Outputs:
# self.codes.unrollLoopHeader:
# - Code module that should be added into the unroll loop header
# In unscheduled code this contains global loads and global address increment
# self.codes.perIterGlobalRead[], self.codes.perIterLocalWrite[]
# - List indexed by unroll iteration.
# Each entry in the list is a code module that should be added into that iteration.
# May be None, indicating no extra code for that iteration
# self.states.grEndMfmaIndex
# self.states.lwStartMfmaIndex
# self.states.lwEndMfmaIndex
# self.states.syncPlrMfmaIndex
# self.states.numMfmaForNextLoopLR
# This routine is responsible for setting the schedule including determining
# that all necessary dependency are met. The driver code in kernelBody
# blindly follows the plan set in unrollLoopHeaderCode and perIterCode
##############################################################################
def makeSchedule(self, kernel, tensorParametersA, tensorParametersB, localWriteEndIter, skipGlobalReadInc=False, firstIter=False, lastLoop=False, lastLc=False, isNGLL=False):
maxVmcnt = self.states.asmCaps["MaxVmcnt"]
self.codes.unrollLoopHeader = Module()
# schedule of work for each local_read iteration:
self.codes.perIterGlobalRead = [ Module() for i in range (kernel["LoopIters"]) ]
self.codes.perIterLocalWrite = [ Module() for i in range (kernel["LoopIters"]) ]
if lastLc:
self.codes.perIterLocalWriteCodeNGLL = [ Module() for i in range (kernel["LoopIters"]) ]
self.states.perIterLocalWriteCanSkip = [ 0 for i in range (kernel["LoopIters"]) ]
assert([item.name for item in self.codes.globalReadIncrements.items()] == ['globalReadIncrementA', 'globalReadIncrementB'])
globalReadIncACode = self.codes.globalReadIncrements.findNamedItem("globalReadIncrementA")
globalReadIncBCode = self.codes.globalReadIncrements.findNamedItem("globalReadIncrementB")
if skipGlobalReadInc:
globalReadIncACode = Module()
globalReadIncBCode = Module()
siaComponent = Component.SIA.find(self)
siaComponent.schedIntoIteration(self, kernel, tensorParametersA, tensorParametersB, \
localWriteEndIter, firstIter, lastLoop, lastLc, maxVmcnt, globalReadIncACode, \
globalReadIncBCode, isNGLL)
##############################################################################
# Schedule work into the each unroll loop iteration
# localReadCode is the local reads for this loop iteration
# (returned by localReadDo). The instructions in localReadCode
# will retain their relative order, but may be interleaved
# with instructions from otherCode.
# globalReadCode is the 'other' buffer loads and addr increments
# localWriteCode is the 'other' local writes
# to schedule in with the ds reads. The instructions
# will retain their relative order, but may be interleaved
# with instructions from localReadCode.
# pointerCode contains local pointer changes (if needed)
# waitCode contains s_waitcnt before macs.
# - Cannot be "" or None
# - may be empty Module if not waiting is desired (perhaps for debug)
# - may be multiple instructions (ConservativeWaitCnt)
# - typically is a single SWaitCnt. This routine will
# modify the lgkmcnt to account for any scheduling decisions.
# If this is not desired, add the waitCnt to pointerCode and
# set waitCode to an empty module
# macIterCode contains the mac iters. May be a macro call.
#
# returns: a Module with the combined, optimally scheduled
# localReadCode + otherCode
##############################################################################
def _makeSubIterSchedule(self, kernel, tPA, tPB, localReadCode, iteration, pointerLWCode, pointerLRCode, waitCode, macIterCode, \
waitLWCode = Module(), syncCode = Module(), packCode = Module(), prevIterCode = Module(), NLLlast = False):
iterCode = Module()
globalReadCode = deepcopy(self.codes.perIterGlobalRead[iteration])
localWriteCode = self.codes.perIterLocalWrite[iteration]
isBarrier = kernel["LoopIters"] - self.states.numItersPLR
hasLocalRead = countLocalRead(localReadCode)
# Default schedule is other, local reads, then local writes:
if self.states.scheduleIterAlg==0:
# simple schedule, just add the modules in-order
iterCode.add(globalReadCode)
iterCode.add(waitLWCode)
iterCode.add(syncCode)
iterCode.add(localReadCode)
iterCode.add(localWriteCode)
iterCode.add(pointerLWCode)
iterCode.add(pointerLRCode)
iterCode.add(waitCode)
iterCode.add(packCode)
iterCode.add(macIterCode)
elif self.states.scheduleIterAlg == 1:
iterCode.add(waitLWCode)
iterCode.add(syncCode)
#import pdb
#pdb.set_trace()
# simple algorithm - do half the reads first:
readsToSchedule = countLocalRead(localReadCode) / 2
#localReadCode.prettyPrint()
readItems = localReadCode.flatitems()
while readItems:
item = readItems.pop(0)
#print "readsToSchedule=", readsToSchedule, "item=", item
iterCode.add(item)
readsThisItem = countLocalRead(item)
if readsThisItem:
assert readsThisItem==1, "Scheduler assumes 1 read per item"
readsToSchedule = readsToSchedule - 1
if readsToSchedule == 0:
break
iterCode.add(globalReadCode)
# add rest of the reads here
for item in readItems:
iterCode.add(item)
#move down write to be the last
iterCode.add(localWriteCode)
# tack on the pointer and mac code:
iterCode.add(pointerLWCode)
iterCode.add(pointerLRCode)
iterCode.add(waitCode)
iterCode.add(packCode)
iterCode.add(macIterCode)
elif self.states.scheduleIterAlg == 2:
# SIA2 use only 1 iteration and separate compute and fetch by raising compute priority
# 2 workgroup interleave, while WG0/WG1 doing compute, WG1/WG0 doing fetch
# EPS need to be 1, or valu instruction will break interleave
iterCode.add(globalReadCode)
iterCode.add(waitLWCode)
iterCode.add(syncCode)
iterCode.add(localReadCode)
iterCode.add(waitCode)
# interleave pack code
# BF16 or FP16: each packCode is for one 32-bit reg, 1 packing inst: half-to-single x1
# INT8 : each packCode is for one 32-bit regs, 3 packing inst: byte-to-half x2 + half-to-single x1
if self.states.archCaps["HasEccHalf"] or not self.states.asmCaps["HasWMMA_V1"]:
instPerRegPack = 1 / kernel["ProblemType"]["DataType"].numRegisters() - 1
else:
instPerRegPack = 1 if (kernel["ProblemType"]["DataType"].numRegisters() == 0.25) else 0
instPerPack = int(kernel["MIInputPerThread"] * kernel["ProblemType"]["DataType"].numRegisters() * instPerRegPack)
packItems = []
for iui in range(kernel["InnerUnroll"]):
packINtems = [ [] for j in range(max(self.states.numReadsIterCoalescedA,self.states.numReadsIterCoalescedB)) ]
packA = packCode.findNamedItem("packA_I%s"%(iui))
packB = packCode.findNamedItem("packB_I%s"%(iui))
# In case localReadDo not generate pack Module
# and findNamedItem will return None type
# TODO: let all type have pack Module
if not packA:
packA = Module()
packAItems = packA.flatitems()
if not packB:
packB = Module()
packBItems = packB.flatitems()
if packAItems:
for j in range(self.states.numReadsIterCoalescedA):
for n in range(instPerPack):
packINtems[j].append(packAItems.pop(0))
if packBItems:
for j in range(self.states.numReadsIterCoalescedB):
for n in range(instPerPack):
packINtems[j].append(packBItems.pop(0))
while packAItems:
for j in range(self.states.numReadsIterCoalescedA):
for n in range(instPerPack):
packINtems[j].append(packAItems.pop(0))
while packBItems:
for j in range(self.states.numReadsIterCoalescedB):
for n in range(instPerPack):
packINtems[j].append(packBItems.pop(0))
for j in range(max(self.states.numReadsIterCoalescedA,self.states.numReadsIterCoalescedB)):
packItems += packINtems.pop(0)
macIterItems = macIterCode.flatitems()
# pop the first code which is s_nop 1 for packing
item = macIterItems.pop(0) if isinstance(macIterItems[0], SNop) else None
numMfmaPerIter = self.states.numMfmaPerIter
curPackIdx = 0
packAIdx = 0
packBIdx = 0
for i in range(numMfmaPerIter):
if packItems:
# how many pack have to be done
# calculate the data index of this mfma used for A and B
# if i // kernel["MIWaveTile"][0]==0, mfma will use new A (need to take iu into account)
# if i % kernel["MIWaveTile"][0]==0, mfma will use new B
packAIdx += instPerPack if i//(kernel["MIWaveTileA"]+kernel["MIWaveTileA"]*kernel["MIWaveTileB"]*(i//(kernel["MIWaveTileA"]*kernel["MIWaveTileB"]))) == 0 else 0
packBIdx += instPerPack if i % kernel["MIWaveTileA"] == 0 else 0
# blockWidth < 1, means 0.5 or 0.25 (BF,H,Int8)
if self.states.archCaps["HasEccHalf"] or not self.states.asmCaps["HasWMMA_V1"]:
packAIdx = packAIdx if tPA["bpe"] < 4 and not kernel["UnrollMajorLDSA"] else 0
packBIdx = packBIdx if tPB["bpe"] < 4 and not kernel["UnrollMajorLDSB"] else 0
else:
packAIdx = packAIdx if tPA["localReadInstruction"].blockWidth == 0.25 else 0
packBIdx = packAIdx if tPB["localReadInstruction"].blockWidth == 0.25 else 0
numPack = (packAIdx + packBIdx)
iterCode.addComment0("pack scheduling: packAIdx:%u, packBIdx:%u" %(packAIdx,packBIdx))
# we put 2 pack in each mfma, "2" means A & B
if packItems:
for j in range(instPerPack):
iterCode.add(packItems.pop(0))
curPackIdx += 1
if packItems:
for j in range(instPerPack):
iterCode.add(packItems.pop(0))
curPackIdx += 1
# since packed register need to wait 2 quad cycle to finish packing
# we insert pack instruction if we can, or s_nop
while curPackIdx < numPack+2:
if packItems:
for j in range(instPerPack):
iterCode.add(packItems.pop(0))
curPackIdx += 1
else:
iterCode.add(SNop(waitState=0, comment="VALU packing writes to be consumed by matrix instruction"))
curPackIdx += 1
if i == 0:
if not packItems:
tmpVgpr = self.vgprPool.checkOut(1)
iterCode.add(VMovB32(dst=vgpr(tmpVgpr), src="0x0", comment="valu operation to have different priority"))
self.vgprPool.checkIn(tmpVgpr)
iterCode.add(SSetPrior(prior=3, comment="Raise priority while processing macs"))
item = macIterItems.pop(0)
iterCode.add(item)
while macIterItems:
iterCode.add(macIterItems.pop(0))
iterCode.add(SSetPrior(prior=1, comment="Raise priority while processing macs"))
if kernel["1LDSBuffer"]:
barrier = Module()
barrier.addComment0("1 LDS buffer: read-sync-write")
barrier.add(SWaitCnt(lgkmcnt=0, comment=""))
barrier.add(SBarrier())
iterCode.add(barrier)
iterCode.add(localWriteCode)
iterCode.add(pointerLWCode)
iterCode.add(pointerLRCode)
iterCode.add(SSetPrior(prior=2, comment="Raise priority while processing macs"))
pass
elif self.states.scheduleIterAlg == 3:
iterCode.addComment0(" grEndMfmaIndex:%u, lwStartMfmaIndex:%u, lwEndMfmaIndex:%u "\
%(self.states.grEndMfmaIndex, self.states.lwStartMfmaIndex, self.states.lwEndMfmaIndex))
iterCode.addComment0(" numMfmaForLR:%u, syncPlrMfmaIndex:%u "\
%(self.states.numMfmaForNextLoopLR, self.states.syncPlrMfmaIndex))
#####
# Prepare and Assign parameter
####
if iteration == 0:
self.localReadsVacancy = []
self.localReadsWait = [ [] for j in range(kernel["LoopIters"])]
self.localReadsWait[iteration] = waitCode
numMfmaPerIter = self.states.numMfmaPerIter
isBarrier = kernel["LoopIters"] - self.states.numItersPLR
writeItems = list(localWriteCode.items())
macIterItems = macIterCode.flatitems()
skipLocalWriteWaitcnt = 0
localReadsWaitcnt = 0
localReadsIssuedInThisIter = 0
curPackIdx = 0
packAIdx = 0
packBIdx = 0
packMIdx = 0
schedulePackConsiderMetadata = kernel["ProblemType"]["Sparse"] and not kernel["DirectToVgprSparseMetadata"]
numPackedA = 0
numPackedB = 0
numPackedM = 0
#####
# Prepare localReadCode
####
localReadCodeAB = Module()
for iui in range(kernel["InnerUnroll"]):
localReadCodeA = localReadCode.findNamedItem("LocalReadDoA_I%s"%(iui))
localReadCodeB = localReadCode.findNamedItem("LocalReadDoB_I%s"%(iui))
localReadCodeM = localReadCode.findNamedItem("LocalReadDoMetadata_I%s"%(iui))
# In case localReadDo not generate localReadCode Module
# and findNamedItem will return None type
# TODO: findNamedItem return Module() if not found
if not localReadCodeA:
localReadCodeA = Module()
if not localReadCodeB:
localReadCodeB = Module()
if not localReadCodeM:
localReadCodeM = Module()
if localReadCodeA.items():
localReadCodeAB.add(localReadCodeA.popFirstItem())
if localReadCodeM.items():
localReadCodeAB.add(localReadCodeM.popFirstItem())
if localReadCodeB.items():
localReadCodeAB.add(localReadCodeB.popFirstItem())
if localReadCodeA.itemsSize():
localReadCodeAB.addItems(localReadCodeA.popFirstNItems(localReadCodeA.itemsSize()))
if localReadCodeM.itemsSize():
localReadCodeAB.addItems(localReadCodeM.popFirstNItems(localReadCodeM.itemsSize()))
if localReadCodeB.itemsSize():
localReadCodeAB.addItems(localReadCodeB.popFirstNItems(localReadCodeB.itemsSize()))
localReadItems = localReadCodeAB.flatitems()
localReadItemsThisLoop = localReadItems if iteration < isBarrier else []
localReadItemsNextLoop = localReadItems if iteration >= isBarrier else []
#####
# Prepare pack Code for B:
# since the mfma reuse B first => for A: mfma[A][B]
# we need 1 vector A and 1 vector B for first mfma
# then we prepare remaining A, then remaining B
# BF16 or FP16: each packCode is for one 32-bit reg, 1 packing inst: half-to-single x1
# INT8 : each packCode is for one 32-bit regs, 3 packing inst: byte-to-half x2 + half-to-single x1
####
if self.states.archCaps["HasEccHalf"] or not self.states.asmCaps["HasWMMA_V1"]:
instPerRegPack = 1 / kernel["ProblemType"]["DataType"].numRegisters() - 1
else:
instPerRegPack = 1 if (kernel["ProblemType"]["DataType"].numRegisters() == 0.25) else 0
instPerPackA = 0 if kernel["UnrollMajorLDSA"] else int(kernel["MIInputPerThreadA"] * kernel["ProblemType"]["DataType"].numRegisters() * instPerRegPack)
instPerPackB = 0 if kernel["UnrollMajorLDSB"] else int(kernel["MIInputPerThreadB"] * kernel["ProblemType"]["DataType"].numRegisters() * instPerRegPack)
if kernel["ConvertAfterDS"]:
if kernel["ProblemType"]["DataTypeA"].isAnyFloat8():
if kernel["UnrollMajorLDSA"]:
if self.states.asmCaps["Hascvtf16_fp8"]:
instPerPackA = 2 * self.states.numReadsIterCoalescedA if(iteration % self.states.numReadsIterCoalescedA == 0) else 0
else:
instPerPackA = 6 * self.states.numReadsIterCoalescedA if(iteration % self.states.numReadsIterCoalescedA == 0) else 0
elif self.states.lrvwTileA == 1:
if self.states.asmCaps["Hascvtf16_fp8"]:
instPerPackA = 4
else:
instPerPackA = 8
elif self.states.lrvwTileA == 2:
if self.states.asmCaps["Hascvtf16_fp8"]:
instPerPackA = 8
else:
instPerPackA = 16
elif self.states.lrvwTileA == 4:
if self.states.asmCaps["Hascvtf16_fp8"]:
instPerPackA = 20
else:
instPerPackA = 36
elif self.states.lrvwTileA == 8:
if self.states.asmCaps["Hascvtf16_fp8"]:
instPerPackA = 44
else:
instPerPackA = 76
if kernel["ProblemType"]["DataTypeB"].isAnyFloat8():
if kernel["UnrollMajorLDSB"]:
if self.states.asmCaps["Hascvtf16_fp8"]:
instPerPackB = 2 * self.states.numReadsIterCoalescedB if(iteration % self.states.numReadsIterCoalescedB == 0) else 0
else:
instPerPackB = 6 * self.states.numReadsIterCoalescedB if(iteration % self.states.numReadsIterCoalescedB == 0) else 0
elif self.states.lrvwTileB == 1:
if self.states.asmCaps["Hascvtf16_fp8"]:
instPerPackB = 4
else:
instPerPackB = 8
elif self.states.lrvwTileB == 2:
if self.states.asmCaps["Hascvtf16_fp8"]:
instPerPackB = 8
else:
instPerPackB = 16
elif self.states.lrvwTileB == 4:
if self.states.asmCaps["Hascvtf16_fp8"]:
instPerPackB = 20
else:
instPerPackB = 36
elif self.states.lrvwTileB == 8:
if self.states.asmCaps["Hascvtf16_fp8"]:
instPerPackB = 44
else:
instPerPackB = 76
instPerPackM = 0
if kernel["ProblemType"]["Sparse"] and not kernel["DirectToVgprSparseMetadata"] and not kernel["UnrollMajorLDSMetadata"]:
instPerPackM = 1
if self.states.lrvwTileMetadata > 1:
if kernel["MIInputPerThreadMetadata"] == 1:
instPerPackM = 1.5
elif kernel["MIInputPerThreadMetadata"] == 4:
instPerPackM = 3
packItems = []
packItemsA = []
packItemsB = []
packItemsM = []
for iui in range(kernel["InnerUnroll"]):
packINtems = [ [] for j in range(max(self.states.numReadsIterCoalescedA,self.states.numReadsIterCoalescedB,self.states.numReadsIterCoalescedMetadata)) ]
packINtemsA = packINtems
packINtemsB = packINtems
packINtemsM = packINtems
if schedulePackConsiderMetadata:
packINtemsA = [ [] for j in range(max(self.states.numReadsIterCoalescedA,self.states.numReadsIterCoalescedB,self.states.numReadsIterCoalescedMetadata)) ]
packINtemsB = [ [] for j in range(max(self.states.numReadsIterCoalescedA,self.states.numReadsIterCoalescedB,self.states.numReadsIterCoalescedMetadata)) ]
packINtemsM = [ [] for j in range(max(self.states.numReadsIterCoalescedA,self.states.numReadsIterCoalescedB,self.states.numReadsIterCoalescedMetadata)) ]
packA = packCode.findNamedItem("packA_I%s"%(iui))
packB = packCode.findNamedItem("packB_I%s"%(iui))
packM = packCode.findNamedItem("packMetadata_I%s"%(iui))
# In case localReadDo not generate pack Module
# and findNamedItem will return None type
# TODO: let all type have pack Module
if not packA:
packA = Module()
packAItems = packA.flatitems()
if not packB:
packB = Module()
packBItems = packB.flatitems()
if not packM:
packM = Module()
packMItems = packM.flatitems()
if packAItems:
if kernel["ConvertAfterDS"] and kernel["ProblemType"]["DataTypeA"].isAnyFloat8():
for n in range(instPerPackA):
packINtemsA[0].append(packAItems.pop(0))
else:
for j in range(self.states.numReadsIterCoalescedA):
for n in range(instPerPackA):
packINtemsA[j].append(packAItems.pop(0))
if kernel["ProblemType"]["Sparse"] and not kernel["DirectToVgprSparseMetadata"]:
for j in range(self.states.numReadsIterCoalescedMetadata):
for n in range(ceil(instPerPackM)):
if packMItems:
packINtemsM[j].append(packMItems.pop(0))
else:
break
if packBItems:
if kernel["ConvertAfterDS"] and kernel["ProblemType"]["DataTypeB"].isAnyFloat8():
for n in range(instPerPackB):
packINtemsB[0].append(packBItems.pop(0))
else:
for j in range(self.states.numReadsIterCoalescedB):
for n in range(instPerPackB):
packINtemsB[j].append(packBItems.pop(0))
while packAItems:
if kernel["ConvertAfterDS"] and kernel["ProblemType"]["DataTypeA"].isAnyFloat8():
for n in range(instPerPackA):
if packAItems:
packINtemsA[0].append(packAItems.pop(0))
else:
break
else:
for j in range(self.states.numReadsIterCoalescedA):
for n in range(instPerPackA):
if packAItems:
packINtemsA[j].append(packAItems.pop(0))
else:
break
if kernel["ProblemType"]["Sparse"] and not kernel["DirectToVgprSparseMetadata"]:
while packMItems:
for j in range(self.states.numReadsIterCoalescedMetadata):
for n in range(ceil(instPerPackM)):
if packMItems:
packINtemsM[j].append(packMItems.pop(0))
else:
break
while packBItems:
if kernel["ConvertAfterDS"] and kernel["ProblemType"]["DataTypeB"].isAnyFloat8():
for n in range(instPerPackB):
if packBItems:
packINtemsB[0].append(packBItems.pop(0))
else:
break
else:
for j in range(self.states.numReadsIterCoalescedB):
for n in range(instPerPackB):
if packBItems:
packINtemsB[j].append(packBItems.pop(0))
else:
break
for j in range(max(self.states.numReadsIterCoalescedA,self.states.numReadsIterCoalescedB,self.states.numReadsIterCoalescedMetadata)):
if schedulePackConsiderMetadata:
packItemsA += packINtemsA.pop(0)
packItemsB += packINtemsB.pop(0)
packItemsM += packINtemsM.pop(0)
else:
packItems += packINtems.pop(0)
if schedulePackConsiderMetadata:
packItems = packItemsA + packItemsB + packItemsM
# remove s_nop for packing
# we will add s_nop if needed
if macIterItems:
if isinstance(macIterItems[0], SNop):
macIterItems.pop(0)
####
# scheduled local read to previous iterations
####