Debian Codegraph @

tensilelite/Tensile/Components/GSU.py

raw symbols SCIP
1 ################################################################################
2 #
3 # Copyright (C) 2024-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 rocisa import countInstruction
24 from rocisa.code import Module, Label, RegSet
25 from rocisa.container import ContinuousRegister, SMEMModifiers, vgpr, sgpr, replaceHolder
26 from rocisa.instruction import SAddCU32, SAddU32, SAndB32, SLoadB32, SStoreB32, SBranch, \
27 SCBranchSCC0, SCBranchSCC1, SCMovB32, SCSelectB32, SCmpEQU32, SCmpLgU32, SCmpLtU32, SCmpGtI32, \
28 SLShiftLeftB64, SLShiftRightB32, SMovB32, SMovB64, SMulI32, SSubU32, SCmpEQI32, SEndpgm, \
29 SCmpLeI32, VCmpGEI32, SSubI32, SCBranchSCC0, VMovB32, SLShiftLeftB32, SWaitCnt, SBarrier, \
30 SNop, SSleep, VAddF32, VAddI32, VReadfirstlaneB32, SMulHIU32, VAddPKF32, VCndMaskB32, SAtomicDec
31 from rocisa.functions import scalarStaticMultiply64, scalarUInt32DivideAndRemainder, vectorStaticMultiply
32
33 from ..Common import ceilDivide, log2, print2
34 from ..Component import Component
35 from ..AsmStoreState import StoreState, VectorDataTypes
36 from ..AsmAddressCalculation import AddrCalculation
37 import abc
38 from copy import deepcopy
39 from math import ceil
40 from ..KernelWriterModules import mapAcctoArchRegs
41
42 class GSU(Component):
43 """
44 GSU block.
45 """
46 @abc.abstractmethod
47 def graWorkGroup(self, writer, kernel):
48 pass
49
50 @abc.abstractmethod
51 def computeLoadSrd(self, writer, kernel, tP, stmp, tileStart):
52 pass
53
54 @abc.abstractmethod
55 def graIncrements(self, writer, kernel, loopIdx, tP):
56 pass
57
58 @abc.abstractmethod
59 def graIncrementsRestore(self, writer, kernel, loopCounterName):
60 pass
61
62 def graIncrementsCommon(self, writer, loopIdx, tc, stride, m):
63 module = Module("GSU Common graIncrements")
64
65 # multiply by stride, optimizing if unit stride
66 if writer.isConstUnitStride(stride):
67 module.add(SMovB32(dst=sgpr("GlobalReadIncs%s+%u"%(tc, loopIdx)), src=m, \
68 comment="incr%s (unrollIdx)"%(tc) ))
69 else:
70 module.add(SMulI32(dst=sgpr("GlobalReadIncs%s+%u"%(tc, loopIdx)), \
71 src0=m, src1=stride, \
72 comment="incr%s unrollIdx)"%(tc) ))
73
74 return module
75
76 @abc.abstractmethod
77 def calculateLoopNumIter(self, writer, kernel, loopCounterName, tmpSgprInfo):
78 pass
79
80 @abc.abstractmethod
81 def calculateIncrementMetadata(self, writer, kernel, sgprOut):
82 pass
83
84 @abc.abstractmethod
85 def computeStoreSrdStart(self, writer, kernel):
86 pass
87
88 @abc.abstractmethod
89 def noLoadLoop(self, writer, kernel, tensorParametersA, tensorParametersB, pack):
90 pass
91
92 @abc.abstractmethod
93 def tailLoopNumIter(self, writer, kernel, loopCounter):
94 pass
95
96 @abc.abstractmethod
97 def setupNewTile(self, writer, kernel, tensorParametersA, tensorParametersB, tPM):
98 pass
99
100 def graIncrementsAB(self, writer, kernel, tensorParametersA, tensorParametersB, tPM):
101 module = Module("GSU Common graIncrementsAB")
102 module.addComment1("global read addresses: increments a")
103 for i in reversed(range(kernel["ProblemType"]["NumIndicesSummation"])):
104 module.add(writer.graIncrements(kernel, i, tensorParametersA))
105 if kernel["ProblemType"]["Sparse"] and not kernel["DirectToVgprSparseMetadata"]:
106 module.addComment1("global read addresses: increments metadata")
107 for i in reversed(range(kernel["ProblemType"]["NumIndicesSummation"])):
108 module.add(writer.graIncrements(kernel, i, tPM))
109 module.addComment1("global read addresses: increments b")
110 for i in reversed(range(kernel["ProblemType"]["NumIndicesSummation"])):
111 module.add(writer.graIncrements(kernel, i, tensorParametersB))
112
113 return module
114
115 @abc.abstractmethod
116 def globalWriteBatchProlog(self, writer, kernel, tmpVgpr, tmpVgprSize, tmpVgprDynamic, \
117 batchIdx, ss, gwvw, batchElements, \
118 beta, edge, sumIdxGSUSYNC, addrCalc):
119 pass
120
121 @abc.abstractmethod
122 def defineAndResources(self, writer, kernel, tmpSgpr0, tmpSgprM, tmpSgprN, tmpSgprNumWG0, tmpSgprAccumTiles):
123 pass
124
125 @abc.abstractmethod
126 def writeBiasToGlobal(self, writer, kernel, biasDataType, tP, tmpSgprRes, biasBpe):
127 pass
128
129 @abc.abstractmethod
130 def reductionBranches(self, writer, kernel, tPB, vectorWidths, elements, tmpVgpr, cvtVgprStruct, vectorDataTypes, factorDims, reductionEndLabel, endLabel):
131 pass
132
133 class GSUOff(GSU):
134 kernel = {"GlobalSplitU": 0}
135
136 def __call__(self):
137 assert(0)
138
139 def graWorkGroup(self, writer, kernel):
140 module = Module("GSU Off graWorkGroup")
141 return module
142
143 def computeLoadSrd(self, writer, kernel, tP, stmp, tileStart):
144 module = Module("GSU Off computeLoadSrd")
145 return module
146
147 def graIncrements(self, writer, kernel, loopIdx, tP):
148 module = Module("GSU Off graIncrements")
149
150 tc = tP["tensorChar"]
151 tcGR = tc if tc == "Metadata" else (tc + "GR")
152 dimIdx = kernel["ProblemType"]["IndicesSummation"][loopIdx] # dimension index
153 loopChar = writer.states.indexChars[dimIdx]
154 stride = writer.strideRef(tc, dimIdx)
155 isMirrorIdx = dimIdx in kernel["ProblemType"]["MirrorDims%s"%tc]
156
157 m = "DepthU*Bpe%s"%(tcGR)
158 if isMirrorIdx:
159 m = "-%s"%(m)
160
161 if writer.states.globalReadIncsUseVgpr:
162 with writer.allocTmpSgpr(2) as tmpSgprInfo:
163 tmpSgpr = tmpSgprInfo.idx
164 module.add(SMovB32(dst=sgpr(tmpSgpr+0), src="DepthU*%d"%(tP["bpeGR"]), comment="DepthU*Bpe"))
165 module.add(SMulI32(dst=sgpr(tmpSgpr+0), src0=sgpr(tmpSgpr+0), src1=stride, \
166 comment="incr%s%s = %s*DepthU*bpeGR (unrollIdx)"%(tc, loopChar, stride) ))
167 # TODO - this should be mul-H??
168 module.add(SMovB32(dst=sgpr(tmpSgpr+1), src=hex(0), comment="(carry)"))
169 module.add(VMovB32(dst=vgpr("GlobalReadIncs%s+%u+0"%(tc, 2*loopIdx)), src=sgpr(tmpSgpr+0)))
170 module.add(VMovB32(dst=vgpr("GlobalReadIncs%s+%u+1"%(tc, 2*loopIdx)), src=sgpr(tmpSgpr+1)))
171 else:
172 module.add(self.graIncrementsCommon(writer, loopIdx, tc, stride, m))
173
174 return module
175
176 def graIncrementsRestore(self, writer, kernel, loopCounterName):
177 module = Module("GSU Off graIncrementsRestore")
178 return module
179
180 def calculateLoopNumIter(self, writer, kernel, loopCounterName, tmpSgprInfo):
181 module = Module("GSU Off calculateLoopNumIter")
182 return module
183
184 def calculateIncrementMetadata(self, writer, kernel, sgprOut):
185 module = Module("GSU Off calculateLoopNumIter")
186 module.add(SMovB32(dst=sgpr(sgprOut), src=kernel["DepthU"], comment="IncsMetadata = DepthU if GSUC == 1"))
187 module.add(SLShiftRightB32(dst=sgpr(sgprOut), shiftHex=hex(log2(8)), src=sgpr(sgprOut)))
188 return module
189
190 def computeStoreSrdStart(self, writer, kernel):
191 module = Module("GSU Off computeStoreSrdStart")
192 return module
193
194 def noLoadLoop(self, writer, kernel, tensorParametersA, tensorParametersB, pack):
195 module = Module("GSU Off noLoadLoop")
196 return module
197
198 def tailLoopNumIter(self, writer, kernel, loopCounter):
199 module = Module("GSU Off tailLoopNumIter")
200 return module
201
202 def setupNewTile(self, writer, kernel, tensorParametersA, tensorParametersB, tPM):
203 module = Module("GSU Off setupNewTile")
204 module.add(self.graIncrementsAB(writer, kernel, tensorParametersA, tensorParametersB, tPM))
205 return module
206
207 def reductionBranches(self, writer, kernel, tPB, vectorWidths, elements, tmpVgpr, cvtVgprStruct, vectorDataTypes, factorDims, reductionEndLabel, endLabel):
208 module = Module("GSU Off reductionBranches")
209 return module
210
211 def globalWriteBatchProlog(self, writer, kernel, tmpVgpr, tmpVgprSize, tmpVgprDynamic, \
212 batchIdx, ss, gwvw, batchElements, \
213 beta, edge, sumIdxGSUSYNC, addrCalc):
214 module = Module("GSU Off globalWriteBatchProlog")
215 return module
216
217 def defineAndResources(self, writer, kernel, tmpSgpr0, tmpSgprM, tmpSgprN, tmpSgprNumWG0, tmpSgprAccumTiles):
218 module = Module("GSU Off defineAndResources")
219 return module
220
221 def writeBiasToGlobal(self, writer, kernel, biasDataType, tP, tmpSgprRes, biasBpe):
222 module = Module("GSU Off writeBiasToGlobal")
223 return module
224
225 class GSUOn(GSU):
226 kernel = {"GlobalSplitUAlgorithm": "MultipleBufferSingleKernel"}
227 # if GSU <= gsuThreshold, last wg does the reduction and no R/W to WS
228 # else, atomic_dec chooses the wg to do the reduction
229 gsuThreshold = 2
230
231 @classmethod
232 def matches(cls, writer, debug=False):
233 return writer.states.kernel["GlobalSplitU"] > 0 or writer.states.kernel["GlobalSplitU"] == -1
234
235 def __call__(self):
236 assert(0)
237
238 def graWorkGroup(self, writer, kernel):
239 module = Module("GSU On graWorkGroup")
240
241 gsuLabel = Label(label=writer.labels.getNameInc("GSU"), comment="")
242 gsuLabelEnd = Label(label=writer.labels.getNameInc("GSU_End"), comment="")
243 with writer.allocTmpSgpr(1) as tmpSgprGSU:
244 module.add(SAndB32(dst=sgpr(tmpSgprGSU.idx), src0=sgpr("GSU"), src1=hex(0x3FFF), comment="Restore GSU"))
245 module.add(SCmpEQU32(src0=sgpr(tmpSgprGSU.idx), src1=1, comment="GSU == 1 ?"))
246 module.add(SCBranchSCC1(labelName=gsuLabel.getLabelName(), comment="branch if GSU == 1"))
247
248 if ((kernel["GlobalSplitUAlgorithm"] == 'MultipleBufferSingleKernel')):
249 extReadEpilogueLabeltmp = Label(label=writer.labels.getNameInc("LoadExternalEpilogueStruct"), comment="")
250 module.addComment0("Check if custom structure pointer is null")
251 if kernel["ProblemType"]["SupportUserArgs"]:
252 module.add(SCmpEQU32(src0=sgpr("ArgType"), src1=2, comment="ArgType == 2 ?"))
253 module.add(SCBranchSCC0(labelName=extReadEpilogueLabeltmp.getLabelName()))
254
255 with writer.allocTmpSgpr(2,2) as tmpSgprD:
256 module.add(SMovB64(dst=sgpr(tmpSgprD.idx,2), src=sgpr("AddressD",2), comment="tmp=Output"))
257 module.add(SMovB64(dst=sgpr("AddressD",2), src=sgpr("AddressTD",2), comment="D=Workspace"))
258 module.add(SMovB64(dst=sgpr("AddressTD",2), src=sgpr(tmpSgprD.idx,2), comment="TD=Output"))
259 module.add(extReadEpilogueLabeltmp)
260
261 module.addComment("GSU-not-WGMapRR :nwg1 = (size%s + MT%s - 1) / MT%s;" \
262 % (writer.states.tileChar1, writer.states.tileChar1, writer.states.tileChar1))
263
264 tmpVgpr = writer.vgprPool.checkOut(2, "tmp")
265 tmpVgprRes = ContinuousRegister(idx=tmpVgpr, size=2)
266 gsuwgmrrLabel = Label(label=writer.labels.getNameInc("GSUWGMRR"), comment="")
267 gsuwgmrrLabelEnd = Label(label=writer.labels.getNameInc("GSUWGMRR_End"), comment="")
268 with writer.allocTmpSgpr(1) as tmpSgprInfo:
269 module.add(SAndB32(dst=sgpr(tmpSgprInfo.idx), src0=sgpr("GSU"), src1=hex(0x4000), comment="SCC = (GSUWGMRR == 1) ?"))
270 module.add(SCBranchSCC1(labelName=gsuwgmrrLabel.getLabelName(), comment="branch if GSUWGMRR == 1"))
271 # wg1 = wg1 / GSU
272 # gsuSumIdx = wg1 % GSU
273 module.add(SAndB32(dst=sgpr(tmpSgprInfo.idx), src0=sgpr("GSU"), src1=hex(0x3FFF), comment="Restore GSU"))
274 module.add(scalarUInt32DivideAndRemainder("WorkGroup1", "WorkGroup1", tmpSgprInfo.idx, "GSUSumIdx", tmpVgprRes, kernel["WavefrontSize"]))
275 module.add(SBranch(gsuwgmrrLabelEnd.getLabelName()))
276 module.add(gsuwgmrrLabel)
277 # gsuSumIdx = wg1 / numWg1
278 # wg1 = wg1 % numWg1
279 module.add(scalarUInt32DivideAndRemainder("GSUSumIdx", "WorkGroup1", "NumWorkGroups1", "WorkGroup1", tmpVgprRes, kernel["WavefrontSize"]))
280 module.add(gsuwgmrrLabelEnd)
281 writer.vgprPool.checkIn(tmpVgpr)
282 module.add(SMovB32(dst=sgpr("GSULog2BpeC"), src=log2(int(writer.states.bpr * kernel["ProblemType"]["DestDataType"].numRegisters()))))
283 module.add(SMovB32(dst=sgpr("GSULog2BpeD"), src=log2(writer.states.bpeCinternal)))
284
285 module.add(SBranch(gsuLabelEnd.getLabelName()))
286 module.add(gsuLabel)
287 module.add(SMovB64(dst=sgpr("GSUSumIdx", 2), src=0, comment="Set GSUSumIdx to 0"))
288 module.add(SMovB32(dst=sgpr("GSULog2BpeC"), src=log2(writer.states.bpeCexternalGSU1)))
289 module.add(SMovB32(dst=sgpr("GSULog2BpeD"), src=log2(writer.states.bpeCexternalGSU1)))
290 module.add(gsuLabelEnd)
291
292 return module
293
294 def computeLoadSrd(self, writer, kernel, tP, stmp, tileStart):
295 module = Module("GSU On computeLoadSrd")
296
297 tc = tP["tensorChar"]
298 depthU = kernel["DepthU"]
299 depthUDiv = kernel["DepthU"]
300 # swizzle
301 if (tP["isSwizzled"] and tc == 'A'):
302 depthUDiv = "%s%s"%(kernel["DepthU"], "*MI_M")
303 elif (tP["isSwizzled"] and tc == 'B'):
304 depthUDiv = "%s%s"%(kernel["DepthU"], "*MI_N")
305
306 gsuOffsetStr = "gsuOffset = DepthU*bpeGR*GSUSumIdx"
307 divider = 1
308 if kernel["ProblemType"]["Sparse"]:
309 if (kernel["ProblemType"]["Sparse"] == 2 and tP["isB"]) or \
310 (kernel["ProblemType"]["Sparse"] == 1 and tP["isA"]) :
311 divider = 2
312 elif tP["isM"]:
313 divider = 8
314 if divider != 1:
315 depthUDiv = depthU // divider
316 gsuOffsetStr = "gsuOffset = DepthU/%s*bpeGR*GSUSumIdx"%(divider)
317 gsucLabel = Label(label=writer.labels.getNameInc("GSUC_A" if tP["isA"] else "GSUC_B"), comment="")
318 gsucLabelEnd = Label(label=writer.labels.getNameInc("GSUC_A_End" if tP["isA"] else "GSUC_B_End"), comment="")
319 module.add(SAndB32(dst=sgpr(stmp), src0=sgpr("GSU"), src1=hex(0x8000), comment="SCC = (GSUC == 1) ?"))
320 module.add(SCBranchSCC1(labelName=gsucLabel.getLabelName(), comment="branch if GSUC == 1"))
321 gsuOffsetStr = "gsuOffset = DepthU*GSUSumIdx"
322 module.addModuleAsFlatItems(writer.s_mul_u64_u32(sgpr(stmp+0), sgpr(stmp+1), depthUDiv, sgpr("GSUSumIdx"), comment=gsuOffsetStr))
323 module.add(SBranch(gsucLabelEnd.getLabelName()))
324 module.add(gsucLabel)
325 gsuOffsetStr = "gsuOffset = DepthU*accumulatedNumOfLoopCounterL"
326 loopCounterName = writer.loopCounterName(kernel, writer.states.unrollIdx)
327 module.add(SLShiftRightB32(dst=sgpr(loopCounterName), src=sgpr("SizesSum"), shiftHex=log2(depthU), \
328 comment="s[%s] = s[sgprSizesSum] / %s"%(loopCounterName, depthU)))
329 tmpSgprInfo = ContinuousRegister(idx=stmp, size=2)
330 module.add(writer.calculateLoopNumIterOffsetGsu(kernel, loopCounterName, tmpSgprInfo))
331 module.addModuleAsFlatItems(writer.s_mul_u64_u32(sgpr(stmp+0), sgpr(stmp+1), sgpr(stmp+0), depthUDiv, comment=gsuOffsetStr))
332 module.add(gsucLabelEnd)
333
334 unrollSummation = [ i for i in tP["ia"] if i in kernel["ProblemType"]["IndicesSummation"] ]
335 stride = writer.strideRef(tc, unrollSummation[-1])
336 if tP["tlu"] and not writer.isConstUnitStride(stride):
337 # non-transpose case, unroll is in perp dim and should be scaled by unroll Stride
338 module.addModuleAsFlatItems(writer.s_mul_u64_u32(sgpr(stmp), sgpr(stmp+1), sgpr(stmp+0), \
339 stride, comment="tlu=1, scaled unroll-offset by stride"))
340
341 module.add(SAddU32(dst=sgpr(tileStart+0), src0=sgpr(tileStart+0), src1=sgpr(stmp+0), comment="accum GsuOffset term to tilestart"))
342 module.add(SAddCU32(dst=sgpr(tileStart+1), src0=sgpr(tileStart+1), src1=sgpr(stmp+1), comment="accum GsuOffset term to tilestart"))
343
344 return module
345
346 def graIncrements(self, writer, kernel, loopIdx, tP):
347 module = Module("GSU On graIncrements")
348
349 tc = tP["tensorChar"]
350 dimIdx = kernel["ProblemType"]["IndicesSummation"][loopIdx] # dimension index
351 loopChar = writer.states.indexChars[dimIdx]
352 stride = writer.strideRef(tc, dimIdx)
353 isMirrorIdx = dimIdx in kernel["ProblemType"]["MirrorDims%s"%tc]
354
355 if writer.states.globalReadIncsUseVgpr:
356 with writer.allocTmpSgpr(3) as tmpSgprInfo:
357 tmpSgpr = tmpSgprInfo.idx
358 gsuSgpr = tmpSgpr + 2
359 module.add(SAndB32(dst=sgpr(tmpSgpr), src0=sgpr("GSU"), src1=hex(0x3FFF), comment="Restore GSU"))
360 module.add(SMulI32(dst=sgpr(gsuSgpr), src0=sgpr(tmpSgpr), src1="DepthU*%d"%(tP["bpeGR"]), comment="GSU*DepthU*Bpe"))
361 module.add(SAndB32(dst=sgpr(tmpSgpr), src0=sgpr("GSU"), src1=hex(0x8000), comment="SCC = (GSUC == 1) ?"))
362 module.add(SCMovB32(dst=sgpr(gsuSgpr), src="DepthU*%d"%(tP["bpeGR"]), comment="DepthU*Bpe if GSUC = 1"))
363 module.add(SMulI32(dst=sgpr(tmpSgpr+0), src0=sgpr(gsuSgpr), src1=stride, \
364 comment="incr%s%s = %s*DepthU*bpeGR (unrollIdx)"%(tc, loopChar, stride) ))
365 # TODO - this should be mul-H??
366 module.add(SMovB32(
367 dst=sgpr(tmpSgpr+1), \
368 src=0, \
369 comment="(carry)"))
370 module.add(VMovB32(
371 dst=vgpr("GlobalReadIncs%s+%u+0"%(tc, 2*loopIdx)), \
372 src=sgpr(tmpSgpr+0)))
373 module.add(VMovB32(
374 dst=vgpr("GlobalReadIncs%s+%u+1"%(tc, 2*loopIdx)), \
375 src=sgpr(tmpSgpr+1)))
376 else:
377 with writer.allocTmpSgpr(2) as tmpSgprInfo:
378 tmpSgpr = tmpSgprInfo.idx
379 gsuSgpr = tmpSgpr + 1
380
381 tcGR = tc if tc == "Metadata" else (tc + "GR")
382
383 # swizzle
384 mult_MI_Dim = ""
385 if tc == "A" and kernel["ProblemType"]["SwizzleTensorA"]:
386 mult_MI_Dim = "*MI_M"
387 elif tc == "B" and kernel["ProblemType"]["SwizzleTensorB"]:
388 mult_MI_Dim = "*MI_N"
389
390 module.add(SAndB32(dst=sgpr(gsuSgpr), src0=sgpr("GSU"), src1=hex(0x3FFF), comment="Restore GSU"))
391 module.add(SMulI32(dst=sgpr(gsuSgpr), src0=sgpr(gsuSgpr), src1="DepthU*Bpe%s%s"%(tcGR, mult_MI_Dim), comment="GSU*DepthU*Bpe%s"%(mult_MI_Dim)))
392 module.add(SAndB32(dst=sgpr(tmpSgpr), src0=sgpr("GSU"), src1=hex(0x8000), comment="SCC = (GSUC == 1) ?"))
393
394 m = sgpr(gsuSgpr)
395
396 if isMirrorIdx:
397 m.setMinus(True)
398
399 incr = sgpr("GlobalReadIncs%s+%u"%(tc, loopIdx))
400 duBpe = "DepthU*Bpe%s%s"%(tcGR, mult_MI_Dim)
401 # multiply by stride, optimizing if unit stride
402 if writer.isConstUnitStride(stride):
403 module.add(SCSelectB32(dst=incr, src0=duBpe, src1=m, comment="incr%s (unrollIdx)"%(tc)))
404 else:
405 module.add(SCMovB32(dst=m, src=duBpe, comment="DepthU*Bpe if GSUC = 1"))
406 module.add(SMulI32(dst=incr, src0=m, src1=stride, comment="incr%s unrollIdx)"%(tc) ))
407
408 if kernel["ProblemType"]["Sparse"]:
409 if tP["is_sparse"]:
410 module.add(SLShiftRightB32(dst=incr, shiftHex=hex(log2(2)), src=incr))
411 elif tP["isM"]:
412 module.add(SLShiftRightB32(dst=incr, shiftHex=hex(log2(8)), src=incr))
413
414 return module
415
416 def graIncrementsRestore(self, writer, kernel, loopCounterName):
417 module = Module("GSU On graIncrementsRestore")
418
419 with writer.allocTmpSgpr(1) as tmpSgprInfo:
420 gsuSgpr = tmpSgprInfo.idx
421 module.add(SAndB32(dst=sgpr(gsuSgpr), src0=sgpr("GSU"), src1=hex(0x3FFF), comment="Restore GSU"))
422 module.add(SMulI32(dst=sgpr(gsuSgpr), src0=sgpr(gsuSgpr), src1=kernel["DepthU"]))
423 module.add(SMulI32(dst=sgpr(loopCounterName), src0=sgpr(loopCounterName), \
424 src1=sgpr(gsuSgpr), comment="=loopCounterName*DepthU"))
425
426 return module
427
428 def calculateLoopNumIter(self, writer, kernel, loopCounterName, tmpSgprInfo):
429 module = Module("GSU On calculateLoopNumIter")
430
431 tmpSgpr = tmpSgprInfo.idx
432 # if GSU numIter++ if gsuSumIdx < remainder
433 gsuLabel = Label(label=writer.labels.getNameInc("GSU"), comment="")
434 module.add(SAndB32(dst=sgpr(tmpSgpr), src0=sgpr("GSU"), src1=hex(0x3FFF), comment="Restore GSU"))
435 module.add(SCmpEQU32(src0=sgpr(tmpSgpr), src1=1, comment="GSU == 1 ?"))
436 module.add(SCBranchSCC1(labelName=gsuLabel.getLabelName(), comment="branch if GSU == 1"))
437 module.add(writer.calculateLoopNumIterGsu(kernel, loopCounterName, tmpSgprInfo))
438 module.add(gsuLabel)
439
440 return module
441
442 ##############################################################################
443 # Emit code to compute loop iterations for GSU.
444 # See same function in KernelWriterSource.py for background explanation
445 # This function is used to compute number of loop iters and also
446 # for computing the global read increment for GSU case.
447 # For multiple summation, the number of loop iterations needs to be reset
448 # for each iteration so replicate the code in addr inc and at open of unroll loop
449
450 # tmpSgpr is allocation of at least 3 tmpSgpr
451
452 # Output: SGPR(destName) contains the number of unroll iterations for
453 # this workgroup.
454 ##############################################################################
455 def calculateLoopNumIterGsu(self, writer, kernel, destName, tmpSgprRes: ContinuousRegister):
456 module = Module("calculateLoopNumIterGsu")
457
458 loopCounter = sgpr(destName)
459 quotient = destName
460 remainder = "GSUSumIdx+1" # numIterPerWgRemainder
461 dividend = destName
462
463 tmpVgpr = writer.vgprPool.checkOut(2,"tmp")
464 tmpVgprRes = ContinuousRegister(idx=tmpVgpr, size=2)
465 module.add(scalarUInt32DivideAndRemainder(quotient, dividend, "GSU", remainder, tmpVgprRes, wavewidth=kernel["WavefrontSize"]))
466 writer.vgprPool.checkIn(tmpVgpr)
467
468 # if gsuSumIdx < numIterPerWgRemainder
469 module.add(SAddU32(dst=sgpr(tmpSgprRes.idx), src0=1, \
470 src1=loopCounter, comment="tmp<-numIterMyWg+" ))
471 module.add(SCmpLtU32(src0=sgpr("GSUSumIdx"), src1=sgpr("GSUSumIdx+1"), \
472 comment="gsuSumIdx < numIterPerWgRemainder" ))
473 module.add(SCMovB32(dst=loopCounter, src=sgpr(tmpSgprRes.idx), comment="numIterMyWg++ if needed"))
474
475 return module
476
477 def calculateIncrementMetadata(self, writer, kernel, sgprOut):
478 module = Module("GSU On calculateLoopNumIter")
479 with writer.allocTmpSgpr(1) as tmpSgprGSU:
480 module.add(SAndB32(dst=sgpr(tmpSgprGSU.idx), src0=sgpr("GSU"), src1=hex(0x3FFF), comment="Restore GSU"))
481 module.add(SMulI32(dst=sgpr(sgprOut), src0=kernel["DepthU"], src1=sgpr(tmpSgprGSU.idx), comment="IncsMetadata = GSU*DepthU"))
482 module.add(SAndB32(dst=sgpr(tmpSgprGSU.idx), src0=sgpr("GSU"), src1=hex(0x8000), comment="SCC = (GSUC == 1) ?"))
483 module.add(SCMovB32(dst=sgpr(sgprOut), src=kernel["DepthU"], comment="IncsMetadata = DepthU if GSUC == 1"))
484 module.add(SLShiftRightB32(dst=sgpr(sgprOut), shiftHex=hex(log2(8)), src=sgpr(sgprOut)))
485 return module
486
487 def computeStoreSrdStart(self, writer, kernel):
488 module = Module("GSU On computeStoreSrdStart")
489
490 indices = list(range(0, kernel["ProblemType"]["NumIndicesC"]))
491 numDim = len(indices)
492
493 if kernel["GlobalSplitUAlgorithm"] == 'MultipleBuffer' or kernel["_GlobalAccumulation"] == 'MultipleBufferSingleKernel':
494 gsuLabel = Label(label=writer.labels.getNameInc("GSU"), comment="")
495 with writer.allocTmpSgpr(1) as tmpSgprGSU:
496 module.add(SAndB32(dst=sgpr(tmpSgprGSU.idx), src0=sgpr("GSU"), src1=hex(0x3FFF), comment="Restore GSU"))
497 module.add(SCmpEQU32(src0=sgpr(tmpSgprGSU.idx), src1=1, comment="GSU == 1 ?"))
498 module.add(SCBranchSCC1(labelName=gsuLabel.getLabelName(), comment="branch if GSU == 1"))
499 # GSU algorithm 2: adjust output buffer address to per GSU buffer
500 with writer.allocTmpSgpr(4, alignment=1) as tmpSgprInfo:
501 if tmpSgprInfo.idx % 2 == 0:
502 tmpSgprX2 = tmpSgprInfo.idx+0
503 tmpSgpr0 = tmpSgprInfo.idx+0
504 tmpSgpr1 = tmpSgprInfo.idx+1
505 tmpSgpr2 = tmpSgprInfo.idx+2
506 tmpSgpr3 = tmpSgprInfo.idx+3
507 else:
508 tmpSgprX2 = tmpSgprInfo.idx+1
509 tmpSgpr0 = tmpSgprInfo.idx+1
510 tmpSgpr1 = tmpSgprInfo.idx+2
511 tmpSgpr2 = tmpSgprInfo.idx+0
512 tmpSgpr3 = tmpSgprInfo.idx+3
513 module.addComment("GSU Output Buffer offset: Free0 + (Free1-1)*StrideC1J + (Free2-1)*StrideCK * GSUIdx * bpe%s")
514 module.addModuleAsFlatItems(writer.s_mul_u64_u32(sgpr(tmpSgpr0), sgpr(tmpSgpr1), sgpr("SizesFree+0"), sgpr("GSUSumIdx"), comment="Free0"))
515 for i in range(1, numDim):
516 module.add(SSubU32(dst=sgpr(tmpSgpr2), src0=sgpr("SizesFree+%u"%i), src1=1, comment="Free%u" % i))
517 module.add(SMulI32(dst=sgpr(tmpSgpr2), src0=sgpr(tmpSgpr2), src1=sgpr("GSUSumIdx"), comment="Free%u" % i))
518 module.addModuleAsFlatItems(writer.s_mul_u64_u32(sgpr(tmpSgpr2), sgpr(tmpSgpr3), sgpr(tmpSgpr2), sgpr("StrideC%s"%writer.states.indexChars[i]), comment="Free%u" % i))
519 module.add(SAddU32(dst=sgpr(tmpSgpr0), src0=sgpr(tmpSgpr0), src1=sgpr(tmpSgpr2), comment="Free%u" % i))
520 module.add(SAddCU32(dst=sgpr(tmpSgpr1), src0=sgpr(tmpSgpr1), src1=sgpr(tmpSgpr3), comment="Free%u" % i))
521 module.add(SLShiftLeftB64(dst=sgpr(tmpSgprX2,2), src=sgpr(tmpSgprX2,2), shiftHex=log2(writer.states.bpeCinternal), comment="scale by bpe"))
522 module.add(SAddU32(dst=sgpr("SrdD+0"), src0=sgpr("SrdD+0"), src1=sgpr(tmpSgprX2), comment="add lo GSU offset to SRD"))
523 module.add(SAddCU32(dst=sgpr("SrdD+1"), src0=sgpr("SrdD+1"), src1=sgpr(tmpSgpr1), comment="add hi GSU offset to SRD"))
524 module.add(gsuLabel)
525
526 return module
527
528 def noLoadLoop(self, writer, kernel, tensorParametersA, tensorParametersB, pack):
529 module = Module("GSU On noLoadLoop")
530
531 isDTV = (kernel["DirectToVgprA"] or kernel["DirectToVgprB"])
532 needSecondNLL = isDTV # need 2 NLL for 2 buffers (PGR1/2)
533 NLLnum = 2 if needSecondNLL else 1
534 gsuLabel = Label(label=writer.labels.getNameInc("GSU"), comment="")
535 with writer.allocTmpSgpr(1) as tmpSgprGSU:
536 module.add(SAndB32(dst=sgpr(tmpSgprGSU.idx), src0=sgpr("GSU"), src1=hex(0x3FFF), comment="Restore GSU"))
537 module.add(SCmpEQU32(src0=sgpr(tmpSgprGSU.idx), src1=1, comment="GSU == 1 ?"))
538 noLoadLoopModules = None
539 acclen = 0
540 gsuBackup = kernel["GlobalSplitU"]
541 gsuAccumBackup = kernel["_GlobalAccumulation"]
542 bpeCexternalBackup = writer.states.bpeCexternal
543 kernel["GlobalSplitU"] = 1
544 kernel["_GlobalAccumulation"] = None
545 writer.states.bpeCexternal = writer.states.bpeCexternalGSU1
546 if kernel["KernelLanguage"] == "Assembly" and kernel["OptNoLoadLoop"] and \
547 kernel["BufferLoad"] and kernel["BufferStore"] and writer.states.doShadowInit and \
548 kernel["LocalSplitU"]==1 and \
549 writer.states.actualSummationLoops==1:
550
551 # two different noLoadLoops:
552 # 1. OptNLL & PAP global-read interleaved (only for PAP=ON)
553 # (2. OptNLL : No PAP global-read (For PAP=OFF, or PAP=ON but the last tile))
554 # -> this is unified with 1. global-read is invalidated at the last tile.
555 # 3. OrdinaryNLL (Not Opt.)
556
557 noLoadLoopModules = Module("noLoadLoop")
558 for NLLindex in range(0, NLLnum):
559 writer.saveLocalPointers(kernel, tensorParametersA, tensorParametersB)
560 # copy pack
561 if NLLindex == NLLnum - 1 or (writer.states.packDTVA or writer.states.packDTVB or writer.states.convDTVA or writer.states.convDTVB):
562 # last NLL or pack DTV case, no deep copy for pack
563 # pack code for local prefetch is generated in noLoadLoopBody and used for DTV even
564 deepCopyPack = pack
565 else:
566 # deepCopy packCode for OptNLL noLoadLoop
567 deepCopyPack = deepcopy(pack)
568 noLoadLoopModules.add(writer.noLoadLoop(kernel, tensorParametersA, tensorParametersB, isOptNLL=True, isNGLL=False, pack=deepCopyPack, NLLindex=NLLindex, NLLnum=NLLnum))
569 writer.restoreLocalPointers(kernel, tensorParametersA, tensorParametersB)
570
571 acclen = countInstruction(noLoadLoopModules)
572 kernel["GlobalSplitU"] = gsuBackup
573 kernel["_GlobalAccumulation"] = gsuAccumBackup
574 writer.states.bpeCexternal = bpeCexternalBackup
575
576 if acclen > 16384:
577 with writer.allocTmpSgpr(3) as tmpSgprInfo:
578 module.add(writer.longBranchScc0(gsuLabel, posNeg=1, tmpSgprInfo=tmpSgprInfo, comment="branch if GSU != 1"))
579 else:
580 module.add(SCBranchSCC0(labelName=gsuLabel.getLabelName(), comment="branch if GSU != 1"))
581
582 if noLoadLoopModules != None:
583 module.add(noLoadLoopModules)
584 module.add(gsuLabel)
585
586 return module
587
588 def tailLoopNumIter(self, writer, kernel, loopCounter):
589 module = Module("GSU On tailLoopNumIter")
590
591 with writer.allocTmpSgpr(3) as tmpSgprInfo:
592 tmpSgpr = tmpSgprInfo.idx
593 remainder = "GSUSumIdx+1" # numIterPerWgRemainder
594 gsucLabel = Label(label=writer.labels.getNameInc("GSUC_TL"), comment="")
595 gsucLabelEnd = Label(label=writer.labels.getNameInc("GSUC_TL_End"), comment="")
596 module.add(SAndB32(dst=sgpr(tmpSgpr), src0=sgpr("GSU"), src1=hex(0x8000), comment="SCC = (GSUC == 1) ?"))
597 module.add(SCBranchSCC1(labelName=gsucLabel.getLabelName(), comment="branch if GSUC == 1"))
598 # if GSU numIter=0 if gsuSumIdx != numIterPerWgRemainder
599 module.add(SCmpLgU32(src0=sgpr("GSUSumIdx"), src1=sgpr("GSUSumIdx+1"), comment="gsuSumIdx == numIterPerWgRemainder"))
600 module.add(SCMovB32(dst=loopCounter, src=0, comment="numIter=0 if gsuSimIdx != numIterPerWgRemainder"))
601 module.add(SBranch(gsucLabelEnd.getLabelName()))
602 module.add(gsucLabel)
603 # calculate the lastWg
604 tmpVgpr = writer.vgprPool.checkOut(2,"tmp")
605 tmpVgprRes = ContinuousRegister(idx=tmpVgpr, size=2)
606 module.add(SLShiftRightB32(dst=sgpr(tmpSgpr+1), src=sgpr("SizesSum"), shiftHex=log2(kernel["DepthU"]), \
607 comment="s%s = s[sgprSizesSum] / %s"%(tmpSgpr+1,kernel["DepthU"])))
608 module.add(SAndB32(dst=sgpr(tmpSgpr+2), src0=sgpr("GSU"), src1=hex(0x3FFF), comment="Restore GSU"))
609 module.add(scalarUInt32DivideAndRemainder(tmpSgpr, tmpSgpr+1, tmpSgpr+2, remainder, tmpVgprRes, kernel["WavefrontSize"]))
610 module.add(SSubU32(dst=sgpr(tmpSgpr+1), src0=sgpr(tmpSgpr+2), src1=1, comment="GSU-1"))
611 writer.vgprPool.checkIn(tmpVgpr)
612 module.add(SCmpEQU32(src0=sgpr(tmpSgpr), src1=0, comment="quotient == 0"))
613 module.add(SCSelectB32(dst=sgpr(tmpSgpr), src0=sgpr("GSUSumIdx+1"), src1=sgpr(tmpSgpr+1), \
614 comment="lastWg = (quotient==0) ? numIterPerWgRemainder : GSU-1"))
615 # if GSU numIter=0 if gsuSumIdx != lastWg
616 module.add(SCmpLgU32(src0=sgpr("GSUSumIdx"), src1=sgpr(tmpSgpr), comment="gsuSumIdx == lastWg"))
617 module.add(SCMovB32(dst=loopCounter, src=0, comment="numIter=0 if gsuSumIdx != lastWg"))
618 module.add(gsucLabelEnd)
619
620 return module
621
622 def setupNewTile(self, writer, kernel, tensorParametersA, tensorParametersB, tPM):
623 module = Module("GSU On setupNewTile")
624
625 addBranch = False
626 for i in reversed(range(kernel["ProblemType"]["NumIndicesSummation"])):
627 if i != writer.states.unrollIdx:
628 addBranch = True
629 break
630 if addBranch:
631 gsuBackup = kernel["GlobalSplitU"]
632 gsuLabel = Label(label=writer.labels.getNameInc("GSU"), comment="")
633 gsuLabelEnd = Label(label=writer.labels.getNameInc("GSU_End"), comment="")
634 with writer.allocTmpSgpr(1) as tmpSgprGSU:
635 module.add(SAndB32(dst=sgpr(tmpSgprGSU.idx), src0=sgpr("GSU"), src1=hex(0x3FFF), comment="Restore GSU"))
636 module.add(SCmpEQU32(src0=sgpr(tmpSgprGSU.idx), src1=1, comment="GSU == 1 ?"))
637 module.add(SCBranchSCC1(labelName=gsuLabel.getLabelName(), comment="branch if GSU == 1"))
638 module.addComment1("global read addresses: increments a")
639 kernel["GlobalSplitU"] = 2
640 module.add(self.graIncrementsAB(writer, kernel, tensorParametersA, tensorParametersB, tPM))
641 if addBranch:
642 module.add(SBranch(gsuLabelEnd.getLabelName()))
643 module.add(gsuLabel)
644 kernel["GlobalSplitU"] = 1
645 module.add(self.graIncrementsAB(writer, kernel, tensorParametersA, tensorParametersB, tPM))
646 kernel["GlobalSplitU"] = gsuBackup
647 module.add(gsuLabelEnd)
648
649 return module
650
651 def GSUSynccodegen(self, writer, kernel, tmpVgpr, tmpVgprSize, tmpVgprDynamic, batchIdx, ss, gwvw, batchElements, labelend, vgprstart, globalOffset, vgproffset):
652 module = Module("GSUSYNC")
653
654 # dot2: enable GSU for non-MFMA mode
655 if kernel["EnableMatrixInstruction"]:
656 WaveNum = str(kernel["MIWaveGroup"][0]*kernel["MIWaveGroup"][1])
657 else:
658 WaveNum = str(kernel["NumThreads"] // kernel["WavefrontSize"])
659
660 module.addComment("check done start")
661
662 #####################################synchronizer offset cal and set synchronizer#####################################
663 #####################################WaveId+WgId*WaveNum+WgNum*WaveNum*Batch
664 #####################################WgId+WaveId*WgNum+WgNum*WaveNum*Batch
665 module.addComment("synchronizer offset cal")
666
667 tmpS02 = writer.sgprPool.checkOut(1, preventOverflow=False) #
668 tmpS01 = writer.sgprPool.checkOut(1, preventOverflow=False) #
669 tmpS03 = writer.sgprPool.checkOut(1, preventOverflow=False) #
670
671 module.add(SMulI32(dst=sgpr(tmpS03), src0=sgpr("NumWorkGroups1"), src1=sgpr("NumWorkGroups0"), comment=""))
672 module.add(SMulI32(dst=sgpr(tmpS02), src0=sgpr(tmpS03), src1=sgpr("WorkGroup2"), comment=""))
673 module.add(SMulI32(dst=sgpr(tmpS01), src0=sgpr("WorkGroup1"), src1=sgpr("NumWorkGroups0"), comment=""))
674 module.add(SAddU32(dst=sgpr(tmpS01), src0=sgpr(tmpS01), src1=sgpr("WorkGroup0")))
675 module.add(SAddU32(dst=sgpr(tmpS01), src0=sgpr(tmpS01), src1=sgpr(tmpS02)))
676
677 module.add(VReadfirstlaneB32(dst=sgpr(tmpS02), src=vgpr("Serial")))
678
679 module.add(SMulI32(dst=sgpr(tmpS03), src0=sgpr(tmpS03), src1=sgpr("SizeK"), comment="cal a wave offset"))
680 module.add(SLShiftRightB32(dst=sgpr(tmpS02), shiftHex=hex(log2(kernel["WavefrontSize"])), src=sgpr(tmpS02)))
681 module.add(SMulI32(dst=sgpr(tmpS02), src0=sgpr(tmpS03), src1=sgpr(tmpS02), comment="wave offset at batch")) # WaveId*WgNum
682 module.add(SAddU32(dst=sgpr(tmpS01), src0=sgpr(tmpS02), src1=sgpr(tmpS01))) # WaveId*WgNum+WgId
683 if batchIdx > 0:
684 module.add(SMulI32(dst=sgpr(tmpS03), src0=sgpr(tmpS03), src1=int(WaveNum), comment="cal a batch offset")) # WgNum*WaveNum
685 module.add(SMulI32(dst=sgpr(tmpS03), src0=sgpr(tmpS03), src1=batchIdx, comment="this batch offset")) # WgNum*WaveNum*Batch
686 module.add(SAddU32(dst=sgpr(tmpS01), src0=sgpr(tmpS01), src1=sgpr(tmpS03))) # WaveId*WgNum+WgId + WgNum*WaveNum*Batch
687 module.add(SLShiftLeftB32(dst=sgpr(tmpS01), src=sgpr(tmpS01), shiftHex=hex(2), comment="")) # atomic 32bits
688 #####################################set synchronizer
689 module.add(SAddU32(dst=sgpr("SrdSync+0"), \
690 src0=sgpr("Synchronizer+0"), \
691 src1=sgpr(tmpS01), \
692 comment="" ))
693 module.add(SAddCU32(dst=sgpr("SrdSync+1"), \
694 src0=sgpr("Synchronizer+1"), \
695 src1=0, \
696 comment="" ))
697
698 module.add(SWaitCnt(waitAll=True, comment="wait store done before synchronizer start load and add"))
699 module.add(SAndB32(dst=sgpr(tmpS02), src0=sgpr("GSU"), src1=hex(0x3FFF), comment="Restore GSU"))
700 module.add(SSubU32(dst=sgpr(tmpS02), src0=sgpr(tmpS02), src1=hex(1), comment=""))
701 module.add(SAtomicDec(dst=sgpr(tmpS02), base=sgpr("SrdSync", 2), smem=SMEMModifiers(glc=True)))
702 module.addSpaceLine()
703 #####################################cal synchronizer sum offset#####################################
704 module.addComment("synchronizer sum offset cal")
705
706 tmpS04 = writer.sgprPool.checkOutAligned(2,2, preventOverflow=False) #
707 tmpS05 = writer.sgprPool.checkOutAligned(2,2, preventOverflow=False) #
708
709 indices = list(range(0, kernel["ProblemType"]["NumIndicesC"]))
710 numDim = len(indices)
711 tmpSgpr1 = writer.sgprPool.checkOut(2, preventOverflow=False)
712 tmpSgpr2 = writer.sgprPool.checkOut(1, preventOverflow=False)
713 tmpSgpr3 = writer.sgprPool.checkOut(1, preventOverflow=False)
714 tmpSgpr4 = writer.sgprPool.checkOut(1, preventOverflow=False)
715
716 module.addModuleAsFlatItems(writer.s_mul_u64_u32(sgpr(tmpSgpr1+0), sgpr(tmpSgpr1+1), sgpr("SizesFree+0"), 1, tmpVgpr, "Free0"))
717
718 for i in range(1, numDim):
719 module.add(SSubU32(dst=sgpr(tmpSgpr4), src0=sgpr("SizesFree+%u" % i), src1=1, comment="Free%u" % i))
720 module.add(SMulI32(dst=sgpr(tmpSgpr4), src0=sgpr(tmpSgpr4), src1=1, comment="Free%u" % i))
721 module.addModuleAsFlatItems(writer.s_mul_u64_u32(sgpr(tmpSgpr2), sgpr(tmpSgpr3), sgpr(tmpSgpr4), sgpr("StrideC%s" % writer.states.indexChars[i]), tmpVgpr, "Free%u" % i))
722 module.add(SAddU32(dst=sgpr(tmpSgpr1+0), src0=sgpr(tmpSgpr1+0), src1=sgpr(tmpSgpr2), comment="Free%u" % i))
723 module.add(SAddCU32(dst=sgpr(tmpSgpr1+1), src0=sgpr(tmpSgpr1+1), src1=sgpr(tmpSgpr3), comment="Free%u" % i))
724
725 bpetmp = int(writer.states.bpr * kernel["ProblemType"]["DestDataType"].numRegisters()) # self.states.bpeCinternal
726 module.add(SLShiftLeftB64(dst=sgpr(tmpS04, 2), src=sgpr(tmpSgpr1+0, 2), shiftHex=log2(writer.states.bpeCexternal), comment="scale by bpe"))
727
728 writer.sgprPool.checkIn(tmpSgpr1)
729 writer.sgprPool.checkIn(tmpSgpr2)
730 writer.sgprPool.checkIn(tmpSgpr3)
731 writer.sgprPool.checkIn(tmpSgpr4)
732
733 module.addSpaceLine()
734 #####################################cal synchronizer sum start#####################################
735 # no need to do because we have workspace start sgpr
736 #####################################check synchronizer done#####################################
737 checkSyncCode = Module("check synchronizer done")
738 checkSyncCode.addComment("check synchronizer done")
739
740 checkSyncCode.add(SWaitCnt(kmcnt=0, comment="Wait for synchronizer"))
741 checkSyncCode.add(SCmpEQU32(
742 src0=sgpr(tmpS02), \
743 src1=hex(1), \
744 comment=""))
745
746 # checkSyncCode.add(SCBranchSCC0(labelName=labelendname, comment=""))
747 branch: Module = writer.longBranchScc0(label=labelend, posNeg=1, tmpSgprInfo=None, comment="long branch sync")
748 rowIncrement = Module('Skip and row increment')
749 totalNumRows = sum(addrCalc.rowInc for addrCalc in ss.elementAddr)
750
751 if totalNumRows > 0 and ss.optSrdIncForRow:
752 dstBpe = int(writer.states.bpr * kernel["ProblemType"]["DestDataType"].numRegisters())
753 wsBpe = int(writer.states.bpr * kernel["ProblemType"]["ComputeDataType"].numRegisters())
754 packedC1 = kernel["PackedC1IndicesX"]
755 pIdx = writer.states.indexChars[packedC1[0]]
756 rowIncrement.add(AddrCalculation.incrementSrdMultipleRows("SrdTD", f"StrideD{pIdx}", tmpS01, totalNumRows, dstBpe))
757 rowIncrement.add(AddrCalculation.incrementSrdMultipleRows("WSDstart", f"StrideD{pIdx}", tmpS01, totalNumRows, wsBpe))
758
759 insertIndex = branch.findIndexByType(SCBranchSCC1)
760
761 if insertIndex is not None and rowIncrement.count():
762 branch.add(rowIncrement, insertIndex+1)
763
764 checkSyncCode.add(branch)
765
766 checkSyncCode.addComment("check done end")
767 checkSyncCode.addSpaceLine()
768 #####################################load buffer#####################################
769 checkSyncCode.addComment("buffer load start")
770 # common variables
771 SyncloadedData = 0
772 tmpS06 = writer.sgprPool.checkOutAligned(4,4, preventOverflow=False) #overflow?
773 addr1 = sgpr(tmpS06, 4)
774 addr0 = vgpr(vgproffset)
775 bps = kernel["ProblemType"]["ComputeDataType"].numBytes() * gwvw
776
777 if not kernel["MbskPrefetchMethod"]:
778 for elementIdx in range(0, len(batchElements)):
779 mask = ss.elementMask[elementIdx]
780 addrCalc: AddrCalculation = ss.elementAddr[elementIdx]
781 SyncloadedData = 0
782
783 SynchronizerAddSkiplabelString = "Synchronizer_read_add_skip"
784 SynchronizerAddSkipComment = "Synchronizer read add skip"
785 SynchronizerAddSkiplabel = Label(writer.labels.getNameInc(SynchronizerAddSkiplabelString), SynchronizerAddSkipComment)
786
787 addr0 = vgpr(addrCalc.addrDVgpr)
788
789 GSUtotal = writer.getMBSKGSUTotal(kernel)
790 SynchronizerAddEndlabel = [""] * GSUtotal
791
792 for idx in range(0, GSUtotal):
793 SynchronizerAddEndlabelString = "Synchronizer_read_add_end_"+str(idx+1)
794 SynchronizerAddEndComment = "Synchronizer read add end_"+str(idx+1)
795 SynchronizerAddEndlabel[idx] = Label(writer.labels.getNameInc(SynchronizerAddEndlabelString), SynchronizerAddEndComment)
796
797 bufferOOB = tmpVgpr + tmpVgprSize - 1
798 module.add(VMovB32(dst=vgpr(bufferOOB), src="BufferOOB"))
799
800 module.add(SMovB32(sgpr(tmpS06+0), sgpr("WSDstart+0"), "Move workspace start"))
801 module.add(SMovB32(sgpr(tmpS06+1), sgpr("WSDstart+1"), "Move workspace start"))
802 module.add(SMovB32(sgpr(tmpS06+2), sgpr("SrdD+2"), ""))
803 module.add(SMovB32(sgpr(tmpS06+3), sgpr("SrdD+3"), ""))
804
805 if elementIdx == 0:
806 # Insert check synchronizer done code here for better scheduling
807 module.add(checkSyncCode)
808
809 for times in range(elementIdx, elementIdx+1):
810 addrCalctmp: AddrCalculation = ss.elementAddr[times]
811 if ss.optSrdIncForRow and addrCalctmp.rowInc:
812 module.add(addrCalctmp.incrementToNextRow(kernel, "D", ss, tmpS05, dst=tmpS06))
813 module.add(SAddU32(dst=sgpr("WSDstart+0"), \
814 src0=sgpr("WSDstart+0"), \
815 src1=sgpr(tmpS05), \
816 comment="" ))
817 module.add(SAddCU32(dst=sgpr("WSDstart+1"), \
818 src0=sgpr("WSDstart+1"), \
819 src1=0, \
820 comment="" ))
821
822 vgprstart = ss.elementSumIdx[elementIdx] #here
823 dataType = kernel["ProblemType"]["DestDataType"]
824 if dataType.isDouble() or dataType.isSingleComplex():
825 vgprstart = vgprstart*2
826 module.add(writer.chooseGlobalRead(True, bps, vgprstart, \
827 addr0, addr1, soffset=0, offset=addrCalc.globalOffset, glc=True, slc=True,\
828 comment="load GSU D 0 "+str(vgprstart)))
829 SyncloadedData += 1
830
831 module.add(SAndB32(dst=sgpr("GSUSync"), src0=sgpr("GSU"), src1=hex(0x3FFF), comment="Restore GSU"))
832
833 SynchronizerlabelString = "Synchronizer_read_add"
834 SynchronizerComment = "Synchronizer read add"
835 Synchronizerlabel = Label(writer.labels.getNameInc(SynchronizerlabelString), SynchronizerComment)
836
837 tmpVAdd = tmpVgprDynamic
838 GSUMvgpr = tmpVgpr
839
840 GSUP1 = GSUtotal-1
841
842 for i in range(0,GSUP1):
843 module.add(SSubI32(dst=sgpr("GSUSync"), src0=sgpr("GSUSync"), src1=1, comment="%u" % i))
844
845 module.add(SAddU32(dst=sgpr(tmpS06+0), \
846 src0=sgpr(tmpS06+0), \
847 src1=sgpr(tmpS04+0), \
848 comment="" ))
849 module.add(SAddCU32(dst=sgpr(tmpS06+1), \
850 src0=sgpr(tmpS06+1), \
851 src1=sgpr(tmpS04+1), \
852 comment="" ))
853
854 module.add(SCmpEQI32(src0=sgpr("GSUSync"), src1=0, comment=""))#GSUSync+GSUP1==GSU
855 module.add(SCBranchSCC1(labelName=SynchronizerAddEndlabel[i].getLabelName(), comment="SyncAddbranchhere"))
856
857 if(kernel["ProblemType"]["DestDataType"].numRegisters() > 1):
858 module.add(writer.chooseGlobalRead(True, bps, tmpVAdd+gwvw*kernel["ProblemType"]["DestDataType"].numRegisters()*i, \
859 addr0, addr1, soffset=0, offset=addrCalc.globalOffset, glc=True, slc=True, \
860 comment="load GSU DD %u %u %u" % (bps, gwvw, kernel["ProblemType"]["DestDataType"].numRegisters())))
861 else:
862 module.add(writer.chooseGlobalRead(True, bps, tmpVAdd+gwvw*i, \
863 addr0, addr1, soffset=0, offset=addrCalc.globalOffset, glc=True, slc=True, \
864 comment="load GSU DD %u %u %u" % (bps, gwvw, kernel["ProblemType"]["DestDataType"].numRegisters())))
865
866 SyncloadedData += 1
867 module.addComment("buffer load end\n")
868
869 #####################################> GSUtotal reduction start#####################################
870 module.addComment("buffer add start")
871 vlcnt = SyncloadedData = SyncloadedData -1
872
873 module.add(Synchronizerlabel)
874
875 for i in range(0, GSUP1):
876 module.addSpaceLine()
877 vlcnt = SyncloadedData = SyncloadedData -1
878 module.add(SWaitCnt(vlcnt=vlcnt, comment="(wait for buffer ready)"))
879
880 if kernel["ProblemType"]["DataType"].isInt8() or kernel["ProblemType"]["DataType"].isInt32():
881 for j in range(0, int(gwvw)):
882 module.add(VAddI32(dst=vgpr(vgprstart+j), src0=vgpr(vgprstart+j), src1=vgpr(tmpVAdd+0+gwvw*i+j), \
883 comment="buffer add"))
884 else:
885 if ((gwvw % 2) == 1):
886 for j in range(0, int(gwvw)):
887 module.add(VAddF32(dst=vgpr(vgprstart+j), src0=vgpr(vgprstart+j), src1=vgpr(tmpVAdd+0+gwvw*i+j), \
888 comment="buffer add"))
889 else:
890 for j in range(0, int(gwvw/2)):
891 module.add(VAddPKF32(dst=vgpr(vgprstart+j*2, 2), src0=vgpr(vgprstart+j*2, 2), \
892 src1=vgpr(tmpVAdd+0+gwvw*i+j*2, 2), comment="buffer pk"))
893
894 module.add(SSubI32(dst=sgpr("GSUSync"), src0=sgpr("GSUSync"), src1=1, comment="%u" % i))
895 module.add(SCmpLeI32(src0=sgpr("GSUSync"), src1=0-(GSUP1-1), comment=""))#GSUSync+GSUP1==GSU
896 module.add(SCBranchSCC1(labelName=SynchronizerAddSkiplabel.getLabelName(), comment="SyncAddbranch"))
897
898 module.add(SAddU32(dst=sgpr(tmpS06+0), \
899 src0=sgpr(tmpS06+0), \
900 src1=sgpr(tmpS04+0), \
901 comment="" ))
902 module.add(SAddCU32(dst=sgpr(tmpS06+1), \
903 src0=sgpr(tmpS06+1), \
904 src1=sgpr(tmpS04+1), \
905 comment="" ))
906
907 module.add(VCmpGEI32(dst=sgpr(tmpS05,2), src0=0, src1=sgpr("GSUSync"), comment=""))
908 module.add(VCndMaskB32(
909 dst=vgpr(GSUMvgpr), \
910 src1=vgpr(bufferOOB), \
911 src0=addr0, \
912 src2=sgpr(tmpS05,2), \
913 comment="protect if OOB"))
914
915 if(kernel["ProblemType"]["DestDataType"].numRegisters() > 1):
916 module.add(writer.chooseGlobalRead(True, bps, tmpVAdd+gwvw*kernel["ProblemType"]["DestDataType"].numRegisters()*i, \
917 vgpr(GSUMvgpr), addr1, soffset=0, offset=addrCalc.globalOffset, glc=True, slc=True, \
918 comment="load GSU DD %u" % bps))
919 else:
920 module.add(writer.chooseGlobalRead(True, bps, tmpVAdd+gwvw*i, \
921 vgpr(GSUMvgpr), addr1, soffset=0, offset=addrCalc.globalOffset, glc=True, slc=True, \
922 comment="load GSU DD %u" % bps))
923
924 SyncloadedData += 1
925
926 module.addComment("buffer add end\n")
927
928 module.add(SCmpGtI32(
929 src0=sgpr("GSUSync"), \
930 src1=hex(1-(GSUP1)), \
931 comment=""))
932 module.add(SCBranchSCC1(labelName=Synchronizerlabel.getLabelName(), comment="Syncbranchhere"))
933
934 #####################################< GSUtotal reduction start#####################################
935 for k in range(GSUtotal-2, -1, -1):
936 module.addSpaceLine()
937 module.add(SynchronizerAddEndlabel[k])
938
939 vlcnt = k
940 for i in range(0, k):
941 module.addSpaceLine()
942 vlcnt = vlcnt -1 if vlcnt > 0 else 0
943 module.add(SWaitCnt(vlcnt=vlcnt, comment="(wait for buffer ready)"))
944 if kernel["ProblemType"]["DataType"].isInt8() or kernel["ProblemType"]["DataType"].isInt32():
945 for j in range(0, int(gwvw)):
946 module.add(VAddI32(dst=vgpr(vgprstart+j), src0=vgpr(vgprstart+j), src1=vgpr(tmpVAdd+0+gwvw*i+j), \
947 comment="buffer add"))
948 else:
949 if ((gwvw % 2) == 1):
950 for j in range(0, int(gwvw)):
951 module.add(VAddF32(dst=vgpr(vgprstart+j), src0=vgpr(vgprstart+j), src1=vgpr(tmpVAdd+0+gwvw*i+j), \
952 comment="buffer add"))
953 else:
954 for j in range(0, int(gwvw/2)):
955 module.add(VAddPKF32(dst=vgpr(vgprstart+j*2, 2), src0=vgpr(vgprstart+j*2, 2), \
956 src1=vgpr(tmpVAdd+0+gwvw*i+j*2, 2), comment="buffer pk"))
957
958 if i == k-1:
959 module.add(SBranch(labelName=SynchronizerAddSkiplabel.getLabelName(), comment="SyncAddbranch"))
960
961 module.add(SynchronizerAddSkiplabel)
962 module.addComment("buffer add end2\n")
963
964 else:
965 tmpWSD = writer.sgprPool.checkOutAligned(4, 4, preventOverflow=False)
966 GSUtotal = writer.getMBSKGSUTotal(kernel)-1
967 loadWidth = gwvw * int(max(1, kernel["ProblemType"]["DestDataType"].numRegisters()))
968 unrolledWGs = GSUtotal // len(batchElements)
969 tmpVidx = tmpVgprDynamic
970 tmpVAdd = [[0] * len(batchElements) for _ in range(unrolledWGs)]
971 for i in range(0, unrolledWGs):
972 for j in range(0, len(batchElements)):
973 tmpVAdd[i][j] = tmpVidx
974 tmpVidx += loadWidth
975
976 SynchronizerAddEndlabel = [""] * (unrolledWGs+1)
977
978 for idx in range(0, unrolledWGs+1):
979 SynchronizerAddEndlabelString = "Synchronizer_read_add_end_"+str(idx+1)
980 SynchronizerAddEndComment = "Synchronizer read add end_"+str(idx+1)
981 SynchronizerAddEndlabel[idx] = Label(writer.labels.getNameInc(SynchronizerAddEndlabelString), SynchronizerAddEndComment)
982
983 # set buffer load address for WG0
984 module.add(SMovB64(sgpr(tmpWSD+0, 2), sgpr("WSDstart+0", 2), "Move workspace start"))
985 module.add(SMovB64(sgpr(tmpWSD+2, 2), sgpr("SrdD+2", 2), ""))
986
987 # Insert check synchronizer done code here for better scheduling
988 module.add(checkSyncCode)
989
990 # set buffer load address for WG1
991 module.add(SAddU32(dst=sgpr("WSDstart+0"), src0=sgpr("WSDstart+0"), src1=sgpr(tmpS04+0), comment="" ))
992 module.add(SAddCU32(dst=sgpr("WSDstart+1"), src0=sgpr("WSDstart+1"), src1=sgpr(tmpS04+1), comment="" ))
993 module.add(SMovB64(sgpr(tmpS06+0, 2), sgpr("WSDstart+0", 2), "Move workspace start"))
994 module.add(SMovB64(sgpr(tmpS06+2, 2), sgpr("SrdD+2", 2), ""))
995
996 accumulationStartlabel = Label(writer.labels.getNameInc("Accumulation_Start"), "Accumulation Start")
997 accumulationEndlabel = Label(writer.labels.getNameInc("Accumulation_End"), "Accumulation End")
998 module.add(SAndB32(dst=sgpr("GSUSync"), src0=sgpr("GSU"), src1=hex(0x3FFF), comment="Restore GSU"))
999
1000 # pre-load
1001 SyncloadedData = 0
1002
1003 # first 2 WGs: read same element first for earlier reduction
1004 for elementIdx in range(0, len(batchElements)):
1005 addrCalc: AddrCalculation = ss.elementAddr[elementIdx]
1006 addr0 = vgpr(addrCalc.addrDVgpr)
1007 for uidx in range(0, 2):
1008 if uidx == 0:
1009 data = ss.elementSumIdx[elementIdx]
1010 tmpAddr1 = tmpWSD
1011 else:
1012 data = tmpVAdd[-1][elementIdx]
1013 tmpAddr1 = tmpS06
1014
1015 if ss.optSrdIncForRow and addrCalc.rowInc:
1016 module.add(addrCalc.incrementToNextRow(kernel, "D", ss, tmpS05, dst=tmpAddr1))
1017
1018 module.add(writer.chooseGlobalRead(True, bps, data, \
1019 addr0, sgpr(tmpAddr1, 4), soffset=0, offset=addrCalc.globalOffset, glc=True, slc=True,\
1020 comment="load GSU WG %d element %d " % (uidx, elementIdx)))
1021
1022 SyncloadedData += 1
1023
1024 module.add(SSubI32(dst=sgpr("GSUSync"), src0=sgpr("GSUSync"), src1=2))
1025 module.add(SCmpLeI32(src0=sgpr("GSUSync"), src1=0, comment="GSUSync <= 0?"))
1026 module.add(SCBranchSCC1(labelName=SynchronizerAddEndlabel[1].getLabelName(), comment=""))
1027 module.add(SAddU32(dst=sgpr("WSDstart+0"), src0=sgpr("WSDstart+0"), src1=sgpr(tmpS04+0), comment="" ))
1028 module.add(SAddCU32(dst=sgpr("WSDstart+1"), src0=sgpr("WSDstart+1"), src1=sgpr(tmpS04+1), comment="" ))
1029 module.add(SMovB64(sgpr(tmpS06+0, 2), sgpr("WSDstart+0", 2), "Move workspace start"))
1030
1031 # other WGs: read all elements together
1032 for uidx in range(2, unrolledWGs+1):
1033 for elementIdx in range(0, len(batchElements)):
1034 addrCalc: AddrCalculation = ss.elementAddr[elementIdx]
1035 addr0 = vgpr(addrCalc.addrDVgpr)
1036 data = tmpVAdd[uidx-2][elementIdx]
1037
1038 if ss.optSrdIncForRow and addrCalc.rowInc:
1039 module.add(addrCalc.incrementToNextRow(kernel, "D", ss, tmpS05, dst=tmpS06))
1040
1041 module.add(writer.chooseGlobalRead(True, bps, data, \
1042 addr0, addr1, soffset=0, offset=addrCalc.globalOffset, glc=True, slc=True,\
1043 comment="load GSU WG %d element %d " % (uidx, elementIdx)))
1044 SyncloadedData += 1
1045
1046 module.add(SSubI32(dst=sgpr("GSUSync"), src0=sgpr("GSUSync"), src1=1))
1047 module.add(SCmpLeI32(src0=sgpr("GSUSync"), src1=0, comment="GSUSync <= 0?"))
1048 module.add(SCBranchSCC1(labelName=SynchronizerAddEndlabel[uidx].getLabelName(), comment=""))
1049 module.add(SAddU32(dst=sgpr("WSDstart+0"), src0=sgpr("WSDstart+0"), src1=sgpr(tmpS04+0), comment="" ))
1050 module.add(SAddCU32(dst=sgpr("WSDstart+1"), src0=sgpr("WSDstart+1"), src1=sgpr(tmpS04+1), comment="" ))
1051 module.add(SMovB64(sgpr(tmpS06+0, 2), sgpr("WSDstart+0", 2), "Move workspace start"))
1052
1053 module.addComment("buffer load end\n")
1054
1055 ##################################### reduction start #####################################
1056 module.addComment("buffer add start")
1057
1058 vlcnt = SyncloadedData
1059
1060 # reduce first 2 WGs
1061 for elementIdx in range(0, len(batchElements)):
1062 addrCalc: AddrCalculation = ss.elementAddr[elementIdx]
1063 addr0 = vgpr(addrCalc.addrDVgpr)
1064 data = tmpVAdd[-1][elementIdx]
1065 vgprstart = ss.elementSumIdx[elementIdx]
1066 vlcnt = vlcnt - 2 if vlcnt > 0 else 0
1067
1068 module.add(SWaitCnt(vlcnt=vlcnt, comment="(wait for buffer ready)"))
1069 if kernel["ProblemType"]["DataType"].isInt8() or kernel["ProblemType"]["DataType"].isInt32():
1070 for j in range(0, int(gwvw)):
1071 module.add(VAddI32(dst=vgpr(vgprstart+j), src0=vgpr(vgprstart+j), src1=vgpr(data+j), \
1072 comment="buffer add"))
1073 else:
1074 if ((gwvw % 2) == 1):
1075 for j in range(0, int(gwvw)):
1076 module.add(VAddF32(dst=vgpr(vgprstart+j), src0=vgpr(vgprstart+j), src1=vgpr(data+j), \
1077 comment="buffer add"))
1078 else:
1079 for j in range(0, int(gwvw/2)):
1080 module.add(VAddPKF32(dst=vgpr(vgprstart+j*2, 2), src0=vgpr(vgprstart+j*2, 2), \
1081 src1=vgpr(data+j*2, 2), comment="buffer pk"))
1082
1083 # prefetch
1084 if ss.optSrdIncForRow and addrCalc.rowInc:
1085 module.add(addrCalc.incrementToNextRow(kernel, "D", ss, tmpS05, dst=tmpS06))
1086
1087 module.add(writer.chooseGlobalRead(True, bps, data, \
1088 addr0, addr1, soffset=0, offset=addrCalc.globalOffset, glc=True, slc=True,\
1089 comment="prefetch element %d " % (elementIdx)))
1090 vlcnt += 1
1091
1092 module.add(SSubI32(dst=sgpr("GSUSync"), src0=sgpr("GSUSync"), src1=1))
1093 module.add(SCmpLeI32(src0=sgpr("GSUSync"), src1=0-unrolledWGs, comment=""))
1094 module.add(SCBranchSCC1(labelName=accumulationEndlabel.getLabelName(), comment="Accumulation finished"))
1095 module.add(SAddU32(dst=sgpr("WSDstart+0"), src0=sgpr("WSDstart+0"), src1=sgpr(tmpS04+0), comment="" ))
1096 module.add(SAddCU32(dst=sgpr("WSDstart+1"), src0=sgpr("WSDstart+1"), src1=sgpr(tmpS04+1), comment="" ))
1097 module.add(SMovB64(sgpr(tmpS06+0, 2), sgpr("WSDstart+0", 2), "Move workspace start"))
1098 module.add(SCmpLeI32(src0=sgpr("GSUSync"), src1=0, comment="disable buffer load if GSUSync <= 0"))
1099 module.add(SCSelectB32(sgpr(tmpS06+2), 0, sgpr(tmpS06+2), ""))
1100 module.add(accumulationStartlabel)
1101
1102 for uidx in range(0, unrolledWGs):
1103 for elementIdx in range(0, len(batchElements)):
1104 addrCalc: AddrCalculation = ss.elementAddr[elementIdx]
1105 addr0 = vgpr(addrCalc.addrDVgpr)
1106 data = tmpVAdd[uidx][elementIdx]
1107 vgprstart = ss.elementSumIdx[elementIdx]
1108 vlcnt = vlcnt -1 if vlcnt > 0 else 0
1109
1110 module.add(SWaitCnt(vlcnt=vlcnt, comment="(wait for buffer ready)"))
1111 if kernel["ProblemType"]["DataType"].isInt8() or kernel["ProblemType"]["DataType"].isInt32():
1112 for j in range(0, int(gwvw)):
1113 module.add(VAddI32(dst=vgpr(vgprstart+j), src0=vgpr(vgprstart+j), src1=vgpr(data+j), \
1114 comment="buffer add"))
1115 else:
1116 if ((gwvw % 2) == 1):
1117 for j in range(0, int(gwvw)):
1118 module.add(VAddF32(dst=vgpr(vgprstart+j), src0=vgpr(vgprstart+j), src1=vgpr(data+j), \
1119 comment="buffer add"))
1120 else:
1121 for j in range(0, int(gwvw/2)):
1122 module.add(VAddPKF32(dst=vgpr(vgprstart+j*2, 2), src0=vgpr(vgprstart+j*2, 2), \
1123 src1=vgpr(data+j*2, 2), comment="buffer pk"))
1124
1125 # prefetch
1126 if ss.optSrdIncForRow and addrCalc.rowInc:
1127 module.add(addrCalc.incrementToNextRow(kernel, "D", ss, tmpS05, dst=tmpS06))
1128
1129 module.add(writer.chooseGlobalRead(True, bps, data, \
1130 addr0, addr1, soffset=0, offset=addrCalc.globalOffset, glc=True, slc=True,\
1131 comment="prefetch element %d " % (elementIdx)))
1132 vlcnt += 1
1133
1134 module.add(SSubI32(dst=sgpr("GSUSync"), src0=sgpr("GSUSync"), src1=1))
1135 module.add(SCmpLeI32(src0=sgpr("GSUSync"), src1=0-unrolledWGs, comment=""))
1136 module.add(SCBranchSCC1(labelName=accumulationEndlabel.getLabelName(), comment="Accumulation finished"))
1137 module.add(SAddU32(dst=sgpr("WSDstart+0"), src0=sgpr("WSDstart+0"), src1=sgpr(tmpS04+0), comment="" ))
1138 module.add(SAddCU32(dst=sgpr("WSDstart+1"), src0=sgpr("WSDstart+1"), src1=sgpr(tmpS04+1), comment="" ))
1139 module.add(SMovB64(sgpr(tmpS06+0, 2), sgpr("WSDstart+0", 2), "Move workspace start"))
1140 module.add(SCmpLeI32(src0=sgpr("GSUSync"), src1=0, comment="disable buffer load if GSUSync <= 0"))
1141 module.add(SCSelectB32(sgpr(tmpS06+2), 0, sgpr(tmpS06+2), ""))
1142
1143 module.add(SBranch(labelName=accumulationStartlabel.getLabelName(), comment=""))
1144
1145 for k in range(unrolledWGs, 0, -1):
1146 module.addSpaceLine()
1147 module.add(SynchronizerAddEndlabel[k])
1148 vlcnt = (k+1) * len(batchElements)
1149
1150 # reduce first 2 WGs
1151 module.addSpaceLine()
1152 for elementIdx in range(0, len(batchElements)):
1153 vlcnt = vlcnt-2 if vlcnt > 0 else 0
1154 vgprstart = ss.elementSumIdx[elementIdx]
1155 data = tmpVAdd[-1][elementIdx]
1156
1157 module.add(SWaitCnt(vlcnt=vlcnt, comment="(wait for buffer ready)"))
1158 if kernel["ProblemType"]["DataType"].isInt8() or kernel["ProblemType"]["DataType"].isInt32():
1159 for j in range(0, int(gwvw)):
1160 module.add(VAddI32(dst=vgpr(vgprstart+j), src0=vgpr(vgprstart+j), src1=vgpr(data+j), \
1161 comment="buffer add"))
1162 else:
1163 if ((gwvw % 2) == 1):
1164 for j in range(0, int(gwvw)):
1165 module.add(VAddF32(dst=vgpr(vgprstart+j), src0=vgpr(vgprstart+j), src1=vgpr(data+j), \
1166 comment="buffer add"))
1167 else:
1168 for j in range(0, int(gwvw/2)):
1169 module.add(VAddPKF32(dst=vgpr(vgprstart+j*2, 2), src0=vgpr(vgprstart+j*2, 2), \
1170 src1=vgpr(data+j*2, 2), comment="buffer pk"))
1171
1172 for i in range(1, k):
1173 module.addSpaceLine()
1174 for elementIdx in range(0, len(batchElements)):
1175 vlcnt = vlcnt-1 if vlcnt > 0 else 0
1176 vgprstart = ss.elementSumIdx[elementIdx]
1177 data = tmpVAdd[i-1][elementIdx]
1178
1179 module.add(SWaitCnt(vlcnt=vlcnt, comment="(wait for buffer ready)"))
1180 if kernel["ProblemType"]["DataType"].isInt8() or kernel["ProblemType"]["DataType"].isInt32():
1181 for j in range(0, int(gwvw)):
1182 module.add(VAddI32(dst=vgpr(vgprstart+j), src0=vgpr(vgprstart+j), src1=vgpr(data+j), \
1183 comment="buffer add"))
1184 else:
1185 if ((gwvw % 2) == 1):
1186 for j in range(0, int(gwvw)):
1187 module.add(VAddF32(dst=vgpr(vgprstart+j), src0=vgpr(vgprstart+j), src1=vgpr(data+j), \
1188 comment="buffer add"))
1189 else:
1190 for j in range(0, int(gwvw/2)):
1191 module.add(VAddPKF32(dst=vgpr(vgprstart+j*2, 2), src0=vgpr(vgprstart+j*2, 2), \
1192 src1=vgpr(data+j*2, 2), comment="buffer pk"))
1193
1194 module.add(SBranch(labelName=accumulationEndlabel.getLabelName(), comment="Accumulation End"))
1195
1196 module.addComment("buffer add end\n")
1197 module.add(accumulationEndlabel)
1198 module.add(SMovB64(sgpr("WSDstart+0", 2), sgpr(tmpWSD+0, 2), "restore for next batch"))
1199 writer.sgprPool.checkIn(tmpWSD)
1200
1201 writer.sgprPool.checkIn(tmpS06)
1202 writer.sgprPool.checkIn(tmpS05)
1203 writer.sgprPool.checkIn(tmpS04)
1204 writer.sgprPool.checkIn(tmpS03)
1205 writer.sgprPool.checkIn(tmpS02)
1206 writer.sgprPool.checkIn(tmpS01)
1207
1208 return module
1209
1210 def globalWriteBatchProlog(self, writer, kernel, tmpVgpr, tmpVgprSize, tmpVgprDynamic, \
1211 batchIdx, ss, gwvw, batchElements, \
1212 beta, edge, sumIdxGSUSYNC, addrCalc):
1213 module = Module("GSU On globalWriteBatchProlog")
1214
1215 if kernel["_GlobalAccumulation"] == 'MultipleBufferSingleKernel':
1216 if writer.states.serializedStore:
1217 module.add(SNop(0, "1 wait state required when next inst writes vgprs held by previous dwordx4 store inst"))
1218
1219 ########################################################
1220
1221 # module.addSpaceLine()
1222 # SynchronizerEndlabelString = "Sync_END%s%s" % ("_Beta" if beta else "", "_Edge" if edge else "" )
1223 # SynchronizerEndlabelComment = "Sync_END"
1224 # SynchronizerEndlabel = Label(writer.labels.getNameInc(SynchronizerEndlabelString), SynchronizerEndlabelComment)
1225 # SynchronizerEndlabel = Label(writer.labels.getName(SynchronizerEndlabelString), SynchronizerEndlabelComment)
1226 # module.addCommentAlign("source store done, GSU:"+str(kernel["GlobalSplitU"])) #GSUSYNC
1227 # module.addSpaceLine()
1228 # module.add(self.GSUSynccodegen(writer, kernel, tmpVgpr, tmpVgprSize, tmpVgprDynamic, \
1229 # batchIdx, ss, gwvw, batchElements, \
1230 # SynchronizerEndlabel, sumIdxGSUSYNC, addrCalc.globalOffset, addrCalc.addrDVgpr))
1231
1232 return module
1233
1234 def defineAndResources(self, writer, kernel, tmpSgpr0, tmpSgprM, tmpSgprN, tmpSgprNumWG0, tmpSgprAccumTiles):
1235 module = Module("GSU On defineAndResources")
1236
1237 if ((kernel["GlobalSplitUAlgorithm"] == 'MultipleBufferSingleKernel')):
1238 extReadEpilogueLabeltmp = Label(label=writer.labels.getNameInc("LoadExternalEpilogueStruct"), comment="")
1239 module.addComment0("Check if custom structure pointer is null")
1240 if kernel["ProblemType"]["SupportUserArgs"]:
1241 module.add(SCmpEQU32(src0=sgpr("ArgType"), src1=2, comment="ArgType == 2 ?"))
1242 module.add(SCBranchSCC0(labelName=extReadEpilogueLabeltmp.getLabelName()))
1243 module.add(SMulI32(dst=sgpr(tmpSgpr0), src0=sgpr(tmpSgprAccumTiles), src1="MTOffset", comment="accumNumTiles*(MT0*MT1*bpeC)"))
1244 module.add(SAddU32(dst=sgpr("AddressTD"), src0=sgpr("AddressTD"), src1=sgpr(tmpSgpr0)))
1245 module.add(SAddCU32(dst=sgpr("AddressTD+1"), src0=sgpr("AddressTD+1"), src1=0))
1246 module.add(SAddU32(dst=sgpr("Synchronizer"), src0=sgpr("Synchronizer"), src1=hex(1638400)))
1247 module.add(SAddCU32(dst=sgpr("Synchronizer+1"), src0=sgpr("Synchronizer+1"), src1=0))
1248 module.add(extReadEpilogueLabeltmp)
1249
1250 return module
1251
1252 def writeBiasToGlobal(self, writer, kernel, biasDataType, tP, tmpSgprRes, biasBpe):
1253 module = Module("GSU On writeBiasToGlobal")
1254
1255 if (kernel["GlobalSplitU"] > 1 or kernel["GlobalSplitU"] == -1) and not (kernel["GlobalSplitUAlgorithm"] == "SingleBuffer" and kernel["ProblemType"]["ComputeDataType"] == biasDataType):
1256 '''
1257 We use num_records to save the bias data, so we have to shift the global pointer.
1258 final offset = d_size * gsu + sizeI/J * gsuIdx
1259 '''
1260 assert tmpSgprRes.size >= 4
1261 tmpSgpr = tmpSgprRes.idx
1262 #Calculate tensor 2d size
1263 module.add(SMovB64(dst=sgpr(tmpSgpr+0, 2), src=0x1, comment="Init tensor size"))
1264 indices = [i for i in range(kernel["ProblemType"]["NumIndicesC"])]
1265 numDim = len(indices)
1266 for i in range(0, numDim):
1267 idx = indices[i]
1268 stride = writer.strideRef("D",idx)
1269 size = writer.sizeRef(idx)
1270 module.add(SSubU32(dst=sgpr(tmpSgpr+2), src0=size, src1=0x1, comment="(size-1)"))
1271 module.addModuleAsFlatItems(writer.s_mul_u64_u32(sgpr(tmpSgpr+2), sgpr(tmpSgpr+3), stride, \
1272 sgpr(tmpSgpr+2), comment="stride x (size-1)"))
1273 module.add(SAddU32(dst=sgpr(tmpSgpr+0), src0=sgpr(tmpSgpr+0), src1=sgpr(tmpSgpr+2), comment="sum tensor size"))
1274 module.add(SAddCU32(dst=sgpr(tmpSgpr+1), src0=sgpr(tmpSgpr+1), src1=sgpr(tmpSgpr+3), comment="sum tensor size"))
1275 # SingleBuffer works on the same work space for every gsu
1276 if kernel["GlobalSplitUAlgorithm"] == "MultipleBuffer":
1277 module.add(SAndB32(dst=sgpr(tmpSgpr+2), src0=sgpr("GSU"), src1=hex(0x3FFF), comment="Restore GSU"))
1278 module.addModuleAsFlatItems(writer.s_mul_u64_u32(sgpr(tmpSgpr+0), sgpr(tmpSgpr+1), sgpr(tmpSgpr+2), \
1279 sgpr(tmpSgpr+0), comment="Recalculate gsu stride (size * gsu)"))
1280 module.add(SMovB32(dst=sgpr(tmpSgpr+2), src=sgpr("GSUSumIdx"), comment="Init tensor size"))
1281 module.add(SMovB32(dst=sgpr(tmpSgpr+3), src=0x0, comment="Init tensor size"))
1282 module.addModuleAsFlatItems(writer.s_mul_u64_u32(sgpr(tmpSgpr+2), sgpr(tmpSgpr+3), writer.sizeRef(tP["idx"]), \
1283 sgpr(tmpSgpr+2), comment="Reduction GSU offset *stride"))
1284 module.add(SAddU32(dst=sgpr(tmpSgpr+0), src0=sgpr(tmpSgpr+0), src1=sgpr(tmpSgpr+2), comment="sum gsu offset"))
1285 module.add(SAddCU32(dst=sgpr(tmpSgpr+1), src0=sgpr(tmpSgpr+1), src1=sgpr(tmpSgpr+3), comment="sum gsu offset"))
1286 module.add(scalarStaticMultiply64(sgpr(tmpSgpr, 2), sgpr(tmpSgpr, 2), biasBpe, None, comment="stride * bpe"))
1287 module.add(SAddU32(dst=sgpr("SrdBias+0"), src0=sgpr("SrdBias+0"), src1=sgpr(tmpSgpr), comment="Recalculate start address for GSU."))
1288 module.add(SAddCU32(dst=sgpr("SrdBias+1"), src0=sgpr("SrdBias+1"), src1=sgpr(tmpSgpr+1), comment="Recalculate start address for GSU."))
1289
1290 return module
1291
1292 def reductionBranches(self, writer, kernel, tPB, vectorWidths, elements, tmpVgpr, cvtVgprStruct, vectorDataTypes, factorDims, reductionEndLabel, endLabel):
1293 module = Module("GSU On reductionBranches")
1294
1295 edges = [False] # no edge variant
1296 alphas = [False] # no ahpla variant
1297 betas = [False] # no beta variant
1298 edgeI = edges[0]
1299 alpha = alphas[0]
1300 beta = betas[0]
1301 gwvw = vectorWidths[edgeI]
1302 atomic = (kernel["GlobalSplitU"] > 1) and (kernel["_GlobalAccumulation"] != 'MultipleBuffer' and kernel["_GlobalAccumulation"] != 'MultipleBufferSingleKernel')
1303
1304 module.add(self.reductionProcedure(writer, kernel, elements, alpha, beta, edges, atomic, gwvw, tmpVgpr, cvtVgprStruct, vectorDataTypes, reductionEndLabel, endLabel))
1305
1306 return module
1307
1308 def reductionProcedure(self, writer, kernel, elements, alpha, beta, edges, atomic, gwvw, tmpVgpr, cvtVgprStruct, vectorDataTypes, reductionEndLabel, endLabel):
1309 module = Module("GSU Common reductionProcedure")
1310
1311 reductionLabels = {}
1312 for edge in edges:
1313 reductionLabels[edge] = Label(writer.labels.getNameInc("Reduction_B%u_E%u" % (1 if beta else 0, 1 if edge else 0)), comment="")
1314
1315 for edge in edges:
1316 # write label for batch case
1317 module.add(reductionLabels[edge])
1318
1319 # PreLoopVmcntCaseStr = ""
1320 # # not generate Case 2 if StoreCInUnroll with StoreVectorWidth==1 (Case 2 will be same as Case 3)
1321 # if self.canOptimizePreLoopLWVmcnt:
1322 # if edge or (kernel["StoreCInUnroll"] and kernel["StoreVectorWidth"]==1):
1323 # self.currPreLoopVmcntCase = PreLoopVmcntCase.OrdNLL_E1_Store
1324 # else:
1325 # self.currPreLoopVmcntCase = PreLoopVmcntCase.OptNLL_Store
1326 # PreLoopVmcntCaseStr = inst("s_mov_b32", sgpr("PreLoopLWVmcntCase"), hex(self.currPreLoopVmcntCase.value), \
1327 # "for optimizing next PreLoop LW vmcnt, set to Case%u"%self.currPreLoopVmcntCase.value)
1328 # # reset vmcnt if the dict has this key (OptNLL_Store, OrdNLL_E1_Store),
1329 # # OrdNLL_B1_Store is excluded
1330 # if self.currPreLoopVmcntCase in self.preLoopVmcntDict:
1331 # self.preLoopVmcntDict[self.currPreLoopVmcntCase] = 0
1332
1333 edgeI = edge # TODO: remove?
1334
1335 ########################################
1336 # Calculate Vgprs for Write Batching
1337 ########################################
1338 writer.vgprPool.resetOccupancyLimit()
1339 writer.sgprPool.resetOccupancyLimit()
1340
1341 # Temporarily grow pool for sgpr
1342 sgprList = []
1343 if kernel["_GlobalAccumulation"] == 'MultipleBufferSingleKernel':
1344 sgprList.append(writer.sgprPool.checkOut(1, preventOverflow=False))
1345 sgprList.append(writer.sgprPool.checkOut(1, preventOverflow=False))
1346 sgprList.append(writer.sgprPool.checkOut(1, preventOverflow=False))
1347 sgprList.append(writer.sgprPool.checkOutAligned(2, 2, preventOverflow=False))
1348 sgprList.append(writer.sgprPool.checkOutAligned(2, 2, preventOverflow=False))
1349 sgprList.append(writer.sgprPool.checkOutAligned(4, 4, preventOverflow=False))
1350 for s in sgprList:
1351 writer.sgprPool.checkIn(s)
1352
1353 tmpVgprDynamic = None
1354 tmpVgprDynamicSize = 0
1355 tmpVgprDynamicAlign = 0
1356 if kernel["_GlobalAccumulation"] == 'MultipleBufferSingleKernel':
1357 GSUTotal = writer.getMBSKGSUTotal(kernel)
1358 vgprMbsk = (GSUTotal-1) * gwvw * max(1, kernel["ProblemType"]["DestDataType"].numRegisters())
1359 tmpVgprDynamicSize = vgprMbsk
1360 tmpVgprDynamicAlign = 4
1361 if tmpVgprDynamicSize > 0:
1362 tmpVgprDynamic = ContinuousRegister(idx=writer.vgprPool.checkOutAligned(tmpVgprDynamicSize, tmpVgprDynamicAlign), size=tmpVgprDynamicSize)
1363
1364 ss = StoreState(writer, kernel, gwvw, edge, True, atomic, elements[edgeI], vectorDataTypes, dim=0, isWorkspace=True)
1365
1366 # how many vgprs are needed for zero elements
1367 # 2 for addressC in vgpr for addition - already checked out
1368 # 2 for coord0,1 of thread - already checked out
1369 # 2 for tmp - already checked out
1370
1371 # 5 = how many vgprs are needed per element (flat)
1372 # - 2 for addr
1373 # - 3 for GLOBAL_OFFSET_C calculation (can overlap below, therefore max)
1374 # - if beta gwvw*rpe for new value
1375 # - if atomic 2*rpe for old and cmp values
1376
1377 # print("numVgprsPerAddr=%u, numVgprsPerDataPerVI=%u, numVgprPerValuC=%u"%(ss.cfg.numVgprsPerAddr, ss.cfg.numVgprsPerDataPerVI, ss.cfg.numVgprPerValuC))
1378 # numVgprsPerElement = ss.cfg.numVgprPerValuC*gwvw + ss.cfg.numVgprsPerAddr + int(ceil(ss.cfg.numVgprsPerDataPerVI * gwvw))
1379
1380 # if kernel["GroupLoadStore"] and kernel["ProblemType"]["UseBeta"]:
1381 # numVgprsPerElement += ss.cfg.numVgprsPerAddr
1382
1383 # Get estimated numVgprAvailable
1384 # print("Max vgprs =", maxVgprs, writer.vgprPool.size(), writer.vgprPool.availableBlock(ss.numVgprsPerElement, ss.align))
1385 numVgprAvailable = writer.vgprPool.availableBlock(ss.numVgprsPerElement, ss.align)
1386
1387 # Grow the register pool if needed - we need enough regs for at least one element
1388 # Unfortunate since this means the write logic is setting the VGPR requirement
1389 # for the entire kernel but at least we have a functional kernel.
1390 # Before growing the pool, see if we can shrink the write vector width instead?
1391 # TODO: the vgprSerial is needed for-ever and if we grow here will split the
1392 # range of the tmps. Maybe want to move vgprSerial to first vgpr?
1393
1394 # TODO: Minimum elems for StoreRemap
1395 # TODO: Which of DataType or DestDataType is in a better sense? 0114: Check Using DestDataType + HSS
1396 minElements = int(4 / kernel["ProblemType"]["ComputeDataType"].numBytes())
1397 minNeeded = minElements * ss.numVgprsPerElement
1398
1399 gsuDebug = 0
1400 if gsuDebug:
1401 print("numVgprAvailable=", numVgprAvailable, "minElements=", minElements, "minNeeded=", minNeeded)
1402
1403 if numVgprAvailable < minNeeded:
1404 gwvwOrig = gwvw
1405 currentOccupancy = writer.getOccupancy(kernel["NumThreads"], writer.getLdsSize(kernel), \
1406 writer.vgprPool.size(), writer.sgprPool.size(), writer.agprPool.size(), writer.states.doubleVgpr)
1407 futureOccupancy = writer.getOccupancy(kernel["NumThreads"], writer.getLdsSize(kernel), \
1408 writer.vgprPool.size() - numVgprAvailable + minNeeded, writer.sgprPool.size(), writer.agprPool.size(), writer.states.doubleVgpr)
1409
1410 if gsuDebug:
1411 print("currentOccupancy=%u futureOccupancy=%u VGPRs=%u numVgprAvail=%u vgprPerElem=%u" \
1412 % (currentOccupancy, futureOccupancy, writer.vgprPool.size(), \
1413 numVgprAvailable, minNeeded))
1414 if futureOccupancy > currentOccupancy:
1415 if gsuDebug:
1416 print("warning: %s growing VGPR for GlobalWrite batching - this may bloat VGPR usage" % \
1417 (writer.states.kernelName))
1418 print(" numVgprAvailable=", numVgprAvailable, \
1419 "numVgprsPerElement=", ss.numVgprsPerElement, \
1420 "gwvw=", gwvw)
1421 elif gwvw != gwvwOrig:
1422 ss.gwvw = gwvw # make both representations consistent
1423 if gsuDebug:
1424 print2("info: %s shrank gwvw from %u to %u but kept occupancy same=%u." \
1425 % (writer.states.kernelName, gwvwOrig, gwvw, currentOccupancy))
1426
1427 if numVgprAvailable < minNeeded:
1428 print2("info: growing pool += %d * %d for GlobalWrite\n" \
1429 % (minElements,ss.numVgprsPerElement))
1430 print2(writer.vgprPool.state())
1431 writer.vgprPool.growPool(0, minElements, ss.numVgprsPerElement, \
1432 "grow-pool for GlobalWrite")
1433 numVgprAvailable = writer.vgprPool.available()
1434 print2(writer.vgprPool.state())
1435
1436 # Use VGPR up to next occupancy threshold:
1437 maxVgprs, occupancy = writer.getMaxRegsForOccupancy(kernel["NumThreads"], writer.vgprPool.size(), writer.sgprPool.size(), \
1438 writer.getLdsSize(kernel), writer.agprPool.size(), writer.states.doubleVgpr)
1439 # Set occupancy limit for register pools
1440 # TODO: Support gfx12
1441 if kernel["ISA"][0] != 12:
1442 writer.vgprPool.setOccupancyLimit(writer.states.regCaps["MaxVgpr"], writer.states.regCaps["PhysicalMaxVgpr"] // occupancy)
1443 writer.sgprPool.setOccupancyLimit(writer.states.regCaps["MaxSgpr"], writer.states.regCaps["PhysicalMaxSgpr"] // occupancy)
1444
1445 if ss.numVgprsPerElement:
1446 numElementsPerBatch = numVgprAvailable // ss.numVgprsPerElement
1447 else:
1448 numElementsPerBatch = len(elements[edgeI]) # max, do 'em all
1449
1450 # assert(self.numVgprValuC % gwvw == 0) # sanity check
1451
1452 numElementsPerBatch = numElementsPerBatch if not kernel["NumElementsPerBatchStore"] else min(kernel["NumElementsPerBatchStore"],numElementsPerBatch)
1453
1454 if gsuDebug:
1455 print("NumElementsPerBatch=", numElementsPerBatch, "LimitedBySgprs=", ss.cfg.numElementsPerBatchLimitedBySgprs, \
1456 "WARNING" if ss.cfg.numElementsPerBatchLimitedBySgprs < numElementsPerBatch else "okay")
1457
1458 if ss.cfg.numElementsPerBatchLimitedBySgprs < numElementsPerBatch:
1459 numElementsPerBatch = ss.cfg.numElementsPerBatchLimitedBySgprs
1460
1461 # TODO: Which of DataType or DestDataType is in a better sense? 0114: Check Using DestDataType + HSS
1462 if (kernel["ProblemType"]["DataType"].isHalf() or kernel["ProblemType"]["DataType"].isBFloat16()):
1463 # only do an even number of halves - since these share hi/lo pieces of some registers?
1464 if numElementsPerBatch > 1:
1465 numElementsPerBatch = int(numElementsPerBatch/2)*2
1466 elif not kernel["EnableMatrixInstruction"]:
1467 # (excluding MFMA+LSU case. It can work without an issue)
1468 # The globalWriteBatch routine below can't handle odd elements per batch
1469 # and 0 elements per batch is illegal.
1470 # so if we don't have *GPR resources to handle a larger batch then need
1471 # to mark overflowedResources rather than generate a kernel that won't work.
1472 # It might be possible to fix globalWriteBatch to handle this case but these
1473 # are likely to be low-performing so likely not worth optimizing.
1474 print("WARNING: half requires at least two elements per batch")
1475 self.overflowedResources = 3
1476 # elif kernel["ProblemType"]["DataType"].is8bitFloat():
1477 # if numElementsPerBatch > 1:
1478 # numElementsPerBatch = int(numElementsPerBatch/4)*4
1479
1480 assert numElementsPerBatch > 0, "numElementsPerBatch=0 for %s"%writer.states.kernelName
1481
1482 # if no atomics and no edge, then write whole vectors
1483 # if not atomic and not edge:
1484 # numVectorsPerBatch = numElementsPerBatch / kernel["GlobalWriteVectorWidth"]
1485 # #print " NumVectorsPerBatch", numVectorsPerBatch
1486 # numElementsPerBatch = numVectorsPerBatch * kernel["GlobalWriteVectorWidth"]
1487 numBatches = max(1, ceilDivide(len(elements[edgeI]),numElementsPerBatch))
1488 numSgprs = ss.cfg.numTempSgprPerBatch + ss.cfg.numMaskSgprPerBatch + ss.cfg.numMaskSgprPerElement * numElementsPerBatch
1489
1490 if writer.db["PrintStoreRegisterDb"]:
1491 print("edgeI", edgeI, "NumBatches", numBatches, "NumElementsPerBatch", numElementsPerBatch, "numVgprsPerElement", ss.numVgprsPerElement, "len(elements[edgeI])", len(elements[edgeI]))
1492 print ("numSgprs=", numSgprs, "sgprPool.size()=", writer.sgprPool.size(), "numTempSgprPerBatch=", ss.cfg.numTempSgprPerBatch,
1493 "numMaskSgprPerBatch=", ss.cfg.numMaskSgprPerBatch, "numMaskSgprPerElement=", ss.cfg.numMaskSgprPerElement)
1494 print(writer.sgprPool.state())
1495 module.addComment1("edge=%d, allocate %u sgpr. perBatchTmpS=%u perBatchMaskS=%u perElementMaskS=%u elementsPerBatch=%u" %
1496 (edgeI, numSgprs, ss.cfg.numTempSgprPerBatch, ss.cfg.numMaskSgprPerBatch, ss.cfg.numMaskSgprPerElement, numElementsPerBatch))
1497
1498 with writer.allocTmpSgpr(numSgprs, 2) as tmpSgpr:
1499 elementSgprs = tmpSgpr.idx + ss.cfg.numTempSgprPerBatch
1500 codeAccVgprRead = deepcopy(writer.codes.accVgprRead) if writer.states.serializedStore else None
1501 codeAccVgprWrite = deepcopy(writer.codes.accVgprWrite) if writer.states.serializedStore else None
1502 codeAccVgprReadBackup = deepcopy(codeAccVgprRead)
1503
1504 if kernel["MIArchVgpr"] and alpha and not kernel["_GlobalAccumulation"] == 'MultipleBufferSingleKernel':
1505 codeAccVgprRead = None
1506 # Only apply when 2 wave optimization features are enabled
1507 if (kernel["StorePriorityOpt"] or kernel["StoreSyncOpt"]) and beta:
1508 self.alphaBeforeLoadC = True
1509
1510 # calculate address in workspace
1511 module.add(self.computeWorkspaceSrd(writer, kernel, tmpSgpr))
1512
1513 lastGsuWgBusyWaitingLabel = Label(writer.labels.getNameInc("last_gsu_wg_busy_waiting"), comment="")
1514 reductionBodyLabel = Label(writer.labels.getNameInc("reduction_body"), comment="")
1515 partialWriteLabel = Label(writer.labels.getNameInc("partial_write"), comment="")
1516
1517 module.add(self.syncOffsetPreparation(writer, kernel, tmpSgpr, partialWriteLabel))
1518
1519 for batchIdx in range(0, numBatches):
1520 elementStartIdx = batchIdx * numElementsPerBatch
1521 elementStopIdx = min(elementStartIdx + numElementsPerBatch, len(elements[edgeI]))
1522 elementsThisBatch = elements[edgeI][elementStartIdx:elementStopIdx]
1523 # print("BATCH[%u/%u]: elements[edgeI][%u:%u] VGPRs=%u" % (batchIdx, numBatches, elementStartIdx, elementStopIdx, ss.numVgprsPerElement ))
1524 # elementVgprs can be large and should be perfectly tuned to the number of available
1525 # VGPRS. We do not want to accidentally overflow and grow the pool here:
1526 module.add(self.partialWriteBatch(writer, kernel, ss, batchIdx, beta, edge, gwvw, elementsThisBatch, tmpVgpr, elementSgprs, \
1527 tmpSgpr, codeAccVgprRead, lastGsuWgBusyWaitingLabel, reductionBodyLabel, partialWriteLabel))
1528
1529 # synchronize GSUWG in reductionBatch. If is the last WG -> do reduction; else branch to GW_END
1530 ss.firstBatch = True
1531 for batchIdx in range(0, numBatches):
1532 elementStartIdx = batchIdx * numElementsPerBatch
1533 elementStopIdx = min(elementStartIdx + numElementsPerBatch, len(elements[edgeI]))
1534 elementsThisBatch = elements[edgeI][elementStartIdx:elementStopIdx]
1535 # print("BATCH[%u/%u]: elements[edgeI][%u:%u] VGPRs=%u" % (batchIdx, numBatches, elementStartIdx, elementStopIdx, ss.numVgprsPerElement ))
1536 # elementVgprs can be large and should be perfectly tuned to the number of available
1537 # VGPRS. We do not want to accidentally overflow and grow the pool here:
1538 module.add(self.reductionBatch(writer, kernel, ss, batchIdx, alpha, beta, edge, atomic, \
1539 gwvw, elementsThisBatch, tmpVgpr, tmpVgprDynamic, elementSgprs, tmpSgpr, \
1540 codeAccVgprReadBackup, codeAccVgprWrite, reductionBodyLabel, endLabel))
1541
1542 module.add(SWaitCnt(vlcnt=0, comment="wait for buffer_load to finish"))
1543 if kernel["MbskPrefetchMethod"] == 0:
1544 module.add(SAndB32(dst=sgpr(tmpSgpr.idx), src0=sgpr("GSU"), src1=hex(0x3FFF), comment="Restore GSU"))
1545 module.add(SCmpGtI32(src0=sgpr(tmpSgpr.idx), src1=self.gsuThreshold, comment="GSU > %u ?" % self.gsuThreshold))
1546 module.add(SCBranchSCC1(labelName=reductionEndLabel.getLabelName(), comment="branch if true"))
1547 module.addComment("GSU > %u, no need to reset synchronizer" % self.gsuThreshold)
1548 module.add(SWaitCnt(kmcnt=0, comment="wait for reset synchronizer to finish"))
1549 ss.resetState()
1550
1551 # Free after final vgpr vcalculation
1552 if tmpVgprDynamic:
1553 writer.vgprPool.checkIn(tmpVgprDynamic.idx)
1554
1555 return module
1556
1557 def syncOffsetPreparation(self, writer, kernel, tmpSgpr, partialWriteLabel):
1558 module = Module("GSU Common syncOffsetPreparation")
1559
1560 tmpS01 = writer.sgprPool.checkOut(1, preventOverflow=False)
1561 tmpS02 = writer.sgprPool.checkOut(1, preventOverflow=False)
1562 tmpS03 = writer.sgprPool.checkOut(1, preventOverflow=False)
1563
1564 #####################################synchronizer offset cal and set synchronizer#####################################
1565 #####################################WaveId+WgId*WaveNum+WgNum*WaveNum*Batch#####################################
1566 #####################################WgId+WaveId*WgNum+WgNum*WaveNum*Batch#####################################
1567 module.addComment("synchronizer offset cal")
1568 module.add(SMulI32(dst=sgpr(tmpS03), src0=sgpr("NumWorkGroups1"), src1=sgpr("NumWorkGroups0"), comment=""))
1569 module.add(SMulI32(dst=sgpr(tmpS02), src0=sgpr(tmpS03), src1=sgpr("WorkGroup2"), comment=""))
1570 module.add(SMulI32(dst=sgpr(tmpS01), src0=sgpr("WorkGroup1"), src1=sgpr("NumWorkGroups0"), comment=""))
1571 module.add(SAddU32(dst=sgpr(tmpS01), src0=sgpr(tmpS01), src1=sgpr("WorkGroup0")))
1572 module.add(SAddU32(dst=sgpr(tmpS01), src0=sgpr(tmpS01), src1=sgpr(tmpS02)))
1573 module.add(VReadfirstlaneB32(dst=sgpr(tmpS02), src=vgpr("Serial")))
1574 module.add(SMulI32(dst=sgpr(tmpS03), src0=sgpr(tmpS03), src1=sgpr("SizeK"), comment="cal a wave offset"))
1575 module.add(SLShiftRightB32(dst=sgpr(tmpS02), shiftHex=hex(log2(kernel["WavefrontSize"])), src=sgpr(tmpS02)))
1576 module.add(SMulI32(dst=sgpr(tmpS02), src0=sgpr(tmpS03), src1=sgpr(tmpS02), comment="wave offset at batch")) # WaveId*WgNum
1577 module.add(SAddU32(dst=sgpr(tmpS01), src0=sgpr(tmpS02), src1=sgpr(tmpS01))) # WaveId*WgNum+WgId
1578 module.add(SLShiftLeftB32(dst=sgpr(tmpS01), src=sgpr(tmpS01), shiftHex=hex(2), comment="")) # atomic 32bits
1579 #####################################set synchronizer#####################################
1580 module.add(SAddU32(dst=sgpr("SrdSync+0"), src0=sgpr("Synchronizer+0"), src1=sgpr(tmpS01), comment="" ))
1581 module.add(SAddCU32(dst=sgpr("SrdSync+1"), src0=sgpr("Synchronizer+1"), src1=hex(0), comment="" ))
1582
1583 if kernel["MbskPrefetchMethod"] == 0:
1584 module.addSpaceLine()
1585 module.add(SAndB32(dst=sgpr(tmpS02), src0=sgpr("GSU"), src1=hex(0x3FFF), comment="Restore GSU"))
1586 module.add(SCmpGtI32(src0=sgpr(tmpS02), src1=self.gsuThreshold, comment="GSU > %u ?" % self.gsuThreshold))
1587 module.add(SCBranchSCC1(labelName=partialWriteLabel.getLabelName(), comment="branch if true"))
1588 module.addComment("GSU <= %u, last gsu wg do the reduction" % self.gsuThreshold)
1589 module.add(SSubU32(dst=sgpr(tmpS02), src0=sgpr(tmpS02), src1=1, comment=""))
1590 module.add(SCmpEQU32(src0=sgpr("GSUSumIdx"), src1=sgpr(tmpS02), comment="GSUSumIdx == GSU-1 ?"))
1591 module.add(SCBranchSCC0(labelName=partialWriteLabel.getLabelName(), comment="branch if false"))
1592
1593 writer.sgprPool.checkIn(tmpS03)
1594 writer.sgprPool.checkIn(tmpS02)
1595 writer.sgprPool.checkIn(tmpS01)
1596
1597 return module
1598
1599 def lastGsuWgBusyWaiting(self, writer, kernel, ss, tmpSgpr, lastGsuWgBusyWaitingLabel, reductionBodyLabel):
1600 module = Module("GSU Common lastGsuWgBusyWaiting")
1601
1602 tmpS01 = tmpSgpr.idx
1603
1604 module.add(SLoadB32(dst=sgpr(tmpS01), base=sgpr("SrdSync",2), soffset=0, smem=SMEMModifiers(glc=True), comment="get atomic_dec value"))
1605 module.add(SWaitCnt(kmcnt=0, comment="wait for atomic_dec value load"))
1606 module.add(SCmpEQU32(src0=sgpr(tmpS01), src1=1, comment="last GSU WG?"))
1607 module.add(SCBranchSCC0(labelName=lastGsuWgBusyWaitingLabel.getLabelName(), comment="branch if false"))
1608 module.add(SMovB32(dst=sgpr(tmpS01), src=0, comment="reset synchronizer"))
1609 module.add(SStoreB32(src=sgpr(tmpS01), base=sgpr("SrdSync", 2), soffset=0, smem=SMEMModifiers(glc=True), comment="reset synchronizer"))
1610 module.add(SBranch(labelName=reductionBodyLabel.getLabelName(), comment=""))
1611
1612 return module
1613
1614 def partialWriteBatch(self, writer, kernel, ss, batchIdx, beta, edge, gwvw, batchElements, tmpVgpr, batchElementSgprs, tmpSgpr, codeAccVgprRead, \
1615 lastGsuWgBusyWaitingLabel, reductionBodyLabel, partialWriteLabel):
1616 module = Module("GSU Common partialWriteBatch")
1617
1618 # allow expanding vgpr pool for OptNLL
1619 # preventOverflow = True #(not isOptNLL)
1620 # ss.setupStoreElementsForBatch(kernel, gwvw, batchElements, batchElementSgprs, isOptNLL=False, factorDim=0, isWorkspace=True)
1621 ss.setupStoreElementsForBatchWihoutVgprCheckOut(kernel, gwvw, batchElements, batchElementSgprs, isOptNLL=True, factorDim=0, isWorkspace=True)
1622
1623 if batchIdx == 0 and kernel["MbskPrefetchMethod"] == 0:
1624 module.add(lastGsuWgBusyWaitingLabel)
1625 module.add(self.lastGsuWgBusyWaiting(writer, kernel, ss, tmpSgpr, lastGsuWgBusyWaitingLabel, reductionBodyLabel))
1626 module.add(partialWriteLabel)
1627
1628 module.addComment0("optSingleColVgpr=%u optSharedColVgpr=%u optSGPRUsage=%s optSrdIncForRow=%u" % \
1629 (ss.optSingleColVgpr, ss.optSharedColVgpr, ss.optSGPRUsage, ss.optSrdIncForRow))
1630
1631 if kernel["StoreSyncOpt"]:
1632 module.add(SSleep(kernel["StoreSyncOpt"] - 1, "optimization: sync and wait"))
1633 module.add(SBarrier())
1634
1635 # comment tt1, tt0, vc1, vc0
1636 # tt = thread tile, vc=vector component
1637 commentStr = "Partial Write%s%s Batch #%u (d1,d0,vc1,vc0) =\n " \
1638 % (" Beta" if beta else "", " Edge" if edge else "", batchIdx)
1639 for elementIdx, element in enumerate(batchElements):
1640 commentStr += "(%u,%u,%u,%u:vw%u)" % (element[0], element[1], element[2], element[3], gwvw)
1641 if elementIdx < len(batchElements)-1:
1642 commentStr += "; "
1643 module.addComment2(commentStr)
1644
1645 storeOffsetSgpr = tmpSgpr.idx
1646 loadOffsetSgpr = tmpSgpr.idx + 1
1647 storeOffsetSgprRes = ContinuousRegister(storeOffsetSgpr, 1)
1648
1649 ########################################
1650 # On input, coord0 and coord1 are VGPRs computed in the pre-batch code, based
1651 # on the thread and tid number. These are ELEMENT offsets from start of tensor C
1652 # for the top-left corner this thread will write. These are not changed
1653 # across all the store loop iters.
1654 if writer.db["ConservativeWaitCnt"] & 0x10:
1655 module.add(SBarrier("debug"))
1656 module.add(SWaitCnt(vlcnt=0, vscnt=0, comment="ConservativeWaitCnt"))
1657 module.add(SBarrier("debug"))
1658 if not edge and writer.db["ForceEdgeStores"]>=2:
1659 module.add(writer.getBomb()) # should not get here
1660 if edge and writer.db["AssertNoEdge"]:
1661 module.add(writer.getBomb()) # should not get here
1662
1663 if kernel["BufferStore"] and edge:
1664 bufferOOB = tmpVgpr.idx + tmpVgpr.size - 1
1665 module.add(VMovB32(dst=vgpr(bufferOOB), src="BufferOOB"))
1666 else:
1667 bufferOOB = None
1668
1669 if beta and kernel["StoreSyncOpt"]:
1670 module.add(SSleep(kernel["StoreSyncOpt"] - 1, "optimization: sync and wait"))
1671 module.add(SBarrier())
1672
1673 ########################################
1674 # accvgpr read
1675 module.addComment("accvgpr read")
1676 if batchIdx > 0:
1677 module.add(SWaitCnt(vlcnt=0, vscnt=0, comment="Wait previous batch write over"))
1678 if codeAccVgprRead is not None and kernel["LocalSplitU"] == 1:
1679 regsPerScalar = writer.states.bpeCinternal // writer.states.bpr # register per scalar
1680 # loop over store instructions within one batch
1681 for elementIdx in range(0, len(batchElements)):
1682 # loop over scalars within one store instruction
1683 for vi in range(0, gwvw):
1684 # loop over registers within one scalar
1685 for rIdx in range(0, regsPerScalar):
1686 codeAccVgprReadInst = codeAccVgprRead.popFirstItem() # v_accvgpr_read_b32
1687 codeAccVgprReadInst.dst = vgpr(ss.elementSumIdx[elementIdx]*regsPerScalar + regsPerScalar*vi + rIdx)
1688 module.add(codeAccVgprReadInst)
1689 elif kernel["LocalSplitU"] > 1:
1690 # read from LSU VGPRs
1691 regsPerScalar = writer.states.bpeCinternal // writer.states.bpr # register per scalar
1692 if kernel["MIArchVgpr"]:
1693 tmpStartVgprValuC = writer.states.c.startVgprValu
1694 writer.states.c.startVgprValu = 0
1695 module.add(RegSet("v", "vgprValuC", 0))
1696 if ss.lsuStartVgprOffset >= 0:
1697 for elementIdx in range(0, len(batchElements)):
1698 for vi in range(0, gwvw):
1699 for rIdx in range(0, regsPerScalar):
1700 codeAccVgprReadInst = codeAccVgprRead.popFirstItem() # v_mov_b32
1701 codeAccVgprReadInst.dst = vgpr(ss.elementSumIdx[elementIdx]*regsPerScalar + regsPerScalar*vi + rIdx)
1702 module.add(codeAccVgprReadInst)
1703 ss.lsuStartVgprOffset += len(batchElements) * gwvw * regsPerScalar
1704
1705 if kernel["MIArchVgpr"]:
1706 writer.states.c.startVgprValu = tmpStartVgprValuC
1707 module.add(RegSet("v", "vgprValuC", tmpStartVgprValuC))
1708 else:
1709 module.add(SNop(1, "2 wait states required before reading vgpr"))
1710 module.addSpaceLine()
1711
1712 ########################################
1713 # Write to workspace
1714 module.addComment("write to workspace")
1715 if kernel["_GlobalAccumulation"] == "MultipleBufferSingleKernel":
1716 storeCodeGSUSK = Module("GroupLoadStore")
1717 storeWidth = kernel["StoreVectorWidth"]
1718 bps = kernel["StoreVectorWidth"] * writer.states.bpeCinternal
1719 rpv = bps / writer.states.bpr
1720 isGlc = True
1721 isSlc = True
1722 isNT = False #bool(kernel["NonTemporalD"] & 0x4)
1723 for elementIdx in range(0, len(batchElements)):
1724 addrCalc = ss.elementAddr[elementIdx]
1725 data = ss.elementData[elementIdx]
1726 addr0 = vgpr(addrCalc.addrDVgpr)
1727 addr1 = sgpr("SrdD", 4)
1728 globalOffset = 0
1729
1730 if batchIdx == 0 and elementIdx == 0:
1731 addrDVgpr = addrCalc.addrDVgpr
1732 storeCodeGSUSK.add(vectorStaticMultiply(vgpr(addrDVgpr), vgpr("Serial"), storeWidth * writer.states.bpeCinternal, storeOffsetSgprRes))
1733 storeCodeGSUSK.add(SMovB32(dst=sgpr(storeOffsetSgpr), src=0, comment="Init sgpr offset for interleaved wave store"))
1734 else:
1735 # Use "NumThreads" instead of "MIWaveGroup" because LSU will not show in "MIWaveGroup"
1736 increment = kernel["NumThreads"] * storeWidth * writer.states.bpeCinternal
1737 storeCodeGSUSK.add(SAddU32(dst=sgpr(storeOffsetSgpr), src0=sgpr(storeOffsetSgpr), src1=increment, comment="Increase sgpr offset for store"))
1738
1739 sumIdx = ss.elementSumIdx[elementIdx]
1740 if not kernel["StoreRemapVectorWidth"]:
1741 # Only GSU>1 MBSK write to workspace (GSU1 MBSK will write to output buffer)
1742 # so we need wsOffset to coalesced store to workspace buffer
1743 wsOffset = sgpr(storeOffsetSgpr)
1744 storeCodeGSUSK.add(writer.chooseGlobalWrite(True, bps, sumIdx, rpv, \
1745 addr0, addr1, globalOffset, soffset=wsOffset, \
1746 glc=isGlc, slc=isSlc, nt=isNT, hi16=0, comment="store WS"))
1747 else:
1748 rpe = writer.states.bpeCinternal // writer.states.bpr
1749 storeCodeGSUSK.add(writer.storeRemapAddLocalWrite(kernel, ss, addrCalc, sumIdx*rpe))
1750 # Column Block Shape has been written to LDS
1751 # Now read back and write out to global memory
1752 module.add(storeCodeGSUSK)
1753
1754 # return registers to pool:
1755 lastDataD = -1
1756 for elementIdx in range(0, len(batchElements)):
1757 if not ss.sharedColDVgprs:
1758 addrCalc: AddrCalculation = ss.elementAddres[elementIdx]
1759 addrDVgpr = addrCalc.addrDVgpr
1760 addrGSUSyncVgprs = addrCalc.addrGSUSyncVgprs
1761 addrCVgpr = addrCalc.addrCVgpr
1762 writer.vgprPool.checkIn(addrDVgpr)
1763 if addrCVgpr != addrDVgpr:
1764 writer.vgprPool.checkIn(addrCVgpr)
1765 if addrGSUSyncVgprs != None:
1766 writer.parentWriter.vgprPool.checkIn(addrGSUSyncVgprs)
1767
1768 data = ss.elementData[elementIdx]
1769 if data != 0:
1770 if data != lastDataD:
1771 writer.vgprPool.checkIn(data)
1772 lastDataD = data
1773
1774 ss.firstBatch = False
1775 ss.checkInTempVgprC()
1776
1777 return module
1778
1779 def reductionBatch(self, writer, kernel, ss, batchIdx, alpha, beta, edge, atomic, gwvw, batchElements, tmpVgpr, tmpVgprDynamic, \
1780 batchElementSgprs, tmpSgpr, codeAccVgprRead, codeAccVgprWrite, reductionBodyLabel, endLabel):
1781 module = Module("GSU Common reductionBatch")
1782
1783 module.addComment0("optSingleColVgpr=%u optSharedColVgpr=%u optSGPRUsage=%s optSrdIncForRow=%u" % \
1784 (ss.optSingleColVgpr, ss.optSharedColVgpr, ss.optSGPRUsage, ss.optSrdIncForRow))
1785
1786 if kernel["StoreSyncOpt"]:
1787 module.add(SSleep(kernel["StoreSyncOpt"] - 1, "optimization: sync and wait"))
1788 module.add(SBarrier())
1789
1790 # comment tt1, tt0, vc1, vc0
1791 # tt = thread tile, vc=vector component
1792 commentStr = "Reduction%s%s Batch #%u (d1,d0,vc1,vc0) =\n " \
1793 % (" Beta" if beta else "", " Edge" if edge else "", batchIdx)
1794 for elementIdx, element in enumerate(batchElements):
1795 commentStr += "(%u,%u,%u,%u:vw%u)" % (element[0], element[1], element[2], element[3], gwvw)
1796 if elementIdx < len(batchElements)-1:
1797 commentStr += "; "
1798 module.addComment2(commentStr)
1799
1800 # allow expanding vgpr pool for OptNLL
1801 # preventOverflow = True #(not isOptNLL)
1802 # ss.setupStoreElementsForBatch(kernel, gwvw, batchElements, batchElementSgprs, isOptNLL=False, factorDim=0, isWorkspace=True)
1803 ss.setupStoreElementsForBatchWihoutVgprCheckOut(kernel, gwvw, batchElements, batchElementSgprs, isOptNLL=True, factorDim=0, isWorkspace=True)
1804
1805 ########################################
1806 # On input, coord0 and coord1 are VGPRs computed in the pre-batch code, based
1807 # on the thread and tid number. These are ELEMENT offsets from start of tensor C
1808 # for the top-left corner this thread will write. These are not changed
1809 # across all the store loop iters.
1810 if writer.db["ConservativeWaitCnt"] & 0x10:
1811 module.add(SBarrier("debug"))
1812 module.add(SWaitCnt(vlcnt=0, vscnt=0, comment="ConservativeWaitCnt"))
1813 module.add(SBarrier("debug"))
1814 if not edge and writer.db["ForceEdgeStores"]>=2:
1815 module.add(writer.getBomb()) # should not get here
1816 if edge and writer.db["AssertNoEdge"]:
1817 module.add(writer.getBomb()) # should not get here
1818
1819 if kernel["BufferStore"] and edge:
1820 bufferOOB = tmpVgpr.idx + tmpVgpr.size - 1
1821 module.add(VMovB32(dst=vgpr(bufferOOB), src="BufferOOB"))
1822 else:
1823 bufferOOB = None
1824
1825 if beta and kernel["StoreSyncOpt"]:
1826 module.add(SSleep(kernel["StoreSyncOpt"] - 1, "optimization: sync and wait"))
1827 module.add(SBarrier())
1828
1829 # do we really need this?
1830 sumIdxGSUSYNC = ss.elementSumIdx[len(batchElements)-1]
1831 addrCalc = ss.elementAddr[len(batchElements)-1]
1832 accvgprWriteLabel = Label(writer.labels.getNameInc("accvgpr_write"), comment="")
1833
1834 if (kernel["_GlobalAccumulation"] == 'MultipleBufferSingleKernel'):
1835 module.add(self.GSUSynccodegenOpt(kernel, writer, ss, batchIdx, tmpSgpr, tmpVgpr, tmpVgprDynamic, gwvw, batchElements,\
1836 endLabel, sumIdxGSUSYNC, addrCalc.addrDVgpr, reductionBodyLabel))
1837 module.addComment("synchronizer store end")
1838 if kernel["MbskPrefetchMethod"] == 0:
1839 module.add(SAndB32(dst=sgpr(tmpSgpr.idx), src0=sgpr("GSU"), src1=hex(0x3FFF), comment="Restore GSU"))
1840 module.add(SCmpGtI32(src0=sgpr(tmpSgpr.idx), src1=self.gsuThreshold, comment="GSU > %u ?" % self.gsuThreshold))
1841 module.add(SCBranchSCC1(labelName=accvgprWriteLabel.getLabelName(), comment="branch if true"))
1842 module.addComment("GSU <= %u, do accvgpr_read for the last gsu wg" % self.gsuThreshold)
1843 module.add(self.lastGsuWgReduction(kernel, writer, ss, batchIdx, tmpVgpr, tmpVgprDynamic, gwvw, batchElements, \
1844 codeAccVgprRead, addrCalc.globalOffset, addrCalc.addrDVgpr))
1845
1846 ########################################
1847 # accvgpr write
1848 module.add(accvgprWriteLabel)
1849 module.addComment("accvgpr write")
1850 if codeAccVgprWrite is not None:
1851 regsPerScalar = writer.states.bpeCinternal // writer.states.bpr # register per scalar
1852 if kernel["MIArchVgpr"] and kernel["LocalSplitU"] > 1:
1853 tmpStartVgprValuC = writer.states.c.startVgprValu
1854 writer.states.c.startVgprValu = 0
1855 module.add(RegSet("v", "vgprValuC", 0))
1856 # loop over store instructions within one batch
1857 for elementIdx in range(0, len(batchElements)):
1858 # loop over scalars within one store instruction
1859 for vi in range(0, gwvw):
1860 # loop over registers within one scalar
1861 for rIdx in range(0, regsPerScalar):
1862 codeAccVgprWriteInst = codeAccVgprWrite.popFirstItem()
1863 codeAccVgprWriteInst.srcs[0] = vgpr(ss.elementSumIdx[elementIdx]*regsPerScalar + regsPerScalar*vi + rIdx)
1864 module.add(codeAccVgprWriteInst)
1865
1866 # TODO: need 3 wait states if read accvgpr after write accvgpr?
1867 # if not kernel["MIArchVgpr"]:
1868 # module.add(SNop(1, "2 wait states required before reading vgpr"))
1869 if kernel["MIArchVgpr"] and kernel["LocalSplitU"] > 1:
1870 writer.states.c.startVgprValu = tmpStartVgprValuC
1871 module.add(RegSet("v", "vgprValuC", tmpStartVgprValuC))
1872
1873 if edge and (not kernel["BufferStore"]): # atomic or
1874 # subsequent batch must start with full exec mask
1875 # BufferStore doesn't need exec since it used buffer range checking when
1876 # possible
1877 module.add(self.getEdgeMovInstType()(EXEC(), -1, "full mask -> exec"))
1878
1879 if writer.db["ConservativeWaitCnt"] & 0x40:
1880 module.add(SBarrier("debug"))
1881 module.add(SWaitCnt(vlcnt=0, vscnt=0, comment="ConservativeWaitCnt"))
1882 module.add(SBarrier("debug"))
1883
1884 # return registers to pool:
1885 lastDataD = -1
1886 for elementIdx in range(0, len(batchElements)):
1887 if not ss.sharedColDVgprs:
1888 addrCalc: AddrCalculation = ss.elementAddres[elementIdx]
1889 addrDVgpr = addrCalc.addrDVgpr
1890 addrGSUSyncVgprs = addrCalc.addrGSUSyncVgprs
1891 addrCVgpr = addrCalc.addrCVgpr
1892 writer.vgprPool.checkIn(addrDVgpr)
1893 if addrCVgpr != addrDVgpr:
1894 writer.vgprPool.checkIn(addrCVgpr)
1895 if addrGSUSyncVgprs != None:
1896 writer.parentWriter.vgprPool.checkIn(addrGSUSyncVgprs)
1897
1898 data = ss.elementData[elementIdx]
1899 if data != 0:
1900 if data != lastDataD:
1901 writer.vgprPool.checkIn(data)
1902 lastDataD = data
1903
1904 ss.firstBatch = False
1905 ss.checkInTempVgprC()
1906
1907 return module
1908
1909 def computeWorkspaceSrd(self, writer, kernel, tmpSgpr):
1910 module = Module("GSU Common computeWorkspaceSrd")
1911
1912 tmpS01 = tmpSgpr.idx
1913 tmpS02 = tmpSgpr.idx + 1
1914
1915 # WS address calculation
1916 module.addComment("calculate the starting WG index of GSU WGs")
1917 module.add(SMulI32(dst=sgpr(tmpS01), src0=sgpr("NumWorkGroups1"), src1=sgpr("WorkGroup0"), comment="NumWorkGroups1*wg0"))
1918 module.add(SAndB32(dst=sgpr(tmpS02), src0=sgpr("GSU"), src1=hex(0x3FFF), comment="Restore GSU"))
1919 module.add(SAddU32(dst=sgpr(tmpS01), src0=sgpr(tmpS01), src1=sgpr("WorkGroup1"), comment="NumWorkGroups1*wg0+wg1"))
1920 module.add(SMulI32(dst=sgpr(tmpS01), src0=sgpr(tmpS01), src1=sgpr(tmpS02), comment="(NumWorkGroups1*wg0+wg1)*GSU"))
1921 module.add(SMulI32(dst=sgpr("GSUStartWGIdx"), src0=sgpr("NumWorkGroups0"), src1=sgpr("NumWorkGroups1"), comment="NumWgPerBatch"))
1922 module.add(SMulI32(dst=sgpr("GSUStartWGIdx"), src0=sgpr("GSUStartWGIdx"), src1=sgpr("WorkGroup2"), comment="NumWgPerBatch"))
1923 module.add(SMulI32(dst=sgpr("GSUStartWGIdx"), src0=sgpr("GSUStartWGIdx"), src1=sgpr(tmpS02), comment="NumWgPerBatch"))
1924 module.add(SAddU32(dst=sgpr("GSUStartWGIdx"), src0=sgpr("GSUStartWGIdx"), src1=sgpr(tmpS01), comment="starting WG index of each GSU WGs"))
1925 module.add(SAddU32(dst=sgpr(tmpS01), src0=sgpr("GSUStartWGIdx"), src1=sgpr("GSUSumIdx"), comment="(NumWorkGroups0*wg1+wg0)*GSU+NumWgPerBatch+GSUSumIdx"))
1926
1927 assert kernel["BufferStore"]
1928 module.addComment("add offset to the base address of workspace buffer")
1929 module.add(SMulHIU32(dst=sgpr(tmpS02), src0=sgpr(tmpS01), src1="MTOffset", comment="(MT0*MT1*bpeC)*WGIdx"))
1930 module.add(SMulI32(dst=sgpr(tmpS01), src0=sgpr(tmpS01), src1="MTOffset", comment="(MT0*MT1*bpeC)*WGIdx"))
1931 module.add(SAddU32(dst=sgpr("SrdD+0"), src0=sgpr("AddressD+0"), src1=sgpr(tmpS01), comment="add lo to SRD"))
1932 module.add(SAddCU32(dst=sgpr("SrdD+1"), src0=sgpr("AddressD+1"), src1=sgpr(tmpS02), comment="add hi to SRD"))
1933 module.addSpaceLine()
1934
1935 return module
1936
1937 def GSUSynccodegenOpt(self, kernel, writer, ss, batchIdx, tmpSgpr, tmpVgpr, tmpVgprDynamic, gwvw, batchElements, \
1938 labelend, vgprstart, vgproffset, reductionBodyLabel):
1939 module = Module("GSUSYNC")
1940
1941 reductionSkipLabel = Label(writer.labels.getNameInc("reduction_skip"), comment="")
1942 reductionAllGsuWgLabel = Label(writer.labels.getNameInc("reduction_all_gsu_wg"), comment="")
1943
1944 tmpS01 = writer.sgprPool.checkOut(1, preventOverflow=False)
1945 tmpS02 = writer.sgprPool.checkOut(1, preventOverflow=False)
1946 tmpS03 = writer.sgprPool.checkOut(1, preventOverflow=False)
1947 tmpS05 = writer.sgprPool.checkOutAligned(2,2, preventOverflow=False)
1948 tmpS06 = writer.sgprPool.checkOutAligned(4,4, preventOverflow=False)
1949 tmpS06Res = ContinuousRegister(idx=tmpS06, size=4)
1950
1951 bufferOOB = tmpVgpr.idx + tmpVgpr.size - 1
1952 storeOffsetSgpr = tmpSgpr.idx
1953 loadOffsetSgpr = tmpSgpr.idx + 1
1954 storeOffsetSgprRes = ContinuousRegister(storeOffsetSgpr, 1)
1955
1956 addr1 = sgpr(tmpS06, 4)
1957 addr0 = vgpr(vgproffset)
1958 bps = kernel["ProblemType"]["ComputeDataType"].numBytes() * gwvw
1959 storeWidth = kernel["StoreVectorWidth"]
1960 increment = kernel["NumThreads"] * storeWidth * writer.states.bpeCinternal
1961
1962 if batchIdx == 0:
1963 # wait for write to ws and do atomic dec to synchronizer
1964 module.addComment("check done start")
1965 module.add(SWaitCnt(waitAll=True, comment="wait store done before synchronizer start load and add"))
1966 module.add(SAndB32(dst=sgpr(tmpS02), src0=sgpr("GSU"), src1=hex(0x3FFF), comment="Restore GSU"))
1967 module.add(SSubU32(dst=sgpr(tmpS02), src0=sgpr(tmpS02), src1=1, comment=""))
1968 module.add(SAtomicDec(dst=sgpr(tmpS02), base=sgpr("SrdSync", 2), smem=SMEMModifiers(glc=True)))
1969 if kernel["MbskPrefetchMethod"] == 0:
1970 module.add(SAndB32(dst=sgpr(tmpS01), src0=sgpr("GSU"), src1=hex(0x3FFF), comment="Restore GSU"))
1971 module.add(SCmpGtI32(src0=sgpr(tmpS01), src1=self.gsuThreshold, comment="GSU > %u ?" % self.gsuThreshold))
1972 module.add(SCBranchSCC0(labelName=reductionSkipLabel.getLabelName(), comment="branch if false"))
1973 module.addComment("GSU > %u, atomic_dec selects the gsu wg to do the reduction" % self.gsuThreshold)
1974
1975 # wait for synchronizer and check whether to branch or not
1976 module.addComment("check synchronizer done")
1977 module.add(SWaitCnt(kmcnt=0, comment="Wait for synchronizer"))
1978 module.add(SCmpEQU32(src0=sgpr(tmpS02), src1=hex(1), comment=""))
1979 module.add(SCBranchSCC1(labelName=reductionBodyLabel.getLabelName(), comment="branch if true"))
1980 if kernel["MbskPrefetchMethod"] == 0:
1981 module.add(reductionSkipLabel)
1982 module.add(SEndpgm())
1983 module.addComment("check done end")
1984 module.add(reductionBodyLabel)
1985
1986 # calculate the address for read from ws
1987 addrCalc = ss.elementAddr[0]
1988 addrDVgpr = addrCalc.addrDVgpr
1989 module.add(SMovB32(sgpr(loadOffsetSgpr), 0, "Init sgpr offset for interleaved wave load"))
1990 module.add(vectorStaticMultiply(vgpr(addrDVgpr), vgpr("Serial"), storeWidth * writer.states.bpeCinternal, storeOffsetSgprRes))
1991 module.add(VMovB32(dst=vgpr(bufferOOB), src="BufferOOB"))
1992 module.addComment("synchronizer sum offset is equal to MTOffset (=MT0*MT1*bpeC)")
1993 module.add(SMulHIU32(dst=sgpr(tmpS06+1), src0="MTOffset", src1=sgpr("GSUStartWGIdx"), comment="(MT0*MT1*bpeC)*WGIdx"))
1994 module.add(SMulI32(dst=sgpr(tmpS06), src0="MTOffset", src1=sgpr("GSUStartWGIdx"), comment="(MT0*MT1*bpeC)*WGIdx"))
1995 module.add(SAddU32(dst=sgpr(tmpS06+0), src0=sgpr("AddressD+0"), src1=sgpr(tmpS06), comment="add lo to SRD"))
1996 module.add(SAddCU32(dst=sgpr(tmpS06+1), src0=sgpr("AddressD+1"), src1=sgpr(tmpS06+1), comment="add hi to SRD"))
1997 module.add(SMovB64(sgpr(tmpS06+2, 2), sgpr("SrdD+2", 2), ""))
1998
1999 # for GSU < self.gsuThreshold, GSU-1 is passed to the reduction body
2000 module.add(SAndB32(dst=sgpr(tmpS02), src0=sgpr("GSU"), src1=hex(0x3FFF), comment="Restore GSU"))
2001 if kernel["MbskPrefetchMethod"] == 0:
2002 module.add(SCmpGtI32(src0=sgpr(tmpS02), src1=self.gsuThreshold, comment="GSU > %u ?" % self.gsuThreshold))
2003 module.add(SCBranchSCC1(labelName=reductionAllGsuWgLabel.getLabelName(), comment="branch if true"))
2004 module.addComment("GSU <= %u, so we minus 1 from GSUSync at the beginning" % self.gsuThreshold)
2005 module.add(SSubI32(dst=sgpr(tmpS02), src0=sgpr(tmpS02), src1=1, comment="Use GSU-1"))
2006 module.add(reductionAllGsuWgLabel)
2007
2008 if not kernel["MbskPrefetchMethod"]:
2009 for elementIdx in range(0, len(batchElements)):
2010 addrCalc: AddrCalculation = ss.elementAddr[elementIdx]
2011 addr0 = vgpr(addrCalc.addrDVgpr)
2012
2013 # pre-load
2014 SyncloadedData = 0
2015 SynchronizerAddSkiplabelString = "Synchronizer_read_add_skip"
2016 SynchronizerAddSkipComment = "Synchronizer read add skip"
2017 SynchronizerAddSkiplabel = Label(writer.labels.getNameInc(SynchronizerAddSkiplabelString), SynchronizerAddSkipComment)
2018
2019 GSUtotal = writer.getMBSKGSUTotal(kernel)
2020 SynchronizerAddEndlabel = [""] * GSUtotal
2021
2022 for idx in range(0, GSUtotal):
2023 SynchronizerAddEndlabelString = "Synchronizer_read_add_end_"+str(idx+1)
2024 SynchronizerAddEndComment = "Synchronizer read add end_"+str(idx+1)
2025 SynchronizerAddEndlabel[idx] = Label(writer.labels.getNameInc(SynchronizerAddEndlabelString), SynchronizerAddEndComment)
2026
2027 #####################################load buffer#####################################
2028 module.addComment("buffer load start")
2029 for times in range(elementIdx, elementIdx+1):
2030 if batchIdx != 0 or elementIdx != 0:
2031 module.add(SAddU32(dst=sgpr(loadOffsetSgpr), src0=sgpr(loadOffsetSgpr), src1=increment, comment="Increase sgpr offset for load"))
2032 module.add(SMulHIU32(dst=sgpr(tmpS06+1), src0="MTOffset", src1=sgpr("GSUStartWGIdx"), comment="(MT0*MT1*bpeC)*WGIdx"))
2033 module.add(SMulI32(dst=sgpr(tmpS06), src0="MTOffset", src1=sgpr("GSUStartWGIdx"), comment="(MT0*MT1*bpeC)*WGIdx"))
2034 module.add(SAddU32(dst=sgpr(tmpS06+0), src0=sgpr("AddressD+0"), src1=sgpr(tmpS06), comment="add lo to SRD"))
2035 module.add(SAddCU32(dst=sgpr(tmpS06+1), src0=sgpr("AddressD+1"), src1=sgpr(tmpS06+1), comment="add hi to SRD"))
2036
2037 vgprstart = ss.elementSumIdx[elementIdx]
2038 dataType = kernel["ProblemType"]["DestDataType"]
2039 if dataType.isDouble() or dataType.isSingleComplex():
2040 vgprstart = vgprstart*2
2041 module.add(writer.chooseGlobalRead(True, bps, vgprstart, \
2042 addr0, addr1, soffset=sgpr(loadOffsetSgpr), offset=0, glc=True, slc=True,\
2043 comment="load GSU D 0 "+str(vgprstart)))
2044 SyncloadedData += 1
2045
2046 # Init GSUSync for different batch
2047 module.add(SMovB32(dst=sgpr("GSUSync"), src=sgpr(tmpS02), comment="Init GSUSync to GSU for batch %u" % batchIdx))
2048
2049 SynchronizerlabelString = "Synchronizer_read_add"
2050 SynchronizerComment = "Synchronizer read add"
2051 Synchronizerlabel = Label(writer.labels.getNameInc(SynchronizerlabelString), SynchronizerComment)
2052 tmpVAdd = tmpVgprDynamic.idx
2053 GSUMvgpr = tmpVgpr.idx
2054 GSUP1 = GSUtotal-1
2055
2056 for i in range(0, GSUP1):
2057 module.add(SSubI32(dst=sgpr("GSUSync"), src0=sgpr("GSUSync"), src1=1, comment="%u" % i))
2058
2059 module.add(SAddU32(dst=sgpr(tmpS06+0), src0=sgpr(tmpS06+0), src1="MTOffset", comment="" ))
2060 module.add(SAddCU32(dst=sgpr(tmpS06+1), src0=sgpr(tmpS06+1), src1="MTOffsetH32", comment="" ))
2061
2062 module.add(SCmpEQI32(src0=sgpr("GSUSync"), src1=0, comment=""))#GSUSync+GSUP1==GSU
2063 module.add(SCBranchSCC1(labelName=SynchronizerAddEndlabel[i].getLabelName(), comment="SyncAddbranchhere"))
2064
2065 if(kernel["ProblemType"]["DestDataType"].numRegisters() > 1):
2066 module.add(writer.chooseGlobalRead(True, bps, tmpVAdd+gwvw*kernel["ProblemType"]["DestDataType"].numRegisters()*i, \
2067 addr0, addr1, soffset=0, offset=0, glc=True, slc=True, \
2068 comment="load GSU DD %u %u %u" % (bps, gwvw, kernel["ProblemType"]["DestDataType"].numRegisters())))
2069 else:
2070 module.add(writer.chooseGlobalRead(True, bps, tmpVAdd+gwvw*i, \
2071 addr0, addr1, soffset=sgpr(loadOffsetSgpr), offset=0, glc=True, slc=True, \
2072 comment="load GSU DD %u %u %u" % (bps, gwvw, kernel["ProblemType"]["DestDataType"].numRegisters())))
2073 SyncloadedData += 1
2074
2075 module.addComment("buffer load end")
2076
2077 #####################################> GSUtotal reduction start#####################################
2078 module.addComment("buffer add start")
2079
2080 module.add(Synchronizerlabel)
2081 vlcnt = SyncloadedData - 1
2082
2083 for i in range(0, GSUP1):
2084 vlcnt = vlcnt - 1 if vlcnt > 0 else 0
2085 module.add(SWaitCnt(vlcnt=vlcnt, comment="(wait for buffer ready)"))
2086 if kernel["ProblemType"]["DataType"].isInt8() or kernel["ProblemType"]["DataType"].isInt32():
2087 for j in range(0, int(gwvw)):
2088 module.add(VAddI32(dst=vgpr(vgprstart+j), src0=vgpr(vgprstart+j), src1=vgpr(tmpVAdd+0+gwvw*i+j), \
2089 comment="buffer add"))
2090 else:
2091 if ((gwvw % 2) == 1):
2092 for j in range(0, int(gwvw)):
2093 module.add(VAddF32(dst=vgpr(vgprstart+j), src0=vgpr(vgprstart+j), src1=vgpr(tmpVAdd+0+gwvw*i+j), \
2094 comment="buffer add"))
2095 else:
2096 for j in range(0, int(gwvw/2)):
2097 module.add(VAddPKF32(dst=vgpr(vgprstart+j*2, 2), src0=vgpr(vgprstart+j*2, 2), \
2098 src1=vgpr(tmpVAdd+0+gwvw*i+j*2, 2), comment="buffer pk"))
2099
2100 module.add(SSubI32(dst=sgpr("GSUSync"), src0=sgpr("GSUSync"), src1=1, comment="%u" % i))
2101 module.add(SCmpLeI32(src0=sgpr("GSUSync"), src1=0-(GSUP1-1), comment=""))#GSUSync+GSUP1==GSU
2102 module.add(SCBranchSCC1(labelName=SynchronizerAddSkiplabel.getLabelName(), comment="SyncAddbranch"))
2103
2104 module.add(SAddU32(dst=sgpr(tmpS06+0), src0=sgpr(tmpS06+0), src1="MTOffset", comment=""))
2105 module.add(SAddCU32(dst=sgpr(tmpS06+1), src0=sgpr(tmpS06+1), src1="MTOffsetH32", comment=""))
2106
2107 module.add(VCmpGEI32(dst=sgpr(tmpS05,2), src0=0, src1=sgpr("GSUSync"), comment=""))
2108 module.add(VCndMaskB32(dst=vgpr(GSUMvgpr), src1=vgpr(bufferOOB), src0=addr0, src2=sgpr(tmpS05,2), comment="protect if OOB"))
2109
2110 if(kernel["ProblemType"]["DestDataType"].numRegisters() > 1):
2111 module.add(writer.chooseGlobalRead(True, bps, tmpVAdd+gwvw*kernel["ProblemType"]["DestDataType"].numRegisters()*i, \
2112 vgpr(GSUMvgpr), addr1, soffset=0, offset=0, glc=True, slc=True, \
2113 comment="load GSU DD %u" % bps))
2114 else:
2115 module.add(writer.chooseGlobalRead(True, bps, tmpVAdd+gwvw*i, \
2116 vgpr(GSUMvgpr), addr1, soffset=sgpr(loadOffsetSgpr), offset=0, glc=True, slc=True, \
2117 comment="load GSU DD %u" % bps))
2118 vlcnt += 1
2119
2120 module.addComment("buffer add end")
2121
2122 module.add(SCmpGtI32(src0=sgpr("GSUSync"), src1=hex(1-(GSUP1)), comment=""))
2123 module.add(SCBranchSCC1(labelName=Synchronizerlabel.getLabelName(), comment="Syncbranchhere"))
2124
2125 #####################################< GSUtotal reduction start#####################################
2126 for k in range(GSUtotal-2, -1, -1):
2127 module.addSpaceLine()
2128 module.add(SynchronizerAddEndlabel[k])
2129
2130 vlcnt = k
2131 for i in range(0, k):
2132 vlcnt = vlcnt - 1 if vlcnt > 0 else 0
2133 module.add(SWaitCnt(vlcnt=vlcnt, comment="(wait for buffer ready)"))
2134 if kernel["ProblemType"]["DataType"].isInt8() or kernel["ProblemType"]["DataType"].isInt32():
2135 for j in range(0, int(gwvw)):
2136 module.add(VAddI32(dst=vgpr(vgprstart+j), src0=vgpr(vgprstart+j), src1=vgpr(tmpVAdd+0+gwvw*i+j), \
2137 comment="buffer add"))
2138 else:
2139 if ((gwvw % 2) == 1):
2140 for j in range(0, int(gwvw)):
2141 module.add(VAddF32(dst=vgpr(vgprstart+j), src0=vgpr(vgprstart+j), src1=vgpr(tmpVAdd+0+gwvw*i+j), \
2142 comment="buffer add"))
2143 else:
2144 for j in range(0, int(gwvw/2)):
2145 module.add(VAddPKF32(dst=vgpr(vgprstart+j*2, 2), src0=vgpr(vgprstart+j*2, 2), \
2146 src1=vgpr(tmpVAdd+0+gwvw*i+j*2, 2), comment="buffer pk"))
2147
2148 if i == k-1:
2149 module.add(SBranch(labelName=SynchronizerAddSkiplabel.getLabelName(), comment="SyncAddbranch"))
2150
2151 module.add(SynchronizerAddSkiplabel)
2152
2153 module.addComment("buffer add end2")
2154 else:
2155 tmpWSD = writer.sgprPool.checkOutAligned(4, 4, preventOverflow=False)
2156 GSUtotal = writer.getMBSKGSUTotal(kernel)-1
2157 loadWidth = gwvw * int(max(1, kernel["ProblemType"]["DestDataType"].numRegisters()))
2158 unrolledWGs = GSUtotal // len(batchElements)
2159 tmpVidx = tmpVgprDynamic.idx
2160 tmpVAdd = [[0] * len(batchElements) for _ in range(unrolledWGs)]
2161 for i in range(0, unrolledWGs):
2162 for j in range(0, len(batchElements)):
2163 tmpVAdd[i][j] = tmpVidx
2164 tmpVidx += loadWidth
2165
2166 SynchronizerAddEndlabel = [""] * (unrolledWGs+1)
2167
2168 for uidx in range(0, unrolledWGs+1):
2169 SynchronizerAddEndlabelString = "Synchronizer_read_add_end_"+str(uidx+1)
2170 SynchronizerAddEndComment = "Synchronizer read add end_"+str(uidx+1)
2171 SynchronizerAddEndlabel[uidx] = Label(writer.labels.getNameInc(SynchronizerAddEndlabelString), SynchronizerAddEndComment)
2172
2173 # set buffer load address for WG0
2174 module.add(SMulHIU32(dst=sgpr(tmpWSD+1), src0="MTOffset", src1=sgpr("GSUStartWGIdx"), comment="(MT0*MT1*bpeC)*WGIdx"))
2175 module.add(SMulI32(dst=sgpr(tmpWSD), src0="MTOffset", src1=sgpr("GSUStartWGIdx"), comment="(MT0*MT1*bpeC)*WGIdx"))
2176 module.add(SAddU32(dst=sgpr(tmpWSD), src0=sgpr("AddressD+0"), src1=sgpr(tmpWSD), comment="add lo to SRD"))
2177 module.add(SAddCU32(dst=sgpr(tmpWSD+1), src0=sgpr("AddressD+1"), src1=sgpr(tmpWSD+1), comment="add hi to SRD WSD"))
2178 module.add(SMovB64(sgpr(tmpWSD+2, 2), sgpr("SrdD+2", 2), ""))
2179
2180 # set buffer load address for WG1
2181 module.add(SAddU32(dst=sgpr(tmpS06+0), src0=sgpr(tmpWSD+0), src1="MTOffset", comment="" ))
2182 module.add(SAddCU32(dst=sgpr(tmpS06+1), src0=sgpr(tmpWSD+1), src1="MTOffsetH32", comment="" ))
2183 module.add(SMovB64(sgpr(tmpS06+2, 2), sgpr("SrdD+2", 2), ""))
2184
2185 accumulationStartlabel = Label(writer.labels.getNameInc("Accumulation_Start"), "Accumulation Start")
2186 accumulationEndlabel = Label(writer.labels.getNameInc("Accumulation_End"), "Accumulation End")
2187 # Init GSUSync for different batch
2188 module.add(SMovB32(dst=sgpr("GSUSync"), src=sgpr(tmpS02), comment="Init GSUSync to GSU for batch %u" % batchIdx))
2189
2190 # pre-load
2191 SyncloadedData = 0
2192
2193 # first 2 WGs: read same element first for earlier reduction
2194 for elementIdx in range(0, len(batchElements)):
2195 addrCalc: AddrCalculation = ss.elementAddr[elementIdx]
2196 addr0 = vgpr(addrCalc.addrDVgpr)
2197 if batchIdx != 0 or elementIdx != 0:
2198 module.add(SAddU32(dst=sgpr(loadOffsetSgpr), src0=sgpr(loadOffsetSgpr), src1=increment, comment="Increase sgpr offset for load"))
2199 if elementIdx == 0:
2200 module.add(SMovB32(dst=sgpr("WSDstart"), src=sgpr(loadOffsetSgpr), comment="save first element offset"))
2201 for uidx in range(0, 2):
2202 if uidx == 0:
2203 data = ss.elementSumIdx[elementIdx]
2204 tmpAddr1 = tmpWSD
2205 else:
2206 data = tmpVAdd[-1][elementIdx]
2207 tmpAddr1 = tmpS06
2208
2209 module.add(writer.chooseGlobalRead(True, bps, data, \
2210 addr0, sgpr(tmpAddr1, 4), soffset=sgpr(loadOffsetSgpr), offset=0, glc=True, slc=True,\
2211 comment="load GSU WG %d element %d " % (uidx, elementIdx)))
2212
2213 SyncloadedData += 1
2214
2215 module.add(SSubI32(dst=sgpr("GSUSync"), src0=sgpr("GSUSync"), src1=2))
2216 module.add(SCmpLeI32(src0=sgpr("GSUSync"), src1=0, comment="GSUSync <= 0?"))
2217 module.add(SCBranchSCC1(labelName=SynchronizerAddEndlabel[1].getLabelName(), comment=""))
2218 module.add(SAddU32(dst=sgpr(tmpS06+0), src0=sgpr(tmpS06+0), src1="MTOffset", comment="" ))
2219 module.add(SAddCU32(dst=sgpr(tmpS06+1), src0=sgpr(tmpS06+1), src1="MTOffsetH32", comment="" ))
2220
2221 # other WGs: read all elements together
2222 for uidx in range(2, unrolledWGs+1):
2223 module.add(SMovB32(dst=sgpr(loadOffsetSgpr), src=sgpr("WSDstart"), comment="restore offset for element0"))
2224 for elementIdx in range(0, len(batchElements)):
2225 addrCalc: AddrCalculation = ss.elementAddr[elementIdx]
2226 addr0 = vgpr(addrCalc.addrDVgpr)
2227 data = tmpVAdd[uidx-2][elementIdx]
2228
2229 if elementIdx != 0:
2230 module.add(SAddU32(dst=sgpr(loadOffsetSgpr), src0=sgpr(loadOffsetSgpr), src1=increment, comment="Increase sgpr offset for load"))
2231
2232 module.add(writer.chooseGlobalRead(True, bps, data, \
2233 addr0, addr1, soffset=sgpr(loadOffsetSgpr), offset=0, glc=True, slc=True,\
2234 comment="load GSU WG %d element %d " % (uidx, elementIdx)))
2235 SyncloadedData += 1
2236
2237 module.add(SSubI32(dst=sgpr("GSUSync"), src0=sgpr("GSUSync"), src1=1))
2238 module.add(SCmpLeI32(src0=sgpr("GSUSync"), src1=0, comment="GSUSync <= 0?"))
2239 module.add(SCBranchSCC1(labelName=SynchronizerAddEndlabel[uidx].getLabelName(), comment=""))
2240 module.add(SAddU32(dst=sgpr(tmpS06+0), src0=sgpr(tmpS06+0), src1="MTOffset", comment="" ))
2241 module.add(SAddCU32(dst=sgpr(tmpS06+1), src0=sgpr(tmpS06+1), src1="MTOffsetH32", comment="" ))
2242
2243 module.addComment("buffer load end\n")
2244
2245 ##################################### reduction start #####################################
2246 module.addComment("buffer add start")
2247
2248 vlcnt = SyncloadedData
2249
2250 # reduce first 2 WGs
2251 module.add(SMovB32(dst=sgpr(loadOffsetSgpr), src=sgpr("WSDstart"), comment="restore offset for element0"))
2252 for elementIdx in range(0, len(batchElements)):
2253 addrCalc: AddrCalculation = ss.elementAddr[elementIdx]
2254 addr0 = vgpr(addrCalc.addrDVgpr)
2255 data = tmpVAdd[-1][elementIdx]
2256 vgprstart = ss.elementSumIdx[elementIdx]
2257 vlcnt = vlcnt - 2 if vlcnt > 0 else 0
2258
2259 module.add(SWaitCnt(vlcnt=vlcnt, comment="(wait for buffer ready)"))
2260 if kernel["ProblemType"]["DataType"].isInt8() or kernel["ProblemType"]["DataType"].isInt32():
2261 for j in range(0, int(gwvw)):
2262 module.add(VAddI32(dst=vgpr(vgprstart+j), src0=vgpr(vgprstart+j), src1=vgpr(data+j), \
2263 comment="buffer add"))
2264 else:
2265 if ((gwvw % 2) == 1):
2266 for j in range(0, int(gwvw)):
2267 module.add(VAddF32(dst=vgpr(vgprstart+j), src0=vgpr(vgprstart+j), src1=vgpr(data+j), \
2268 comment="buffer add"))
2269 else:
2270 for j in range(0, int(gwvw/2)):
2271 module.add(VAddPKF32(dst=vgpr(vgprstart+j*2, 2), src0=vgpr(vgprstart+j*2, 2), \
2272 src1=vgpr(data+j*2, 2), comment="buffer pk"))
2273
2274 # prefetch
2275 if elementIdx != 0:
2276 module.add(SAddU32(dst=sgpr(loadOffsetSgpr), src0=sgpr(loadOffsetSgpr), src1=increment, comment="Increase sgpr offset for load"))
2277
2278 module.add(writer.chooseGlobalRead(True, bps, data, \
2279 addr0, addr1, soffset=sgpr(loadOffsetSgpr), offset=0, glc=True, slc=True,\
2280 comment="prefetch element %d " % (elementIdx)))
2281 vlcnt += 1
2282
2283 module.add(SSubI32(dst=sgpr("GSUSync"), src0=sgpr("GSUSync"), src1=1))
2284 module.add(SCmpLeI32(src0=sgpr("GSUSync"), src1=0-unrolledWGs, comment=""))
2285 module.add(SCBranchSCC1(labelName=accumulationEndlabel.getLabelName(), comment="Accumulation finished"))
2286 module.add(SAddU32(dst=sgpr(tmpS06+0), src0=sgpr(tmpS06+0), src1="MTOffset", comment="" ))
2287 module.add(SAddCU32(dst=sgpr(tmpS06+1), src0=sgpr(tmpS06+1), src1="MTOffsetH32", comment="" ))
2288 module.add(SCmpLeI32(src0=sgpr("GSUSync"), src1=0, comment="disable buffer load if GSUSync <= 0"))
2289 module.add(SCSelectB32(sgpr(tmpS06+2), 0, sgpr(tmpS06+2), ""))
2290 module.add(accumulationStartlabel)
2291
2292 for uidx in range(0, unrolledWGs):
2293 module.add(SMovB32(dst=sgpr(loadOffsetSgpr), src=sgpr("WSDstart"), comment="restore offset for element0"))
2294 for elementIdx in range(0, len(batchElements)):
2295 addrCalc: AddrCalculation = ss.elementAddr[elementIdx]
2296 addr0 = vgpr(addrCalc.addrDVgpr)
2297 data = tmpVAdd[uidx][elementIdx]
2298 vgprstart = ss.elementSumIdx[elementIdx]
2299 vlcnt = vlcnt - 1 if vlcnt > 0 else 0
2300
2301 module.add(SWaitCnt(vlcnt=vlcnt, comment="(wait for buffer ready)"))
2302 if kernel["ProblemType"]["DataType"].isInt8() or kernel["ProblemType"]["DataType"].isInt32():
2303 for j in range(0, int(gwvw)):
2304 module.add(VAddI32(dst=vgpr(vgprstart+j), src0=vgpr(vgprstart+j), src1=vgpr(data+j), \
2305 comment="buffer add"))
2306 else:
2307 if ((gwvw % 2) == 1):
2308 for j in range(0, int(gwvw)):
2309 module.add(VAddF32(dst=vgpr(vgprstart+j), src0=vgpr(vgprstart+j), src1=vgpr(data+j), \
2310 comment="buffer add"))
2311 else:
2312 for j in range(0, int(gwvw/2)):
2313 module.add(VAddPKF32(dst=vgpr(vgprstart+j*2, 2), src0=vgpr(vgprstart+j*2, 2), \
2314 src1=vgpr(data+j*2, 2), comment="buffer pk"))
2315
2316 # prefetch
2317 if elementIdx != 0:
2318 module.add(SAddU32(dst=sgpr(loadOffsetSgpr), src0=sgpr(loadOffsetSgpr), src1=increment, comment="Increase sgpr offset for load"))
2319
2320 module.add(writer.chooseGlobalRead(True, bps, data, \
2321 addr0, addr1, soffset=sgpr(loadOffsetSgpr), offset=0, glc=True, slc=True,\
2322 comment="prefetch element %d " % (elementIdx)))
2323 vlcnt += 1
2324
2325 module.add(SSubI32(dst=sgpr("GSUSync"), src0=sgpr("GSUSync"), src1=1))
2326 module.add(SCmpLeI32(src0=sgpr("GSUSync"), src1=0-unrolledWGs, comment=""))
2327 module.add(SCBranchSCC1(labelName=accumulationEndlabel.getLabelName(), comment="Accumulation finished"))
2328 module.add(SAddU32(dst=sgpr(tmpS06+0), src0=sgpr(tmpS06+0), src1="MTOffset", comment="" ))
2329 module.add(SAddCU32(dst=sgpr(tmpS06+1), src0=sgpr(tmpS06+1), src1="MTOffsetH32", comment="" ))
2330 module.add(SCmpLeI32(src0=sgpr("GSUSync"), src1=0, comment="disable buffer load if GSUSync <= 0"))
2331 module.add(SCSelectB32(sgpr(tmpS06+2), 0, sgpr(tmpS06+2), ""))
2332
2333 module.add(SBranch(labelName=accumulationStartlabel.getLabelName(), comment=""))
2334
2335 for k in range(unrolledWGs, 0, -1):
2336 module.addSpaceLine()
2337 module.add(SynchronizerAddEndlabel[k])
2338 vlcnt = (k+1) * len(batchElements)
2339
2340 # reduce first 2 WGs
2341 for elementIdx in range(0, len(batchElements)):
2342 vlcnt = vlcnt-2 if vlcnt > 0 else 0
2343 vgprstart = ss.elementSumIdx[elementIdx]
2344 data = tmpVAdd[-1][elementIdx]
2345
2346 module.add(SWaitCnt(vlcnt=vlcnt, comment="(wait for buffer ready)"))
2347 if kernel["ProblemType"]["DataType"].isInt8() or kernel["ProblemType"]["DataType"].isInt32():
2348 for j in range(0, int(gwvw)):
2349 module.add(VAddI32(dst=vgpr(vgprstart+j), src0=vgpr(vgprstart+j), src1=vgpr(data+j), \
2350 comment="buffer add"))
2351 else:
2352 if ((gwvw % 2) == 1):
2353 for j in range(0, int(gwvw)):
2354 module.add(VAddF32(dst=vgpr(vgprstart+j), src0=vgpr(vgprstart+j), src1=vgpr(data+j), \
2355 comment="buffer add"))
2356 else:
2357 for j in range(0, int(gwvw/2)):
2358 module.add(VAddPKF32(dst=vgpr(vgprstart+j*2, 2), src0=vgpr(vgprstart+j*2, 2), \
2359 src1=vgpr(data+j*2, 2), comment="buffer pk"))
2360
2361 for i in range(1, k):
2362 for elementIdx in range(0, len(batchElements)):
2363 vlcnt = vlcnt-1 if vlcnt > 0 else 0
2364 vgprstart = ss.elementSumIdx[elementIdx]
2365 data = tmpVAdd[i-1][elementIdx]
2366
2367 module.add(SWaitCnt(vlcnt=vlcnt, comment="(wait for buffer ready)"))
2368 if kernel["ProblemType"]["DataType"].isInt8() or kernel["ProblemType"]["DataType"].isInt32():
2369 for j in range(0, int(gwvw)):
2370 module.add(VAddI32(dst=vgpr(vgprstart+j), src0=vgpr(vgprstart+j), src1=vgpr(data+j), \
2371 comment="buffer add"))
2372 else:
2373 if ((gwvw % 2) == 1):
2374 for j in range(0, int(gwvw)):
2375 module.add(VAddF32(dst=vgpr(vgprstart+j), src0=vgpr(vgprstart+j), src1=vgpr(data+j), \
2376 comment="buffer add"))
2377 else:
2378 for j in range(0, int(gwvw/2)):
2379 module.add(VAddPKF32(dst=vgpr(vgprstart+j*2, 2), src0=vgpr(vgprstart+j*2, 2), \
2380 src1=vgpr(data+j*2, 2), comment="buffer pk"))
2381
2382 module.add(SBranch(labelName=accumulationEndlabel.getLabelName(), comment="Accumulation End"))
2383
2384 module.addComment("buffer add end\n")
2385 module.add(accumulationEndlabel)
2386 writer.sgprPool.checkIn(tmpWSD)
2387
2388 writer.sgprPool.checkIn(tmpS06)
2389 writer.sgprPool.checkIn(tmpS05)
2390 writer.sgprPool.checkIn(tmpS03)
2391 writer.sgprPool.checkIn(tmpS02)
2392 writer.sgprPool.checkIn(tmpS01)
2393
2394 return module
2395
2396 def lastGsuWgReduction(self, kernel, writer, ss, batchIdx, tmpVgpr, tmpVgprDynamic, gwvw, batchElements, codeAccVgprRead, vgproffset, soffset):
2397 module = Module("lastGsuWgReduction")
2398
2399 accvgprReadLabel = Label(writer.labels.getNameInc("last_gsu_wg_accvgpr_read"), comment="")
2400 module.add(accvgprReadLabel)
2401 module.add(SWaitCnt(vlcnt=0, comment="wait for buffer_load to finish"))
2402
2403 tmpVAdd = tmpVgprDynamic.idx
2404 # last gsu wg accvgpr read
2405 if codeAccVgprRead is not None and kernel["LocalSplitU"] == 1:
2406 regsPerScalar = writer.states.bpeCinternal // writer.states.bpr # register per scalar
2407 # loop over store instructions within one batch
2408 batchNumAccRegs = len(batchElements) * gwvw * regsPerScalar
2409 vmcntForSummation = int(batchNumAccRegs / gwvw)
2410 for elementIdx in range(0, len(batchElements)):
2411 # loop over scalars within one store instruction
2412 for vi in range(0, gwvw):
2413 # loop over registers within one scalar
2414 for rIdx in range(0, regsPerScalar):
2415 codeAccVgprReadInst = codeAccVgprRead.popFirstItem()
2416 codeAccVgprReadInst.dst = vgpr(tmpVAdd + regsPerScalar*vi + rIdx) # replace dst with temp sgpr
2417 module.add(codeAccVgprReadInst)
2418
2419 vgprstart = ss.elementSumIdx[elementIdx]
2420 dataType = kernel["ProblemType"]["DestDataType"]
2421 if dataType.isDouble() or dataType.isSingleComplex():
2422 vgprstart = vgprstart*2
2423 vmcntForSummation = vmcntForSummation - 1
2424 # module.add(SWaitCnt(vlcnt=vmcntForSummation, comment="wait for buffer_load to finish"))
2425
2426 GSUP1 = 1 # do 1 element at a time
2427 for i in range(0, GSUP1):
2428 if kernel["ProblemType"]["DataType"].isInt8() or kernel["ProblemType"]["DataType"].isInt32():
2429 for j in range(0, int(gwvw)):
2430 module.add(VAddI32(dst=vgpr(vgprstart+j), src0=vgpr(vgprstart+j), src1=vgpr(tmpVAdd+0+gwvw*i+j), \
2431 comment="buffer add"))
2432 else:
2433 if ((gwvw % 2) == 1):
2434 for j in range(0, int(gwvw)):
2435 module.add(VAddF32(dst=vgpr(vgprstart+j), src0=vgpr(vgprstart+j), src1=vgpr(tmpVAdd+0+gwvw*i+j), \
2436 comment="buffer add"))
2437 else:
2438 for j in range(0, int(gwvw/2)):
2439 module.add(VAddPKF32(dst=vgpr(vgprstart+j*2, 2), src0=vgpr(vgprstart+j*2, 2), \
2440 src1=vgpr(tmpVAdd+0+gwvw*i+j*2, 2), comment="buffer pk"))
2441 elif kernel["LocalSplitU"] > 1:
2442 # read from LSU VGPRs
2443 regsPerScalar = writer.states.bpeCinternal // writer.states.bpr # register per scalar
2444 if kernel["MIArchVgpr"]:
2445 tmpStartVgprValuC = writer.states.c.startVgprValu
2446 writer.states.c.startVgprValu = 0
2447 module.add(RegSet("v", "vgprValuC", 0))
2448 if ss.lsuStartVgprOffset > 0:
2449 for elementIdx in range(0, len(batchElements)):
2450 for vi in range(0, gwvw):
2451 for rIdx in range(0, regsPerScalar):
2452 codeAccVgprReadInst = codeAccVgprRead.popFirstItem()
2453 codeAccVgprReadInst.dst = vgpr(tmpVAdd + regsPerScalar*vi + rIdx) # replace dst with temp sgpr
2454 codeAccVgprReadInst.comment = "copy acc to vreg[%u]" % (tmpVAdd + regsPerScalar*vi + rIdx)
2455 module.add(codeAccVgprReadInst)
2456
2457 vgprstart = ss.elementSumIdx[elementIdx]
2458 dataType = kernel["ProblemType"]["DestDataType"]
2459 if dataType.isDouble() or dataType.isSingleComplex():
2460 vgprstart = vgprstart*2
2461
2462 GSUP1 = 1 # do 1 element at a time
2463 for i in range(0, GSUP1):
2464 if kernel["ProblemType"]["DataType"].isInt8() or kernel["ProblemType"]["DataType"].isInt32():
2465 for j in range(0, int(gwvw)):
2466 module.add(VAddI32(dst=vgpr(vgprstart+j), src0=vgpr(vgprstart+j), src1=vgpr(tmpVAdd+0+gwvw*i+j), \
2467 comment="buffer add"))
2468 else:
2469 if ((gwvw % 2) == 1):
2470 for j in range(0, int(gwvw)):
2471 module.add(VAddF32(dst=vgpr(vgprstart+j), src0=vgpr(vgprstart+j), src1=vgpr(tmpVAdd+0+gwvw*i+j), \
2472 comment="buffer add"))
2473 else:
2474 for j in range(0, int(gwvw/2)):
2475 module.add(VAddPKF32(dst=vgpr(vgprstart+j*2, 2), src0=vgpr(vgprstart+j*2, 2), \
2476 src1=vgpr(tmpVAdd+0+gwvw*i+j*2, 2), comment="buffer pk"))
2477
2478 ss.lsuStartVgprOffset += len(batchElements) * gwvw * regsPerScalar
2479
2480 if kernel["MIArchVgpr"]:
2481 writer.states.c.startVgprValu = tmpStartVgprValuC
2482 module.add(RegSet("v", "vgprValuC", tmpStartVgprValuC))
2483 else:
2484 module.add(SNop(1, "2 wait states required before reading vgpr"))
2485
2486 module.addSpaceLine()
2487
2488 return module