Debian Codegraph @

tensilelite/Tensile/TensileCreateLibrary/Run.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 rocisa
26
27 import functools
28 import glob
29 import itertools
30 import os
31 import shutil
32 from pathlib import Path
33 from timeit import default_timer as timer
34 from typing import List, NamedTuple, Optional, Union
35
36 from Tensile import SOURCE_PATH, LibraryIO
37 from Tensile.Common import (
38 CHeader,
39 DebugConfig,
40 ensurePath,
41 HR,
42 IsaVersion,
43 ParallelMap2,
44 print1,
45 print2,
46 printWarning,
47 printExit,
48 printWarning,
49 state,
50 tqdm,
51 setVerbosity,
52 getVerbosity,
53 )
54 from Tensile.Common.Architectures import gfxToIsa, isaToGfx, SUPPORTED_GFX, splitArchsFromPredicates, filterLogicFilesByPredicates
55 from Tensile.Common.Capabilities import makeIsaInfoMap
56 from Tensile.Common.GlobalParameters import assignGlobalParameters, globalParameters
57 from Tensile.SolutionStructs.Naming import getKernelFileBase, getKeyNoInternalArgs, getKernelNameMin
58
59 from Tensile.CustomYamlLoader import load_logic_gfx_arch
60 from Tensile.KernelHelperNaming import kernelObjectNameCallables, initHelperKernelObjects
61 from Tensile.KernelWriterAssembly import KernelWriterAssembly
62 from Tensile.KernelWriterBase import (
63 KERNEL_HELPER_FILENAME_CPP,
64 KERNEL_HELPER_FILENAME_H,
65 )
66 from Tensile.SolutionLibrary import MasterSolutionLibrary
67 from Tensile.SolutionStructs import Solution
68 from Tensile.Toolchain.Assembly import makeAssemblyToolchain, buildAssemblyCodeObjectFiles
69 from Tensile.Toolchain.Source import makeSourceToolchain, buildSourceCodeObjectFiles
70 from Tensile.Toolchain.Validators import (
71 ToolchainDefaults,
72 validateToolchain,
73 )
74 from Tensile.Toolchain.Component import Assembler
75 from Tensile.Utilities.Decorators.Profile import profile
76 from Tensile.Utilities.Decorators.Timing import timing
77
78 from .ParseArguments import parseArguments
79
80
81 class KernelCodeGenResult(NamedTuple):
82 err: int
83 src: str
84 header: Optional[str]
85 name: str
86 targetObjFilename: str
87 isa: IsaVersion
88 wavefrontSize: int
89 cuoccupancy: int
90 pgr: int
91 mathclk: int
92
93 class KernelMinResult(NamedTuple):
94 err: int
95 cuoccupancy: int
96 pgr: int
97 mathclk: int
98
99 def processKernelSource(kernelWriterAssembly, data, splitGSU, kernel) -> KernelCodeGenResult:
100 """
101 Generate source for a single kernel.
102 Returns (error, source, header, kernelName).
103 """
104 kernelWriter = kernelWriterAssembly
105 kernelWriter.setRocIsa(data)
106 asmFilename = getKernelFileBase(splitGSU, kernel)
107 err, src = kernelWriter.getSourceFileString(kernel)
108 header = kernelWriter.getHeaderFileString(kernel)
109 objFilename = kernel._state.get("codeObjectFile", None)
110 pgr = int(kernel["PrefetchGlobalRead"])
111 return KernelCodeGenResult(
112 err, src, header, asmFilename, objFilename, tuple(kernel["ISA"]), \
113 kernel["WavefrontSize"], kernel["CUOccupancy"], \
114 pgr, kernel["MathClocksUnrolledLoop"]
115 )
116
117
118 def removeInvalidSolutionsAndKernels(results, kernels, solutions, errorTolerant, printLevel: bool, splitGSU: bool):
119 removeKernels = []
120 removeKernelNames = []
121 removeSolutions = []
122 removeResults = []
123
124 for kernIdx, r in (
125 tqdm(enumerate(results)) if printLevel > 1 else enumerate(results)
126 ):
127 if r.err != 0:
128 if not errorTolerant:
129 print(
130 "\nKernel generation failed for kernel: {}".format(
131 kernels[kernIdx]["SolutionIndex"]
132 )
133 )
134 print(kernels[kernIdx]["SolutionNameMin"])
135 removeKernels.append(kernels[kernIdx])
136 kName = getKeyNoInternalArgs(kernels[kernIdx], splitGSU)
137 if kName not in removeKernelNames:
138 removeKernelNames.append(kName)
139 removeResults.append(results[kernIdx])
140
141 if len(removeKernels) > 0 and not errorTolerant:
142 printExit("** kernel generation failure **")
143
144 for kern in removeKernels:
145 kernels.remove(kern)
146
147 for solution in (
148 tqdm(solutions, "Finding invalid solutions")
149 if printLevel > 1
150 else solutions
151 ):
152 solutionKernels = solution.getKernels()
153 for kernel in solutionKernels:
154 kName = getKeyNoInternalArgs(kernel, splitGSU)
155 if kName in removeKernelNames:
156 removeSolutions.append(solution)
157 break
158
159 for solut in removeSolutions:
160 solutions.remove(solut)
161
162 for rel in removeResults:
163 results.remove(rel)
164
165 def passPostKernelInfoToSolution(results, kernels, solutions, splitGSU: bool):
166 resultDict = {}
167 for kernIdx, r in enumerate(results):
168 kName = getKernelNameMin(kernels[kernIdx], splitGSU)
169 resultDict["%s"%kName] = r
170 for solution in solutions:
171 solutionKernels = solution.getKernels()
172 for kernel in solutionKernels:
173 kName = getKernelNameMin(kernel, splitGSU)
174 result = resultDict["%s"%kName]
175 solution._state["CUOccupancy"] = result.cuoccupancy
176 solution._state["PrefetchGlobalRead"] = result.pgr
177 solution._state["MathClocksUnrolledLoop"] = result.mathclk
178
179 def writeAssembly(asmPath: Union[Path, str], result: KernelCodeGenResult):
180 if result.err:
181 printExit(f"Failed to build kernel {result.name} because it has error code {result.err}")
182 path = Path(asmPath) / f"{result.name}.s"
183 isa = result.isa
184 wfsize = result.wavefrontSize
185 with open(path, "w", encoding="utf-8") as f:
186 f.write(result.src)
187
188 minResult = KernelMinResult(result.err, result.cuoccupancy, result.pgr, result.mathclk)
189 return path, isa, wfsize, minResult
190
191
192 def writeHelpers(
193 outputPath, kernelHelperObjs, KERNEL_HELPER_FILENAME_CPP, KERNEL_HELPER_FILENAME_H
194 ):
195 kernelSourceFilename = os.path.join(os.path.normcase(outputPath), KERNEL_HELPER_FILENAME_CPP)
196 kernelHeaderFilename = os.path.join(os.path.normcase(outputPath), KERNEL_HELPER_FILENAME_H)
197
198 with open(kernelHeaderFilename, "w", encoding="utf-8") as kernelHeaderFile, open(
199 kernelSourceFilename, "w", encoding="utf-8"
200 ) as kernelSourceFile:
201 kernelSourceFile.write(CHeader)
202 kernelHeaderFile.write(CHeader)
203 kernelSourceFile.write('#include "Kernels.h"\n')
204 kernelHeaderFile.write("#pragma once\n")
205 kernelHeaderFile.write("#include <hip/hip_runtime.h>\n")
206 kernelHeaderFile.write("#include <hip/hip_ext.h>\n\n")
207 kernelHeaderFile.write('#include "KernelHeader.h"\n\n')
208 HeaderText = ""
209 for ko in kernelHelperObjs:
210 kernelName = ko.getKernelName()
211 (err, src) = ko.getSourceFileString()
212
213 kernelSourceFile.write(src)
214 if err:
215 print("*** warning: invalid kernel#%u" % kernelName)
216 HeaderText += ko.getHeaderFileString()
217 kernelHeaderFile.write(HeaderText)
218
219
220 def writeSolutionsAndKernels(
221 outputPath,
222 asmToolchain,
223 srcToolchain,
224 solutions,
225 kernels,
226 kernelHelperObjs,
227 kernelWriterAssembly,
228 splitGSU: bool,
229 cmdlineArchs: List[str],
230 errorTolerant=False,
231 generateSourcesAndExit=False,
232 compress=True,
233 ):
234 if globalParameters["PythonProfile"]:
235 globalParameters["CpuThreads"] = 0
236 printWarning("Python profiling is enabled. CpuThreads set to 0.")
237 import yappi
238 yappi.start()
239
240 codeObjectFiles = []
241
242 outputPath = Path(outputPath)
243 destLibPath = ensurePath(
244 outputPath / "library"
245 ) # Destination for code object library files (.co)
246 buildTmpPath = ensurePath(outputPath / "build_tmp" / outputPath.stem.upper()) #
247 assemblyTmpPath = ensurePath(
248 buildTmpPath / "assembly"
249 ) # Temp path for generated assembly files (.s)
250 objectTmpPath = ensurePath(
251 buildTmpPath / "code_object_tmp"
252 ) # Temp path for HSA code object files (.hsaco)
253
254 asmKernels = [k for k in kernels if k["KernelLanguage"] == "Assembly"]
255
256 visited = set()
257 duplicates = 0
258 for k in asmKernels:
259 base = getKernelFileBase(splitGSU, k)
260 k.duplicate = True if base in visited else False
261 if not k.duplicate:
262 k["BaseName"] = base
263 duplicates += k.duplicate
264 print2(f"Duplicate: {base}")
265 visited.add(base)
266 print1(f"Number of duplicate kernels: {duplicates}")
267
268 numAsmKernels = len(asmKernels)
269 numKernels = len(asmKernels)
270 assert numKernels == numAsmKernels, "Only assembly kernels are supported in TensileLite"
271 asmIter = zip(
272 itertools.repeat(kernelWriterAssembly),
273 itertools.repeat(rocisa.rocIsa.getInstance().getData()),
274 itertools.repeat(splitGSU),
275 asmKernels
276 )
277 asmResults = ParallelMap2(processKernelSource, asmIter, "Generating assembly kernels", return_as="list")
278 removeInvalidSolutionsAndKernels(
279 asmResults, asmKernels, solutions, errorTolerant, getVerbosity(), splitGSU
280 )
281 passPostKernelInfoToSolution(
282 asmResults, asmKernels, solutions, splitGSU
283 )
284
285 def assemble(ret):
286 p, isa, wavefrontsize, result = ret
287 asmToolchain.assembler(isaToGfx(isa), wavefrontsize, str(p), str(p.with_suffix(".o")))
288
289 unaryWriteAssembly = functools.partial(writeAssembly, assemblyTmpPath)
290 compose = lambda *F: functools.reduce(lambda f, g: lambda x: f(g(x)), F)
291 ret = ParallelMap2(
292 compose(assemble, unaryWriteAssembly),
293 asmResults,
294 "Writing assembly kernels",
295 return_as="list",
296 multiArg=False,
297 )
298
299 writeHelpers(outputPath, kernelHelperObjs, KERNEL_HELPER_FILENAME_CPP, KERNEL_HELPER_FILENAME_H)
300 srcKernelFile = Path(outputPath) / "Kernels.cpp"
301
302 if globalParameters["PythonProfile"]:
303 yappi.stop()
304 yappi.get_func_stats().save("yappi_results.profile", type="callgrind")
305 with open("yappi_results.txt", "w") as f:
306 yappi.get_func_stats().print_all(out=f)
307 if globalParameters["CpuThreads"] != 0:
308 with open("yappi_thread_stats.txt", "w") as f:
309 yappi.get_thread_stats().print_all(out=f)
310
311 if not generateSourcesAndExit:
312 codeObjectFiles += buildAssemblyCodeObjectFiles(
313 asmToolchain.linker,
314 asmToolchain.bundler,
315 asmKernels,
316 destLibPath,
317 assemblyTmpPath,
318 compress,
319 )
320 buildSourceCodeObjectFiles(
321 srcToolchain.compiler,
322 srcToolchain.bundler,
323 destLibPath,
324 objectTmpPath,
325 outputPath,
326 srcKernelFile,
327 cmdlineArchs,
328 )
329
330 return codeObjectFiles, numKernels
331
332
333 def writeSolutionsAndKernelsTCL(
334 outputPath,
335 asmToolchain,
336 srcToolchain,
337 solutions,
338 kernels,
339 kernelHelperObjs,
340 kernelWriterAssembly,
341 cmdlineArchs: List[str],
342 compress=True,
343 ):
344 outputPath = Path(outputPath)
345 destLibPath = ensurePath(
346 outputPath / "library"
347 ) # Destination for code object library files (.co)
348 buildTmpPath = ensurePath(outputPath / "build_tmp" / outputPath.stem.upper())
349 assemblyTmpPath = ensurePath(
350 buildTmpPath / "assembly"
351 ) # Temp path for generated assembly files (.s)
352 objectTmpPath = ensurePath(
353 buildTmpPath / "code_object_tmp"
354 ) # Temp path for HSA code object files (.hsaco)
355
356 asmKernels = [k for k in kernels if k["KernelLanguage"] == "Assembly"]
357
358 visited = set()
359 duplicates = 0
360 splitGSU = False
361 for k in asmKernels:
362 base = getKernelFileBase(splitGSU, k)
363 k["BaseName"] = base
364 k.duplicate = True if base in visited else False
365 duplicates += k.duplicate
366 print2(f"Duplicate: {base}")
367 visited.add(base)
368 print1(f"Number of duplicate kernels: {duplicates}")
369
370 uniqueAsmKernels = [k for k in asmKernels if not k.duplicate]
371
372 def assemble(ret):
373 p, isa, wavefrontsize, result = ret
374 asmToolchain.assembler(isaToGfx(isa), wavefrontsize, str(p), str(p.with_suffix(".o")))
375 return result
376
377 unaryProcessKernelSource = functools.partial(
378 processKernelSource,
379 kernelWriterAssembly,
380 rocisa.rocIsa.getInstance().getData(),
381 splitGSU,
382 )
383
384 unaryWriteAssembly = functools.partial(writeAssembly, assemblyTmpPath)
385 compose = lambda *F: functools.reduce(lambda f, g: lambda x: f(g(x)), F)
386 ret = ParallelMap2(
387 compose(assemble, unaryWriteAssembly, unaryProcessKernelSource),
388 uniqueAsmKernels,
389 "Generating assembly kernels",
390 multiArg=False,
391 return_as="list"
392 )
393 passPostKernelInfoToSolution(
394 ret, uniqueAsmKernels, solutions, splitGSU
395 )
396 # result.src is very large so let garbage collector know to clean up
397 del ret
398 buildAssemblyCodeObjectFiles(
399 asmToolchain.linker,
400 asmToolchain.bundler,
401 asmKernels,
402 destLibPath,
403 assemblyTmpPath,
404 compress,
405 )
406
407 writeHelpers(outputPath, kernelHelperObjs, KERNEL_HELPER_FILENAME_CPP, KERNEL_HELPER_FILENAME_H)
408 srcKernelFile = Path(outputPath) / "Kernels.cpp"
409 buildSourceCodeObjectFiles(
410 srcToolchain.compiler,
411 srcToolchain.bundler,
412 destLibPath,
413 objectTmpPath,
414 outputPath,
415 srcKernelFile,
416 cmdlineArchs,
417 )
418
419 return len(uniqueAsmKernels)
420
421
422 @timing
423 def copyStaticFiles(outputPath):
424 libraryStaticFiles = [
425 "TensileTypes.h",
426 "tensile_bfloat16.h",
427 "tensile_float8_bfloat8.h",
428 "KernelHeader.h",
429 "ReductionTemplate.h",
430 "memory_gfx.h",
431 ]
432
433 for fileName in libraryStaticFiles:
434 shutil.copy(os.path.join(SOURCE_PATH, fileName), outputPath)
435
436 return libraryStaticFiles
437
438
439 @timing
440 def generateKernelObjectsFromSolutions(solutions):
441 kernels = []
442 kernelNames = set()
443 for solution in solutions:
444 solutionKernels = solution.getKernels()
445 for kernel in solutionKernels:
446 kName = getKeyNoInternalArgs(kernel, False)
447 if kName not in kernelNames:
448 kernels.append(kernel)
449 kernelNames.add(kName)
450 return kernels
451
452
453 def generateKernelHelperObjects(solutions: List[Solution], cxxCompiler: str, isaInfoMap):
454 """
455 Generates a unique list of kernel helpers.
456
457 Kernel helpers are used to generate hip source code kernels called
458 before/after gemm kernels. This function creates a minimal list of
459 kernel helpers required to support the solutions reuested in a build.
460 The list of kernel helpers is then used to write Kernels.cpp/h to
461 disk. To ensure the ActivationEnumHeaders are written first, the
462 list is sorted such that those kernel helpers appear first.
463
464 Args:
465 solutions: a list of solutions to process.
466 cxxCompiler: the full path to the cxxCompiler.
467
468 Returns:
469 List of kernel helpers.
470 """
471 khos = []
472 visited = set()
473 for solution in solutions:
474 for kernelHelperType, callable in kernelObjectNameCallables():
475 buildMask = []
476 names = callable(solution)
477 if names:
478 sortByEnum = lambda x: ("Enum" in x, names.index(x))
479 names = sorted(names, key=sortByEnum, reverse=True)
480 for name in names:
481 if name not in visited:
482 visited.add(name)
483 buildMask.append(True)
484 else:
485 buildMask.append(False)
486 if any(buildMask):
487 kho = initHelperKernelObjects(solution, kernelHelperType, cxxCompiler, isaInfoMap)
488 kho = list(itertools.compress(kho, buildMask))
489 if kho:
490 khos.extend(kho)
491 khos = list(set(khos))
492 sortByEnum = lambda x: ("Enum" in x.getKernelName(), khos.index(x))
493 return sorted(khos, key=sortByEnum, reverse=True) # Ensure that we write Enum kernel helpers are first in list
494
495
496 @timing
497 def generateLogicDataAndSolutions(logicFiles, args, assembler: Assembler, isaInfoMap):
498
499 if ";" in args["Architecture"]:
500 archs = args["Architecture"].split(";") # user arg list format
501 else:
502 archs = args["Architecture"].split("_") # workaround for cmake list in list issue
503
504 solutions = []
505 masterLibraries = {}
506 nextSolIndex = 0
507 splitGSU = False
508 printSolutionRejectionReason = True
509 printIndexAssignmentInfo = False
510
511 fIter = zip(
512 logicFiles,
513 itertools.repeat(assembler),
514 itertools.repeat(splitGSU),
515 itertools.repeat(printSolutionRejectionReason),
516 itertools.repeat(printIndexAssignmentInfo),
517 itertools.repeat(isaInfoMap),
518 itertools.repeat(args["LazyLibraryLoading"]),
519 )
520
521 def libraryIter(lib: MasterSolutionLibrary):
522 if len(lib.solutions):
523 for i, s in enumerate(lib.solutions.items()):
524 yield (i, *s)
525 else:
526 for _, lazyLib in lib.lazyLibraries.items():
527 yield from libraryIter(lazyLib)
528
529 for library in ParallelMap2(
530 LibraryIO.parseLibraryLogicFile, fIter, "Loading Logics...", return_as="generator_unordered"
531 ):
532 _, architectureName, _, _, _, newLibrary = library
533
534 if architectureName == "":
535 continue
536
537 if architectureName in masterLibraries:
538 nextSolIndex = masterLibraries[architectureName].merge(newLibrary, nextSolIndex)
539 else:
540 masterLibraries[architectureName] = newLibrary
541 masterLibraries[architectureName].version = args["CodeObjectVersion"]
542
543 # Sort masterLibraries to make global soln index values deterministic
544 solnReIndex = 0
545 masterLibraries = dict(sorted(masterLibraries.items()))
546 for _, masterLibrary in masterLibraries.items():
547 for _, sol in masterLibrary.solutions.items():
548 sol.index = solnReIndex
549 solnReIndex += 1
550 # Sort masterLibrary to make global soln index values deterministic
551 masterLibrary.lazyLibraries = dict(sorted(masterLibrary.lazyLibraries.items()))
552 for name, lib in masterLibrary.lazyLibraries.items():
553 # Sort solns by the lib logic file they were generated from
554 lib.solutions = {
555 k: lib.solutions[k]
556 for k in sorted(lib.solutions, key=lambda idx: lib.solutions[idx].srcName)
557 }
558 for _, sol in lib.solutions.items():
559 sol.index = solnReIndex
560 solnReIndex += 1
561
562 if args["GenSolTable"]:
563 matchTable = {}
564 # Match yaml file solutions to solution index
565 for _, masterLibrary in masterLibraries.items():
566 for _, _, s in libraryIter(masterLibrary):
567 matchTable[s.index] = [s.srcName, s.libraryLogicIndex]
568 LibraryIO.write("MatchTable", matchTable)
569
570 if "fallback" in masterLibraries.keys():
571 for key, value in masterLibraries.items():
572 if key != "fallback":
573 value.merge(masterLibraries["fallback"])
574 masterLibraries.pop("fallback")
575 solIndex = []
576 for _, masterLibrary in masterLibraries.items():
577 for _, sol in masterLibrary.solutions.items():
578 solutions.append(sol.originalSolution)
579 solIndex.append(sol.index)
580 for name, lib in masterLibrary.lazyLibraries.items():
581 for _, sol in lib.solutions.items():
582 sol.originalSolution._state["codeObjectFile"] = name
583 solutions.append(sol.originalSolution)
584 solIndex.append(sol.index)
585
586 # Get the solution index and it's codeObjectFile name
587 codeObjectFilesIndex = {}
588 for solution, index in zip(solutions, solIndex):
589 if "codeObjectFile" in solution._state and solution._state["codeObjectFile"] is not None:
590 if solution._state["codeObjectFile"] in codeObjectFilesIndex:
591 codeObjectFilesIndex[solution._state["codeObjectFile"]] = min(index, codeObjectFilesIndex[solution._state["codeObjectFile"]])
592 else:
593 codeObjectFilesIndex[solution._state["codeObjectFile"]] = index
594
595 # Reorder to int: name format
596 codeObjectFilesIndex = {v: k for k, v in codeObjectFilesIndex.items()}
597 # Reorder to maintain ascending order by index
598 codeObjectFilesIndex = dict(sorted(codeObjectFilesIndex.items()))
599
600 # remove duplicates while preserving order
601 numSoln = len(solutions)
602 solutions = dict.fromkeys(solutions).keys()
603
604 print1(f"Number of solutions parsed: {numSoln}")
605 print1(f"Number of unique solutions: {len(solutions)}")
606
607 return solutions, masterLibraries, codeObjectFilesIndex
608
609
610 ################################################################################
611 # Tensile Create Library
612 ################################################################################
613 @profile
614 def run():
615 start = timer()
616 print1("")
617 print1(HR)
618 print1("# Tensile Create Library")
619 print2(HR)
620 print2("")
621
622 arguments = parseArguments()
623 setVerbosity(arguments["PrintLevel"])
624 outputPath = Path(ensurePath(os.path.abspath(arguments["OutputPath"])))
625 cxxCompiler, _, offloadBundler, _, _ = validateToolchain(
626 arguments["CxxCompiler"],
627 arguments["CCompiler"],
628 arguments["OffloadBundler"],
629 arguments["Assembler"],
630 ToolchainDefaults.HIP_CONFIG,
631 )
632
633 if ";" in arguments["Architecture"]:
634 archs = arguments["Architecture"].split(";")
635 else:
636 archs = arguments["Architecture"].split("_")
637 archs = SUPPORTED_GFX if "all" in archs else archs
638 archs, requestedPredicateMap = splitArchsFromPredicates(archs)
639
640 targetIsas = [gfxToIsa(a) for a in archs]
641 isaInfoMap = makeIsaInfoMap(targetIsas, cxxCompiler)
642 assignGlobalParameters(arguments, isaInfoMap)
643
644 asmToolchain = makeAssemblyToolchain(
645 cxxCompiler,
646 offloadBundler,
647 arguments["CodeObjectVersion"],
648 arguments["BuildIdKind"],
649 arguments["AsmDebug"],
650 )
651 srcToolchain = makeSourceToolchain(
652 cxxCompiler,
653 offloadBundler,
654 arguments["AsanBuild"],
655 arguments["BuildIdKind"],
656 save_temps=False
657 )
658
659 print1(asmToolchain.assembler)
660 print1(asmToolchain.bundler)
661
662 if not os.path.exists(arguments["LogicPath"]):
663 printExit(f"LogicPath {arguments['LogicPath']} doesn't exist")
664
665 logicExtFormat = ".yaml"
666 if arguments["LogicFormat"] == "yaml":
667 pass
668 elif arguments["LogicFormat"] == "json":
669 logicExtFormat = ".json"
670 else:
671 printExit(f"Unrecognized LogicFormat: {arguments['LogicFormat']}")
672
673 def archMatch(arch: str, archs: List[str]):
674 return (arch in archs) or any(a.startswith(arch) for a in archs)
675
676 def validLogicFile(p: Path):
677 return p.suffix == logicExtFormat and (
678 "all" in archs or archMatch(load_logic_gfx_arch(p), archs)
679 )
680
681 globPattern = os.path.join(
682 arguments["LogicPath"], f"**/{arguments['LogicFilter']}{logicExtFormat}"
683 )
684 print1(f"# LogicFilter: {globPattern}")
685 logicFiles = [
686 file for file in glob.iglob(globPattern, recursive=True)
687 ]
688
689 logicFiles = [file for file in logicFiles if validLogicFile(Path(file))]
690
691 print1(f"# Experimental: {arguments['Experimental']}")
692 if not arguments["Experimental"]:
693 logicFiles = [
694 file for file in logicFiles if "experimental" not in map(str.lower, Path(file).parts)
695 ]
696
697 print1("# Archs: " + ' ,'.join(archs))
698 if requestedPredicateMap:
699 print1("# Predicates:\n" + "\n".join(f"# {arch}: {', '.join(v) if v else 'all variants'}" for arch, v in requestedPredicateMap.items()))
700 numPrior = len(logicFiles)
701 logicFiles = filterLogicFilesByPredicates(logicFiles, requestedPredicateMap)
702 print1(f"# Filtered {numPrior - len(logicFiles)} logic files not matching requested predicates")
703
704 print1(f"# LibraryLogicFiles: {len(logicFiles)}")
705
706 for logicFile in logicFiles:
707 print2("# %s" % logicFile)
708
709 start_glds = timer()
710 solutions, masterLibraries, libraryMapping = generateLogicDataAndSolutions(
711 logicFiles, arguments, asmToolchain.assembler, isaInfoMap
712 )
713 stop_glds = timer()
714 print(f"Time to load yaml files (s): {(stop_glds-start_glds):3.2f}")
715
716
717 kernels = generateKernelObjectsFromSolutions(solutions)
718 kernelHelperObjs = generateKernelHelperObjects(kernels, str(asmToolchain.assembler.path), isaInfoMap)
719 kernelWriterAssembly = KernelWriterAssembly(asmToolchain.assembler, DebugConfig())
720
721 copyStaticFiles(outputPath)
722
723 start_wsk = timer()
724 numKernels = writeSolutionsAndKernelsTCL(
725 outputPath,
726 asmToolchain,
727 srcToolchain,
728 solutions,
729 kernels,
730 kernelHelperObjs,
731 kernelWriterAssembly,
732 archs,
733 compress=arguments["UseCompression"],
734 )
735 stop_wsk = timer()
736 print(f"Time to generate kernels (s): {(stop_wsk-start_wsk):3.2f}")
737
738 archs = [ # is this really different than the other archs above?
739 isaToGfx(arch)
740 for arch in targetIsas
741 if isaInfoMap[arch].asmCaps["SupportedISA"]
742 ]
743 newLibraryDir = ensurePath(os.path.join(outputPath, "library"))
744 splitGSU = False
745
746 solDict = {}
747 for solution in solutions:
748 solutionKernels = solution.getKernels()
749 for kernel in solutionKernels:
750 kName = getKeyNoInternalArgs(kernel, False)
751 if kName not in solDict:
752 solDict["%s"%kName] = kernel
753
754 def writeMsl(name, lib):
755 filename = os.path.join(newLibraryDir, name)
756 lib.applyNaming(splitGSU)
757 LibraryIO.write(filename, state(lib), arguments["LibraryFormat"])
758
759 filename = os.path.join(newLibraryDir, "TensileLiteLibrary_lazy_Mapping")
760 LibraryIO.write(filename, libraryMapping, "msgpack")
761
762 start_msl = timer()
763 for archName, newMasterLibrary in masterLibraries.items():
764 if archName in archs:
765 if arguments["LazyLibraryLoading"]:
766 masterFile = os.path.join(newLibraryDir, "TensileLibrary_lazy_" + archName)
767 else:
768 masterFile = os.path.join(newLibraryDir, "TensileLibrary_" + archName)
769 newMasterLibrary.applyNaming(splitGSU)
770 LibraryIO.write(masterFile, state(newMasterLibrary), arguments["LibraryFormat"])
771
772 for name, lib in newMasterLibrary.lazyLibraries.items():
773 for k, s in lib.solutions.items():
774 kName = getKeyNoInternalArgs(s.originalSolution, splitGSU)
775 s.sizeMapping.CUOccupancy = solDict["%s"%kName]["CUOccupancy"]
776
777 ParallelMap2(writeMsl,
778 newMasterLibrary.lazyLibraries.items(),
779 "Writing master solution libraries",
780 return_as="list")
781 stop_msl = timer()
782 print(f"Time to write master solution libraries (s): {(stop_msl-start_msl):3.2f}")
783
784 if not arguments["KeepBuildTmp"]:
785 buildTmp = Path(arguments["OutputPath"]).parent / "library" / "build_tmp"
786 if buildTmp.exists() and buildTmp.is_dir():
787 shutil.rmtree(buildTmp)
788 buildTmp = Path(arguments["OutputPath"]) / "build_tmp"
789 if buildTmp.exists() and buildTmp.is_dir():
790 shutil.rmtree(buildTmp)
791 else:
792 printWarning(f"Cannot remove build_tmp")
793
794 print("# Tensile Library Writer DONE")
795 print(HR)
796 print("")
797
798 stop = timer()
799
800 print(f"Total time (s): {(stop-start):3.2f}")
801 print(f"Total kernels processed: {numKernels}")
802 print(f"Kernels processed per second: {(numKernels/(stop-start)):3.2f}")
803 print(f"KernelHelperObjs: {len(kernelHelperObjs)}")