Debian Codegraph @

tensilelite/Tensile/Utilities/merge.py

raw symbols SCIP
1 ################################################################################
2 #
3 # Copyright (C) 2022-2025 Advanced Micro Devices, Inc. All rights reserved.
4 #
5 # Permission is hereby granted, free of charge, to any person obtaining a copy
6 # of this software and associated documentation files (the "Software"), to deal
7 # in the Software without restriction, including without limitation the rights
8 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 # copies of the Software, and to permit persons to whom the Software is
10 # furnished to do so, subject to the following conditions:
11 #
12 # The above copyright notice and this permission notice shall be included in
13 # all copies or substantial portions of the Software.
14 #
15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 # SOFTWARE.
22 #
23 ################################################################################
24
25 import yaml
26 import os
27 import sys
28 import shutil
29 import argparse
30 from copy import deepcopy
31 from enum import IntEnum
32
33 verbosity = 1
34
35 def ensurePath(path):
36 if not os.path.exists(path):
37 os.makedirs(path)
38 return path
39
40 def allFiles(startDir):
41 current = os.listdir(startDir)
42 files = []
43 for filename in [_current for _current in current if os.path.splitext(_current)[-1].lower() == '.yaml']:
44 fullPath = os.path.join(startDir,filename)
45 if os.path.isdir(fullPath):
46 files = files + allFiles(fullPath)
47 else:
48 files.append(fullPath)
49 return files
50
51 def reindexSolutions(data):
52 for i, _ in enumerate(data[5]):
53 data[5][i]["SolutionIndex"] = i
54 return data
55
56 def fixSizeInconsistencies(sizes, fileType):
57 duplicates = list()
58 for i in range(0,len(sizes)):
59 currSize = sizes[i][0]
60 # >= so size will be trimmed when a SolutionTag is included
61 if len(currSize) >= 8:
62 currSize = currSize[:-4]
63 if currSize in (item for index in sizes for item in index):
64 duplicates.append(i-len(duplicates))
65 else:
66 sizes[i][0] = currSize
67 sizes_ = deepcopy(sizes)
68 if len(duplicates) > 0:
69 for i in duplicates:
70 sizes_.pop(i)
71 verbose(len(duplicates), "duplicate size(s) removed from", fileType, "logic file")
72 return sizes_, len(sizes_)
73
74 # remove dict keys "SolutionIndex" and "SolutionNameMin" from dict
75 def cmpHelper(sol):
76 return {k:v for k, v in sol.items() if k!="SolutionIndex" and k!="SolutionNameMin"}
77
78 def addKernel(solutionPool, solution):
79 for item in solutionPool:
80 if cmpHelper(item) == cmpHelper(solution):
81 index = item["SolutionIndex"]
82 debug("...Reuse previously existed kernel", end="")
83 break
84 else:
85 index = len(solutionPool)
86 _solution = deepcopy(solution) # if we don't we will see some subtle errors
87 _solution["SolutionIndex"] = index
88 solutionPool.append(_solution)
89 debug("...A new kernel has been added", end="")
90 debug("({}) {}".format(index, solutionPool[index]["SolutionNameMin"] if "SolutionNameMin" in solutionPool[index] else "(SolutionName N/A)"))
91 return solutionPool, index
92
93 # update dependant parameters if StaggerU == 0
94 def sanitizeSolutions(solList):
95 for sol in solList:
96 if "ProblemType" in sol:
97 del sol["ProblemType"] # remove ProblemType from solution
98 if sol.get("StaggerU") == 0:
99 sol["StaggerUMapping"] = 0
100 sol["StaggerUStride"] = 0
101 sol["_staggerStrideShift"] = 0
102
103 def removeUnusedKernels(oriData, prefix=""):
104 origNumSolutions = len(oriData[5])
105
106 kernelsInUse = [ index for _, [index, _] in oriData[7] ]
107 for i, solution in enumerate(oriData[5]):
108 solutionIndex = solution["SolutionIndex"]
109 oriData[5][i]["__InUse__"] = True if solutionIndex in kernelsInUse else False
110
111 # debug prints
112 for o in [o for o in oriData[5] if o["__InUse__"]==False]:
113 debug("{}Solution ({}) {} is unused".format(
114 prefix,
115 o["SolutionIndex"],
116 o["SolutionNameMin"] if "SolutionNameMin" in o else "(SolutionName N/A)"))
117
118 # filter out dangling kernels
119 oriData[5] = [ {k: v for k, v in o.items() if k != "__InUse__"}
120 for o in oriData[5] if o["__InUse__"]==True ]
121
122 # reindex solutions
123 idMap = {} # new = idMap[old]
124 for i, solution in enumerate(oriData[5]):
125 idMap[solution["SolutionIndex"]] = i
126 oriData[5][i]["SolutionIndex"] = i
127 for i, [size, [oldSolIndex, eff]] in enumerate(oriData[7]):
128 oriData[7][i] = [size, [idMap[oldSolIndex], eff]]
129
130 numInvalidRemoved = origNumSolutions - len(oriData[5])
131 return oriData, numInvalidRemoved
132
133 def loadData(filename):
134 try:
135 stream = open(filename, "r")
136 except IOError:
137 print("Cannot open file: ", filename)
138 sys.stdout.flush()
139 sys.exit(-1)
140 data = yaml.load(stream, yaml.SafeLoader)
141 return data
142
143 def compareDestFolderToYaml(originalDir, incFile, incData):
144 checkFolders = ["Equality", "GridBased"]
145 # Parsing destination folder and yaml attribute
146 destFolder = originalDir.rstrip('/').split('/')[-1]
147 incAttribute = incData[11] # the last item in yaml file
148 if not incAttribute:
149 sys.exit(f"[Error] Empty YAML attribute. Need to set Equality or GridBased in {incFile}.")
150 # Check Equality and GradBased folders only
151 if destFolder in checkFolders and destFolder != incAttribute:
152 restuls = f"\t{incFile} must be {destFolder} tuning"
153 sys.exit(f"[Error] Destination folder(={destFolder}) failed to match YAML attribute(={incAttribute}): \n{restuls}")
154
155 def compareProblemType(oriData, incData):
156 # ProblemType defined in originalFiles and incrementalFiles
157 oriProblemType = oriData[4] # header
158 incProblemType = incData[4] # header
159 # Delete waived ProblemType items in originalFiles
160 waivedItems = [item for item in oriProblemType if item not in incProblemType]
161 if waivedItems:
162 # Header ProblemType
163 for item in waivedItems:
164 oriProblemType.pop(item)
165 # Kernel ProblemType
166 for i, _ in enumerate(oriData[5]):
167 # TODO: delete this for loop if kernel ProblemType is removed in the future
168 if "ProblemType" not in oriData[5][i]:
169 continue
170 oriKernelProblemType = oriData[5][i]["ProblemType"]
171 for item in waivedItems:
172 try:
173 oriKernelProblemType.pop(item)
174 except KeyError:
175 oriSolutionIndex = oriData[5][i]["SolutionIndex"]
176 print(f"[Warning] Popping '{item}' failed in oriData(idx={oriSolutionIndex})")
177
178 results = ""
179 solIdx = 0
180 # Compare existing ProblemType items of originalFiles with incrementalFiles
181 for i, _ in enumerate(incData[5]):
182 if "ProblemType" not in incData[5][i]:
183 continue
184 # TODO: check header ProblemType if kernel ProblemType is removed in the future
185 incKernelProblemType = incData[5][i]["ProblemType"]
186 if oriProblemType != incKernelProblemType:
187 for item in oriProblemType:
188 if oriProblemType[item] != incKernelProblemType[item]:
189 results += f"\t{item}: {oriProblemType[item]} != {incKernelProblemType[item]}\n"
190 solIdx = i
191 break
192 if (results):
193 sys.exit(f"[Error] ProblemType in library logic doesn't match solution(idx={solIdx}): \n{results}")
194
195 # this is for complying the behavior of legacy merge script, where incremental logic
196 # file always replaces the base logic file even it's slower in performance -
197 # in the future we may let default force merge policy = False
198 def defaultForceMergePolicy(incFile):
199 if "arcturus" in incFile:
200 forceMerge = False
201 else:
202 forceMerge = True
203
204 return forceMerge
205
206 def msg(*args, **kwargs):
207 for i in args: print(i, end=" ")
208 print(**kwargs)
209
210 def verbose(*args, **kwargs):
211 if verbosity < 1: return
212 msg(*args, **kwargs)
213
214 def debug(*args, **kwargs):
215 if verbosity < 2: return
216 msg(*args, **kwargs)
217
218 # Tags distinguishing solution types
219 # Can be added to size key to allow solutions of each type to be present
220 # in logic file for a given size
221 class MfmaTag(IntEnum):
222 VALU = 0
223 MFMA = 1
224
225 def __str__(self):
226 return ["VALU", "MFMA"][self]
227 def __repr__(self):
228 return str(self)
229
230 class AlphaValueTag(IntEnum):
231 ANY = 0
232 ONE = 1
233 NEG_ONE = 2
234 ZERO = 3
235
236 def __str__(self):
237 return "Alpha="+["Any", "1", "-1", "0"][self]
238 def __repr__(self):
239 return str(self)
240
241 class BetaValueTag(IntEnum):
242 ANY = 0
243 ONE = 1
244 NEG_ONE = 2
245 ZERO = 3
246
247 def __str__(self):
248 return "Beta="+["Any", "1", "-1", "0"][self]
249 def __repr__(self):
250 return str(self)
251
252 def strToScalarValueTag(Class, value):
253 if value == "Any":
254 return Class.ANY
255 if value == 1:
256 return Class.ONE
257 if value == -1:
258 return Class.NEG_ONE
259 if value == 0:
260 return Class.ZERO
261 else:
262 raise RuntimeError("Unsupported value for Alpha/Beta scalar value")
263
264 class CEqualsDTag(IntEnum):
265 C_EQ_D = 0
266 C_NEQ_D = 1
267
268 def __str__(self):
269 return ["C=D", "C!=D"][self]
270 def __repr__(self):
271 return str(self)
272
273 # Tag of form (MFMATag, AlphaValueTag, BetaValueTag, CEqualsDTag)
274 def getSolutionTag(solution):
275 tagTuple = ()
276 if solution.get("EnableMatrixInstruction", False) or solution.get("MatrixInstruction", False):
277 tagTuple = tagTuple + (MfmaTag.MFMA,)
278 else:
279 tagTuple = tagTuple + (MfmaTag.VALU,)
280
281 return tagTuple
282
283 def findSolutionWithIndex(solutionData, solIndex):
284 # Check solution at the index corresponding to solIndex first
285 if solIndex < len(solutionData) and solutionData[solIndex]["SolutionIndex"] == solIndex:
286 return solutionData[solIndex]
287 else:
288 debug("Searching for index...")
289 solution = [s for s in solutionData if s["SolutionIndex"]==solIndex]
290 assert(len(solution) == 1)
291 return solution[0]
292
293 def addSolutionTagToKeys(solutionMap, solutionPool):
294 return [[[getSolutionTag(findSolutionWithIndex(solutionPool, idx))] + keys, [idx, eff]]
295 for [keys, [idx, eff]] in solutionMap]
296
297 def removeSolutionTagFromKeys(solutionMap):
298 return [[keys[1:], [idx, incEff]] for keys, [idx, incEff] in solutionMap]
299
300 # To be used with add_solution_tags to allow faster general solutions to supercede slower specific ones
301 def findFastestCompatibleSolution(origDict, sizeMapping):
302 tags = sizeMapping[0]
303 # Tag of form (MFMATag, AlphaValueTag, BetaValueTag, CEqualsDTag)
304 compatibleTagList = [tags]
305
306 # Add all compatible tags to the list
307 if tags[1] != AlphaValueTag.ANY:
308 compatibleTagList = compatibleTagList + [(t[0], AlphaValueTag.ANY) + t[2:] for t in compatibleTagList]
309 if tags[2] != BetaValueTag.ANY:
310 compatibleTagList = compatibleTagList + [t[:2] + (BetaValueTag.ANY,) + t[3:] for t in compatibleTagList]
311 if tags[3] != CEqualsDTag.C_NEQ_D:
312 compatibleTagList = compatibleTagList + [t[:3] + (CEqualsDTag.C_NEQ_D,) + t[4:] for t in compatibleTagList]
313
314 #Find the fastest efficiency of all compatible tags
315 maxEfficiency = 0
316 for tag in compatibleTagList:
317 result = origDict.get((tag,) + sizeMapping[1:], None)
318 if result:
319 _, eff = origDict[(tag,) + sizeMapping[1:]]
320 maxEfficiency = max(maxEfficiency, eff)
321
322 return maxEfficiency
323
324
325 # returns merged logic data as list
326 def mergeLogic(oriData, incData, forceMerge, trimSize=True, addSolutionTags=False, noEff=False):
327 origNumSizes = len(oriData[7])
328 origNumSolutions = len(oriData[5])
329
330 incData[7] = incData[7] or []
331 incNumSizes = len(incData[7])
332 incNumSolutions = len(incData[5])
333
334 verbose(origNumSizes, "sizes and", origNumSolutions, "kernels in base logic file")
335 verbose(incNumSizes, "sizes and", incNumSolutions, "kernels in incremental logic file")
336
337 # Add SolutionTag to distinguish solutions with different requirements
338 origTaggedSizes = addSolutionTagToKeys(oriData[7], oriData[5])
339 incTaggedSizes = addSolutionTagToKeys(incData[7], incData[5])
340 if addSolutionTags:
341 oriData[7] = origTaggedSizes
342 incData[7] = incTaggedSizes
343 # Print warning if addSolutionTags=False results in removed sizes
344 else:
345 origSet = {tuple(size) for size, [_, _] in oriData[7]}
346 origTaggedSet = {tuple(size) for size, [_, _] in origTaggedSizes}
347 incSet = {tuple(size) for size, [_, _] in incData[7]}
348 incTaggedSet = {tuple(size) for size, [_, _] in incTaggedSizes}
349
350 if len(origSet) != len(origTaggedSet):
351 verbose("Warning:", len(origTaggedSet) - len(origSet), "duplicate sizes are present in base logic",
352 "that may not be handled correctly unless --add_solution_tags is used")
353 if len(incSet) != len(incTaggedSet):
354 verbose("Warning:", len(incTaggedSet) - len(incSet), "duplicate sizes are present in incremental logic",
355 "that may not be handled correctly unless --add_solution_tags is used")
356
357
358
359 if trimSize:
360 # trim 8-tuple gemm size format to 4-tuple [m, n, b, k]
361 # TODO future gemm size could include dictionary format so need robust preprocessing
362 [oriData[7], origNumSizes] = fixSizeInconsistencies(oriData[7], "base")
363 [incData[7], incNumSizes] = fixSizeInconsistencies(incData[7], "incremental")
364
365 sanitizeSolutions(oriData[5])
366 sanitizeSolutions(incData[5])
367 oriData, numOrigRemoved = removeUnusedKernels(oriData, "Base logic file: ")
368 incData, numIncRemoved = removeUnusedKernels(incData, "Inc logic file: ")
369
370 solutionPool = deepcopy(oriData[5])
371 solutionMap = deepcopy(oriData[7])
372
373 origDict = {tuple(origSize): [i, origEff] for i, [origSize, [origIndex, origEff]] in enumerate(oriData[7])}
374 for incSize, [incIndex, incEff] in incData[7]:
375 incSolution = findSolutionWithIndex(incData[5], incIndex)
376
377 storeEff = incEff if noEff == False else 0.0
378 try:
379 j, origEff = origDict[tuple(incSize)]
380 if incEff > origEff or forceMerge:
381 if incEff > origEff:
382 verbose("[O]", incSize, "already exists and has improved in performance.", end="")
383 elif forceMerge:
384 verbose("[!]", incSize, "already exists but does not improve in performance.", end="")
385 verbose("Efficiency:", origEff, "->", incEff, "(force_merge=True)" if forceMerge else "")
386 solutionPool, index = addKernel(solutionPool, incSolution)
387 solutionMap[j][1] = [index, storeEff]
388 else:
389 verbose("[X]", incSize, "already exists but does not improve in performance.", end="")
390 verbose("Efficiency:", origEff, "->", incEff)
391 except KeyError:
392 if addSolutionTags and findFastestCompatibleSolution(origDict, tuple(incSize)) > incEff:
393 verbose("[X]", incSize, "has been rejected because a compatible solution already exists with higher performance")
394 else:
395 verbose("[-]", incSize, "has been added to solution table, Efficiency: N/A ->", incEff)
396 solutionPool, index = addKernel(solutionPool, incSolution)
397 solutionMap.append([incSize,[index, storeEff]])
398
399 verbose(numOrigRemoved, "unused kernels removed from base logic file")
400 verbose(numIncRemoved, "unused kernels removed from incremental logic file")
401
402 # Remove SolutionTag for yaml output
403 if addSolutionTags:
404 solutionMap = removeSolutionTagFromKeys(solutionMap)
405
406 mergedData = deepcopy(oriData)
407 mergedData[5] = solutionPool
408 mergedData[7] = solutionMap
409 mergedData, numReplaced = removeUnusedKernels(mergedData, "Merged data: ")
410
411 numSizesAdded = len(solutionMap)-len(oriData[7])
412 numSolutionsAdded = len(solutionPool)-len(oriData[5])
413 numSolutionsRemoved = numReplaced+numOrigRemoved # incremental file not counted
414
415 return [mergedData, numSizesAdded, numSolutionsAdded, numSolutionsRemoved]
416
417 def avoidRegressions(originalDir, incrementalDir, outputPath, forceMerge, trimSize=True, addSolutionTags=False, noEff=False):
418 originalFiles = allFiles(originalDir)
419 incrementalFiles = allFiles(incrementalDir)
420 ensurePath(outputPath)
421
422 incrementalFilesTemp = []
423 originalFileNames = [os.path.split(o)[-1] for o in originalFiles]
424 for file in incrementalFiles:
425 if os.path.split(file)[-1] in originalFileNames:
426 incrementalFilesTemp.append(file)
427 else:
428 outputFile = os.path.join(outputPath, os.path.split(file)[-1])
429 shutil.copyfile(file, outputFile)
430 msg("Copied", file, "to", outputFile)
431
432 incrementalFiles = incrementalFilesTemp
433
434 for incFile in incrementalFiles:
435 basename = os.path.split(incFile)[-1]
436 origFile = os.path.join(originalDir, basename)
437 forceMerge = defaultForceMergePolicy(incFile) if forceMerge is None else forceMerge
438
439 msg("Base logic file:", origFile, "| Incremental:", incFile, "| Merge policy: %s"%("Forced" if forceMerge else "Winner"), "| Trim size:", trimSize,
440 "| Add solution tags:", addSolutionTags)
441 oriData = loadData(origFile)
442 incData = loadData(incFile)
443
444 # Terminate when the destination folder doesn't match Incremental logic yaml
445 # For example, merge Gridbased yaml to Equality folder or Equality yaml to GridBased folder
446 compareDestFolderToYaml(originalDir, incFile, incData)
447
448 # Terminate when ProblemType of originalFiles and incrementalFiles mismatch
449 compareProblemType(oriData, incData)
450
451 # So far "SolutionIndex" in logic yamls has zero impact on actual 1-1 size mapping (but the order of the Solution does)
452 # since mergeLogic() takes that value very seriously so we reindex them here so it doesn't choke on duplicated SolutionIndex
453 oriData = reindexSolutions(oriData)
454 incData = reindexSolutions(incData)
455
456 mergedData, *stats = mergeLogic(oriData, incData, forceMerge, trimSize, addSolutionTags, noEff)
457 msg(stats[0], "size(s) and", stats[1], "kernel(s) added,", stats[2], "kernel(s) removed")
458
459 with open(os.path.join(outputPath, basename), "w") as outFile:
460 yaml.safe_dump(mergedData,outFile,default_flow_style=None)
461 msg("File written to", os.path.join(outputPath, basename))
462 msg("------------------------------")
463
464 # partialLogicFilePaths: list of full paths to partial logic files
465 # outputDir: Directory to write the final result to
466 # forceMerge:
467 # trimSize:
468 # Expects: that all the partial logic files
469 # have the same base name, but are located
470 # in different folders.
471 # Provides: one final logic file that is the
472 # merged result of all partial files.
473 # This is useful for when a tuning task is
474 # shared between multiple machines who each
475 # will provide a partial result.
476 def mergePartialLogics(partialLogicFilePaths, outputDir, forceMerge, trimSize=True, addSolutionTags=False):
477 logicFiles = deepcopy(partialLogicFilePaths)
478 ensurePath(outputDir)
479
480 baseLogicFile = logicFiles.pop(0)
481 baseLogicData = loadData(baseLogicFile)
482 msg("Base logic file:", baseLogicFile)
483 for f in logicFiles:
484 forceMerge = defaultForceMergePolicy(f) if forceMerge is None else forceMerge
485
486 msg("Incremental file:", f, "| Merge policy: %s"%("Forced" if forceMerge else "Winner"), "| Trim size:", trimSize)
487 incLogicData = loadData(f)
488
489 # So far "SolutionIndex" in logic yamls has zero impact on actual 1-1 size mapping (but the order of the Solution does)
490 # since mergeLogic() takes that value very seriously so we reindex them here so it doesn't choke on duplicated SolutionIndex
491 baseLogicData = reindexSolutions(baseLogicData)
492 incLogicData = reindexSolutions(incLogicData)
493
494 mergedData, *stats = mergeLogic(baseLogicData, incLogicData, forceMerge, trimSize, addSolutionTags)
495 msg(stats[0], "size(s) and", stats[1], "kernel(s) added,", stats[2], "kernel(s) removed")
496
497 # Use the merged data as the base data for the next partial logic file
498 baseLogicData = deepcopy(mergedData)
499
500
501 baseFileName = os.path.basename(baseLogicFile)
502 outputFilePath = os.path.join(outputDir, baseFileName)
503 with open(outputFilePath, "w") as outFile:
504 yaml.safe_dump(baseLogicData, outFile, default_flow_style=None)
505 msg("File written to", outputFilePath)
506 msg("------------------------------")
507
508 if __name__ == "__main__":
509 argParser = argparse.ArgumentParser()
510 argParser.add_argument("original_dir", help="The library logic directory without tuned sizes")
511 argParser.add_argument("incremental_dir", help="The incremental logic directory")
512 argParser.add_argument("output_dir", help="The output logic directory")
513 argParser.add_argument("-v", "--verbosity", help="0: summary, 1: verbose, 2: debug", default=1, type=int)
514 argParser.add_argument("--force_merge", help="Merge previously known sizes unconditionally. Default behavior if not arcturus", default="none")
515 argParser.add_argument("--notrim", help="Do not trim long size format down to short format (m,n,b,k). Default is --trim", action="store_false")
516 argParser.add_argument("--add_solution_tags", help="Add tags to the size key for solution properies, allowing for solutions with different requirements "
517 "to exist for the same size. Default doesn't add this tag.", action="store_true")
518 argParser.add_argument("--no_eff", help="force set eff as 0.0.", action="store_true")
519
520 args = argParser.parse_args(sys.argv[1:])
521 originalDir = args.original_dir
522 incrementalDir = args.incremental_dir
523 outputPath = args.output_dir
524 verbosity = args.verbosity
525 forceMerge = args.force_merge.lower()
526 trimSize = args.notrim
527 add_solution_tags = args.add_solution_tags
528 no_eff = args.no_eff
529
530 if forceMerge in ["none"]: forceMerge=None
531 elif forceMerge in ["true", "1"]: forceMerge=True
532 elif forceMerge in ["false", "0"]: forceMerge=False
533
534 msg("***************************************************************")
535 msg("Warning: merge.py is deprecated, please use TensileMergeLibrary")
536 msg("***************************************************************")
537 avoidRegressions(originalDir, incrementalDir, outputPath, forceMerge, trimSize, add_solution_tags, no_eff)