Debian Codegraph @

tensilelite/Tensile/GenerateSummations.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 os
26
27 import pandas as pd
28 import numpy as np
29 import yaml
30 import subprocess
31 import glob
32
33 from shutil import copyfile
34 from copy import deepcopy
35
36 from . import LibraryIO
37
38 from . import ClientWriter
39 from Tensile.Common import ensurePath, printExit
40 from Tensile.Common.Architectures import isaToGfx, gfxToSwCodename, detectGlobalCurrentISA
41 from Tensile.Common.GlobalParameters import assignGlobalParameters
42 from .SolutionStructs import ProblemSizes
43 from .Toolchain.Validators import ToolchainDefaults, validateToolchain
44
45
46 def createLibraryForBenchmark(logicPath, libraryPath, currentPath):
47 """
48 takes the path of existing logic files as input and adds the summation
49 model for each of the solutions. This is used in the Tile Aware Metirc
50 Selection.
51 """
52
53 pythonExePath = os.path.join(os.path.dirname(os.path.realpath(__file__)), "bin", "TensileCreateLibrary")
54 args = [pythonExePath, \
55 "--new-client-only", "--no-short-file-names", \
56 "--architecture=all", "--code-object-version=default", "--library-format=yaml", \
57 logicPath, libraryPath, "HIP"]
58
59 try:
60 subprocess.run(args, check=True, cwd=currentPath)
61 except (subprocess.CalledProcessError, OSError) as e:
62 printExit("ClientWriter Benchmark Process exited with error: {}".format(e))
63
64 def GenerateSummations(userArgs):
65
66 inputLogicPath = userArgs[0]
67 outputPath = userArgs[1]
68 isaInfoMap = assignGlobalParameters({})
69 cxxCompiler, cCompiler, enumerator = validateToolchain(ToolchainDefaults.CXX_COMPILER,
70 ToolchainDefaults.C_COMPILER,
71 ToolchainDefaults.DEVICE_ENUMERATOR)
72
73 currentISA = detectGlobalCurrentISA(0, enumerator)
74 gfxName = isaToGfx(currentISA)
75 commonName = gfxToSwCodename(gfxName)
76
77 globPath = os.path.join(inputLogicPath, "{}*".format(commonName))
78 logicFileNames = glob.glob(globPath)
79
80 for logicFileName in logicFileNames:
81
82 logicFileBaseName = os.path.basename(logicFileName)
83 logicFileStem, ext = os.path.splitext(logicFileBaseName)
84 if (ext != ".yaml"):
85 continue
86
87 currentPath = ensurePath(os.path.join(outputPath, logicFileStem))
88
89 libPath = ensurePath(os.path.join(currentPath, "lib"))
90 finalPath = ensurePath(os.path.join(currentPath, "final"))
91 localLogicPath = ensurePath(os.path.join(currentPath, "logic"))
92 localLogicFilePath = os.path.join(localLogicPath, logicFileBaseName)
93
94 # Here we read in two version of the logic the first one fills the solutions with
95 # defaults and modifies some of the parameters. The final logic file should be the
96 # same as the initial logic with the summation model added. To preseve the original
97 # logic we also read in the raw unaltered version of the logic and stage the content
98 # to write the final logic.
99 logic = LibraryIO.parseLibraryLogicFile(logicFileName, cxxCompiler, isaInfoMap)
100 rawLogic = LibraryIO.rawLibraryLogic(logicFileName)
101
102 # If we cannot read the logic file then skip it
103 if rawLogic == None or logic == None:
104 printExit("Error reading the file: %s. skipping." % logicFileName)
105
106 (versionStringR, scheduleNameR, architectureNameR, deviceNamesR, problemTypeStateR,\
107 solutionStatesR, indexOrderR, exactLogicR, rangeLogicR, otherFieldsR) =\
108 rawLogic
109
110 copyfile(logicFileName, localLogicFilePath)
111 createLibraryForBenchmark(localLogicPath, libPath, currentPath)
112
113 exactList = []
114
115 solutionSummationSizes = [32,64,96,128,256,512,1024,2048,4096,8192,16384]
116
117 for K in solutionSummationSizes:
118 e = {"Exact" : [8192, 4096, 1, K]}
119 exactList.append(e)
120
121 libraryPath = libPath
122 clientBuildDir = os.path.join(outputPath, "client")
123 problemTypeObj = logic.problemType.state
124
125 problemSizes = ProblemSizes(problemTypeObj, exactList)
126 dataPath = ensurePath(os.path.join(outputPath, logicFileStem, "data"))
127 configFilePath = ensurePath(os.path.join(outputPath, logicFileStem, "configs"))
128 dataFilePath = os.path.join(dataPath, "benchmark.csv")
129 configFile = os.path.join(configFilePath, "ClientParameters.ini")
130 scriptPath = ensurePath(os.path.join(outputPath, logicFileStem, "script"))
131
132 ClientWriter.CreateBenchmarkClientParametersForSizes(libraryPath, problemSizes, dataFilePath, configFile, problemTypeObj)
133 ClientWriter.runNewClient(scriptPath, configFile, clientBuildDir, cxxCompiler, cCompiler)
134
135 tensileLibraryFile = os.path.join(libPath, "library", "TensileLibrary.yaml")
136
137 stream = open(tensileLibraryFile, "r")
138 tensileLibrary = yaml.load(stream, yaml.SafeLoader)
139 stream.close()
140
141 libSolutions = tensileLibrary["solutions"]
142
143 libSolutionNames = []
144 for s in libSolutions:
145 kernelName=s["name"]
146 libSolutionNames.append(kernelName)
147
148 working_data=pd.read_csv(dataFilePath).rename(str.strip,axis='columns')
149
150 index_keys = working_data.SizeL.unique()
151 solutionsDF = working_data.filter(like='Cij')
152
153 perf_max = solutionsDF.max().max().item()
154
155 solutionIndex = 0
156 for s_stateR, kernelName in zip(solutionStatesR, libSolutionNames):
157 solutionIndex += 1
158 perf_raw = working_data[kernelName]
159 perf = (1000*index_keys) / perf_raw
160 model = np.polyfit(x=index_keys, y=perf, deg=1)
161 slope = model[0].item()
162 intercept = model[1].item()
163 linearModel = {"slope": slope, "intercept": intercept, "max": perf_max}
164 s_stateR["LinearModel"] = deepcopy(linearModel)
165
166 rawLogicData = []
167 rawLogicData.append(deepcopy(versionStringR))
168 rawLogicData.append(deepcopy(scheduleNameR))
169 rawLogicData.append(deepcopy(architectureNameR))
170 rawLogicData.append(deepcopy(deviceNamesR))
171 rawLogicData.append(deepcopy(problemTypeStateR))
172 rawLogicData.append(deepcopy(solutionStatesR))
173 rawLogicData.append(deepcopy(indexOrderR))
174 rawLogicData.append(deepcopy(exactLogicR))
175 rawLogicData.append(deepcopy(rangeLogicR))
176 for idx in range(0, len(otherFieldsR)):
177 rawLogicData.append(deepcopy(otherFieldsR[idx]))
178
179 localFinalLogic = os.path.join(finalPath, logicFileBaseName)
180
181 yamlWriter = LibraryIO.YAMLWriter()
182 yamlWriter.write(localFinalLogic, rawLogicData)
183
184 outputFinal = ensurePath(os.path.join(outputPath, "final"))
185 finalLogic = os.path.join(outputFinal, logicFileBaseName)
186
187 copyfile(localFinalLogic, finalLogic)