Debian Codegraph @

tensilelite/Tensile/KernelWriterActivationFunction.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 cop-
9 # ies of the Software, and to permit persons to whom the Software is furnished
10 # to do so, subject to the following conditions:
11 #
12 # The above copyright notice and this permission notice shall be included in all
13 # copies or substantial portions of the Software.
14 #
15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM-
16 # PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17 # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18 # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19 # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNE-
20 # CTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 ################################################################################
22
23 from copy import deepcopy
24 from typing import List
25
26 from rocisa import rocIsa
27
28 from Tensile.Activation import ActivationInline, ActivationType
29 from Tensile.Common.Architectures import isaToGfx, IsaVersion
30 from Tensile.KernelWriterBase import KernelWriterBase
31
32 class KernelWriterActivationFunction(KernelWriterBase):
33
34 def __init__(self, state, cxxCompiler: str, supportedISA: List[IsaVersion]):
35 super().__init__()
36 self.cxxCompiler = cxxCompiler
37 self.state["ProblemType"] = deepcopy(state["ProblemType"])
38 self.state["Kernel"] = state["Kernel"]
39
40 self.actGradientPrefix = ""
41 self.actExportType = ActivationType.Export.NORMAL
42 if self.state["ProblemType"]["Gradient"]:
43 self.actGradientPrefix = "Gradient"
44 self.actExportType = ActivationType.Export.GRADONLY
45 self.gaurdStr = "NG" if self.state["ProblemType"]["ActivationNoGuard"] else ""
46
47 self.enumName = "Tensile::%sActivationType_%s"%(self.actGradientPrefix, \
48 self.state["ProblemType"]["ActivationComputeDataType"])
49
50 self.supportedArchs = supportedISA
51
52 # derive parameter
53 self.language = "HIP"
54 self.kernelName = self.getKernelName()
55
56 def keys(self):
57 return self.getKernelName()
58
59 @staticmethod
60 def kernelName(solution):
61 state = solution._state if hasattr(solution, "_state") else solution.state
62 actGradientPrefix = "Gradient" if state["ProblemType"]["Gradient"] else ""
63 gaurdStr = "NG" if state["ProblemType"]["ActivationNoGuard"] else ""
64 return "Tensile%sActivation%s_%s_%s"%(actGradientPrefix, \
65 gaurdStr, \
66 state["ProblemType"]["ActivationComputeDataType"].toChar(), \
67 state["ProblemType"]["ActivationType"])
68
69 def getKernelName(self):
70 return KernelWriterActivationFunction.kernelName(self)
71
72 def getSourceFileString(self):
73 fileString = "// This is a dummy file."
74 return (0, fileString)
75
76 def functionSignature(self):
77 kStr = ""
78
79 ptrStr = self.state["ProblemType"]["ActivationComputeDataType"].toDevice("HIP")
80 names = ""
81 if self.state["ProblemType"]["ActivationType"] in ['all', 'hipblaslt_all']:
82 names += ",\n"
83 names += " %s const activationType"%self.enumName
84 for name in self.state["ProblemType"]["ActivationType"].getAdditionalArgStringList(False):
85 names += ",\n"
86 names += " %s const %s"%(ptrStr, name)
87 changeLine = "\n " if names else ""
88 kStr += "__device__ inline %s activation%s(%s%s value%s)\n{\n"%(ptrStr, self.gaurdStr, changeLine, ptrStr, names)
89 return kStr
90
91 def getInlineAsm(self, activation: ActivationInline, spaces: int, activationType: str):
92 activationStrList = []
93
94 isa = tuple(self.state["Kernel"]["ISA"])
95 tf = rocIsa.getInstance()
96 if not tf.isInit():
97 tf.init(isa, self.cxxCompiler)
98 tf.setKernel(isa, self.state["Kernel"]["WavefrontSize"])
99
100 for arch in self.supportedArchs:
101 tf.init(arch, self.cxxCompiler)
102 tf.setKernel(arch, self.state["Kernel"]["WavefrontSize"])
103 activationStrList.append(activation.generateInlineAssemblyBody(spaces, activationType))
104
105 activationStrSetList = list(set(activationStrList))
106 # Return if all codes are the same.
107 if len(activationStrSetList) == 1:
108 return activationStrList[0]
109
110 # Categorize them.
111 cateArch = [[] for _ in range(len(activationStrSetList))]
112 for idx, actStr in enumerate(activationStrList):
113 for i, actSetStr in enumerate(activationStrSetList):
114 if actStr == actSetStr:
115 cateArch[i].append(tuple(self.supportedArchs[idx]))
116 break
117
118 # create marcos
119 defineStr = []
120 macroStr = "#if"
121 for archList in cateArch:
122 defStr = "%s defined(__%s__)"%(macroStr, isaToGfx(archList[0]))
123 for arch in archList:
124 defStr += "|| defined(__%s__)"%isaToGfx(arch)
125 defStr += "\n"
126 defineStr.append(defStr)
127 macroStr = "#elif"
128
129 kStr = ""
130 # Insert activation inline codes to fileString
131 for i, defStr in enumerate(defineStr):
132 kStr += defStr
133 kStr += activationStrSetList[i]
134 kStr += "#endif\n"
135 return kStr
136
137 def getHeaderFileString(self):
138 if self.state["ProblemType"]["ActivationType"] == 'none':
139 return fileString
140
141 isa = tuple(self.state["Kernel"]["ISA"])
142 tf = rocIsa.getInstance()
143 tf.init(isa, self.cxxCompiler)
144 tf.setKernel(isa, self.state["Kernel"]["WavefrontSize"])
145
146 activationCDataType = self.state["ProblemType"]["ActivationComputeDataType"]
147 activationType = self.state["ProblemType"]["ActivationType"]
148 tf.setKernel(tuple(self.state["Kernel"]["ISA"]), self.state["Kernel"]["WavefrontSize"])
149 activation = ActivationInline(activationCDataType, not self.state["ProblemType"]["ActivationNoGuard"])
150
151 fileString = "" # CHeader
152 fileString += "#pragma clang diagnostic push\n"
153 fileString += "#pragma clang diagnostic ignored \"-Winline-asm\"\n"
154 fileString += self.functionSignature()
155 if activationType in ['all', 'hipblaslt_all']:
156 supportedBy = ActivationType.SupportedBy.ALL if activationType == 'all' else ActivationType.SupportedBy.HIPBLASLT
157 for index, enumStr in enumerate(ActivationType.getEnumStrList(activationCDataType, \
158 supportedBy, \
159 includeNone=False, \
160 exportType=self.actExportType)):
161 if index == 0:
162 fileString += " if (activationType == %s::%s) {\n"%(self.enumName, ActivationType(enumStr).toEnum())
163 else:
164 fileString += " else if (activationType == %s::%s) {\n"%(self.enumName, ActivationType(enumStr).toEnum())
165 fileString += self.getInlineAsm(activation, 4, enumStr)
166 fileString += " }"
167 fileString += "\n"
168 else:
169 fileString += self.getInlineAsm(activation, 2, self.state["ProblemType"]["ActivationType"])
170 fileString += " return value;\n"
171 fileString += "}\n"
172 fileString += "#pragma clang diagnostic pop\n"
173
174 return fileString