Debian Codegraph @

tensilelite/Tensile/TensileRetuneLibrary.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 . import BenchmarkProblems
26 from . import ClientWriter
27 from . import LibraryIO
28 from . import LibraryLogic
29 from .Common import globalParameters, print1, printWarning, ensurePath, assignGlobalParameters, \
30 restoreDefaultGlobalParameters, HR, __version__
31 from .Tensile import addCommonArguments, argUpdatedGlobalParameters
32 from .SolutionStructs import ProblemSizes
33 from .Toolchain.Validators import validateToolchain
34
35 from pathlib import Path
36
37 import argparse
38 import copy
39 import os
40 import shutil
41 import sys
42 from pathlib import Path
43
44 workingDirectoryStack = []
45 def pushWorkingPath( foldername ):
46 # Warning: this is not thread-safe, modifies the global WorkingPath!
47 globalParameters["WorkingPath"] = \
48 os.path.join(globalParameters["WorkingPath"], foldername )
49 return ensurePath( globalParameters["WorkingPath"] )
50 def popWorkingPath():
51 # Warning: this is not thread-safe, modifies the global WorkingPath!
52 if len(workingDirectoryStack) == 0:
53 globalParameters["WorkingPath"] = \
54 os.path.split(globalParameters["WorkingPath"])[0]
55 else:
56 globalParameters["WorkingPath"] = workingDirectoryStack.pop()
57 def ensurePath(path):
58 try:
59 os.makedirs(path)
60 except FileExistsError:
61 pass
62 return path
63 def setWorkingPath( fullPathName ):
64 # Warning: this is not thread-safe, modifies the global WorkingPath!
65 workingDirectoryStack.append(globalParameters["WorkingPath"])
66 globalParameters["WorkingPath"] = ensurePath(fullPathName)
67
68 workingDirectoryStack = []
69 def pushWorkingPath( foldername ):
70 # Warning: this is not thread-safe, modifies the global WorkingPath!
71 globalParameters["WorkingPath"] = \
72 os.path.join(globalParameters["WorkingPath"], foldername )
73 return ensurePath( globalParameters["WorkingPath"] )
74 def popWorkingPath():
75 # Warning: this is not thread-safe, modifies the global WorkingPath!
76 if len(workingDirectoryStack) == 0:
77 globalParameters["WorkingPath"] = \
78 os.path.split(globalParameters["WorkingPath"])[0]
79 else:
80 globalParameters["WorkingPath"] = workingDirectoryStack.pop()
81 def ensurePath(path):
82 try:
83 os.makedirs(path)
84 except FileExistsError:
85 pass
86 return path
87 def setWorkingPath( fullPathName ):
88 # Warning: this is not thread-safe, modifies the global WorkingPath!
89 workingDirectoryStack.append(globalParameters["WorkingPath"])
90 globalParameters["WorkingPath"] = ensurePath(fullPathName)
91
92
93 def parseCurrentLibrary(libPath, sizePath):
94 libYaml = LibraryIO.read(libPath)
95 # parseLibraryLogicData mutates the original data, so make a copy
96 fields = LibraryIO.parseLibraryLogicData(copy.deepcopy(libYaml), libPath)
97 (_, _, problemType, solutions, exactLogic, _, _) = fields
98
99 # get performance metric
100 if len(libYaml) > 10:
101 GlobalParameters.globalParameters["PerformanceMetric"] = libYaml[10]
102
103 # process exactLogic into ProblemSizes
104 sizes = []
105 if sizePath is None:
106 for (size, mapping) in exactLogic:
107 sizes.append({"Exact": size})
108 else:
109 sizes = LibraryIO.read(sizePath)
110
111 # remove duplicate solutions and reindex
112 solutions = [v1 for i, v1 in enumerate(solutions) if not any(v1 == v2 for v2 in solutions[:i])]
113 for i, s in enumerate(solutions):
114 s["SolutionIndex"] = i
115
116 problemSizes = ProblemSizes(problemType, sizes)
117
118 return (libYaml, solutions, problemSizes)
119
120
121 def runBenchmarking(solutions, problemSizes, outPath, update, cxxCompiler: str, cCompiler: str, assembler: str, offloadBundler: str):
122 # TODO some copy-pasting from BenchmarkProblems.benchmarkProblemType
123 # could use a refactor to elimate duplicated code
124 ClientWriter.getClientExecutablePath()
125
126
127
128 shortName = "benchmark"
129 benchmarkDir = os.path.join(outPath, shortName)
130 sourceDir = os.path.join(benchmarkDir, "source")
131 resultsDir = os.path.normpath(os.path.join(globalParameters["WorkingPath"], "Data"))
132 libraryFile = os.path.join(resultsDir, "benchmark.yaml")
133
134 ensurePath(sourceDir)
135 ensurePath(resultsDir)
136
137 if update:
138 globalParameters["LibraryUpdateFile"] = os.path.join(resultsDir, "update.yaml")
139
140 pushWorkingPath(shortName)
141 pushWorkingPath("source")
142 BenchmarkProblems.writeBenchmarkFiles(benchmarkDir, solutions, problemSizes , "", "", "", "", shortName, [], cxxCompiler, assembler, offloadBundler)
143 popWorkingPath() # source
144
145 libraryLogicPath = None
146 forBenchmark = True
147 # TODO make this work with TileAware selection
148 returncode = ClientWriter.runClient(libraryLogicPath, forBenchmark, False, cxxCompiler, cCompiler)
149 if returncode:
150 printWarning("Benchmarking Client exited with code {}. Trying to continue".format(returncode))
151
152 # write solutions yaml file
153 for sol in solutions:
154 sol["ISA"] = list(sol["ISA"])
155 LibraryIO.writeSolutions(libraryFile, problemSizes, "", solutions)
156
157 popWorkingPath() # benchmark
158
159 # copy results to expected directory
160 out = os.path.join(globalParameters["WorkingPath"], "2_BenchmarkData")
161 ensurePath(out)
162 shutil.copy(os.path.join(resultsDir, "benchmark.csv"), os.path.join(out, "benchmark.csv"))
163 shutil.copy(os.path.join(resultsDir, "benchmark.yaml"), os.path.join(out, "benchmark.yaml"))
164
165
166 def TensileRetuneLibrary(userArgs):
167 print1("")
168 print1(HR)
169 print1("#")
170 print1("# Tensile Retune Library v{}".format(__version__))
171
172 # argument parsing and related setup
173 argParser = argparse.ArgumentParser()
174 argParser.add_argument("LogicFile", type=os.path.realpath,
175 help="Library logic file to retune")
176 argParser.add_argument("OutputPath", type=os.path.realpath,
177 help="Where to run benchmarks and output results")
178 argParser.add_argument("SizeFile", type=os.path.realpath, nargs="?",
179 help="Yaml file with sizes to tune; same format as the 'ProblemSizes' "
180 "section of a regular Tensile config "
181 "(https://github.com/ROCmSoftwarePlatform/Tensile/wiki/Benchmark-Protocol)",
182 default=None)
183 argParser.add_argument("--update-method", "-u", dest="updateMethod",
184 choices=["remake", "update", "both"], default="remake",
185 help="Method for making new library logic file")
186
187 addCommonArguments(argParser)
188 args = argParser.parse_args(userArgs)
189
190 libPath = args.LogicFile
191 sizePath = args.SizeFile
192 libraryFormat = args.LibraryFormat
193
194 print1("# Library Logic: {}".format(libPath))
195 print1("#")
196 print1(HR)
197 print1("")
198
199 if args.updateMethod == "remake":
200 update = False
201 remake = True
202 elif args.updateMethod == "update":
203 update = True
204 remake = False
205 else: # args.updateMethod == "both"
206 update = True
207 remake = True
208
209 cxxCompiler, cCompiler, assembler, offloadBundler = validateToolchain(args.CxxCompiler, args.CCompiler, args.Assembler, args.OffloadBundler)
210
211 ##############################################
212 # Retuning
213 ##############################################
214 outputPath = Path(ensurePath(os.path.abspath(args.OutputPath)))
215 restoreDefaultGlobalParameters()
216
217 assignGlobalParameters({"LibraryFormat": libraryFormat, "OutputPath": outputPath})
218
219 overrideParameters = argUpdatedGlobalParameters(args)
220 for key, value in overrideParameters.items():
221 print1("Overriding {0}={1}".format(key, value))
222 globalParameters[key] = value
223
224 # parse library logic then setup and run benchmarks
225 (rawYaml, solutions, problemSizes) = parseCurrentLibrary(libPath, sizePath)
226 runBenchmarking(solutions, problemSizes, outputPath, update, cxxCompiler, cCompiler, assembler, offloadBundler)
227
228 if remake:
229 # write library logic file
230 LibraryLogic.main(
231 {
232 "ScheduleName": rawYaml[1],
233 "ArchitectureName": rawYaml[2],
234 "DeviceNames": rawYaml[3]
235 },
236 cxxCompiler,
237 outputPath
238 )
239
240 if update:
241 # read update yaml from benchmark client and update logic
242 print1("")
243 print1(HR)
244 print1("# Reading update file from Benchmarking Client")
245 updateFile = os.path.join(outputPath, "Data", "update.yaml")
246 updateLogic = LibraryIO.read(updateFile)
247 rawYaml[7] = updateLogic
248
249 # write updated library logic (does not overwrite original)
250 libName = os.path.basename(libPath)
251 outFile = os.path.join(outputPath, libName)
252
253 print1("# Writing updated Library Logic: {}".format(outFile))
254 LibraryIO.writeYAML(outFile, rawYaml, explicit_start=False, explicit_end=False)
255 print1(HR)
256
257
258 def main():
259 TensileRetuneLibrary(sys.argv[1:])