Debian Codegraph @

tensilelite/Tensile/Components/SumUnroll.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 rocisa.code import RegSet, Module
26 from rocisa.container import EXEC, vgpr, sgpr, SDWAModifiers, DSModifiers, ContinuousRegister
27 from rocisa.enum import SelectBit
28 from rocisa.instruction import DSStoreB16, DSStoreB32, DSStoreB64, SBarrier, \
29 SMovB32, SSetMask, VAddF32, VAddU32, VCmpXEqU32, VCvtPkBF8toF32, VCvtPkFP8toF32, \
30 VDot2F32BF16, VDot2F32F16, VLShiftLeftB32, VMovB32, VCvtBF16toFP32
31 from rocisa.functions import vectorStaticDivide, vectorStaticRemainder, vectorStaticMultiply
32 from ..Component import SumUnroll
33 from ..Common import printExit, log2
34
35 class SumUnrollMfma(SumUnroll):
36 kernel = {"EnableMatrixInstruction": True}
37
38 """
39 Sum unroll for reduction
40 Use the same pattern as mfma
41 """
42 def __call__(self):
43 assert(0)
44
45 def initSumUnroll(self, writer, kernel):
46 imod = Module("initSumUnroll")
47 idx = 0
48 while idx < writer.states.bias.numVgprValu:
49 imod.add(VMovB32(dst=vgpr("ValuSum+%d"%idx), src=0, comment="reset 0"))
50 idx += 1
51
52 # Init sum unroll, create pack for dot if needed
53 # Unregister is in storeSumLDS
54 if kernel["ProblemType"]["DataType"].numRegisters() < 1:
55 if kernel["ProblemType"]["DataType"].isHalf():
56 writer.defineSgpr("SumUnrollConstOne", 1)
57 imod.add(RegSet("s", "sgprSumUnrollConstOne", writer.sgprs["SumUnrollConstOne"]))
58 imod.add(SMovB32(dst=sgpr("SumUnrollConstOne"), src=hex(0x3c003c00), comment="packed 1.0"))
59 elif kernel["ProblemType"]["DataType"].isBFloat16() and writer.states.asmCaps['v_dot2_f32_bf16']:
60 writer.defineSgpr("SumUnrollConstOne", 1)
61 imod.add(RegSet("s", "sgprSumUnrollConstOne", writer.sgprs["SumUnrollConstOne"]))
62 imod.add(SMovB32(dst=sgpr("SumUnrollConstOne"), src=hex(0x3F803F80), comment="packed 1.0"))
63 else:
64 assert "[initSumUnroll] Unsupported data type"
65 return imod
66
67 def loopSum(self, writer, kernel, tP, u, innerUnroll):
68 tc = tP["tensorChar"]
69 imod = Module("SumUnroll%s_I%s" % (tc, innerUnroll))
70
71 m = (u) % (writer.states.numVgprBuffer) # local to use for MACs
72
73 # calculate constant
74 numRegistersIn = kernel["ProblemType"]["DataType"].numRegisters()
75 numMIInput = kernel["MIInputPerThread%s"%tc]
76 vgprPerInput = int(numMIInput * numRegistersIn)
77
78 if tc == "A":
79 waveTile = kernel["MIWaveTile"][0]
80 numIterPerCoalescedRead = writer.states.numIterPerCoalescedReadA
81 numReadsIterCoalesced = writer.states.numReadsIterCoalescedA
82 elif tc == "B":
83 waveTile = kernel["MIWaveTile"][1]
84 numIterPerCoalescedRead = writer.states.numIterPerCoalescedReadB
85 numReadsIterCoalesced = writer.states.numReadsIterCoalescedB
86 else:
87 printExit("Unsupported tc %s"%tc)
88 # here we remap index to where it read for wider local read
89 # ex. if we read 2 iteration at a time,
90 # original : _ds_load_b64 valuA_X0_I0
91 # read 2 iter: _ds_load_b128 valuA_X0_I0 (we read valuA_X0_I0 and valuA_X1_I0)
92 # instead of using valuA_X1_I0, we use valuA_X0_I0+2 as mfma input
93
94 vgprBuffer_new = (m//numIterPerCoalescedRead)*numIterPerCoalescedRead
95 vgprBuffer_new_offset = m%numIterPerCoalescedRead*kernel["InnerUnroll"]*vgprPerInput
96
97 if kernel["ProblemType"]["DataType"].isBFloat16():
98 hiBitsMaskVgpr = writer.vgprPool.checkOut(1)
99 imod.add(VMovB32(dst=vgpr(hiBitsMaskVgpr), src=hex(0xffff0000), comment="mask 0xffff0000 for pack two bfloat16 element to 32bit"))
100
101 for iui in range(0, innerUnroll):
102 iui_new = (iui//numReadsIterCoalesced)*numReadsIterCoalesced
103 iui_new_offset = iui%numReadsIterCoalesced*vgprPerInput
104 for idx in range(0, waveTile):
105 new = idx*vgprPerInput*numReadsIterCoalesced
106 # valuStr = "Valu%s_X%u_I%u+%u+%u+%u" % (tc, vgprBuffer_new, iui_new, new, vgprBuffer_new_offset, iui_new_offset)
107 valuStr = "Valu%s_X%u_I%u+%u+%u" % (tc, vgprBuffer_new, iui_new, new, vgprBuffer_new_offset)
108 valuSumStr = "ValuSum+%u"%idx
109 # If direct ot vgpr, use "G2LA+%u+%u+%u", currently not supported
110 if kernel["ProblemType"]["DataType"].isHalf():
111 # First version only supports mfma with K > 1
112 if vgprPerInput > 1 and (vgprPerInput % 2 == 0):
113 for inputIdx in range(0, vgprPerInput):
114 imod.add(VDot2F32F16(dst=vgpr(valuSumStr), src0=vgpr("%s+%s"%(valuStr, iui_new_offset + inputIdx)), src1=sgpr("SumUnrollConstOne"), src2=vgpr(valuSumStr), comment="sum K"))
115 else:
116 printExit("Currently unsupported vgprPerInput %u"%vgprPerInput)
117 elif kernel["ProblemType"]["DataType"].isSingle():
118 inputIdx = 0
119 while inputIdx < vgprPerInput:
120 imod.add(VAddF32(dst=vgpr(valuSumStr), src0=vgpr("%s+%s"%(valuStr, iui_new_offset + inputIdx)), src1=vgpr(valuSumStr), comment="sum K"))
121 inputIdx += 1
122 elif kernel["ProblemType"]["DataType"].isBFloat16():
123 # BF16 BiasSrcA,B
124 tmpVgpr = writer.vgprPool.checkOutAligned(2,2)
125 if vgprPerInput > 1 and (vgprPerInput % 2 == 0):
126 for inputIdx in range(0, vgprPerInput):
127 if writer.states.asmCaps['v_dot2_f32_bf16']:
128 imod.add(VDot2F32BF16(dst=vgpr(valuSumStr), src0=vgpr("%s+%s"%(valuStr, iui_new_offset + inputIdx)), src1=sgpr("SumUnrollConstOne"), src2=vgpr(valuSumStr), comment="sum K"))
129 else:
130 imod.add(VCvtBF16toFP32(dst=vgpr(tmpVgpr), src=vgpr("%s+%s"%(valuStr, iui_new_offset + inputIdx)), vgprMask=None, vi=0))
131 imod.add(VCvtBF16toFP32(dst=vgpr(tmpVgpr+1), src=vgpr("%s+%s"%(valuStr, iui_new_offset + inputIdx)), vgprMask=vgpr(hiBitsMaskVgpr), vi=1))
132 imod.add(VAddF32(dst=vgpr(valuSumStr), src0=vgpr(tmpVgpr), src1=vgpr(valuSumStr), comment="sum K"))
133 imod.add(VAddF32(dst=vgpr(valuSumStr), src0=vgpr(tmpVgpr+1), src1=vgpr(valuSumStr), comment="sum K"))
134 else:
135 printExit("Currently unsupported vgprPerInput %u"%vgprPerInput)
136 writer.vgprPool.checkIn(tmpVgpr)
137 elif (kernel["ProblemType"]["DataType"].isAnyFloat8A() and tc == "A") or \
138 (kernel["ProblemType"]["DataType"].isAnyFloat8B() and tc == "B"):
139 #FP8
140 tmpVgpr = writer.vgprPool.checkOutAligned(4,2)
141 if vgprPerInput > 1 and (vgprPerInput % 2 == 0):
142 for inputIdx in range(0, vgprPerInput):
143 sdwa = SDWAModifiers(src0_sel=SelectBit.WORD_0)
144 imod.add(VCvtPkFP8toF32(dst=vgpr(tmpVgpr,2), src=vgpr("%s+%s"%(valuStr, iui_new_offset + inputIdx)), sdwa=sdwa, comment="convert to FP32"))
145 sdwa = SDWAModifiers(src0_sel=SelectBit.WORD_1)
146 imod.add(VCvtPkFP8toF32(dst=vgpr(tmpVgpr+2,2), src=vgpr("%s+%s"%(valuStr, iui_new_offset + inputIdx)), sdwa=sdwa, comment="convert to FP32"))
147 imod.add(VAddF32(dst=vgpr(valuSumStr), src0=vgpr(tmpVgpr), src1=vgpr(valuSumStr), comment="sum K"))
148 imod.add(VAddF32(dst=vgpr(valuSumStr), src0=vgpr(tmpVgpr+1), src1=vgpr(valuSumStr), comment="sum K"))
149 imod.add(VAddF32(dst=vgpr(valuSumStr), src0=vgpr(tmpVgpr+2), src1=vgpr(valuSumStr), comment="sum K"))
150 imod.add(VAddF32(dst=vgpr(valuSumStr), src0=vgpr(tmpVgpr+3), src1=vgpr(valuSumStr), comment="sum K"))
151 else:
152 printExit("Currently unsupported vgprPerInput %u"%vgprPerInput)
153 writer.vgprPool.checkIn(tmpVgpr)
154 elif (kernel["ProblemType"]["DataType"].isAnyBFloat8A() and tc == "A") or \
155 (kernel["ProblemType"]["DataType"].isAnyBFloat8B() and tc == "B"):
156 #BF8
157 tmpVgpr = writer.vgprPool.checkOutAligned(4,2)
158 if vgprPerInput > 1 and (vgprPerInput % 2 == 0):
159 for inputIdx in range(0, vgprPerInput):
160 sdwa = SDWAModifiers(src0_sel=SelectBit.WORD_0)
161 imod.add(VCvtPkBF8toF32(dst=vgpr(tmpVgpr,2), src=vgpr("%s+%s"%(valuStr, iui_new_offset + inputIdx)), sdwa=sdwa, comment="convert to FP32"))
162 sdwa = SDWAModifiers(src0_sel=SelectBit.WORD_1)
163 imod.add(VCvtPkBF8toF32(dst=vgpr(tmpVgpr+2,2), src=vgpr("%s+%s"%(valuStr, iui_new_offset + inputIdx)), sdwa=sdwa, comment="convert to FP32"))
164 imod.add(VAddF32(dst=vgpr(valuSumStr), src0=vgpr(tmpVgpr), src1=vgpr(valuSumStr), comment="sum K"))
165 imod.add(VAddF32(dst=vgpr(valuSumStr), src0=vgpr(tmpVgpr+1), src1=vgpr(valuSumStr), comment="sum K"))
166 imod.add(VAddF32(dst=vgpr(valuSumStr), src0=vgpr(tmpVgpr+2), src1=vgpr(valuSumStr), comment="sum K"))
167 imod.add(VAddF32(dst=vgpr(valuSumStr), src0=vgpr(tmpVgpr+3), src1=vgpr(valuSumStr), comment="sum K"))
168 else:
169 printExit("Currently unsupported vgprPerInput %u"%vgprPerInput)
170 writer.vgprPool.checkIn(tmpVgpr)
171 else:
172 printExit("Currently unsupported data type")
173
174 if kernel["ProblemType"]["DataType"].isBFloat16():
175 writer.vgprPool.checkIn(hiBitsMaskVgpr)
176
177 return imod
178
179 """
180 Store sum to LDS
181 Use the same pattern as local read, except the leading dimension is the sum index instead of free indices
182 maxKId is calculated to find out the length of the sum index.
183 """
184 def storeSumLDS(self, writer, kernel, tP):
185 imod = Module("StoreSumLDS")
186 # Unregister defined sgpr
187 if kernel["ProblemType"]["DataType"].numRegisters() < 1:
188 if kernel["ProblemType"]["DataType"].isHalf():
189 writer.undefineSgpr("SumUnrollConstOne")
190
191 # bias data type
192 diasBpe = kernel["ProblemType"]["ComputeDataType"].numBytes()
193 # get constant parameter
194 tile01 = tP["tile01Idx"]
195 waveWidth = writer.states.kernel["WavefrontSize"]
196
197 wReg = writer.vgprPool.checkOut(1,"wReg") # quotient
198 tReg = writer.vgprPool.checkOut(1,"tReg") # remainder
199 kReg = writer.vgprPool.checkOut(1,"kReg") # remainder
200 tmpVgpr = writer.vgprPool.checkOutAligned(2,2,"tmpVgpr")
201 tmpVgprRes = ContinuousRegister(tmpVgpr, 2)
202 ldsVgpr = writer.vgprPool.checkOut(1,"ldsVgpr")
203 ldsVgpr1 = writer.vgprPool.checkOut(1,"ldsVgpr1")
204 dummy = writer.vgprPool.checkOut(1,"dummy")
205
206 # parameter for get each type index
207 tile10 = 1 - tile01
208 # Must init LraTileProperties in LraTileAssignment
209 assert writer.states.lraTileProperties[tile01] and writer.states.lraTileProperties[tile10]
210
211 dividendForKId = writer.states.lraTileProperties[tile01].dividendForKId
212 num1DBlocks = writer.states.lraTileProperties[tile01].num1DBlocks
213 num1DBlocks1 = writer.states.lraTileProperties[tile10].num1DBlocks
214 num1DWaves = writer.states.lraTileProperties[tile01].num1DWaves
215 dividedForBlkId = writer.states.lraTileProperties[tile01].dividedForBlkId
216 dividedForBlkId1 = writer.states.lraTileProperties[tile10].dividedForBlkId
217 dividedForWaveId = writer.states.lraTileProperties[tile01].dividedForWaveId
218 vectorWidth = writer.states.lraTileProperties[tile01].vectorWidth
219 maxKId = writer.states.lraTileProperties[tile01].maxKId
220
221 strideTile = maxKId
222 strideBlock = kernel["MatrixInstM"] * strideTile
223 strideWave = kernel["MatrixInstM"] * num1DBlocks * strideTile * vectorWidth
224
225 with writer.allocTmpSgpr(1) as tmpSgprInfo:
226 # tile offset
227 imod.add(vectorStaticRemainder(dummy, kReg, "Serial", waveWidth, tmpVgprRes, tmpSgprInfo, \
228 "0. thread id in wave: wtid = tid %% wavelength(%u)" % waveWidth))
229 imod.add(vectorStaticRemainder(dummy, tReg, kReg, kernel["MatrixInstN"], tmpVgprRes, tmpSgprInfo, \
230 "1. N offset: nIdx = wtid %% MI_N(%u)" % kernel["MatrixInstN"]))
231 imod.add(vectorStaticMultiply(vgpr(tReg), vgpr(tReg), strideTile, tmpSgprInfo, \
232 "1. N offset: nOffset = nIdx * nStride(%u)" % strideTile))
233 # block offset
234 # Here we calculate the coordinate of the block offset, and remove the duplicated blocks.
235 # For example we have block = 2x2, source swap = False:
236 # 0 1
237 # 2 3
238 # For tile01 = 0 we should only use 0, 2. For tile01 = 1 we should only use 0, 1.
239 imod.add(vectorStaticDivide(wReg, kReg, dividedForBlkId1, tmpVgprRes, \
240 "2-1. block offset: bnIdx = wtid / dividedForBlkId1(%u)" % dividedForBlkId1))
241 imod.add(vectorStaticRemainder(dummy, wReg, wReg, num1DBlocks1, tmpVgprRes, tmpSgprInfo, \
242 "2-1. block offset: bnIdx = bnIdx %% num1DBlocks1(%u)" % num1DBlocks1))
243 imod.add(VCmpXEqU32(dst=EXEC(), src0=vgpr(wReg), src1=0, comment="2-1. True if ans = 0"))
244 imod.add(vectorStaticDivide(wReg, kReg, dividedForBlkId, tmpVgprRes, \
245 "2. block offset: bnIdx = wtid / dividedForBlkId(%u)" % dividedForBlkId))
246 imod.add(vectorStaticRemainder(dummy, wReg, wReg, num1DBlocks, tmpVgprRes, tmpSgprInfo, \
247 "2. block offset: bnIdx = bnIdx %% num1DBlocks(%u)" % num1DBlocks))
248 imod.add(vectorStaticMultiply(vgpr(wReg), vgpr(wReg), strideBlock, tmpSgprInfo, \
249 "2. block offset: bnOffset = bnIdx * strideBlock(%u)" % strideBlock))
250 imod.add(VAddU32(dst=vgpr(tReg), src0=vgpr(wReg), src1=vgpr(tReg), \
251 comment="3. add N and block offset: bnOffset = block and N offset"))
252 imod.add(vectorStaticMultiply(vgpr(tReg), vgpr(tReg), vectorWidth, tmpSgprInfo, \
253 "3. apply VectorWidth: bnOffset = bnOffset * vw(%u)" % vectorWidth))
254 # unroll offset
255 imod.add(vectorStaticDivide(kReg, kReg, dividendForKId, tmpVgprRes, \
256 "4. K offset: kIdx = wtid / (MIN(%u) * MIBB(%u))" % (kernel["MatrixInstN"], kernel["MatrixInstB"])))
257 imod.add(vectorStaticMultiply(vgpr(kReg), vgpr(kReg), 1, tmpSgprInfo, \
258 "4. K offset: lrKOffset = kIdx * mStride(1)"))
259
260 imod.add(VAddU32(dst=vgpr(tReg), src0=vgpr(kReg), src1=vgpr(tReg), \
261 comment="5. offset in wave: lrOffset = bnOffset + lrKOffset"))
262 # wave offset
263 if num1DWaves > 1:
264 # FIXME: Should be two cases tile01 == 0 and tile01 == 1
265 imod.add(vectorStaticDivide(wReg, "Serial", dividedForWaveId, tmpVgprRes, \
266 "6. wave offset in N dimen: wtid = tid / dividedForWaveId(%u)" % dividedForWaveId))
267 # Here we calculate the coordinate of the block offset, and remove the duplicated wave.
268 if tile01 == 0:
269 imod.add(vectorStaticDivide(dummy, wReg, num1DWaves, tmpVgprRes, \
270 "6-1.mask duplicated: wtid0 = wtid / num1DWaves(%u)" % num1DWaves))
271 else:
272 imod.add(vectorStaticDivide(dummy, "Serial", waveWidth, tmpVgprRes, \
273 "6-1. wave offset in N dimen (waveWidth): wtid_1 = tid / waveWidth(%u)" % waveWidth))
274 imod.add(vectorStaticRemainder(dummy, dummy, dummy, kernel["MIWaveGroup"][0], tmpVgprRes, tmpSgprInfo, \
275 "6-1. wave offset in M dimen (MIWaveGroup0): wtid0 = wtid_1 %% MIWaveGroup0(%u)" % kernel["MIWaveGroup"][0]))
276 imod.add(VCmpXEqU32(dst=EXEC(), src0=vgpr(dummy), src1=0, comment="6-1. True if ans = 0"))
277 imod.add(vectorStaticRemainder(dummy, wReg, wReg, num1DWaves, tmpVgprRes, tmpSgprInfo, \
278 "6. wave offset in M dimen: wtid0 = wtid %% num1DWaves(%u)" % num1DWaves))
279 imod.add(vectorStaticMultiply(vgpr(wReg), vgpr(wReg), strideWave, tmpSgprInfo, \
280 "6. wave offset in M dimen: wOffset = wtid0 * W0Stride(%u)" % strideWave))
281 imod.add(VAddU32(dst=vgpr(tReg), src0=vgpr(wReg), src1=vgpr(tReg), \
282 comment="7. final local read offset: flrOffset = lrOffset + WOffset"))
283 imod.add(VLShiftLeftB32(dst=vgpr(tReg), src=vgpr(tReg), shiftHex=hex(log2(diasBpe)), \
284 comment="offset = offset*bpe" ))
285 # release register
286 writer.vgprPool.checkIn(wReg)
287 writer.vgprPool.checkIn(kReg)
288 writer.vgprPool.checkIn(tmpVgpr)
289 writer.vgprPool.checkIn(ldsVgpr)
290 writer.vgprPool.checkIn(ldsVgpr1)
291 writer.vgprPool.checkIn(dummy)
292
293 # Add barrier here to avoid race condition if lds offset starts from 0
294 if kernel["LdsOffsetBias"] == 0: # Compatible for both GSU1 and GSUM
295 imod.add(SBarrier(comment="Wait for all wavefronts"))
296
297 MIWaveGroupShape = [ kernel["MatrixInstM"] * kernel["MatrixInstBM"] * kernel["MIWaveGroup"][0] * kernel["VectorWidthA"], \
298 kernel["MatrixInstN"] * kernel["MatrixInstBN"] * kernel["MIWaveGroup"][1] * kernel["VectorWidthB"]]
299 numReadPerTileVector = vectorWidth
300 numVectorsPerTile = kernel["MIWaveTile"][tile01] // numReadPerTileVector
301 idx = 0
302 for vIdx in range(0, numVectorsPerTile):
303 for eIdx in range(0, numReadPerTileVector):
304 # normal case
305 offset_val = (eIdx + vIdx * MIWaveGroupShape[tile01]) * maxKId * kernel["ProblemType"]["ComputeDataType"].numBytes()
306 bps = kernel["ProblemType"]["ComputeDataType"].numBytes()
307 ds = DSModifiers(offset=offset_val)
308 dst = vgpr(tReg)
309 vgprStr = "ValuSum+%u"%idx
310 if bps==2:
311 imod.add(DSStoreB16(dstAddr=dst, src=vgpr(vgprStr), ds=ds, comment="local store bias"))
312 elif bps==4:
313 imod.add(DSStoreB32(dstAddr=dst, src=vgpr(vgprStr), ds=ds, comment="local store bias"))
314 elif bps==8:
315 imod.add(DSStoreB64(dstAddr=dst, src=vgpr(vgprStr, 2), ds=ds, comment="local store bias"))
316 else:
317 assert 0
318 idx += 1
319 # tReg
320 writer.vgprPool.checkIn(tReg)
321 imod.add(SSetMask(dst=EXEC(), src=-1, comment="reset mask" ))
322 # For later write in Global Write Batch
323 return imod