Debian Codegraph @

tensilelite/Tensile/SolutionLibrary.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 . import Properties
28 from . import Hardware
29 from . import Contractions
30 from Tensile.Common import state, IsaInfo
31 from Tensile.Common.Architectures import gfxToIsa
32 from Tensile.SolutionStructs.Naming import getSolutionNameMin, getKernelNameMin
33
34 class SingleSolutionLibrary:
35 Tag = "Single"
36
37 def __init__(self, solution):
38 self.solution = solution
39
40 @property
41 def tag(self):
42 return self.__class__.Tag
43
44 def state(self):
45 return {"type": self.tag, "index": self.solution.index}
46
47 def remapSolutionIndices(self, indexMap):
48 pass
49
50 class IndexSolutionLibrary(SingleSolutionLibrary):
51 Tag = "Index"
52
53 def state(self):
54 return self.solution.index
55
56
57 class PlaceholderLibrary:
58 Tag = 'Placeholder'
59
60 def __init__(self, name):
61 self.filenamePrefix = name
62
63 @property
64 def tag(self):
65 return self.__class__.Tag
66
67 def state(self):
68 return {'type': self.tag, 'value': self.filenamePrefix}
69
70 def remapSolutionIndices(self, indexMap):
71 pass
72
73 def merge(self, other):
74 pass
75
76
77 class MatchingLibrary:
78 Tag = "Matching"
79 StateKeys = [("type", "tag"), "properties", "table", "distance"]
80
81 @classmethod
82 def FromOriginalState(cls, d, solutions):
83 indices = d["indexOrder"]
84 distance = d["distance"]
85 origTable = d["table"]
86
87 propertyKeys = {
88 2: Properties.Property("FreeSizeA", index=0),
89 3: Properties.Property("FreeSizeB", index=0),
90 1: Properties.Property("BoundSize", index=0)
91 }
92 if distance == "Equality" or distance == "GridBased":
93 propertyKeys[0] = Properties.Property("BatchSize", index=0)
94
95 if distance == "Range":
96 propertyKeys = {
97 0: Properties.Property("FreeSizeA", index=0),
98 1: Properties.Property("FreeSizeA", index=0),
99 2: Properties.Property("FreeSizeB", index=0),
100 3: Properties.Property("FreeSizeB", index=0),
101 4: Properties.Property("BatchSize", index=0),
102 5: Properties.Property("BatchSize", index=0),
103 6: Properties.Property("BoundSize", index=0),
104 7: Properties.Property("BoundSize", index=0)
105 }
106
107 properties = list([propertyKeys[i] for i in indices if i in propertyKeys])
108 keyOrder = [i for i, j in enumerate(indices) if j in propertyKeys]
109
110 table = []
111
112 for row in origTable:
113 try:
114 index = row[1][0]
115 value = IndexSolutionLibrary(solutions[index])
116 key = list([row[0][i] for i in keyOrder])
117 if distance == "GridBased":
118 entry = {"key": key, "index": value}
119 else:
120 entry = {"key": key, "index": value, "speed": row[1][1]}
121
122 table.append(entry)
123 except KeyError:
124 pass
125
126 table.sort(key=lambda r: r["key"])
127
128 return cls(properties, table, distance)
129
130 @property
131 def tag(self):
132 return self.__class__.Tag
133
134 def merge(self, other):
135 assert self.__class__ == other.__class__ \
136 and self.properties == other.properties \
137 and self.distance == other.distance
138
139 self.table += other.table
140
141 self.table.sort(key=lambda r: r["key"])
142
143 def remapSolutionIndices(self, indexMap):
144 pass
145
146 def __init__(self, properties, table, distance):
147 self.properties = properties
148 self.table = table
149 self.distance = distance
150
151 class FreeSizeLibrary:
152 Tag = "FreeSize"
153 StateKeys = [("type", "tag"), "table"]
154
155 @classmethod
156 def FromOriginalState(cls, d, solutions):
157 origTable = d["table"]
158
159 table = []
160
161 try:
162 indexStart = origTable[0]
163 indexOffset = origTable[1]
164 for index in range(indexStart, indexStart + indexOffset):
165 value = IndexSolutionLibrary(solutions[index])
166 entry = {"index": value}
167 table.append(entry)
168 except KeyError:
169 pass
170
171 return cls(table)
172
173 @property
174 def tag(self):
175 return self.__class__.Tag
176
177 def merge(self, other):
178 assert self.__class__ == other.__class__
179
180 self.table += other.table
181
182 def remapSolutionIndices(self, indexMap):
183 pass
184
185 def __init__(self, table):
186 self.table = table
187
188 class PredictionLibrary:
189 Tag = "Prediction"
190 StateKeys = [("type", "tag"), "table"]
191
192 @classmethod
193 def FromOriginalState(cls, d, solutions):
194 origTable = d["table"]
195
196 table = []
197
198 try:
199 indexStart = origTable[0]
200 indexOffset = origTable[1]
201 for index in range(indexStart, indexStart + indexOffset):
202 value = IndexSolutionLibrary(solutions[index])
203 table.append(value)
204 except KeyError:
205 pass
206
207 return cls(table)
208
209 @property
210 def tag(self):
211 return self.__class__.Tag
212
213 def merge(self, other):
214 assert self.__class__ == other.__class__
215
216 self.table += other.table
217
218 def remapSolutionIndices(self, indexMap):
219 pass
220
221 def __init__(self, table):
222 self.table = table
223
224 class MLPClassificationLibrary:
225 Tag = "MLPClassification"
226 StateKeys = [("type", "tag"), "table", "mlp", "problemFeatures"]
227
228 @classmethod
229 def FromOriginalState(cls, d, solutions):
230 origTable = d["table"]
231 table = []
232
233 try:
234 indexStart = origTable[0]
235 indexOffset = origTable[1]
236 for index in range(indexStart, indexStart + indexOffset):
237 value = IndexSolutionLibrary(solutions[index])
238 table.append(value)
239 except KeyError:
240 pass
241
242 mlp = d["mlp"]
243 problem_features = d["problemFeatures"]
244 return cls(table, mlp, problem_features)
245
246 @property
247 def tag(self):
248 return self.__class__.Tag
249
250 def merge(self, other):
251 raise RuntimeError(
252 "MLPClassificationLibrary does not support merging."
253 )
254
255 def remapSolutionIndices(self, indexMap):
256 pass
257
258 def __init__(self, table, mlp, problem_features):
259 self.table = table
260 self.mlp = mlp
261 self.problemFeatures = problem_features
262
263
264 class ProblemMapLibrary:
265 Tag = "ProblemMap"
266 StateKeys = [("type", "tag"), ("property", "mappingProperty"), ("map", "mapping")]
267
268 def __init__(self, mappingProperty=None, mapping=None):
269 self.mappingProperty = mappingProperty
270 self.mapping = mapping
271
272 @property
273 def tag(self):
274 return self.__class__.Tag
275
276 def merge(self, other):
277 assert self.__class__ == other.__class__ and self.tag == other.tag and self.mappingProperty == other.mappingProperty
278
279 for key, value in list(other.mapping.items()):
280 if key in self.mapping:
281 self.mapping[key].merge(value)
282 else:
283 self.mapping[key] = value
284
285 def remapSolutionIndices(self, indexMap):
286 for key, value in list(self.mapping.items()):
287 value.remapSolutionIndices(indexMap)
288
289
290 class PredicateLibrary:
291 StateKeys = [("type", "tag"), "rows"]
292
293 def __init__(self, tag=None, rows=None):
294 self.tag = tag
295 if rows is None: rows = []
296 self.rows = rows
297
298 def merge(self, other):
299 assert self.__class__ == other.__class__ and self.tag == other.tag
300
301 rowPreds = [r["predicate"] for r in self.rows]
302
303 for row in other.rows:
304 if row["predicate"] in rowPreds:
305 myRownum = rowPreds.index(row["predicate"])
306 self.rows[myRownum]["library"].merge(row["library"])
307 else:
308 self.rows.append(row)
309
310 if self.rows[0]["library"].tag == "Placeholder":
311 # Sort to ensure pure gemm can be search first
312 self.rows.sort(key=lambda x: len(x["library"].filenamePrefix))
313 else:
314 # Sort to ensure consistent fallback logic.
315 self.rows.sort(key=lambda x: x["predicate"])
316
317 def remapSolutionIndices(self, indexMap):
318 for row in self.rows:
319 row["library"].remapSolutionIndices(indexMap)
320
321
322 class MasterSolutionLibrary:
323 StateKeys = ["solutions", "library"]
324
325 @classmethod
326 def FixSolutionIndices(cls, solutions):
327 # fix missing and duplicate solution indices.
328 try:
329 maxSolutionIdx = max([s.index for s in solutions if s.index is not None])
330 except ValueError:
331 maxSolutionIdx = -1
332
333 solutionsSoFar = set()
334 for solution in solutions:
335 if solution.index is None or solution.index in solutionsSoFar:
336 maxSolutionIdx += 1
337 solution.index = maxSolutionIdx
338 else:
339 solutionsSoFar.add(solution.index)
340
341 @classmethod
342 def FromOriginalState(cls,
343 origData,
344 origSolutions,
345 splitGSU: bool,
346 printSolutionRejectionReason: bool,
347 printIndexAssignmentInfo: bool,
348 assembler,
349 isaInfoMap: Dict[str, IsaInfo],
350 lazyLibraryLoading: bool,
351 solutionClass=Contractions.Solution,
352 libraryOrder=None,
353 placeholderName='TensileLibrary'):
354
355 # functions for creating each "level" of the library
356 def hardware(d, problemType, solutions, library, placeholderName):
357 devicePart = d["ArchitectureName"]
358 cuCount = d["CUCount"]
359
360 newLib = PredicateLibrary(tag="Hardware")
361 if devicePart == "fallback":
362 pred = Hardware.HardwarePredicate("TruePred")
363 else:
364 pred = Hardware.HardwarePredicate.FromHardware(gfxToIsa(devicePart), cuCount)
365
366 newLib.rows.append({"predicate": pred, "library": library})
367
368 if lazyLibrary:
369 if cuCount: placeholderName += "_CU" + str(cuCount)
370 placeholderName += "_" + str(devicePart)
371
372 return newLib, placeholderName
373
374 def operationIdentifier(d, problemType, solutions, library, placeholderName):
375 operationID = problemType.operationIdentifier
376 prop = Properties.Property("OperationIdentifier")
377 mapping = {operationID: library}
378
379 newLib = ProblemMapLibrary(prop, mapping)
380
381 if lazyLibrary:
382 placeholderName += "_" + operationID
383
384 return newLib, placeholderName
385
386 def performanceMetric(d, problemType, solutions, library, placeholderName):
387 if d.get("PerfMetric", "DeviceEfficiency") != "DeviceEfficiency":
388 predicate = Properties.Predicate(tag=d["PerfMetric"])
389 else:
390 predicate = Properties.Predicate(tag="TruePred")
391 newLib = PredicateLibrary(tag="Problem")
392 newLib.rows.append({"predicate": predicate, "library": library})
393
394 if lazyLibrary and predicate.tag != "TruePred":
395 placeholderName += "_" + predicate.tag
396
397 return newLib, placeholderName
398
399 def predicates(d, problemType, solutions, library, placeholderName):
400 predicates = problemType.predicates(includeBatch=True, includeType=True)
401 predicate = Contractions.ProblemPredicate.And(predicates)
402
403 newLib = PredicateLibrary(tag="Problem")
404 newLib.rows.append({"predicate": predicate, "library": library})
405
406 if lazyLibrary:
407 placeholderName += problemType.placeholderStr(includeBatch=True, includeType=True)
408
409 return newLib, placeholderName
410
411 def placeholder(d, problemType, solutions, library, placeholderName):
412 newLib = PlaceholderLibrary(placeholderName)
413 return newLib, placeholderName
414
415 def selection(d, problemType, solutions, library, placeholderName):
416 if d["LibraryType"] == "Matching":
417 if d["Library"]["distance"] == "Equality":
418 predicate = Properties.Predicate(tag="EqualityMatching")
419 elif d["Library"]["distance"] == "Range":
420 predicate = Properties.Predicate(tag="RangeMatching")
421 else:
422 predicate = Properties.Predicate(tag="TruePred")
423
424 matchingLib = MatchingLibrary.FromOriginalState(d["Library"], solutions)
425 library = PredicateLibrary(tag="Problem")
426 library.rows.append({"predicate": predicate, "library": matchingLib})
427 elif d["LibraryType"] == "FreeSize":
428 predicate = Properties.Predicate(tag="FreeSizeMatching")
429
430 freesizeLib = FreeSizeLibrary.FromOriginalState(d["Library"], solutions)
431 library = PredicateLibrary(tag="Problem")
432 library.rows.append({"predicate": predicate, "library": freesizeLib})
433 elif d["LibraryType"] == "Prediction":
434 predicate = Properties.Predicate(tag="FreeSizeMatching") # TODO Do we need a new predicate here?
435
436 predictionLib = PredictionLibrary.FromOriginalState(d["Library"], solutions)
437 library = PredicateLibrary(tag="Problem")
438 library.rows.append({"predicate": predicate, "library": predictionLib})
439 elif d["LibraryType"] == "MLPClassification":
440 predicate = Properties.Predicate(tag="TruePred")
441
442 regressionLib = MLPClassificationLibrary.FromOriginalState(d["Library"], solutions)
443 library = PredicateLibrary(tag="Problem")
444 library.rows.append({"predicate": predicate, "library": regressionLib})
445 else:
446 assert 0 and "Unrecognized LibraryType."
447
448 if lazyLibraryLoading:
449 placeholderName += '_' + str(problemType.aType) + str(problemType.bType)
450 placeholderName += '_' + str(problemType.cType) + str(problemType.computeInputType)
451 if problemType.activationType != 'none':
452 if str(problemType.activationType).upper() == 'ALL':
453 placeholderName += "_A"
454 elif str(problemType.activationType).upper() == 'HIPBLASLT_ALL':
455 placeholderName += "_HA"
456 else:
457 placeholderName += "_%s"%str(problemType.activationType).upper()
458
459 if problemType.swizzleTensorA:
460 placeholderName += '_STA'
461
462 if problemType.swizzleTensorB:
463 placeholderName += '_STB'
464
465 if problemType.useBias:
466 placeholderName += '_Bias'
467 if problemType.useE:
468 placeholderName += '_Grad' if problemType.useGradient else '_Aux'
469 if problemType.groupedGemm:
470 placeholderName += "_GG"
471 else:
472 placeholderName += "" if problemType.stridedBatched else "_GB" # legacy
473 if problemType.useScaleAB == "Scalar":
474 placeholderName += '_SAB'
475 elif problemType.useScaleAB == "Vector":
476 placeholderName += '_SABV'
477 if problemType.useScaleCD:
478 placeholderName += '_SCD'
479 if problemType.useScaleAlphaVec:
480 placeholderName += '_SAV'
481 if problemType.sparse:
482 placeholderName += '_SPB' if problemType.sparse == 2 else '_SPA'
483 if not problemType.f32XdlMathOp.isSingle() and problemType.computeInputType.isSingle():
484 placeholderName += '_M' + str(problemType.f32XdlMathOp)
485 if problemType.supportDeviceUserArguments:
486 placeholderName += '_UA'
487
488 return library, placeholderName
489
490 # end library creation functions
491
492 if libraryOrder is None:
493 if lazyLibraryLoading:
494 libraryOrder = [
495 hardware, operationIdentifier, performanceMetric, predicates,
496 placeholder, selection
497 ]
498 else:
499 libraryOrder = [
500 hardware, operationIdentifier, performanceMetric, predicates,
501 selection
502 ]
503 #assert libraryOrder[-1] == selection
504
505 lazyLibrary = None
506 if placeholder in libraryOrder:
507 placeholderIndex = libraryOrder.index(placeholder) + 1
508 lazyLibrary, placeholderName = \
509 MasterSolutionLibrary.FromOriginalState(origData,
510 origSolutions,
511 splitGSU,
512 printSolutionRejectionReason,
513 printIndexAssignmentInfo,
514 assembler,
515 isaInfoMap,
516 lazyLibraryLoading,
517 solutionClass,
518 libraryOrder[placeholderIndex:],
519 placeholderName)
520 libraryOrder = libraryOrder[0:placeholderIndex]
521 origSolutions = []
522
523 problemType = Contractions.ProblemType.FromOriginalState(origData["ProblemType"])
524 allSolutions = [solutionClass.FromSolutionStruct(
525 s,
526 splitGSU,
527 printSolutionRejectionReason,
528 printIndexAssignmentInfo,
529 assembler,
530 isaInfoMap
531 ) for s in origSolutions]
532 cls.FixSolutionIndices(allSolutions)
533
534 # library is constructed in reverse order i.e. bottom-up
535 library = None
536 placeholderLibrary = None
537 for libName in reversed(libraryOrder):
538 library, placeholderName = libName(origData, problemType, allSolutions, library,
539 placeholderName)
540 if libName == placeholder:
541 placeholderLibrary = library
542
543 solutions = {s.index: s for s in allSolutions}
544 rv = cls(solutions, library)
545 if lazyLibrary and placeholderLibrary:
546 rv.lazyLibraries[placeholderName] = lazyLibrary
547 placeholderLibrary.filenamePrefix = placeholderName
548
549 return rv, placeholderName
550
551 @classmethod
552 def BenchmarkingLibrary(
553 cls,
554 solutions,
555 assembler,
556 splitGSU: bool,
557 printSolutionRejectionReason: bool,
558 printIndexAssignmentInfo: bool,
559 isaInfoMap
560 ):
561 solutionObjs = list([Contractions.Solution.FromOriginalState(
562 s._state,
563 splitGSU,
564 printSolutionRejectionReason,
565 printIndexAssignmentInfo,
566 assembler,
567 isaInfoMap)
568 for s in solutions])
569 cls.FixSolutionIndices(solutionObjs)
570
571 predRows = list([{
572 "predicate": s.problemPredicate,
573 "library": SingleSolutionLibrary(s)
574 } for s in solutionObjs])
575 library = PredicateLibrary(tag="Problem", rows=predRows)
576
577 solutionMap = {s.index: s for s in solutionObjs}
578
579 return cls(solutionMap, library)
580
581 def __init__(self, solutions, library, version=None):
582 self.lazyLibraries = {}
583 self.solutions = solutions
584 self.library = library
585 self.version = version
586
587 def state(self):
588 rv = {
589 "solutions": state(self.solutions.values()),
590 "library": state(self.library)
591 }
592
593 if self.version is not None:
594 rv["version"] = self.version
595 return rv
596
597 def applyNaming(self, splitGSU: bool):
598 for s in list(self.solutions.values()):
599 s.name = getSolutionNameMin(s.originalSolution.getKernels()[0], splitGSU)
600 s.kernelName = getKernelNameMin(s.originalSolution.getKernels()[0], splitGSU)
601
602 def remapSolutionIndicesStartingFrom(self, curIndex):
603 reIndexMap = {}
604 solutionCopy = self.solutions
605 self.solutions = dict()
606 for k, s in solutionCopy.items():
607 reIndexMap[s.index] = curIndex
608 s.index = curIndex
609 self.solutions[curIndex] = s
610 curIndex += 1
611
612 self.library.remapSolutionIndices(reIndexMap)
613
614 def merge(self, other, startIndex=0):
615 assert self.__class__ == other.__class__
616
617 curIndex = max(startIndex, max(self.solutions.keys()) + 1 if self.solutions else 0)
618 if self.lazyLibraries:
619 curIndex = max(
620 curIndex,
621 max(max(lib.solutions.keys()) for _, lib in self.lazyLibraries.items()) + 1)
622
623 #Merge separate library files
624 for name, lib in other.lazyLibraries.items():
625 if name in self.lazyLibraries.keys():
626 curIndex = self.lazyLibraries[name].merge(lib, curIndex)
627 else:
628 reIndexMap = {}
629 newSolutions = {}
630
631 for k, s in lib.solutions.items():
632 reIndexMap[s.index] = curIndex
633 s.index = curIndex
634 newSolutions[curIndex] = s
635 curIndex += 1
636
637 lib.solutions = newSolutions
638 lib.library.remapSolutionIndices(reIndexMap)
639
640 self.lazyLibraries[name] = lib
641
642 reIndexMap = {}
643 for k, s in other.solutions.items():
644 reIndexMap[s.index] = curIndex
645 s.index = curIndex
646 self.solutions[curIndex] = s
647 curIndex += 1
648
649 other.library.remapSolutionIndices(reIndexMap)
650
651 self.library.merge(other.library)
652
653 return curIndex #Next unused index
654
655 @property
656 def cpp_base_class(self):
657 return "SolutionLibrary<ContractionProblemGemm, ContractionSolution>"
658
659 @property
660 def cpp_class(self):
661 return "MasterSolutionLibrary<ContractionProblemGemm, ContractionSolution>"