Debian Codegraph @

tensilelite/Tensile/TensileLogic/HandleCustomKernel.py

raw symbols SCIP
1 ################################################################################
2 #
3 # Copyright (C) 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
26 from pprint import pformat
27 from pathlib import Path
28 from typing import Dict, Tuple
29
30 from Tensile.Common import print1, IsaVersion, IsaInfo
31 from Tensile.SolutionStructs.Validators.MatrixInstruction import matrixInstructionToMIParameters
32
33 from Tensile.CustomKernels import isCustomKernelConfig, getCustomKernelConfig
34 from Tensile import CUSTOM_KERNEL_PATH
35
36
37 def handleCustomKernel(sol: dict, isaInfoMap: Dict[IsaVersion, IsaInfo]) -> Tuple[dict, bool]:
38 """
39 Process custom kernel configuration for a given solution.
40
41 Args:
42 sol: Dictionary containing the solution.
43 isaInfoMap: Dictionary mapping IsaVersion to IsaInfo.
44
45 Returns:
46 A tuple containing the updated solution dictionary and a boolean indicating
47 whether the solution uses a custom kernel.
48 """
49 if not isCustomKernelConfig(sol):
50 return sol, False
51
52 name = sol["CustomKernelName"]
53 dir = CUSTOM_KERNEL_PATH
54 config = getCustomKernelConfig(name, {}, dir)
55 sol.update(config)
56
57 mi = sol["MatrixInstruction"]
58 print1(f">> Found custom kernel: {name} with MI {mi}")
59
60 if not (len(mi) == 4 or len(mi) == 0):
61 print1(
62 f">> Error: Custom kernels in logic files should have 'MatrixInstruction' of length 4 or 0, not length {len(mi)}"
63 )
64 mi = sol["MatrixInstruction"]
65 isa = next(iter(isaInfoMap.keys()))
66 wavefrontSize = sol["WavefrontSize"]
67 ptype = sol["ProblemType"]
68 workgroup = sol.get("WorkGroup", None)
69 miParams = matrixInstructionToMIParameters(
70 mi, isa, wavefrontSize, ptype, workgroup, isaInfoMap
71 )
72 print1(
73 f">> Hint: Replace 'MatrixInstruction' in {name}.s with following diff:\n"
74 f"{prepareCustomKernelConfig(miParams, mi)}"
75 )
76 return sol, True
77
78
79 def hasCustomKernel(file: Path) -> bool:
80 """
81 Check if the given logic file contains at least one custom kernel.
82
83 Args:
84 file: Path to a logic file.
85
86 Returns:
87 True if the logic file contains at least one custom kernel.
88 """
89 with open(file, "r") as f:
90 for line in f:
91 l = line.strip()
92 if l.startswith("CustomKernelName:") and not l.endswith("''"):
93 return True
94 return False
95
96
97 def prepareCustomKernelConfig(miParams: dict, prevMi: list) -> str:
98 """
99 Formats fields on custom kernel configuration to be used by developers to update
100 prototype custom kernel configuration for production serialized logic files.
101
102 Args:
103 miParams: Dictionary of matrix instruction parameters.
104
105 Returns:
106 A string containing formatted fields for the custom kernel configuration.
107 """
108 pformatStr = pformat(miParams)
109 # Remove the dictionary braces and split into lines
110 lines = pformatStr.strip("{}").split("\n")
111 formattedLines = []
112 for line in lines:
113 line = line.strip()
114 # Remove the 'ISA' line as it is not needed in the output
115 if line.startswith("'ISA'"):
116 continue
117 line = line.replace("'", "")
118 line = "+ " + line
119 formattedLines.append(line[:-1] if line.endswith(",") else line)
120 result = "\n".join(formattedLines)
121
122 result = f"- MatrixInstruction: {prevMi}\n" + result
123 return result