Debian Codegraph @

tensilelite/Tensile/SolutionStructs/Problem.py

raw symbols SCIP
1 ################################################################################
2 #
3 # Copyright (C) 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 rocisa.enum import DataTypeEnum
26 from collections import OrderedDict
27 from collections.abc import Mapping
28
29 from typing import List
30
31 from Tensile.Activation import ActivationType
32 from Tensile.Common import fastdeepcopy as deepcopy
33 from Tensile.Common.Constants import INDEX_CHARS
34 from Tensile.Common.DataType import DataType
35 from Tensile.Common.Utilities import assignParameterWithDefault, printWarning, print2, printExit
36
37
38
39
40 class ProblemSizeRange:
41
42 def __init__(self, problemType, config):
43 self.totalIndices = 1+max(problemType["IndexAssignmentsA"]) + problemType["NumIndicesLD"]
44 if len(config) < self.totalIndices:
45 for i in range(len(config), self.totalIndices):
46 if i < self.totalIndices - problemType["NumIndicesLD"]:
47 config.append(0)
48 else:
49 config.append([0])
50
51 self.indexMax = []
52 self.indexIsSized = []
53 self.indicesSized = []
54 self.indicesMapped = []
55 for i in range(0, self.totalIndices):
56 dim = deepcopy(config[i])
57 if isinstance(dim, list):
58 if len(dim) == 1:
59 self.indicesSized.append([dim[0], 1, 0, dim[0]])
60 elif len(dim) == 2:
61 self.indicesSized.append([dim[0], dim[0], 0, dim[1]])
62 elif len(dim) == 3:
63 self.indicesSized.append([dim[0], dim[1], 0, dim[2]])
64 elif len(dim) == 4:
65 self.indicesSized.append([dim[0], dim[1], dim[2], dim[3]])
66 else:
67 printExit("dimension[%u] config (%s) has %u descriptors rather than 1-4."
68 % ( i, dim, len(dim) ))
69 self.indexIsSized.append(True)
70 self.indexMax.append(self.indicesSized[len(self.indicesSized)-1][3])
71
72 elif isinstance(dim, int):
73 self.indicesMapped.append(dim)
74 self.indexIsSized.append(False)
75 self.indexMax.append(self.indicesSized[self.indicesMapped[ \
76 len(self.indicesMapped)-1]][3])
77
78 # max num elements in each tensor
79 self.maxNumElements = [ 1, 1, 1 ]
80 for i in range(0, problemType["NumIndicesC"]):
81 self.maxNumElements[0] *= self.indexMax[i]
82 for i in problemType["IndexAssignmentsA"]:
83 self.maxNumElements[1] *= self.indexMax[i]
84 for i in problemType["IndexAssignmentsB"]:
85 self.maxNumElements[2] *= self.indexMax[i]
86
87 self.totalProblemSizes = 1
88 self.numProblemSizes = [] # per index
89 self.problemSizeToIndex = []
90 self.problemIndexToSize = []
91 sizedIdx = 0
92 for i in range(0, len(self.indexIsSized)):
93 self.problemSizeToIndex.append({})
94 self.problemIndexToSize.append({})
95 if self.indexIsSized[i]:
96 self.numProblemSizes.append(0)
97 index = self.indicesSized[sizedIdx]
98 sizedIdx += 1
99 currentSize = index[0]
100 currentIncrement = index[1]
101 while currentSize <= index[3]:
102 currentSize += currentIncrement
103 currentIncrement += index[2]
104 self.numProblemSizes[i] += 1
105 else:
106 self.numProblemSizes.append(1)
107 self.totalProblemSizes *= self.numProblemSizes[i]
108
109 ########################################
110 # enumerate problem sizes
111 currentSizedIndexSizes = []
112 currentSizedIndexIncrements = []
113 for i in range(0, len(self.indicesSized)):
114 currentSizedIndexSizes.append(self.indicesSized[i][0])
115 currentSizedIndexIncrements.append(self.indicesSized[i][1])
116
117 # iterate over all problem sizes
118 self.problemSizes = []
119 moreProblemSizes = True
120 problemIdx = 0
121 problemSize = [0]*self.totalIndices
122 while moreProblemSizes:
123 #/ convert current sized and mapped indices to full sizes
124 currentSizedIdx = 0
125 currentMappedIdx = 0
126 for i in range(0, self.totalIndices):
127 if self.indexIsSized[i]:
128 problemSize[i] = currentSizedIndexSizes[currentSizedIdx]
129 currentSizedIdx+=1
130 else:
131 problemSize[i] = problemSize[self.indicesMapped[currentMappedIdx]]
132 currentMappedIdx+=1
133 self.problemSizes.append(tuple(problemSize))
134
135 #/ increment sizes for next benchmark
136 currentSizedIndexSizes[0] += currentSizedIndexIncrements[0]
137 currentSizedIndexIncrements[0] += self.indicesSized[0][2]
138 for i in range(1, len(self.indicesSized)+1):
139 # if prior index past max, reset to min and increment next index
140 if currentSizedIndexSizes[i-1] > self.indicesSized[i-1][3]:
141 #/ reset prior index
142 currentSizedIndexSizes[i-1] = self.indicesSized[i-1][0]
143 currentSizedIndexIncrements[i-1] = self.indicesSized[i-1][1]
144 # increment next index
145 if i >= len(self.indicesSized):
146 moreProblemSizes = False
147 else:
148 currentSizedIndexSizes[i] += currentSizedIndexIncrements[i]
149 currentSizedIndexIncrements[i] += self.indicesSized[i][2]
150
151 problemIdx+=1
152
153 ########################################
154 # YAML format
155 def __str__(self):
156 state = "[ "
157 sizedIdx = 0
158 mappedIdx = 0
159 for i in range(0, len(self.indexIsSized)):
160 if self.indexIsSized[i]:
161 indices = self.indicesSized[sizedIdx]
162 state += "[ %u, %u, %u, %u ]" \
163 % (indices[0], indices[1], indices[2], indices[3])
164 sizedIdx += 1
165 else:
166 indices = self.indicesSized[self.indicesMapped[mappedIdx]]
167 state += str(self.indicesMapped[mappedIdx])
168 mappedIdx += 1
169 if i < len(self.indexIsSized)-1:
170 state += ", "
171 state += " ]"
172 return state
173
174 class Problem:
175 """ Problem sizes, strides, padding and other info"""
176 def __init__(self, sizes=None, stridesA=None, stridesB=None, stridesC=None, stridesD=None, count=None):
177 self.sizes = tuple(sizes) if sizes else None
178 self.stridesA = tuple(stridesA) if stridesA else None
179 self.stridesB = tuple(stridesB) if stridesB else None
180 self.stridesC = tuple(stridesC) if stridesC else None
181 self.stridesD = tuple(stridesD) if stridesD else None
182
183 self.count = count
184
185 def __str__(self):
186 rv= "{ sizes:" + str(list(self.sizes))
187 if self.stridesA:
188 rv += ", stridesA:" + str(list(self.stridesA))
189 if self.stridesB:
190 rv += ", stridesB:" + str(list(self.stridesB))
191 if self.stridesC:
192 rv += ", stridesC:" + str(list(self.stridesC))
193 if self.stridesD:
194 rv += ", stridesD:" + str(list(self.stridesD))
195 rv += " }"
196 return rv
197
198 class ExactList(Problem):
199 def __init__(self, e, problemType):
200 if len(e) == problemType["TotalIndices"]:
201 if -1 in e:
202 printExit("ExactSize %s contains -1" % (e))
203 if problemType["OperationType"] == "GEMM":
204 e += [-1, -1, -1, -1]
205 e = ExactList.convertLeadingDims(problemType, tuple(e))
206 sizes=e
207
208 elif len(e) == (problemType["TotalIndices"] + problemType["NumIndicesLD"]):
209 sizes = ExactList.convertLeadingDims(problemType, tuple(e))
210 else:
211 printExit("ExactSize %s doesn't match indices of ProblemType %s, totalIndices=%d, len e=%d, NumIndicesLD = %d" \
212 % (e, problemType, problemType["TotalIndices"], len(e), problemType["NumIndicesLD"]) )
213
214 # TODO- pass strides here, remove calls to convertLeadingDims
215 Problem.__init__(self, sizes=sizes)
216
217 def __str__(self):
218 return str(list(self.sizes))
219
220 @staticmethod
221 def convertLeadingDims(problemType, problemSize, stridesA = None, stridesB = None, stridesC = None, stridesD = None):
222 # FIXME-problem: refactor to eliminate max, pass strides in strideB parm rather than hacked
223 # onto the end of the sizes list
224 predStridesD = stridesD is not None and stridesD[1] != -1
225 predStridesC = stridesC is not None and stridesC[1] != -1
226 predStridesA = stridesA is not None and stridesA[1] != -1
227 predStridesB = stridesB is not None and stridesB[1] != -1
228 return problemSize[:problemType["NumIndicesC"]+1] + \
229 (max(problemSize[0], problemSize[problemType["IndexAssignmentsLD"][0]]) if not predStridesD else stridesD[1], ) + \
230 (max(problemSize[0], problemSize[problemType["IndexAssignmentsLD"][1]]) if not predStridesC else stridesC[1], ) + \
231 (max(problemSize[problemType["IndexAssignmentsLD"][2]],
232 problemSize[problemType["IndexAssignmentsA"][0]]) if not predStridesA else stridesA[1], ) + \
233 (max(problemSize[problemType["IndexAssignmentsLD"][3]],
234 problemSize[problemType["IndexAssignmentsB"][0]]) if not predStridesB else stridesB[1], )
235
236
237 class ExactDict(Problem):
238 AllowedFields = [ 'count', 'sizes', 'stridesA', 'stridesB', 'stridesC', 'stridesD' ]
239
240 def __init__(self, e, problemType):
241 Problem.__init__(self)
242
243 for f in e:
244 if f in ExactDict.AllowedFields:
245 setattr(self, f, e[f])
246 else:
247 raise RuntimeError ("specified field '%s' is not a valid Exact dict field"%f)
248
249 if problemType:
250 if "OperationType" in problemType and problemType["OperationType"] == "GEMM":
251 sizesTuple = tuple(self.sizes + [-1, -1, -1, -1])
252 self.sizes = ExactList.convertLeadingDims(problemType, sizesTuple, self.stridesA, self.stridesB, self.stridesC, self.stridesD)
253
254 if problemType:
255 if "OperationType" in problemType and problemType["OperationType"] == "GEMM":
256 if len(self.sizes) != (problemType["TotalIndices"] + problemType["NumIndicesLD"]):
257 # FIXME-ExactDict size descriptor still (but preferrably not so) uses 8-tuple for GEMM problems
258 raise RuntimeError ("specified size=%s does not have enough indices for problem (expected %d, got %d)" \
259 % (self.sizes, problemType["TotalIndices"]+problemType["NumIndicesLD"], len(self.sizes)))
260 elif len(self.sizes) != problemType["TotalIndices"]:
261 raise RuntimeError ("specified size=%s does not have enough indices for problem (expected %d, got %d)" \
262 % (self.sizes, problemType["TotalIndices"], len(self.sizes)))
263
264
265 ################################################################################
266 # ProblemSizes
267 ################################################################################
268 """
269 Adapter class for class `ProblemSizes`. It satisfies the implicit usage requirement
270 of ClientWriter.writeClientConfig() by converting ExactLogic to list of `Problem` objects
271 """
272 class ProblemSizesMock:
273 def __init__(self, exactLogic):
274 self.problems = [Problem(problem) for problem, solution in exactLogic]
275
276 class ProblemSizesMockDummy:
277 def __init__(self):
278 self.problems = [Problem(sizes=[128, 128, 1, 512])]
279
280 class ProblemSizes:
281
282 ########################################
283 def __init__(self, problemType, config):
284 self.problemType = problemType
285 self.ranges = []
286 self.exacts = []
287 self.minStrides = None
288 if config:
289 for dictionary in config:
290 for sizeTypeKey in dictionary:
291 #print ("PROBLEM parsed:", sizeTypeKey, dictionary[sizeTypeKey])
292 if sizeTypeKey == "Range":
293 psr = ProblemSizeRange(problemType, dictionary[sizeTypeKey])
294 self.ranges.append( psr )
295 elif sizeTypeKey == "Exact":
296 e= dictionary[sizeTypeKey]
297 if isinstance(e,list):
298 self.exacts.append(ExactList(e, problemType))
299 elif isinstance(e,dict):
300 self.exacts.append(ExactDict(e, problemType))
301 else:
302 printExit("Unsupported Exact type==%s"%type(e))
303 elif sizeTypeKey == "MinStride":
304 e = dictionary[sizeTypeKey]
305 if len(e) != problemType["TotalIndices"]:
306 printExit("MinStride %s doesn't match indices of ProblemType %s" \
307 % (e, problemType) )
308 if self.minStrides:
309 printExit("Only one MinStride command is allowed in a ProblemsSizes definition. Previous minStrides:%s, New minstride:%s" \
310 % (self.minStrides, e) )
311
312 self.minStrides=(tuple(e))
313 else:
314 printExit("ProblemSize Type %s not supported"%sizeTypeKey)
315
316 if not self.minStrides:
317 # set harmless default mins of 0
318 self.minStrides = ([0]* problemType["TotalIndices"])
319
320 # not the ideal spot, but convert leading dims that are below the minimum size
321 if problemType["OperationType"] == "GEMM":
322 for i in range(0, len(self.ranges)):
323 self.ranges[i].problemSizes[:] = \
324 [ExactList.convertLeadingDims(self.problemType, problemSize) for problemSize in self.ranges[i].problemSizes]
325
326 self.problems = OrderedDict()
327 for sizeRange in self.ranges:
328 for rangeSize in sizeRange.problemSizes:
329 self.problems.update({Problem(rangeSize) : 1})
330 for e in self.exacts:
331 self.problems.update({e : 1})
332 self.problems = list(self.problems.keys())
333 self.totalProblemSizes = len(self.problems)
334
335 # max sizes
336 self.maxD = 0
337 self.maxC = 0
338 self.maxA = 0
339 self.maxB = 0
340 for problem in self.problems:
341 problemSize = problem.sizes # FIXME-problem. This should use problem.strides*
342
343 sizeLdd = problemSize[self.problemType["IndexAssignmentsLD"][0]] if problemType["OperationType"] == "GEMM" else problemSize[0]
344 sizeD = max(self.minStrides[0], sizeLdd)
345 for i in range(1, problemType["NumIndicesC"]):
346 sizeD *= max(self.minStrides[i], problemSize[i])
347
348 sizeLdc = problemSize[self.problemType["IndexAssignmentsLD"][1]] if problemType["OperationType"] == "GEMM" else problemSize[0]
349 sizeC = max(self.minStrides[0], sizeLdc)
350 for i in range(1, problemType["NumIndicesC"]):
351 sizeC *= max(self.minStrides[i], problemSize[i])
352
353 sizeLda = problemSize[self.problemType["IndexAssignmentsLD"][2]] \
354 if problemType["OperationType"] == "GEMM" \
355 else problemSize[self.problemType["IndexAssignmentsA"][0]]
356 sizeA = max(self.minStrides[self.problemType["IndexAssignmentsA"][0]], sizeLda)
357 for i in self.problemType["IndexAssignmentsA"][1:]:
358 sizeA *= max(self.minStrides[i], problemSize[i])
359
360 sizeLdb = problemSize[self.problemType["IndexAssignmentsLD"][3]] \
361 if problemType["OperationType"] == "GEMM" \
362 else problemSize[self.problemType["IndexAssignmentsB"][0]]
363 sizeB = max(self.minStrides[self.problemType["IndexAssignmentsB"][0]], sizeLdb)
364 for i in self.problemType["IndexAssignmentsB"][1:]:
365 sizeB *= max(self.minStrides[i], problemSize[i])
366
367 self.maxD = max(self.maxD, sizeD)
368 self.maxC = max(self.maxC, sizeC)
369 self.maxA = max(self.maxA, sizeA)
370 self.maxB = max(self.maxB, sizeB)
371
372 def __str__(self):
373 s = "ProblemSizes\n"
374 for sizeRange in self.ranges:
375 s += " %s" % sizeRange
376 return s
377
378 ################################################################################
379 # ProblemType
380 # name of solution should begin with name of problemType, and arguments can be listed out explicitly
381
382 ################################################################################
383 # Default Problem Type
384 ################################################################################
385 _defaultProblemType = {
386 # =GEMM uses TransposeA,B parameters and makes the problem type more readable for users
387 # =TensorContraction requires specifying
388 "OperationType": "GEMM", # GEMM, TensorContraction, ConvolutionForward, ConvolutionBackwardData, ConvolutionBackwardWeights
389 "DataType": 0, # data types can specified by a variety of ways, such as "s", as listed in SolutionStructs.py::DataType
390 "DataTypeA": 0, # A data type can specified by a variety of ways, such as "s", as listed in SolutionStructs.py::DataType
391 "DataTypeB": 0, # B data type can specified by a variety of ways, such as "s", as listed in SolutionStructs.py::DataType
392 "DataTypeE": 0, # E data type can specified by a variety of ways, such as "s", as listed in SolutionStructs.py::DataType
393 "DataTypeAmaxD": 0, # AmaxD data type can specified by a variety of ways, such as "s", as listed in SolutionStructs.py::DataType
394 "DestDataType": 0, # destination data types can specified by a variety of ways, such as "s", as listed in SolutionStructs.py::DataType
395 "ComputeDataType": 0, # compute data types can specified by a variety of ways, such as "s", as listed in SolutionStructs.py::DataType
396 "F32XdlMathOp": 0, # reducing intermediate precision from f32 to a specific type, such as "x", as listed in SolutionStructs.py::DataType.
397 # in:f32, intermediate:xf32, out:f32. f32 = xf32(f32) * xf32(f32)
398 "UseBeta": True, # =True use beta parameter (asm will check for B=0 and optimize the write for that), =False don't use beta parameter
399 "UseE": False, # =True use output E to output gemm results before activation
400 "Gradient": False, # =True set globalWriteElements to gradient mode
401 "UseBias": 0, # =1 support bias vector on M direction, =2 support bias vector on N direction, =3 support bias vector on both M,N direction
402 "BiasSrc": "D", # This parameter is used in gradient + bias. Support A, B, D.
403 "UseScaleAB": "", # Support "", "Scalar", and "Vector"
404 "UseScaleCD": False, # =True use scaleC, scaleD
405 "UseScaleAlphaVec": 0, # =1 support alpha vector on M direction, =2 support bias vector on N direction, =3 support alpha vector on both M,N direction
406 "HighPrecisionAccumulate": False, # f32 += f16*f16
407 "SilentHighPrecisionAccumulate": False, # Keep kernel names the same for HPA mode. Useful for testing.
408 "Sparse": 0, # 4:2 Structured Sparse A Matrix, 0=Non Sparse, 1=Sparse Matrix A, 2=Sparse Matrix B
409 "ComplexConjugateA": False, # complex data should be conjugated for "C" transpose case
410 "ComplexConjugateB": False,
411 "StochasticRounding": False, # By default, IEEE RNE rounding
412 # for OperationType == GEMM
413 "TransposeA": False, # =True means transA="T" or "C", =False means transA = "N"
414 "TransposeB": True,
415 "Batched": False, # add batching dimension
416 "StridedBatched": True, # use to select general batch or strided batch
417 "GroupedGemm": False, # use to select general batch or strided batch
418 # for OperationType == TensorContraction
419 # - Indices < NumIndicesC are Free or Batch indices and appear in C and D
420 # - Indices which appear in both A and B, and are < NumIndicesC are batch. A and B must have same number of batch indices.
421 # - Indices which appear in both A and B, and are >= NumIndicesC are summation. A and B must have same number of summation indices.
422 # - Indices which appear in A or B (but not both), are Free. A and B may have different numbers of free indices.
423 # - Summation loops are nested from smallest index number to largest, with the largest summation index as the 'unroll' loop.
424 # - Memory order of C and D matrices is always 0..NumIndicesC-1, with 0 as the fastest-moving.
425 # - By choosing index assignments the output can be 'transposed'. For example if IA=[1,2] IB=[0,2] then 0 is the coalesced dim for C/D.
426 # - Likewise batch index may be assigned between two free indices to control the output order, ie to write in CNHW format.
427 # - For example : IA=[0,1,3] IB=[2,1,3]. 0,2 are free indices; 1 is batch.
428 "IndexAssignmentsA": [0, 2],
429 "IndexAssignmentsB": [1, 2],
430 "NumIndicesC": 2,
431 # use initial strides for AB.
432 # This has some performance impact for the increased flexibility:
433 # - Additional strides will be passed into the kernel and will occupy SGPR registers
434 # - GlobalReadWidth must be 1 (since elements are not guaranteed to be adjacent in memory)
435 "UseInitialStridesAB": False,
436 # use initial strides for CD.
437 # This has some performance impact for the increased flexibility:
438 # - Additional strides will be passed into the kernel and will occupy SGPR registers
439 # - Additional multiply on the store address path
440 # -VectorStore must be 0. If VectorStore is -1, it will be silently set to 0 internally.
441 "UseInitialStridesCD": False,
442 "AllowNoFreeDims": False, # allow A or B to specify no free dims
443 # (if false, A and B must have at least one free dim)
444 # (if true, A and B must have at least one free or batch dim)
445 # SetConstStride* sets the specified stride in the problem.
446 # These no longer generate predicates - see AssertStrideEqualA/B below
447 # List of pairs of [index, constValue].
448 # Index is a member of the global index assignments (not an offset into IndexAssignmentsA/B)
449 # EX: SetConstStrideA: [ [3, 1], [2, 4] ] sets
450 # strideA for index3 to constant '1' and stride for index2 to constant '4'.
451 "SetConstStrideA": [],
452 "SetConstStrideB": [],
453 "SetConstStrideBias": [],
454 # Summation dimension indices
455 "MirrorDimsA": [],
456 "MirrorDimsB": [],
457 "MirrorDimsMetadata": [],
458 # for LD description
459 "NumIndicesLD": 4,
460 "IndexAssignmentsLD": [3, 4, 5, 6], # order is LDD, LDC, LDA, LDB
461 # Tile aware solution selection
462 "TileAwareSelection": False,
463 # Activation
464 "Activation": False,
465 "ActivationNoGuard": False,
466 # AmaxD
467 "OutputAmaxD": False,
468 # For kernels putting arguments in workspaces instead of kernel arguments, they can choose to support user arguments input instead.
469 "SupportUserArgs": True,
470 "SwizzleTensorA": False,
471 "SwizzleTensorB": False,
472 }
473
474 # The supported typed GEMM, each entry is (Ti, To, Tc).
475 # DataType (Ti) = The data-type of the input matrices: A/B
476 # DestDataType (To) = The data-type of the output matrices: C/D
477 # ComputeDataType (Tc) = The data-type of computation: alpha/beta:
478 # Cinternal: basically should == ComputeDataType
479 # This is used in _checkIfSupportedGEMMType()
480 _validGEMMTypes = [
481 ("H", "H", "H"),
482 ("S", "S", "S"),
483 ("D", "D", "D"),
484 ("C", "C", "C"),
485 ("Z", "Z", "Z"),
486 ("H", "H", "S"),
487 ("H", "S", "S"),
488 ("B", "B", "S"),
489 ("B", "S", "S"),
490 ("B", "H", "S"),
491 ("I8", "I", "I"),
492 ("4xi8", "I", "I"),
493 ("I8", "I8", "I"),
494 ("I8", "I", "S"),
495 ("I8", "I8", "S"),
496 ("I8", "H", "S"),
497 ("I8", "B", "S"),
498 ("F8", "S", "S"),
499 ("B8", "S", "S"),
500 ("F8B8", "S", "S"),
501 ("B8F8", "S", "S"),
502 ("F8", "H", "S"),
503 ("B8", "H", "S"),
504 ("F8B8", "H", "S"),
505 ("B8F8", "H", "S"),
506 ("B8", "B", "S"),
507 ("H", "F8", "S"),
508 ("F8", "B", "S"),
509 ("F8B8", "B", "S"),
510 ("B8F8", "B", "S"), # in/out are both R8
511 ("F8", "F8", "S"),
512 ("B8", "B8", "S"),
513 ("F8B8", "B8", "S"),
514 ("B8F8", "B8", "S"),
515 ("F8", "B8", "S"),
516 ("B8", "F8", "S"),
517 ("F8B8", "F8", "S"),
518 ("B8F8", "F8", "S"), # F8 NANOO
519 ("F8N", "S", "S"),
520 ("B8N", "S", "S"),
521 ("F8B8N", "S", "S"),
522 ("B8F8N", "S", "S"),
523 ("F8N", "H", "S"),
524 ("B8N", "H", "S"),
525 ("F8B8N", "H", "S"),
526 ("B8F8N", "H", "S"),
527 ("B8N", "B", "S"),
528 ("H", "F8N", "S"),
529 ("F8N", "B", "S"),
530 ("F8B8N", "B", "S"),
531 ("B8F8N", "B", "S"), # in/out are both R8
532 ("F8N", "F8N", "S"),
533 ("B8N", "B8N", "S"),
534 ("F8B8N", "B8N", "S"),
535 ("B8F8N", "B8N", "S"),
536 ("F8N", "B8N", "S"),
537 ("B8N", "F8N", "S"),
538 ("F8B8N", "F8N", "S"),
539 ("B8F8N", "F8N", "S"),
540 ]
541
542
543 # All HPA types are listed here (HPA=T). The name of the library logic files for these types is:
544 # *_TiToTc_BH*.yaml where Ti, To, and Tc are the data types of A/B, C/D, and computation, respectively.
545 # The name of the library logic files for non-HPA (HPA=F) types is: *_TiB*.yaml.
546 _HPATypes = [
547 ("H", "S", "S"),
548 ("H", "H", "S"),
549 ("B", "B", "S"),
550 ("B", "S", "S"),
551 ("B", "H", "S"),
552 ("I8", "I", "I"),
553 ("4xi8", "I", "I"),
554 ("I8", "I", "S"),
555 ("I8", "I8", "S"),
556 ("I8", "H", "S"),
557 ("I8", "B", "S"),
558 ("F8", "S", "S"),
559 ("B8", "S", "S"),
560 ("F8B8", "S", "S"),
561 ("B8F8", "S", "S"),
562 ("F8", "H", "S"),
563 ("B8", "H", "S"),
564 ("F8B8", "H", "S"),
565 ("B8F8", "H", "S"),
566 ("H", "F8", "S"),
567 ("F8", "B", "S"),
568 ("F8B8", "B", "S"), # in/out are both R8
569 ("F8", "F8", "S"),
570 ("B8", "B8", "S"),
571 ("F8B8", "B8", "S"),
572 ("B8F8", "B8", "S"),
573 ("F8", "B8", "S"),
574 ("B8", "F8", "S"),
575 ("F8B8", "F8", "S"),
576 ("B8F8", "F8", "S"),
577 ("F8N", "S", "S"),
578 ("B8N", "S", "S"),
579 ("F8B8N", "S", "S"),
580 ("B8F8N", "S", "S"),
581 ("F8N", "H", "S"),
582 ("B8N", "H", "S"),
583 ("F8B8N", "H", "S"),
584 ("B8F8N", "H", "S"),
585 ("H", "F8N", "S"),
586 ("F8N", "B", "S"),
587 ("F8B8N", "B", "S"), # in/out are both R8
588 ("F8N", "F8N", "S"),
589 ("B8N", "B8N", "S"),
590 ("F8B8N", "B8N", "S"),
591 ("B8F8N", "B8N", "S"),
592 ("F8N", "B8N", "S"),
593 ("B8N", "F8N", "S"),
594 ("F8B8N", "F8N", "S"),
595 ("B8F8N", "F8N", "S"),
596 ]
597
598 def problemTypeToEnum(problemType):
599 problemType["DataType"] = \
600 problemType["DataType"].value
601 problemType["DataTypeA"] = \
602 problemType["DataTypeA"].value
603 problemType["DataTypeB"] = \
604 problemType["DataTypeB"].value
605 problemType["DataTypeE"] = \
606 problemType["DataTypeE"].value
607 problemType["DataTypeAmaxD"] = \
608 problemType["DataTypeAmaxD"].value
609 problemType["DestDataType"] = \
610 problemType["DestDataType"].value
611 problemType["ComputeDataType"] = \
612 problemType["ComputeDataType"].value
613 problemType["BiasDataTypeList"] = \
614 [btype.value for btype in problemType["BiasDataTypeList"]]
615 problemType["ActivationComputeDataType"] = \
616 problemType["ActivationComputeDataType"].value
617 problemType["ActivationType"] = \
618 problemType["ActivationType"].value
619 problemType["F32XdlMathOp"] = \
620 problemType["F32XdlMathOp"].value
621 if "DataTypeMetadata" in problemType:
622 problemType["DataTypeMetadata"] = \
623 problemType["DataTypeMetadata"].value
624
625 class ProblemType(Mapping):
626 ########################################
627
628 @classmethod
629 def FromDefaultConfig(printIndexAssignmentInfo: bool):
630 return ProblemType(_defaultProblemType, printIndexAssignmentInfo)
631
632 def __init__(self, config, printIndexAssignmentInfo: bool):
633 self.state = {}
634
635 for key in _defaultProblemType:
636 assignParameterWithDefault(self.state, key, config, _defaultProblemType)
637
638 # adjusting all data types
639 if "DataType" in config:
640 self["DataType"] = DataType(config["DataType"])
641 self["DataTypeA"] = self["DataType"]
642 self["DataTypeB"] = self["DataType"]
643 else:
644 raise Exception("NO data type specified")
645 self["DataType"] = DataType(0)
646 self["DataTypeA"] = DataType(0)
647 self["DataTypeB"] = DataType(0)
648
649 if "DataTypeA" in config:
650 self["DataTypeA"] = DataType(config["DataTypeA"])
651
652 if "DataTypeB" in config:
653 self["DataTypeB"] = DataType(config["DataTypeB"])
654
655 if "DestDataType" in config:
656 self["DestDataType"] = DataType(config["DestDataType"])
657 else:
658 if "DataType" in config:
659 self["DestDataType"] = DataType(config["DataType"])
660 else:
661 raise Exception("NO dest data type or data type specified")
662 self["DataType"] = DataType(0)
663
664 self["DataTypeE"] = self["DestDataType"]
665 if "DataTypeE" in config:
666 self["DataTypeE"] = DataType(config["DataTypeE"])
667
668 if "ComputeDataType" in config:
669 self["ComputeDataType"] = DataType(config["ComputeDataType"])
670 else:
671 if "DestDataType" in config:
672 self["ComputeDataType"] = DataType(config["DestDataType"])
673 else:
674 if "DataType" in config:
675 self["ComputeDataType"] = DataType(config["DataType"])
676 else:
677 raise Exception("NO compute data type, or dest data type, or data type specified")
678 self["DataType"] = DataType(0)
679
680 # Just like DataTypeE is DestDataType by default; DataTypeAmaxD if ComputeDataType by default.
681 # So far we don't have to set it in config yamls
682 self["DataTypeAmaxD"] = self["ComputeDataType"]
683 if "DataTypeAmaxD" in config:
684 self["DataTypeAmaxD"] = DataType(config["DataTypeAmaxD"])
685
686 if self["Sparse"]:
687 self["DataTypeMetadata"] = DataType("I8")
688
689 if "F32XdlMathOp" in config:
690 self["F32XdlMathOp"] = DataType(config["F32XdlMathOp"])
691 else:
692 self["F32XdlMathOp"] = DataType(DataTypeEnum.Float)
693
694 # Modifying ComputeDataType for HHH+HPA: if (HHH+HPA), convert it to HHS_BH by setting ComputeDataType to S.
695 if self["ComputeDataType"].isHalf() and self["DataType"].isHalf() and self["HighPrecisionAccumulate"]:
696 printWarning("Inconsistent DataTypes: DataType == f16, DestType == f16, ComputeDataType == f16, but HPA == True (HHH+HPA, no such a type); Converting HHH+HPA to HHS_BH by setting compute data type to f32.")
697 self["ComputeDataType"] = DataType('s')
698
699 # Modifying ComputeDataType for BBB+HPA: if (BBB+HPA), convert it to BBS_BH by setting ComputeDataType to S.
700 if self["ComputeDataType"].isBFloat16() and self["DataType"].isBFloat16() and self["HighPrecisionAccumulate"]:
701 printWarning("Inconsistent DataTypes: DataType == bf16, DestType == bf16, ComputeDataType == bf16, but HPA == True (BBB+HPA, no such a type); Converting BBB+HPA to BBS_BH by setting compute data type to f32.")
702 self["ComputeDataType"] = DataType('s')
703
704 # Modifying ComputeDataType for I8I8I_BH: if (I8I8I8+HPA), convert it to I8I8I_BH by setting ComputeDataType to i.
705 if self["ComputeDataType"].isInt8() and DataType(config["DataType"]).isInt8() and self["HighPrecisionAccumulate"]:
706 print2("DataType == i8 and HPA == True; setting compute data type to int32")
707 self["ComputeDataType"] = DataType('i')
708
709 if self["OperationType"] == "GEMM":
710 self._checkIfSupportedGEMMType()
711 self.initGEMM()
712 else:
713 raise Exception("Unsupported OperationType = %s" % self["OperationType"])
714
715 self.state["AssignedDerivedParameters"] = False
716 ProblemType.assignDerivedParameters(self.state, printIndexAssignmentInfo)
717
718 for tc in ('A', 'B'):
719 for sc in self["SetConstStride%s"%tc] :
720 (anchorDim, stride) = sc[:2]
721 if anchorDim not in self.state["IndexAssignments%s"%tc]:
722 raise Exception("SetConstStride%s=%s anchorDim=%u is not in IndexAssignments%s"%(tc, sc, anchorDim, tc))
723
724 # Bias
725 # If compute data type is not equal to dest data type, tensile will run conversion kernel.
726 # In this case we don't need to apply bias in beta only kernel.
727 if "UseBias" in config:
728 if self["ComputeDataType"] != self["DestDataType"]:
729 self["BetaOnlyUseBias"] = False
730 else:
731 self["BetaOnlyUseBias"] = True if self["UseBias"] > 0 else False
732 if "BiasDataTypeList" in config:
733 self["BiasDataTypeList"] = [DataType(btype) for btype in config["BiasDataTypeList"]]
734 self["BiasDataTypeList"].sort() # Make name unique
735 else:
736 self["BiasDataTypeList"] = getBiasDataTypeListDefault(self)
737 else:
738 self["BetaOnlyUseBias"] = False
739 self["BiasDataTypeList"] = []
740
741 # Activation
742 # Currently, ActivationType supports only 'all' and 'hipblaslt_all', and is active only when the Activation configuration is set to True.
743 # Otherwise, ActivationType will be set to 'none'.
744 if "Activation" in config:
745 typeStr = config.get("ActivationType", 'none')
746 if typeStr not in ['all', 'hipblaslt_all']:
747 typeStr = 'none'
748 else:
749 typeStr = 'none'
750 self["ActivationType"] = ActivationType(typeStr)
751 if "ActivationComputeDataType" in config:
752 self["ActivationComputeDataType"] = DataType(config["ActivationComputeDataType"])
753 else:
754 self["ActivationComputeDataType"] = self["ComputeDataType"]
755
756 if self["ActivationType"] != 'none':
757 # This is a dummy guard in case we currently don't have a converter to convert data from compute type to activation compute type
758 if self["ActivationComputeDataType"] not in [self["ComputeDataType"], self["DestDataType"]]:
759 printWarning("TensileLite currently only supports ActivationComputeDataType (%s) = ComputeDataType (%s) or DestDataType (%s). \
760 ActivationComputeDataType will be set to ComputeDataType automatically."%(self["ActivationComputeDataType"].toChar(), \
761 self["ComputeDataType"], \
762 self["DestDataType"]))
763 self["ActivationComputeDataType"] = self["ComputeDataType"]
764 if (self["ActivationComputeDataType"].numRegisters() != self["ComputeDataType"].numRegisters()) and \
765 (self["DataType"].numRegisters() < self["DestDataType"].numRegisters()):
766 printWarning("TensileLite only supports ActivationComputeDataType = ComputeDataType if DestDataType > DataType. \
767 ActivationComputeDataType will be set to ComputeDataType automatically.")
768 self["ActivationComputeDataType"] = self["ComputeDataType"]
769
770 if "UseE" in config:
771 if config["UseE"]:
772 if self["ActivationType"] == 'none':
773 printWarning("Use E is disabled cause Activation is set to False.")
774 self["UseE"] = False
775 else:
776 self["UseE"] = config["UseE"]
777 else:
778 self["UseE"] = config["UseE"]
779
780 if "Gradient" in config:
781 if config["Gradient"]:
782 if (not self["UseBias"]) and self["ActivationType"] == 'none':
783 printWarning("Gradient is disabled cause bias and activation are both disabled.")
784 self["Gradient"] = False
785 if self["ActivationType"] != 'none' and self["UseE"] == False:
786 printWarning("Use E is enabled cause Activation is enabled.")
787 self["UseE"] = True
788 elif self["ActivationType"] != 'none' and self["UseE"] == False:
789 printWarning("Use E is disabled cause Activation is disabled.")
790 self["UseE"] = False
791 # if self["UseScaleAlphaVec"]:
792 # printWarning("Use scaleAlphaVec is disabled cause Gradient is enabled.")
793 # self["UseScaleAlphaVec"] = False
794 self["Gradient"] = config["Gradient"]
795
796 # Need gradient info
797 biasSrcList = ["A", "B", "D"]
798 if "BiasSrc" in config:
799 if not self["Gradient"] and config["BiasSrc"] != "D":
800 printWarning("BiasSrc is set to D cause Gradient is disabled.")
801 self["BiasSrc"] = "D"
802 elif self["Gradient"]:
803 # # Currently only supports D :)
804 # if config["BiasSrc"] != "D":
805 # raise Exception("BiasSrc currently only supports D.")
806 if config["BiasSrc"] not in biasSrcList:
807 raise Exception("BiasSrc only supports A, B, D.")
808
809 if "ActivationNoGuard" in config:
810 self["ActivationNoGuard"] = config["ActivationNoGuard"]
811 if self["ActivationNoGuard"]:
812 if self["ActivationType"] == 'none':
813 printWarning("ActivationNoGuard is set to False cause Acivation is off.")
814 self["ActivationNoGuard"] = False
815 if (not self["Gradient"]):
816 printWarning("ActivationNoGuard is set to False cause Gradient is off.")
817 self["ActivationNoGuard"] = False
818
819 ################################################################################
820 # Function checkIfSupportedGEMMType:
821 # Assures 3 data-types are valid, supported and well-assigned
822 # See the discussion in ValidParameters.py for validGEMMTypes
823 ################################################################################
824 def _checkIfSupportedGEMMType(self):
825 inType = self["DataType"]
826 outType = self["DestDataType"]
827 computeType = self["ComputeDataType"]
828
829 gemmType = ( inType.toChar(), outType.toChar(), computeType.toChar() )
830 if gemmType not in _validGEMMTypes:
831 raise Exception("This typed-GEMM (Ti, To, Tc) = (%s, %s, %s) is not supported yet."%(gemmType[0], gemmType[1], gemmType[2]))
832
833 ########################################
834 def initGEMM(self):
835 sumIdx = 3 if self["Batched"] else 2
836 self["IndexAssignmentsA"] = [0, sumIdx] # N
837 self["IndexAssignmentsB"] = [sumIdx, 1] # N
838 if self.state["Sparse"] == 2:
839 self["IndexAssignmentsMetadata"] = [sumIdx, 1] # N (ref B)
840 else:
841 self["IndexAssignmentsMetadata"] = [sumIdx, 0] # T (ref A)
842 if self["TransposeA"]:
843 self["IndexAssignmentsA"] = [sumIdx, 0] # T
844 if self["TransposeB"]:
845 self["IndexAssignmentsB"] = [1, sumIdx] # T
846 if self["Batched"]:
847 self["IndexAssignmentsA"].append(2)
848 self["IndexAssignmentsB"].append(2)
849 self["IndexAssignmentsMetadata"].append(2)
850 self["NumIndicesC"] = 3
851 else:
852 self["NumIndicesC"] = 2
853
854 self["NumIndicesLD"] = 4
855 self["IndexAssignmentsLD"][0] = self["NumIndicesC"] + 1
856 for i in range(1, len(self["IndexAssignmentsLD"])):
857 self["IndexAssignmentsLD"][i] = self["IndexAssignmentsLD"][i-1] + 1
858
859 ########################################
860 def isGEMM(self):
861 return self.operationType == 0
862
863 ########################################
864 # determine d0, d1, dU
865 @staticmethod
866 def assignDerivedParameters(state, printIndexAssignmentInfo: bool=False):
867 if "AssignedDerivedParameters" in state:
868 if state["AssignedDerivedParameters"]:
869 return
870 state["AssignedDerivedParameters"] = False
871
872 state["TotalIndices"] = max(max(state["IndexAssignmentsA"])+1, \
873 max(state["IndexAssignmentsB"])+1)
874
875 # determine num free, batch
876 state["IndicesFree"] = []
877 state["IndicesBatch"] = []
878 state["IndicesSummation"] = []
879
880 for i in range(0, state["NumIndicesC"]):
881 inA = i in state["IndexAssignmentsA"]
882 inB = i in state["IndexAssignmentsB"]
883 if inA and inB:
884 state["IndicesBatch"].append(i)
885
886 elif inA or inB:
887 state["IndicesFree"].append(i)
888 else:
889 raise Exception("invalid index %u (inC but not (inA or inB))" % i)
890
891 # determine num summation
892 for i in range(state["NumIndicesC"], state["TotalIndices"]):
893 inA = i in state["IndexAssignmentsA"]
894 inB = i in state["IndexAssignmentsB"]
895 if inA and inB:
896 state["IndicesSummation"].append(i)
897 else:
898 raise Exception("invalid index %u (expected summation but not (inA and inB))" % i)
899 # print index assignments
900 if printIndexAssignmentInfo:
901 print("IndicesFree: %s" % state["IndicesFree"])
902 print("IndicesBatch: %s" % state["IndicesBatch"])
903 print("IndicesSum: %s" % state["IndicesSummation"])
904 print("IndexAssignmentsA: %s" % state["IndexAssignmentsA"])
905 print("IndexAssignmentsB: %s" % state["IndexAssignmentsB"])
906 print("NumIndicesC: %s" % state["NumIndicesC"])
907
908 for k in ('IndexAssignmentsA','IndexAssignmentsB'):
909 if len(state[k]) != len(set(state[k])):
910 raise Exception("duplicate index in %s=%s"% (k,state[k]))
911
912 state["NumIndicesFree"] = len(state["IndicesFree"])
913 state["NumIndicesBatch"] = len(state["IndicesBatch"])
914 state["NumIndicesSummation"] = len(state["IndicesSummation"])
915 if not state["AllowNoFreeDims"] and state["NumIndicesFree"] < 2 :
916 raise Exception("Tensile requires >= 2 free indices or set AllowNoFreeDims; FreeIndices=%s."% state["IndicesFree"])
917
918 # by default, unroll index will be the last/inner summation index
919 state["IndexUnroll"] = state["IndicesSummation"][len(state["IndicesSummation"])-1]
920 for i in range(0, len(state["IndexAssignmentsA"])):
921 if state["IndexAssignmentsA"][i] == state["IndexUnroll"]:
922 state["IndexUnrollA"] = i
923 break
924 for i in range(0, len(state["IndexAssignmentsB"])):
925 if state["IndexAssignmentsB"][i] == state["IndexUnroll"]:
926 state["IndexUnrollB"] = i
927 break
928 for i in range(0, len(state["IndexAssignmentsMetadata"])):
929 if state["IndexAssignmentsMetadata"][i] == state["IndexUnroll"]:
930 state["IndexUnrollM"] = i
931 break
932 #print2("IndexUnrollA: %u" % state["IndexUnrollA"])
933 #print2("IndexUnrollB: %u" % state["IndexUnrollB"])
934
935 # assign d0, d1
936 if state["AllowNoFreeDims"]:
937 dimList = state["IndicesFree"] + state["IndicesBatch"]
938 else:
939 dimList = state["IndicesFree"]
940 state["Index01A"] = [i for i in state["IndexAssignmentsA"] if i in dimList][0]
941 state["Index01B"] = [i for i in state["IndexAssignmentsB"] if i in dimList][0]
942 #print2("Index01A: %u" % state["Index01A"])
943 #print2("Index01B: %u" % state["Index01B"])
944 # Store code is optimized for 0 as the fastest-moving in memory
945 # whichever has lower stride in C (lower value), is 0, other is 1
946 if state["Index01A"] < state["Index01B"]:
947 state["Index0"] = state["Index01A"]
948 state["Index1"] = state["Index01B"]
949 state["Tensor0"] = 0
950 state["Tensor1"] = 1
951 state["TileA"] = 0
952 state["TileB"] = 1
953 else:
954 state["Index0"] = state["Index01B"]
955 state["Index1"] = state["Index01A"]
956 state["Tensor0"] = 1
957 state["Tensor1"] = 0
958 state["TileA"] = 1
959 state["TileB"] = 0
960
961 # generalize transpose
962 strideIdxA = state["IndexAssignmentsA"].index(state["Index01A"])
963 strideIdxB = state["IndexAssignmentsB"].index(state["Index01B"])
964 unrollIdxA = state["IndexAssignmentsA"].index(state["IndexUnroll"])
965 unrollIdxB = state["IndexAssignmentsB"].index(state["IndexUnroll"])
966 state["TLUA"] = strideIdxA < unrollIdxA
967 state["TLUB"] = strideIdxB < unrollIdxB
968 #state["TLUB"] = True # hack
969
970 if printIndexAssignmentInfo:
971 print("TLUA: %s (stridePosA(%d) <? unrollIdxA(%d)" % \
972 (state["TLUA"], strideIdxA, unrollIdxA))
973 print("TLUB: %s (stridePosB(%d) <? unrollIdxB(%d)" % \
974 (state["TLUB"], strideIdxB, unrollIdxB))
975 print("Index01A: %s" % state["Index01A"])
976 print("Index01B: %s" % state["Index01B"])
977 #unrollDimStrideGreaterThanTileDimStrideA = TLUA = !transA = fast
978 #!unrollDimStrideLessThanTileDimStrideB = TLUB = transB = fast
979 state["AssignedDerivedParameters"] = True
980
981 if state["Sparse"]:
982 state["Index01Metadata"] = [i for i in state["IndexAssignmentsMetadata"] if i in dimList][0]
983 strideIdxM = state["IndexAssignmentsMetadata"].index(state["Index01Metadata"])
984 unrollIdxM = state["IndexAssignmentsMetadata"].index(state["IndexUnroll"])
985 state["TLUMetadata"] = strideIdxM < unrollIdxM
986 if printIndexAssignmentInfo:
987 print("TLUMetadata: %s (stridePosM(%d) <? unrollIdxM(%d)" % \
988 (state["TLUMetadata"], strideIdxM, unrollIdxM))
989 print("Index01Metadata: %s" % state["Index01Metadata"])
990
991 ########################################
992 def __str__(self):
993 indexChars = INDEX_CHARS
994 # C dimensions
995 name = ["C" + "".join(indexChars[i].lower() for i in range(0, self["NumIndicesC"]))]
996
997 # A dimensions
998 name.append("A" + "".join(indexChars[i] if i in self["MirrorDimsA"] else indexChars[i].lower() for i in self["IndexAssignmentsA"]))
999 if self["ComplexConjugateA"]:
1000 name.append("C")
1001
1002 # B dimensions
1003 name.append("B" + "".join(indexChars[i] if i in self["MirrorDimsB"] else indexChars[i].lower() for i in self["IndexAssignmentsB"]))
1004 if self["ComplexConjugateB"]:
1005 name.append("C")
1006
1007 # DataTypes
1008 if self["DataType"] != self["DataTypeA"] or self["DataType"] != self["DataTypeB"]:
1009 name.append(self["DataTypeA"].toChar() + self["DataTypeB"].toChar())
1010 name.append(self["DataType"].toChar()) # Type of A/B
1011
1012 # Special condition for some newly supported kernels:
1013 # HHS, HSS, BSS and I8II kernels, use a clearer naming _TiToTc_
1014 # TODO: Distinguish all kernels by _TiToTc_ to be more consistent with rocblas
1015 gemmType = (self["DataType"].toChar(),self["DestDataType"].toChar(),self["ComputeDataType"].toChar() )
1016 if gemmType in _HPATypes:
1017 name[-1] += "".join([self["DestDataType"].toChar(), self["ComputeDataType"].toChar()])
1018
1019 if not self["F32XdlMathOp"].isSingle() and self["DataType"].isSingle():
1020 name.append("".join(["M", self["F32XdlMathOp"].toChar()]))
1021
1022 if self["SwizzleTensorA"]:
1023 name.append("STA")
1024
1025 if self["SwizzleTensorB"]:
1026 name.append("STB")
1027
1028 # Other
1029 other = ""
1030 if self["UseBeta"]: other += "B"
1031 if self["HighPrecisionAccumulate"] and not self["SilentHighPrecisionAccumulate"]: other += "H"
1032 if self["UseInitialStridesAB"]: other += "I"
1033 if self["UseInitialStridesCD"]: other += "Ic"
1034 if other: name.append(other)
1035
1036 if self["UseBias"]:
1037 name.append("Bias")
1038 if self["BiasDataTypeList"] != getBiasDataTypeListDefault(self):
1039 name.append("".join(i.toChar() for i in self["BiasDataTypeList"]))
1040 if self["BiasSrc"] and self["Gradient"]: # Show bias src if gradient = True
1041 name.append(f"{self['BiasSrc']}")
1042
1043 factorDim = max(self["UseScaleAlphaVec"], self["UseBias"])
1044 if factorDim > 1 :
1045 s = ("N" if factorDim == 2 else "MN")
1046 name.append(f"FD{s}")
1047
1048 if self["UseE"]:
1049 if self["Gradient"]:
1050 name.append(f"Grad{self['DataTypeE'].toChar()}")
1051 else:
1052 name.append(f"Aux{self['DataTypeE'].toChar()}")
1053 if self["OutputAmaxD"]:
1054 name.append("AmaxD")
1055 if self["Sparse"]:
1056 if self["Sparse"] == 2:
1057 name.append("SPB")
1058 else:
1059 name.append("SPA")
1060
1061 # precision and other
1062 # name += "_SB" if self["StridedBatched"] else "_GB"
1063 if self["GroupedGemm"]:
1064 name.append("GG")
1065 else:
1066 if not self["StridedBatched"]:
1067 name.append("GB") # legacy
1068
1069 # Activation Naming
1070 if self["ActivationType"] != 'none':
1071 if self["ActivationType"] == 'all':
1072 name.append("A")
1073 elif self["ActivationType"] == 'hipblaslt_all':
1074 name.append("HA")
1075 else:
1076 name.append(f"{str(self['ActivationType']).upper()}")
1077 name.append(self["ActivationComputeDataType"].toChar())
1078 if self["ActivationNoGuard"]: name[-1] += "NG"
1079
1080 if self["UseScaleAB"] == "Scalar":
1081 name.append("SAB")
1082 elif self["UseScaleAB"] == "Vector":
1083 name.append("SABV")
1084 if self["UseScaleCD"]: name.append("SCD")
1085 if self["UseScaleAlphaVec"]: name.append("SAV")
1086
1087 if self["SupportUserArgs"]: name.append("UserArgs")
1088
1089 return "_".join(name)
1090
1091 def keys(self):
1092 return list(self.state.keys())
1093 def __len__(self):
1094 return len(self.state)
1095 def __iter__(self):
1096 return iter(self.state)
1097 def __getitem__(self, key):
1098 return self.state[key]
1099 def __setitem__(self, key, value):
1100 self.state[key] = value
1101 def __repr__(self):
1102 return self.__str__()
1103 def getAttributes(self):
1104 return self.state
1105 def __hash__(self):
1106 return hash(str(self))
1107 def __eq__(self, other):
1108 return isinstance(other, ProblemType) and self.getAttributes() == other.getAttributes()
1109 def __ne__(self, other):
1110 result = self.__eq__(other)
1111 if result is NotImplemented:
1112 return result
1113 return not result
1114
1115 def get(self, key, default=None):
1116 try:
1117 return self.state[key]
1118 except:
1119 return default
1120
1121 ################################################################################
1122 # Bias Type
1123 ################################################################################
1124
1125 def getBiasDataTypeListDefault(problem: ProblemType) -> List[DataType]:
1126 bList = []
1127 for d in ["DataType", "ComputeDataType", "DestDataType"]:
1128 dtype = DataType(problem[d])
1129 # filter out int8/f8/b8, because it is not supported by bias datatype
1130 # TODO
1131 if not dtype.isInt8() and not dtype.is8bitFloat():
1132 bList.append(dtype)
1133
1134 biasDataTypeList = list(set(bList))
1135 biasDataTypeList.sort() # Make name unique
1136 return biasDataTypeList