Debian Codegraph @

tensilelite/Tensile/LibraryIO.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 .CustomKernels import getCustomKernelConfig
26 from . import SolutionLibrary
27 from .CustomYamlLoader import load_yaml_stream
28 from Tensile import __version__
29 from Tensile.Common import printExit, printWarning, print2, \
30 versionIsCompatible, IsaInfo
31 from Tensile.Common.Architectures import gfxToIsa
32 from Tensile.SolutionStructs import Solution, ProblemSizes
33 from Tensile.SolutionStructs.Problem import ProblemType, problemTypeToEnum
34
35 from typing import NamedTuple, List, Dict
36 import os
37 import sys
38 import subprocess
39 import re
40
41 try:
42 import orjson as json
43 except ImportError:
44 try:
45 import ujson as json
46 print2("orjson not installed. Fallback to ujson.")
47 except ImportError:
48 try:
49 import simplejson as json
50 print2("orjson, ujson not installed. Fallback to simplejson.")
51 except ImportError:
52 import json
53 print2("orjson, ujson, simplejson not installed. Fallback to json.")
54
55 try:
56 import yaml
57 except ImportError:
58 printExit(
59 "You must install PyYAML to use Tensile (to parse config files). See http://pyyaml.org/wiki/PyYAML for installation instructions."
60 )
61
62 try:
63 from yaml import CSafeLoader as yamlLoader
64 except ImportError:
65 from yaml import SafeLoader as yamlLoader
66 printWarning("CSafeLoader not installed. Fallback to SafeLoader.")
67
68 try:
69 import msgpack
70 except ImportError:
71 print("Message pack python library not detected. Must use YAML backend instead.")
72
73
74 ###################
75 # Writing functions
76 ###################
77 def write(filename_noExt, data, format="yaml"):
78 """Writes data to file with specified format; extension is appended based on format."""
79 if format == "yaml":
80 writeYAML(filename_noExt + ".yaml", data)
81 elif format == "json":
82 writeJson(filename_noExt + ".json", data)
83 elif format == "msgpack":
84 writeMsgPack(filename_noExt + ".dat", data)
85 else:
86 printExit("Unrecognized write format {}".format(format))
87
88
89 def writeYAML(filename, data, **kwargs):
90 """Writes data to file in YAML format."""
91 # set default kwags for yaml dump
92 if "explicit_start" not in kwargs:
93 kwargs["explicit_start"] = True
94 if "explicit_end" not in kwargs:
95 kwargs["explicit_end"] = True
96 if "default_flow_style" not in kwargs:
97 kwargs["default_flow_style"] = None
98
99 with open(filename, "w") as f:
100 yaml.dump(data, f, **kwargs)
101
102 def writeJson(filename, data):
103 """Writes data to file in json format."""
104 with open(filename, "w") as f:
105 json_object = json.dumps(data, option=json.OPT_INDENT_2).decode("utf-8") if 'orjson' in sys.modules else json.dumps(data, indent=2)
106 f.write(json_object)
107
108 def writeMsgPack(filename, data):
109 """Writes data to file in Message Pack format."""
110 with open(filename, "wb") as f:
111 msgpack.pack(data, f)
112
113 def writeSolutions(filename, problemSizes, biasTypeArgs, activationArgs, solutions, cache=False):
114 """Writes solution YAML file."""
115
116 # convert objects to nested dictionaries
117 solutionStates = []
118
119 if cache:
120 solYaml = read(filename)
121 if biasTypeArgs and activationArgs:
122 solutionStates = solYaml[4:]
123 elif biasTypeArgs or activationArgs:
124 solutionStates = solYaml[3:]
125 else:
126 solutionStates = solYaml[2:]
127 else:
128 for solution in solutions:
129 solutionState = solution.getAttributes()
130 solutionState["ProblemType"] = solutionState["ProblemType"].state
131 problemTypeToEnum(solutionState["ProblemType"])
132 isa = solutionState["ISA"]
133 solutionState["ISA"] = [isa[0], isa[1], isa[2]]
134 solutionStates.append(solutionState)
135 # write dictionaries
136 with open(filename, "w") as f:
137 f.write("- MinimumRequiredVersion: {}\n".format(__version__))
138 f.write("- ProblemSizes:\n")
139 if problemSizes:
140 for sizeRange in problemSizes.ranges:
141 f.write(" - Range: {}\n".format(sizeRange))
142 for problemExact in problemSizes.exacts:
143 #FIXME-problem, this ignores strides:
144 f.write(" - Exact: {}\n".format(problemExact))
145 if biasTypeArgs:
146 f.write("- BiasTypeArgs: [{}]\n".format([btype.value for btype in biasTypeArgs.biasTypes]))
147 if activationArgs:
148 f.write("- ActivationArgs:\n")
149 for setting in activationArgs.settingList:
150 f.write(" - [Enum: %s]\n"%(setting.activationEnum))
151 yaml.dump(solutionStates, f, default_flow_style=None)
152
153
154 ###############################
155 # Reading and parsing functions
156 ###############################
157 def read(filename, customizedLoader=False):
158 name, extension = os.path.splitext(filename)
159 if extension == ".yaml":
160 return load_yaml_stream(filename, yamlLoader) if customizedLoader else readYAML(filename)
161 if extension == ".json":
162 return readJson(filename)
163 else:
164 printExit("Unrecognized read format {}".format(extension))
165
166
167 def readYAML(filename):
168 """Reads and returns YAML data from file."""
169 with open(filename, "r") as f:
170 data = yaml.load(f, yamlLoader)
171 return data
172
173
174 def readJson(filename):
175 """Reads and returns JSON data from file."""
176 with open(filename, "r") as f:
177 data = json.loads(f.read())
178 return data
179
180
181 def parseSolutionsFile(
182 filename,
183 assembler,
184 splitGSU: bool,
185 printSolutionRejectionReason: bool,
186 printIndexAssignmentInfo: bool,
187 isaInfoMap
188 ):
189 """Wrapper function to read and parse a solutions file."""
190 return parseSolutionsData(
191 read(filename),
192 filename,
193 assembler,
194 splitGSU,
195 printSolutionRejectionReason,
196 printIndexAssignmentInfo,
197 isaInfoMap
198 )
199
200
201 def parseSolutionsData(
202 data,
203 srcFile,
204 assembler,
205 splitGSU: bool,
206 printSolutionRejectionReason: bool,
207 printIndexAssignmentInfo: bool,
208 isaInfoMap
209 ):
210 """Parses problem sizes and solutions from the data of a solutions file."""
211 if len(data) < 3:
212 printExit("Solution file {} is missing required fields (len = {} < 3" \
213 .format(srcFile, len(data)))
214
215 versionString = data[0]["MinimumRequiredVersion"]
216 if not versionIsCompatible(versionString):
217 printWarning("Version = {} in solution file {} does not match Tensile version = {}" \
218 .format(srcFile, versionString, __version__) )
219
220 if "ProblemSizes" not in data[1]:
221 printExit("Solution file {} doesn't begin with ProblemSizes".format(srcFile))
222
223 problemSizesConfig = data[1]["ProblemSizes"]
224 solutionStartIdxInData = 2
225 if (len(data) > solutionStartIdxInData) and "BiasTypeArgs" in data[solutionStartIdxInData]:
226 solutionStartIdxInData += 1
227 if (len(data) > solutionStartIdxInData) and "ActivationArgs" in data[solutionStartIdxInData]:
228 solutionStartIdxInData += 1
229
230 solutions = []
231 for i in range(solutionStartIdxInData, len(data)):
232 solutionState = data[i]
233 # force redo the deriving of parameters, make sure old version logic yamls can be validated
234 solutionState["AssignedProblemIndependentDerivedParameters"] = False
235 solutionState["AssignedDerivedParameters"] = False
236 solutionObject = Solution(
237 solutionState,
238 splitGSU,
239 printSolutionRejectionReason,
240 printIndexAssignmentInfo,
241 assembler,
242 isaInfoMap,
243 srcFile
244 )
245 solutions.append(solutionObject)
246 problemType = solutions[0]["ProblemType"]
247 problemSizes = ProblemSizes(problemType, problemSizesConfig)
248 return (problemSizes, solutions)
249
250
251 class LibraryLogic(NamedTuple):
252 """Return tuple for parseLibraryLogicData()"""
253 schedule: str
254 architecture: str
255 problemType: ProblemType
256 solutions: list
257 exactLogic: list
258 library: SolutionLibrary.MasterSolutionLibrary
259
260 def parseLibraryLogicFile(
261 filename,
262 assembler,
263 splitGSU: bool,
264 printSolutionRejectionReason: bool,
265 printIndexAssignmentInfo: bool,
266 isaInfoMap: Dict[str, IsaInfo],
267 lazyLibraryLoading: bool
268 ):
269 """Wrapper function to read and parse a library logic file."""
270 return parseLibraryLogicData(
271 read(filename, True),
272 filename,
273 assembler,
274 splitGSU,
275 printSolutionRejectionReason,
276 printIndexAssignmentInfo,
277 isaInfoMap,
278 lazyLibraryLoading
279 )
280
281
282 def parseLibraryLogicData(
283 data,
284 srcFile,
285 assembler,
286 splitGSU: bool,
287 printSolutionRejectionReason: bool,
288 printIndexAssignmentInfo: bool,
289 isaInfoMap: Dict[str, IsaInfo],
290 lazyLibraryLoading: bool
291 ):
292 """Parses the data of a library logic file."""
293 if isinstance(data, List):
294 data = parseLibraryLogicList(data, srcFile)
295
296 if "CUCount" not in data:
297 data["CUCount"] = None
298
299 if not versionIsCompatible(data["MinimumRequiredVersion"]):
300 printWarning("Version = {} in library logic file {} does not match Tensile version = {}" \
301 .format(srcFile, data["MinimumRequiredVersion"], __version__) )
302
303 # unpack problemType
304 problemType = ProblemType(data["ProblemType"], printIndexAssignmentInfo)
305
306 # unpack solution
307 def solutionStateToSolution(solutionState, assembler, isaInfoMap) -> Solution:
308 if solutionState["KernelLanguage"] == "Assembly":
309 solutionState["ISA"] = gfxToIsa(data["ArchitectureName"])
310 solutionState["CUCount"] = data["CUCount"]
311 # force redo the deriving of parameters, make sure old version logic yamls can be validated
312 solutionState["AssignedProblemIndependentDerivedParameters"] = False
313 solutionState["AssignedDerivedParameters"] = False
314 if solutionState["CustomKernelName"]:
315 isp = {}
316 if "InternalSupportParams" in solutionState:
317 isp = solutionState["InternalSupportParams"]
318 customConfig = getCustomKernelConfig(solutionState["CustomKernelName"], isp)
319 for key, value in customConfig.items():
320 solutionState[key] = value
321
322 if "MatrixInstruction" in customConfig and len(customConfig["MatrixInstruction"]) != 4:
323 raise ValueError(f"Custom kernel MatrixInstruction can only be of length 4, found {customConfig['MatrixInstruction']}")
324 # overwrite problemType if any
325 solutionState["ProblemType"] = problemType
326 solutionObject = Solution(
327 solutionState,
328 splitGSU,
329 printSolutionRejectionReason,
330 printIndexAssignmentInfo,
331 assembler,
332 isaInfoMap,
333 srcFile
334 )
335 return solutionObject
336
337 solutions = [solutionStateToSolution(solutionState, assembler, isaInfoMap) for solutionState in data["Solutions"]]
338
339 newLibrary, _ = SolutionLibrary.MasterSolutionLibrary.FromOriginalState(
340 data,
341 solutions,
342 splitGSU,
343 printSolutionRejectionReason,
344 printIndexAssignmentInfo,
345 assembler,
346 isaInfoMap,
347 lazyLibraryLoading
348 )
349
350 return LibraryLogic(data["ScheduleName"], data["ArchitectureName"], problemType, solutions, \
351 data.get("ExactLogic"), newLibrary)
352
353
354 def parseLibraryLogicList(data, srcFile="?"):
355 """Parses the data of a matching table style library logic file."""
356 if len(data) < 9:
357 printExit("Library logic file {} is missing required fields (len = {} < 9)" \
358 .format(srcFile, len(data)))
359
360 rv = {}
361 rv["MinimumRequiredVersion"] = data[0]["MinimumRequiredVersion"]
362 rv["ScheduleName"] = data[1]
363 rv["DeviceNames"] = data[3]
364 rv["ProblemType"] = data[4]
365 rv["Solutions"] = data[5]
366
367 if type(data[2]) is dict:
368 rv["ArchitectureName"] = data[2]["Architecture"]
369 rv["CUCount"] = data[2]["CUCount"]
370 else:
371 rv["ArchitectureName"] = data[2]
372 rv["CUCount"] = None
373
374 # TODOBEN: figure out what to do with these...
375 rv["ExactLogic"] = data[7]
376 rv["RangeLogic"] = data[8]
377
378 # optional fields
379 if len(data) > 10 and data[10]:
380 rv["PerfMetric"] = data[10]
381
382 # library logic fields
383 libraryType = None
384 if len(data) > 11 and data[11]:
385 libraryType = data[11]
386 else:
387 printExit("Library logic file {} is missing required field matching property." \
388 .format(srcFile))
389 if libraryType == "FreeSize":
390 rv["LibraryType"] = "FreeSize"
391 rv["Library"] = {}
392 rv["Library"]["indexOrder"] = None
393 rv["Library"]["table"] = [0, len(data[5])]
394 rv["Library"]["distance"] = None
395 elif libraryType == "Prediction":
396 rv["LibraryType"] = "Prediction"
397 rv["Library"] = {}
398 rv["Library"]["indexOrder"] = None
399 rv["Library"]["table"] = [0, len(data[5])]
400 rv["Library"]["distance"] = None
401 else:
402 rv["LibraryType"] = "Matching"
403 rv["Library"] = {}
404 rv["Library"]["indexOrder"] = data[6]
405 rv["Library"]["table"] = data[7]
406 rv["Library"]["distance"] = libraryType
407
408 return rv
409
410
411 def rawLibraryLogic(data):
412 """Returns a tuple of the data in a library logic file."""
413 versionString = data[0]
414 scheduleName = data[1]
415 architectureName = data[2]
416 deviceNames = data[3]
417 problemTypeState = data[4]
418 solutionStates = data[5]
419 indexOrder = data[6]
420 exactLogic = data[7]
421 rangeLogic = data[8]
422 otherFields = []
423
424 dataLength = len(data)
425 if dataLength > 9:
426 for idx in range(9, dataLength):
427 otherFields.append(data[idx])
428
429 return (versionString, scheduleName, architectureName, deviceNames,\
430 problemTypeState, solutionStates, indexOrder, exactLogic, rangeLogic, otherFields)
431
432
433 #################
434 # Other functions
435 #################
436 def getCUCount() -> int:
437 """Return the number of CU Count in current Hardware."""
438 CU = os.environ.get("CU", None)
439 if CU is None:
440 res = subprocess.run("rocminfo | grep Compute", stdout=subprocess.PIPE, shell=True, env={"ROCR_VISIBLE_DEVICES":"0"})
441 CU_RE = r"Compute Unit:(?P<COMPUTE_UNIT>[\w ]+)"
442 match = re.search(CU_RE, res.stdout.decode("utf-8").split('\n')[-2])
443 if match:
444 CU = int(match.group('COMPUTE_UNIT').strip())
445 return CU
446
447 def createLibraryLogic(schedulePrefix, architectureName, deviceNames, libraryType, logicTuple):
448 """Creates the data for a library logic file suitable for writing to YAML."""
449 problemType = logicTuple[0]
450 solutions = logicTuple[1]
451 indexOrder = logicTuple[2]
452 exactLogic = logicTuple[3]
453 rangeLogic = logicTuple[4]
454
455 tileSelection = False
456 if len(logicTuple) > 5 and logicTuple[5]:
457 tileSelection = True
458
459 data = []
460 # Tensile version
461 data.append({"MinimumRequiredVersion": __version__})
462 # schedule name
463 data.append(schedulePrefix) # change from Tensile to vega10
464 # schedule architecture name and get CU count
465 CUCount=getCUCount()
466 data.append({"Architecture": architectureName, "CUCount": CUCount} if architectureName=="gfx942" and CUCount and CUCount!=304 else architectureName)
467 # schedule device names
468 data.append(deviceNames)
469 # problem type
470 problemTypeState = problemType.state
471 problemTypeState["DataType"] = \
472 problemTypeState["DataType"].value
473 problemTypeState["DataTypeA"] = \
474 problemTypeState["DataTypeA"].value
475 problemTypeState["DataTypeB"] = \
476 problemTypeState["DataTypeB"].value
477 problemTypeState["DataTypeE"] = \
478 problemTypeState["DataTypeE"].value
479 problemTypeState["DataTypeAmaxD"] = \
480 problemTypeState["DataTypeAmaxD"].value
481 problemTypeState["DestDataType"] = \
482 problemTypeState["DestDataType"].value
483 problemTypeState["ComputeDataType"] = \
484 problemTypeState["ComputeDataType"].value
485 problemTypeState["BiasDataTypeList"] = \
486 [btype.value for btype in problemTypeState["BiasDataTypeList"]]
487 problemTypeState["ActivationComputeDataType"] = \
488 problemTypeState["ActivationComputeDataType"].value
489 problemTypeState["ActivationType"] = \
490 problemTypeState["ActivationType"].value
491 problemTypeState["F32XdlMathOp"] = \
492 problemTypeState["F32XdlMathOp"].value
493 if "DataTypeMetadata" in problemTypeState:
494 problemTypeState["DataTypeMetadata"] = \
495 problemTypeState["DataTypeMetadata"].value
496 data.append(problemTypeState)
497 # solutions
498 solutionList = []
499 for solution in solutions:
500 solutionState = solution.getAttributes()
501 del solutionState["ProblemType"]
502 isa = solutionState["ISA"]
503 solutionState["ISA"] = [isa[0], isa[1], isa[2]]
504 solutionList.append(solutionState)
505
506 if tileSelection:
507 tileSolutions = logicTuple[5]
508 for solution in tileSolutions:
509 solutionState = solution.getAttributes()
510 del solutionState["ProblemType"]
511 solutionList.append(solutionState)
512
513 data.append(solutionList)
514 # index order
515 data.append(indexOrder)
516
517 # exactLogic
518 exactLogicList = []
519 if exactLogic:
520 for key in exactLogic:
521 exactLogicList.append([list(key), exactLogic[key]])
522 data.append(exactLogicList)
523 else:
524 data.append(None)
525
526 # rangeLogic
527 data.append(rangeLogic)
528
529 if tileSelection:
530 tileSelectionLogic = {}
531 tileSelectionIndices = logicTuple[6]
532 tileSelectionLogic["TileSelectionIndices"] = tileSelectionIndices
533 data.append(tileSelectionLogic)
534 else:
535 data.append(None)
536
537 data.append(logicTuple[7]) # PerfMetric
538 data.append(libraryType) # LibraryType
539 return data