Debian Codegraph @

tensilelite/Tensile/SolutionStructs/Validators/MatrixInstruction.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 import pprint
26 from typing import Dict, Optional
27
28 from Tensile.Common import IsaVersion, IsaInfo, print2, elineno
29 from Tensile.Common.Architectures import SUPPORTED_ISA
30 from Tensile.Common.DataType import DataType
31 from Tensile.Common.ValidParameters import makeValidMatrixInstructions, makeValidMFMA, makeValidSMFMA, makeValidWMMA
32
33 from ..Utilities import reject
34
35 MI_KEY: str = "MatrixInstruction"
36 MI_ENABLED_KEY: str = "EnableMatrixInstruction"
37
38 def matrixInstructionToMIParameters(
39 mi: list,
40 isa: IsaVersion,
41 wavefrontSize: int,
42 problemType: dict,
43 workGroup: Optional[list],
44 isaInfoMap: Dict[IsaVersion, IsaInfo]
45 ):
46 """
47 Converts a 9-item matrix instruction into the associated 4-item representation and
48 populates supporting MI parameters.
49
50 Args:
51 mi: The matrix instruction to convert. Must have length 9.
52 isa: The ISA tuple.
53 wavefrontSize: The wavefront size. Typically "WavefrontSize" in a solution.
54 problemType: The problem type dictionary. Typically "ProblemType" in a solution.
55 """
56 print2(f">> Converting MatrixInstruction {mi} to MI parameters")
57
58 if len(mi) != 9:
59 raise ValueError(f"MatrixInstruction must be 9 items long to convert into MI"
60 f" Parameters, found {mi} with length {len(mi)}")
61
62 result = {}
63 result["ISA"] = isa
64
65 # Enable F32 XDL math operation only when the input type is f32.
66 enableF32xdl = (
67 "F32XdlMathOp" in problemType
68 and not problemType["F32XdlMathOp"].isSingle()
69 and problemType["DataType"].isSingle()
70 )
71 result["EnableF32XdlMathOp"] = enableF32xdl
72
73 mi4 = [mi[0], mi[1], mi[2], mi[3]]
74 result["MatrixInstruction"] = mi4
75 result["EnableMatrixInstruction"] = True
76 result["MatrixInstM"] = mi[0]
77 result["MatrixInstN"] = mi[1]
78 result["MatrixInstK"] = mi[2]
79 result["MatrixInstB"] = mi[3]
80
81 waves = mi[7]* mi[8]
82 wg0 = mi[4] * mi[0] * mi[7]
83
84 result["WavefrontSize"] = wavefrontSize
85 if workGroup:
86 # NOTE: Typically, the WorkGroup is set to the default [16, 16, 1] for a
87 # length-9 matrix instruction. However, some custom kernel solutions used
88 # during benchmarking don't have WorkGroup set at all.
89 result["WorkGroup"] = [wg0, waves*wavefrontSize//wg0, workGroup[2]]
90 result["ThreadTile"] = [1, 1] # dummy
91
92 isSparse = problemType.get("Sparse", 0)
93 miDataType = DataType(
94 problemType["DataType"]
95 if not enableF32xdl
96 else problemType["F32XdlMathOp"]
97 )
98
99 validMFMA = makeValidMFMA()
100 result["MFMA_BF16_1K"] = (
101 not isSparse
102 and isaInfoMap[isa].asmCaps["HasMFMA"]
103 and not (miDataType.toChar() in validMFMA and mi4 in validMFMA[miDataType.toChar()])
104 and miDataType.isBFloat16()
105 and mi4 in validMFMA["B1k"]
106 )
107
108 # set MIBlock
109 MIBlockBM = wg0 // mi[0]
110 MIBlockBM = min(MIBlockBM, mi[3])
111 MIBlockBN = mi[3] // MIBlockBM
112 result["MatrixInstBM"] = MIBlockBM
113 result["MatrixInstBN"] = MIBlockBN
114 result["MIBlock"] = [mi[0], mi[1], mi[2], mi[3], MIBlockBM, MIBlockBN]
115
116 # set MIWaveGroup
117 miwg0 = min((wg0 // mi[0]) // MIBlockBM, waves)
118 result['MIWaveGroup'] = [miwg0, waves // miwg0]
119
120 # set MIWaveTile
121 result['MIWaveTile'] = [mi[5], mi[6]]
122
123 # set MIInputPerThread
124 hasMFMA = isaInfoMap[isa].asmCaps["HasMFMA"]
125 hasWMMA = isaInfoMap[isa].asmCaps["HasWMMA"]
126
127 result['MIInputPerThread'] = mi[0] * mi[2] * mi[3] // wavefrontSize
128 if (not hasMFMA) and hasWMMA and (isa[0] == 10 or isa[0] == 11):
129 result['MIInputPerThread'] = mi[2]
130
131 sparseA = False if not isSparse else False if isSparse == 2 else True
132 sparseB = False if not isSparse else True if isSparse == 2 else False
133 result['MIInputPerThreadA'] = result['MIInputPerThread'] if not sparseA else result['MIInputPerThread'] // 2
134 result['MIInputPerThreadB'] = result['MIInputPerThread'] if not sparseB else result['MIInputPerThread'] // 2
135 result['MIInputPerThreadMetadata'] = result['MIInputPerThread'] if not isSparse else result['MIInputPerThread'] // 8
136
137 print2(f">> MI Parameters: {pprint.pformat(result)}")
138 return result
139
140
141 def validateMIParameters(
142 solution: dict, isaInfoMap: Dict[IsaVersion, IsaInfo], printSolutionRejectionReason: bool = True
143 ):
144 """
145 Validates matrix instruction (MI) related parameters in the given solution.
146
147 This function performs the following checks:
148 - Ensures that "MatrixInstruction" is of length 4.
149 - Ensures that the solution contains the required keys for matrix instruction support.
150 - Ensures that the matrix instruction is not empty when it is enabled.
151 - Validates that the matrix instruction is in the list of valid matrix instructions.
152 - Validates the work group dimensions.
153 - Checks if the matrix instruction is supported by the assembler capabilities (MFMA or WMMA).
154 - Validates the input per thread for sparse and non-sparse configurations.
155 - Validates the matrix instruction block, wave group, and wave tile dimensions.
156 - If the matrix instruction has 4 elements, it ensures that matrix instructions are enabled.
157 - If the matrix instruction is empty, it ensures that matrix instructions are disabled.
158
159 Args:
160 solution: The solution to validate.
161 isaInfoMap: The map of ISA versions to assembler and architecture capabilities.
162 filepath: The path to the file containing the solution.
163
164 Raises:
165 AssertionError: If any of the validation checks fail.
166 """
167 validMatrixInstructions = makeValidMatrixInstructions()
168 validMFMA = makeValidMFMA()
169 validSMFMA = makeValidSMFMA()
170 validWMMA = makeValidWMMA()
171
172 assert MI_KEY in solution, elineno() + ": missing MatrixInstruction"
173 assert MI_ENABLED_KEY in solution, elineno() + ": missing EnableMatrixInstruction"
174 assert not (solution[MI_KEY] == [] and solution[MI_ENABLED_KEY] == True), (
175 elineno() + ": MI empty but enabled"
176 )
177
178 isa = IsaVersion(*solution["ISA"])
179 assert isa in SUPPORTED_ISA, elineno() + ": Unsupported ISA: " + str(isa)
180 # TODO: Temporary until all 940/941 ISAs are removed
181 if (9, 4, 0) <= isa <= (9, 4, 1):
182 isa = (9, 4, 2)
183
184 ptype = solution["ProblemType"]
185 isSparse = ptype.get("Sparse", 0)
186 miDataType = DataType(
187 ptype["DataType"]
188 if not solution.get("EnableF32XdlMathOp", False)
189 else ptype["F32XdlMathOp"]
190 )
191
192 mi4 = solution[MI_KEY]
193 miEnabled = solution[MI_ENABLED_KEY]
194 assert len(mi4) == 4 or len(mi4) == 0, elineno() + ": MI length not 4 or 0"
195 if len(mi4) == 0:
196 assert miEnabled == False, elineno()
197 return True
198
199 assert solution["MatrixInstM"] == mi4[0]
200 assert solution["MatrixInstN"] == mi4[1]
201 assert solution["MatrixInstK"] == mi4[2]
202 assert solution["MatrixInstB"] == mi4[3]
203
204 assert mi4 in validMatrixInstructions, f"{elineno()} : invalid MI4: {str(mi4)} for type {miDataType.toChar()}"
205
206 mi9 = [mi4[0], mi4[1], mi4[2], mi4[3]]
207 assert "MatrixInstBM" in solution, elineno() + ": missing MatrixInstBM"
208 mi9.append(solution["MatrixInstBM"])
209 assert "MIWaveTile" in solution, elineno() + ": missing MIWaveTile"
210 mi9.extend(solution["MIWaveTile"])
211 assert "MIWaveGroup" in solution, elineno() + ": missing MIWaveGroup"
212 mi9.extend(solution["MIWaveGroup"])
213
214 assert len(mi4) == 4 and len(mi9) == 9, elineno() + " MI4: " + str(mi4) + " MI9: " + str(mi9)
215
216 if not miEnabled:
217 return False
218
219
220 wfsize = solution["WavefrontSize"]
221 waves = solution["MIWaveGroup"][0] * solution["MIWaveGroup"][1]
222 wg0 = mi9[4] * mi9[0] * mi9[7] # Work group 0
223
224 hasMFMA = isaInfoMap[isa].asmCaps["HasMFMA"]
225 hasWMMA = isaInfoMap[isa].asmCaps["HasWMMA"]
226
227 miBlock = solution["MIBlock"]
228 miWaveGroup = solution["MIWaveGroup"]
229 miWaveTile = solution["MIWaveTile"]
230
231 if not isSparse:
232 if hasMFMA:
233 if not (miDataType.toChar() in validMFMA and mi4 in validMFMA[miDataType.toChar()]):
234 if miDataType.isBFloat16() and mi4 in validMFMA["B1k"]: # but is valid bf16 MFMA
235 assert solution["MFMA_BF16_1K"], elineno()
236 else:
237 return not reject(
238 solution,
239 printSolutionRejectionReason,
240 f"Invalid MFMA configuration: {solution}",
241 )
242 elif hasWMMA and (not mi4 in validWMMA):
243 return not reject(
244 solution, printSolutionRejectionReason, f"Invalid WMMA configuration: {solution}"
245 )
246 else:
247 if not (miDataType.toChar() in validSMFMA and mi4 in validSMFMA[miDataType.toChar()]):
248 return not reject(
249 solution, printSolutionRejectionReason, f"Invalid SMFMA configuration: {solution}"
250 )
251
252 # Check MIBlock
253 assert miBlock[0] == mi4[0], elineno()
254 assert miBlock[1] == mi4[1], elineno()
255 assert miBlock[2] == mi4[2], elineno()
256 assert miBlock[3] == mi4[3], elineno()
257 assert miBlock[4] == min(wg0 // mi4[0], mi4[3]), elineno()
258 assert miBlock[5] == mi4[3] // miBlock[4], elineno()
259
260 # Check MIWaveGroup
261 assert miWaveGroup[0] == min((wg0 // mi4[0]) // miBlock[4], waves), elineno()
262 assert miWaveGroup[1] == waves // miWaveGroup[0], elineno()
263
264 # Check MIWaveTile
265 assert miWaveTile[0] == mi9[5], elineno()
266 assert miWaveTile[1] == mi9[6], elineno()
267
268 # Check MIInputPerThread
269 miInputPerThread = solution["MIInputPerThread"]
270
271 if (not hasMFMA) and hasWMMA:
272 if isa[0] == 10 or isa[0] == 11:
273 assert miInputPerThread == mi4[2], elineno()
274
275 # If Navi architecture, the input per thread is different
276 if IsaVersion(10, 0, 0) <= isa <= IsaVersion(11, 5, 1):
277 assert miInputPerThread == mi4[2], elineno()
278 else:
279 assert miInputPerThread == mi4[0] * mi4[2] * mi4[3] // wfsize, f"{elineno()} MIInputPerThread: {miInputPerThread} != {mi4[0]} * {mi4[2]} * {mi4[3]} / {wfsize} = {mi4[0] * mi4[2] * mi4[3] // wfsize}"
280
281 if "MIInputPerThreadA" in solution:
282 miInputPerThreadA = solution["MIInputPerThreadA"]
283 sparseA = False if not isSparse else False if isSparse == 2 else True
284 assert miInputPerThreadA == miInputPerThread if not sparseA else miInputPerThread // 2, elineno()
285
286 if "MIInputPerThreadB" in solution:
287 miInputPerThreadB = solution["MIInputPerThreadB"]
288 sparseB = False if not isSparse else True if isSparse == 2 else False
289 assert miInputPerThreadB == miInputPerThread if not sparseB else miInputPerThread // 2, elineno()
290
291 if "MIInputPerThreadMetadata" in solution:
292 miInutPerThreadMeta = solution["MIInputPerThreadMetadata"]
293 assert miInutPerThreadMeta == miInputPerThread if not isSparse else miInputPerThread // 8, elineno()
294 return True