Debian Codegraph @

tensilelite/Tensile/Contractions.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 from typing import Dict
26
27 from .Activation import ActivationType
28 from . import Hardware
29 from . import Properties
30 from Tensile.Common import state, state_key_ordering, IsaInfo
31 from Tensile.Common.Architectures import gfxToIsa
32 from Tensile.Common.DataType import DataType
33 from Tensile.Common.GlobalParameters import internalParameters
34 from Tensile.SolutionStructs import Solution as OriginalSolution
35 from Tensile.SolutionStructs.Problem import getBiasDataTypeListDefault
36 from Tensile.Toolchain.Component import Assembler
37 from math import ceil
38
39 MIN_K_FOR_GSU = 32
40 @state_key_ordering
41 class FreeIndex:
42 StateKeys = ['isA', 'i', 'c', 'd']
43
44 def __init__(self, isA, i=None, c=None, d=None):
45 self.isA = isA
46 self.i = i # index into A or B (depending on isA)
47 self.c = c
48 self.d = d
49
50 @state_key_ordering
51 class BatchIndex:
52 StateKeys = ['a', 'b', 'c', 'd']
53 def __init__(self, a=None, b=None, c=None, d=None):
54 self.a = a
55 self.b = b
56 self.c = c
57 self.d = d
58
59 @state_key_ordering
60 class BoundIndex:
61 StateKeys = ['a', 'b', 'aMirror', 'bMirror']
62 def __init__(self, a=None, b=None, aMirror=False, bMirror=False):
63 self.a = a
64 self.b = b
65 self.aMirror = aMirror
66 self.bMirror = bMirror
67
68
69 class ProblemType:
70 StateKeys = ['operationIdentifier', 'transA', 'transB', 'computeInputType', 'aType', 'bType', 'cType', 'dType', 'eType', 'computeType',
71 'useBeta', 'useBias', 'biasSrcWhiteList', 'useE', 'useScaleAB', 'useScaleCD', 'useScaleAlphaVec', 'biasDataTypeWhiteList',
72 'highPrecisionAccumulate', 'useInitialStridesAB', 'useInitialStridesCD', 'stridedBatched', 'groupedGemm',
73 'useGradient', 'activationType', 'activationArgLength', 'activationComputeDataType', 'activationNoGuard',
74 'sparse', 'f32XdlMathOp', 'supportDeviceUserArguments', 'outputAmaxD', 'swizzleTensorA', 'swizzleTensorB']
75 @classmethod
76 def FromOriginalState(cls, d):
77 indices = [None]*d['TotalIndices']
78 freeIndices = []
79 batchIndices = []
80 boundIndices = []
81
82 for i in d['IndicesSummation']:
83 bi = BoundIndex(aMirror=('MirrorDimsA' in d and i in d['MirrorDimsA']),
84 bMirror=('MirrorDimsB' in d and i in d['MirrorDimsB']))
85 indices[i] = bi
86 boundIndices.append(bi)
87
88 for i in range(0,d["NumIndicesC"]):
89 if i in d['IndicesBatch']:
90 bi = BatchIndex(c=i, d=i)
91 indices[i] = bi
92 batchIndices.append(bi)
93 else:
94 assert i in d['IndicesFree']
95 if i in d['IndexAssignmentsA']:
96 fi = FreeIndex(isA=True, i=d["IndexAssignmentsA"].index(i), c=i, d=i)
97 elif i in d['IndexAssignmentsB']:
98 fi = FreeIndex(isA=False, i=d["IndexAssignmentsB"].index(i), c=i, d=i)
99 else:
100 raise RuntimeError("free index %u not in ia or ib"%i)
101 indices[i] = fi
102 freeIndices.append(fi)
103
104 for ia, ic in enumerate(d['IndexAssignmentsA']):
105 indices[ic].a = ia
106
107 for ib, ic in enumerate(d['IndexAssignmentsB']):
108 indices[ic].b = ib
109
110 for idx in indices:
111 assert idx is not None
112 idxState = state(idx)
113 for (key, value) in list(idxState.items()):
114 assert value is not None
115
116 rv = cls()
117 rv.indices = indices
118 rv.freeIndices = freeIndices
119 rv.batchIndices = batchIndices
120 rv.boundIndices = boundIndices
121 rv.aDims = len(d['IndexAssignmentsA'])
122 rv.bDims = len(d['IndexAssignmentsB'])
123 rv.cDims = d['NumIndicesC']
124 rv.dDims = rv.cDims
125
126 rv.aConjugate = d['ComplexConjugateA']
127 rv.bConjugate = d['ComplexConjugateB']
128
129 srcType = DataType(d['DataType'])
130 dstType = DataType(d['DestDataType']) if 'DestDataType' in d else srcType
131 computeType = DataType(d['ComputeDataType']) if 'ComputeDataType' in d else dstType
132
133 rv.transA = bool(d['TransposeA'])
134 rv.transB = bool(d['TransposeB'])
135 if 'DataTypeA' in d: #it will either be set as d['DataType'] or a specified input
136 rv.aType = DataType(d['DataTypeA'])
137 else:
138 rv.aType = srcType
139 if 'DataTypeB' in d:
140 rv.bType = DataType(d['DataTypeB'])
141 else:
142 rv.bType = srcType
143
144 if rv.aType.isFloat8BFloat8() or rv.bType.isFloat8BFloat8():
145 rv.aType = DataType("F8")
146 rv.bType = DataType("B8")
147 elif rv.aType.isFloat8BFloat8_fnuz() or rv.bType.isFloat8BFloat8_fnuz():
148 rv.aType = DataType("F8N")
149 rv.bType = DataType("B8N")
150 elif rv.aType.isBFloat8Float8() or rv.bType.isBFloat8Float8():
151 rv.aType = DataType("B8")
152 rv.bType = DataType("F8")
153 elif rv.aType.isBFloat8Float8_fnuz() or rv.bType.isBFloat8Float8_fnuz():
154 rv.aType = DataType("B8N")
155 rv.bType = DataType("F8N")
156
157 if 'DataTypeE' in d:
158 rv.eType = DataType(d['DataTypeE'])
159 else:
160 rv.eType = dstType
161
162 if 'DataTypeAmaxD' in d:
163 rv.amaxDType = DataType(d['DataTypeAmaxD'])
164 else:
165 rv.amaxDType = computeType
166
167 rv.computeInputType = srcType
168 rv.cType = dstType
169 rv.dType = dstType
170 # we already checked the src/dst/compute types are supported and well-assigned in SolutionStruct
171 rv.alphaType = computeType
172 rv.betaType = computeType
173 rv.computeType = computeType
174
175 rv.highPrecisionAccumulate = False
176 if 'HighPrecisionAccumulate' in d:
177 rv.highPrecisionAccumulate = d['HighPrecisionAccumulate']
178
179 rv.useInitialStridesAB = False
180 if 'UseInitialStridesAB' in d:
181 rv.useInitialStridesAB = d['UseInitialStridesAB']
182 rv.useInitialStridesCD = False
183 if 'UseInitialStridesCD' in d:
184 rv.useInitialStridesCD = d['UseInitialStridesCD']
185
186 rv.stridedBatched = True
187 if 'StridedBatched' in d:
188 rv.stridedBatched = d['StridedBatched']
189
190 rv.groupedGemm = False
191 if 'GroupedGemm' in d:
192 rv.groupedGemm = d['GroupedGemm']
193
194 rv.setConstStrideA = []
195 if 'SetConstStrideA' in d:
196 rv.setConstStrideA = d['SetConstStrideA']
197 rv.setConstStrideB = []
198 if 'SetConstStrideB' in d:
199 rv.setConstStrideB = d['SetConstStrideB']
200
201 rv.mirrorDimsA = d['MirrorDimsA'] if 'MirrorDimsA' in d else []
202 rv.mirrorDimsB = d['MirrorDimsB'] if 'MirrorDimsB' in d else []
203
204 rv.useBeta = True
205 if 'UseBeta' in d:
206 rv.useBeta = d['UseBeta']
207
208 rv.useBias = 0
209 rv.biasDataTypeWhiteList = []
210 rv.biasSrcWhiteList = []
211 rv.setConstStrideBias = []
212
213 if 'UseBias' in d:
214 rv.useBias = d['UseBias']
215 if 'BiasDataTypeList' in d:
216 d["BiasDataTypeList"].sort() # Sort to make sure names are unique
217 rv.biasDataTypeWhiteList = d['BiasDataTypeList']
218 else:
219 rv.biasDataTypeWhiteList = getBiasDataTypeListDefault(d)
220 if 'BiasSrc' in d:
221 m = ["A", "B", "C", "D"]
222 rv.biasSrcWhiteList = [m.index(d['BiasSrc'])]
223 if 'SetConstStrideBias' in d:
224 rv.setConstStrideBias = d['SetConstStrideBias']
225
226 rv.useE = False
227 if 'UseE' in d:
228 rv.useE = d['UseE']
229
230 rv.useGradient = False
231 if 'Gradient' in d:
232 rv.useGradient = d["Gradient"]
233
234 rv.outputAmaxD = False
235 if 'OutputAmaxD' in d:
236 rv.outputAmaxD = d['OutputAmaxD']
237
238 rv.useScaleAB = ""
239 if 'UseScaleAB' in d:
240 rv.useScaleAB = d['UseScaleAB']
241 rv.useScaleCD = False
242 if 'UseScaleCD' in d:
243 rv.useScaleCD = d['UseScaleCD']
244
245 rv.useScaleAlphaVec = 0
246 if 'UseScaleAlphaVec' in d:
247 rv.useScaleAlphaVec = d['UseScaleAlphaVec']
248
249 rv.batched = d['Batched']
250
251 rv.activationType = ActivationType('none')
252 rv.activationArgLength = 0
253 if 'ActivationType' in d:
254 rv.activationType = ActivationType(d['ActivationType'])
255 rv.activationArgLength = len(rv.activationType.getAdditionalArgStringList())
256 rv.activationComputeDataType = DataType(d['ActivationComputeDataType'])
257 rv.activationNoGuard = False
258 if 'ActivationNoGuard' in d:
259 rv.activationNoGuard = d["ActivationNoGuard"]
260 rv.sparse = 0
261 if 'Sparse' in d:
262 rv.sparse = int(d['Sparse'])
263
264 rv.f32XdlMathOp = DataType(d['F32XdlMathOp']) if 'F32XdlMathOp' in d else DataType(0)
265
266 rv.supportDeviceUserArguments = False
267 if 'SupportUserArgs' in d:
268 rv.supportDeviceUserArguments = d['SupportUserArgs']
269
270 rv.swizzleTensorA = d.get('SwizzleTensorA', False)
271 rv.swizzleTensorB = d.get('SwizzleTensorB', False)
272 return rv
273
274 def __init__(self, freeIndices=None, batchIndices=None, boundIndices=None, aDims=None, bDims=None, cDims=None, dDims=None):
275 self.freeIndices = freeIndices
276 self.batchIndices = batchIndices
277 self.boundIndices = boundIndices
278 self.aDims = aDims
279 self.bDims = bDims
280 self.cDims = cDims
281 self.dDims = dDims
282
283 @property
284 def indexNames(self):
285 aNames = ['_'] * self.aDims
286 bNames = ['_'] * self.bDims
287 cNames = ['_'] * self.cDims
288
289 allIndexNames = 'ijklmnopqrstuvwxyz'
290 index = 0
291
292 dNames = list([allIndexNames[index+i] for i in range(self.cDims)])
293 index += len(dNames)
294
295 sumNames = list([allIndexNames[index+i] for i in range(len(self.boundIndices))])
296 index += len(sumNames)
297
298 for free in self.freeIndices:
299 if free.isA:
300 aNames[free.i ] = dNames[free.d]
301 else:
302 bNames[free.i ] = dNames[free.d]
303 cNames[free.c] = dNames[free.d]
304
305 for batch in self.batchIndices:
306 name = dNames[batch.d]
307 aNames[batch.a] = name
308 bNames[batch.b] = name
309 cNames[batch.c] = name
310
311 for i, bound in enumerate(self.boundIndices):
312 name = sumNames[i]
313 aNames[bound.a] = name.upper() if bound.aMirror else name
314 bNames[bound.b] = name.upper() if bound.bMirror else name
315
316 aNames = ''.join(aNames)
317 bNames = ''.join(bNames)
318 cNames = ''.join(cNames)
319 dNames = ''.join(dNames)
320 sumNames = ''.join(sumNames)
321
322 return (aNames, bNames, cNames, dNames, sumNames)
323
324 @property
325 def operationIdentifier(self):
326 (aNames, bNames, cNames, dNames, sumNames) = self.indexNames
327
328 aOp = 'C' if self.aConjugate else ''
329 bOp = 'C' if self.bConjugate else ''
330
331 return '_'.join(['Contraction', sumNames,
332 'A' + aNames + aOp,
333 'B' + bNames + bOp,
334 'C' + cNames,
335 'D' + dNames])
336
337 def placeholderStr(self, includeBatch=False, includeOperation=False, includeType=False):
338 ret = ""
339 if includeOperation:
340 ret = self.operationIdentifier
341 if not self.useBeta:
342 ret += "_Beta0"
343 ret += "_StridedBatched{}".format(int(self.stridedBatched))
344 if includeType:
345 ret += "_Type_{}{}".format(DataType(self.aType).toChar(), DataType(self.cType).toChar())
346 if self.highPrecisionAccumulate:
347 ret += "_HPA"
348
349 return ret
350
351 def predicates(self, includeBatch=False, includeOperation=False, includeType=False):
352 predicates = []
353
354 #if includeBatch and not self.batched:
355 # predicates.append(ProblemPredicate("BatchSizeEqual", index=0, value=1))
356
357 if includeOperation:
358 predicates.append(ProblemPredicate("OperationIdentifierEqual", value=self.operationIdentifier))
359 if not self.useBeta:
360 predicates.append(ProblemPredicate("BetaZero"))
361 predicates.append(ProblemPredicate("BiasDataTypeWhiteList", value=self.biasDataTypeWhiteList))
362 predicates.append(ProblemPredicate("BiasSrcWhiteList", value=self.biasSrcWhiteList))
363 predicates.append(ProblemPredicate("AmaxDCheck", value=self.outputAmaxD))
364 if self.activationType in ['all', 'hipblaslt_all']:
365 exportType = ActivationType.Export.GRADONLY if self.useGradient else ActivationType.Export.NORMAL
366 supportedBy = ActivationType.SupportedBy.ALL if self.activationType == 'all' else ActivationType.SupportedBy.HIPBLASLT
367 enumList = [actEnum.capitalize() for actEnum in ActivationType.getEnumStrList(self.activationComputeDataType, supportedBy, exportType=exportType)]
368 predicates.append(ProblemPredicate("ActivationEnumWhiteList", value=enumList))
369 # predicates.append(ProblemPredicate("UseScaleAlphaVec", value=self.useScaleAlphaVec))
370 # predicates.append(ProblemPredicate("GroupedGemm", value=self.groupedGemm))
371
372 if includeType:
373 predicates.append(ProblemPredicate("TypesEqual", value=(self.aType, self.bType, self.cType, self.dType, self.computeInputType)))
374 predicates.append(ProblemPredicate("HighPrecisionAccumulate", value=self.highPrecisionAccumulate))
375 predicates.append(ProblemPredicate("Activation", value=self.activationType))
376 predicates.append(ProblemPredicate("ActivationComputeType", value=self.activationComputeDataType))
377 predicates.append(ProblemPredicate("ActivationNoGuard", value=self.activationNoGuard))
378 predicates.append(ProblemPredicate("UseGradient", value=self.useGradient))
379 predicates.append(ProblemPredicate("UseBias", value=self.useBias))
380 predicates.append(ProblemPredicate("UseE", value=self.useE))
381 predicates.append(ProblemPredicate("DataTypeE", value=self.eType))
382 predicates.append(ProblemPredicate("StridedBatched", value=self.stridedBatched))
383 predicates.append(ProblemPredicate("GroupedGemm", value=self.groupedGemm))
384 predicates.append(ProblemPredicate("UseScaleAB", value=self.useScaleAB))
385 predicates.append(ProblemPredicate("UseScaleCD", value=self.useScaleCD))
386 predicates.append(ProblemPredicate("UseScaleAlphaVec", value=self.useScaleAlphaVec))
387 predicates.append(ProblemPredicate("Sparse", value=self.sparse))
388 predicates.append(ProblemPredicate("F32XdlMathOp", value=self.f32XdlMathOp))
389 predicates.append(ProblemPredicate("SupportDeviceUserArguments", value=self.supportDeviceUserArguments))
390 predicates.append(ProblemPredicate("SwizzleTensorA", value=self.swizzleTensorA))
391 predicates.append(ProblemPredicate("SwizzleTensorB", value=self.swizzleTensorB))
392
393 return predicates
394
395 def extractDimPredicate(cls, key, value, predicateName):
396 """
397 Extract the predicate for AssertStrideEqual*
398 Value is a dictionary
399 """
400 predicates = []
401 for pos,val in value.items():
402 if val != -1:
403 predicates.append(cls(predicateName, index=pos, value=val))
404 if len(predicates) == 1:
405 return predicates[0]
406 elif len(predicates) > 1:
407 return cls.And(predicates)
408
409 class TaskPredicate(Properties.Predicate):
410 @classmethod
411 def FromOriginalKeyPair(cls, pair):
412 (key, value) = pair
413 if key == "_WorkspaceSizePerElemC" and value > 0:
414 return cls("WorkspaceCheck")
415 return None
416
417 @classmethod
418 def FromOriginalState(cls, d, problemType, morePreds=[]):
419 predicates = [p for p in map(cls.FromOriginalKeyPair, d.items()) if p is not None]
420 return cls.And(predicates)
421
422 class ProblemPredicate(Properties.Predicate):
423 @classmethod
424 def FromOriginalKeyPair(cls, pair):
425 (key, value) = pair
426 # Arithmetic intensity assertions
427 if key == "AssertAIGreaterThanEqual":
428 return cls("AIGreaterThanEqual", value=value) if value > 0 else None
429 if key == "AssertAILessThanEqual":
430 return cls("AILessThanEqual", value=value) if value > 0 else None
431
432 if key.endswith('Multiple'):
433 if value == 1:
434 return None
435
436 if key == "AssertFree0ElementMultiple":
437 tag = "Free0SizeMultiple"
438 index = 0
439 elif key == "AssertFree1ElementMultiple":
440 tag = "Free1SizeMultiple"
441 index = 0
442 elif key == "AssertSummationElementMultiple":
443 tag = "BoundSizeMultiple"
444 index = -1
445 else:
446 raise RuntimeError("Unknown Multiple Value: {}".format(key))
447
448 return cls(tag, index=index, value=value)
449
450 if key.startswith('Assert'):
451 raise RuntimeError("Unknown assertion key: {}".format(key))
452
453 @classmethod
454 def CompoundPredicates(cls, state, problemType):
455 rv = []
456
457 if "BatchSizeEqual" in state:
458 rv += [cls('BatchSizeEqual', index=0, value=state["BatchSizeEqual"])]
459
460 if "SynchronizerSizeCheck" in state:
461 if state["SynchronizerSizeCheck"]:
462 valuepredicates = []
463 valuepredicates.append(state["MacroTile0"])
464 valuepredicates.append(state["MacroTile1"])
465 if state["EnableMatrixInstruction"]:
466 valuepredicates.append(state["MIWaveTile"][0]*state["MIWaveTile"][1])
467 else:
468 valuepredicates.append(state["ThreadTile0"]*state["ThreadTile1"])
469 if state["NumElementsPerBatchStore"] != 0:
470 valuepredicates.append(int((state["NumElementsPerThread"])/state["NumElementsPerBatchStore"]))
471 else:
472 valuepredicates.append(1)
473 valuepredicates.append(ceil(state["NumThreads"] / state["WavefrontSize"]))
474 valuepredicates.append(state["GlobalSplitU"])
475
476 rv += [cls('SynchronizerSizeCheck', index=0, value=valuepredicates)]
477
478 if state["InternalSupportParams"]["KernArgsVersion"] >= 1 and \
479 not (('StreamK' in state) and (state['StreamK'] > 0)):
480 valuepredicates = []
481 valuepredicates.append(state["MacroTile0"])
482 valuepredicates.append(state["MacroTile1"])
483 valuepredicates.append(state["GlobalSplitU"])
484 rv += [cls('WorkgroupNumberCheck', index=0, value=valuepredicates)]
485
486 if not problemType.aType.isInt8x4():
487 # calculate the minimum supported free dimension size
488 TLUA = state['ProblemType']['TLUA']
489 TLUB = state['ProblemType']['TLUB']
490 minFree0 = state['GlobalReadVectorWidthA'] if TLUA else 1
491 minFree1 = state['GlobalReadVectorWidthB'] if TLUB else 1
492 rv += [cls('LeadingFree0SizesGreaterOrEqual', value=minFree0)]
493 rv += [cls('LeadingFree1SizesGreaterOrEqual', value=minFree1)]
494
495 if len(state["PackedC0IndicesX"]) > 1:
496 rv += [cls("CDStridesEqual")]
497
498 if "KernelLanguage" in state:
499 rv += [cls("KernelLanguageCompatible", value=state["KernelLanguage"])]
500
501 if ('GlobalSplitU' in state) and (state['GlobalSplitU'] > 1 or state['GlobalSplitU'] == -1):
502 if ('_GlobalAccumulation' not in state) or (state['_GlobalAccumulation'] != 'MultipleBuffer'):
503 rv += [cls("DeterministicMode", value = False)]
504
505 if ('StreamK' in state) and (state['StreamK'] > 0) and ('StreamKAtomic' in state) and (state['StreamKAtomic'] == 1):
506 # StreamKAtomic = 1 uses atomic for partial tiles
507 rv += [cls("DeterministicMode", value = False)]
508
509 # if bufferload is performed, we output some predication info for host side,
510 # to prevent from some extremely large problems from launching and causing bufferload offset limit < 2^32
511 # thoses cases will not satisfy the assertion thus won't use the kernel.
512 # See Common.py for more details, we will need four values:
513 # TODO - haven't been fully tested for FP16 and BF, need to verify the false-positive
514 if 'BufferLoad' in state and state['BufferLoad'] == True:
515 TLUA = state['ProblemType']['TLUA']
516 TLUB = state['ProblemType']['TLUB']
517 MayShiftA = TLUA and state['AssertFree0ElementMultiple'] < state['GlobalReadVectorWidthA']
518 MayShiftB = TLUB and state['AssertFree1ElementMultiple'] < state['GlobalReadVectorWidthB']
519 subrv={}
520 subrv['ShiftPtrElemB'] = state['GlobalReadVectorWidthB'] if MayShiftB else 0
521 subrv['ShiftPtrElemA'] = state['GlobalReadVectorWidthA'] if MayShiftA else 0
522 subrv['DUorMT1'] = state['DepthU'] if TLUB else state['MacroTile1']
523 subrv['DUorMT0'] = state['DepthU'] if TLUA else state['MacroTile0']
524 # value is also a dict for better readibility, client side need to handel the serialization
525 rv += [cls('BufferLoadOffsetLimitCheck', value=subrv)]
526
527 # When doing globol write, may need to load matrix C if beta !=0
528 if 'BufferLoad' in state and state['BufferLoad'] == True:
529 rv += [cls('BufferLoadOffsetLimitCheck_Beta', value=state['MacroTile1'])]
530
531 # similiar check is applied for bufferstore,
532 # for bufferstore offset, test if the bot-right offset < 2^32,
533 # it should be StrideA*MT1, so we need to output MT1 and use the StrideA of problem in host-side for predication
534 if 'BufferStore' in state and state['BufferStore'] == True:
535 rv += [cls('BufferStoreOffsetLimitCheck', value=state['MacroTile1'])]
536
537 if '_GlobalAccumulation' in state and state['_GlobalAccumulation'] != None and not state["StreamK"]:
538 value = MIN_K_FOR_GSU
539 rv += [cls('GlobalSplitUCheckMinK', value=[value, state["GlobalSplitU"]])]
540
541 if ('WorkGroupMappingXCC' in state) and ('WorkGroupMappingXCCGroup' in state):
542 rv += [cls("WorkgroupMappingXCCCheck", value=[state['WorkGroupMappingXCC'], state['WorkGroupMappingXCCGroup']])]
543
544 if state['ProblemType']['SwizzleTensorA']:
545 rv += [cls('SwizzleTensorA', value=state['ProblemType']['SwizzleTensorA'])]
546
547 if state['ProblemType']['SwizzleTensorB']:
548 rv += [cls('SwizzleTensorB', value=state['ProblemType']['SwizzleTensorB'])]
549
550 return rv
551
552 @classmethod
553 def FromOriginalState(cls, d, problemType, morePreds=[]):
554 problemTypePreds = problemType.predicates(True, True, True)
555 compoundPreds = cls.CompoundPredicates(d, problemType)
556 extraPreds = problemTypePreds + compoundPreds + morePreds
557
558 predicates = [p for p in map(cls.FromOriginalKeyPair, d.items()) if p is not None] + extraPreds
559 return cls.And(predicates)
560
561 class SizeMapping:
562 StateKeys = ['waveNum',
563 'workGroup',
564 'macroTile',
565 'threadTile',
566 'matrixInstruction',
567 'grvwA',
568 'grvwB',
569 'gwvwC',
570 'gwvwD',
571 'depthU',
572 'staggerU',
573 'staggerUMapping',
574 'globalSplitUPGR',
575 'globalSplitU',
576 'staggerStrideShift',
577 'workGroupMapping',
578 'packBatchDims',
579 'magicDivAlg',
580 'streamK',
581 'streamKAtomic',
582 'sourceKernel',
583 'globalAccumulation',
584 'workspaceSizePerElemC',
585 'workspaceSizePerElemBias',
586 'activationFused',
587 'CustomKernelName',
588 'workGroupMappingXCC',
589 'workGroupMappingXCCGroup',
590 'globalSplitUCoalesced',
591 'globalSplitUWorkGroupMappingRoundRobin',
592 'CUOccupancy',
593 'PrefetchGlobalRead',
594 'MathClocksUnrolledLoop',
595 'synchronizerSizePerWG',
596 'nonTemporalA',
597 'nonTemporalB',
598 ]
599
600 @classmethod
601 def FromOriginalState(cls, d):
602 globalAccum = 0
603 if d['GlobalSplitUAlgorithm'] == 'SingleBuffer':
604 globalAccum = 1
605 if d['GlobalSplitUAlgorithm'] == 'MultipleBuffer':
606 globalAccum = 2
607 if d['_GlobalAccumulation'] == 'MultipleBufferSingleKernel':
608 globalAccum = 3
609 if d['_GlobalAccumulation'] == 'PartialsBuffer':
610 globalAccum = 4
611 pgr = int(d['PrefetchGlobalRead'])
612 synchronizerSizePerWG = ceil((d['MIWaveTile'][0]*d['MIWaveTile'][1] if d['EnableMatrixInstruction'] else d['ThreadTile0']*d['ThreadTile1'] \
613 * ceil((d['NumElementsPerThread'])/d['NumElementsPerBatchStore']) if d['NumElementsPerBatchStore'] != 0 else 1 \
614 * ceil(d["NumThreads"] / d["WavefrontSize"])))
615
616 return cls(waveNum = d['NumThreads'] // d['WavefrontSize'],
617 workGroup = d['WorkGroup'],
618 macroTile = cls.ReadOriginalMacroTile(d),
619 threadTile = d['ThreadTile'],
620 matrixInstruction = d['MatrixInstruction'],
621 grvwA = d['GlobalReadVectorWidthA'],
622 grvwB = d['GlobalReadVectorWidthB'],
623 gwvwC = d['StoreVectorWidth'],
624 gwvwD = d['StoreVectorWidth'],
625 workGroupMapping = d['WorkGroupMapping'],
626 staggerU = d['StaggerU'] if 'StaggerU' in d else 0,
627 staggerUMapping = d['StaggerUMapping'] if 'StaggerUMapping' in d else 0,
628 depthU = d['DepthU'],
629 globalSplitUPGR = internalParameters["GlobalSplitUPGR"],
630 globalSplitU = d['GlobalSplitU'],
631 staggerStrideShift = d['_staggerStrideShift'] if '_staggerStrideShift' in d else 0,
632 packBatchDims = 0,
633 streamK = d['StreamK'] if 'StreamK' in d else 0,
634 streamKAtomic = d['StreamKAtomic'] if 'StreamKAtomic' in d else 0,
635 magicDivAlg = d.get('MagicDivAlg', 1),
636 sourceKernel = d['KernelLanguage'] == 'Source',
637 globalAccumulation = globalAccum,
638 workspaceSizePerElemC = d['_WorkspaceSizePerElemC'],
639 workspaceSizePerElemBias = d['_WorkspaceSizePerElemBias'],
640 activationFused = d['ActivationFused'],
641 CustomKernelName = d['CustomKernelName'],
642 workGroupMappingXCC = d['WorkGroupMappingXCC'],
643 workGroupMappingXCCGroup = d['WorkGroupMappingXCCGroup'],
644 globalSplitUCoalesced = d['GlobalSplitUCoalesced'],
645 globalSplitUWorkGroupMappingRoundRobin = d['GlobalSplitUWorkGroupMappingRoundRobin'],
646 CUOccupancy = d['CUOccupancy'],
647 PrefetchGlobalRead = pgr,
648 MathClocksUnrolledLoop = d['MathClocksUnrolledLoop'],
649 synchronizerSizePerWG = synchronizerSizePerWG,
650 nonTemporalA = d['NonTemporalA'],
651 nonTemporalB = d['NonTemporalB'],
652 )
653 @classmethod
654 def ReadOriginalMacroTile(cls, d):
655 rv = [1,1,1]
656 rv[0] = d['MacroTile0']
657 rv[1] = d['MacroTile1']
658 return rv
659
660 def __init__(self, **kwargs):
661 for (key, value) in list(kwargs.items()):
662 setattr(self, key, value)
663
664 class InternalArgsSupport:
665 StateKeys = ['version',
666 'gsu',
667 'wgm',
668 'staggerU',
669 'useUniversalArgs']
670
671 @classmethod
672 def FromOriginalState(cls, d):
673 return cls(version = d['InternalSupportParams']['KernArgsVersion'],
674 gsu = d['InternalSupportParams']['SupportUserGSU'],
675 wgm = d['InternalSupportParams']['SupportCustomWGM'],
676 staggerU = d['InternalSupportParams']['SupportCustomStaggerU'],
677 useUniversalArgs = d['InternalSupportParams']['UseUniversalArgs'])
678
679 def __init__(self, **kwargs):
680 for (key, value) in list(kwargs.items()):
681 setattr(self, key, value)
682
683 class Solution:
684 StateKeys = ['name',
685 'kernelName',
686 'problemType',
687 'hardwarePredicate',
688 'problemPredicate',
689 'taskPredicate',
690 'sizeMapping',
691 'internalArgsSupport',
692 'debugKernel',
693 'libraryLogicIndex',
694 'index',
695 'ideals',
696 'linearModel']
697 HiddenKeys = ['originalSolution']
698
699 @classmethod
700 def FromSolutionStruct(
701 cls,
702 solution,
703 splitGSU: bool,
704 printSolutionRejectionReason: bool,
705 printIndexAssignmentInfo: bool,
706 assembler: Assembler,
707 isaInfoMap: Dict[str, IsaInfo]
708 ):
709 return cls.FromOriginalState(
710 solution._state,
711 splitGSU,
712 printSolutionRejectionReason,
713 printIndexAssignmentInfo,
714 assembler,
715 isaInfoMap,
716 solution.srcName
717 )
718
719 @classmethod
720 def FromOriginalState(
721 cls,
722 d,
723 splitGSU: bool,
724 printSolutionRejectionReason: bool,
725 printIndexAssignmentInfo: bool,
726 #mink
727 assembler,
728 isaInfoMap,
729 srcName = "",
730 deviceInfo=None
731 ):
732 rv = cls()
733
734 if 'SolutionNameMin' in d:
735 rv.name = d['SolutionNameMin']
736
737 if 'KernelNameMin' in d:
738 rv.kernelName = d['KernelNameMin']
739
740 rv.problemType = ProblemType.FromOriginalState(d['ProblemType'])
741
742 rv.problemPredicate = ProblemPredicate.FromOriginalState(d, rv.problemType)
743 rv.taskPredicate = TaskPredicate.FromOriginalState(d, rv.problemType)
744
745 if 'DebugKernel' in d:
746 rv.debugKernel = d['DebugKernel']
747
748 if 'SolutionIndex' in d:
749 rv.index = d['SolutionIndex']
750
751 info = cls.ReadOriginalInfo(d)
752 rv.libraryLogicIndex = int(info.get("SolutionIndex", -1))
753
754 rv.sizeMapping = SizeMapping.FromOriginalState(d)
755
756 rv.internalArgsSupport = InternalArgsSupport.FromOriginalState(d)
757
758 if 'Ideals' in d:
759 rv.ideals = d['Ideals']
760 else:
761 rv.ideals = {}
762
763 if 'LinearModel' in d:
764 rv.linearModel = d['LinearModel']
765 else:
766 rv.linearModel = {}
767
768 if 'ISA' not in d:
769 if d['KernelLanguage'] == 'Assembly':
770 d['ISA'] = gfxToIsa(deviceInfo[1])
771
772 if 'CUCount' not in d:
773 d['CUCount'] = None
774
775 rv.hardwarePredicate = Hardware.HardwarePredicate.FromHardware(d['ISA'], d['CUCount'])
776 rv.originalSolution = OriginalSolution(
777 d,
778 splitGSU,
779 printSolutionRejectionReason,
780 printIndexAssignmentInfo,
781 assembler,
782 isaInfoMap,
783 srcName
784 )
785 rv.srcName = srcName
786
787 return rv
788
789 @classmethod
790 def ReadOriginalInfo(cls, d):
791 return dict([(key, str(value)) for (key, value) in list(d.items()) if key != 'ProblemType'])
792
793 def __init__(self, **kwargs):
794 self.name = None
795 self.problemType = None
796 self.hardwarePredicate = Hardware.HardwarePredicate('TruePred')
797 self.problemPredicate = ProblemPredicate('TruePred')
798 self.taskPredicate = TaskPredicate('TruePred')
799 self.sizeMapping = None
800 self.debugKernel = False
801 self.libraryLogicIndex = {}
802 self.index = None
803 self.ideals = {}
804 self.srcName = ""
805
806 for key, value in kwargs:
807 if key not in Solution.StateKeys and key not in Solution.HiddenKeys:
808 raise KeyError("{0} is not a property of Solution.".format(key))
809
810 setattr(self, key, value)
811
812 def getSolutionKeys(self):
813 return self.originalSolution.keys()