Debian Codegraph @

tensilelite/Tensile/TensileMergeLibrary.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
32 from Tensile import __version__
33 from Tensile.SolutionStructs.Naming import getSolutionNameMin
34 from Tensile.SolutionStructs.Naming import getKernelNameMin
35 from Tensile.SolutionStructs.Problem import ProblemType, problemTypeToEnum
36 from Tensile.Common import ParallelMap2
37
38 verbosity = 1
39
40 def ensurePath(path):
41 if not os.path.exists(path):
42 os.makedirs(path)
43 return path
44
45 def allFiles(startDir):
46 current = os.listdir(startDir)
47 files = []
48 for filename in [_current for _current in current if os.path.splitext(_current)[-1].lower() == '.yaml']:
49 fullPath = os.path.join(startDir,filename)
50 if os.path.isdir(fullPath):
51 files = files + allFiles(fullPath)
52 else:
53 files.append(fullPath)
54 return files
55
56 def fixSizeInconsistencies(sizes, fileType):
57 origNumSizes = len(sizes)
58 sizesDict = dict()
59 for size, index in sizes:
60 size = size[:-4] if len(size) >= 8 else size
61 sizesDict[(value for value in size)] = [size, index]
62 newSizes = list()
63 for value in sizesDict.values():
64 newSizes.append(value)
65 numSize = len(newSizes)
66 if numSize - origNumSizes > 0:
67 verbose(numSize - origNumSizes, "duplicate size(s) removed from", fileType, "logic file")
68 return newSizes, len(newSizes)
69
70 def addKernel(solutionPool, solDict, solution):
71 if solution["SolutionNameMin"] in solDict:
72 index = solDict[solution["SolutionNameMin"]]["SolutionIndex"]
73 debug("...Reuse previously existed solution", end="")
74 else:
75 index = len(solutionPool)
76 _solution = deepcopy(solution) # if we don't we will see some subtle errors
77 _solution["SolutionIndex"] = index
78 solutionPool.append(_solution)
79 solDict[solution["SolutionNameMin"]] = _solution
80 debug("...A new solution has been added", end="")
81 debug("({}) {}".format(index, solutionPool[index]["SolutionNameMin"] if "SolutionNameMin" in solutionPool[index] else "(SolutionName N/A)"))
82 return solutionPool, solDict, index
83
84 # update dependant parameters if StaggerU == 0
85 def sanitizeSolutions(solList):
86 for sol in solList:
87 if sol.get("StaggerU") == 0:
88 sol["StaggerUMapping"] = 0
89 sol["StaggerUStride"] = 0
90 sol["_staggerStrideShift"] = 0
91
92 from Tensile.Common.GlobalParameters import defaultSolution, defaultInternalSupportParams
93 from Tensile.Common import assignParameterWithDefault
94
95 def reNameSolutions(data):
96 solList = data[5]
97 for sol in solList:
98 # Assign solution state from config, filling missing from the defaultSolution
99 for key in defaultSolution:
100 assignParameterWithDefault(sol, key, sol, defaultSolution)
101 sol["ProblemType"] = data[4]
102 sol["SolutionNameMin"] = getSolutionNameMin(sol,splitGSU=False)
103 sol["KernelNameMin"] = getKernelNameMin(sol,splitGSU=False)
104 del sol["ProblemType"]
105
106 def removeUnusedSolutions(oriData, prefix=""):
107 origNumSolutions = len(oriData[5])
108
109 kernelsInUse = [ index for _, [index, _] in oriData[7] ]
110 for i, solution in enumerate(oriData[5]):
111 solutionIndex = solution["SolutionIndex"]
112 oriData[5][i]["__InUse__"] = True if solutionIndex in kernelsInUse else False
113
114 # debug prints
115 for o in [o for o in oriData[5] if o["__InUse__"]==False]:
116 debug("{}Solution ({}) {} is unused".format(
117 prefix,
118 o["SolutionIndex"],
119 o["SolutionNameMin"] if "SolutionNameMin" in o else "(SolutionName N/A)"))
120
121 # filter out dangling kernels
122 oriData[5] = [ {k: v for k, v in o.items() if k != "__InUse__"}
123 for o in oriData[5] if o["__InUse__"]==True ]
124
125 # reindex solutions
126 idMap = {} # new = idMap[old]
127 for i, solution in enumerate(oriData[5]):
128 idMap[solution["SolutionIndex"]] = i
129 oriData[5][i]["SolutionIndex"] = i
130 for i, [size, [oldSolIndex, eff]] in enumerate(oriData[7]):
131 oriData[7][i] = [size, [idMap[oldSolIndex], eff]]
132
133 numInvalidRemoved = origNumSolutions - len(oriData[5])
134 return oriData, numInvalidRemoved
135
136 def removeDuplicatedSolutions(oriData, prefix=""):
137 origNumSolutions = len(oriData[5])
138
139 solutionsName = {}
140 solutions = []
141 kernelsName = {}
142
143 for solution in oriData[5]:
144 if solution["SolutionNameMin"] not in solutionsName:
145 solutionsName[solution["SolutionNameMin"]] = len(solutionsName)
146 solutions.append(solution)
147 if solution["KernelNameMin"] not in kernelsName:
148 kernelsName[solution["KernelNameMin"]] = len(kernelsName)
149
150 for i, solution in enumerate(solutions):
151 solution["SolutionIndex"] = i
152
153 for data in oriData[7]:
154 index = data[1][0]
155 data[1][0] = solutionsName[oriData[5][index]["SolutionNameMin"]]
156
157 oriData[5] = solutions
158 numRemoved = origNumSolutions - len(solutions)
159 return oriData, numRemoved, len(solutions), len(kernelsName)
160
161 from .CustomYamlLoader import load_yaml_stream
162
163 def loadData(filename):
164 data = load_yaml_stream(filename, yaml.CSafeLoader)
165 return [filename, data]
166
167 def compareDestFolderToYaml(originalDir, incFile, incData):
168 checkFolders = ["Equality", "GridBased"]
169 # Parsing destination folder and yaml attribute
170 destFolder = originalDir.rstrip('/').split('/')[-1]
171 incAttribute = incData[11] # the last item in yaml file
172 if not incAttribute:
173 sys.exit(f"[Error] Empty YAML attribute. Need to set Equality or GridBased in {incFile}.")
174 # Check Equality and GradBased folders only
175 if destFolder in checkFolders and destFolder != incAttribute:
176 restuls = f"\t{incFile} must be {destFolder} tuning"
177 sys.exit(f"[Error] Destination folder(={destFolder}) failed to match YAML attribute(={incAttribute}): \n{restuls}")
178
179 def compareProblemType(oriData, incData):
180 # ProblemType defined in originalFiles
181 oriData[4] = ProblemType(oriData[4],False)
182 problemTypeToEnum(oriData[4])
183 oriData[4] = oriData[4].state
184 oriProblemType = oriData[4]
185
186 incData[4] = ProblemType(incData[4],False)
187 problemTypeToEnum(incData[4])
188 incData[4] = incData[4].state
189 incProblemType = incData[4]
190
191 results = ""
192 if oriProblemType != incProblemType:
193 for item in oriProblemType:
194 if oriProblemType[item] != incProblemType[item]:
195 results += f"\t{item}: {oriProblemType[item]} != {incProblemType[item]}\n"
196 if (results):
197 sys.exit(f"[Error] ProblemType in library logic doesn't match: \n{results}")
198
199 def msg(*args, **kwargs):
200 for i in args: print(i, end=" ")
201 print(**kwargs)
202
203 def verbose(*args, **kwargs):
204 if verbosity < 1: return
205 msg(*args, **kwargs)
206
207 def debug(*args, **kwargs):
208 if verbosity < 2: return
209 msg(*args, **kwargs)
210
211 def findSolutionWithIndex(solutionData, solIndex):
212 # Check solution at the index corresponding to solIndex first
213 if solIndex < len(solutionData) and solutionData[solIndex]["SolutionIndex"] == solIndex:
214 return solutionData[solIndex]
215 else:
216 debug("Searching for index...")
217 solution = [s for s in solutionData if s["SolutionIndex"]==solIndex]
218 assert(len(solution) == 1)
219 return solution[0]
220
221 # returns merged logic data as list
222 def mergeLogic(oriData, incData, forceMerge, noEff=False):
223 origNumSizes = len(oriData[7])
224 origNumSolutions = len(oriData[5])
225
226 incData[7] = incData[7] or []
227 incNumSizes = len(incData[7])
228 incNumSolutions = len(incData[5])
229
230 verbose(origNumSizes, "sizes and", origNumSolutions, "solutions in base logic file")
231 verbose(incNumSizes, "sizes and", incNumSolutions, "solutions in incremental logic file")
232
233 # trim 8-tuple gemm size format to 4-tuple [m, n, b, k]
234 # TODO future gemm size could include dictionary format so need robust preprocessing
235 [oriData[7], origNumSizes] = fixSizeInconsistencies(oriData[7], "base")
236 [incData[7], incNumSizes] = fixSizeInconsistencies(incData[7], "incremental")
237
238 oriData, numOrigRemoved = removeUnusedSolutions(oriData, "Base logic file: ")
239 incData, numIncRemoved = removeUnusedSolutions(incData, "Inc logic file: ")
240
241 solutionPool = deepcopy(oriData[5])
242 solDict = {sol["SolutionNameMin"]: sol for sol in oriData[5]}
243 solutionMap = deepcopy(oriData[7])
244
245 origDict = {tuple(origSize): [i, origEff] for i, [origSize, [origIndex, origEff]] in enumerate(oriData[7])}
246 for incSize, [incIndex, incEff] in incData[7]:
247 incSolution = findSolutionWithIndex(incData[5], incIndex)
248
249 storeEff = incEff if noEff == False else 0.0
250 try:
251 j, origEff = origDict[tuple(incSize)]
252 if incEff > origEff or forceMerge:
253 if incEff > origEff:
254 verbose("[O]", incSize, "already exists and has improved in performance.", end="")
255 elif forceMerge:
256 verbose("[!]", incSize, "already exists but does not improve in performance.", end="")
257 verbose("Efficiency:", origEff, "->", incEff, "(force_merge=True)" if forceMerge else "")
258 solutionPool, solDict, index = addKernel(solutionPool, solDict, incSolution)
259 solutionMap[j][1] = [index, storeEff]
260 else:
261 verbose("[X]", incSize, "already exists but does not improve in performance.", end="")
262 verbose("Efficiency:", origEff, "->", incEff)
263 except KeyError:
264 verbose("[-]", incSize, "has been added to solution table, Efficiency: N/A ->", incEff)
265 solutionPool, solDict, index = addKernel(solutionPool, solDict, incSolution)
266 solutionMap.append([incSize,[index, storeEff]])
267
268 verbose(numOrigRemoved, "unused solutions removed from base logic file")
269 verbose(numIncRemoved, "unused solutions removed from incremental logic file")
270
271 mergedData = deepcopy(oriData)
272 mergedData[5] = solutionPool
273 mergedData[7] = solutionMap
274 mergedData, numReplaced = removeUnusedSolutions(mergedData, "Merged data: ")
275
276 numSizesAdded = len(solutionMap) - len(oriData[7])
277 numSolutionsAdded = len(solutionPool) - len(oriData[5])
278 numSolutionsRemoved = numReplaced + numOrigRemoved # incremental file not counted
279
280 return [mergedData, numSizesAdded, numSolutionsAdded, numSolutionsRemoved]
281
282 def avoidRegressions(originalDir, incrementalDir, outputPath, forceMerge, noEff=False):
283 originalFiles = allFiles(originalDir)
284 incrementalFiles = allFiles(incrementalDir)
285 ensurePath(outputPath)
286
287 incrementalFilesTemp = []
288 originalFileNames = [os.path.split(o)[-1] for o in originalFiles]
289 for file in incrementalFiles:
290 if os.path.split(file)[-1] in originalFileNames:
291 incrementalFilesTemp.append(file)
292 else:
293 outputFile = os.path.join(outputPath, os.path.split(file)[-1])
294 shutil.copyfile(file, outputFile)
295 msg("Copied", file, "to", outputFile)
296
297 incrementalFiles = incrementalFilesTemp
298
299 logicsFiles = {}
300 for incFile in incrementalFiles:
301 basename = os.path.split(incFile)[-1]
302 origFile = os.path.join(originalDir, basename)
303 logicsFiles[origFile] = origFile
304 logicsFiles[incFile] = incFile
305
306 iters = zip(logicsFiles.keys())
307 logicsList = ParallelMap2(loadData, iters, "Loading Logics...", return_as="list")
308 logicsDict = {}
309 for i, _ in enumerate(logicsList):
310 logicsDict[logicsList[i][0]] = logicsList[i][1]
311
312 for incFile in incrementalFiles:
313 basename = os.path.split(incFile)[-1]
314 origFile = os.path.join(originalDir, basename)
315
316 msg("Base logic file:", origFile, "| Incremental:", incFile, "| Merge policy: %s"%("Forced" if forceMerge else "Winner"))
317 oriData = logicsDict[origFile]
318 incData = logicsDict[incFile]
319
320 # Terminate when the destination folder doesn't match Incremental logic yaml
321 # For example, merge Gridbased yaml to Equality folder or Equality yaml to GridBased folder
322 compareDestFolderToYaml(originalDir, incFile, incData)
323
324 # Terminate when ProblemType of originalFiles and incrementalFiles mismatch
325 compareProblemType(oriData, incData)
326
327 sanitizeSolutions(oriData[5])
328 sanitizeSolutions(incData[5])
329
330 reNameSolutions(oriData)
331 reNameSolutions(incData)
332
333 # So far "SolutionIndex" in logic yamls has zero impact on actual 1-1 size mapping (but the order of the Solution does)
334 # since mergeLogic() takes that value very seriously so we reindex them here so it doesn't choke on duplicated SolutionIndex
335 oriData, numRemoved, numSolutions, numKernels = removeDuplicatedSolutions(oriData)
336 msg("Base logic file:", numRemoved, "duplicated solution(s) removed,",\
337 "sizes: %d, solutions: %d, kernels: %d"%(len(oriData[7]),numSolutions,numKernels))
338 incData, numRemoved, numSolutions, numKernels = removeDuplicatedSolutions(incData)
339 msg("Inc logic file:", numRemoved, "duplicated solution(s) removed,",\
340 "sizes: %d, solutions: %d, kernels: %d"%(len(incData[7]),numSolutions,numKernels))
341
342 mergedData, *stats = mergeLogic(oriData, incData, forceMerge, noEff)
343 mergedData[0] = {"MinimumRequiredVersion": "%s"%__version__}
344 msg(stats[0], "size(s) and", stats[1], "solution(s) added,", stats[2], "solution(s) removed.", \
345 len(mergedData[7]), "sizes and", len(mergedData[5]), "solutions")
346 with open(os.path.join(outputPath, basename), "w") as outFile:
347 yaml.safe_dump(mergedData,outFile,default_flow_style=None)
348 msg("File written to", os.path.join(outputPath, basename))
349 msg("------------------------------")
350
351 def main():
352 argParser = argparse.ArgumentParser()
353 argParser.add_argument("original_dir", help="The library logic directory without tuned sizes")
354 argParser.add_argument("incremental_dir", help="The incremental logic directory")
355 argParser.add_argument("output_dir", help="The output logic directory")
356 argParser.add_argument("-v", "--verbosity", help="0: summary, 1: verbose, 2: debug", default=1, type=int)
357 argParser.add_argument("--force_merge", help="Merge previously known sizes unconditionally. Default behavior if not arcturus", default="none")
358 argParser.add_argument("--no_eff", help="force set eff as 0.0.", action="store_true")
359
360 args = argParser.parse_args(sys.argv[1:])
361 originalDir = args.original_dir
362 incrementalDir = args.incremental_dir
363 outputPath = args.output_dir
364 global verbosity
365 verbosity = args.verbosity
366 forceMerge = args.force_merge.lower()
367 no_eff = args.no_eff
368
369 if forceMerge in ["none"]: forceMerge=True
370 elif forceMerge in ["true", "1"]: forceMerge=True
371 elif forceMerge in ["false", "0"]: forceMerge=False
372
373 avoidRegressions(originalDir, incrementalDir, outputPath, forceMerge, no_eff)