Debian Codegraph @

tensilelite/Tensile/BenchmarkStructs.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 copy import deepcopy
26 import itertools
27
28 from Tensile.Common.ValidParameters import checkParametersAreValid
29 from Tensile.Common import print1, print2, hasParam, printExit
30 from Tensile.Common.GlobalParameters import defaultBenchmarkCommonParameters, globalParameters, \
31 defaultBatchedBenchmarkFinalProblemSizes, \
32 defaultBenchmarkFinalProblemSizes
33 from Tensile.Common.ValidParameters import validParameters
34 from Tensile.SolutionStructs.Problem import ProblemType
35
36 from .CustomKernels import getAllCustomKernelNames
37 from .SolutionStructs import ProblemSizes, ActivationArgs, BiasTypeArgs, \
38 FactorDimArgs
39
40
41 def getDefaultsForMissingParameters(paramList, defaultParams):
42 """Returns all parameters (with values) in defaultParams not present in paramList"""
43 benchmarkParams = {}
44 for paramDict in defaultParams:
45 for name, value in paramDict.items():
46 if not hasParam(name, paramList) \
47 or name == "ProblemSizes":
48 benchmarkParams[name] = value
49 return benchmarkParams
50
51
52 def separateParameters(paramSetList):
53 """Separates paramSetList into parameters with single and multiple values"""
54 singleVaules = {}
55 multiValues = {}
56 for name, values in paramSetList.items():
57 if values == None:
58 printExit("You must specify value(s) for parameter \"{}\"".format(name))
59 if len(values) == 1 and name != "ProblemSizes":
60 singleVaules[name] = values[0]
61 elif len(values) > 1 and name != "ProblemSizes":
62 multiValues[name] = values
63
64 return singleVaules, multiValues
65
66
67 def checkCDBufferAndStrides(problemType, problemSizes, isCEqualD):
68 """Ensures ldd == ldc when CEqualD"""
69 if isCEqualD and problemType["OperationType"] == "GEMM":
70 for problem in problemSizes.problems:
71 ldd = problem.sizes[problemType["IndexAssignmentsLD"][0]]
72 ldc = problem.sizes[problemType["IndexAssignmentsLD"][1]]
73 if ldd != ldc:
74 printExit("LDD({}) != LDC({}) causes unpredictable result when CEqualD(True)" \
75 .format(ldd, ldc))
76
77
78 class BenchmarkProcess:
79 """Representation of benchmarking parameters and resulting steps"""
80
81 def __init__(self, problemTypeConfig, problemSizeGroupConfig, printIndexAssignmentInfo: bool):
82 """Create from the two sections of a config for a BenchmarkProblem"""
83 self.problemType = ProblemType(problemTypeConfig, printIndexAssignmentInfo)
84 self.isBatched = "Batched" in problemTypeConfig and problemTypeConfig["Batched"]
85 print2("# BenchmarkProcess beginning {}".format(self.problemType))
86
87 # fill parameter values from config
88 self.singleValueParams = {}
89 self.multiValueParams = {}
90 self.customKernels = []
91 self.sizes = None
92 self.getConfigParameters(self.isBatched, problemSizeGroupConfig)
93
94 # convert parameter lists to steps
95 # previously, multiple benchmark steps were possible
96 # currently only 1 benchmark step is possible; more may be added back later
97 self.benchmarkSteps = []
98 self.benchmarkStepIdx = 0
99 self.convertParametersToSteps()
100
101 def getConfigParameters(self, isbatched, config):
102 """Parse and validate benchmarking parameters in config"""
103 print2("")
104 print2("####################################################################")
105 print1("# Filling in Parameters With Defaults")
106 print2("####################################################################")
107 print2("")
108
109 # check for no longer supported legacy benchmark steps
110 badParams = ["InitialSolutionParameters", "BenchmarkForkParameters", \
111 "JoinParameters", "BenchmarkJoinParameters"]
112 badsInConfig = []
113
114 for p in badParams:
115 if config.get(p) is not None:
116 badsInConfig.append(p)
117
118 if len(badsInConfig) == 1:
119 printExit("Benchmark step {} is no longer supported".format("'" + badsInConfig[0] +
120 "'"))
121 elif len(badsInConfig) > 1:
122 printExit("Benchmark steps {} are no longer supported".format(badsInConfig))
123
124 # get supported configurations
125 # value in config file may be "None", which we should ignore
126 def getNonNoneFromConfig(key, default):
127 if config.get(key) is not None:
128 return config[key]
129 else:
130 return default
131
132 # converts list of dicts into a flat dict
133 benchmarkCommonParams = dict(itertools.chain(*[x.items() \
134 for x in getNonNoneFromConfig("BenchmarkCommonParameters", [])]))
135 forkParams = dict(itertools.chain(*[x.items() \
136 for x in getNonNoneFromConfig("ForkParameters", [])]))
137 self.paramGroups = forkParams.pop("Groups") if "Groups" in forkParams else []
138 self.customKernels = getNonNoneFromConfig("CustomKernels", [])
139 self.internalSupportParams = getNonNoneFromConfig("InternalSupportParams", {})
140 if self.customKernels == [] and self.internalSupportParams != {}:
141 printExit("InternalSupportParams only supports Custom Kernels")
142
143 activationConf = ""
144 biasTypesConf = ""
145 factorDimConf = ""
146 icacheFlush = None
147 if "BenchmarkFinalParameters" in config:
148 sizes = config["BenchmarkFinalParameters"][0]["ProblemSizes"]
149 for bfp in config["BenchmarkFinalParameters"][1:]:
150 if "ActivationArgs" in bfp:
151 if activationConf:
152 printExit("Duplicated ActivationArgs.")
153 activationConf = bfp["ActivationArgs"]
154 if "BiasTypeArgs" in bfp:
155 if biasTypesConf:
156 printExit("Duplicated BiasTypeArgs.")
157 biasTypesConf = bfp["BiasTypeArgs"]
158 if "FactorDimArgs" in bfp:
159 if factorDimConf:
160 printExit("Duplicated FactorDimArgs.")
161 factorDimConf = bfp["FactorDimArgs"]
162 if "ICacheFlush" in bfp:
163 if icacheFlush is not None:
164 printExit("Duplicated ICacheFlush.")
165 icacheFlush = bfp["ICacheFlush"]
166 else:
167 sizes = defaultBatchedBenchmarkFinalProblemSizes if isbatched \
168 else defaultBenchmarkFinalProblemSizes
169
170 if icacheFlush is None:
171 icacheFlush = [False,]
172
173 self.problemSizes = ProblemSizes(self.problemType, sizes)
174 checkCDBufferAndStrides(self.problemType, self.problemSizes, globalParameters["CEqualD"])
175
176 self.biasTypesArgs = BiasTypeArgs(self.problemType, biasTypesConf)
177 self.activationArgs = ActivationArgs(self.problemType, activationConf)
178 self.factorDimArgs = FactorDimArgs(self.problemType, factorDimConf)
179 self.icacheFlushArgs = icacheFlush
180
181 # validate parameter values
182 configParams = {**benchmarkCommonParams, **forkParams}
183 for param in configParams.items():
184 checkParametersAreValid(param, validParameters)
185
186 # TODO other checks on groups (same params for each entry? no dups between groups?)
187 for list in self.paramGroups:
188 for group in list:
189 for k, v in group.items():
190 checkParametersAreValid((k, [v]), validParameters)
191
192 params = dict(itertools.chain(*[x.items() for x in defaultBenchmarkCommonParameters]))
193 params.update(configParams)
194 self.singleValueParams, self.multiValueParams = separateParameters(params)
195
196 # print summary of parameter values
197 print2("Single Value Parameters:")
198 for k, v in self.singleValueParams.items():
199 print2(" {}: {}".format(k, v))
200
201 print2("Multi-Value Parameters:")
202 for k, v in self.multiValueParams.items():
203 print2(" {}: {}".format(k, v))
204
205 if len(self.paramGroups) > 0:
206 print2("{} Parameter Group(s):".format(len(self.paramGroups)))
207 for i, group in enumerate(self.paramGroups):
208 print2(" {} entries is group {}".format(len(group), i + 1))
209
210 def convertParametersToSteps(self):
211 """Create benchmark steps based on parsed parameters"""
212 print2("")
213 print2("####################################################################")
214 print1("# Convert Parameters to Benchmark Step(s)")
215 print2("####################################################################")
216 print2("")
217
218 # currently only a single step is supported
219 print2("")
220 print2("####################################################################")
221 print1("# Benchmark Final")
222 benchmarkStep = BenchmarkStep( \
223 self.multiValueParams, \
224 self.singleValueParams, \
225 self.paramGroups, \
226 self.customKernels, \
227 self.internalSupportParams, \
228 self.problemSizes, \
229 self.biasTypesArgs, \
230 self.factorDimArgs, \
231 self.activationArgs, \
232 self.icacheFlushArgs, \
233 self.benchmarkStepIdx)
234 self.benchmarkSteps.append(benchmarkStep)
235 self.benchmarkStepIdx += 1
236
237 def __len__(self):
238 return len(self.benchmarkSteps)
239
240 def __getitem__(self, key):
241 return self.benchmarkSteps[key]
242
243 def __str__(self):
244 string = "BenchmarkProcess:\n"
245 for step in self.benchmarkSteps:
246 string += str(step)
247 return string
248
249 def __repr__(self):
250 return self.__str__()
251
252
253 def constructForkPermutations(forkParams, paramGroups):
254 """Constructs cartesian product of parameter values in forkParams and paramGroups"""
255
256 myParams = {}
257 myParams.update(forkParams)
258
259 totalPermutations = 1
260 for _, values in forkParams.items():
261 totalPermutations *= len(values)
262
263 # add groups to parameters to fork on
264 for i, group in enumerate(paramGroups):
265 myParams["_group" + str(i)] = group
266 totalPermutations *= len(group)
267
268 forkPermutations = []
269 for i in range(0, totalPermutations):
270 permutation = {}
271 pIdx = i
272 for name, v in myParams.items():
273 values = deepcopy(v)
274 valueIdx = pIdx % len(v)
275
276 # groups have multiple parameters to update
277 if "_group" in name:
278 entry = values[valueIdx]
279 for n2, v2 in entry.items():
280 permutation[n2] = v2
281 else:
282 permutation[name] = values[valueIdx]
283
284 pIdx //= len(values)
285 forkPermutations.append(permutation)
286
287 return forkPermutations
288
289
290 class BenchmarkStep:
291 """A single benchmark step which consists of constant and fork parameters and a set of sizes"""
292
293 def __init__(self, forkParams, constantParams, paramGroups, customKernels, internalSupportParams, problemSizes, biasTypeArgs, factorDimArgs, activationArgs, icacheFlushArgs, idx):
294 """Basic constructor storing each argument"""
295 self.forkParams = forkParams
296 self.constantParams = constantParams
297 self.paramGroups = paramGroups
298 self.customKernels = customKernels
299 self.internalSupportParams = internalSupportParams
300 self.problemSizes = problemSizes
301 self.biasTypeArgs = biasTypeArgs
302 self.factorDimArgs = factorDimArgs
303 self.activationArgs = activationArgs
304 self.icacheFlushArgs = icacheFlushArgs
305 self.stepIdx = idx
306
307 self.customKernelWildcard = False
308 if self.customKernels == ["*"]:
309 self.customKernels = getAllCustomKernelNames()
310 self.customKernelWildcard = True
311
312 print2("# Creating BenchmarkStep: {} fork params and {} sizes" \
313 .format( len(forkParams), problemSizes.totalProblemSizes))
314
315 def isFinal(self):
316 """Legacy. Currently always returns true since only one benchmark step is possible"""
317 return True
318
319 def __str__(self):
320 string = "{:02d}".format(self.stepIdx)
321 if self.isFinal():
322 string += "_Final"
323 return string
324
325 def __repr__(self):
326 return self.__str__()