Debian Codegraph @

tensilelite/Tensile/SolutionStructs/Solution.py

raw symbols SCIP
1 ################################################################################
2 #
3 # Copyright (C) 2022-2025 Advanced Micro Devices, Inc. All rights reserved.
4 #
5 # Permission is hereby granted, free of charge, to any person obtaining a copy
6 # of this software and associated documentation files (the "Software"), to deal
7 # in the Software without restriction, including without limitation the rights
8 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 # copies of the Software, and to permit persons to whom the Software is
10 # furnished to do so, subject to the following conditions:
11 #
12 # The above copyright notice and this permission notice shall be included in
13 # all copies or substantial portions of the Software.
14 #
15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 # SOFTWARE.
22 #
23 ################################################################################
24
25 import collections
26 import math
27
28 from enum import Enum
29 from typing import List, Dict, Literal
30
31 from Tensile.AsmStoreState import VectorDataTypes
32 from Tensile.Activation import ActivationType
33 from Tensile.Activation import ActivationType
34 from Tensile.AsmStoreState import VectorDataTypes
35 from Tensile.Common import assignParameterWithDefault, IsaInfo, \
36 print2, printExit, printWarning, \
37 roundUp, INDEX_CHARS, IsaVersion, SemanticVersion, \
38 roundUpToNearestMultiple
39 from Tensile.Common.DataType import DataType
40 from Tensile.Common.GlobalParameters import defaultSolution, \
41 defaultInternalSupportParams
42 from Tensile.SolutionStructs.Naming import getSolutionNameFull
43 from Tensile.SolutionStructs.Problem import ProblemType
44 from Tensile.Toolchain.Component import Assembler
45 from Tensile.Components.CustomSchedule import hasCustomSchedule
46
47 from .Utilities import reject, roundupRatio, pvar
48
49 class Fbs(Enum):
50 Free=0 # Expect to be free dimension
51 Batch=1 # Expect to be batch dimension
52 Sum=2 # Expect to be summation dimension
53
54 ################################################################################
55 # Factor Type
56 ################################################################################
57 class FactorDimArgs:
58
59 ########################################
60 def __init__(self, problemType, config):
61 self.factorDims = []
62 self.totalProblemSizes = 0
63 if problemType["UseScaleAlphaVec"] or problemType["UseBias"]:
64 for fdim in config:
65 dim = int(fdim)
66 if dim not in [0, 1]:
67 printWarning("Factor Dim: must be 0 or 1, current is %s."%(dim))
68 self.factorDims.append(dim)
69 self.totalProblemSizes = len(self.factorDims)
70
71 def __str__(self):
72 s = "FactorDimArgs\n"
73 return s
74
75 class BiasTypeArgs:
76
77 ########################################
78 def __init__(self, problemType, config):
79 self.biasTypes = []
80 self.totalProblemSizes = 0
81 if problemType["UseBias"]:
82 for btype in config:
83 datatype = DataType(btype)
84 if datatype not in problemType["BiasDataTypeList"]:
85 printWarning("Datatype: %s not support in this kernel (%s)"%(datatype, str(problemType["BiasDataTypeList"])))
86 self.biasTypes.append(datatype)
87
88 if not self.biasTypes:
89 printExit("Must provide a bias type in benchmark parameters if UseBias is set to True.")
90
91 self.totalProblemSizes = len(self.biasTypes)
92
93 def __str__(self):
94 s = "BiasTypesArgs\n"
95 return s
96
97 ################################################################################
98 # Activation
99 ################################################################################
100
101 class activationSetting:
102 def __init__(self):
103 self.activationEnum = ""
104 class ActivationArgs:
105
106 ########################################
107 def __init__(self, problemType, config):
108 self.settingList = []
109 self.totalProblemSizes = 0
110 if problemType["ActivationType"] == 'none':
111 return
112 if config:
113 for settings in config:
114 actSetting = activationSetting()
115 for dictionary in settings:
116 for sizeTypeKey in dictionary:
117 if sizeTypeKey == "Enum":
118 actSetting.activationEnum = ActivationType(dictionary[sizeTypeKey])
119 if problemType["ActivationType"] in ['all', 'hipblaslt_all']:
120 if (not actSetting.activationEnum):
121 printExit("Must provide an activation enum if Activation is set to True.")
122 else:
123 actSetting.activationEnum = problemType["ActivationType"]
124 self.settingList.append(actSetting)
125 self.totalProblemSizes += 1
126 if (problemType["ActivationType"] == 'all') and (not self.settingList):
127 printExit("Must provide an activation enum in benchmark parameters if Activation is set to True.")
128 def __str__(self):
129 s = "ActivationArgs\n"
130 return s
131
132 # kds is class Solution or class Kernel
133 # All free dims are packed
134 def isPackedIndex(ks, index):
135 problemType = ks["ProblemType"]
136 return index in problemType["IndicesFree"]
137
138 def isExtractableIndex(ks, index, tc='x'):
139 xA = index in ks['PackedC0IndicesX'][:-1]
140 xB = index in ks['PackedC1IndicesX'][:-1]
141 if tc=='A':
142 return xA
143 elif tc=='B':
144 return xB
145 else:
146 return xA or xB
147
148 ################################################################################
149 # Solution
150 ################################################################################
151 class Solution(collections.abc.Mapping):
152
153 ######################################## # need to be sure PSRR is passing to all fxns
154 def __init__(
155 self,
156 config,
157 splitGSU: bool,
158 printSolutionRejectionReason: bool,
159 printIndexAssignmentInfo: bool,
160 assembler: Assembler,
161 isaInfoMap: Dict[IsaVersion, IsaInfo],
162 srcName: str = ""
163 ):
164
165 self._name = None
166 self.assembler = assembler
167 self.isaInfoMap = isaInfoMap
168 self.srcName = srcName
169 self.splitGSU = splitGSU
170 config = config
171 targetIsas = list(isaInfoMap.keys())
172
173 self._state = {}
174 # problem type
175 if "ProblemType" in config:
176 self["ProblemType"] = ProblemType(config["ProblemType"], printIndexAssignmentInfo)
177 else:
178 self["ProblemType"] = ProblemType.FromDefaultConfig(printIndexAssignmentInfo)
179
180 if "InternalSupportParams" in config:
181 self["InternalSupportParams"] = {}
182 for key in defaultInternalSupportParams:
183 assignParameterWithDefault(self["InternalSupportParams"], key, config["InternalSupportParams"], defaultInternalSupportParams)
184 else:
185 self["InternalSupportParams"] = defaultInternalSupportParams
186
187 # Assign solution state from config, filling missing from the defaultSolution
188 for key in defaultSolution:
189 assignParameterWithDefault(self._state, key, config, defaultSolution)
190
191 if 'ISA' not in self._state:
192 if 'ISA' in config:
193 # The ISA is expected to be defined when calling from TensileCreateLibrary
194 isa = config['ISA']
195 isa = IsaVersion(isa[0], isa[1], isa[2])
196 assert self.isaInfoMap[isa].asmCaps["SupportedISA"]
197 self._state['ISA'] = IsaVersion(isa[0], isa[1], isa[2])
198 else:
199 # When calling from Tensile, the ISA is typically not defined.
200 printWarning(f"ISA not set on config using {targetIsas[0]}.")
201 self._state['ISA'] = targetIsas[0]
202
203 if "CodeObjectVersion" not in self._state:
204 if "CodeObjectVersion" in config:
205 self._state["CodeObjectVersion"] = str(config["CodeObjectVersion"])
206 else:
207 self._state["CodeObjectVersion"] = self.assembler.code_object_version
208 # assign parameters without defaults
209 for key in config:
210 if (key != "ProblemType" or key != "InternalSupportParams") and key not in self._state:
211 self._state[key] = config[key]
212 self["Valid"] = True
213 # this could prevent OriginalSolution from re-assigning the parameters, save lots of time
214 if "AssignedProblemIndependentDerivedParameters" not in self._state:
215 self["AssignedProblemIndependentDerivedParameters"] = False
216 if "AssignedDerivedParameters" not in self._state:
217 self["AssignedDerivedParameters"] = False
218 Solution.assignDerivedParameters(
219 self._state,
220 splitGSU,
221 printSolutionRejectionReason,
222 printIndexAssignmentInfo,
223 isaInfoMap,
224 assembler.rocm_version
225 )
226 self._name = config["CustomKernelName"] if "CustomKernelName" in config and config["CustomKernelName"] else None
227
228 # these keys are copied from ProblemType to internal that may be overridden
229 InternalKeys = ["UseSgprForGRO","VectorStore"]
230
231
232 ########################################
233 # get a list of kernel parameters for this solution
234 def getKernels(self):
235 kernel = self
236 kernel._state.update({"Kernel": True})
237 kernels = []
238 kernels.append(kernel)
239 return kernels
240
241
242 ########################################
243 # get Helper Kernels
244 def getKernelBetaOlnyObjects(self):
245 return self.betaOnlyKernelObjects
246
247
248 ########################################
249 # get Helper Kernels
250 def getKernelConversionObjects(self):
251 return self.conversionKernelObjects
252
253 @staticmethod
254 def getMIOutputInfo(state, isaInfoMap: Dict[str, IsaInfo]):
255 outputVectorWidth = 4
256 RegsPerOut = 1
257
258 isa = tuple(state["ISA"])
259 if isaInfoMap[isa].asmCaps['HasMFMA']:
260 if state["ProblemType"]["DataType"].MIOutputTypeNameAbbrev() == 'f64':
261 outputVectorWidth, RegsPerOut = 1, 2
262 else:
263 outputVectorWidth, RegsPerOut = 4, 1
264 elif isaInfoMap[isa].asmCaps['HasWMMA_V1']:
265 outputVectorWidth, RegsPerOut = 1, 1
266 elif isaInfoMap[isa].asmCaps['HasWMMA_V2']:
267 outputVectorWidth, RegsPerOut = 8, 1
268 else:
269 print("WARNING: unexpect code flow")
270
271 return outputVectorWidth, RegsPerOut
272
273 ########################################
274 # assign tile sizes
275 @staticmethod
276 def assignProblemIndependentDerivedParameters(state, printRejectionReason: bool, isaInfoMap: Dict[str, IsaInfo]):
277
278 if "AssignedProblemIndependentDerivedParameters" in state:
279 if state["AssignedProblemIndependentDerivedParameters"]:
280 return
281 state["AssignedProblemIndependentDerivedParameters"] = False
282 if "Valid" not in state:
283 state["Valid"] = True
284
285 if (not state["ProblemType"]["StridedBatched"]) and (not state["ProblemType"]['Batched']):
286 reject(state, printRejectionReason, "General Batched GEMM only support Batched Problem")
287
288 if (not state["ProblemType"]["StridedBatched"]) and (state["ProblemType"]["OperationType"] != 'GEMM'):
289 reject(state, printRejectionReason, "General Batched GEMM only support GEMM OperationType")
290
291 ### ---> This is where we previously called matrixInstructionToMIParameters
292
293 EnableMatrixInstruction = state["EnableMatrixInstruction"] if "EnableMatrixInstruction" in state else None
294 if EnableMatrixInstruction == None:
295 if ("MIBlock" in state and len(state["MIBlock"]) == 6) \
296 and ("MIWaveGroup" in state and len(state["MIWaveGroup"]) == 2) \
297 and ("MIWaveTile" in state and len(state["MIWaveTile"]) == 2):
298 EnableMatrixInstruction = True
299 elif ("WorkGroup" in state and len(state["WorkGroup"]) == 3) \
300 and ("ThreadTile" in state and len(state["ThreadTile"]) == 2) :
301 EnableMatrixInstruction = False
302 else:
303 reject(state, printRejectionReason, "EnableMatrixInstruction undetermined")
304
305 if EnableMatrixInstruction == True:
306 state["MatrixInstM"] = state["MIBlock"][0]
307 state["MatrixInstN"] = state["MIBlock"][1]
308 state["MatrixInstK"] = state["MIBlock"][2]
309 state["MatrixInstB"] = state["MIBlock"][3]
310 state["MatrixInstBM"] = state["MIBlock"][4]
311 state["MatrixInstBN"] = state["MIBlock"][5]
312
313 state["LocalSplitU"] = state["WorkGroup"][2]
314 state["NumWaveSplitK"] = 1
315
316 state["MIOutputVectorWidth"], state["MIRegPerOut"] = Solution.getMIOutputInfo(state, isaInfoMap)
317
318 if state["MatrixInstM"] == 4:
319 state["ThreadTile0"] = state["MIWaveTile"][0] * state["MIOutputVectorWidth"]
320 state["ThreadTile1"] = state["MIWaveTile"][1]
321 state["SubGroup0"] = state["MIWaveGroup"][0] * state["MatrixInstM"] * state["MatrixInstBM"] // state["MIOutputVectorWidth"]
322 state["SubGroup1"] = state["MIWaveGroup"][1] * state["MatrixInstN"] * state["MatrixInstBN"]
323 else:
324 state["ThreadTile0"] = state["MatrixInstBM"] * state["MIWaveTile"][0] * (state["MatrixInstM"] * state["MatrixInstN"] // state["WavefrontSize"])
325 state["ThreadTile1"] = state["MatrixInstBN"] * state["MIWaveTile"][1]
326 state["SubGroup0"] = state["MIWaveGroup"][0] * (state["WavefrontSize"] // state["MatrixInstN"])
327 state["SubGroup1"] = state["MIWaveGroup"][1] * state["MatrixInstN"]
328
329 #for the old Logic yaml file which does not contain keys: MIInputPerThreadA/B
330 if not "MIInputPerThreadA" in state:
331 state["MIInputPerThreadA"] = state["MIInputPerThread"]
332 state["MIInputPerThreadB"] = state["MIInputPerThread"]
333
334 elif EnableMatrixInstruction == False:
335 state["ThreadTile0"] = state["ThreadTile"][0]
336 state["ThreadTile1"] = state["ThreadTile"][1]
337
338 state["SubGroup0"] = state["WorkGroup"][0]
339 state["SubGroup1"] = state["WorkGroup"][1]
340 # choose between 2 split modes
341 state["LocalSplitU"] = 1 if state["WaveSplitK"] else state["WorkGroup"][2]
342 state["NumWaveSplitK"] = state["WorkGroup"][2] if state["WaveSplitK"] else 1
343
344 if "SubGroup0" in state and "SubGroup1" in state and "LocalSplitU" in state and "NumWaveSplitK" in state:
345 state["NumThreads"] = state["SubGroup0"] * state["SubGroup1"] * state["LocalSplitU"] * state["NumWaveSplitK"]
346 if (state["NumThreads"] % state['WavefrontSize']) != 0:
347 reject(state, printRejectionReason, f"size of WorkGroup {state['NumThreads']} should be multiple of WavefrontSize {state['WavefrontSize']}")
348
349 # macro tile sizes
350 if "SubGroup0" in state and "ThreadTile0" in state:
351 state["MacroTile0"] = state["SubGroup0"]*state["ThreadTile0"]
352 if "SubGroup1" in state and "ThreadTile1" in state:
353 state["MacroTile1"] = state["SubGroup1"]*state["ThreadTile1"]
354 if "MacroTile" in state:
355 if state["MacroTile0"] != state["MacroTile"][0] \
356 or state["MacroTile1"] != state["MacroTile"][1]:
357 reject(state, printRejectionReason, "MacroTile mismatch")
358
359 # dot2: currently only support fp16 with HPA on gfx942 or fp16 &bf16 on gfx950
360 state["UseDotInstruction"] = (not state["EnableMatrixInstruction"]) \
361 and state["ProblemType"]["HighPrecisionAccumulate"] \
362 and ((state["ISA"] == IsaVersion(9,4,2) and state["ProblemType"]["DataType"].isHalf()) \
363 or (state["ISA"] == IsaVersion(9,5,0) and (state["ProblemType"]["DataType"].isBFloat16() or state["ProblemType"]["DataType"].isHalf())))
364 if state["UseDotInstruction"]:
365 # need modification for dot4 or dot8
366 state["NumDotElements"] = 2
367 if not state["UseDotInstruction"] and state["WaveSplitK"]:
368 reject(state, "WaveSplitK currently only support dot2 kernel.")
369 return
370
371 # tail loop optimization
372 state["tailLoopOptA"] = True
373 state["tailLoopOptB"] = True
374
375 # Use nonDTL loads in DTL tail loop
376 state["NonDTLTailLoopA"] = False
377 state["NonDTLTailLoopB"] = False
378
379 bpeA = state["ProblemType"]["DataTypeA"].numBytes()
380 bpeB = state["ProblemType"]["DataTypeB"].numBytes()
381 aemA = state["AssertSummationElementMultiple"] if not state["ProblemType"]["TLUA"] else state["AssertFree0ElementMultiple"]
382 aemB = state["AssertSummationElementMultiple"] if not state["ProblemType"]["TLUB"] else state["AssertFree1ElementMultiple"]
383 # For DTL, we use nonDTL loads in tail loop only if
384 # a partial 32b read is required to read the last few elements of a row/col of A/B
385 # i.e. ASEM * BPE % 4 != 0. In this case dword/dwordx4 DTL load will
386 # zero out the entire partial 32b read and cause accuracy issues.
387 # For TLU = 0 we check AF{0,1}EM instead of ASEM.
388 if (aemA * bpeA) % 4 != 0 or not state["BufferLoad"]:
389 state["NonDTLTailLoopA"] = True
390 if (aemB * bpeB) % 4 != 0 or not state["BufferLoad"]:
391 state["NonDTLTailLoopB"] = True
392
393 if (state["ISA"] != (9, 4, 2) and state["ISA"] != (9, 5, 0)) or \
394 (state["ProblemType"]["Sparse"]) or \
395 (state["UseDotInstruction"]):
396 state["tailLoopOptA"] = False
397 state["tailLoopOptB"] = False
398 if (state["DirectToVgprA"]):
399 state["tailLoopOptA"] = False
400 if (state["DirectToVgprB"]):
401 state["tailLoopOptB"] = False
402
403 # reorder globalread instructions if dtv and TN cases. (along coalesced dim)
404 if state["ScheduleIterAlg"] == 3:
405 state["reorderGRInstForDTVA"] = True if state["ProblemType"]["TransposeA"] and \
406 state["DirectToVgprA"] and \
407 not state["ProblemType"]["SwizzleTensorA"] else False
408 state["reorderGRInstForDTVB"] = True if not state["ProblemType"]["TransposeB"] and \
409 state["DirectToVgprB"] and \
410 not state["ProblemType"]["SwizzleTensorB"] else False
411 else:
412 state["reorderGRInstForDTVA"] = False
413 state["reorderGRInstForDTVB"] = False
414
415 state["UsePLRPack"] = False
416 state["SwapGlobalReadOrder"] = False
417 state["MfmaInitCVgprs"] = False
418
419 hasCMS,_ = hasCustomSchedule(state)
420 state["UseCustomMainLoopSchedule"] = hasCMS
421
422 # done
423 state["AssignedProblemIndependentDerivedParameters"] = True
424
425 ########################################
426 # This is the "classic" algorithm which requires that each threads load the same number of bytes
427 # Called with tc=A and then with tc=B
428 # totalVectors is totalElements/GRVW, this is #vectors loaded by the LoadTile
429 # Reduces the GlobalReadVectorWidth if necessary if each thread has a small amount of work to do.
430 # Output from this function:
431 # state[GlobalReadVectorWidth*]
432 # state[NumLoads*] # only used in SolutionStructs, with classic alg
433 @staticmethod
434 def setGlobalReadVectorWidth(state, tc, totalVectors, grvw, printRejectionReason: bool):
435 validDepthU = True
436 if grvw not in [1,2,4,8,16,32]:
437 validDepthU = False
438 if totalVectors % state["NumThreads"] != 0:
439 reject(None, printRejectionReason, "totalVectors%s %u %% NumThreads %u != 0" \
440 % (tc, totalVectors, state["NumThreads"]))
441 validDepthU = False
442
443 state["GlobalReadVectorWidth%s"%tc] = grvw
444
445 # NumLoads is NOT used on the fractional path
446 # NumLoads is number of vector loads per-thread
447 state["NumLoads%s"%tc] = totalVectors // state["NumThreads"]
448 #print "result: ", pvar(state, "GlobalReadVectorWidth%s"%tc), \
449 # pvar(state, "NumLoads%s"%tc)
450
451 return validDepthU
452
453 ########################################
454 # Sets the Global Read Tile dims (para, perp)
455 # This information controls which threads read which addresses from global mem)
456 # Output from this function:
457 # state[NumLoadsCoalescedA]
458 # state[NumLoadsPerpendicularA]
459 # state[LSCA]
460 # state[LSPA]
461 @staticmethod
462 def setGlobalLoadTileDimClassic(state, tc, numLoads, totalVectorsCoalesced, totalElementsPerp, depthU, printRejectionReason: bool):
463
464 if state["WaveSeparateGlobalRead%s"%tc]:
465 totalElementsPerp = roundupRatio(totalElementsPerp, state["NumThreads"] // state["WavefrontSize"])
466
467 if (tc == "A" or tc == "B") and state["enableGLTr%s"%tc]:
468 totalVectorsCoalesced, totalElementsPerp = totalElementsPerp, totalVectorsCoalesced
469
470 # nlc = 1
471 if state["NumLoadsCoalesced%s"%tc] == 1:
472 foundValid = False
473 nlcStart = 1
474 if (tc == "A" or tc == "B") and state["DirectToVgpr%s"%tc]:
475 # adjust nlc for DirectToVgprA/B
476 if state["ProblemType"]["TLU%s"%tc] and not state["enableGLTr%s"%tc]:
477 nlcStart = roundupRatio(state["MIWaveTile%s"%tc], state["GlobalReadVectorWidth%s"%tc])
478 else:
479 nlcStart = roundupRatio(depthU, state["MatrixInstK"] * state["GlobalReadVectorWidth%s"%tc] * state["LocalSplitU"] // state["MIInputPerThread"])
480 for nlc in range(nlcStart, int(state["NumLoads%s"%tc]+1)):
481 nlp = state["NumLoads%s"%tc] // nlc
482 if state["NumLoads%s"%tc] % nlc == 0 \
483 and totalVectorsCoalesced % nlc == 0 \
484 and totalElementsPerp % nlp == 0:
485 state["NumLoadsCoalesced%s"%tc] = nlc
486 state["NumLoadsPerpendicular%s"%tc] = nlp
487 # print("NumLoads%s:"%tc,state["NumLoads%s"%tc])
488 # print("NumLoadsCoalesced%s:"%tc,state["NumLoadsCoalesced%s"%tc])
489 # print("NumLoadsPerpendicular%s:"%tc,state["NumLoadsPerpendicular%s"%tc])
490 # print("\n")
491 foundValid = True
492 break
493 if not foundValid:
494 reject(state, printRejectionReason, "%s: No NumLoadsCoalesced=1 found"%tc)
495 return False
496
497 # nlc = -1
498 elif state["NumLoadsCoalesced%s"%tc] == -1:
499 foundValid = False
500 for nlc in range(state["NumLoads%s"%tc], 0, -1):
501 nlp = state["NumLoads%s"%tc] // nlc
502 if state["NumLoads%s"%tc] % nlc == 0 \
503 and totalVectorsCoalesced % nlc == 0 \
504 and totalElementsPerp % nlp == 0:
505 state["NumLoadsCoalesced%s"%tc] = nlc
506 state["NumLoadsPerpendicular%s"%tc] = nlp
507 foundValid = True
508 break
509 if not foundValid:
510 reject(state, printRejectionReason, "%s: No NumLoadsCoalesced=-1 found"%tc)
511 return False
512
513 # nlc = other
514 else:
515 if state["NumLoadsCoalesced%s"%tc] > state["NumLoads%s"%tc]:
516 reject(state, printRejectionReason, "%s nlc > numLoads"%tc)
517 return False
518
519 state["NumLoadsPerpendicular%s"%tc] = state["NumLoads%s"%tc] \
520 // state["NumLoadsCoalesced%s"%tc]
521
522 if state["NumLoads%s"%tc] % state["NumLoadsCoalesced%s"%tc] != 0:
523 reject(state, printRejectionReason, "%s: numLoads %u %% numLoadsCoalesced %u != 0" \
524 % (tc, state["NumLoads%s"%tc], state["NumLoadsCoalesced%s"%tc]))
525 return False
526
527 if totalVectorsCoalesced % state["NumLoadsCoalesced%s"%tc] != 0 :
528 reject(state, printRejectionReason, "%s: totalVectorsCoalesced %u %% numLoadsPara %u != 0" \
529 % (tc, totalVectorsCoalesced, state["NumLoadsCoalesced%s"%tc]))
530 return False
531 if totalElementsPerp % state["NumLoadsPerpendicular%s"%tc] != 0:
532 reject(state, printRejectionReason, "%s: totalElementsPerp %u %% numLoadsPerp %u != 0" \
533 % (tc, totalElementsPerp, state["NumLoadsPerpendicular%s"%tc]))
534 return False
535
536 if (tc == "A" or tc == "B") and state["enableGLTr%s"%tc]:
537 state["NumLoadsCoalesced%s"%tc], state["NumLoadsPerpendicular%s"%tc] = state["NumLoadsPerpendicular%s"%tc], state["NumLoadsCoalesced%s"%tc]
538
539 if state["ProblemType"]["TLU%s"%tc]:
540 state["LSC%s"%tc] = state["MacroTile%s"%tc] // state["NumLoadsCoalesced%s"%tc]
541 state["LSP%s"%tc] = int(math.ceil(float(depthU) / state["NumLoadsPerpendicular%s"%tc]))
542 else:
543 state["LSC%s"%tc] = int(math.ceil(float(depthU) / state["NumLoadsCoalesced%s"%tc]))
544 state["LSP%s"%tc] = state["MacroTile%s"%tc] // state["NumLoadsPerpendicular%s"%tc]
545
546 if state["WaveSeparateGlobalRead%s"%tc] == 1:
547 state["LSP%s"%tc] = roundupRatio(state["LSP%s"%tc], state["NumThreads"] // state["WavefrontSize"])
548 elif state["WaveSeparateGlobalRead%s"%tc] == 2:
549 state["LSP%s"%tc] = state["NumThreads"] // state["WavefrontSize"]
550
551 return True
552
553
554
555
556 ##############################################
557 # check and calculate Wave Separate Global Read
558 @staticmethod
559 def checkAndAssignWaveSeparateGlobalRead(state, tc, printRejectionReason: bool):
560 # check can we use WaveSeparateGlobalRead
561 numOfWaves = state["NumThreads"] // state["WavefrontSize"]
562 if state["WaveSeparateGlobalRead%s"%tc]:
563 if state["ProblemType"]["TLU%s"%tc] and (state["_DepthU%s"%tc] > 0) and (state["_DepthU%s"%tc] % numOfWaves != 0):
564 reject(state, printRejectionReason, "didn't support WaveSeparateGlobalRead when DepthU is not multiple of wave %u in TLU%s" % (state["_DepthU%s"%tc], tc))
565 if not state["ProblemType"]["TLU%s"%tc] and (state["MacroTile%s" % tc] % numOfWaves != 0):
566 reject(state, printRejectionReason, "didn't support WaveSeparateGlobalRead when MacroTile is not multiple of wave %u in TLU%s" % (state["MacroTile%s"%tc], tc))
567
568
569 ########################################
570 # determine can we use VgprForLocalReadPacking
571 @staticmethod
572 def isVgprForLocalReadPackingDoable(state, isaInfoMap: Dict[str, IsaInfo]):
573 isa = tuple(state["ISA"])
574 doable = True
575 # MatrixInstruction only
576 if not state["EnableMatrixInstruction"]:
577 doable = False
578 # only for HasEccHalf
579 if not isaInfoMap[isa].archCaps["HasEccHalf"]:
580 doable = False
581 # only for PLR>=1 (except for DTVA+B)
582 if state["PrefetchLocalRead"] < 1 and not (state["DirectToVgprA"] and state["DirectToVgprB"]):
583 doable = False
584 # only for 1 or 2 byte input (numRegister < 1)
585 if state["ProblemType"]["DataType"].numRegisters() >= 1:
586 doable = False
587 return doable
588
589 ########################################
590 # determine if current datatype can support DirectToVgpr
591 @staticmethod
592 def isDirectToVgprSupportDataType(state):
593 return (state["ProblemType"]["DataType"].isSingle() or state["ProblemType"]["DataType"].isDouble() or state["ProblemType"]["DataType"].isComplex() or \
594 state["ProblemType"]["DataType"].isHalf() or state["ProblemType"]["DataType"].isBFloat16() or state["ProblemType"]["DataType"].isInt8()) or \
595 state["ProblemType"]["DataType"].is8bitFloat()
596
597 ########################################
598 # determine can we use DirectToVgpr
599 @staticmethod
600 def isDirectToVgprDoable(state, tc, printRejectionReason: bool, isaInfoMap: Dict[str, IsaInfo]):
601 numBytes = state["ProblemType"]["DataType"].numBytes()
602 numBytesGR = state["ProblemType"]["DataType%s"%tc].numBytes()
603 isSwizzle = state["ProblemType"]["SwizzleTensor%s"%tc]
604
605 # With MatrixInstruction only
606 if not state["EnableMatrixInstruction"] :
607 reject(state, printRejectionReason, "DirectToVgpr is for MatrixInstruction only")
608 return False
609
610 # disable the following combinations for initial implementation
611 # TODO: enable them (for pure DTV)
612 if (state["LocalSplitU"] != 1) and (not state["ProblemType"]["TLU%c"%tc]) and (not isSwizzle):
613 reject(state, printRejectionReason, "Non-Swizzled DirectToVgpr + LSU + TLU=False has not been enabled yet(tentative)")
614 return False
615
616 if state["DirectToVgprA"] and state["DirectToVgprB"]:
617 # change the following parameter values
618 state["PrefetchGlobalRead"] = 1
619 state["ExpandPointerSwap"] = 0
620 state["1LDSBuffer"] = 0
621 state["PrefetchLocalRead"] = 0
622 # So far, DTVA + DTVB does not perform well (waitcnt is not ideal).
623 # Disable it for now (TODO: improve waitcnt and re-enable)
624 # Exception: allow if enableGLTrA or enableGLTrB are set; this still provides better performance than enabling only one side
625 if not (state["enableGLTrA"] or state["enableGLTrB"]):
626 reject(state, printRejectionReason, "DirectToVgprA + DirectToVgprB disabled")
627 return False
628
629 # DTV + input type conversion
630 if state["ProblemType"]["DataType%s"%tc] != state["ProblemType"]["DataType"]:
631 if not state["ConvertAfterDS"]:
632 reject(state, printRejectionReason, "DirectToVgpr%s + input conversion + ConvertAfterDS=False not supported"%(tc))
633 return False
634
635 # check if the DataType can support DirectToVgpr
636 if not Solution.isDirectToVgprSupportDataType(state):
637 reject(state, printRejectionReason, "no DirectToVgpr support for this input data type")
638 return False
639
640 # Does not work with TLU = False and PrefetchLocalRead = 0
641 if (not state["ProblemType"]["TLU%c"%tc]) and state["PrefetchLocalRead"] == 0 and not (state["DirectToVgprA"] and state["DirectToVgprB"]):
642 reject(state, printRejectionReason, "DirectToVgpr%c does not supports TLU%c = False and PrefetchLocalRead = 0"%(tc, tc))
643 return False
644
645 # Does not work with TLU = False and CGEMM/DGEMM/DGEMM (not supported)
646 if (not state["ProblemType"]["TLU%c"%tc]) and (state["ProblemType"]["DataType"].isDouble() or \
647 state["ProblemType"]["DataType"].isComplex()):
648 reject(state, printRejectionReason, "DirectToVgpr%c does not supports TLU%c = False + S/C/D/ZGEMM"%(tc, tc))
649 return False
650
651 if numBytesGR * state["GlobalReadVectorWidth%c"%tc] < 4:
652 # no support for DTV + numBytesGR * GlobalReadVectorWidth< 4
653 reject(state, printRejectionReason, "DirectToVgpr%c does not support TLU%c + numByte * GlobalReadVectorWidth%c < 4"%(tc, tc, tc))
654 return False
655
656 if numBytes < 4:
657 # numBytes < 4 case
658 if state["ProblemType"]["TLU%c"%tc] and not state["enableGLTr%c"%tc]:
659 # use pack logic (with v_perm) same as local read (only if VgprForLocalReadPacking is doable)
660 if not Solution.isVgprForLocalReadPackingDoable(state, isaInfoMap):
661 reject(state, printRejectionReason, "Does not meet the requirement for DirectToVgpr%c + TLU%c + numByte < 4"%(tc, tc))
662 return False
663 # force ClusterLocalRead=1 for DTV + pack
664 state["ClusterLocalRead"] = 1
665 else:
666 # numBytes >= 4 case
667 if state["ProblemType"]["TLU%c"%tc] and state["MIInputPerThread"] > 1:
668 # no support for numBytes >= 4 + MIInputPerThread > 1
669 reject(state, printRejectionReason, "DirectToVgpr%c does not support TLU%c+ numByte >= 4 + MIInputPerThread > 1"%(tc, tc))
670 return False
671
672 # MatrixInstBM,BN check
673 # for A, MatrixInstBN should be 1
674 # for B, MatrixInstBM should be 1
675 # This is to limit the number of Vgpr
676 if tc == 'A' and not (state['MatrixInstBN'] == 1):
677 reject(state, printRejectionReason, "MatrixInstBN should be 1 for DirectToVgprA. Current value is %d"%(state['MatrixInstBN']))
678 return False
679 if tc == 'B' and not (state['MatrixInstBM'] == 1):
680 reject(state, printRejectionReason, "MatrixInstBM should be 1 for DirectToVgprB. Current value is %d"%(state['MatrixInstBM']))
681 return False
682
683 # Does not work with WaveSeparateGlobalRead
684 if state["WaveSeparateGlobalRead%c"%tc]:
685 reject(state, printRejectionReason, "DirectToVgpr%c does not supports WaveSeparateGlobalRead%c"%(tc, tc))
686 return False
687
688 # Does not work with TLU + VectorWidth != GlobalReadVectorWidth (VW = 2 + GRVW = 1 or VW = 1 + GRVW = 2 does not work)
689 if state["ProblemType"]["TLU%c"%tc] and (state["VectorWidth%s"%tc] != state["GlobalReadVectorWidth%c"%tc]) and (not state["enableGLTr%s"%tc]):
690 reject(state, printRejectionReason, "DirectToVgpr%c does not supports TLU + VectorWidth%s(=%u) != GlobalReadVectorWidth%c(%u)"%(tc, tc, state["VectorWidth%s"%tc], tc, state["GlobalReadVectorWidth%c"%tc]))
691 return False
692
693 # Does not work with TLU=False and NumLoadsCoalesced != DepthU//(MatrixInstK*GRVW*LSU//MIInputPerThread)
694 if (not state["ProblemType"]["TLU%c"%tc]) and \
695 state["NumLoadsCoalesced%c"%tc] != state["DepthU"] // (state["MatrixInstK"] * state["GlobalReadVectorWidth%c"%tc] * state["LocalSplitU"] // state["MIInputPerThread"]):
696 reject(state, printRejectionReason, "DirectToVgpr%c does not supports TLU=False and NumLoadsCoalesced%c != DepthU//(MatrixInstK*GlobalReadVectorWidth*LocalSplitU//MIInputPerThread(=%u))"%(tc, tc, state["MIInputPerThread"]))
697 return False
698
699 # Does not work with enableGLTr and GRVW != 8
700 if state["enableGLTr%c"%tc] and state["GlobalReadVectorWidth%c"%tc] != 8:
701 reject(state, printRejectionReason, "DirectToVgpr%c does not supports enableGLTr%c and GlobalReadVectorWidth != 8"%(tc, tc))
702 return False
703
704 # TLU=False case, need GlobalReadVectorWidth == LocalReadVectorWidth
705 if (not state["ProblemType"]["TLU%c"%tc]) and \
706 state["GlobalReadVectorWidth%c"%tc] != state["LocalReadVectorWidth"]:
707 reject(state, printRejectionReason, "DirectToVgpr%c does not supports TLU=False GlobalReadVectorWidth%c(%u) != LocalReadVectorWidth(%u)"%(tc, tc, state["GlobalReadVectorWidth%c"%tc], state["LocalReadVectorWidth"]))
708 return False
709
710 # Does not work with SIA<3
711 if state["ScheduleIterAlg"] < 3:
712 reject(state, printRejectionReason, "DirectToVgpr%c does not supports ScheduleIterAlg < 3"%(tc))
713 return False
714
715 # Does not work with InnerUnroll>1
716 if state["InnerUnroll"]>1:
717 reject(state, printRejectionReason, "DirectToVgpr%c does not supports InnerUnroll>1"%(tc))
718 return False
719
720 # Reject TLU = UnrollMajorLDS
721 if state["ProblemType"]["TLU%c"%tc] == state["UnrollMajorLDS%c"%tc]:
722 reject(state, printRejectionReason, "DirectToVgpr%c does not supports TLU%c = UnrollMajorLDS%c"%(tc, tc, tc))
723 return False
724
725 # does not work with UnrollLoopSwapGlobalReadOrder
726 if state["UnrollLoopSwapGlobalReadOrder"]:
727 reject(state, printRejectionReason, "DirectToVgpr%c does not supports UnrollLoopSwapGlobalReadOrder"%(tc))
728 return False
729
730 # does not work with PGR2 + EPS
731 if state["PrefetchGlobalRead"] == 2 and state["ExpandPointerSwap"]:
732 # force EPS=0 and continue
733 state["ExpandPointerSwap"] = 0
734
735 # does not work with Sparse
736 if state["ProblemType"]["Sparse"]:
737 reject(state, printRejectionReason, "DirectToVgpr%c does not supports Sparse"%(tc))
738 return False
739
740 # for DTVA/DTVB, does not work with PGR0
741 if state["PrefetchGlobalRead"] == 0:
742 reject(state, printRejectionReason, "DirectToVgpr%c does not supports PrefetchGlobalRead == 0."%(tc))
743 return False
744
745 # for DTVA, does not work with NN and TLDS0
746 if tc == 'A' and state["TransposeLDS"] == 0 and (not state["ProblemType"]["TransposeA"] and not state["ProblemType"]["TransposeB"]):
747 reject(state, printRejectionReason, "DirectToVgpr%c does not supports NN case with TransposeLDS == 0."%(tc))
748 return False
749
750 # for DTVA, does not work with TT and Tail-loop
751 if tc == 'A' and (state["ProblemType"]["TransposeA"] and state["ProblemType"]["TransposeB"]):
752 # Use AssertSummationElementMultiple (BoundSizeMultiple in predicates) to exclude failed tail-loop cases
753 state["AssertSummationElementMultiple"] = max(state["AssertSummationElementMultiple"], state["DepthU"])
754
755 # for DTVB, does not work with NN and Tail-loop
756 if tc == 'B' and (not state["ProblemType"]["TransposeA"] and not state["ProblemType"]["TransposeB"]):
757 # Use AssertSummationElementMultiple (BoundSizeMultiple in predicates) to exclude failed tail-loop cases
758 state["AssertSummationElementMultiple"] = max(state["AssertSummationElementMultiple"], state["DepthU"])
759
760 # Does not work with DirectToLDS
761 # -> this will be checked after DirectToLDS doable check is done
762
763 return True
764
765 ########################################
766 # determine can we use DirectToLds
767 @staticmethod
768 def isDirectToLdsDoable(state, tc, isaInfoMap, printRejectionReason: bool):
769
770 numBytes = state["ProblemType"]["DataType"].numBytes()
771 isa = state["ISA"]
772
773 # x4 support for directToLds
774 canDTLx4 = isaInfoMap[isa].asmCaps["HasDirectToLdsx4"]
775
776 # numelements_perlane = 4/numBytes
777 # TN with transposeLDS feature should work as long as state["AssertSummationElementMultiple"] % (numelements_perlane*2) = 0
778 # state["AssertSummationElementMultiple"] % (numelements_perlane*4) = 0
779
780 #NT
781 # use only for f32 & DGEMM and TLU = 1
782 #TN
783 # use for all precisions with TransposeLDS=1
784
785 numBytesAB = state["ProblemType"]["DataType%s"%tc].numBytes()
786 numBytesPerLoad = state["GlobalReadVectorWidth%s"%tc] * numBytesAB
787
788 MT = state["MacroTile0"] if tc == 'A' else state["MacroTile1"]
789
790 if (MT & (MT-1)) != 0: # Check of MT not power of 2
791 # so far, numBytesAB<4 case, TLU=False only (continue with False)
792 if (numBytesAB < 4 or state["UseF32XEmulation"]) and state["ProblemType"]["TLU%c"%tc]:
793 return False
794
795 # x2 DTL is not supported
796 if numBytesPerLoad == 8:
797 printWarning("can't use DirectToLds with b64 buffer load, using non DirectToLds version instead")
798 return False
799
800 if numBytesPerLoad == 16 and not canDTLx4:
801 reject(state, printRejectionReason, "b128 DirectToLds not supported")
802 return False
803
804 if numBytesPerLoad < 4:
805 reject(state, printRejectionReason, "DirectToLds not supported for loads less than 32bits")
806 return False
807
808 # so far MFMA only (TODO: enable non MFMA case)
809 if not state["EnableMatrixInstruction"]:
810 reject(state, printRejectionReason, "DirectToLds is for MatrixInstruction only for now (tentative)")
811 return False
812
813 # ToDo: Review def of lrvw and this check
814 # DTL + LocalReadVectorWidth > MIInputPerThread does not work
815 # Need support for TailLoop
816 if not state["ProblemType"]["Sparse"] and not(state["ProblemType"]["DataType"].is8bitFloat() and (state["MatrixInstK"] == 64 or state["MatrixInstK"] == 128)):
817 if state["LocalReadVectorWidth"] > state["MIInputPerThread"]:
818 reject(state, printRejectionReason, "DirectToLds does not work with LocalReadVectorWidth > MIInputPerThread")
819 return False
820
821 if state["NumThreads"] % state["WavefrontSize"] != 0:
822 reject(state, printRejectionReason, "can't use DirectToLds for NumThreads % WavefrontSize != 0")
823 return False
824
825 if state["ProblemType"]["TLU%c"%tc] == state["UnrollMajorLDS%c" % tc]:
826 reject(state, printRejectionReason, "can't use DirectToLds for TLU%c == UnrollMajorLDS%c"%(tc, tc))
827 return False
828
829 # avoid picking x2&x4 for precisions < f32/f64 in [ProblemType][TLU] == TRUE
830 if not state["EnableMatrixInstruction"]:
831 if state["GlobalReadVectorWidth%c"%tc] * numBytesAB * state["WavefrontSize"] > 256:
832 reject(state, printRejectionReason, "can't use DirectToLds for not EnableMatrixInstruction and GlobalReadVectorWidth%c * bpe%c * WavefrontSize > 256"%(tc,tc))
833 return False
834
835 if state["WaveSeparateGlobalRead%c" % tc]:
836 if state["LSC%c"%tc] * state["LSP%c"%tc] * numBytesAB != state["WavefrontSize"] * state["GlobalReadVectorWidth%c"%tc] * numBytesAB:
837 reject(state, printRejectionReason, "can't use DirectToLds for LSC%c and LSP%c * bpe!= WavefrontSize * GlobalReadVectorWidth%c * bpe%c > 4"%(tc, tc, tc, tc))
838 return False
839 else:
840 if state["LSC%c"%tc] * state["LSP%c"%tc] * numBytesAB != state["NumThreads"] * state["GlobalReadVectorWidth%c"%tc] * numBytesAB:
841 reject(state, printRejectionReason, "can't use DirectToLds for LSC%c and LSP%c * bpe != NumThreads * GlobalReadVectorWidth%c * bpe%c > 4"%(tc, tc, tc, tc))
842 return False
843
844 # so far, DirectToLds does not work with LRVW=2
845 if state["LocalReadVectorWidth"] == 2:
846 reject(state, printRejectionReason, "can't use DirectToLds for LocalReadVectorWidth == 2")
847 return False
848
849 # Does not work with (NumLoadsCoalesced>1 and UseInstOffsetForGRO) + DGEMM
850 if state["ProblemType"]["DataType"].isDouble() and \
851 (state["NumLoadsCoalesced%c"%tc] > 1 and state["UseInstOffsetForGRO"]):
852 reject(state, printRejectionReason, "DirectToLds%c does not supports NumLoadsCoalesced%c > 1 and UseInstOffsetForGRO for dgemm"%(tc, tc))
853 return False
854
855 # Does not work with NumLoadsCoalesced>1 + ZGEMM
856 if state["ProblemType"]["DataType"].isDoubleComplex() and state["NumLoadsCoalesced%c"%tc] > 1:
857 reject(state, printRejectionReason, "DirectToLds%c does not supports NumLoadsCoalesced%c > 1 for zgemm"%(tc, tc))
858 return False
859
860 # DirectToLds does not work with TLU=False and bpe > bpr and DepthU//NumLoadsCoalesced < 8
861 # bpe > bpr case, Lower and upper 4 bytes elements are stored separately.
862 # if TLU=False and DepthU//NumLoadsCoalesced is smaller than lower block size (8 elements),
863 # current offset swap logic does not work
864 if (not state["ProblemType"]["TLU%c"%tc]) and state["ProblemType"]["DataType"].numRegisters() > 1 and \
865 state["_DepthU%s"%tc] // state["NumLoadsCoalesced%c"%tc] < 8:
866 reject(state, printRejectionReason, "DirectToLds%c does not work with TLU=False and bpe > bpr and DepthU//NumLoadsCoalesced%c < 8"%(tc, tc))
867 return False
868
869 # TODO: Currently DTL with input types of different size is not support. There are functional issues
870 # This needs to be fixed.
871 if state["ProblemType"]["DataType%s"%tc].numBytes() != state["ProblemType"]["DataType"].numBytes():
872 reject(state, printRejectionReason, "DirectToLds%s with conversion to different sized data types is not supported"%tc)
873 return False
874
875 # DTL + input type conversion
876 if state["ProblemType"]["DataType%s"%tc] != state["ProblemType"]["DataType"]:
877 if not state["ConvertAfterDS"]:
878 reject(state, printRejectionReason, "DirectToLds%s + input conversion + ConvertAfterDS=False not supported"%(tc))
879 return False
880
881 return True
882
883 @staticmethod
884 def getDivisorName(state, tC):
885 if state["GlobalReadCoalesceGroup{}".format(tC)]:
886 if state["GlobalReadCoalesceVector{}".format(tC)]:
887 divisorName = "LVC{}".format(tC)
888 else:
889 # Fractional load use the more accurate lsc, multiply by VW later
890 divisorName = "LSC{}".format(tC)
891 else:
892 if state["GlobalReadCoalesceVector{}".format(tC)]:
893 divisorName = "LSP{}".format(tC)
894 else:
895 divisorName = "LVP{}".format(tC)
896 return divisorName
897
898 ########################################
899 # assign all derived parameters
900 @staticmethod
901 def assignDerivedParameters(
902 state,
903 splitGSU: bool,
904 printRejectionReason: bool,
905 printIndexAssignmentInfo: bool,
906 isaInfoMap,
907 rocmVersion: SemanticVersion
908 ):
909 isa = tuple(state["ISA"])
910
911 if state["MaxLDS"] == -1:
912 state["MaxLDS"] = isaInfoMap[isa].archCaps["DeviceLDS"]
913
914 # NOTE: This entry should instead should already be set on the solution within the logic
915 # files. This code will be removed once all logic files are updated to contain both
916 # the keys "EnableF32XdlMathOp" and "F32XdlMathOp".
917 state["EnableF32XdlMathOp"] = False
918 state["UseF32XEmulation"] = False #enable emulation for missing hardware support
919 state["UseDot2F32XEmulation"] = True
920 #ignore the F32 xDL MathOp by default.
921 #enable F32 xDL MathOp only when the input type is f32.
922 if "F32XdlMathOp" in state["ProblemType"] \
923 and (not state["ProblemType"]["F32XdlMathOp"].isSingle()) \
924 and (state["ProblemType"]["DataType"].isSingle()):
925 state["EnableF32XdlMathOp"] = True
926 if isaInfoMap[isa].archCaps["HasF32XEmulation"]:
927 state["UseF32XEmulation"] = True
928
929 # initial info to be exported for solution prediction
930 state["CUOccupancy"] = -1
931 state["MathClocksUnrolledLoop"] = 0
932
933 Solution.assignProblemIndependentDerivedParameters(state, printRejectionReason, isaInfoMap)
934
935 if "AssignedDerivedParameters" in state:
936 if state["AssignedDerivedParameters"]:
937 return
938 state["AssignedDerivedParameters"] = False
939
940 for s in Solution.InternalKeys:
941 if '_'+s not in state:
942 state['_'+s] = state[s]
943 #del state[s]
944
945 # Force update _GlobalAccumulation
946 computeBytes = state["ProblemType"]["ComputeDataType"].numBytes()
947 state["_GlobalAccumulation"] = None
948 computeName = state["ProblemType"]["ComputeDataType"].toName()
949 if state["StreamK"] > 0 and state["StreamKAtomic"] == 0:
950 # StreamK Workspace size
951 state["_GlobalAccumulation"] = 'PartialsBuffer'
952 elif state["GlobalSplitUAlgorithm"] == 'SingleBuffer':
953 if computeName != state["ProblemType"]["DestDataType"].toName():
954 state["_GlobalAccumulation"] = 'SingleBuffer'
955 elif state["GlobalSplitUAlgorithm"] == 'MultipleBuffer':
956 state["_GlobalAccumulation"] = 'MultipleBuffer'
957 elif state["GlobalSplitUAlgorithm"] == 'MultipleBufferSingleKernel':
958 if (not splitGSU):
959 state["_GlobalAccumulation"] = 'MultipleBufferSingleKernel'
960 else:
961 if state["GlobalSplitU"] > 1 or state["GlobalSplitU"] == -1:
962 state["_GlobalAccumulation"] = 'MultipleBufferSingleKernel'
963
964 if state["_GlobalAccumulation"] == 'MultipleBufferSingleKernel':
965 state["SynchronizerSizeCheck"] = 1
966 # state["BatchSizeEqual"] = 1
967
968 if state["StreamK"] == 0 and state["GlobalSplitU"] == 0:
969 reject(state, printRejectionReason, "Either GSU or StreamK must be enabled")
970 return
971
972 if state["StreamK"] != 0:
973 state["GlobalSplitU"] = 0 # Cannot enable both Stream-K and GSU
974 state["InternalSupportParams"]["SupportUserGSU"] = False # Disable UserGSU for Stream-K
975 state["GlobalSplitUAlgorithm"] = "MultipleBuffer" # Set default Algorithm
976 if not state["EnableMatrixInstruction"]:
977 reject(state, printRejectionReason, "Stream-K requires MatrixInstruction")
978 if isaInfoMap[isa].asmCaps["HasWMMA"]:
979 reject(state, printRejectionReason, "Stream-K untested with WMMA")
980 # if state["PersistentKernel"]:
981 # reject(state, printRejectionReason, "Cannot enable both Stream-K and PersistentKernel")
982 if not state["ProblemType"]["StridedBatched"]:
983 reject(state, printRejectionReason, "General batch not supported with Stream-K")
984 if state["ProblemType"]["GroupedGemm"]:
985 reject(state, printRejectionReason, "Grouped gemm not yet supported with Stream-K")
986 if state["ScheduleGlobalRead"] != 1:
987 reject(state, printRejectionReason, "ScheduleGlobalRead not supported with Stream-K")
988 if state["ScheduleLocalWrite"] != 1:
989 reject(state, printRejectionReason, "ScheduleLocalWrite not supported with Stream-K")
990 if state["ScheduleIterAlg"] != 2 and state["ScheduleIterAlg"] != 3:
991 reject(state, printRejectionReason, "ScheduleIterAlg not supported with Stream-K")
992 if state["StreamKAtomic"] == 1:
993 if not state["ProblemType"]["DataType"].isSingle():
994 reject(state, printRejectionReason, "Atomic Stream-K currently only tested for SGEMM")
995 if not state["BufferStore"]:
996 reject(state, printRejectionReason, "Atomic Stream-K requires BufferStore")
997 if state["LocalSplitU"] > 1:
998 reject(state, printRejectionReason, "Atomic Stream-K not working with LocalSplitU")
999 if not state["Valid"]:
1000 print2("in assignDerivedParameters, state['Valid'] = False")
1001 return
1002 else:
1003 # If not using StreamK, clear other stream-k settings to avoid duplicate kernels
1004 state["StreamKAtomic"] = 0
1005 state["StreamKXCCMapping"] = 0
1006 state["DebugStreamK"] = 0
1007
1008 computeBytes = state["ProblemType"]["ComputeDataType"].numBytes()
1009 state["_WorkspaceSizePerElemC"] = computeBytes
1010 state["_WorkspaceSizePerElemBias"] = 0
1011 if state["ProblemType"]["UseBias"] and state["ProblemType"]["Gradient"]:
1012 state["_WorkspaceSizePerElemBias"] = computeBytes
1013
1014 state["WorkspaceCheck"] = [state["_WorkspaceSizePerElemC"], state["_WorkspaceSizePerElemBias"], state["GlobalSplitU"] if (state["GlobalSplitUAlgorithm"] == 'MultipleBuffer' or state["_GlobalAccumulation"] == 'MultipleBufferSingleKernel') else 1]
1015
1016 if state["VectorStore"] == -1:
1017 state["_VectorStore"] = 1 # default, may be changed if needed to generate a valid kernel
1018
1019 ProblemType.assignDerivedParameters(state["ProblemType"], printIndexAssignmentInfo)
1020 if not state["Valid"]:
1021 print2("in assignDerivedParameters, state['Valid'] = False")
1022 return
1023
1024 if not isaInfoMap[isa].asmCaps["HasNTModifier"]:
1025 # force to disable nt flag if it is not supported by arch
1026 for ch in ["", "A", "B", "C", "D", "E", "WS", "Metadata"]:
1027 if state["NonTemporal%s"%ch] >= 4:
1028 state["NonTemporal%s"%ch] -= 4
1029
1030 if state["WavefrontSize"] == 32 and not isaInfoMap[isa].archCaps["HasWave32"]:
1031 reject(state, printRejectionReason, "WavefrontSize=32 not supported for ISA {}".format(isa))
1032 return
1033
1034 if state["WavefrontSize"] == 32 and state["KernelLanguage"] == "Source":
1035 reject(state, printRejectionReason, "WavefrontSize=32 not yet supported for source kernels.")
1036 return
1037
1038 if state["EnableMatrixInstruction"]:
1039 if not (isaInfoMap[isa].asmCaps["HasMFMA"] or isaInfoMap[isa].asmCaps["HasWMMA"]):
1040 reject(state, printRejectionReason, f"isa {isa} doesn't support matrix instruction")
1041 return
1042 if not (state["ProblemType"]["DataType"].isSingle() \
1043 or state["ProblemType"]["DataType"].isDouble() \
1044 or state["ProblemType"]["DataType"].isBFloat16() \
1045 or state["ProblemType"]["DataType"].isHalf() \
1046 or state["ProblemType"]["DataType"].isComplex() \
1047 or state["ProblemType"]["DataType"].is8bitFloat() \
1048 or state["ProblemType"]["DataType"].isInt8()):
1049 reject(state, printRejectionReason, "didn't support Matrix Instruction with type %s" % str(state["ProblemType"]["DataType"]))
1050 return
1051 if (not isaInfoMap[isa].asmCaps["HasMFMA"] and isaInfoMap[isa].asmCaps["HasWMMA"] and (state["WavefrontSize"] == 64)):
1052 print2("!! Warning: WMMA only well tune on WGP mode, wave size = 32")
1053 # reject(state, printRejectionReason, "WMMA only suppport on WGP mode, wave size = 32")
1054 # return
1055 if not state["MIBlock"] or len(state["MIBlock"]) != 6:
1056 reject(state, printRejectionReason, "invalid MIBlock")
1057 return
1058 if not state["MIWaveGroup"] or len(state["MIWaveGroup"]) != 2:
1059 reject(state, printRejectionReason, "invalid MIWaveGroup")
1060 return
1061 if not state["MIWaveTile"] or len(state["MIWaveTile"]) != 2:
1062 reject(state, printRejectionReason, "invalid MIWaveTile")
1063 return
1064 if isaInfoMap[isa].asmCaps["HasMFMA"]:
1065 if not state["ProblemType"]["HighPrecisionAccumulate"] \
1066 and state["ProblemType"]["DataType"].numRegisters() < 1 \
1067 and state["ProblemType"]["DataTypeA"].numRegisters() <= state["ProblemType"]["DataType"].numRegisters() \
1068 and state["ProblemType"]["DataTypeB"].numRegisters() <= state["ProblemType"]["DataType"].numRegisters():
1069 reject(state, printRejectionReason, "Matrix instructions for half, bf16 (or i8) types are natively accumulated" + \
1070 " in fp32 (or i32) precision. Please add the following config:" + \
1071 "\n - HighPrecisionAccumulate: True")
1072 return
1073 if isaInfoMap[isa].asmCaps["HasWMMA"]:
1074 if state["ProblemType"]["DataType"].numRegisters() >=1:
1075 reject(state, printRejectionReason, "WMMA only support half, bf16 and i8 type")
1076 return
1077 if state["InterleaveAlpha"]:
1078 reject(state, printRejectionReason, "Matrix instruction doesn't support InterleaveAlpha")
1079 return
1080 if state["ProblemType"]["DataType"].isInt8():
1081 if isa[:2] == (9, 4):
1082 if tuple(state["MatrixInstruction"])[:3] in ((32, 32, 8), (16, 16, 16)):
1083 reject(state, printRejectionReason, "v_mfma_i32_32x32x8 and v_mfma_i32_16x16x16 have been deprecated in gfx94x")
1084 return
1085 if state["ProblemType"]["ComputeDataType"].isDouble():
1086 # See [4,4,4,4] snop for more info
1087 if state["MatrixInstruction"] == [4,4,4,4] and (not state['ISA'] == IsaVersion(9,0,10)) and state["ScheduleIterAlg"] == 3:
1088 reject(state, printRejectionReason, "Currently Matrix instructions [4,4,4,4] is disabled.")
1089 return
1090 if state["UseF32XEmulation"]:
1091 if not isaInfoMap[isa].archCaps["HasF32XEmulation"]:
1092 reject(state, printRejectionReason, "Missing emulation for F32X")
1093 return
1094 if state["ScheduleIterAlg"] != 3:
1095 reject(state, printRejectionReason, "F32X Emulation only supported with Schedule Iter Alg == 3")
1096 return
1097 if tuple(state["MatrixInstruction"])[:3] in ((16, 16, 8), (16, 16, 16), (32, 32, 4)):
1098 reject(state, printRejectionReason, "tf32 emulation currently only supports mfma MI 16x16x32 and 32x32x16")
1099 return
1100
1101 else:
1102 if not state["ProblemType"]["HighPrecisionAccumulate"] \
1103 and state["ProblemType"]["ComputeDataType"].numRegisters() > state["ProblemType"]["DataType"].numRegisters() :
1104 reject(state, printRejectionReason, "For non-MI Kernel, if sizeof(ComputeDataType) > sizeof(DataType), " + \
1105 "Please add the following config:" + \
1106 "\n - HighPrecisionAccumulate: True")
1107 return
1108 if state["ProblemType"]["Sparse"]:
1109 reject(state, printRejectionReason, "Sparse A problem is only supported by SMFMA MI kernel.")
1110 return
1111
1112 if state["ThreadTile0"] > 16 or state["ThreadTile1"] > 16:
1113 reject(state, printRejectionReason, "Invalid value for ThreadTile")
1114 return
1115
1116 if state["ScheduleIterAlg"] == 2 or state["ScheduleIterAlg"] == 3:
1117 reject(state, printRejectionReason, "SIA2 and SIA3 only support MatrixInstruction")
1118 return
1119
1120 if state["ProblemType"]["Tensor0"]==0:
1121 state["ThreadTileA"] = state["ThreadTile0"]
1122 state["ThreadTileB"] = state["ThreadTile1"]
1123 state["SubGroupA"] = state["SubGroup0"]
1124 state["SubGroupB"] = state["SubGroup1"]
1125 state["MacroTileA"] = state["MacroTile0"]
1126 state["MacroTileB"] = state["MacroTile1"]
1127 if state["EnableMatrixInstruction"]:
1128 state["MIWaveTileA"] = state["MIWaveTile"][0]
1129 state["MIWaveTileB"] = state["MIWaveTile"][1]
1130 else:
1131 state["ThreadTileB"] = state["ThreadTile0"]
1132 state["ThreadTileA"] = state["ThreadTile1"]
1133 state["SubGroupB"] = state["SubGroup0"]
1134 state["SubGroupA"] = state["SubGroup1"]
1135 state["MacroTileB"] = state["MacroTile0"]
1136 state["MacroTileA"] = state["MacroTile1"]
1137 if state["EnableMatrixInstruction"]:
1138 state["MIWaveTileA"] = state["MIWaveTile"][1]
1139 state["MIWaveTileB"] = state["MIWaveTile"][0]
1140
1141 if state["ProblemType"]["Sparse"] == 2 and state["DirectToVgprSparseMetadata"]:
1142 reject(state, printRejectionReason, "Sparse B does not supprot DirectToVgprSparseMetadata")
1143 return
1144
1145
1146 if state["ProblemType"]["Sparse"]:
1147 state["LocalWriteUseSgprMetadata"] = False
1148 if state["ProblemType"]["Sparse"] == 2:
1149 if not state["DirectToVgprSparseMetadata"]:
1150 state["ThreadTileMetadata"] = state["ThreadTileB"]
1151 state["SubGroupMetadata"] = state["SubGroupB"]
1152 state["MacroTileMetadata"] = state["MacroTileB"]
1153 state["WaveSeparateGlobalReadMetadata"] = state["WaveSeparateGlobalReadB"]
1154 state["DirectToLdsMetadata"] = False
1155 state["ProblemType"]["MirrorDimsMetadata"] = list(state["ProblemType"]["MirrorDimsB"])
1156 state["VectorWidthMetadata"] = state["VectorWidthB"]
1157 if state["EnableMatrixInstruction"]:
1158 state["MIWaveTileMetadata"] = state["MIWaveTileB"]
1159 else:
1160 if not state["DirectToVgprSparseMetadata"]:
1161 state["ThreadTileMetadata"] = state["ThreadTileA"]
1162 state["SubGroupMetadata"] = state["SubGroupA"]
1163 state["MacroTileMetadata"] = state["MacroTileA"]
1164 state["WaveSeparateGlobalReadMetadata"] = state["WaveSeparateGlobalReadA"]
1165 state["DirectToLdsMetadata"] = False
1166 state["ProblemType"]["MirrorDimsMetadata"] = list(state["ProblemType"]["MirrorDimsA"])
1167 state["VectorWidthMetadata"] = state["VectorWidthA"]
1168 if state["EnableMatrixInstruction"]:
1169 state["MIWaveTileMetadata"] = state["MIWaveTileA"]
1170 elif not state["ProblemType"]["Sparse"]:
1171 state["DirectToVgprSparseMetadata"] = False
1172 state["MIWaveTileMetadata"] = 0
1173
1174 if state["NonTemporal"] != -1:
1175 state["NonTemporalA"] = state["NonTemporal"]
1176 state["NonTemporalB"] = state["NonTemporal"]
1177 state["NonTemporalC"] = state["NonTemporal"]
1178 state["NonTemporalD"] = state["NonTemporal"]
1179 state["NonTemporalMetadata"] = state["NonTemporal"]
1180
1181 # Init vars early since there are early-exit return statements below
1182 state["DirectToLdsA"] = False
1183 state["DirectToLdsB"] = False
1184 state["LocalWriteUseSgprA"] = False
1185 state["LocalWriteUseSgprB"] = False
1186 state["StoreSwapAddr"] = False
1187
1188 state["WorkGroupMappingXCC"] = abs(state["WorkGroupMappingXCC"])
1189
1190
1191 problemType = state["ProblemType"]
1192
1193 for (tc,batchMask) in (('A', 0x1), ('B', 0x2)):
1194 freeDims = [i for i in problemType["IndexAssignments%s"%tc] if i in problemType["IndicesFree"]]
1195 if not freeDims:
1196 reject(state, printRejectionReason, "tensor%s contains no free indices.")
1197 return False
1198
1199 # Determine which indices will be packed together as this impacts several different parms (sizes, magic numbers, etc)
1200 # The order in PackedC*Indices also determines the order that dimensions are packed - the first elements in
1201 # the list are the fastest-moving elements.
1202 # The store code optimizes for C0 being the coalesced dimension and C1 the perp dimension.
1203 # C0/C1 indices can come from IndexAssignmentsA or IndexAssignmentsB
1204 # grid size [0,1]
1205 state["PackedC0IdxChars"] = []
1206 state["PackedC0IndicesX"] = []
1207 indexChars = INDEX_CHARS
1208 # Pack all the dimensions (free) of A into grid[0]
1209
1210 if problemType["Index0"] in problemType["IndexAssignmentsA"]:
1211 tc0 = 'A'
1212 tc1 = 'B'
1213 else:
1214 tc0 = 'B'
1215 tc1 = 'A'
1216 assert(isPackedIndex(state, problemType["Index01A"]))
1217 assert(isPackedIndex(state, problemType["Index01B"]))
1218
1219 # Pack all the dimensions (batch and free) of A into grid[0]
1220 for idx in problemType["IndexAssignments%s"%tc0]:
1221 if isPackedIndex(state, idx):
1222 assert (idx < problemType["NumIndicesC"])
1223 state["PackedC0IdxChars"].append("%s" % indexChars[idx])
1224 state["PackedC0IndicesX"].append(idx)
1225
1226 state["PackedC1IdxChars"] = []
1227 state["PackedC1IndicesX"] = []
1228 for idx in problemType["IndexAssignments%s"%tc1]:
1229 if isPackedIndex(state, idx):
1230 assert (idx < problemType["NumIndicesC"])
1231 state["PackedC1IdxChars"].append("%s" % indexChars[idx])
1232 state["PackedC1IndicesX"].append(idx)
1233
1234 # If dims are packed, then need to ensure a global vector load isn't split by a tensor dim
1235 # (since this could result in non-contiguous addresses)
1236 # Current implementation ensures that the vector load is not partial across the Free* boundary:
1237 # GlobalReadVectorWidth=1 will always meet this requirement.
1238 # (TODO - could make this more sophisticated if dims use default strides and are thus contiguous)
1239 packedC0 = len(state["PackedC0IdxChars"])>1
1240 packedC1 = len(state["PackedC1IdxChars"])>1
1241
1242 bufferLoad = state["BufferLoad"] and state["KernelLanguage"] == "Assembly"
1243 if not bufferLoad:
1244 state["DirectToLds"] = False
1245 state["_UseSgprForGRO"] = False
1246 if state["PrefetchGlobalRead"] == 2:
1247 reject(state, printRejectionReason, "BufferLoad=0 does not support PrefetchGlobalRead=2")
1248 return
1249
1250 if problemType["UseBias"]:
1251 reject(state, printRejectionReason, "BufferLoad=0 does not support UseBias due to no suppress no load.")
1252 return
1253
1254 #These modes only work under certain conditions, apply them here:
1255 # - The "NoLoad" loop is only generated if PrefetchGlobalRead>0
1256 # - And Suppress does not work if GSU>1 for some reason
1257 if state["SuppressNoLoadLoop"] == 1:
1258 if not (bufferLoad and state["PrefetchGlobalRead"] == 1 and (state["GlobalSplitU"]==1 or state["GlobalSplitU"]==-1)):
1259 state["SuppressNoLoadLoop"] = 0
1260
1261 #print("PackedC0IdxChars", state["PackedC0IdxChars"])
1262 #print("PackedC1IdxChars", state["PackedC1IdxChars"])
1263
1264 if state["EnableMatrixInstruction"]:
1265 if state["TransposeLDS"] == -1:
1266 if state["ProblemType"]["TLUA"] and state["ProblemType"]["TLUB"]:
1267 state["TransposeLDS"] = 0
1268 else:
1269 state["TransposeLDS"] = 1
1270 if state["TransposeLDS"] == 0:
1271 state["UnrollMajorLDSA"] = 0
1272 state["UnrollMajorLDSB"] = 0
1273 elif state["TransposeLDS"] == 1:
1274 state["UnrollMajorLDSA"] = not state["ProblemType"]["TLUA"]
1275 state["UnrollMajorLDSB"] = not state["ProblemType"]["TLUB"]
1276 elif state["TransposeLDS"] == 2:
1277 state["UnrollMajorLDSA"] = 1
1278 state["UnrollMajorLDSB"] = 1
1279 else: # mac instruction
1280 if state["UseDotInstruction"]:
1281 # dot2: force TLDS = 2
1282 if state["TransposeLDS"] not in [-1,2]:
1283 reject(state, "dot2 kernel does not support TransposeLDS != 2")
1284 state["TransposeLDS"] = 2
1285 state["UnrollMajorLDSA"] = True
1286 state["UnrollMajorLDSB"] = True
1287 else:
1288 state["TransposeLDS"] = 0
1289 state["UnrollMajorLDSA"] = False
1290 state["UnrollMajorLDSB"] = False
1291
1292 if state["VectorWidthA"] == -1:
1293 if state["EnableMatrixInstruction"]:
1294 regPerElem = state["ProblemType"]["DataType"].numRegisters()
1295 optVW = int(4 // regPerElem)
1296 while 1:
1297 if state["MIWaveTile"][0] % optVW == 0:
1298 state["VectorWidthA"] = optVW
1299 break
1300 else:
1301 optVW //= 2
1302 if state["ProblemType"]["Sparse"]:
1303 state["VectorWidthA"] = 1
1304 else:
1305 state["VectorWidthA"] = 1
1306
1307 if state["VectorWidthB"] == -1:
1308 if state["EnableMatrixInstruction"]:
1309 regPerElem = state["ProblemType"]["DataType"].numRegisters()
1310 optVW = int(4 // regPerElem)
1311 while 1:
1312 if state["MIWaveTile"][1] % optVW == 0:
1313 state["VectorWidthB"] = optVW
1314 break
1315 else:
1316 optVW //= 2
1317 if state["ProblemType"]["Sparse"]:
1318 state["VectorWidthB"] = 1
1319 else:
1320 state["VectorWidthB"] = 1
1321
1322 if state["ProblemType"]["Sparse"] and not state["DirectToVgprSparseMetadata"]:
1323 state["VectorWidthMetadata"] = state["VectorWidthA"] if state["ProblemType"]["Sparse"] == 1 else state["VectorWidthB"]
1324
1325 numBytes = state["ProblemType"]["DataType"].numBytes()
1326 isa = tuple(state["ISA"])
1327 state["enableLDSTrA"] = state["LDSTrInst"] and isaInfoMap[isa].asmCaps["HasLDSTr"] and numBytes == 2 \
1328 and not state["UnrollMajorLDSA"] and not state["DirectToVgprA"]
1329 state["enableLDSTrB"] = state["LDSTrInst"] and isaInfoMap[isa].asmCaps["HasLDSTr"] and numBytes == 2 \
1330 and not state["UnrollMajorLDSB"] and not state["DirectToVgprB"]
1331
1332 state["enableGLTrA"] = state["DirectToVgprA"] and state["ProblemType"]["TLUA"] \
1333 and ((numBytes == 1 and isaInfoMap[isa].asmCaps["HasGLTr8B64"]) \
1334 or (numBytes == 2 and isaInfoMap[isa].asmCaps["HasGLTr16B128"]) \
1335 )
1336 state["enableGLTrB"] = state["DirectToVgprB"] and state["ProblemType"]["TLUB"] \
1337 and ((numBytes == 1 and isaInfoMap[isa].asmCaps["HasGLTr8B64"]) \
1338 or (numBytes == 2 and isaInfoMap[isa].asmCaps["HasGLTr16B128"]) \
1339 )
1340
1341 if state["enableLDSTrA"] or state["enableGLTrA"]:
1342 state["VectorWidthA"] = 1
1343
1344 if state["enableLDSTrB"] or state["enableGLTrB"]:
1345 state["VectorWidthB"] = 1
1346
1347 # if state["EnableMatrixInstruction"] and not state["SourceSwap"] and (state["VectorWidthA"] > 1 or state["VectorWidthB"] > 1):
1348 # reject(state, printRejectionReason, "not implement VectorWidth without SourceSwap")
1349
1350 # TT0,1 both must be multiples of VW, b/c of rC, rA, rB
1351 if state["EnableMatrixInstruction"]:
1352 if (state["MIWaveTile"][0] % state["VectorWidthA"]) != 0:
1353 reject(state, printRejectionReason, "MIWaveTile0(%u) should be multiple of VectorWidthA(%u)" % (state["MIWaveTile"][0], state["VectorWidthA"]))
1354 return
1355 if (state["MIWaveTile"][1] % state["VectorWidthB"]) != 0:
1356 reject(state, printRejectionReason, "MIWaveTile0(%u) should be multiple of VectorWidthB(%u)" % (state["MIWaveTile"][1], state["VectorWidthB"]))
1357 return
1358
1359 if len(problemType["IndicesSummation"]) > 1:
1360 # not supported with multiple summations, bug is maybe something with
1361 # how stagger iteration is wrapped when unroll loop exits
1362 state["StaggerU"] = 0
1363
1364 # Some restrictions for half:
1365 if state["KernelLanguage"] == "Assembly" \
1366 and state["ProblemType"]["DataType"].isHalf():
1367
1368 if isaInfoMap[state["ISA"]].archCaps["HasEccHalf"]:
1369 if not state["ProblemType"]["HighPrecisionAccumulate"] and state["AssertFree0ElementMultiple"] % 2 != 0:
1370 # beta-on-edge has AF0EM requirement except for HPA kernels
1371 reject(state, printRejectionReason, "Archs with HasEccHalf require AF0EM%2==0 except for HPA kernels")
1372 return
1373
1374 if state["ConvertAfterDS"]:
1375 if (state["ProblemType"]["DataType"].isHalf() == False) and (state["ProblemType"]["DataType"].isBFloat16() == False):
1376 reject(state, printRejectionReason, "ConvertAfterDS only support DataType half")
1377 return
1378 if (state["ProblemType"]["DataTypeA"].isAnyFloat8() == False) and (state["ProblemType"]["DataTypeB"].isAnyFloat8() == False) \
1379 and not (state["ProblemType"]["DataTypeA"].isSingle() and state["ProblemType"]["DataTypeB"].isSingle()):
1380 reject(state, printRejectionReason, "one of DataTypeA or DataTypeB need to be float8/float8_fnuz or both are fp32")
1381 return
1382 if state["ProblemType"]["DataType"].isBFloat16() \
1383 and (state["ProblemType"]["DataTypeA"].isSingle() and state["ProblemType"]["DataTypeB"].isSingle()):
1384 reject(state, printRejectionReason, "ConvertAfterDS doesn't support SS_BSS type")
1385 return
1386
1387 # DepthU == -1?
1388 if state["DepthU"] == -1:
1389 depthuList = [1024,512,256,128,64,32,16]
1390 else:
1391 depthuList = [state["DepthU"]]
1392 index = [0]
1393 backupValues = []
1394 for key, value in state.items():
1395 if isinstance(value, int) and value < 0:
1396 backupValues.append([key, value])
1397 while True:
1398 for backup in backupValues:
1399 state[backup[0]] = backup[1]
1400 state["ValidDepthU"] = True
1401 state["DepthU"] = depthuList[index[0]]
1402 Solution.depthUIteration(
1403 state,
1404 index,
1405 depthuList,
1406 problemType,
1407 isa,
1408 bufferLoad,
1409 packedC0,
1410 packedC1,
1411 printRejectionReason,
1412 isaInfoMap,
1413 rocmVersion
1414 )
1415 if state["Valid"] or (state["ValidDepthU"] and (not state["Valid"])):
1416 break
1417 index[0] += 1
1418 if index[0] >= len(depthuList):
1419 break
1420 if "ValidDepthU" in state:
1421 del state["ValidDepthU"]
1422
1423 # 0: Normal mode. Hardware applies all of the normal data dependency checks
1424 # 1: Full expert mode (not suppoeted yet). Disable hardware checks against: VA_VDST, VA_SDST, VA_SSRC, VA_VCC, VM_VSRC and SA_SDST.
1425 # 2: Disable only VA_VDST and VM_VSRC checks.
1426 def evaluateExpertSchedulingMode() -> Literal[0, 1, 2]:
1427 # Check if the current parameters is supported by the ExpertSchedulingMode
1428 if not isaInfoMap[isa].archCaps["HasSchedMode"]: return 0
1429 if state["ProblemType"]["Sparse"]: return 0
1430 if state["ProblemType"]["DataType"].isSingle(): return 0
1431
1432 # parameters not tested yet:
1433 supportedParameters = {
1434 "EnableMatrixInstruction": state["EnableMatrixInstruction"],
1435 "ScheduleIterAlg": state["ScheduleIterAlg"] == 3,
1436 "WavefrontSize": state["WavefrontSize"] == 32,
1437 "UnrollLoopSwapGlobalReadOrder": not state["UnrollLoopSwapGlobalReadOrder"],
1438 "SuppressNoLoadLoop": not state["SuppressNoLoadLoop"],
1439 "ScheduleGlobalRead": state["ScheduleGlobalRead"] == 1,
1440 "ScheduleLocalWrite": state["ScheduleLocalWrite"] == 1,
1441 "GlobalReadPerMfma": state["GlobalReadPerMfma"] == 1,
1442 "InterleaveAlpha": not state["InterleaveAlpha"],
1443 "DirectToLds": not state["DirectToLds"],
1444 "UseSgprForGRO": state["UseSgprForGRO"] == -1,
1445 "UseInstOffsetForGRO": not state["UseInstOffsetForGRO"],
1446 "Use64bShadowLimit": state["Use64bShadowLimit"] == 1,
1447 "StorePriorityOpt": not state["StorePriorityOpt"],
1448 "StoreSyncOpt": not state["StoreSyncOpt"],
1449 "GroupLoadStore": not state["GroupLoadStore"],
1450 "StreamK": not state["StreamK"],
1451 "StreamKAtomic": not state["StreamKAtomic"],
1452 "StreamKXCCMapping": not state["StreamKXCCMapping"],
1453 "DebugStreamK": not state["DebugStreamK"],
1454 "WorkGroupReduction": not state["WorkGroupReduction"],
1455 "ConvertAfterDS": not state["ConvertAfterDS"],
1456 "ForceDisableShadowInit": not state["ForceDisableShadowInit"],
1457 }
1458
1459 for key, supported in supportedParameters.items():
1460 if supported:
1461 continue
1462
1463 print2(f"ExpertSchedulingMode not supported with {key}={state[key]}")
1464 return 0
1465
1466 # Currently, only the mode that disables VA_VDST and VM_VSRC checks is supported.
1467 return 2
1468
1469 state["ExpertSchedulingMode"] = evaluateExpertSchedulingMode()
1470
1471 def depthUIteration(
1472 state,
1473 index,
1474 depthuList,
1475 problemType,
1476 isa,
1477 bufferLoad,
1478 packedC0,
1479 packedC1,
1480 printRejectionReason: bool,
1481 isaInfoMap: Dict[IsaVersion, IsaInfo],
1482 rocmVersion: SemanticVersion
1483 ):
1484 ########################################
1485 # Auto search for DepthU starts here
1486 # Activates when DepthU == -1
1487 ########################################
1488 resetStaggerUStride = state["StaggerUStride"]
1489 resetLocalReadVectorWidth = state["LocalReadVectorWidth"]
1490 resetGlobalReadVectorWidthA = state["GlobalReadVectorWidthA"]
1491 resetGlobalReadVectorWidthB = state["GlobalReadVectorWidthB"]
1492
1493 while True:
1494 userDepthU = depthuList[index[0]]
1495 state["StaggerUStride"] = resetStaggerUStride
1496 state["LocalReadVectorWidth"] = resetLocalReadVectorWidth
1497 state["GlobalReadVectorWidthA"] = resetGlobalReadVectorWidthA
1498 state["GlobalReadVectorWidthB"] = resetGlobalReadVectorWidthB
1499 state["Valid"] = True
1500 ########################################
1501 # Initial DepthU
1502 ########################################
1503 depthU = userDepthU
1504 depthUA = depthUB = depthUM = depthU
1505 if state["ProblemType"]["Sparse"]:
1506 if state["ProblemType"]["Sparse"] == 2:
1507 depthUB = depthUB // 2
1508 depthUM = depthUB if state["DirectToVgprSparseMetadata"] else depthUB // 4
1509 else:
1510 depthUA = depthUA // 2
1511 depthUM = depthUA if state["DirectToVgprSparseMetadata"] else depthUA // 4
1512 state["_DepthU"] = state["DepthU"]# internal
1513 state["_DepthUA"] = depthUA# internal
1514 state["_DepthUB"] = depthUB# internal
1515 state["_DepthUMetadata"] = depthUM# internal
1516
1517 Solution.checkAndAssignWaveSeparateGlobalRead(state, 'A', printRejectionReason)
1518 Solution.checkAndAssignWaveSeparateGlobalRead(state, 'B', printRejectionReason)
1519 if state["ProblemType"]["Sparse"]:
1520 if state["ProblemType"]["Sparse"] == 2:
1521 if not state["DirectToVgprSparseMetadata"]:
1522 Solution.checkAndAssignWaveSeparateGlobalRead(state, 'Metadata', printRejectionReason)
1523 else:
1524 if not state["DirectToVgprSparseMetadata"]:
1525 Solution.checkAndAssignWaveSeparateGlobalRead(state, 'Metadata', printRejectionReason)
1526
1527 # Set up stagger shift:
1528 bpeAB = int(4*state["ProblemType"]["DataType"].numRegisters())
1529 # (1<<staggerStrideShift) is number of loop iterations to traverse the stride
1530 if state["StaggerU"] == 0:
1531 state["StaggerUMapping"] = 0
1532 state["StaggerUStride"] = 0
1533
1534 if state["StaggerUStride"] == -1 or state["StaggerUStride"] < (state["DepthU"] * bpeAB):
1535 # (StaggerUStride) shoud be greater than or equal to (DepthU * bpeAB)
1536 state["StaggerUStride"] = state["DepthU"] * bpeAB
1537
1538 state["_staggerStrideShift"] = (int)(math.ceil(math.log(state["StaggerUStride"] / (state["DepthU"] * bpeAB), 2)))
1539
1540 def calcLdsPad(lrvw: int, isaInfoMap: Dict[str, IsaInfo]) -> int:
1541 ldsPadA = state["LdsPadA"]
1542 ldsPadB = state["LdsPadB"]
1543 ldsPadM = state["LdsPadMetadata"]
1544 optPadA = optPadB = lrvw
1545 readRegsA = readRegsB = lrvw * state["ProblemType"]["DataType"].numBytes() // 4
1546 if state["ProblemType"]["Sparse"]:
1547 if state["ProblemType"]["Sparse"] == 2:
1548 optPadB //= 2
1549 readRegsB //= 2
1550 else:
1551 optPadA //= 2
1552 readRegsA //= 2
1553 if (not isaInfoMap[isa].asmCaps['HasWMMA']) and (readRegsA > 4 or readRegsB > 4):
1554 reject(state, "LocalReadVectorWidth results in attemping to read LDS larger than b128, reject")
1555 return ldsPadA, ldsPadB, ldsPadM
1556 if state["EnableMatrixInstruction"]:
1557 # for readRegs = 1 or 4, we need to double pad for MI16x16xNx1 to avoid bank conflict.
1558 if state["MatrixInstB"] == 1 and state["MatrixInstM"] == 16:
1559 if readRegsA == 4 or readRegsA == 1:
1560 optPadA *= 2
1561 if readRegsB == 4 or readRegsB == 1:
1562 optPadB *= 2
1563 if ldsPadA == -1:
1564 if not state["UnrollMajorLDSA"]:
1565 if state["EnableMatrixInstruction"]:
1566 ldsPadA = 0
1567 if state["MatrixInstB"] == 1 and state["MatrixInstM"] == 16:
1568 ldsPadA = ((16 * state["VectorWidthA"] * state["ProblemType"]["DataType"].numBytes() + state["MacroTile0"] * state["ProblemType"]["DataType"].numBytes() * state["LocalReadVectorWidth"]) % 128) // state["ProblemType"]["DataType"].numBytes()
1569 if state["GlobalReadVectorWidthA"] * state["ProblemType"]["DataType"].numBytes() == 32 and ldsPadA == 0:
1570 ldsPadA = 16 // state["ProblemType"]["DataType"].numBytes()
1571 if state["DirectToLdsA"]:
1572 # TODO: Check if there are cases which benefit from padding, currently set to zero by default
1573 ldsPadA = 0
1574 else: # mac instruction
1575 if state["ProblemType"]["TLUA"]:
1576 ldsPadA = 0
1577 else:
1578 ldsPadA = state["VectorWidthA"]
1579 else:
1580 if state["DirectToLdsA"]:
1581 ldsPadA = max(lrvw, optPadA) if not state["ProblemType"]["TLUA"] else 0
1582 else:
1583 ldsPadA = max(state["GlobalReadVectorWidthA"],optPadA)
1584 assert(ldsPadA >= 0)
1585
1586 if ldsPadB == -1:
1587 if not state["UnrollMajorLDSB"]:
1588 if state["EnableMatrixInstruction"]:
1589 ldsPadB = 0
1590 if state["MatrixInstB"] == 1 and state["MatrixInstM"] == 16:
1591 ldsPadB = ((16 * state["VectorWidthB"] * state["ProblemType"]["DataType"].numBytes() + state["MacroTile1"] * state["ProblemType"]["DataType"].numBytes() * state["LocalReadVectorWidth"]) % 128) // state["ProblemType"]["DataType"].numBytes()
1592 if state["GlobalReadVectorWidthB"] * state["ProblemType"]["DataType"].numBytes() == 32 and ldsPadB == 0:
1593 ldsPadB = 16 // state["ProblemType"]["DataType"].numBytes()
1594 if state["DirectToLdsB"]:
1595 # TODO: Check if there are cases which benefit from padding, currently set to zero by default
1596 ldsPadB = 0
1597 else:
1598 if state["ProblemType"]["TLUB"]:
1599 ldsPadB = 0
1600 else:
1601 ldsPadB = state["VectorWidthB"]
1602 else:
1603 if state["DirectToLdsB"]:
1604 ldsPadB = max(lrvw, optPadB) if not state["ProblemType"]["TLUB"] else 0
1605 else:
1606 ldsPadB = max(state["GlobalReadVectorWidthB"],optPadB)
1607 assert(ldsPadB >= 0)
1608
1609 if state["ProblemType"]["Sparse"] and not state["DirectToVgprSparseMetadata"]:
1610 optPadM = (optPadB if state["ProblemType"]["Sparse"] == 2 else optPadA) // 4
1611 grvwM = (state["GlobalReadVectorWidthB"] if state["ProblemType"]["Sparse"] == 2 else state["GlobalReadVectorWidthA"]) // 4
1612 vwM = (state["VectorWidthB"] if state["ProblemType"]["Sparse"] == 2 else state["VectorWidthA"]) // 4
1613
1614 if ldsPadM == -1:
1615 ldsPadM = 0
1616 if not state["ProblemType"]["TLUMetadata"]:
1617 if state["EnableMatrixInstruction"] and state["TransposeLDSMetadata"]:
1618 ldsPadM = max(grvwM, optPadM)
1619 else:
1620 ldsPadM = vwM
1621 ## turn-off padding for directToLds
1622 if state["EnableMatrixInstruction"] and state["TransposeLDSMetadata"] and state["DirectToLdsMetadata"]:
1623 ldsPadM = 0
1624 assert(ldsPadM >= 0)
1625
1626 if state["DirectToLdsA"] and state["ProblemType"]["TLUA"]:
1627 ldsPadA = 0
1628 if state["DirectToLdsB"] and state["ProblemType"]["TLUB"]:
1629 ldsPadB = 0
1630 # set ldsPadA,B=0 for DirectToVgpr
1631 if state["DirectToVgprA"]:
1632 ldsPadA = 0
1633 if state["DirectToVgprB"]:
1634 ldsPadB = 0
1635
1636 return ldsPadA, ldsPadB, ldsPadM
1637
1638 def calcLdsBlockSizePerPad(lrvw: int) -> int:
1639 LdsBlockSizePerPadA = state["LdsBlockSizePerPadA"]
1640 LdsBlockSizePerPadB = state["LdsBlockSizePerPadB"]
1641 tmpBpe = state["ProblemType"]["DataTypeA"].numBytes() if state["ConvertAfterDS"] else state["ProblemType"]["DataType"].numBytes()
1642 if LdsBlockSizePerPadA == -1:
1643 if state["EnableMatrixInstruction"]:
1644 if state["UnrollMajorLDSA"]:
1645 LdsBlockSizePerPadA = roundUpToNearestMultiple(state["_DepthUA"] * tmpBpe, 128)
1646 if state["_DepthUA"] * tmpBpe * state["VectorWidthA"] > 128:
1647 LdsBlockSizePerPadA = roundUpToNearestMultiple(state["_DepthUA"] * tmpBpe * state["VectorWidthA"], 128)
1648 else:
1649 if state["MatrixInstB"] == 1 and state["MatrixInstM"] == 16:
1650 LdsBlockSizePerPadA = state["MacroTile0"] * tmpBpe * lrvw
1651 else:
1652 LdsBlockSizePerPadA = 0
1653 else:
1654 LdsBlockSizePerPadA = 0
1655 tmpBpe = state["ProblemType"]["DataTypeB"].numBytes() if state["ConvertAfterDS"] else state["ProblemType"]["DataType"].numBytes()
1656 if LdsBlockSizePerPadB == -1:
1657 if state["EnableMatrixInstruction"]:
1658 if state["UnrollMajorLDSB"]:
1659 LdsBlockSizePerPadB = roundUpToNearestMultiple(state["_DepthUB"] * tmpBpe, 128)
1660 if state["_DepthUB"] * tmpBpe * state["VectorWidthB"] > 128:
1661 LdsBlockSizePerPadB = roundUpToNearestMultiple(state["_DepthUB"] * tmpBpe * state["VectorWidthB"], 128)
1662 else:
1663 if state["MatrixInstB"] == 1 and state["MatrixInstM"] == 16:
1664 LdsBlockSizePerPadB = state["MacroTile1"] * tmpBpe * lrvw
1665 else:
1666 LdsBlockSizePerPadB = 0
1667 else:
1668 LdsBlockSizePerPadB = 0
1669
1670 # set LdsBlockSizePerPadA,B=0 for DirectToVgpr
1671 if state["DirectToVgprA"]:
1672 LdsBlockSizePerPadA = 0
1673 if state["DirectToVgprB"]:
1674 LdsBlockSizePerPadB = 0
1675
1676 if state["DirectToLdsA"]:
1677 bpeA = state["ProblemType"]["DataTypeA"].numBytes()
1678 # For DTL lds padding must be a multiple of the instruction load size (in bytes)
1679 MinLdsBlockSizePerPadA = (state[f"GlobalReadVectorWidthA"] * bpeA) * state["WavefrontSize"]
1680 LdsBlockSizePerPadA = roundUpToNearestMultiple(LdsBlockSizePerPadA, MinLdsBlockSizePerPadA)
1681
1682 if state["DirectToLdsB"]:
1683 bpeB = state["ProblemType"]["DataTypeB"].numBytes()
1684 # For DTL lds padding must be a multiple of the instruction load size (in bytes)
1685 MinLdsBlockSizePerPadB = (state[f"GlobalReadVectorWidthB"] * bpeB) * state["WavefrontSize"]
1686 LdsBlockSizePerPadB = roundUpToNearestMultiple(LdsBlockSizePerPadB, MinLdsBlockSizePerPadB)
1687
1688 return LdsBlockSizePerPadA, LdsBlockSizePerPadB
1689
1690 def calcLdsNumBytes(ldsPadA: int, LdsBlockSizePerPadA: int, ldsPadB: int, LdsBlockSizePerPadB: int) -> int:
1691 bpeA = state["ProblemType"]["DataTypeA"].numBytes() if state["ConvertAfterDS"] else state["ProblemType"]["DataType"].numBytes()
1692 bpeB = state["ProblemType"]["DataTypeB"].numBytes() if state["ConvertAfterDS"] else state["ProblemType"]["DataType"].numBytes()
1693 ldsAlign = int(64 / state["ProblemType"]["DataType"].numRegisters())
1694
1695 if state["UnrollMajorLDSA"]:
1696 ldsNumBytesA = (state["_DepthUA"] + ldsPadA) * state["MacroTileA"] * bpeA
1697 else:
1698 ldsNumBytesA = state["_DepthUA"] * (state["MacroTileA"] + ldsPadA) * bpeA
1699 padInterval = LdsBlockSizePerPadA
1700
1701 if padInterval != 0:
1702 ldsNumBytesA = int((state["_DepthUA"] * state["MacroTileA"] * bpeA) / padInterval * (padInterval + ldsPadA * bpeA))
1703 ldsNumBytesAlignedA = roundUpToNearestMultiple(ldsNumBytesA, ldsAlign)
1704 # DirectToVgpr case, set 0 to lds related variables
1705 if state["DirectToVgprA"]:
1706 ldsNumBytesA = 0
1707 ldsNumBytesAlignedA = 0
1708
1709 if state["UnrollMajorLDSB"]:
1710 ldsNumBytesB = (state["_DepthUB"] + ldsPadB) * state["MacroTileB"] * bpeB
1711 else:
1712 ldsNumBytesB = state["_DepthUB"] * (state["MacroTileB"] + ldsPadB) * bpeB
1713 padInterval = LdsBlockSizePerPadB
1714 if padInterval != 0:
1715 ldsNumBytesB = int((state["_DepthUB"] * state["MacroTileB"] * bpeB) / padInterval * (padInterval + ldsPadB * bpeB))
1716 ldsNumBytesAlignedB = roundUpToNearestMultiple(ldsNumBytesB, ldsAlign)
1717
1718 # DirectToVgpr case, set 0 to lds related variables
1719 if state["DirectToVgprB"]:
1720 ldsNumBytesB = 0
1721 ldsNumBytesAlignedB = 0
1722
1723 if state["ProblemType"]["Sparse"] and not state["DirectToVgprSparseMetadata"]:
1724 bpeAB = state["ProblemType"]["DataType"].numBytes()
1725 if state["UnrollMajorLDSMetadata"]:
1726 ldsNumBytesMetadata = (state["_DepthUMetadata"] + state["LdsPadMetadata"]) * state["MacroTileMetadata"]
1727 else:
1728 ldsNumBytesMetadata = state["_DepthUMetadata"] * (state["MacroTileMetadata"] + state["LdsPadMetadata"])
1729 ldsNumBytesMetadata = roundUp(ldsNumBytesMetadata / bpeAB) # metadata is in byte type. so divide ldsNumBytesMetadata by A,B's bpe
1730 padInterval = state["LdsBlockSizePerPadMetadata"]
1731 if padInterval != 0:
1732 ldsNumBytesMetadata = int(roundUp(state["_DepthUMetadata"] * state["MacroTileMetadata"] / bpeAB) / padInterval * (padInterval + state["LdsPadMetadata"]))
1733 ldsNumBytesAlignedMetadata = roundUpToNearestMultiple(ldsNumBytesMetadata, ldsAlign) * bpeAB
1734 ldsNumBytesMetadata = ldsNumBytesMetadata * bpeAB
1735 else:
1736 ldsNumBytesMetadata = 0
1737 ldsNumBytesAlignedMetadata = 0
1738
1739 return ldsNumBytesA, ldsNumBytesAlignedA, ldsNumBytesB, ldsNumBytesAlignedB, ldsNumBytesMetadata, ldsNumBytesAlignedMetadata
1740
1741 # Default LocalReadVectorWidth
1742 if state["EnableMatrixInstruction"]:
1743 autoLRVW = 0
1744 if state["LocalReadVectorWidth"] == -1:
1745 autoLRVW = 1
1746 if state["TransposeLDS"] or (state["MIInputPerThread"] * state["ProblemType"]["DataType"].numBytes() > 16):
1747 state["LocalReadVectorWidth"] = 16 // state["ProblemType"]["DataType"].numBytes()
1748 else:
1749 state["LocalReadVectorWidth"] = state["MIInputPerThread"]
1750 else:
1751 if state["ProblemType"]["Sparse"] and state["MIInputPerThread"] * state["ProblemType"]["DataType"].numBytes() > 16:
1752 if state["LocalReadVectorWidth"] < state["MIInputPerThread"] // 2:
1753 reject(state, printRejectionReason, "LocalReadVectorWidth < %u" %(state["MIInputPerThread"] // 2))
1754 elif not state["ProblemType"]["Sparse"] and not state["UseF32XEmulation"] and not(state["ProblemType"]["DataType"].is8bitFloat() and (state["MatrixInstK"] == 64 or state["MatrixInstK"] == 128)):
1755 if state["LocalReadVectorWidth"] < state["MIInputPerThread"]:
1756 reject(state, printRejectionReason, "LocalReadVectorWidth < %u" %(state["MIInputPerThread"]))
1757 if state["LocalReadVectorWidth"] > state["MIInputPerThread"] and not state["TransposeLDS"]:
1758 reject(state, printRejectionReason, "LocalReadVectorWidth require Transpose LDS")
1759
1760 if autoLRVW:
1761 if state["LocalReadVectorWidth"] // state["MIInputPerThread"] > 1:
1762 if (state["DepthU"] // state["MatrixInstK"] <= state["LocalReadVectorWidth"] // state["MIInputPerThread"]):
1763 # if only have 1 iteration with wider local read, reduce LRVW to have better scheduling (at least 2 iterations)
1764 state["LocalReadVectorWidth"] //= 2
1765 if state["LocalReadVectorWidth"] // state["MIInputPerThread"] > 1:
1766 padA, padB, padM = calcLdsPad(state["LocalReadVectorWidth"], isaInfoMap)
1767 ldsBlockSizePerPadA, ldsBlockSizePerPadB = calcLdsBlockSizePerPad(state["LocalReadVectorWidth"])
1768 ldsNumBytesA, ldsNumBytesAlignedA, ldsNumBytesB, ldsNumBytesAlignedB, ldsNumBytesMetadata, ldsNumBytesAlignedMetadata = calcLdsNumBytes(padA, ldsBlockSizePerPadA, padB, ldsBlockSizePerPadB)
1769 if (ldsNumBytesAlignedA + ldsNumBytesAlignedB) > state["MaxLDS"]:
1770 state["LocalReadVectorWidth"] //= 2
1771 else:
1772 if state["UseDotInstruction"]:
1773 # dot2: LRVW should be equal to NumDotElements * InnerUnroll
1774 if state["LocalReadVectorWidth"] not in [-1, state["NumDotElements"] * state["InnerUnroll"]]:
1775 reject(state, printRejectionReason, "dot kernel requires LocalReadVectorWidth = NumDotElements(%u) * InnerUnroll(%u)" \
1776 % (state["NumDotElements"], state["InnerUnroll"]))
1777 return
1778 state["LocalReadVectorWidth"] = state["NumDotElements"] * state["InnerUnroll"]
1779 else: # mac
1780 if state["LocalReadVectorWidth"] == -1:
1781 state["LocalReadVectorWidth"] = state["VectorWidthA"]
1782 if state["LocalReadVectorWidth"] != state["VectorWidthA"] or \
1783 state["LocalReadVectorWidth"] != state["VectorWidthB"]:
1784 reject(state, printRejectionReason, "LocalReadVectorWidth must equal VectorWidthA/B for MAC kernels")
1785
1786 def calcOptGRVW(lrvw: int, unrollMajorLDS: bool, datatype: DataType) -> int:
1787 # with UnrollMajorLDS, GRVW need to less or equal than LRVW to have conflict free LDS read with padding.
1788 optGRVW = lrvw if unrollMajorLDS else 4 / datatype.numRegisters()
1789 if optGRVW * datatype.numBytes() > 16:
1790 optGRVW = 16 // datatype.numBytes()
1791 return optGRVW
1792
1793 def calSwizzlePackK(state, tc):
1794 return 16 // state[f"MIInputPerThread{tc}"] // state["ProblemType"][f"DataType{tc}"].numBytes()
1795
1796 genGRVWA = False
1797 genGRVWB = False
1798 # Default GlobalReadVectorWidthA
1799 if state["EnableMatrixInstruction"]:
1800 if state["GlobalReadVectorWidthA"] < 0:
1801 genGRVWA = True
1802 if state["GlobalReadVectorWidthA"] == -2:
1803 if state["MatrixInstBM"] == 1 and state["MIWaveTile"][0] == 1 and state["MIWaveGroup"][0] == 1 and state["ProblemType"]["TLUA"]:
1804 state["GlobalReadVectorWidthA"] = 1
1805 else:
1806 reject(state, printRejectionReason, "GRVWA=-2 is set for skinny MT")
1807 elif state["GlobalReadVectorWidthA"] == -1:
1808 if state["ProblemType"]["SwizzleTensorA"]:
1809 state["GlobalReadVectorWidthA"] = state["MIInputPerThreadA"] * calSwizzlePackK(state, "A")
1810 elif state["enableGLTrA"]:
1811 state["GlobalReadVectorWidthA"] = 8
1812 else:
1813 optGRVW = calcOptGRVW(state["LocalReadVectorWidth"], state["UnrollMajorLDSA"], state["ProblemType"]["DataTypeA"])
1814 curGRVW = 1
1815 state["GlobalReadVectorWidthA"] = int(curGRVW)
1816 while (curGRVW <= optGRVW):
1817 if (state["MacroTile0"]*state["_DepthUA"]//state["NumThreads"]) % curGRVW == 0:
1818 state["GlobalReadVectorWidthA"] = int(curGRVW)
1819 curGRVW *= 2
1820 else:
1821 # dot2
1822 if state["UseDotInstruction"]:
1823 coalescedA = state["MacroTile0"] if state["ProblemType"]["TLUA"] else state["DepthU"]
1824 elementPerThread = state["MacroTile0"] * state["DepthU"] // state["NumThreads"]
1825 if state["GlobalReadVectorWidthA"] == -1:
1826 for tmpGRVW in [8,4,2,1]:
1827 if coalescedA % tmpGRVW == 0 and elementPerThread % tmpGRVW == 0:
1828 state["GlobalReadVectorWidthA"] = tmpGRVW
1829 break
1830 if coalescedA % state["GlobalReadVectorWidthA"] != 0 or elementPerThread % state["GlobalReadVectorWidthA"] != 0:
1831 reject(state, "dot2: non-valid GRVWA")
1832 return
1833 # TODO: support edge shiftptr to release this constraint.
1834 if state["ProblemType"]["TLUA"]:
1835 state["AssertFree0ElementMultiple"] = max(state["AssertFree0ElementMultiple"], state["GlobalReadVectorWidthA"])
1836
1837
1838 # Default GlobalReadVectorWidthB
1839 if state["EnableMatrixInstruction"]:
1840 if state["GlobalReadVectorWidthB"] < 0:
1841 genGRVWB = True
1842 if state["GlobalReadVectorWidthB"] == -2:
1843 if state["MatrixInstBN"] == 1 and state["MIWaveTile"][1] == 1 and state["MIWaveGroup"][1] == 1 and state["ProblemType"]["TLUB"]:
1844 state["GlobalReadVectorWidthB"] = 1
1845 else:
1846 reject(state, printRejectionReason, "GRVWB=-2 is set for skinny MT")
1847 elif state["GlobalReadVectorWidthB"] == -1:
1848 if state["ProblemType"]["SwizzleTensorB"]:
1849 state["GlobalReadVectorWidthB"] = state["MIInputPerThreadB"] * calSwizzlePackK(state, "B")
1850 elif state["enableGLTrB"]:
1851 state["GlobalReadVectorWidthB"] = 8
1852 else:
1853 optGRVW = calcOptGRVW(state["LocalReadVectorWidth"], state["UnrollMajorLDSB"], state["ProblemType"]["DataTypeB"])
1854 curGRVW = 1
1855 state["GlobalReadVectorWidthB"] = int(curGRVW)
1856 while (curGRVW <= optGRVW):
1857 if (state["MacroTile1"]*state["_DepthUB"]//state["NumThreads"]) % curGRVW == 0:
1858 state["GlobalReadVectorWidthB"] = int(curGRVW)
1859 curGRVW *= 2
1860 else:
1861 # dot2
1862 if state["UseDotInstruction"]:
1863 coalescedB = state["MacroTile1"] if state["ProblemType"]["TLUB"] else state["DepthU"]
1864 elementPerThread = state["MacroTile1"] * state["DepthU"] // state["NumThreads"]
1865 if state["GlobalReadVectorWidthB"] == -1:
1866 for tmpGRVW in [8,4,2,1]:
1867 if coalescedB % tmpGRVW == 0 and elementPerThread % tmpGRVW == 0:
1868 state["GlobalReadVectorWidthB"] = tmpGRVW
1869 break
1870 if coalescedB % state["GlobalReadVectorWidthB"] != 0 or elementPerThread % state["GlobalReadVectorWidthB"] != 0:
1871 reject(state, "dot2: non-valid GRVWB")
1872 return
1873 # TODO: support edge shiftptr to release this constraint.
1874 if state["ProblemType"]["TLUB"]:
1875 state["AssertFree1ElementMultiple"] = max(state["AssertFree1ElementMultiple"], state["GlobalReadVectorWidthB"])
1876
1877 #for tensor swizzling, we calculate pack-k to achieve buffer_load_dwordx4
1878 for tc in ("A", "B",):
1879 if state["ProblemType"][f"SwizzleTensor{tc}"]:
1880 if not state["EnableMatrixInstruction"]:
1881 reject(state, printRejectionReason, f"Tensor {tc} swizzling supports MI only")
1882 # Print rejection reason instead of force set
1883 # 16 means bytes of buffer_load_dwordx4
1884 SwizzlePackK = calSwizzlePackK(state, tc)
1885 if state[f"GlobalReadVectorWidth{tc}"] != state[f"MIInputPerThread{tc}"] * SwizzlePackK:
1886 GRVW_TC = state[f"GlobalReadVectorWidth{tc}"]
1887 MIInPerThread = state[f"MIInputPerThread{tc}"]
1888 reject(state, printRejectionReason, f"SwizzleTensor{tc} doesn't support GRVW{tc} ({GRVW_TC}) != MIInputPerThread{tc} ({MIInPerThread}) * {SwizzlePackK}")
1889
1890 if state["ProblemType"]["SwizzleTensorA"]:
1891 if not state["DirectToVgprA"]:
1892 reject(state, printRejectionReason, f"Tensor A swizzling requires DirectToVgprA")
1893 if not state["ProblemType"]["TransposeA"]:
1894 reject(state, printRejectionReason, f"Tensor A swizzling supports TN or TT only")
1895
1896 if state["ProblemType"]["SwizzleTensorB"]:
1897 if not state["DirectToVgprB"]:
1898 reject(state, printRejectionReason, f"Tensor B swizzling requires DirectToVgprB")
1899 if state["ProblemType"]["TransposeB"]:
1900 reject(state, printRejectionReason, f"Tensor B swizzling supports TN or NN only")
1901
1902 # TODO- NN fails validation due to DTVB + Tail-Loop is not working correctly
1903 if not (state["ProblemType"]["TransposeA"] and not state["ProblemType"]["TransposeB"]):
1904 reject(state, printRejectionReason, f"Tensor B swizzling supports TN only")
1905
1906 # Force GRVW the same when UnrollLoopSwapGlobalReadOrder = 1.
1907 if genGRVWA and state["UnrollLoopSwapGlobalReadOrder"] == 1:
1908 state["GlobalReadVectorWidthA"] = min(state["GlobalReadVectorWidthA"], state["GlobalReadVectorWidthB"])
1909 if genGRVWB and state["UnrollLoopSwapGlobalReadOrder"] == 1:
1910 state["GlobalReadVectorWidthB"] = min(state["GlobalReadVectorWidthA"], state["GlobalReadVectorWidthB"])
1911
1912 # reject - VW too big
1913 if (state["VectorWidthA"] * state["ProblemType"]["DataType"].numBytes()) > 16:
1914 reject(state, printRejectionReason, "VWA * DataType.numBytes() > 16")
1915 if (state["VectorWidthB"] * state["ProblemType"]["DataType"].numBytes()) > 16:
1916 reject(state, printRejectionReason, "VWB * DataType.numBytes() > 16")
1917
1918 # reject - GRVW too big
1919 if (state["GlobalReadVectorWidthA"] * state["ProblemType"]["DataTypeA"].numBytes()) > 16 and not state["UseF32XEmulation"]:
1920 reject(state, printRejectionReason, "GRVWA * DataTypeA.numBytes() > 16")
1921 if (state["GlobalReadVectorWidthB"] * state["ProblemType"]["DataTypeB"].numBytes()) > 16 and not state["UseF32XEmulation"]:
1922 reject(state, printRejectionReason, "GRVWB * DataTypeB.numBytes() > 16")
1923
1924 ########################################
1925 # Search DepthU
1926 # Inputs:
1927 # - depthU, userDepthU, state["LocalSplitU"], state["InnerUnroll"], state["MacroTile0/1"], state["GlobalReadVectorWidth"]
1928 # - state["MatrixInstK"], ...
1929 # Outputs:
1930 # - totalVectorsCoalescedA, totalVectorsCoalescedB, totalElementsPerpA, totalElementsPerpB, state["DepthU"]
1931 #######################################
1932 while True: # exit criteria at end
1933 validDepthU = True
1934
1935 # how many elements to load
1936 if state["ProblemType"]["TLUA"]: # NT/NN
1937 totalElementsCoalescedA = state["MacroTileA"]
1938 totalElementsPerpA = depthUA
1939 if state["DirectToVgprA"]:
1940 totalElementsCoalescedA *= state["MIWaveGroup"][1]
1941 else: # TN/TT
1942 totalElementsCoalescedA = depthUA
1943 totalElementsPerpA = state["MacroTileA"]
1944 if state["DirectToVgprA"]:
1945 totalElementsPerpA *= state["MIWaveGroup"][1]
1946
1947 if state["ProblemType"]["TLUB"]: # NT/TT
1948 totalElementsCoalescedB = state["MacroTileB"]
1949 totalElementsPerpB = depthUB
1950 if state["DirectToVgprB"]:
1951 totalElementsCoalescedB *= state["MIWaveGroup"][0]
1952 else: # TN/NN
1953 totalElementsCoalescedB = depthUB
1954 totalElementsPerpB = state["MacroTileB"]
1955 if state["DirectToVgprB"]:
1956 totalElementsPerpB *= state["MIWaveGroup"][0]
1957
1958 totalElementsA = totalElementsCoalescedA * totalElementsPerpA
1959 totalElementsB = totalElementsCoalescedB * totalElementsPerpB
1960 if state["ProblemType"]["Sparse"] and not state["DirectToVgprSparseMetadata"]:
1961 if state["ProblemType"]["TLUMetadata"]:
1962 totalElementsCoalescedM = state["MacroTileMetadata"]
1963 totalElementsPerpM = depthUM
1964 else:
1965 totalElementsCoalescedM = depthUM
1966 totalElementsPerpM = state["MacroTileMetadata"]
1967 totalElementsM = totalElementsCoalescedM * totalElementsPerpM
1968
1969 tva = totalElementsA // state["GlobalReadVectorWidthA"]
1970 if not Solution.setGlobalReadVectorWidth(state, "A", tva, state["GlobalReadVectorWidthA"], printRejectionReason):
1971 validDepthU = False
1972 tvb = totalElementsB // state["GlobalReadVectorWidthB"]
1973 if not Solution.setGlobalReadVectorWidth(state, "B", tvb, state["GlobalReadVectorWidthB"], printRejectionReason):
1974 validDepthU = False
1975
1976 if state["EnableMatrixInstruction"] and state["GlobalReadVectorWidthA"]:
1977 partialA = state["ProblemType"]["TLUA"] and (state["AssertFree0ElementMultiple"] % state["GlobalReadVectorWidthA"] != 0)
1978 if partialA:
1979 glvwAlimit = 16 // state["ProblemType"]["DataType"].numBytes()
1980 if state["SourceSwap"]:
1981 matrixInstM = (state["MatrixInstM"] * state["MatrixInstBM"]) if (state["MatrixInstM"] == 4) else state["MatrixInstM"]
1982 glvwAlimit = matrixInstM * state["VectorWidthA"]
1983 else:
1984 matrixInstN = (state["MatrixInstN"] * state["MatrixInstBN"]) if (state["MatrixInstN"] == 4) else state["MatrixInstN"]
1985 glvwAlimit = state["MIOutputVectorWidth"] * (state["WavefrontSize"] // matrixInstN)
1986 if state["ProblemType"]["DataType"].numRegisters() == 0.25:
1987 glvwAlimit = max(glvwAlimit, 4)
1988
1989 # reduce GLVA if GLVA larger than MIOVW
1990 if state["GlobalReadVectorWidthA"] > glvwAlimit:
1991 tva = totalElementsA // glvwAlimit
1992 if not Solution.setGlobalReadVectorWidth(state, "A", tva, glvwAlimit, printRejectionReason):
1993 validDepthU = False
1994
1995 if state["EnableMatrixInstruction"] and state["GlobalReadVectorWidthB"]:
1996 partialB = state["ProblemType"]["TLUB"] and (state["AssertFree1ElementMultiple"] % state["GlobalReadVectorWidthB"] != 0)
1997 if partialB:
1998 glvwBlimit = 16 // state["ProblemType"]["DataType"].numBytes()
1999 if state["SourceSwap"]:
2000 matrixInstM = (state["MatrixInstM"] * state["MatrixInstBM"]) if (state["MatrixInstM"] == 4) else state["MatrixInstM"]
2001 glvwBlimit = state["MIOutputVectorWidth"] * (state["WavefrontSize"] // matrixInstM)
2002 # else: # use origin shiftptr for B
2003 # matrixInstN = (state["MatrixInstN"] * state["MatrixInstBN"]) if (state["MatrixInstN"] == 4) else state["MatrixInstN"]
2004 if state["ProblemType"]["DataType"].numRegisters() == 0.25:
2005 glvwBlimit = max(glvwBlimit, 4)
2006
2007 # reduce GLVB if GLVB larger than MIOVW
2008 if state["GlobalReadVectorWidthB"] > glvwBlimit:
2009 tvb = totalElementsB // glvwBlimit
2010 if not Solution.setGlobalReadVectorWidth(state, "B", tvb, glvwBlimit, printRejectionReason):
2011 validDepthU = False
2012
2013 if validDepthU and state["KernelLanguage"] == "Assembly":
2014 if isaInfoMap[state["ISA"]].archCaps["HasEccHalf"]:
2015 if state["ProblemType"]["DataType"].numRegisters() == 0.5 and (not state["ProblemType"]["HighPrecisionAccumulate"]) \
2016 and (not state["ProblemType"]["DataTypeA"].isSingle()) and (not state["ProblemType"]["DataTypeB"].isSingle()):
2017 if state["GlobalReadVectorWidthA"] == 1 or state["GlobalReadVectorWidthB"] == 1:
2018 reject(state, printRejectionReason, "HalfEcc requires HPA if glvw = 1")
2019 break
2020
2021 if state["ProblemType"]["Sparse"] and not state["DirectToVgprSparseMetadata"]:
2022 grvw = 1
2023 vw = 1
2024 if state["ProblemType"]["Sparse"] == 2:
2025 grvw = state["GlobalReadVectorWidthB"] // 4
2026 vw = state["VectorWidthB"] // 4
2027 if state["GlobalReadVectorWidthB"] % 4 != 0:
2028 reject(state, printRejectionReason, "Sparse B requires GRVWB %% 4 == 0, current GRVWB is %u"%state["GlobalReadVectorWidthB"])
2029 break
2030 else:
2031 grvw = state["GlobalReadVectorWidthA"] // 4
2032 vw = state["VectorWidthA"] // 4
2033 if state["GlobalReadVectorWidthA"] % 4 != 0:
2034 reject(state, printRejectionReason, "Sparse A requires GRVWA %% 4 == 0, current GRVWA is %u"%state["GlobalReadVectorWidthA"])
2035 break
2036
2037
2038 tvm = totalElementsM // grvw
2039
2040 if not Solution.setGlobalReadVectorWidth(state, "Metadata", tvm, grvw, printRejectionReason):
2041 validDepthU = False
2042
2043 if state["EnableMatrixInstruction"] and state["GlobalReadVectorWidthMetadata"]:
2044 partialM = True
2045 if state["ProblemType"]["Sparse"] == 2:
2046 partialM = state["ProblemType"]["TLUMetadata"] and (state["AssertFree1ElementMultiple"] % state["GlobalReadVectorWidthB"] != 0)
2047 else:
2048 partialM = state["ProblemType"]["TLUMetadata"] and (state["AssertFree0ElementMultiple"] % state["GlobalReadVectorWidthA"] != 0)
2049
2050 if partialM:
2051 glvwMlimit = 16
2052 if state["SourceSwap"]:
2053 matrixInstM = (state["MatrixInstM"] * state["MatrixInstBM"]) if (state["MatrixInstM"] == 4) else state["MatrixInstM"]
2054 glvwMlimit = matrixInstM * vw
2055 else:
2056 if state["ProblemType"]["Sparse"] == 1:
2057 matrixInstN = (state["MatrixInstN"] * state["MatrixInstBN"]) if (state["MatrixInstN"] == 4) else state["MatrixInstN"]
2058 glvwMlimit = state["MIOutputVectorWidth"] * (state["WavefrontSize"] // matrixInstN)
2059
2060 # reduce GLVMetadata if GLVMetadata larger than MIOVW
2061 if state["GlobalReadVectorWidthMetadata"] > glvwMlimit:
2062 tvm = totalElementsM // glvwMlimit
2063 if not Solution.setGlobalReadVectorWidth(state, "Metadata", tvm, glvwMlimit, printRejectionReason):
2064 validDepthU = False
2065
2066 if state["ProblemType"]["Sparse"] and state["DirectToVgprSparseMetadata"]:
2067 if state["VectorWidthA"] > 1 or state["VectorWidthB"] > 1 :
2068 reject(state, printRejectionReason, "Not implement DTVSM with VW>1")
2069 break
2070
2071 # Now convert elements to vectors based on GlobalReadVectorWidth
2072 GlobalReadVectorWidthA = state["GlobalReadVectorWidthA"]
2073 GlobalReadVectorWidthB = state["GlobalReadVectorWidthB"]
2074 totalVectorsCoalescedA = totalElementsCoalescedA // GlobalReadVectorWidthA
2075 totalVectorsCoalescedB = totalElementsCoalescedB // GlobalReadVectorWidthB
2076
2077 extraComment = ""
2078 if validDepthU:
2079 if not state["ProblemType"]["TLUA"]:
2080 if depthUA < state["GlobalReadVectorWidthA"]:
2081 validDepthU = False
2082
2083 if not state["ProblemType"]["TLUB"]:
2084 if depthUB < state["GlobalReadVectorWidthB"]:
2085 validDepthU = False
2086
2087 if state["ProblemType"]["Sparse"] and not state["DirectToVgprSparseMetadata"]:
2088 if not state["ProblemType"]["TLUMetadata"]:
2089 if depthUM < state["GlobalReadVectorWidthMetadata"]:
2090 validDepthU = False
2091
2092 # swizzle
2093 if state["LocalSplitU"] > 1:
2094 if state["ProblemType"]["SwizzleTensorA"]:
2095 SwizzlePackK = calSwizzlePackK(state, "A")
2096 if depthUA < state["MatrixInstK"] * SwizzlePackK * state["LocalSplitU"]:
2097 validDepthU = False
2098 extraComment = ": DepthU(%u) < Min-DU for swizzleA + LSU(%u)"%(depthUA, state["LocalSplitU"])
2099
2100 if state["ProblemType"]["SwizzleTensorB"]:
2101 SwizzlePackK = calSwizzlePackK(state, "B")
2102 if depthUB < state["MatrixInstK"] * SwizzlePackK * state["LocalSplitU"]:
2103 validDepthU = False
2104 extraComment = ": DepthU(%u) < Min-DU for swizzleB + LSU(%u)"%(depthUB, state["LocalSplitU"])
2105 # this depthU is valid, done unless user wants to double (for TN)
2106 if validDepthU:
2107 state["DepthU"] = depthU
2108 break
2109
2110 # this depthU not valid
2111 else:
2112 reject(state, printRejectionReason, "No valid DepthU found%s"%(extraComment))
2113 state["ValidDepthU"] = False
2114 break
2115 ########################################
2116 # end DepthU loop
2117 ########################################
2118 if state["Valid"]:
2119 break
2120 index[0] += 1
2121 if index[0] >= len(depthuList):
2122 break
2123 if not state["Valid"]:
2124 return
2125 assert(state["DepthU"]> 0)
2126
2127 if state["ScheduleIterAlg"] == 2:
2128 state["InnerUnroll"] = state["DepthU"] // state["MatrixInstK"]
2129 state["PrefetchLocalRead"] = 1
2130 state["ExpandPointerSwap"] = 1
2131 state["1LDSBuffer"] = 1
2132 print2("\nSet SIA=2, force PrefetchLocalRead=1, ExpandPointerSwap=1, 1LDSBuffer=1")
2133
2134 if state["ExpandPointerSwap"] == 1:
2135 # Pointer swap only used if PGR==1 or (PGR>1 and double/double complex) - so set ExpandPointerSwap=0 here
2136 # So far, EPS=1 and PGR>1 works only with double/double complex.
2137 #if not (bufferLoad and state["PrefetchGlobalRead"] == 1):
2138 if not (bufferLoad and ( state["PrefetchGlobalRead"] == 1 \
2139 or (state["PrefetchGlobalRead"] > 1 and \
2140 (state["ProblemType"]["DataType"].isDouble() or state["ProblemType"]["DataType"].isDoubleComplex()))
2141 or (state["ProblemType"]["Sparse"] and state["PrefetchGlobalRead"] > 0))):
2142 state["ExpandPointerSwap"] = 0
2143
2144 # Default GlobalStoreVectorWidth
2145 if state["StoreVectorWidth"] == -1:
2146 if state["SourceSwap"]:
2147 state["StoreVectorWidth"] = state["VectorWidthA"]
2148 else:
2149 if state["EnableMatrixInstruction"]:
2150 state["StoreVectorWidth"] = state["MIOutputVectorWidth"]
2151 if state["VectorWidthA"] * state["MIOutputVectorWidth"] <= 4 / state["ProblemType"]["DestDataType"].numRegisters():
2152 state["StoreVectorWidth"] = state["VectorWidthA"] * state["MIOutputVectorWidth"]
2153 if state["LocalSplitU"] > 1:
2154 state["StoreVectorWidth"] = state["VectorWidthA"]
2155 else:
2156 state["StoreVectorWidth"] = state["VectorWidthA"]
2157
2158 if state["EnableMatrixInstruction"]:
2159 if state["SourceSwap"]:
2160 if ((state["VectorWidthA"] % state["StoreVectorWidth"]) != 0):
2161 reject(state, printRejectionReason, "MFMA SourceSwap mode doesn't support vwA(%u) with svw(%u)" % (state["VectorWidthA"], state["StoreVectorWidth"]))
2162 return
2163 else:
2164 if (((state["VectorWidthA"] * state["MIOutputVectorWidth"]) % state["StoreVectorWidth"]) != 0):
2165 reject(state, printRejectionReason, "MFMA non-SourceSwap mode doesn't support miovw(%u) with svw(%u)" % (state["VectorWidthA"]*state["MIOutputVectorWidth"], state["StoreVectorWidth"]))
2166 return
2167
2168 # LocalSplitU too large?
2169 # dot2: every NumWaveSplitK threads compute the same element.
2170 numElementsPerWorkGroup = state["MacroTile0"]*state["MacroTile1"]*state["NumWaveSplitK"]
2171
2172 if numElementsPerWorkGroup < state["NumThreads"]:
2173 reject(state, printRejectionReason, "NumElementsPerWorkGroup %u < NumThreads %u; reduce LocalSplitU" \
2174 % (numElementsPerWorkGroup, state["NumThreads"]))
2175 return
2176
2177 state["NumElementsPerThread"] = numElementsPerWorkGroup // state["NumThreads"]
2178 state["GlobalWriteVectorWidth"] = min(state["VectorWidthA"], state["NumElementsPerThread"] )
2179 if state["NumElementsPerThread"] % state["GlobalWriteVectorWidth"] != 0:
2180 reject(state, printRejectionReason, "LSU NumElementsPerThread %u not divisible into GWVW %u" \
2181 % (state["NumElementsPerThread"], state["GlobalWriteVectorWidth"]))
2182 return
2183 state["NumGlobalWriteVectorsPerThread"] = state["NumElementsPerThread"] \
2184 // state["GlobalWriteVectorWidth"]
2185
2186
2187 # LocalSplitU but can't NumThreads%MacroTile doesn't support sideways store
2188 if state["LocalSplitU"] > 1:
2189 if not state["SourceSwap"] and state["StoreVectorWidth"] > state["VectorWidthA"]:
2190 reject(state, printRejectionReason, "LSU and non-SourceSwap doesn't support StoreVectorWidth(%u)>VWA(%u)." \
2191 % (state["StoreVectorWidth"], state["VectorWidthA"]))
2192 return
2193 if not (state["ProblemType"]["ComputeDataType"].isSingle() or state["ProblemType"]["ComputeDataType"].isInt32()):
2194 reject(state, printRejectionReason, "TODO: LSU doesn't support ComputeDataType!=(single or Int32).")
2195 return
2196 if state["StoreRemapVectorWidth"] > 0:
2197 reject(state, printRejectionReason, "TODO: LSU doesn't support StoreRemapVectorWidth>0.")
2198 return
2199 if state["NumThreads"] % state["MacroTile0"] != 0:
2200 reject(state, printRejectionReason, "LocalSplitU but NumThreads=%u not divisible by MT0=%u for sideways store" \
2201 % (state["NumThreads"], state["MacroTile0"]))
2202 return
2203 if state["MacroTile0"]*state["MacroTile1"] % state["NumThreads"] != 0:
2204 reject(state, printRejectionReason, "LocalSplitU but MT0*MT1=%u elements doesn't divide into NumThreads=%u" \
2205 % (state["MacroTile0"]*state["MacroTile1"], state["NumThreads"]))
2206 return
2207
2208 # GlobalSplitU doesn't work with some other things:
2209 if state["GlobalSplitU"] > 1 or state["GlobalSplitU"] == -1:
2210 # added GSU support for DGEMM
2211 supported = \
2212 (state["ProblemType"]["DataType"].isSingle()) or \
2213 (state["ProblemType"]["DataType"].isDouble() and state["BufferStore"]) or \
2214 (state["ProblemType"]["DestDataType"].isInt32()) or \
2215 (state["KernelLanguage"] == "Assembly" and
2216 (state["ProblemType"]["DataType"].isHalf() and not state["ProblemType"]["HighPrecisionAccumulate"]) or
2217 (state["_GlobalAccumulation"])
2218 )
2219 if not supported:
2220 reject(state, printRejectionReason, "GlobalSplitU only compatible with single or asm and (half or mixed) precision")
2221 return
2222
2223 if state["ProblemType"]["DataType"].isHalf() and state["KernelLanguage"] == "Assembly":
2224 if (state["GlobalSplitU"] > 1 or state["GlobalSplitU"] == -1) and (not state["_GlobalAccumulation"]):
2225 if state["AssertFree0ElementMultiple"] < 2:
2226 reject(state, printRejectionReason, "Assembly GSU half requires AF0EM>=2 (for atomics on edge tiles)")
2227
2228 if state["EnableMatrixInstruction"] and isaInfoMap[isa].asmCaps['HasWMMA']:
2229 reject(state, printRejectionReason, "Half WMMA doesn't support single buffer GSU")
2230 return
2231 # dot2 limitation
2232 if state["UseDotInstruction"]:
2233 if state["EnableMatrixInstruction"]:
2234 reject(state, "dot inst is for mac kernel!")
2235 if not bufferLoad:
2236 reject(state, "dot2 kernel only support bufferLoad!")
2237 if not ((isaInfoMap[isa].asmCaps['v_dot2_f32_f16'] and state["ProblemType"]["DataType"].isHalf()) \
2238 or (isaInfoMap[isa].asmCaps['v_dot2_f32_bf16'] and state["ProblemType"]["DataType"].isBFloat16())) \
2239 and state["ProblemType"]["HighPrecisionAccumulate"]:
2240 reject(state, "dot2 kernel only support DataType fp16 or bf16 with HPA")
2241 if state["InnerUnroll"] not in [1,2,4]:
2242 reject(state, "dot2 kernel requires InnerUnroll = 1,2 or 4")
2243 if state["NumWaveSplitK"] not in [1,2,4,8,16,32,64]:
2244 reject(state, "Unsupported NumWaveSplitK value. Need to be power of 2 and does not exceed 64.")
2245 if state["DepthU"] % (state["LocalReadVectorWidth"] * state["NumWaveSplitK"]) != 0:
2246 reject(state, "Non-valid DepthU for dot2 kernel, need to be multiple of (LocalReadVectorWidth * InnerUnroll * NumWaveSplitK) for atomics")
2247 # TODO: Need to consider VectorWidth in LraTileAssignmentVALU
2248 if state["VectorWidthA"] != 1 or state["VectorWidthB"] != 1:
2249 reject(state, "dot2 kernel requires VectorWidth = 1")
2250 # TODO: Need to remap VGPR index
2251 if (state["ThreadTile0"] != 1 or state["ThreadTile1"] != 1) and state["InnerUnroll"] > 1:
2252 reject(state, "dot2 kernel does not support wider local read with ThreadTile > 1")
2253 if state["ScheduleLocalWrite"] != 1:
2254 reject(state, "dot2 kernel requires ScheduleLocalWrite = 1")
2255 if state["LocalSplitU"] != 1:
2256 reject(state, "dot2 kernel requires LocalSplitU = 1")
2257 if state["ProblemType"]["Sparse"]:
2258 reject(state, "dot2 kernel does not support sparse gemm")
2259 # TODO: Need to fix WS address calculation of MT<16x16 cases
2260 if state["GlobalSplitUAlgorithm"] == "MultipleBufferSingleKernel":
2261 reject(state, "dot2 kernel does not support MBSK")
2262
2263 if state["ProblemType"]["Sparse"] and not state["DirectToVgprSparseMetadata"]:
2264 state["NumLoadsCoalescedMetadata"] = 1
2265
2266 if not Solution.setGlobalLoadTileDimClassic(state, "A", state["NumLoadsA"], \
2267 totalVectorsCoalescedA, totalElementsPerpA, depthUA, printRejectionReason):
2268 return
2269 if not Solution.setGlobalLoadTileDimClassic(state, "B", state["NumLoadsB"], \
2270 totalVectorsCoalescedB, totalElementsPerpB, depthUB, printRejectionReason):
2271 return
2272
2273 if state["ProblemType"]["Sparse"] and not state["DirectToVgprSparseMetadata"]:
2274 if state["ProblemType"]["TLUMetadata"]:
2275 totalElementsCoalescedM = state["MacroTileMetadata"]
2276 totalElementsPerpM = depthUM
2277 else:
2278 totalElementsCoalescedM = depthUM
2279 totalElementsPerpM = state["MacroTileMetadata"]
2280 totalElementsM = totalElementsCoalescedM * totalElementsPerpM
2281 GlobalReadVectorWidthMetadata = state["GlobalReadVectorWidthMetadata"]
2282 totalVectorsCoalescedM = totalElementsCoalescedM // GlobalReadVectorWidthMetadata
2283
2284 # Try to enlarge GLVW for metadata
2285 bGlobalReadVectorWidthMetadata = state["GlobalReadVectorWidthMetadata"]
2286 glvwMlimit = 16
2287 if state["GlobalReadVectorWidthMetadata"] < glvwMlimit:
2288 if state["ProblemType"]["Sparse"] == 2:
2289 GlobalReadVectorWidth = min(state["GlobalReadVectorWidthMetadata"] * state["NumLoadsPerpendicularB"], depthUM, glvwMlimit) #sum all need read
2290 tvm = totalElementsM // GlobalReadVectorWidth
2291 if not Solution.setGlobalReadVectorWidth(state, "Metadata", tvm, GlobalReadVectorWidth, printRejectionReason):
2292 #fallback
2293 tvm = totalElementsM // bGlobalReadVectorWidthMetadata
2294 Solution.setGlobalReadVectorWidth(state, "Metadata", tvm, bGlobalReadVectorWidthMetadata, printRejectionReason)
2295
2296 GlobalReadVectorWidthMetadata = state["GlobalReadVectorWidthMetadata"]
2297 if GlobalReadVectorWidthMetadata == 0:
2298 GlobalReadVectorWidthMetadata = 1
2299 totalVectorsCoalescedM = totalElementsCoalescedM // GlobalReadVectorWidthMetadata
2300 totalVectorsM = totalElementsM // GlobalReadVectorWidthMetadata
2301 else:
2302 GlobalReadVectorWidth = min(state["GlobalReadVectorWidthMetadata"] * state["NumLoadsPerpendicularA"], depthUM, glvwMlimit) #sum all need read
2303 tvm = totalElementsM // GlobalReadVectorWidth
2304 if not Solution.setGlobalReadVectorWidth(state, "Metadata", tvm, GlobalReadVectorWidth, printRejectionReason):
2305 #fallback
2306 tvm = totalElementsM // bGlobalReadVectorWidthMetadata
2307 Solution.setGlobalReadVectorWidth(state, "Metadata", tvm, bGlobalReadVectorWidthMetadata, printRejectionReason)
2308
2309 GlobalReadVectorWidthMetadata = state["GlobalReadVectorWidthMetadata"]
2310 if GlobalReadVectorWidthMetadata == 0:
2311 GlobalReadVectorWidthMetadata = 1
2312 totalVectorsCoalescedM = totalElementsCoalescedM // GlobalReadVectorWidthMetadata
2313 totalVectorsM = totalElementsM // GlobalReadVectorWidthMetadata
2314
2315 if not Solution.setGlobalLoadTileDimClassic(state, "Metadata", state["NumLoadsMetadata"], \
2316 totalVectorsCoalescedM, totalElementsPerpM, depthUM, printRejectionReason):
2317 return
2318
2319 # TODO
2320 if (0 and state["LSCA"] % state["GlobalReadVectorWidthA"] != 0):
2321 reject(state, printRejectionReason, "lsca % grvw != 0")
2322 return
2323 if (0 and state["LSPA"] % state["GlobalReadVectorWidthA"] != 0):
2324 reject(state, printRejectionReason, "lspa % grvw != 0")
2325 return
2326 if (0 and state["LSCB"] % state["GlobalReadVectorWidthB"] != 0):
2327 reject(state, printRejectionReason, "lscb % grvw != 0")
2328 return
2329 if (0 and state["LSPB"] % state["GlobalReadVectorWidthB"] != 0):
2330 reject(state, printRejectionReason, "lspb % grvw != 0")
2331 return
2332
2333 state["LVCA"] = roundupRatio(state["LSCA"] , state["GlobalReadVectorWidthA"])
2334 state["LVPA"] = roundupRatio(state["LSPA"] , state["GlobalReadVectorWidthA"])
2335 state["LVCB"] = roundupRatio(state["LSCB"] , state["GlobalReadVectorWidthB"])
2336 state["LVPB"] = roundupRatio(state["LSPB"] , state["GlobalReadVectorWidthB"])
2337
2338 if state["ProblemType"]["Sparse"] and not state["DirectToVgprSparseMetadata"]:
2339 state["LVCMetadata"] = roundupRatio(state["LSCMetadata"] , state["GlobalReadVectorWidthMetadata"])
2340 state["LVPMetadata"] = roundupRatio(state["LSPMetadata"] , state["GlobalReadVectorWidthMetadata"])
2341
2342 for tc in ('A','B'):
2343 if problemType["TLU%s"%tc]:
2344 pos = problemType["IndexAssignments%s"%tc].index(problemType["Index01%s"%tc])
2345 else:
2346 pos = problemType["IndexAssignments%s"%tc].index(problemType["IndexUnroll"])
2347
2348 # Some of these might become 0?
2349 if 0:
2350 print("info: ", pvar(state, "LVCA"), pvar(state, "LVPA"), \
2351 pvar(state, "LVCB"), pvar(state, "LVPB"))
2352
2353 # lds buffer size for A, B
2354 if state["KernelLanguage"] == "Source" and \
2355 state["LdsPadA"] != state["LdsPadB"]:
2356 reject(state, printRejectionReason, "Source KernelLanguage only supports LdsPadA == LdsPadB")
2357 return
2358
2359 # NoTailLoop parameter initialization.
2360 # If ASEM is multiple of DepthU TailLoop will not be used.
2361 # Unless kernel is Stream-K; Stream-K always requires TailLoop to handle work division.
2362 state["NoTailLoop"] = False
2363 if state["AssertSummationElementMultiple"] % state["DepthU"] == 0 and state["StreamK"] == 0:
2364 state["NoTailLoop"] = True
2365
2366 # Determine if we can load directly-to-Vgpr
2367 # need to check after state["LocalReadVectorWidth"] = -1 is resolved
2368 if state["DirectToVgprA"]:
2369 if not Solution.isDirectToVgprDoable(state, 'A', printRejectionReason, isaInfoMap):
2370 return # rejected
2371 if state["DirectToVgprB"]:
2372 if not Solution.isDirectToVgprDoable(state, 'B', printRejectionReason, isaInfoMap):
2373 return # rejected
2374
2375 ########################################
2376 # LDS
2377 ########################################
2378
2379 state["TransposeLDSMetadata"] = False if state["ProblemType"]["Sparse"] == 2 else True
2380 state["UnrollMajorLDSMetadata"] = False if state["ProblemType"]["Sparse"] == 2 else True
2381
2382 if state["ProblemType"]["Sparse"] and not state["DirectToVgprSparseMetadata"]:
2383 state["UnrollMajorLDSMetadata"] = state["TransposeLDSMetadata"] and (not state["ProblemType"]["TLUMetadata"])
2384
2385 # Determine if we can load directly-to-LDS.
2386 # Transpose requires a trip through registers to perform the transpose so can't use DirectToLdsA
2387 # LDS loads always write 4 bytes apart so can use only 4-byte operations
2388 # TODO - for doubles we need to add something special here?
2389 # The matrix must not require transposing since that is done by reading to VGPR and writing in different order
2390 # The LSC (load size coalesced) must load some multiple of 256 bytes since that is what each DirectToLds load provides
2391 # Note for these matrices LSC is same as MacroTile dim
2392 # MatrixInstruction rules:
2393 # DirectToLDS is supported for TLU=0 (make sure transposeLDS=1)
2394 # LDS (load size coalesced) * LSPA must load some multiple of 256 bytes.
2395 # No longer support loadX2/loadx4 .
2396 if state["DirectToLds"]:
2397
2398 if (not state["DirectToVgprA"]) and Solution.isDirectToLdsDoable(state, 'A', isaInfoMap, printRejectionReason):
2399 state['tailLoopOptA'] = False
2400 state["DirectToLdsA"] = True
2401 state["LocalWriteUseSgprA"] = True
2402
2403 if (not state["DirectToVgprB"]) and Solution.isDirectToLdsDoable(state, 'B', isaInfoMap, printRejectionReason):
2404 state['tailLoopOptB'] = False
2405 state["DirectToLdsB"] = True
2406 state["LocalWriteUseSgprB"] = True
2407
2408 # Update parent variable so kernel display is accurate
2409 state["DirectToLds"] = state["DirectToLdsA"] or state["DirectToLdsB"]
2410 if state["1LDSBuffer"] == -1 and state["DirectToLds"]:
2411 #1LDS buffer must be 0 for DirectToLdsA
2412 state["1LDSBuffer"] = 0
2413
2414 # Temp: Force enable CLR when DTL is used for TF32.
2415 # TODO: Determine why DTL+CLR=0 causes issues
2416 if state["UseF32XEmulation"] and state["DirectToLds"]:
2417 state["ClusterLocalRead"] = 1
2418
2419 # Re-check DTV + WaveGroup after DTL is confirmed
2420 if state["DirectToLds"]:
2421 if state["DirectToVgprA"] and state['MIWaveGroup'][1] > 1:
2422 reject(state, printRejectionReason, "DirectToLds + (DirectToVgprA + WaveGroups along N-Dim) is not supported yet")
2423 return False
2424 if state["DirectToVgprB"] and state['MIWaveGroup'][0] > 1:
2425 reject(state, printRejectionReason, "DirectToLds + (DirectToVgprB + WaveGroups along M-Dim) is not supported yet")
2426 return False
2427
2428 auto_LdsBlockSizePerPadA_for_mix = 0
2429 if state["LdsBlockSizePerPadA"] == -1:
2430 auto_LdsBlockSizePerPadA_for_mix = 1
2431 auto_LdsBlockSizePerPadB_for_mix = 0
2432 if state["LdsBlockSizePerPadB"] == -1:
2433 auto_LdsBlockSizePerPadB_for_mix = 1
2434 state["LdsBlockSizePerPadA"], state["LdsBlockSizePerPadB"] = calcLdsBlockSizePerPad(state["LocalReadVectorWidth"])
2435
2436 if state["LdsBlockSizePerPadMetadata"] == -1:
2437 state["LdsBlockSizePerPadMetadata"] = state["LdsBlockSizePerPadA"]
2438
2439 if state["EnableMatrixInstruction"]:
2440 if state["LdsBlockSizePerPadA"]:
2441 if state["UnrollMajorLDSA"]:
2442 if state["LdsBlockSizePerPadA"] % (state["_DepthUA"] * state["ProblemType"]["DataTypeA"].numBytes()) != 0:
2443 reject(state, printRejectionReason, "reject: LdsBlockSizePerPadA %u %% depthU %u x bpeA != 0" % (state["LdsBlockSizePerPadA"],state["_DepthUA"]))
2444 if (state["LdsBlockSizePerPadA"] // (state["_DepthUA"] * state["ProblemType"]["DataType"].numBytes())) % state["LSPA"] != 0 and \
2445 state["LSPA"] % (state["LdsBlockSizePerPadA"] // (state["_DepthUA"] * state["ProblemType"]["DataType"].numBytes())) != 0:
2446 reject(state, printRejectionReason, "can't pad by addrVgpr or instOffset")
2447
2448 if state["LdsBlockSizePerPadB"]:
2449 if state["UnrollMajorLDSB"]:
2450 if state["LdsBlockSizePerPadB"] % state["_DepthUB"] * state["ProblemType"]["DataTypeB"].numBytes() != 0:
2451 reject(state, printRejectionReason, "reject: LdsBlockSizePerPadB %u %% depthU %u x bpeB != 0" % (state["LdsBlockSizePerPadB"],state["_DepthUB"]))
2452 if (state["LdsBlockSizePerPadB"] // (state["_DepthUB"] * state["ProblemType"]["DataType"].numBytes())) % state["LSPB"] != 0 and \
2453 state["LSPB"] % (state["LdsBlockSizePerPadB"] // (state["_DepthUB"] * state["ProblemType"]["DataType"].numBytes())) != 0:
2454 reject(state, printRejectionReason, "can't pad by addrVgpr or instOffset")
2455 else:
2456 if not state["UseDotInstruction"] and (state["UnrollMajorLDSA"] or state["UnrollMajorLDSB"]):
2457 reject(state, printRejectionReason, "didn't support UnrollMajorLDS in VALU mode yet (except for dot2 kernel)")
2458 if state["LdsBlockSizePerPadA"] != 0 or state["LdsBlockSizePerPadB"] != 0:
2459 reject(state, printRejectionReason, "didn't support LdsBlockSizePerPad in VALU mode yet")
2460
2461 def checkLdsBlockSizePerPad(tc):
2462 """
2463 Simulated to calculate the local write address and local write offset, to check the pad will be added correctly or not.
2464
2465 Expected: (address + offset) // lbspp == (address // lbspp + offset // lbspp)
2466
2467 # offset is an array, the amount is 'NLP x NLC x (grvw / width of ds write instruction)'
2468 # Assumed Wave ID is zero
2469
2470 refer KernelWriterAssembly.lwaFirstOffset and KernelWriterAssembly.lwaTileAssignment to come out the address (local write address).
2471 refer KereelWriterAssembly.localWriteDo and KereelWriteAssembly.calculateLdsWriteOffset to come out the offset (local write offset).
2472 """
2473
2474 def caculateLdsWriteOffset(perp, para, sPerp, sPara, tlu, uMLds, bpe, tc, idx):
2475 mask = 0
2476 #print "tc ", tc, " perp ", perp, " para ", para, " sPerp ", sPerp, " sPara ", sPara
2477 lscaOffset = para * state["LSC%s"%tc]
2478 perp_masked = perp
2479 perp_rem = 0
2480 lspaOffset = perp_masked * state["LSP%s"%tc]
2481 rem = 0
2482
2483 # Add component offset to interleave from different regs
2484 # and compute mysterious "i"
2485 assert(sPerp==0 or sPara==0)
2486
2487 if tlu != uMLds:
2488 lspaOffset += sPerp & mask
2489 lscaOffset += sPara
2490 rem = (sPerp & ~mask)
2491 else:
2492 lscaOffset += sPara
2493 lspaOffset += sPerp
2494 rem = 0
2495
2496 lds_stride = state["_DepthU%s"%tc] if uMLds else state["MacroTile%d"%idx]
2497 if tlu != uMLds:
2498 lspaOffset *= lds_stride
2499 lspaOffset += rem + perp_rem
2500 else:
2501 lscaOffset *= lds_stride
2502 lscaOffset += rem
2503
2504 offsetElements = (lspaOffset + lscaOffset)
2505 offsetBytes = offsetElements * bpe
2506 return offsetBytes
2507
2508 def caculateLdsWriteAddress(tc, idx, serial, tlu, uMLds, grvw, bpe):
2509 id = serial
2510 if state["WaveSeparateGlobalRead%s"%tc]:
2511 id = id % state["WavefrontSize"]
2512
2513 q = id // state["LVC%s"%tc]
2514 r = id % state["LVC%s"%tc]
2515
2516 #assumed wave id = 0
2517 if state["WaveSeparateGlobalRead%s"%tc] == 2:
2518 q *= state["NumLoadsPerpendicular%s"%tc]*state["NumThreads"]//state["WavefrontSize"]
2519
2520 if tlu:
2521 t = r
2522 u = q
2523 t *= grvw
2524 else:
2525 t = q
2526 u = r
2527 u *= grvw
2528
2529 address = 0
2530 if uMLds:
2531 address = (state["_DepthU%s"%tc] * t + u) * bpe
2532 else:
2533 address = (state["MacroTile%s"%tc] * u + t) * bpe
2534
2535 return address
2536
2537 def findValidWriteBlockWidth(nwcv, bpe, bpr):
2538 localWriteWidth = nwcv * bpe // bpr
2539 if localWriteWidth < 1:
2540 localWriteWidth = (1.0* nwcv * bpe )/bpr
2541 blockWidth = 0
2542 for bw in [8, 4, 2, 1, 0.5, 0.25]:
2543 if localWriteWidth >= bw:
2544 blockWidth = bw
2545 break
2546 if blockWidth == 0:
2547 reject(state, printRejectionReason, "invalid local write block width")
2548
2549 return blockWidth
2550
2551 def subCheckLdsBlockSizePerPad(tc, idx):
2552 lbspp = state["LdsBlockSizePerPad%s"%tc]
2553 bpe = state["ProblemType"]["DataType"].numBytes()
2554 bpr = 4
2555 vw = state["GlobalReadVectorWidth%s"%tc]
2556 tlu = state["ProblemType"]["TLU%s"%tc]
2557 uMLds = state["UnrollMajorLDS%s"%tc]
2558 if tlu != uMLds: # NT no transpose
2559 wtc = False # Vector
2560 # writeCoal indicates writes should be done in the coal dim or else perp
2561 nwcv = vw
2562 nwpv = 1
2563 else: # TN yes transpose
2564 wtc = True
2565 nwcv = 1
2566 nwpv = vw
2567
2568 blockWidth = findValidWriteBlockWidth(nwcv, bpe, bpr)
2569 nwcvpi = int(blockWidth * bpr / bpe)
2570
2571 serials = []
2572 if tlu != uMLds:
2573 serials = range(0, state["LVC%s"%tc])
2574 else:
2575 serials = [state["LVC%s"%tc] * q for q in range(0, max(1, state["NumThreads"] // state["LVC%s"%tc]))]
2576
2577 for serial in serials:
2578 address = caculateLdsWriteAddress(tc, idx, serial, tlu, uMLds, vw, bpe)
2579 for perp in range(0, state["NumLoadsPerpendicular%s"%tc]):
2580 for para in range(0, state["NumLoadsCoalesced%s"%tc]):
2581 sPerp = 0
2582 sPara = 0
2583 for s in range(0, vw // nwcvpi):
2584 if tlu != uMLds:
2585 if wtc:
2586 sPerp = s
2587 else:
2588 if wtc:
2589 sPara = s
2590 offset = caculateLdsWriteOffset(perp, para, sPerp, sPara, tlu, uMLds, bpe, tc, idx)
2591 lLdsBlocks = (address + offset) // lbspp
2592 rLdsBlocks = address // lbspp + offset // lbspp
2593 if 0: #Debug
2594 pad = state["LdsPad%s"%tc]
2595 print(tc, serial, state["UnrollMajorLDS%s"%tc], perp, para, bpe, lbspp, address, offset, address // lbspp * pad * bpe, offset // lbspp * pad * bpe, lLdsBlocks, rLdsBlocks, address + offset + lLdsBlocks * pad * bpe, address + offset + rLdsBlocks * pad * bpe)
2596 if lLdsBlocks != rLdsBlocks:
2597 return False
2598 return True
2599
2600 if state["LdsBlockSizePerPad%s"%tc] != 0 and state["LdsPad%s"%tc] != 0:
2601 idx = 0 if tc == "A" else 1
2602 auto_LdsBlockSizePerPad_for_mix = auto_LdsBlockSizePerPadA_for_mix if tc == "A" else auto_LdsBlockSizePerPadB_for_mix
2603
2604 if not subCheckLdsBlockSizePerPad(tc, idx):
2605 if auto_LdsBlockSizePerPad_for_mix:
2606 printWarning("Padded address is inconisstent, set LdsBlockSizePerPad%s=0."%tc)
2607 state["LdsBlockSizePerPad%s"%tc] = 0
2608 else:
2609 reject(state, printRejectionReason, "%s's padded address is inconisstent"%tc)
2610
2611 if(not (state["CustomKernelName"] and state["CustomKernelName"] != "")): #don't check the custom kernel.
2612 checkLdsBlockSizePerPad("A")
2613 checkLdsBlockSizePerPad("B")
2614
2615 # set NoLdsWriteCode if (DirectToVgpr or DirectToLds)A+B is enabled
2616 state["NoLdsWriteCode"] = False
2617 if (state["DirectToVgprA"] or state["DirectToLdsA"]) and (state["DirectToVgprB"] or state["DirectToLdsB"]):
2618 state["NoLdsWriteCode"] = True
2619
2620 # calculate ldsPad
2621 state["LdsPadA"], state["LdsPadB"], state["LdsPadMetadata"] = calcLdsPad(state["LocalReadVectorWidth"], isaInfoMap)
2622
2623 if state["GlobalReadVectorWidthA"] * state["ProblemType"]["DataType"].numBytes() == 32 and state["LdsPadA"] == 16 // state["ProblemType"]["DataType"].numBytes():
2624 if auto_LdsBlockSizePerPadA_for_mix:
2625 state["LdsBlockSizePerPadA"] = 128
2626 assert(state["LdsPadA"] >= 0)
2627
2628 if state["GlobalReadVectorWidthB"] * state["ProblemType"]["DataType"].numBytes() == 32 and state["LdsPadB"] == 16 // state["ProblemType"]["DataType"].numBytes():
2629 if auto_LdsBlockSizePerPadB_for_mix:
2630 state["LdsBlockSizePerPadB"] = 128
2631 assert(state["LdsPadB"] >= 0)
2632
2633 if (state["UnrollMajorLDSA"] or state["UnrollMajorLDSB"]) and (not state["EnableMatrixInstruction"]) and (not state["UseDotInstruction"]):
2634 reject(state, printRejectionReason, "UnrollMajorLDS Supports only in EnableMatrixInstruction=1 or dot2 kernel")
2635
2636 ldsNumBytesA, ldsNumBytesAlignedA, ldsNumBytesB, ldsNumBytesAlignedB, ldsNumBytesMetadata, ldsNumBytesAlignedMetadata = calcLdsNumBytes(state["LdsPadA"], state["LdsBlockSizePerPadA"], state["LdsPadB"], state["LdsBlockSizePerPadB"])
2637 state["LdsOffsetA_Blk"]=0
2638 state["LdsOffsetB_Blk"]=0
2639 state["LdsOffsetMetadata_Blk"]=0
2640 # todo, can the alignment be a power of 2?
2641 state["LdsOffsetA"] = 0
2642 state["LdsNumElementsAlignedA"] = ldsNumBytesAlignedA
2643 state["LdsNumElementsAlignedB"] = ldsNumBytesAlignedB
2644 state["LdsNumElementsAlignedMetadata"] = ldsNumBytesAlignedMetadata
2645 if state["PrefetchGlobalRead"]:
2646 state["LdsOffsetMetadata"] = state["LdsOffsetA"] + state["LdsNumElementsAlignedA"]
2647 state["LdsOffsetB"] = state["LdsOffsetMetadata"] + state["LdsNumElementsAlignedMetadata"]
2648
2649 offsetBlk = state["LdsOffsetB"] + ldsNumBytesAlignedB
2650
2651 state["StoreSwapAddr"] = (state["PrefetchGlobalRead"] == 2) and \
2652 (state["1LDSBuffer"] == 0) and \
2653 (offsetBlk + int(2**(math.ceil(math.log(offsetBlk, 2)))) > state["MaxLDS"])
2654
2655 if offsetBlk > 0 and not state["StoreSwapAddr"]:
2656 # Rounds offsetBlk to a power of two to enable inlining {s,v}_xor constants for swapping offsets
2657 offsetBlk = int(2**(math.ceil(math.log(offsetBlk, 2))))
2658
2659 state["LdsOffsetA_Blk"] = offsetBlk
2660 state["LdsOffsetMetadata_Blk"] = state["LdsOffsetA_Blk"] + state["LdsNumElementsAlignedA"]
2661 state["LdsOffsetB_Blk"] = state["LdsOffsetMetadata_Blk"] + state["LdsNumElementsAlignedMetadata"]
2662 ldsNumBytesAB = state["LdsOffsetB_Blk"] + ldsNumBytesB
2663 else:
2664 state["LdsOffsetMetadata"] = ldsNumBytesAlignedA
2665 state["LdsOffsetB"] = state["LdsOffsetMetadata"] + ldsNumBytesAlignedMetadata
2666 ldsNumBytesAB = state["LdsOffsetB"] + ldsNumBytesB
2667
2668 # lds buffer size for reduction
2669 # if User want to control the LDS usage, we may open this para in the future
2670 ldsNumBytesReduction = state["LocalSplitU"] * state["MacroTile0"] * state["MacroTile1"] * state["ProblemType"]["ComputeDataType"].numBytes() if state["LocalSplitU"] > 1 else 0
2671 state["LocalSplitUReuseLDS"] = 1
2672 if ldsNumBytesReduction > state["MaxLDS"]:
2673 state["LocalSplitUReuseLDS"] = math.ceil(ldsNumBytesReduction / state["MaxLDS"])
2674 # reserve all the LDS to LSU.
2675 ldsNumBytesReduction = state["MaxLDS"]
2676
2677 # lds max occupancy
2678 ldsSizeOccupancy = isaInfoMap[isa].archCaps["DeviceLDS"] // state["MaxOccupancy"]
2679 ldsNumBytesOccupancy = ldsSizeOccupancy
2680
2681 #print("LdsOffsetB", state["LdsOffsetB"])
2682 #print("LdsOffsetMetadata", state["LdsOffsetMetadata"])
2683 #if state["PrefetchGlobalRead"]:
2684 # print("LdsOffsetA_BLK", state["LdsOffsetA_Blk"])
2685 # print("LdsOffsetB_BLK", state["LdsOffsetB_Blk"])
2686 # print("LdsOffsetMetadata_BLK", state["LdsOffsetMetadata_Blk"])
2687
2688 if state["EnableMatrixInstruction"]:
2689 if state["DirectToLds"] and state["1LDSBuffer"]:
2690 reject(state, printRejectionReason, "1LDSBuffer must be 0 for directToLds")
2691
2692 if state["1LDSBuffer"] == -1:
2693 if ldsNumBytesAB <= max(ldsSizeOccupancy,32768) or \
2694 (state["ProblemType"]["ComputeDataType"].numBytes() * state["MacroTile0"] * state["MacroTile1"] > 32768*4 and \
2695 not (ldsNumBytesAB > isaInfoMap[isa].archCaps["DeviceLDS"])):
2696 state["1LDSBuffer"] = 0
2697 else:
2698 state["1LDSBuffer"] = 1
2699
2700 if state["1LDSBuffer"]:
2701 if not state["PrefetchGlobalRead"]:
2702 reject(state, printRejectionReason, "PGR=0 already use 1 LDS buffer only")
2703 # Should be able to support as long as NO scheduleLocalWrite
2704 if (not state["ScheduleIterAlg"] == 2) and (not state["ScheduleIterAlg"] == 3) and (state["ScheduleLocalWrite"]):
2705 reject(state, printRejectionReason, "1LDSBuffer only support SIA2 or SIA3, or SIA1 without SLW")
2706 state["LdsOffsetB"] = ldsNumBytesAlignedA
2707 state["LdsOffsetMetadata"] = state["LdsOffsetB"] + ldsNumBytesAlignedB
2708 ldsNumBytesAB = ldsNumBytesAlignedA + ldsNumBytesAlignedB + ldsNumBytesMetadata
2709
2710 # lds size is the greater of the two
2711 ldsNumBytes = max(ldsNumBytesAB, ldsNumBytesReduction, ldsNumBytesOccupancy)
2712
2713 if state["NumElementsPerBatchStore"] == -1:
2714 if ldsNumBytes > 32768 or \
2715 state["ProblemType"]["ComputeDataType"].numBytes() * state["MacroTile0"] * state["MacroTile1"] > 32768*4:
2716 state["NumElementsPerBatchStore"] = 0
2717 state["StorePriorityOpt"] = 0
2718 state["StoreSyncOpt"] = 0
2719 state["GroupLoadStore"] = 0
2720 else:
2721 state["NumElementsPerBatchStore"] = 16 if not state["ProblemType"]["DataType"].numBytes() == 8 else 1
2722
2723 # Mbsk prefetch optimization
2724 if state["_GlobalAccumulation"] != 'MultipleBufferSingleKernel':
2725 state["MbskPrefetchMethod"] = 0
2726 elif state["MbskPrefetchMethod"] == -1:
2727 numStoreElements = state["NumElementsPerThread"] // state["StoreVectorWidth"]
2728 state["MbskPrefetchMethod"] = 1 if numStoreElements >= 4 else 0
2729 if state["MbskPrefetchMethod"] == 1:
2730 state["NumMbskPrefetchElements"] = 16
2731 storeRegs = state["StoreVectorWidth"] * state["ProblemType"]["ComputeDataType"].numRegisters()
2732 # exceed 16*4 = 64 VPGRs
2733 if storeRegs > 4:
2734 state["NumMbskPrefetchElements"] //= storeRegs // 4
2735 if state["NumElementsPerBatchStore"] == 0 or state["NumElementsPerBatchStore"] > state["NumMbskPrefetchElements"]:
2736 state["NumElementsPerBatchStore"] = state["NumMbskPrefetchElements"]
2737
2738 if state["StoreRemapVectorWidth"] == -1:
2739 # use de_read_b64 as default in storeRemap to avoid bank conflict
2740 defaultRemap = 8 // state["ProblemType"]["DestDataType"].numBytes()
2741 defaultRemap = max(defaultRemap, state["MacroTile0"]//state["WavefrontSize"])
2742 if state["EnableMatrixInstruction"]:
2743 ldsRemapPad = max(defaultRemap, state["MIOutputVectorWidth"])
2744 ldsNumElementsRemapC = (state["MacroTile0"]+ldsRemapPad)* state["MatrixInstN"] * state["MIWaveGroup"][1]
2745 computeBytes = state["ProblemType"]["ComputeDataType"].numBytes()
2746 # max(GlobalAccumulation case, non-GlobalAccumulation)
2747 ldsNumElementsRemapC = max(ldsNumElementsRemapC, ldsNumElementsRemapC * (computeBytes / state["ProblemType"]["DestDataType"].numBytes()))
2748 ldsSize = ldsNumElementsRemapC * state["ProblemType"]["DestDataType"].numBytes()
2749 if not math.log(state["MacroTile0"],2).is_integer() or \
2750 ldsSize > state["MaxLDS"] or \
2751 state["SourceSwap"] or \
2752 (state["GlobalSplitU"] > 1 or state["GlobalSplitU"] == -1) and (state["_GlobalAccumulation"] != 'MultipleBuffer') or \
2753 state["MatrixInstBN"] > 1 and state["MatrixInstN"] == 4 :
2754 state["StoreRemapVectorWidth"] = 0
2755 else:
2756 state["StoreRemapVectorWidth"] = defaultRemap
2757 else:
2758 state["StoreRemapVectorWidth"] = defaultRemap
2759
2760 if not state["SourceSwap"]:
2761 if not state["StoreRemapVectorWidth"]:
2762 reject(state, printRejectionReason, "reject to reduce number of kernels")
2763 elif state["VectorWidthA"] > 1:
2764 reject(state, printRejectionReason, "reject to reduce number of kernels")
2765
2766 # GuaranteeNoPartial
2767 if state["ProblemType"]["TLUA"]:
2768 state["GuaranteeNoPartialA"] = state["AssertFree0ElementMultiple"]%state["GlobalReadVectorWidthA"]==0
2769 else:
2770 state["GuaranteeNoPartialA"] = True
2771
2772 if state["ProblemType"]["TLUB"]:
2773 state["GuaranteeNoPartialB"] = state["AssertFree1ElementMultiple"]%state["GlobalReadVectorWidthB"]==0
2774 else:
2775 state["GuaranteeNoPartialB"] = True
2776
2777 state["GuaranteeNoPartialMetadata"] = False if state["ProblemType"]["Sparse"] else True
2778
2779 # SourceSwap
2780 if state["StoreRemapVectorWidth"]:
2781 if state["SourceSwap"]:
2782 reject(state, printRejectionReason, "SourceSwap not compatible with StoreRemap")
2783 return
2784 if state["VectorWidthA"] > 1 or state["VectorWidthB"] > 1:
2785 reject(state, printRejectionReason, "VW>1 not compatible with StoreRemap")
2786 return
2787
2788 # Sparse problem
2789 if state["ProblemType"]["Sparse"]:
2790 if state["PrefetchGlobalRead"] and not state["ExpandPointerSwap"]:
2791 reject(state, printRejectionReason, "Sparse A kernel only support PGR with EPS=1.")
2792 return
2793 if state["EnableMatrixInstruction"] and state["MIArchVgpr"]:
2794 reject(state, printRejectionReason, "Sparse A kernel does not support MIArchVgpr yet.")
2795 return
2796 # Not Support Feature
2797 if state["ProblemType"]["Sparse"] == 1 and state["SourceSwap"] :
2798 reject(state, printRejectionReason, "Sparse A kernel cannot support SourceSwap.")
2799 return
2800 else:
2801 if state["ProblemType"]["Sparse"] == 2 and not state["SourceSwap"]:
2802 reject(state, printRejectionReason, "Sparse B kernel must enable SourceSwap.")
2803 return
2804 state["AssertSummationElementMultiple"] = 8
2805
2806 # check if need to use lds init Acc vgprs
2807 state["LdsInitCVgprs"] = False
2808 if isaInfoMap[isa].archCaps["HasAccCD"] and \
2809 state["EnableMatrixInstruction"] and state["StorePriorityOpt"] and \
2810 state["ProblemType"]["DataType"].isDouble():
2811 state["LdsInitCVgprs"] = True
2812
2813 # force MIArchVgpr when using WMMA
2814 if state["EnableMatrixInstruction"] and isaInfoMap[isa].asmCaps["HasWMMA"]:
2815 state["MIArchVgpr"] = True
2816
2817 if state["MIArchVgpr"]:
2818 if not state["EnableMatrixInstruction"]:
2819 reject(state, printRejectionReason, "MIArchVgpr only support for MatrixInstruction")
2820 return
2821
2822 if isaInfoMap[isa].asmCaps["HasMFMA"]:
2823 if not (state["ProblemType"]["ComputeDataType"].isDouble() or \
2824 state["ProblemType"]["ComputeDataType"].isSingle() or \
2825 (state["ProblemType"]["ComputeDataType"].isHalf() and state["ProblemType"]["HighPrecisionAccumulate"]) or \
2826 state["ProblemType"]["ComputeDataType"].isInt32() or \
2827 state["ProblemType"]["ComputeDataType"].isComplex()):
2828 reject(state, printRejectionReason, "MIArchVgpr now only support fp64, fp64c, fp32, fp32c, fp16, int8 MatrixInstruction.")
2829 return
2830
2831 #check not support cases and calculate lds resources
2832 ldsNumBytesRemapC = 0
2833 if state["StoreRemapVectorWidth"]:
2834 if not state["EnableMatrixInstruction"]:
2835 reject(state, printRejectionReason, "storeRemap only support MatrixInstruction kernel")
2836 return
2837 if ((state["GlobalSplitU"] > 1 or state["GlobalSplitU"] == -1) and (state["_GlobalAccumulation"] != 'MultipleBuffer' or state["_GlobalAccumulation"] == 'MultipleBufferSingleKernel')) or \
2838 ((state["GlobalSplitU"] == 1 or state["GlobalSplitU"] == -1) and state["_GlobalAccumulation"] == 'SingleBuffer'):
2839 reject(state, printRejectionReason, "storeRemap doesn't support GlobalSplitU yet, except GSU algorithm 2")
2840 return
2841 if packedC0 or packedC1:
2842 reject(state, printRejectionReason, "storeRemap doesn't support packedC0 and packedC1 yet")
2843 return
2844 if state["MatrixInstBN"] > 1 and state["MatrixInstN"] == 4:
2845 reject(state, printRejectionReason, "storeRemap doesn't support MI4x4 multi blocks in N direction yet")
2846 return
2847 if not math.log(state["MacroTile0"],2).is_integer():
2848 reject(state, printRejectionReason, "storeRemap only supports power-of-2 MT0")
2849 # TODO - this return should be here, but this is a hotfix,
2850 # Somehow we have a "Validation Failed" kernel in rocBLAS now (SRVW=4 and MT0=96) and this will stop the whole building process
2851 # Actions: 1. Hotfix, comment out this "return" temporarily for that invalidated kernel
2852 # 2. Remove / replace that invalidated kernel
2853 # 3. Put back this return
2854 # 4. How to design a better way to prevent from invalid kernel in rocBLAS?
2855 # return
2856
2857 storeInstMinWidth = 1 # minimum dwordx1
2858 storeInstMaxWidth = 4 # maximum dwordx4
2859 srMinVw = max(storeInstMinWidth, int(storeInstMinWidth/state["ProblemType"]["DestDataType"].numRegisters()))
2860 numReg = max(state["ProblemType"]["DestDataType"].numRegisters(), state["ProblemType"]["ComputeDataType"].numRegisters())
2861
2862 srMaxVw = int(storeInstMaxWidth/numReg)
2863 # FIXME: Add StoreRemapVectorWidthGSU and StoreRemapVectorWidthNonGSU
2864 while srMaxVw < state["StoreRemapVectorWidth"]:
2865 state["StoreRemapVectorWidth"] = state["StoreRemapVectorWidth"] // 2
2866 if srMinVw > state["StoreRemapVectorWidth"] or srMaxVw < state["StoreRemapVectorWidth"]:
2867 reject(state, printRejectionReason, "StoreRemapVectorWidth %u is not allowed for this data type" % state["StoreRemapVectorWidth"])
2868 return
2869
2870 if state["StoreRemapVectorWidth"] * state["WavefrontSize"] < state["MacroTile0"]:
2871 reject(state, printRejectionReason, "storeRemap: Per wave single global write instruction doesn't enough to write one M column." + \
2872 " Please use larger StoreRemapVectorWidth.")
2873 return
2874 if (state["MacroTile0"]*state["MatrixInstN"])//state["MIWaveGroup"][0] < state["StoreRemapVectorWidth"]*state["WavefrontSize"]:
2875 reject(state, printRejectionReason, "storeRemap: number elements of lds less than per wave per local read elements." + \
2876 " Please use smaller StoreRemapVectorWidth.")
2877 return
2878 ldsRemapPad = max(state["StoreRemapVectorWidth"],state["MIOutputVectorWidth"])
2879 ldsNumBytesRemapC = (state["MacroTile0"]+ldsRemapPad)* state["MatrixInstN"] * state["MIWaveGroup"][1]
2880
2881
2882 computeBytes = state["ProblemType"]["ComputeDataType"].numBytes()
2883 multiplierGSU = computeBytes
2884 if state["ProblemType"]["DestDataType"].numBytes() > state["ProblemType"]["DataType"].numBytes():
2885 # Determine ratio of output to input element size.
2886 # SRVW remaps output so we need to scale up resources.
2887 multiplier = state["ProblemType"]["DestDataType"].numBytes()
2888 else:
2889 multiplier = state["ProblemType"]["DataType"].numBytes()
2890
2891 ldsNumBytesRemapCNonGSU = ldsNumBytesRemapC * multiplier
2892 ldsNumBytesRemapCGSU = ldsNumBytesRemapC * multiplierGSU
2893 ldsNumBytesRemapC *= max(multiplier, multiplierGSU)
2894
2895
2896 #print("ldsNumBytesRemapC=%u" % ldsNumBytesRemapC)
2897
2898 # if LDS is bound by RemapC (SRVW), then 1LDSBuffer actually doesn't help in SIA3
2899 # since LDS usage couldn't be reduced
2900 if state["1LDSBuffer"] and (state["ScheduleIterAlg"] == 3) and (ldsNumBytes < ldsNumBytesRemapC):
2901 # TODO- Remove this DataType test condition,
2902 # Currently we do this test is just because we don't want to affect existing logic in rocBLAS
2903 if state["ProblemType"]["DataType"].isInt8():
2904 reject(state, printRejectionReason, "LDS usage is bound be StoreRemap, thus 1LDSBuffer wouldn't have any help. Skip.")
2905 return
2906
2907 ldsNumBytes = max(ldsNumBytes, ldsNumBytesRemapC)
2908
2909 state["LdsOffsetBias"] = 0 # TODO: ldsBiasOffset = ldsNumBytesAB
2910 state["LdsOffsetBiasNonGSU"] = 0
2911 state["LdsOffsetBiasGSU"] = 0
2912
2913 # TODO: Should change name to LdsOffsetEpilogue or something.
2914 if state["StoreRemapVectorWidth"]:
2915 state["LdsOffsetBiasNonGSU"] = ldsNumBytesRemapCNonGSU
2916 state["LdsOffsetBiasGSU"] = ldsNumBytesRemapCGSU
2917 state["LdsOffsetBias"] = ldsNumBytesRemapC
2918
2919 # Calcualte the correct LDS usages
2920 def calcEpilogueTurns(factorDims: List) -> int:
2921 divisor = state["SubGroup0"] * state["SubGroup1"]
2922 # d will be a list containing 0 or 1
2923 maxTurn = 0
2924 for d in range(len(factorDims)):
2925 turn = math.ceil(state["MacroTile%d"%d] / divisor)
2926 maxTurn = max(maxTurn, turn)
2927 return maxTurn
2928
2929 # Calc the required LDS
2930 vecDT = VectorDataTypes()
2931 biasDim = state["ProblemType"]["UseBias"]
2932 savDim = state["ProblemType"]["UseScaleAlphaVec"]
2933 sAB = state["ProblemType"]["UseScaleAB"] == "Vector"
2934 # Calc LDS for Bias
2935 maxTurn = 0
2936 if biasDim == 1:
2937 maxTurn = calcEpilogueTurns([0])
2938 elif biasDim == 2:
2939 maxTurn = calcEpilogueTurns([1])
2940 elif biasDim == 3:
2941 maxTurn = calcEpilogueTurns([0, 1])
2942 vecDT.bias(0).turn = maxTurn
2943 vecDT.bias(1).turn = maxTurn
2944
2945 # Calc LDS for SAV
2946 maxTurn = 0
2947 if savDim == 1:
2948 maxTurn = calcEpilogueTurns([0])
2949 elif savDim == 2:
2950 maxTurn = calcEpilogueTurns([1])
2951 elif savDim == 3:
2952 maxTurn = calcEpilogueTurns([0, 1])
2953 vecDT.scaleAlpha(0).turn = maxTurn
2954 vecDT.scaleAlpha(1).turn = maxTurn
2955
2956 # Calc LDS for ScaleA, ScaleB
2957 if sAB:
2958 vecDT.scaleA.turn = calcEpilogueTurns([0])
2959 vecDT.scaleB.turn = calcEpilogueTurns([1])
2960
2961 epilogueSize = 0
2962 # Bias
2963 if state["ProblemType"]["UseBias"]:
2964 # Currently all offsets starts from 0
2965 if state["ProblemType"]["Gradient"]:
2966 if state["ProblemType"]["BiasSrc"] == "A":
2967 tile01 = state["ProblemType"]["Index01A"]
2968 elif state["ProblemType"]["BiasSrc"] == "B":
2969 tile01 = state["ProblemType"]["Index01B"]
2970 elif state["ProblemType"]["BiasSrc"] == "D":
2971 tile01 = -1
2972 else:
2973 assert 0 and "Unsupported tile01 for bias lds calculation."
2974 # Don't need to calculate lds bias
2975 if tile01 > -1:
2976 maxKId = state["WavefrontSize"] // ((state["MatrixInstM"] if (tile01 == 0) else state["MatrixInstN"]) * state["MatrixInstB"])
2977 for dataType in state["ProblemType"]["BiasDataTypeList"]:
2978 epilogueSize = max(epilogueSize, state["MacroTile%d"%tile01] * maxKId * dataType.numBytes()) # TODO- GetTurn ?
2979 else:
2980 epilogueSize = state["NumThreads"] * state["ProblemType"]["ComputeDataType"].numBytes() * vecDT.bias(0).turn
2981 # Calculate max ldsNumBytes for other epilogues
2982 if state["ProblemType"]["UseScaleAlphaVec"]:
2983 epilogueSize += state["NumThreads"] * state["ProblemType"]["ComputeDataType"].numBytes() * vecDT.scaleAlpha(0).turn
2984 if state["ProblemType"]["UseScaleAB"] == "Vector":
2985 epilogueSize += state["NumThreads"] * state["ProblemType"]["ComputeDataType"].numBytes() * (vecDT.scaleA.turn + vecDT.scaleB.turn)
2986 ldsNumBytes = max(ldsNumBytes, state["LdsOffsetBias"] + epilogueSize)
2987
2988 state["LdsBytesNoAmax"] = ldsNumBytes
2989 if state["ProblemType"]["OutputAmaxD"]:
2990 # used in reduce inter wave
2991 # 4 data * half_wave_num * amax bytePerE
2992 num_workItems = state["NumThreads"]
2993 half_wave_size = state["WavefrontSize"] // 2
2994 amaxBPE = state["ProblemType"]["DataTypeAmaxD"].numBytes()
2995 ldsAmaxDBytes = 4 * (num_workItems // half_wave_size) * amaxBPE
2996 ldsNumBytes += ldsAmaxDBytes
2997
2998 state["LdsNumBytes"] = ldsNumBytes
2999 ldsSize = ldsNumBytes
3000 if ldsSize > state["MaxLDS"]:
3001 reject(state, printRejectionReason, "Kernel Uses %u > %u bytes of LDS" % ( ldsSize, state["MaxLDS"]))
3002 state["ValidDepthU"] = False
3003 return
3004
3005 # LoopUnroll = DepthU / LocalSplitU
3006 if "LocalSplitU" in state:
3007 state["LoopUnroll"] = state["DepthU"] // state["LocalSplitU"]
3008 if state["LoopUnroll"] * state["LocalSplitU"] != state["DepthU"]:
3009 state["Valid"] = False
3010 if state["KernelLanguage"] != "Assembly" and state["InnerUnroll"] != 1:
3011 reject(state, printRejectionReason, "InnerUnroll only supported on assembly")
3012 state["LoopUnroll"] //= state["InnerUnroll"]
3013
3014 if 0:
3015 print("info: ", pvar(state, "LoopUnroll"), " LDS Stats:", pvar(state, "LdsOffsetA"), pvar(state, "LdsOffsetB"))
3016 print("info: ", pvar(state["ProblemType"], "TLUA"), \
3017 pvar(state, "NumLoadsCoalescedA"), pvar(state, "NumLoadsPerpendicularA"), \
3018 pvar(state, "LSCA"), pvar(state, "LSPA"))
3019 print("info:", pvar(state["ProblemType"], "TLUB"), \
3020 pvar(state, "NumLoadsCoalescedB"), pvar(state, "NumLoadsPerpendicularB"), \
3021 pvar(state, "LSCB"), pvar(state, "LSPB"))
3022
3023 state["LoopIters"] = state["LoopUnroll"]
3024 if state["EnableMatrixInstruction"]:
3025 state["LoopIters"] //= state["MatrixInstK"]
3026 elif state["UseDotInstruction"]:
3027 # dot2
3028 state["LoopIters"] //= (state["NumDotElements"] * state["NumWaveSplitK"])
3029
3030 if state["LoopIters"] < 1:
3031 reject(state, printRejectionReason, "LoopIters need to greater than 0")
3032 return
3033
3034 # Since we use PLR >= LoopIters for allocating numberOfIters vgprBuffer for a while
3035 # we need to support both PLR >= LoopIters and CLR parameter for solutions in rocBLAS
3036 if state["ClusterLocalRead"] and state["PrefetchLocalRead"] >= state["LoopIters"] and not state["ScheduleIterAlg"] == 2:
3037 # 1 or 2 Byte input + DTVA or DTVB case, does not work with PLR=0. Reject it here.
3038 if state["ProblemType"]["DataType"].numBytes() < 4 and \
3039 (state["ProblemType"]["TLUA"] and state["DirectToVgprA"] or state["ProblemType"]["TLUB"] and state["DirectToVgprB"]):
3040 reject(state, printRejectionReason, "DirectToVgpr does not work with 1 or 2 Byte input + TLU + PrefetchLocalRead(%u) >= LoopIters(%u)"%(state["PrefetchLocalRead"], state["LoopIters"]))
3041 return
3042 state["ClusterLocalRead"] = 0
3043 state["PrefetchLocalRead"] = 0
3044 if not state["EnableMatrixInstruction"]:
3045 state["ClusterLocalRead"] = 0
3046 # dot2: allow PLR=1
3047 if state["UseDotInstruction"]:
3048 state["PrefetchLocalRead"] = min(state["PrefetchLocalRead"], state["LoopIters"]-1)
3049 if state["LoopIters"] % (state["PrefetchLocalRead"]+1) != 0:
3050 reject(state, "dot2 kernel does not support LoopIters(%u) %% (PLR+1)(%u) != 0" % (state["LoopIters"], state["PrefetchLocalRead"]+1))
3051
3052 # reject iterations are not enough to use wider local read
3053 if state["EnableMatrixInstruction"] and state["PrefetchLocalRead"] > 0:
3054 # Multiple = WLR-size / input-size = how many iters could be covered by one WLR ?
3055 wlrMultiple = state["LocalReadVectorWidth"]//state["MIInputPerThread"]
3056 # NOTE: wlrmultiple can be 0 for new MFMA
3057 if not state["ProblemType"]["Sparse"] and not state["UseF32XEmulation"] and not(state["ProblemType"]["DataType"].is8bitFloat() and (state["MatrixInstK"] == 64 or state["MatrixInstK"] == 128)):
3058 if wlrMultiple == 0:
3059 reject(state, printRejectionReason, "LocalReadVectorWidth %u is less than MIInput" % (state["LocalReadVectorWidth"]))
3060 return
3061 # for example, if the original ds_read is b32...
3062 # 1. if LoopIters = 5 (b32 x 5 times), WLR-Multiple = 2 (b64), then we can fit the WLR
3063 # 2. if LoopIters = 2 (b32 x 2 times), WLR-Multiple = 4 (b128), this is not allowed
3064 # 3. if LoopIters = 2 (b32 x 2 times), WLR-Multiple = 2 (b64), this is allowed
3065 if wlrMultiple and state["LoopIters"] % wlrMultiple != 0:
3066 reject(state, printRejectionReason, "LocalReadVectorWidth %u cannot be distributed evenly, LoopIters %u should be divisible by WLR-Multiple %u" \
3067 % (state["LocalReadVectorWidth"], state["LoopIters"], wlrMultiple))
3068
3069 if state["LoopIters"] - (state["PrefetchLocalRead"] * wlrMultiple) < 0 :
3070 reject(state, printRejectionReason, "with PrefetchLocalRead %u LoopIters %u LocalReadVectorWidth %u, not enough LoopIters to prefetch %ux%u iterations, " \
3071 % (state["PrefetchLocalRead"],state["LoopIters"],state["LocalReadVectorWidth"], state["PrefetchLocalRead"] , wlrMultiple) )
3072
3073 # # reject conditions with lower performance
3074 # if state["ScheduleIterAlg"] == 2 and \
3075 # (state["ExpandPointerSwap"] != 1 or state["LoopIters"] != 1 or state["ScheduleGlobalRead"] != 1):
3076 # reject(state, printRejectionReason, "ScheduleIterAlg 2 only work with EPS1_SGR1, LoopIter=1")
3077
3078 if state["TransposeLDS"] == 1:
3079 if not state["EnableMatrixInstruction"]:
3080 reject(state, printRejectionReason, "TransposeLds Supports only in MatrixInstruction=1")
3081 if state["ProblemType"]["TLUA"] and state["ProblemType"]["TLUB"]:
3082 # TODO: Now in rocBLAS, lot of logic yamls are Type=NT and TLDS=1? Why aren't they rejected and how to get rid of them?
3083 reject(state, printRejectionReason, "TransposeLds requires TLUA=0 or TLUB=0")
3084 if state["EnableMatrixInstruction"]:
3085 # enable widerLocalRead
3086 if state["LocalReadVectorWidth"] > state["MIInputPerThread"]:
3087 # wider localRead support 2 types
3088 # 1. prefetch all lds to register
3089 # 2. using larger InnerUnroll
3090 if not (state["PrefetchLocalRead"] >= state["LoopIters"] and state["InnerUnroll"] == 1) and \
3091 not state["ClusterLocalRead"] and \
3092 not state["InnerUnroll"] >= state["LocalReadVectorWidth"] // state["MIInputPerThread"]:
3093 reject(state, printRejectionReason, "wider localRead only support ClusterLocalRead or (InnerUnroll > WiderLocalReadxN)")
3094
3095 if state["GlobalReadPerMfma"] > 1 and state["PrefetchGlobalRead"] == 2:
3096 reject(state, printRejectionReason, "GlobalReadPerMfma need to be 1 if PGR2")
3097
3098 if state["UseInstOffsetForGRO"] == -1:
3099 state["UseInstOffsetForGRO"] = 1 if state["DirectToLds"] else 0
3100
3101 state["ULSGRODoubleG2L"] = 0
3102 if state["UnrollLoopSwapGlobalReadOrder"] == 1:
3103 bpeAB = state["ProblemType"]["DataType"].numBytes()
3104 bpr = 4
3105 numVgprG2LA = roundUp((state["NumLoadsCoalescedA"] * state["NumLoadsPerpendicularA"] * \
3106 state["GlobalReadVectorWidthA"] * bpeAB) / (float)(bpr))
3107 numVgprG2LB = roundUp((state["NumLoadsCoalescedB"] * state["NumLoadsPerpendicularB"] * \
3108 state["GlobalReadVectorWidthB"] * bpeAB) / (float)(bpr))
3109 if numVgprG2LA % 2 == 1 or numVgprG2LB % 2 == 1:
3110 reject(state, printRejectionReason, "G2LA/B vgpr has bubble inside. Cannot use UnrollLoopSwapGlobalReadOrder=1.")
3111 if state["GlobalReadVectorWidthA"] != state["GlobalReadVectorWidthB"]:
3112 # TODO: Add a configuration to schedule better.
3113 state["ULSGRODoubleG2L"] = 1
3114 minGRVW = min(state["GlobalReadVectorWidthA"], state["GlobalReadVectorWidthB"])
3115 if minGRVW * bpeAB < 4:
3116 # G2LA/B vgpr index will jump.
3117 state["ULSGRODoubleG2L"] = 1
3118 if state["ExpandPointerSwap"] == 1:
3119 reject(state, printRejectionReason, "ExpandPointerSwap need to be 0 if UnrollLoopSwapGlobalReadOrder")
3120 if state["PrefetchGlobalRead"] != 2:
3121 reject(state, printRejectionReason, "PrefetchGlobalRead need to be 2 if UnrollLoopSwapGlobalReadOrder")
3122 if state["ProblemType"]["DataTypeA"].numBytes() != state["ProblemType"]["DataTypeB"].numBytes():
3123 reject(state, printRejectionReason, "UnrollLoopSwapGlobalReadOrder doesn't support mixed precision.")
3124
3125 if state["ExpandPointerSwap"] == 1 and state["LDSTrInst"]:
3126 reject(state, printRejectionReason, "LDSTrInst + ExpandPointerSwap not supported")
3127
3128 # guard against out of bounds reads
3129 # None: don't guard against ou
3130 # ShiftPtr: shift read pointers to be in bounds, then unshift registers (source & assembly),
3131 # ShiftPtr does not support very small problem dims < global load vector width since the shift
3132 # would move outside the array bounds.
3133 # If GLVW==1 or Assert*ElementMultiple for the coalesced dim is > GRVW, then shifting is not
3134 # necessary and the shift/unshift code will not be generated
3135 state["EdgeType"] = "ShiftPtr" # Use ShiftPtr by default
3136
3137 # Precise bounds check uses the "num_records" field in the buffer to
3138 # precisely detect when we are inbounds or not. Only a one-dimensional
3139 # check is used since this is faster and also for computation we only
3140 # need to ensure that none of the loads fault. threads which are
3141 # computing bogus sections of the C tile will later be ignored.
3142 # precise checking only works when all elements of the load are in-bounds
3143 # since if the vload crosses boundary we ignore all components not just the
3144 # ones that are OOB. See comments for groOffsetInMacroTile in KernelWriterAssembly.py
3145 #
3146 # So check for the cases where the unroll loop can
3147 # generate partial loads here and reject PBC solutions:
3148 # For non-TLU the free dim is in perp dim - should always be TRUE? TODO
3149
3150 #--
3151 # ShiftPtr can't use UseSgprForGRO since it needs to modify the VGPR pointers
3152 if bufferLoad and state["_UseSgprForGRO"] and state["EdgeType"]=="ShiftPtr":
3153 if not state["GuaranteeNoPartialA"] or not state["GuaranteeNoPartialB"] or not state["GuaranteeNoPartialMetadata"]:
3154 state["_UseSgprForGRO"] = False
3155 #reject(state, printRejectionReason, "PBC with wide load has insufficient overlap guarantees- try GRVW=1 or adding appropriate Assert*ElementMultiple")
3156
3157
3158
3159
3160 if state["EnableMatrixInstruction"]:
3161 cont1 = not state["GuaranteeNoPartialB"]
3162 cont2 = ((state["MatrixInstN"] % state["GlobalReadVectorWidthB"]) != 0)
3163 if cont1 and cont2:
3164 reject(state, printRejectionReason, "MatrixInstN %u %% GlobalReadVectorWidthB %u must be 0" % \
3165 (state["MatrixInstN"], state["GlobalReadVectorWidthB"]))
3166 else: # mac
3167 # if not bufferLoad or not state["GuaranteeNoPartialA"]:
3168 # Restrict GRVW/VW combos so shift-ptr logic will work
3169 if state["GlobalReadVectorWidthA"] > 1 \
3170 and state["GlobalReadVectorWidthA"] != state["VectorWidthA"]:
3171 reject(state, printRejectionReason, "GlobalReadVectorWidthA %u must be == VectorWidthA %u or == 1" % \
3172 (state["GlobalReadVectorWidthA"], state["VectorWidthA"]))
3173 if state["GlobalReadVectorWidthB"] > 1 \
3174 and state["GlobalReadVectorWidthB"] != state["VectorWidthB"]:
3175 reject(state, printRejectionReason, "GlobalReadVectorWidthB %u must be == VectorWidthB %u or == 1" % \
3176 (state["GlobalReadVectorWidthB"], state["VectorWidthB"]))
3177
3178 # Use SGPR to store an offset from GlobalReadOffsetA+0.
3179 # (as opposed to using dedicated VGPR for each GRO
3180 # Requires preciseBounds check since we rely on the buffer bounds check, not
3181 # individual vector registers doing bounds compares.
3182
3183 if state["_UseSgprForGRO"] == 1 and (state["ProblemType"]["SwizzleTensorA"] or state["ProblemType"]["SwizzleTensorB"]):
3184 reject(state, printRejectionReason, "UseSgprForGRO for Swizzle is not supported")
3185
3186 if state["_UseSgprForGRO"] == -1:
3187 # Don't use SGPR if it looks like we might not have enough - better to leave PBC enabled even if we have to use VGPR
3188 # 40 is based on current SGPR usage, this may need to be tuned in the future:
3189 numLoadsA = state["NumLoadsCoalescedA"]*state["NumLoadsPerpendicularA"]
3190 numLoadsB = state["NumLoadsCoalescedB"]*state["NumLoadsPerpendicularB"]
3191 numLoadsM = 0
3192 if state["ProblemType"]["Sparse"] and not state["DirectToVgprSparseMetadata"]:
3193 numLoadsM = state["NumLoadsCoalescedMetadata"]*state["NumLoadsPerpendicularMetadata"]
3194 if numLoadsA + numLoadsB + numLoadsM > 35 or state["ProblemType"]["SwizzleTensorA"] or state["ProblemType"]["SwizzleTensorB"]:
3195 #print "info: Disabling UseSgprForGRO since predicting too many SGPR will be used"
3196 state["_UseSgprForGRO"] = 0
3197 else:
3198 state["_UseSgprForGRO"] = 1
3199
3200 if packedC0 and not state["GuaranteeNoPartialA"]:
3201 reject(state, printRejectionReason, "packedC0 requires GuaranteeNoPartialA")
3202 if packedC1 and not state["GuaranteeNoPartialB"]:
3203 reject(state, printRejectionReason, "packedC1 requires GuaranteeNoPartialB")
3204
3205 if packedC0 or packedC1:
3206 state["_UseSgprForGRO"] = 0
3207
3208 if state["EdgeType"] != "ShiftPtr":
3209 reject(state, printRejectionReason, "Packed dims requires EdgeType==ShiftPtr")
3210 if state["KernelLanguage"] == "Assembly":
3211 if not bufferLoad:
3212 reject(state, printRejectionReason, "Packed dims for Assembly requires BufferLoad")
3213
3214 if packedC0: # VectorWidth must not span tensor dim
3215 if state["KernelLanguage"] == "Source":
3216 if state["AssertFree0ElementMultiple"]<state["VectorWidthA"]:
3217 reject(state, printRejectionReason, "packedC0 Source requires AF0EM>=VectorWidth (for loads and stores)")
3218 else:
3219 if state["AssertFree0ElementMultiple"]<state["VectorWidthA"]\
3220 or state["AssertFree0ElementMultiple"] == 1:
3221 if state["VectorStore"] <= 0:
3222 state["_VectorStore"] = 0
3223 else:
3224 reject(state, printRejectionReason, "packedC0 Assembly requires AF0EM>=VectorWidth or not VectorStore (for stores)")
3225
3226 state["AssignedDerivedParameters"] = True
3227
3228 # Set E
3229 if state["ProblemType"]["UseE"]:
3230 if (state["_GlobalAccumulation"] == 'SingleBuffer') and (state["GlobalSplitU"] > 1 or state["GlobalSplitU"] == -1):
3231 reject(state, printRejectionReason, "GlobalSplitU > 1 only compatible with MultipleBuffer")
3232 if len(state["PackedC1IndicesX"]) > 1:
3233 reject(state, printRejectionReason, "Use E does not support len(PackedC1IndicesX) > 1.")
3234 if not state["BufferStore"]:
3235 reject(state, printRejectionReason, "Use E only supports BufferStore due to no suppress no store.")
3236 if state["StoreRemapVectorWidth"] and (state["GlobalSplitU"] == 1 or state["GlobalSplitU"] == -1):
3237 reject(state, printRejectionReason, "Use E does not support StoreRemapVectorWidth if GSU == 1.")
3238 if state["GroupLoadStore"]:
3239 reject(state, printRejectionReason, "Use E does not support GroupLoadStore.")
3240
3241 # Activation
3242 # Function call is set to false if GSU != 1 or Activation is not fused or ActivationType is not All.
3243 if not (state["ActivationFused"] and state["ProblemType"]["ActivationType"] in ['all', 'hipblaslt_all']) \
3244 and state["ActivationFuncCall"]:
3245 state["ActivationFuncCall"] = False
3246
3247 if state["ActivationAlt"]:
3248 reject(state, printRejectionReason, "Currently does not accept ActivationAlt.")
3249
3250 # Bias reduction
3251 if state["ProblemType"]["UseBias"] and state["ProblemType"]["Gradient"]:
3252 if (state["_GlobalAccumulation"] == 'SingleBuffer') and (state["GlobalSplitU"] > 1 or state["GlobalSplitU"] == -1):
3253 reject(state, printRejectionReason, "GlobalSplitU > 1 only compatible with MultipleBuffer for bias reduction")
3254 if len(state["PackedC1IndicesX"]) > 1:
3255 reject(state, printRejectionReason, "Bias reduction does not support len(PackedC1IndicesX) > 1.")
3256 if not state["BufferStore"]:
3257 reject(state, printRejectionReason, "Bias reduction only supports BufferStore due to no suppress no store.")
3258 if state["StoreRemapVectorWidth"] and (state["GlobalSplitU"] == 1 or state["GlobalSplitU"] == -1):
3259 reject(state, printRejectionReason, "Bias reduction does not support StoreRemapVectorWidth if GSU == 1.")
3260 if state["GroupLoadStore"]:
3261 reject(state, printRejectionReason, "Bias reduction does not support GroupLoadStore.")
3262
3263 # Bias and ScaleAlphaVec
3264 if state["ProblemType"]["UseBias"] != 0 and state["ProblemType"]["UseScaleAlphaVec"] != 0 and state["ProblemType"]["UseBias"] != state["ProblemType"]["UseScaleAlphaVec"]:
3265 reject(state, printRejectionReason, "When both UseBias and UseScaleAlphaVec are enabled then UseBias and UseScaleAlphaVec must have same settings.")
3266
3267 # ScaleAB or ScaleABVec
3268 if state["ProblemType"]["DataTypeA"] != state["ProblemType"]["DataTypeB"] and \
3269 state["ProblemType"]["DataTypeA"] != state["ProblemType"]["DataType"] and \
3270 state["ProblemType"]["UseScaleAB"] == "Vector":
3271 reject(state, "Currently does not support using scaleABVec if DataTypeA != DataTypeB != DataType.")
3272
3273 if state["ProblemType"]["UseScaleAB"] and state["OptNoLoadLoop"]:
3274 # Hard to check alpha == 1.0 directly
3275 # Turn off ONLL for now
3276 # TODO: support ONLL if necessary
3277 state["OptNoLoadLoop"] = 0
3278
3279 # if state["GlobalSplitU"] > 1 or state["GlobalSplitU"] == -1:
3280 # if state["ProblemType"]["SupportUserArgs"] and state["_GlobalAccumulation"] != 'MultipleBufferSingleKernel':
3281 # reject(state, printRejectionReason, "Currently SupportUserArgs does not support GSU > 1.")
3282
3283 if state["_GlobalAccumulation"] == 'MultipleBufferSingleKernel':
3284 if state["NumElementsPerBatchStore"] == 1:
3285 reject(state, printRejectionReason, "too many store at MultipleBufferSingleKernel direct reject")
3286 if state["ProblemType"]["UseScaleCD"]:
3287 reject(state, printRejectionReason, "MultipleBufferSingleKernel not support UseScaleCD yet")
3288 if state["ProblemType"]["UseE"]:
3289 reject(state, printRejectionReason, "MultipleBufferSingleKernel not support UseE yet")
3290 if state["ProblemType"]["BiasSrc"] != "D":
3291 reject(state, printRejectionReason, "MultipleBufferSingleKernel not support BiasSrc not D yet")
3292 if state["ProblemType"]["DataType"].isDouble():
3293 reject(state, printRejectionReason, "MultipleBufferSingleKernel not support " + str(state["ProblemType"]["DataType"]) + " yet")
3294
3295 #Need to force disabling PreloadKernArgs if compiler does not support
3296 #Can not just reject the solution since the user library may find any solutions
3297 if state["PreloadKernArgs"]:
3298 if (rocmVersion.major < 6 or (rocmVersion.major == 6 and rocmVersion.patch < 32650)) or \
3299 not (isa == (9, 0, 10) or isa[:2] == (9, 4) or isa == (9, 5, 0)):
3300 #print("Force to Disable PreloadKernArgs since this hipcc version doesn't support",)
3301 state["PreloadKernArgs"] = 0
3302
3303
3304 ########################################
3305 @ staticmethod
3306 def getParametersIndented(state, indent):
3307 s = ""
3308 s += "%sProblemType: %s\n" % (indent, str(state["ProblemType"]))
3309 for key in sorted(state):
3310 s += "%s%s: %s\n" % (indent, str(key), str(state[key]))
3311 return s
3312
3313
3314 class NonprimitiveParameterValueException(Exception):
3315 pass
3316
3317
3318 ##########################
3319 # make class look like dict
3320 def keys(self):
3321 return list(self._state.keys())
3322
3323 def __len__(self):
3324 return len(self._state)
3325
3326 def __iter__(self):
3327 return iter(self._state)
3328
3329 def __getitem__(self, key):
3330 return self._state[key]
3331
3332 def __setitem__(self, key, value):
3333 self._name = None
3334 self._state[key] = value
3335
3336 def __str__(self):
3337 if self._name is None:
3338 self._name = getSolutionNameFull(self._state, self.splitGSU)
3339 return self._name
3340
3341 def __repr__(self):
3342 return self.__str__()
3343
3344 def getAttributes(self):
3345 return self._state
3346
3347 def __hash__(self):
3348 return hash(str(self) + self._state.get("codeObjectFile", ""))
3349 #return hash(self.getAttributes())
3350
3351 def __eq__(self, other):
3352 #return isinstance(other, Solution) and self.getAttributes() == other.getAttributes()
3353 return isinstance(other, Solution) and str(self) == str(other)
3354
3355 def __ne__(self, other):
3356 result = self.__eq__(other)
3357 if result is NotImplemented:
3358 return result
3359 return not result