Debian Codegraph @

tensilelite/Tensile/Components/GlobalWriteBatch.py

raw symbols SCIP
1 ################################################################################
2 #
3 # Copyright (C) 2022-2025 Advanced Micro Devices, Inc. All rights reserved.
4 #
5 # Permission is hereby granted, free of charge, to any person obtaining a copy
6 # of this software and associated documentation files (the "Software"), to deal
7 # in the Software without restriction, including without limitation the rights
8 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell cop-
9 # ies of the Software, and to permit persons to whom the Software is furnished
10 # to do so, subject to the following conditions:
11 #
12 # The above copyright notice and this permission notice shall be included in all
13 # copies or substantial portions of the Software.
14 #
15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM-
16 # PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17 # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18 # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19 # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNE-
20 # CTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 ################################################################################
22
23 from rocisa.code import Label, Module, RegSet
24 from rocisa.container import SMEMModifiers, VOP3PModifiers, MUBUFModifiers, \
25 SDWAModifiers, replaceHolder, EXEC, VCC, vgpr, sgpr, ContinuousRegister
26 from rocisa.enum import CvtType, RoundType, SaturateCastType, SelectBit
27 from rocisa.instruction import BufferAtomicAddF32, BufferAtomicCmpswapB32, \
28 BufferAtomicCmpswapB64, FlatAtomicCmpswapB32, SAddCU32, SAddU32, SAndB32, \
29 SAndB64, SAtomicDec, SBarrier, SBranch, SCBranchExecNZ, SCBranchExecZ, \
30 SCBranchSCC1, SCSelectB32, SCmpEQI32, SCmpEQU32, SCmpGtI32, SCmpLeI32, \
31 SLShiftLeftB32, SLShiftLeftB64, SLShiftRightB32, SMovB32, SMovB64, SMulI32, \
32 SNop, SOrB32, SOrB64, SOrSaveExecB32, SOrSaveExecB64, SSleep, SSubI32, SSubU32, \
33 SSwapPCB64, SWaitCnt, SWaitAlu, VAShiftRightI32, VAddCCOU32, VAddCOU32, VAddF32, VAddF64, \
34 VAddI32, VAddPKF16, VAddPKF32, VAddU32, VBfeI32, VCmpEQU32, VCmpGEI32, VCmpGtU32, \
35 VCmpNeU32, VCmpNeU64, VCndMaskB32, VCvtBF8toF32, VCvtF16toF32, VCvtF32toI32, \
36 VCvtFP8toF32, VCvtI32toF32, VCvtPkBF8toF32, VCvtPkFP8toF32, VFmaF64, VFmaMixF32, \
37 VLShiftRightB32, VMacF32, VMadMixF32, VMaxF32, VMovB32, VMovB64, VMulF32, VMulF64, \
38 VMulLOU32, VMulPKF16, VMulPKF32, VPackF16toB32, VReadfirstlaneB32, VRndneF32, VCvtBF16toFP32
39 from rocisa.functions import vectorStaticMultiply
40
41 from ..Common import DataDirection, SemanticVersion
42 from ..Common.DataType import DataType
43 from ..Component import GlobalWriteComponents
44 from ..Component import Component
45 from ..SolutionStructs import Solution
46 from ..Activation import ActivationModule
47 from ..AsmStoreState import StoreState
48 from ..AsmAddressCalculation import AddrCalculation
49 from ..Components.PackData import formatting, PackData_F16, PackData_BF16, PackData_FLOAT8, PackData_FLOAT8_fnuz
50
51 from math import ceil
52
53 class GlobalWriteBatchComponent(GlobalWriteComponents):
54 kernel = {"ProblemType": {"OperationType": "GEMM" }}
55 def __call__(self, kernel: Solution, tPA, tPB, activation: ActivationModule, ss: StoreState, \
56 batchIdx, applyAlpha, beta, edge, atomic, gwvw, atomicW, \
57 batchElements, addrE, addrD, addrC, addrBias, addrScaleAVec, addrScaleBVec, addrScaleAlphaVec, isLocalBarrierInit: bool, \
58 tmpVgpr, tmpVgprDynamic, cvtVgprStruct, activationSetPCStruct, activationTypeStr, batchElementSgprs, tmpSgpr, codeAccVgprRead, \
59 codeMulAlpha, packdata, parentWriter, factorDim, amdClangVersion: SemanticVersion) -> Module:
60 return GlobalWriteBatchWriter(kernel, tPA, tPB, activation, ss, batchIdx, applyAlpha, \
61 beta, edge, atomic, gwvw, atomicW, \
62 batchElements, addrE, addrD, addrC, addrBias, addrScaleAVec, addrScaleBVec, addrScaleAlphaVec, isLocalBarrierInit, \
63 tmpVgpr, tmpVgprDynamic, cvtVgprStruct, activationSetPCStruct, activationTypeStr, batchElementSgprs, tmpSgpr, \
64 codeAccVgprRead, codeMulAlpha, packdata, parentWriter, factorDim, amdClangVersion).emit()
65
66 class GlobalWriteBatchWriter:
67 def __init__(self, kernel: Solution, tPA, tPB, activation: ActivationModule, ss: StoreState, \
68 batchIdx, applyAlpha, beta, edge, atomic, gwvw, atomicW, \
69 batchElements, addrE, addrD, addrC, addrBias, addrScaleAVec, addrScaleBVec, addrScaleAlphaVec, isLocalBarrierInit: bool, \
70 tmpVgpr, tmpVgprDynamic, cvtVgprStruct, activationSetPCStruct, activationTypeStr, batchElementSgprs, tmpSgpr, codeAccVgprRead, \
71 codeMulAlpha, packdata, parentWriter, factorDim, amdClangVersion: SemanticVersion):
72 self.kernel = kernel
73 self.tPA = tPA
74 self.tPB = tPB
75 self.activation = activation
76 self.ss = ss
77 self.batchIdx = batchIdx
78 self.applyAlpha = applyAlpha
79 self.beta = beta
80 self.edge = edge
81 self.atomic = atomic
82 self.gwvw = gwvw
83 self.atomicW = atomicW
84 self.batchElements = batchElements
85 self.addrE = addrE
86 self.addrD = addrD
87 self.addrC = addrC
88 self.addrBias = addrBias
89 self.addrScaleAVec = addrScaleAVec
90 self.addrScaleBVec = addrScaleBVec
91 self.addrScaleAlphaVec = addrScaleAlphaVec
92 self.isLocalBarrierInit = isLocalBarrierInit
93 self.activationSetPCStruct = activationSetPCStruct
94 self.activationTypeStr = activationTypeStr
95 self.tmpVgpr = tmpVgpr.idx
96 self.tmpVgprSize = tmpVgpr.size
97 self.tmpVgprDynamic = None
98 if tmpVgprDynamic:
99 self.tmpVgprDynamic = tmpVgprDynamic.idx
100 self.tmpVgprDynamicSize = tmpVgprDynamic.size
101 self.cvtVgprStruct = cvtVgprStruct
102 self.batchElementSgprs = batchElementSgprs
103 self.tmpSgpr = tmpSgpr
104 self.codeAccVgprRead = codeAccVgprRead
105 self.codeMulAlpha = codeMulAlpha
106 self.packdata = packdata
107 self.parentWriter = parentWriter
108 self.storesIssued = 0
109 self.factorDim = factorDim
110 self.amdClangVersion = amdClangVersion
111
112 # Internal state for GlobalWriteBatch
113 # 0 for None, 1 for WorkGroupReduction = False, 2 for WorkGroupReduction = True
114 self.storeBiasD = 0
115 if self.parentWriter.states.useBias == DataDirection.WRITE and \
116 (not self.kernel["WorkGroupReduction"]) and \
117 self.kernel["ProblemType"]["BiasSrc"] == "D":
118 self.storeBiasD = 1
119
120
121
122 @property
123 def wavelen(self) -> int:
124 return self.kernel["WavefrontSize"]
125
126 @property
127 def laneSGPRC(self) -> int:
128 return self.parentWriter.states.laneSGPRCount
129
130 @property
131 def tmpS01(self):
132 return self.tmpSgpr
133
134 @property
135 def tmpS23(self):
136 return self.tmpS01 + self.laneSGPRC
137
138 @property
139 def debugConfig(self):
140 return self.parentWriter.db
141
142 @property
143 def computeDataType(self) -> DataType:
144 return self.kernel["ProblemType"]["ComputeDataType"]
145
146 @property
147 def destDataType(self) -> DataType:
148 return self.kernel["ProblemType"]["DestDataType"]
149
150 @property
151 def moduleName(self):
152 return "globalWriteBatch (Atomic)" if self.atomic else "globalWriteBatch (Non atomic)"
153
154 def getEdgeMovInstType(self):
155 return SMovB32 if self.wavelen == 32 else SMovB64
156
157 def getEdgeOrInstType(self):
158 return SOrB32 if self.wavelen == 32 else SOrB64
159
160 def getEdgeAndInstType(self):
161 return SAndB32 if self.wavelen == 32 else SAndB64
162
163 def getSOrSaveExecType(self):
164 return SOrSaveExecB32 if self.wavelen == 32 else SOrSaveExecB64
165
166 def emit(self) -> Module:
167 assert self._checkAtomicPreconditions()
168 module = Module(self.moduleName)
169 self._prolog(module)
170 self._emitAdd(module)
171 self._epilog(module)
172 return module
173
174 def globalStoreWait(self, elementIdx, waitCnter, vlcntTotalIssued, dscntTotalIssued, interleaveStoreVmcnt: bool):
175 vlcnt = -1
176 dscnt = -1
177 vscnt = -1
178 isSingleKernel = ((self.kernel["GlobalSplitU"] == 1 or self.kernel["GlobalSplitU"] == -1) or self.kernel["GlobalSplitUAlgorithm"] == "MultipleBufferSingleKernel") or self.kernel["StreamK"] > 0
179 if interleaveStoreVmcnt:
180 waitLocalLoadCnt = 0
181 waitLocalLoadCntStrList = []
182 waitLoadCnt = 0
183 waitLoadCntStrList = []
184 # Calculate global loads
185 if self.beta:
186 waitLoadCnt += self.betaLoadIssued[elementIdx]
187 waitLoadCntStrList.append("%d (beta)"%self.betaLoadIssued[elementIdx])
188 if self.loadE:
189 waitLoadCnt += self.eLoadIssued[elementIdx]
190 waitLoadCntStrList.append("%d (load E)"%self.eLoadIssued[elementIdx])
191 # Calculate local loads
192 if self.parentWriter.states.useBias == DataDirection.READ:
193 waitLocalLoadCnt += self.biasLoadIssued[elementIdx]
194 waitLocalLoadCntStrList.append("%d (bias)"%self.biasLoadIssued[elementIdx])
195 if (self.kernel["ProblemType"]["UseScaleAB"] == "Vector") and isSingleKernel:
196 waitLocalLoadCnt += self.scaleAVecLoadIssued[elementIdx]
197 waitLocalLoadCntStrList.append("%d (scaleAVec)"%self.scaleAVecLoadIssued[elementIdx])
198 waitLocalLoadCnt += self.scaleBVecLoadIssued[elementIdx]
199 waitLocalLoadCntStrList.append("%d (scaleBVec)"%self.scaleBVecLoadIssued[elementIdx])
200 if self.kernel["ProblemType"]["UseScaleAlphaVec"] and isSingleKernel:
201 waitLocalLoadCnt += self.scaleAlphaVecLoadIssued[elementIdx]
202 waitLocalLoadCntStrList.append("%d (scaleAlphaVec)"%self.scaleAlphaVecLoadIssued[elementIdx])
203 # Get vlcnt and dscnt
204 vlcnt = vlcntTotalIssued - waitLoadCnt
205 if waitCnter[0] > 0 or vlcnt != waitCnter[0] : # Check if global load issued > 0
206 if waitCnter[0] == vlcnt: # No need to wait if the global load cnt doesn't change
207 vlcnt = -1
208 else:
209 waitCnter[0] = vlcnt
210 else:
211 vlcnt = -1
212
213 dscnt = dscntTotalIssued - waitLocalLoadCnt
214 if waitCnter[1] > 0 or dscnt != waitCnter[1]: # Check if local load issued > 0
215 if waitCnter[1] == dscnt: # No need to wait if the local load cnt doesn't change
216 dscnt = -1
217 else:
218 waitCnter[1] = dscnt
219 else:
220 dscnt = -1
221 # Get vscnt
222 if vlcnt != -1 and not (self.parentWriter.states.asmCaps["SeparateVscnt"] or self.parentWriter.states.asmCaps["SeparateVMcnt"]):
223 vscnt = self.storesIssued if not self.kernel["GroupLoadStore"] else 0
224 if (vlcnt != -1) or (vscnt != -1) or (dscnt != -1):
225 # Get comment
226 comment = ""
227 if vlcnt != -1:
228 tmp = ""
229 for cntStr in waitLoadCntStrList:
230 tmp += " - %s"%cntStr
231 comment = "vlcnt(%s) = %d%s"%(vlcnt, vlcntTotalIssued, tmp)
232 if vscnt != -1:
233 comment = comment + (" " if comment else "") + "vscnt(%s)"%(vscnt)
234 if dscnt != -1:
235 tmp = ""
236 for cntStr in waitLocalLoadCntStrList:
237 tmp += " - %s"%cntStr
238 comment = comment + (" " if comment else "") + "dscnt(%d) = %d%s"%(dscnt, dscntTotalIssued, tmp)
239 # if not self.kernel["_GlobalAccumulation"] == "MultipleBufferSingleKernel":
240 return SWaitCnt(dscnt=dscnt, vlcnt=vlcnt, vscnt=vscnt, comment="%s (interleaved)"%comment)
241 else:
242 commentList = []
243 # Global read wait
244 if self.beta:
245 vlcnt = 0
246 commentList.append("Beta")
247 if self.loadE:
248 vlcnt = 0
249 commentList.append("E")
250 # Local read wait
251 if self.parentWriter.states.useBias == DataDirection.READ:
252 dscnt = 0
253 commentList.append("Bias LDS")
254 if (self.kernel["ProblemType"]["UseScaleAB"] == "Vector") and isSingleKernel:
255 dscnt = 0
256 commentList.append("ScaleABVec")
257 if self.kernel["ProblemType"]["UseScaleAlphaVec"] and isSingleKernel:
258 dscnt = 0
259 commentList.append("ScaleAlphaVec")
260 if (vlcnt != -1) or (dscnt != -1):
261 # Get comment
262 comment = "wait for " + commentList[0]
263 for c in commentList[1:]:
264 comment += ", %s"%c
265 return SWaitCnt(dscnt=dscnt, vlcnt=vlcnt, vscnt=vscnt, comment=comment)
266 return None
267
268 ##############################################################################
269 # choose the ADD instruction for combining external C with internal C
270 # used in atomic=1 case to compute expected external data
271 ##############################################################################
272 def _chooseAddForAtomic(self, kernel, dst, src0, src1, comment):
273 module = Module("chooseAddForAtomic")
274 if kernel["ProblemType"]["DataType"].isBFloat16():
275 if kernel["_GlobalAccumulation"]:
276 module.add(VAddF32(dst, src0, src1, comment=comment))
277 elif kernel["ProblemType"]["DataType"].isHalf():
278 if kernel["_GlobalAccumulation"]:
279 module.add(VAddF32(dst, src0, src1, comment=comment))
280 elif kernel["ProblemType"]["HighPrecisionAccumulate"]:
281 if self.parentWriter.states.asmCaps["v_fma_mix_f32"]:
282 module.add(VFmaMixF32(dst, src0, 1, src1, comment=comment))
283 elif self.parentWriter.states.asmCaps["v_mad_mix_f32"]:
284 module.add(VMadMixF32(dst, src0, 1, src1, comment=comment))
285 else:
286 assert False, "No valid v_mad_mix_f32 equivalent"
287 else:
288 module.add(VAddPKF16(dst, src0, src1, comment))
289 elif kernel["ProblemType"]["DataType"].isInt8x4() or kernel["ProblemType"]["DataType"].isInt8():
290 # assume v_add_i32 can be used in place of v_add_f32
291 # need to add saturation directive to v_add_i32 instruction to clamp integer arithmetic
292 module.add(VAddI32(dst, src0, src1, comment=comment))
293 elif kernel["ProblemType"]["DataType"].isSingle():
294 module.add(VAddF32(dst, src0, src1, comment=comment))
295 else:
296 #support for double
297 module.add(VAddF64(dst, src0, src1, comment=comment))
298
299 return module
300
301 def _prolog(self, module: Module):
302 module.addComment0("optSingleColVgpr=%u optSharedColVgpr=%u optSGPRUsage=%s optSrdIncForRow=%u factorDim=%u" % \
303 (self.ss.optSingleColVgpr, self.ss.optSharedColVgpr, self.ss.optSGPRUsage, self.ss.optSrdIncForRow, self.factorDim))
304
305 if self.kernel["StoreSyncOpt"]:
306 self._storeSyncOpt(module)
307
308 # comment tt1, tt0, vc1, vc0
309 # tt = thread tile, vc=vector component
310 commentStr = "Global Write%s%s Batch #%u (d1,d0,vc1,vc0) =\n " \
311 % (" Beta" if self.beta else "", " Edge" if self.edge else "", self.batchIdx)
312
313 commentStr = ''.join([commentStr] \
314 + ["(%u,%u,%u,%u:vw%u%s)%s" % \
315 (element[0], element[1], element[2], element[3], self.gwvw,
316 ":vaw:%u"%self.atomicW if self.atomic else "",
317 "" if idx == len(self.batchElements) -1 else "; ")
318 for idx, element in enumerate(self.batchElements)])
319 module.addComment2(commentStr)
320
321 if self.kernel["_GlobalAccumulation"] != "MultipleBufferSingleKernel":
322 self.ss.setupStoreElementsForBatch(self.kernel, self.gwvw, self.batchElements, self.batchElementSgprs, isOptNLL=False, factorDim=self.factorDim)
323 else:
324 self.ss.setupStoreElementsForBatch(self.kernel, self.gwvw, self.batchElements, self.batchElementSgprs, isOptNLL=True, factorDim=self.factorDim)
325
326 self.localLoadsBiasIssued = 0
327 self.storesIssued = 0
328 self.loadsBetaIssued = 0
329 self.loadsEIssued = 0
330 self.loadsScaleAVecIssued = 0
331 self.loadsScaleBVecIssued = 0
332 self.loadsScaleAlphaVecIssued = 0
333
334 ########################################
335 # calculate addr and masks
336 module.addComment1("calc coords, apply mask, and issue loads (if necessary)")
337 # On input, coord0 and coord1 are VGPRs computed in the pre-batch code, based
338 # on the thread and tid number. These are ELEMENT offsets from start of tensor C
339 # for the top-left corner this thread will write. These are not changed
340 # across all the store loop iters.
341 if self.debugConfig["ConservativeWaitCnt"] & 0x10:
342 module.add(SBarrier("debug"))
343 module.add(SWaitCnt(vlcnt=0, vscnt=0, comment="ConservativeWaitCnt"))
344 module.add(SBarrier("debug"))
345 if not self.edge and self.debugConfig["ForceEdgeStores"] >= 2:
346 module.add(self.parentWriter.getBomb()) # should not get here
347 if self.edge and self.debugConfig["AssertNoEdge"]:
348 module.add(self.parentWriter.getBomb()) # should not get here
349
350 ########################################
351 # rC *= alpha
352 if not self.kernel["InterleaveAlpha"] and self.applyAlpha and self.parentWriter.alphaBeforeLoadC:
353 module.addComment1("rC *= alpha batchElements=%s"%self.batchElements)
354 if self.codeMulAlpha is None:
355 elementIdx = 0
356 while elementIdx < len(self.batchElements):
357 isEnd = (elementIdx == len(self.batchElements) - 1)
358 if not isEnd and (self.ss.elementSumIdx[elementIdx] + 1 == self.ss.elementSumIdx[elementIdx + 1]) and (self.ss.elementSumIdx[elementIdx] % 2 == 0):
359 module.add(self._applyAlpha(self.kernel, self.gwvw, self.ss.elementSumIdx, elementIdx, self.tmpS01, usePK=True))
360 elementIdx += 2
361 else:
362 module.add(self._applyAlpha(self.kernel, self.gwvw, self.ss.elementSumIdx, elementIdx, self.tmpS01))
363 elementIdx += 1
364 else:
365 regsPerScalar = self.parentWriter.states.bpeCinternal // self.parentWriter.states.bpr # register per scalar
366 for elementIdx in range(len(self.batchElements)):
367 for vi in range(self.gwvw):
368 module.add(replaceHolder(self.codeMulAlpha.popFirstItem(), self.ss.elementSumIdx[elementIdx]*regsPerScalar + regsPerScalar*vi))
369
370 loadInputCode = Module("loadInputCode")
371
372 self.betaLoadIssued = []
373 self.eLoadIssued = []
374 self.biasLoadIssued = []
375 self.scaleAVecLoadIssued = []
376 self.scaleBVecLoadIssued = []
377 self.scaleAlphaVecLoadIssued = []
378 loadedDataBeta = {}
379 loadedDataE = {}
380 loadedDataBias = {}
381 loadedDataScaleAVec = {}
382 loadedDataScaleBVec = {}
383 loadedDataScaleAlphaVec = {}
384
385 if self.kernel["BufferStore"] and (self.edge or (self.kernel["NumWaveSplitK"] > 1)):
386 bufferOOB = self.tmpVgpr + self.tmpVgprSize - 1
387 module.add(VMovB32(dst=vgpr(bufferOOB), src="BufferOOB"))
388 else:
389 bufferOOB = None
390 #when factorDim = 1 the bias's gwvw is alwasy be 1.
391 factor_gwvw = 1 if self.factorDim else self.ss.cfg.gwvw
392 for elementIdx, element in enumerate(self.batchElements):
393 addrCalc: AddrCalculation = self.ss.elementAddr[elementIdx]
394 addrCVgpr = addrCalc.addrCVgpr
395 addrDVgpr = addrCalc.addrDVgpr
396 addrEVgpr = addrCalc.addrEVgpr
397 addrBiasVgpr = addrCalc.addrBiasVgpr
398 addrScaleAVecVgpr = addrCalc.addrScaleAVecVgpr
399 addrScaleBVecVgpr = addrCalc.addrScaleBVecVgpr
400 addrScaleAlphaVecVgpr = addrCalc.addrScaleAlphaVecVgpr
401 data = self.ss.elementData[elementIdx]
402 dataBeta = self.ss.elementData[elementIdx]
403 dataE = self.ss.elementDataE[elementIdx]
404 dataBias = self.ss.elementDataBias[elementIdx]
405 dataScaleAVec = self.ss.elementDataScaleAVec[elementIdx]
406 dataScaleBVec = self.ss.elementDataScaleBVec[elementIdx]
407 dataScaleAlphaVec = self.ss.elementDataScaleAlphaVec[elementIdx]
408 mask = self.ss.elementMask[elementIdx]
409 vc0 = element[3]
410 sumIdxGSUSYNC = self.ss.elementSumIdx[elementIdx]
411
412 module.add(addrCalc.emitAddressSetupCode(self.kernel, self.tPB, self.ss, self.tmpVgpr, self.tmpS01, self.edge, self.beta, self.atomic, elementIdx, addrDVgpr))
413
414 if self.edge:
415 module.add(addrCalc.edgeProtectCode(self.kernel, self.edge, self.beta, self.atomic, mask, self.tmpSgpr))
416 if self.kernel["_GlobalAccumulation"] == "MultipleBufferSingleKernel":
417 module.addComment1("edge Protect")
418 # create code Module to push mov vgpr,acc instructions
419 if self.beta:
420 module.add(addrCalc.emitLdChange(self.kernel, self.ss, 'C', self.edge, self.beta, mask, bufferOOB, (elementIdx == 0), self.tmpVgpr, self.tmpSgpr, addrCVgpr, self.addrC, 0))
421 if dataBeta not in loadedDataBeta:
422 if self.kernel["GroupLoadStore"]:
423 loadInputCode.add(self.parentWriter.readInput(self.kernel, self.ss, 'C', self.kernel["ProblemType"]["DestDataType"], addrCalc, vc0, data, self.gwvw, addrCVgpr, self.tmpS01))
424 else:
425 module.add(self.parentWriter.readInput(self.kernel, self.ss, 'C', self.kernel["ProblemType"]["DestDataType"], addrCalc, vc0, data, self.gwvw, addrCVgpr, self.tmpS01))
426 loadedDataBeta[dataBeta] = ceil(self.kernel["ProblemType"]["DestDataType"].numBytes() * self.ss.cfg.gwvw / 16)
427 self.loadsBetaIssued += ceil(self.kernel["ProblemType"]["DestDataType"].numBytes() * self.gwvw / 16)
428 self.betaLoadIssued.append(len(loadedDataBeta) * ceil(self.kernel["ProblemType"]["DestDataType"].numBytes() * self.ss.cfg.gwvw / 16))
429
430 if (self.kernel["ProblemType"]["UseE"] and self.kernel["ProblemType"]["Gradient"] and self.kernel["ProblemType"]["ActivationType"] != 'none') and ((self.kernel["GlobalSplitU"] == 1 or self.kernel["GlobalSplitU"] == -1) or self.kernel["StreamK"] > 0):
431 module.add(addrCalc.emitLdChange(self.kernel, self.ss, 'E', self.edge, self.beta, mask, bufferOOB, (elementIdx == 0), self.tmpVgpr, self.tmpSgpr, addrEVgpr, self.addrE, 0))
432 if dataE not in loadedDataE:
433 loadOffset = int((self.kernel["ProblemType"]["ComputeDataType"].numRegisters() - self.kernel["ProblemType"]["DataTypeE"].numRegisters()) * self.ss.cfg.gwvw)
434 if self.kernel["GroupLoadStore"]:
435 loadInputCode.add(self.parentWriter.readInput(self.kernel, self.ss, 'E', self.kernel["ProblemType"]["DataTypeE"], addrCalc, vc0, dataE + loadOffset, self.gwvw, addrEVgpr, self.tmpS01))
436 else:
437 module.add(self.parentWriter.readInput(self.kernel, self.ss, 'E', self.kernel["ProblemType"]["DataTypeE"], addrCalc, vc0, dataE + loadOffset, self.gwvw, addrEVgpr, self.tmpS01))
438 loadedDataE[dataE] = ceil(self.kernel["ProblemType"]["DataTypeE"].numBytes() * self.ss.cfg.gwvw / 16)
439 self.loadsEIssued += ceil(self.kernel["ProblemType"]["DataTypeE"].numBytes() * self.gwvw / 16)
440 self.loadE = True
441 else:
442 self.loadE = False
443 self.eLoadIssued.append(len(loadedDataE) * ceil(self.kernel["ProblemType"]["DataTypeE"].numBytes() * self.ss.cfg.gwvw / 16))
444
445 def addEpilogueLoad(modGwvw, ldName: str, addrVecVgpr, addrVec, dataVec, loadedDataVec, vecOffset, gwvw, referenceVgpr, dim, referenceDim, skipLoad=False, comment=""):
446 loadsIssued = 0
447 module.add(addrCalc.emitLdChange(self.kernel, self.ss, ldName, self.edge, self.beta, mask, bufferOOB, (elementIdx == 0), self.tmpVgpr, self.tmpSgpr, addrVecVgpr, addrVec, dim))
448 ldsAddrVgpr = referenceVgpr if (referenceVgpr and (dim == referenceDim)) else addrVecVgpr
449 isSingleKernel = ((self.kernel["GlobalSplitU"] == 1 or self.kernel["GlobalSplitU"] == -1) or self.kernel["GlobalSplitUAlgorithm"] == "MultipleBufferSingleKernel") or self.kernel["StreamK"] > 0
450 if dataVec not in loadedDataVec:
451 if self.kernel["GroupLoadStore"]:
452 # Group bias load with C input to
453 if isSingleKernel and (not self.isLocalBarrierInit):
454 loadInputCode.add(SWaitCnt(dscnt=0, comment="Wait for LDS write"))
455 loadInputCode.add(SBarrier("LDS write barrier"))
456 self.isLocalBarrierInit = True
457 loadInputCode.add(self.parentWriter.addLdsLoad(self.kernel["ProblemType"]["ComputeDataType"], dataVec, ldsAddrVgpr, vecOffset, gwvw, comment=comment))
458 else:
459 if isSingleKernel and (not self.isLocalBarrierInit):
460 module.add(SWaitCnt(dscnt=0, comment="Wait for LDS write"))
461 module.add(SBarrier("LDS write barrier"))
462 self.isLocalBarrierInit = True
463 module.add(self.parentWriter.addLdsLoad(self.kernel["ProblemType"]["ComputeDataType"], dataVec, ldsAddrVgpr, vecOffset, gwvw, comment=comment))
464 loadedDataVec[dataVec] = ceil(self.kernel["ProblemType"]["ComputeDataType"].numBytes() * gwvw / 16)
465 loadsIssued = ceil(self.kernel["ProblemType"]["ComputeDataType"].numBytes() * gwvw / 16)
466 if (self.ss.cfg.gwvw != gwvw) and (not skipLoad):
467 remain_load = self.ss.cfg.gwvw - 1
468 bpl = self.kernel["ProblemType"]["ComputeDataType"].numBytes() * gwvw
469 bpr = ceil(bpl / self.parentWriter.states.bpr)
470 #For below ds_read instruction do not add bias issued , because of all ds_load instructions need to be completed at the same time in this batch.
471 for r in range(remain_load):
472 modGwvw.add(self.parentWriter.addLdsLoad(self.kernel["ProblemType"]["ComputeDataType"], dataVec, ldsAddrVgpr, vecOffset, factor_gwvw, comment=comment))
473 return loadsIssued
474
475 skipLoad = True if self.factorDim else False
476
477 modGwvwScale = []
478 localReferenceVgpr = None
479 if self.parentWriter.states.useBias == DataDirection.READ:
480 modGwvwBias = Module("GwvwBias")
481 self.localLoadsBiasIssued += addEpilogueLoad(modGwvwBias, 'Bias', addrBiasVgpr, self.addrBias, dataBias, loadedDataBias, addrCalc.biasOffset[self.factorDim], factor_gwvw, localReferenceVgpr, self.factorDim, self.factorDim, skipLoad=skipLoad, comment="load Bias")
482 localReferenceVgpr = addrBiasVgpr
483 modGwvwScale.append(modGwvwBias)
484
485 self.biasLoadIssued.append(len(loadedDataBias) * ceil(self.kernel["ProblemType"]["ComputeDataType"].numBytes() * factor_gwvw / 16))
486
487 isSingleKernel = ((self.kernel["GlobalSplitU"] == 1 or self.kernel["GlobalSplitU"] == -1) or self.kernel["GlobalSplitUAlgorithm"] == "MultipleBufferSingleKernel") or self.kernel["StreamK"] > 0
488
489 if self.kernel["ProblemType"]["UseScaleAlphaVec"] and isSingleKernel:
490 modGwvwScaleAlpha = Module("GwvwScaleAlpha")
491 self.loadsScaleAlphaVecIssued += addEpilogueLoad(modGwvwScaleAlpha, "ScaleAlphaVec", addrScaleAlphaVecVgpr, self.addrScaleAlphaVec, dataScaleAlphaVec, loadedDataScaleAlphaVec, addrCalc.scaleAlphaVecOffset[self.factorDim], factor_gwvw, localReferenceVgpr, self.factorDim, self.factorDim, skipLoad=skipLoad, comment="load scaleAlpha")
492 if localReferenceVgpr == None:
493 localReferenceVgpr = addrScaleAlphaVecVgpr
494 modGwvwScale.append(modGwvwScaleAlpha)
495 self.scaleAlphaVecLoadIssued.append(len(loadedDataScaleAlphaVec) if self.factorDim else len(loadedDataScaleAlphaVec) * ceil(self.kernel["ProblemType"]["ComputeDataType"].numBytes() * factor_gwvw / 16))
496
497 if (self.kernel["ProblemType"]["UseScaleAB"] == "Vector") and isSingleKernel:
498 modGwvwScaleA = Module("GwvwScaleA")
499 modGwvwScaleB = Module("GwvwScaleB")
500 self.loadsScaleAVecIssued += addEpilogueLoad(modGwvwScaleA, "ScaleAVec", addrScaleAVecVgpr, self.addrScaleAVec, dataScaleAVec, loadedDataScaleAVec, addrCalc.scaleAVecOffset, self.ss.cfg.gwvw, localReferenceVgpr, 0, self.factorDim, comment="load scaleA")
501 self.loadsScaleBVecIssued += addEpilogueLoad(modGwvwScaleB, "ScaleBVec", addrScaleBVecVgpr, self.addrScaleBVec, dataScaleBVec, loadedDataScaleBVec, addrCalc.scaleBVecOffset, 1, localReferenceVgpr, 1, self.factorDim, skipLoad=True, comment="load scaleB")
502 if localReferenceVgpr == None:
503 localReferenceVgpr = addrScaleAVecVgpr if self.factorDim == 0 else addrScaleBVecVgpr
504 modGwvwScale.append(modGwvwScaleA)
505 modGwvwScale.append(modGwvwScaleB)
506 self.scaleAVecLoadIssued.append(len(loadedDataScaleAVec) * ceil(self.kernel["ProblemType"]["ComputeDataType"].numBytes() * self.ss.cfg.gwvw / 16))
507 self.scaleBVecLoadIssued.append(len(loadedDataScaleBVec))
508
509 # Reorder scale
510 length = 0
511 for mod in modGwvwScale:
512 length = max(length, len(mod.items()))
513
514 for index in range(0, length):
515 for mod in modGwvwScale:
516 if len(mod.items()) > index:
517 module.add(mod.items()[index])
518
519 if (self.kernel["ProblemType"]["UseE"] and not self.kernel["ProblemType"]["Gradient"]) and ((self.kernel["GlobalSplitU"] == 1 or self.kernel["GlobalSplitU"] == -1) or self.kernel["StreamK"] > 0):
520 module.add(addrCalc.emitLdChange(self.kernel, self.ss, 'E', self.edge, self.beta, mask, bufferOOB, (elementIdx == len(self.batchElements) - 1), self.tmpVgpr, self.tmpSgpr, addrEVgpr, self.addrE, 0))
521 if self.storeBiasD == 1:
522 module.add(addrCalc.emitLdChange(self.kernel, self.ss, 'Bias', self.edge, self.beta, mask, bufferOOB, (elementIdx == len(self.batchElements) - 1), self.tmpVgpr, self.tmpSgpr, addrBiasVgpr, self.addrBias, self.factorDim))
523 if self.kernel["GlobalSplitU"] == 1 or (self.kernel["GlobalSplitUAlgorithm"] != "MultipleBufferSingleKernel"): # "SingleBuffer" or "MultipleBuffer"
524 module.add(addrCalc.emitLdChange(self.kernel, self.ss, 'D', self.edge, self.beta, mask, bufferOOB, (elementIdx == len(self.batchElements) - 1), self.tmpVgpr, self.tmpSgpr, addrDVgpr, self.addrD, 0))
525 if self.kernel["_GlobalAccumulation"] == "MultipleBufferSingleKernel":
526 module.add(addrCalc.emitLdChange(self.kernel, self.ss, 'TD', self.edge, self.beta, mask, bufferOOB, (elementIdx == len(self.batchElements) - 1), self.tmpVgpr, self.tmpSgpr, addrCalc.addrGSUSyncVgprs, self.addrD, 0))
527
528 if self.atomic and (not self.parentWriter.states.useAtomicAdd):
529 # load c into data+1 because of CAS structure
530 # TODO - Fix for double here, would need bigger load
531 # FIXME
532 # gwvw is the number of elements in the batch
533 # iterate over number of atomic operations to perform, each of width atomicW
534 for avi in range(self.gwvw // self.atomicW):
535 dataV = self.ss.elementData[elementIdx] + int(avi*self.ss.cfg.numVgprsPerDataPerVI)
536 bpm = self.parentWriter.states.bpeCexternal * self.atomicW
537 useBuffer = self.kernel["BufferStore"]
538 if self.kernel["BufferStore"]: # yes, BufferStore here - use same addressing regs for this load
539 addr0 = vgpr(addrDVgpr)
540 addr1 = sgpr("SrdD", 4)
541 else:
542 addr0 = vgpr(addrDVgpr, 2)
543 addr1 = ""
544 # Calculate vgpr Index for 32-bit/64-bit instruction
545 # DGEMM use SRCS[2] register
546 vgprIdx = bpm // 4
547 module.add(self.parentWriter.chooseGlobalRead(useBuffer, bpm, dataV + vgprIdx, \
548 addr0, addr1, soffset=0, offset=addrCalc.globalOffset,
549 comment="load D (atomic) bpm=%u vaw=%u"%(bpm,self.atomicW)))
550
551 if self.kernel["InterleaveAlpha"] and self.applyAlpha:
552 module.add(self._applyAlpha(self.kernel, self.gwvw, self.ss.elementSumIdx, elementIdx, self.tmpS01))
553
554 if not self.kernel["BufferStore"]:
555 offsetSrc = (self.tmpVgpr + 2) if self.beta else addrDVgpr
556
557 module.add(VAddCOU32(vgpr(addrDVgpr+0), VCC(), vgpr(self.addrD+0), \
558 vgpr(offsetSrc+0), "addrDVgpr = D + index*bytes (lo)"))
559 module.add(VAddCCOU32(vgpr(addrDVgpr+1), VCC(), vgpr(self.addrD+1), \
560 vgpr(offsetSrc+1), VCC(), "addrDVgpr = D + index*bytes (hi)"))
561
562 # restore full exec mask for calculating addr of next element
563 if self.edge and (self.beta or self.loadE or self.atomic):
564 module.add(self.getEdgeMovInstType()(EXEC(), -1, "full mask -1 -> exec"))
565
566 if self.kernel["_GlobalAccumulation"] == "MultipleBufferSingleKernel":
567 if self.ss.optSrdIncForRow and addrCalc.rowInc and self.kernel["StoreRemapVectorWidth"] > 0:
568 module.addComment1("StoreRemap: shift coord1 address MultipleBufferSingleKernel")
569 if self.kernel["ProblemType"]["UseE"] and (self.kernel["GlobalSplitU"] == 1 or self.kernel["GlobalSplitU"] == -1):
570 # TODO Check if works with StreamK
571 printExit("Use E does not support StoreRemapVectorWidth if GSU == 1.")
572 # module.add(addrCalc.incrementToNextRow(self.kernel, "E", self.ss, self.tmpS01, isCompute=True))
573 module.add(addrCalc.incrementToNextRow(self.kernel, "D", self.ss, self.tmpS01))
574 module.add(VMovB32(vgpr(self.tmpVgpr), addrCalc.rowInc, comment="set shift rows"))
575 module.add(VAddU32(vgpr(self.parentWriter.vgprs.storeRemapCoord1), vgpr(self.parentWriter.vgprs.storeRemapCoord1), vgpr(self.tmpVgpr), "shift storeRemap coord1"))
576
577 module.add(loadInputCode)
578
579 if self.beta and self.kernel["StoreSyncOpt"]:
580 self._storeSyncOpt(module)
581
582 ########################################
583 # AccVgpr read
584 if self.codeAccVgprRead is not None and (self.kernel["LocalSplitU"] == 1 or self.kernel["_GlobalAccumulation"] == "MultipleBufferSingleKernel"):
585 regsPerScalar = self.parentWriter.states.bpeCinternal // self.parentWriter.states.bpr # register per scalar
586 if self.kernel["MIArchVgpr"] and self.kernel["LocalSplitU"] > 1:
587 tmpStartVgprValuC = self.parentWriter.states.c.startVgprValu
588 self.parentWriter.states.c.startVgprValu = 0
589 module.add(RegSet("v", "vgprValuC", 0))
590 # loop over store instructions within one batch
591 for elementIdx in range(len(self.batchElements)):
592 # loop over scalars within one store instruction
593 for vi in range(self.gwvw):
594 # loop over registers within one scalar
595 for rIdx in range(0, regsPerScalar):
596 module.add(replaceHolder(self.codeAccVgprRead.popFirstItem(), self.ss.elementSumIdx[elementIdx]*regsPerScalar + regsPerScalar*vi + rIdx - self.parentWriter.states.c.startVgprValu))
597
598 if self.kernel["MIArchVgpr"] and self.kernel["LocalSplitU"] > 1:
599 self.parentWriter.states.c.startVgprValu = tmpStartVgprValuC
600 module.add(RegSet("v", "vgprValuC", tmpStartVgprValuC))
601
602 elif self.kernel["LocalSplitU"] > 1:
603 # read from LSU VGPRs
604 regsPerScalar = self.parentWriter.states.bpeCinternal // self.parentWriter.states.bpr # register per scalar
605 if self.ss.lsuStartVgprOffset > 0:
606 for elementIdx in range(len(self.batchElements)):
607 for vi in range(self.gwvw):
608 for rIdx in range(0, regsPerScalar):
609 idx = self.ss.elementSumIdx[elementIdx]*regsPerScalar + regsPerScalar*vi + rIdx - self.parentWriter.states.c.startVgprValu
610 module.add(VMovB32(vgpr("ValuC+%u"%(idx)), vgpr("ValuC+%u"%(idx + self.ss.lsuStartVgprOffset)), comment="load from "+str(idx + self.ss.lsuStartVgprOffset)+" to "+str(idx) ))
611 self.ss.lsuStartVgprOffset += len(self.batchElements) * self.gwvw * regsPerScalar
612
613 if not self.kernel["MIArchVgpr"]:
614 module.add(SNop(1, "2 wait states required before reading vgpr"))
615
616 if self.kernel["_GlobalAccumulation"] == "MultipleBufferSingleKernel":
617 module.addComment1("store after Acc, "+"GSU: "+str(self.kernel["GlobalSplitU"]))
618
619 storeCodeGSUSK = Module("GroupLoadStore")
620 if self.kernel["_GlobalAccumulation"] == "MultipleBufferSingleKernel":#GSUGSU
621 storeWidth = self.kernel["StoreVectorWidth"]
622 for elementIdx in range(0, len(self.batchElements)):
623 addrCalc: AddrCalculation = self.ss.elementAddr[elementIdx]
624 if self.batchIdx == 0 and elementIdx == 0:
625 addrDVgpr = addrCalc.addrDVgpr
626 storeCodeGSUSK.add(vectorStaticMultiply(vgpr(addrDVgpr), vgpr("Serial"), storeWidth * self.parentWriter.states.bpeCinternal, ContinuousRegister(self.tmpS01, 1)))
627 storeCodeGSUSK.add(SMovB32(dst=sgpr(self.tmpS01), src=0, comment="Init sgpr offset"))
628 storeCodeGSUSK.addSpaceLine()
629 if (self.kernel["ProblemType"]["UseE"] and not self.kernel["ProblemType"]["Gradient"]) and ((self.kernel["GlobalSplitU"] == 1 or self.kernel["GlobalSplitU"] == -1) or self.kernel["StreamK"] > 0):
630 vgprIdx = self.ss.elementSumIdx[elementIdx] - self.parentWriter.states.c.startVgprValu
631 vgprDst = self.activationSetPCStruct.vgprActCopy if mergeActFuncCall else "ValuC+%d"%vgprIdx
632 module.add(self.parentWriter.addStore(self.kernel, self.ss, 'E', addrCalc, vgprDst, self.tmpS01, self.edge, comment="store E"))
633
634 sumIdx = self.ss.elementSumIdx[elementIdx]
635 if self.kernel["StoreRemapVectorWidth"]:
636 rpe = self.parentWriter.states.bpeCinternal // self.parentWriter.states.bpr
637 module.add(self.parentWriter.storeRemapAddLocalWrite(self.kernel, self.ss, addrCalc, sumIdx*rpe))
638 # Column Block Shape has been written to LDS
639 # Now read back and write out to global memory
640 # module.add(storeCodeGSUSK)
641
642 if self.kernel["_GlobalAccumulation"] == "MultipleBufferSingleKernel" and self.kernel["StoreRemapVectorWidth"]:
643 if self.parentWriter.StoreRemapLastBatch == 1:
644 module.addComment1("Handle local read and global write")
645 storeModule, numNewStores = self.parentWriter.storeRemapAddStore(self.kernel, self.tmpVgpr, self.tmpS01, self.edge, self.parentWriter.StoreRemapLastBatch)
646 module.add(storeModule)
647 self.storesIssued += numNewStores
648
649 gsuComponent = Component.GSU.find(self.parentWriter)
650 module.add(gsuComponent.globalWriteBatchProlog(self.parentWriter, self.kernel, self.tmpVgpr, self.tmpVgprSize, self.tmpVgprDynamic, \
651 self.batchIdx, self.ss, self.gwvw, self.batchElements, \
652 self.beta, self.edge, sumIdxGSUSYNC, addrCalc))
653
654 # rC *= alpha
655 if not self.kernel["InterleaveAlpha"] and self.applyAlpha and not self.parentWriter.alphaBeforeLoadC:
656 module.addComment1("rC *= alpha batchElements=%s"%self.batchElements)
657 if self.codeMulAlpha is None:
658 elementIdx = 0
659 while elementIdx < len(self.batchElements):
660 isEnd = (elementIdx == len(self.batchElements) - 1)
661 if not isEnd and (self.ss.elementSumIdx[elementIdx] + 1 == self.ss.elementSumIdx[elementIdx + 1]) and (self.ss.elementSumIdx[elementIdx] % 2 == 0):
662 module.add(self._applyAlpha(self.kernel, self.gwvw, self.ss.elementSumIdx, elementIdx, self.tmpS01, usePK=True))
663 elementIdx += 2
664 else:
665 module.add(self._applyAlpha(self.kernel, self.gwvw, self.ss.elementSumIdx, elementIdx, self.tmpS01))
666 elementIdx += 1
667 else:
668 regsPerScalar = self.parentWriter.states.bpeCinternal // self.parentWriter.states.bpr # register per scalar
669 for elementIdx in range(len(self.batchElements)):
670 for vi in range(self.gwvw):
671 module.add(replaceHolder(self.codeMulAlpha.popFirstItem(), self.ss.elementSumIdx[elementIdx]*regsPerScalar + regsPerScalar*vi - self.parentWriter.states.c.startVgprValu ))
672
673 def _epilog(self, module: Module):
674 # return registers to pool:
675 lastDataD = -1
676 lastDataE = -1
677 checkedDataBias = {}
678 checkedDataScaleAVec = {}
679 checkedDataScaleBVec = {}
680 checkedDataScaleAlphaVec = {}
681 for elementIdx in range(len(self.batchElements)):
682 sumIdxGSUSYNC = self.ss.elementSumIdx[elementIdx]
683 if not self.ss.sharedColDVgprs:
684 addrCalc: AddrCalculation = self.ss.elementAddr[elementIdx]
685 addrEVgpr = addrCalc.addrEVgpr
686 addrDVgpr = addrCalc.addrDVgpr
687 addrGSUSyncVgprs = addrCalc.addrGSUSyncVgprs
688 addrCVgpr = addrCalc.addrCVgpr
689 addrBiasVgpr = addrCalc.addrBiasVgpr
690 addrScaleAVecVgpr = addrCalc.addrScaleAVecVgpr
691 addrScaleBVecVgpr = addrCalc.addrScaleBVecVgpr
692 addrScaleAlphaVecVgpr = addrCalc.addrScaleAlphaVecVgpr
693 if addrEVgpr != None:
694 self.parentWriter.vgprPool.checkIn(addrEVgpr)
695 self.parentWriter.vgprPool.checkIn(addrDVgpr)
696 if addrCVgpr != addrDVgpr:
697 self.parentWriter.vgprPool.checkIn(addrCVgpr)
698 if addrGSUSyncVgprs != None:
699 self.parentWriter.vgprPool.checkIn(addrGSUSyncVgprs)
700 if addrBiasVgpr != None:
701 self.parentWriter.vgprPool.checkIn(addrBiasVgpr)
702 if addrScaleAVecVgpr != None:
703 self.parentWriter.vgprPool.checkIn(addrScaleAVecVgpr)
704 if addrScaleBVecVgpr != None:
705 self.parentWriter.vgprPool.checkIn(addrScaleBVecVgpr)
706 if addrScaleAlphaVecVgpr != None:
707 self.parentWriter.vgprPool.checkIn(addrScaleAlphaVecVgpr)
708
709 data = self.ss.elementData[elementIdx]
710 if data != 0:
711 if data != lastDataD:
712 self.parentWriter.vgprPool.checkIn(data)
713 lastDataD = data
714
715 dataBias = self.ss.elementDataBias[elementIdx]
716 if dataBias != 0:
717 if dataBias not in checkedDataBias:
718 self.parentWriter.vgprPool.checkIn(dataBias)
719 checkedDataBias[dataBias] = 1
720
721 dataE = self.ss.elementDataE[elementIdx]
722 if dataE != 0:
723 if dataE != lastDataE:
724 self.parentWriter.vgprPool.checkIn(dataE)
725 lastDataE = dataE
726
727 def checkScaleVec(dataScaleVec, checkedDataScaleVec):
728 if dataScaleVec != 0:
729 if dataScaleVec not in checkedDataScaleVec:
730 self.parentWriter.vgprPool.checkIn(dataScaleVec)
731 checkedDataScaleVec[dataScaleVec] = 1
732
733 checkScaleVec(self.ss.elementDataScaleAVec[elementIdx], checkedDataScaleAVec)
734 checkScaleVec(self.ss.elementDataScaleBVec[elementIdx], checkedDataScaleBVec)
735 checkScaleVec(self.ss.elementDataScaleAlphaVec[elementIdx], checkedDataScaleAlphaVec)
736
737 self.ss.firstBatch = False
738 self.ss.checkInTempVgprC()
739 if self.kernel["_GlobalAccumulation"] != "MultipleBufferSingleKernel" and self.kernel["StoreRemapVectorWidth"]:
740 if self.parentWriter.StoreRemapLastBatch == 1:
741 module.addComment1("Handle local read and global write")
742 # this seems buggy? it's possible to issue more than one stores for SR
743 # module.add(self.storeRemapAddStore(kernel, tmpVgpr, tmpS01, edge))
744 # storesIssued += 1
745 storeModule, numNewStores = self.parentWriter.storeRemapAddStore(self.kernel, self.tmpVgpr, self.tmpS01, self.edge, self.parentWriter.StoreRemapLastBatch)
746 module.add(storeModule)
747 self.storesIssued += numNewStores
748
749 if self.parentWriter.states.serializedStore:
750 module.add(SNop(0, "1 wait state required when next inst writes vgprs held by previous dwordx4 store inst"))
751
752 if self.kernel["_GlobalAccumulation"] == "MultipleBufferSingleKernel":
753 module.addCommentAlign("GW end") #GSUSYNC
754
755 def _emitAdd(self, module: Module):
756 if self.atomic:
757 del self.tmpVgpr # catch bugs
758 if self.parentWriter.states.useAtomicAdd:
759 self._emitAtomicAdd(module)
760 else:
761 self._emitCasAdd(module)
762 else:
763 self._emitNonatomicAdd(module)
764
765 def _emitNonatomicAdd(self, module: Module):
766 ########################################
767 # Not Atomic
768 ########################################
769 # edge has v_cndmask so loads or stores may not issue, hard to track vmcnt:
770 interleaveStoreVmcnt = self.parentWriter.states.interleaveStoreVmcnt and not self.edge
771
772 for elementIdx in range(len(self.batchElements)):
773 for vi in range(self.gwvw):
774 sumIdxV = self.ss.elementSumIdx[elementIdx] + vi
775 newSumIdxV = sumIdxV - self.parentWriter.states.c.startVgprValu
776 # covers sgemm, gemm_ex(HHS/HSS/BBS/BSS (HPA=T)), int8 (int8x4?)
777 if self.kernel["ProblemType"]["ComputeDataType"].isInt32() or \
778 self.kernel["ProblemType"]["ComputeDataType"].isSingle(): # covers sgemm/gemm_ex(HHS/HSS/BBS/BSS)
779 if self.debugConfig["ForceExpectedValue"]:
780 module.add(VMovB32(vgpr("ValuC+%u"%newSumIdxV), self.debugConfig["ValueCExpectedValue"], "force expected value" ))
781 if self.parentWriter.db["ForceVSerial"]:
782 module.add(VMovB32(vgpr("ValuC+%u"%newSumIdxV), vgpr("Serial"), "force expected value to serial" ))
783 if self.parentWriter.db["CheckValueC"]:
784 module.add(SMovB32(sgpr(self.tmpS01), self.debugConfig["ValueCExpectedValue"], "Move expected value"))
785 module.add(self.parentWriter.getCmpAssert(self.parentWriter.asmAssert.eq, vgpr("ValuC+%u"%newSumIdxV), sgpr(self.tmpS01)))
786
787 ########################################
788 # wait for batched load
789 # Here we wait all
790 if not interleaveStoreVmcnt:
791 waitcntInst = self.globalStoreWait(0, [], 0, 0, False)
792 if waitcntInst:
793 module.add(waitcntInst)
794
795 module.addComment1("apply mask, calc new C and issue writes")
796 # module.add(self.getBomb()) # can see store addresses just before the store inst
797
798 activationCDataType = self.kernel["ProblemType"]["ActivationComputeDataType"]
799
800 if self.kernel["_GlobalAccumulation"] != 'MultipleBuffer':
801 if self.kernel["ProblemType"]["DestDataType"].isBFloat16() and self.kernel["ProblemType"]["HighPrecisionAccumulate"]:
802 module.add(VMovB32(vgpr(self.cvtVgprStruct.vgprBf16Mask), "0xffff0000", comment="mask for pack two bfloat16 element to 32bit" ))
803 module.add(VMovB32(vgpr(self.cvtVgprStruct.vgprFp32Nan), "0x7fff0000", comment="fp32 Nan" ))
804 module.add(VMovB32(vgpr(self.cvtVgprStruct.vgprBf16Inc), "0x7fff", comment="rounding bias for bfloat16" ))
805 elif self.kernel["ProblemType"]["DestDataType"].isFloat8_fnuz() and self.kernel["ProblemType"]["HighPrecisionAccumulate"]:
806 module.add(VMovB32(vgpr(self.cvtVgprStruct.vgprFp8NanInf), "0x207", comment="Nan and +/- inf" ))
807 module.add(VMovB32(vgpr(self.cvtVgprStruct.vgprFp8Max), "0x43700000", comment="Fp8 Max value 240 as float32" ))
808 module.add(VMovB32(vgpr(self.cvtVgprStruct.vgprFp8Min), "0xc3700000", comment="Fp8 Min value -240 as float32" ))
809 elif self.kernel["ProblemType"]["DestDataType"].isFloat8() and self.kernel["ProblemType"]["HighPrecisionAccumulate"]:
810 module.add(VMovB32(vgpr(self.cvtVgprStruct.vgprFp8NanInf), "0x207", comment="Nan and +/- inf" ))
811 module.add(VMovB32(vgpr(self.cvtVgprStruct.vgprFp8Max), "0x43E00000", comment="Fp8 Max value 448 as float32" ))
812 module.add(VMovB32(vgpr(self.cvtVgprStruct.vgprFp8Min), "0xc3E00000", comment="Fp8 Min value -448 as float32" ))
813 elif self.kernel["ProblemType"]["DestDataType"].isAnyBFloat8() and self.kernel["ProblemType"]["HighPrecisionAccumulate"]:
814 module.add(VMovB32(vgpr(self.cvtVgprStruct.vgprBF8NanInf), "0x207", comment="Nan and +/- inf" ))
815 module.add(VMovB32(vgpr(self.cvtVgprStruct.vgprBF8Max), "0x47600000", comment="BF8 Max value 57344 as float32" ))
816 module.add(VMovB32(vgpr(self.cvtVgprStruct.vgprBF8Min), "0xc7600000", comment="BF8 Min value -57344 as float32" ))
817
818 storeCode = Module("GroupLoadStore")
819 vlcntTotalIssued = self.loadsBetaIssued + self.loadsEIssued
820 dscntTotalIssued = self.localLoadsBiasIssued + self.loadsScaleAVecIssued + self.loadsScaleBVecIssued + self.loadsScaleAlphaVecIssued
821 waitCnter = [vlcntTotalIssued, dscntTotalIssued]
822 for elementIdx in range(0, len(self.batchElements)):
823 element = self.batchElements[elementIdx]
824 addrCalc: AddrCalculation = self.ss.elementAddr[elementIdx]
825 addr = addrCalc.addrDVgpr
826 dataE = self.ss.elementDataE[elementIdx]
827 dataBias = self.ss.elementDataBias[elementIdx]
828 dataScaleAVec = self.ss.elementDataScaleAVec[elementIdx]
829 dataScaleBVec = self.ss.elementDataScaleBVec[elementIdx]
830 dataScaleAlphaVec = self.ss.elementDataScaleAlphaVec[elementIdx]
831 mask = self.ss.elementMask[elementIdx]
832 vc0 = element[3]
833 sumIdx = self.ss.elementSumIdx[elementIdx]
834
835 # print(str(element)+" rowInc="+str(addrCalc.rowInc))
836 # Already write wave column block into LDS
837 # Now read lds data back to registers and write to global memroy
838 if self.kernel["_GlobalAccumulation"] != "MultipleBufferSingleKernel":
839 if self.ss.optSrdIncForRow and addrCalc.rowInc and self.kernel["StoreRemapVectorWidth"] > 0:
840 module.addComment1("StoreRemap: shift coord1 address")
841 if self.kernel["ProblemType"]["UseE"] and (self.kernel["GlobalSplitU"] == 1 or self.kernel["GlobalSplitU"] == -1):
842 # TODO Check if works with StreamK
843 printExit("Use E does not support StoreRemapVectorWidth if GSU == 1.")
844 # module.add(addrCalc.incrementToNextRow(self.kernel, "E", self.ss, self.tmpS01, isCompute=True))
845 module.add(addrCalc.incrementToNextRow(self.kernel, "D", self.ss, self.tmpS01))
846 module.add(VMovB32(vgpr(self.tmpVgpr), addrCalc.rowInc, comment="set shift rows"))
847 module.add(VAddU32(vgpr(self.parentWriter.vgprs.storeRemapCoord1), vgpr(self.parentWriter.vgprs.storeRemapCoord1), vgpr(self.tmpVgpr), "shift storeRemap coord1"))
848
849 # apply in-bounds exec mask
850 if self.edge and not self.kernel["BufferStore"]:
851 module.add(self.getEdgeMovInstType()(EXEC(), sgpr(mask, self.laneSGPRC), "sgprs -> exec"))
852
853 if interleaveStoreVmcnt:
854 waitcntInst = self.globalStoreWait(elementIdx, waitCnter, vlcntTotalIssued, dscntTotalIssued, True)
855 if waitcntInst:
856 module.addSpaceLine()
857 module.add(waitcntInst)
858
859 def applyScaleVec(vecModule, addressStr, dataScaleVec, factorDim, isGlobal=True):
860 if not self.beta and not self.applyAlpha: # case for beta-0 and alpha == 1,(OptNLL)
861 if (self.kernel["ProblemType"]["DestDataType"].isInt8() or self.kernel["ProblemType"]["DestDataType"].isInt32() or \
862 (self.kernel["ProblemType"]["DataType"].isInt8() and self.kernel["ProblemType"]["DestDataType"].isHalf()) or \
863 (self.kernel["ProblemType"]["DataType"].isInt8() and self.kernel["ProblemType"]["DestDataType"].isBFloat16())) and \
864 self.kernel["ProblemType"]["ComputeDataType"].isSingle():
865 module.add(convertData(self.gwvw, self.ss.elementSumIdx[elementIdx], cvtType=CvtType.CVT_I32_to_F32, \
866 inputPrefix="ValuC+", prefixOffset=self.parentWriter.states.c.startVgprValu))
867
868 if self.kernel["ProblemType"]["ComputeDataType"].isSingle():
869 maskConst = 1.0
870 elif self.kernel["ProblemType"]["ComputeDataType"].isInt32():
871 maskConst = 1
872
873 gwvw = 1 if factorDim else self.gwvw
874 if isGlobal:
875 vecModule.add(VCmpGtU32(dst=sgpr("Address%s"%addressStr, self.parentWriter.states.laneSGPRCount), src0=sgpr("Srd%s+2"%addressStr), src1=0, comment=" == 0 ?"))
876 for vi2 in range(0, gwvw):
877 vecModule.add(VCndMaskB32(
878 dst=vgpr(dataScaleVec + vi2), \
879 src1=vgpr(dataScaleVec + vi2), \
880 src0=maskConst, \
881 src2=sgpr("Address%s"%addressStr, self.parentWriter.states.laneSGPRCount), \
882 comment="1. mul 1 if 0"))
883 if factorDim and self.gwvw > 1:
884 vecModule.add(VMovB32(dst=vgpr(dataScaleVec+1), src=vgpr(dataScaleVec), comment="copy data%s to data%s+1"%(addressStr, addressStr)))
885
886 for vi in range(0, self.gwvw):
887 inputScaleVecVgpr = dataScaleVec + (0 if factorDim else vi)
888 sumIdxV = self.ss.elementSumIdx[elementIdx] + vi
889 if self.kernel["ProblemType"]["ComputeDataType"].isSingle():
890 vgprIdx = sumIdxV - self.parentWriter.states.c.startVgprValu
891 # Generate single f32 code if edge is detected.
892 if ((vi + 1) == self.gwvw) and ((self.gwvw % 2) == 1):
893 vecModule.add(VMulF32(dst=vgpr("ValuC+%d"%vgprIdx), src0=vgpr(inputScaleVecVgpr), src1=vgpr("ValuC+%d"%vgprIdx), comment="*= %sVMul"%addressStr ))
894 # Original packed route
895 elif vi%2 == 1:
896 assert (self.gwvw % 2 == 0)
897 else:
898 vecModule.add(VMulPKF32(dst=vgpr("ValuC+%d"%vgprIdx, 2), src0=vgpr(inputScaleVecVgpr, 2), src1=vgpr("ValuC+%d"%vgprIdx, 2), comment="*= %sVMulPK(%d)(%d)"%(addressStr, dataScaleVec,vi)))
899 elif self.kernel["ProblemType"]["ComputeDataType"].isInt32():
900 vgprIdx = sumIdxV - self.parentWriter.states.c.startVgprValu
901 # Generate single i32 code if edge is detected.
902 if ((vi + 1) == self.gwvw) and ((self.gwvw % 2) == 1):
903 vecModule.add(VMulLOU32(dst=vgpr("ValuC+%d"%vgprIdx), src0=vgpr(inputScaleVecVgpr), src1=vgpr("ValuC+%d"%vgprIdx), comment="*= %sVMul"%addressStr ))
904 elif vi%2 == 1:
905 assert (self.gwvw % 2 == 0)
906 else:
907 vecModule.add(VMulLOU32(dst=vgpr("ValuC+%d"%vgprIdx), src0=vgpr(inputScaleVecVgpr), src1=vgpr("ValuC+%d"%vgprIdx), comment="*= %sVMulPK(%d)(%d)"%(addressStr, dataScaleAlphaVec,vi)))
908 vecModule.add(VMulLOU32(dst=vgpr("ValuC+%d"%(vgprIdx+1)), src0=vgpr(inputScaleVecVgpr+1), src1=vgpr("ValuC+%d"%(vgprIdx+1)), comment="*= %sVMulPK(%d)(%d)"%(addressStr, dataScaleAlphaVec,vi)))
909 else:
910 raise RuntimeError("Unsupported %s compute data type %s."%(addressStr, str(self.kernel["ProblemType"]["ComputeDataType"])))
911
912 isSingleKernel = ((self.kernel["GlobalSplitU"] == 1 or self.kernel["GlobalSplitU"] == -1) or self.kernel["GlobalSplitUAlgorithm"] == "MultipleBufferSingleKernel") or self.kernel["StreamK"] > 0
913
914 scaleAVecModule = Module("ScaleAVecModule")
915 scaleBVecModule = Module("ScaleBVecModule")
916 if (self.kernel["ProblemType"]["UseScaleAB"] == "Vector") and isSingleKernel:
917 applyScaleVec(scaleAVecModule, "ScaleA", dataScaleAVec, 0, isGlobal=False)
918 applyScaleVec(scaleBVecModule, "ScaleB", dataScaleBVec, 1, isGlobal=False)
919 module.add(scaleAVecModule)
920 module.add(scaleBVecModule)
921
922 scaleAlphaVecModule = Module("scaleAlphaVecModule")
923 if self.kernel["ProblemType"]["UseScaleAlphaVec"] and isSingleKernel:
924 applyScaleVec(scaleAlphaVecModule, "ScaleAlphaVec", dataScaleAlphaVec, self.factorDim, isGlobal=False)
925 module.add(scaleAlphaVecModule)
926
927 if self.beta:
928 module.add(self._addSumAlphaWithCBeta(self.kernel, self.ss, self.gwvw, elementIdx, vc0, self.tmpVgpr, self.cvtVgprStruct))
929 elif ((self.parentWriter.states.useBias == DataDirection.READ) or self.kernel["ActivationFuncCall"]) and not self.applyAlpha \
930 and not ( self.kernel["ProblemType"]["UseScaleAlphaVec"] and isSingleKernel): # case of alpha=1 and beta=0
931 if (self.kernel["ProblemType"]["DestDataType"].isInt8() or self.kernel["ProblemType"]["DestDataType"].isInt32() or \
932 (self.kernel["ProblemType"]["DataType"].isInt8() and self.kernel["ProblemType"]["DestDataType"].isHalf()) or \
933 (self.kernel["ProblemType"]["DataType"].isInt8() and self.kernel["ProblemType"]["DestDataType"].isBFloat16())) and \
934 self.kernel["ProblemType"]["ComputeDataType"].isSingle():
935 module.add(convertData(self.gwvw, self.ss.elementSumIdx[elementIdx], cvtType=CvtType.CVT_I32_to_F32, \
936 inputPrefix="ValuC+", prefixOffset=self.parentWriter.states.c.startVgprValu))
937
938 # Add bias
939 mergeActFuncCall = False
940 if self.parentWriter.states.useBias == DataDirection.READ:
941 if activationCDataType == self.kernel["ProblemType"]["ComputeDataType"] and self.kernel["ActivationFuncCall"]:
942 mergeActFuncCall = True
943 if (self.kernel["ProblemType"]["Gradient"] and self.kernel["ProblemType"]["ActivationType"] != 'none' and self.kernel["ProblemType"]["UseE"]) and ((self.kernel["GlobalSplitU"] == 1 or self.kernel["GlobalSplitU"] == -1) or self.kernel["StreamK"] > 0):
944 mergeActFuncCall = False
945
946 if self.factorDim and self.gwvw > 1:
947 module.add(VMovB32(dst=vgpr(dataBias+1), src=vgpr(dataBias), comment="copy dataBias to dataBIas+1"))
948
949 for vi in range(0, self.gwvw):
950 inputVgpr = dataBias + + (0 if self.factorDim else vi)
951 sumIdxV = self.ss.elementSumIdx[elementIdx] + vi
952 if self.kernel["ProblemType"]["ComputeDataType"].isSingle():
953 vgprIdx = sumIdxV - self.parentWriter.states.c.startVgprValu
954 vgprDst = (self.activationSetPCStruct.vgprActCopy + vi) if mergeActFuncCall else "ValuC+%d"%vgprIdx
955 # Generate single f32 code if edge is detected.
956 if ((vi + 1) == self.gwvw) and ((self.gwvw % 2) == 1):
957 module.add(VAddF32(dst=vgpr(vgprDst), src0=vgpr(inputVgpr), src1=vgpr("ValuC+%d"%vgprIdx), \
958 comment="C += bias"))
959
960 # Original packed route
961 elif vi%2 == 1:
962 assert (self.gwvw % 2 == 0)
963 else:
964 module.add(VAddPKF32(dst=vgpr(vgprDst, 2), src0=vgpr(inputVgpr, 2), \
965 src1=vgpr("ValuC+%d"%vgprIdx, 2), comment="C += bias"))
966 else:
967 raise RuntimeError("Unsupported bias compute data type %s."%str(self.kernel["ProblemType"]["ComputeDataType"]))
968
969 if (self.kernel["ProblemType"]["UseE"] and not self.kernel["ProblemType"]["Gradient"]) and ((self.kernel["GlobalSplitU"] == 1 or self.kernel["GlobalSplitU"] == -1) or self.kernel["StreamK"] > 0):
970 vgprIdx = self.ss.elementSumIdx[elementIdx] - self.parentWriter.states.c.startVgprValu
971 vgprDst = self.activationSetPCStruct.vgprActCopy if mergeActFuncCall else vgprIdx
972 prefixStr = "" if mergeActFuncCall else "ValuC+"
973 prefixOffset = 0 if mergeActFuncCall else self.parentWriter.states.c.startVgprValu
974 # Packdata if needed
975 tmpVgpr = self.tmpVgpr
976 if mergeActFuncCall:
977 tmpVgpr += self.gwvw * self.kernel["ProblemType"]["ComputeDataType"].numRegisters()
978 if self.kernel["ProblemType"]["ComputeDataType"].isSingle():
979 if self.kernel["ProblemType"]["DataTypeE"].isHalf():
980 packdata = PackData_F16()
981 module.add(packdata(self.gwvw, tmpVgpr, vgprDst, tmpVgpr=tmpVgpr, inputPrefix=prefixStr, prefixOffset=prefixOffset))
982 vgprDst = tmpVgpr
983 elif self.kernel["ProblemType"]["DataTypeE"].isBFloat16():
984 packdata = PackData_BF16()
985 module.add(packdata(self.gwvw, tmpVgpr, vgprDst, self.cvtVgprStruct, self.tmpS01, self.laneSGPRC,
986 tmpVgpr=tmpVgpr, inputPrefix=prefixStr, prefixOffset=prefixOffset))
987 vgprDst = tmpVgpr
988 elif self.kernel["ProblemType"]["DataTypeE"].isSingle():
989 if not mergeActFuncCall:
990 vgprDst = "ValuC+%d" % vgprDst
991 elif self.kernel["ProblemType"]["DataTypeE"].isFloat8():
992 packdata = PackData_FLOAT8()
993 module.add(packdata(self.gwvw, tmpVgpr, vgprDst, self.cvtVgprStruct, self.tmpS01, self.laneSGPRC,
994 inputPrefix=prefixStr, prefixOffset=prefixOffset))
995 vgprDst = tmpVgpr
996 elif self.kernel["ProblemType"]["DataTypeE"].isFloat8_fnuz():
997 packdata = PackData_FLOAT8_fnuz()
998 module.add(packdata(self.gwvw, tmpVgpr, vgprDst, self.cvtVgprStruct, self.tmpS01, self.laneSGPRC,
999 inputPrefix=prefixStr, prefixOffset=prefixOffset))
1000 vgprDst = tmpVgpr
1001 else:
1002 printExit("Unsupport type for E output. (%s)"%self.kernel["ProblemType"]["DataTypeE"].toEnum())
1003 else:
1004 printExit("Unsupport compute type for E output. (%s)"%self.kernel["ProblemType"]["ComputeDataType"].toEnum())
1005
1006 module.add(self.parentWriter.addStore(self.kernel, self.ss, 'E', addrCalc, vgprDst, self.tmpS01, self.edge, comment="store E"))
1007
1008 SaturateTypeInt8 = SaturateCastType.NORMAL
1009
1010 gradientCvtModule = Module("gradientCvtModule")
1011 if (self.kernel["ProblemType"]["UseE"] and self.kernel["ProblemType"]["Gradient"]) and ((self.kernel["GlobalSplitU"] == 1 or self.kernel["GlobalSplitU"] == -1) or self.kernel["StreamK"] > 0):
1012 loadOffset = int((self.kernel["ProblemType"]["ComputeDataType"].numRegisters() - self.kernel["ProblemType"]["DataTypeE"].numRegisters()) * self.ss.cfg.gwvw)
1013 if activationCDataType != self.kernel["ProblemType"]["DataTypeE"]:
1014 if activationCDataType.isSingle() and self.kernel["ProblemType"]["DataTypeE"].isHalf():
1015 for vi in range(0, self.gwvw):
1016 dataEV = dataE + vi
1017 dataEV2 = dataE + vi // 2
1018 selectbit = SelectBit.WORD_0 if (self.gwvw != 1 and vi % 2 == 0) or (self.gwvw == 1 and elementIdx % 2 == 0) else SelectBit.WORD_1
1019 gradientCvtModule.add(VCvtF16toF32(dst=vgpr(dataEV), src=vgpr(dataEV2+loadOffset), sdwa=SDWAModifiers(src0_sel=selectbit), comment="gwvw %d, elementIdx %d"%(self.gwvw, elementIdx)))
1020 elif activationCDataType.isSingle() and self.kernel["ProblemType"]["DataTypeE"].isBFloat16():
1021 for vi in range(0, self.gwvw):
1022 dataEV = dataE + vi
1023 dataEV2 = dataE + vi // 2
1024 selectWord = 0 if (self.gwvw != 1 and vi % 2 == 0) or (self.gwvw == 1 and elementIdx % 2 == 0) else 1
1025 module.add(VCvtBF16toFP32(dst=vgpr(dataEV), src=vgpr(dataEV2+loadOffset), vgprMask=vgpr(self.cvtVgprStruct.vgprBf16Mask), vi=(selectWord), comment="gwvw %d, elementIdx %d"%(self.gwvw, elementIdx)))
1026 else:
1027 printExit("[Gradient input] Unsupported conversion.")
1028
1029 # Activation
1030 activationModule = None
1031 isActivationInsertAfter = False
1032 if self.kernel["ProblemType"]["Gradient"] and ((self.kernel["GlobalSplitU"] == 1 or self.kernel["GlobalSplitU"] == -1) or self.kernel["StreamK"] > 0):
1033 gradientInput = dataE
1034 enableValuC = False
1035 else:
1036 gradientInput = self.ss.elementSumIdx[elementIdx]
1037 enableValuC = True
1038 if self.kernel["LocalSplitU"] > 1:
1039 # When LSU > 1, the VGPRs are from LSU output.
1040 # the elementSumIdx has indicated the VGPRs from LSU.
1041 # Don't use the ValuC prefix here.
1042 enableValuC = False
1043 if self.kernel["ActivationFuncCall"]:
1044 if (activationCDataType == self.kernel["ProblemType"]["DestDataType"]) and \
1045 (activationCDataType != self.kernel["ProblemType"]["ComputeDataType"]) and ((self.kernel["ProblemType"]["UseScaleCD"] == False) or (self.kernel["ProblemType"]["UseScaleAlphaVec"] == False)):
1046 isActivationInsertAfter = True
1047 activationModule = Module("ActivationFuncCall")
1048 if (not mergeActFuncCall) and (not isActivationInsertAfter):
1049 activationModule.appendModule (copyData(activationCDataType, gradientInput, self.gwvw, \
1050 self.activationSetPCStruct.vgprActCopy))
1051 activationModule.add(SSwapPCB64(dst=sgpr(self.activationSetPCStruct.sgprOffsetBack, 2), \
1052 src=sgpr(self.activationSetPCStruct.sgprOffsetActivation, 2)))
1053 activationModule.appendModule (copyData(activationCDataType, gradientInput, self.gwvw, \
1054 self.activationSetPCStruct.vgprActCopy, 1))
1055 elif self.parentWriter.insertActivationAfterPacked(self.kernel, self.activationTypeStr) and (self.kernel["ProblemType"]["UseScaleAlphaVec"] == False):
1056 isActivationInsertAfter = True
1057 activationModule = self.parentWriter.getActivationDestDataType(self.kernel, self.activation, \
1058 self.activationTypeStr, self.gwvw, gradientInput , gradientInput, self.tmpVgpr, self.tmpSgpr)
1059 else:
1060 satInt8 = False
1061 if self.kernel["ProblemType"]["DestDataType"].isInt8():
1062 if (self.activationTypeStr == 'abs') or (self.activationTypeStr == 'relu'):
1063 SaturateTypeInt8 = SaturateCastType.DO_NOTHING
1064 satInt8 = True
1065 activationModule = self.parentWriter.getActivationActivationComputeType(self.kernel, self.activation, \
1066 self.activationTypeStr, self.gwvw, gradientInput, gradientInput, self.tmpVgpr, self.tmpSgpr, satInt8, enableValuC)
1067 # Add C *= GradientAct
1068 if self.kernel["ProblemType"]["ActivationType"] != 'none' and self.kernel["ProblemType"]["Gradient"] and ((self.kernel["GlobalSplitU"] == 1 or self.kernel["GlobalSplitU"] == -1) or self.kernel["StreamK"] > 0):
1069 if isActivationInsertAfter:
1070 assert 0, "Gradient does not support isActivationInsertAfter."
1071 for vi in range(0, self.gwvw):
1072 sumIdxV = self.ss.elementSumIdx[elementIdx] + vi
1073 dataEV = dataE + vi
1074 if self.kernel["ProblemType"]["ComputeDataType"].isSingle():
1075 vgprIdx = sumIdxV - self.parentWriter.states.c.startVgprValu
1076 # Generate single f32 code if edge is detected.
1077 if ((vi + 1) == self.gwvw) and ((self.gwvw % 2) == 1):
1078 activationModule.add(VMulF32(dst=vgpr("ValuC+%d"%vgprIdx), src0=vgpr("ValuC+%d"%vgprIdx), src1=vgpr(dataEV), comment="C *= GradAct"))
1079 # Original packed route
1080 elif vi%2 == 1:
1081 assert (self.gwvw % 2 == 0)
1082 else:
1083 activationModule.add(VMulPKF32(dst=vgpr("ValuC+%d"%vgprIdx, 2), src0=vgpr("ValuC+%d"%vgprIdx, 2), src1=vgpr(dataEV, 2), comment="C *= GradAct"))
1084 else:
1085 assert 0, "Unsupported gradient type"
1086
1087 scaleDModule = Module("Empty scaleDModule")
1088 if self.kernel["ProblemType"]["UseScaleCD"] and ((self.kernel["GlobalSplitU"] == 1 or self.kernel["GlobalSplitU"] == -1) or self.kernel["StreamK"] > 0):
1089 for vi in range(0, self.gwvw):
1090 sumIdxV = self.ss.elementSumIdx[elementIdx] + vi
1091 if self.kernel["ProblemType"]["ComputeDataType"].isSingle():
1092 vgprIdx = sumIdxV - self.parentWriter.states.c.startVgprValu
1093 # Generate single f32 code if edge is detected.
1094 if ((vi + 1) == self.gwvw) and ((self.gwvw % 2) == 1):
1095 if self.kernel["ProblemType"]["OutputAmaxD"]:
1096 if self.edge:
1097 activationModule.add(VCmpEQU32(dst=VCC(), src0="BufferOOB", src1=(vgpr(addrCalc.addrDVgpr)), comment =""))
1098 activationModule.add(VCndMaskB32(dst=vgpr("AmaxOutB"), src0=vgpr("ValuC+%d"%vgprIdx), src1=0, src2=VCC(), comment="Check If OOB, put zero if OOB"))
1099 activationModule.add(VMaxF32(dst=vgpr("AmaxOut"), src0=vgpr("AmaxOut"), src1=vgpr("AmaxOutB", isAbs=True), comment="absmax"))
1100 else:
1101 activationModule.add(VMaxF32(dst=vgpr("AmaxOut"), src0=vgpr("AmaxOut"), src1=vgpr("ValuC+%d"%vgprIdx, isAbs=True), comment="absmax"))
1102 activationModule.add(VMulF32(dst=vgpr("ValuC+%d"%vgprIdx), src0=vgpr("ValuC+%d"%vgprIdx), src1=sgpr("ScaleD"), comment="result *= ScaleD"))
1103 # Original packed route
1104 elif vi%2 == 1:
1105 assert (self.gwvw % 2 == 0)
1106 else:
1107 activationModule.add(VMulPKF32(dst=vgpr("ValuC+%d"%vgprIdx, 2), src0=vgpr("ValuC+%d"%vgprIdx, 2), src1=sgpr("ScaleD", 2), comment="result *= ScaleD"))
1108 else:
1109 assert 0, "Unsupported scaleD type"
1110
1111
1112 # pack stores, beta and non-beta reach here:
1113 packModule = Module("Empty pack module")
1114 convertModule = Module("Empty convert module")
1115 if self.kernel["ProblemType"]["HighPrecisionAccumulate"] and (self.kernel["_GlobalAccumulation"] != 'MultipleBuffer'):
1116 if self.kernel["ActivationFuncCall"] and activationCDataType == self.kernel["ProblemType"]["DestDataType"]:
1117 destIdx = self.activationSetPCStruct.vgprActCopy
1118 else:
1119 destIdx = self.ss.elementSumIdx[elementIdx]
1120 if self.kernel["ProblemType"]["DestDataType"].isHalf():
1121 packModule = self.packdata(self.gwvw, destIdx, self.ss.elementSumIdx[elementIdx], inputPrefix="ValuC+", prefixOffset=self.parentWriter.states.c.startVgprValu)
1122 elif self.kernel["ProblemType"]["DestDataType"].isBFloat16():
1123 packModule = self.packdata(self.gwvw, destIdx, self.ss.elementSumIdx[elementIdx], bf16CVTVgprStruct=self.cvtVgprStruct,
1124 tmpS01=self.tmpS01, laneSGPRC=self.laneSGPRC, inputPrefix="ValuC+", prefixOffset=self.parentWriter.states.c.startVgprValu)
1125 elif self.kernel["ProblemType"]["DestDataType"].isAnyFloat8():
1126 packModule = self.packdata(self.gwvw, destIdx, self.ss.elementSumIdx[elementIdx], fp8CVTVgprStruct=self.cvtVgprStruct, \
1127 tmpS01=self.tmpS01, laneSGPRC=self.laneSGPRC, inputPrefix="ValuC+", prefixOffset=self.parentWriter.states.c.startVgprValu)
1128 elif self.kernel["ProblemType"]["DestDataType"].isAnyBFloat8():
1129 packModule = self.packdata(self.gwvw, destIdx, self.ss.elementSumIdx[elementIdx], bf8CVTVgprStruct=self.cvtVgprStruct, \
1130 tmpS01=self.tmpS01, laneSGPRC=self.laneSGPRC, inputPrefix="ValuC+", prefixOffset=self.parentWriter.states.c.startVgprValu)
1131 elif self.kernel["ProblemType"]["DestDataType"].isInt32():
1132 if self.kernel["ProblemType"]["ComputeDataType"].isSingle() and ((self.parentWriter.states.useBias == DataDirection.READ) or self.kernel["ActivationFuncCall"] or self.applyAlpha or self.beta):
1133 convertModule = convertData(self.gwvw, self.ss.elementSumIdx[elementIdx], cvtType=CvtType.CVT_F32_to_I32, \
1134 inputPrefix="ValuC+", prefixOffset=self.parentWriter.states.c.startVgprValu)
1135 elif self.kernel["ProblemType"]["DestDataType"].isInt8():
1136 if self.kernel["ProblemType"]["ComputeDataType"].isSingle() and ((self.parentWriter.states.useBias == DataDirection.READ) or self.kernel["ActivationFuncCall"] or self.applyAlpha or self.beta):
1137 convertModule = convertData(self.gwvw, self.ss.elementSumIdx[elementIdx], cvtType=CvtType.CVT_F32_to_I32, roundType=RoundType.ROUND_TO_NEAREST_EVEN, \
1138 inputPrefix="ValuC+", prefixOffset=self.parentWriter.states.c.startVgprValu)
1139 packModule = self.packdata(self.gwvw, destIdx, self.ss.elementSumIdx[elementIdx], self.cvtVgprStruct, self.tmpS01,
1140 SaturateTypeInt8=SaturateTypeInt8, inputPrefix="ValuC+", prefixOffset=self.parentWriter.states.c.startVgprValu)
1141
1142 if self.parentWriter.states.asmCaps["HasWMMA_V1"] and self.kernel["EnableMatrixInstruction"] and self.kernel["ProblemType"]["DestDataType"].isHalf() and (not self.kernel["ProblemType"]["HighPrecisionAccumulate"]):
1143 for vi in range(0, self.gwvw):
1144 sumIdxV = self.ss.elementSumIdx[elementIdx] + vi
1145 if vi%2 == 1:
1146 formatVgpr = formatting(sumIdxV, "ValuC+", self.parentWriter.states.c.startVgprValu)
1147 d = self.ss.elementSumIdx[elementIdx] + vi//2
1148 dVgpr = formatting(d, "ValuC+", self.parentWriter.states.c.startVgprValu)
1149 packModule.add(VPackF16toB32(dst=vgpr(dVgpr), src0=vgpr(formatting(sumIdxV-1, "ValuC+", self.parentWriter.states.c.startVgprValu)), src1=vgpr(formatVgpr), \
1150 comment="Pack with neighbor"))
1151
1152 if self.kernel["ExpertSchedulingMode"] > 0:
1153 packModule.add(SWaitAlu(va_vdst=0, comment="wait for writes to complete"))
1154
1155 biasReductionModule = Module("biasReductionModule")
1156 if self.storeBiasD == 1:
1157 vgprIdx = self.ss.elementSumIdx[elementIdx] - self.parentWriter.states.c.startVgprValu
1158 biasReductionModule.add(self.parentWriter.addStore(self.kernel, self.ss, 'Bias', addrCalc, "ValuC+%d"%vgprIdx, self.tmpS01, self.edge, comment="store Bias"))
1159
1160 if isActivationInsertAfter:
1161 module.add(convertModule)
1162 module.add(packModule)
1163 module.add(gradientCvtModule)
1164 module.add(activationModule)
1165 else:
1166 module.add(gradientCvtModule)
1167 module.add(activationModule)
1168 module.add(scaleDModule)
1169 module.add(biasReductionModule)
1170 module.add(convertModule)
1171 module.add(packModule)
1172
1173 if not self.kernel["StoreRemapVectorWidth"]:
1174 if self.kernel["_GlobalAccumulation"] == "MultipleBufferSingleKernel":#GSUGSU
1175 tmpStoreCode = self.parentWriter.addStore(self.kernel, self.ss, 'TD', addrCalc, sumIdx, self.tmpS01, self.edge, comment="store TD not StoreRemapVectorWidth")
1176 else:
1177 tmpStoreCode = self.parentWriter.addStore(self.kernel, self.ss, 'D', addrCalc, sumIdx, self.tmpS01, self.edge, comment="store D")
1178 if self.kernel["GroupLoadStore"]:
1179 storeCode.add(tmpStoreCode)
1180 else:
1181 module.add(tmpStoreCode)
1182
1183 self.storesIssued += 1
1184 if (self.kernel["ProblemType"]["UseE"] and not self.kernel["ProblemType"]["Gradient"]) and ((self.kernel["GlobalSplitU"] == 1 or self.kernel["GlobalSplitU"] == -1) or self.kernel["StreamK"] > 0):
1185 self.storesIssued += 1
1186 if self.storeBiasD == 1:
1187 self.storesIssued += 1
1188
1189 else:
1190 if not self.kernel["_GlobalAccumulation"] == "MultipleBufferSingleKernel":#GSUGSU
1191 rpe = self.parentWriter.states.bpeCinternal // self.parentWriter.states.bpr
1192 module.add(self.parentWriter.storeRemapAddLocalWrite(self.kernel, self.ss, addrCalc, sumIdx*rpe))
1193 # Column Block Shape has been written to LDS
1194 # Now read back and write out to global memory
1195 else:
1196 tmpStoreCode = self.parentWriter.addStore(self.kernel, self.ss, 'TD', addrCalc, sumIdx, self.tmpS01, self.edge, comment="store TD StoreRemapVectorWidth")
1197
1198 if self.kernel["GroupLoadStore"]:
1199 storeCode.add(tmpStoreCode)
1200
1201 module.add(tmpStoreCode)
1202
1203 self.storesIssued += 1
1204 if (self.kernel["ProblemType"]["UseE"] and not self.kernel["ProblemType"]["Gradient"]) and ((self.kernel["GlobalSplitU"] == 1 or self.kernel["GlobalSplitU"] == -1) or self.kernel["StreamK"] > 0):
1205 self.storesIssued += 1
1206 if self.storeBiasD == 1:
1207 self.storesIssued += 1
1208
1209 module.add(storeCode)
1210
1211 if self.parentWriter.db["CheckStoreC"]>=0:
1212 useBuffer = self.kernel["BufferStore"]
1213 # Note - CheckStoreC won't work for EDGE store cases since they load 0 for OOB, would need more sophisticated check
1214 # Note - TODO- CheckStoreC also won't work for StoreRemap
1215 module.add(SWaitCnt(vscnt=0, comment="CheckStoreC, wait for stores to complete"))
1216 for elementIdx in range(0, len(self.batchElements)):
1217 addr = self.ss.elementAddr[elementIdx].addrDVgpr
1218 sumIdx = self.ss.elementSumIdx[elementIdx]
1219
1220 bps = self.kernel["ProblemType"]["DestDataType"].numBytes() * self.gwvw
1221 if self.kernel["BufferStore"]:
1222 addr0 = vgpr(addr)
1223 addr1 = sgpr("SrdC", 4)
1224 else:
1225 addr0 = vgpr(addr,2)
1226 addr1 = ""
1227
1228 if self.kernel["ProblemType"]["DestDataType"].isHalf() or self.kernel["ProblemType"]["DestDataType"].isBFloat16():
1229 if not self.kernel["ProblemType"]["HighPrecisionAccumulate"]:
1230 module.add(self.parentWriter.chooseGlobalRead(useBuffer, bps, sumIdx//2, \
1231 addr0, addr1, soffset=0, offset=0, hi16=sumIdx%2))
1232 else:
1233 module.add(self.parentWriter.chooseGlobalRead(useBuffer, bps, sumIdx, \
1234 addr0, addr1, soffset=0, offset=0, hi16=0))
1235 elif self.kernel["ProblemType"]["DestDataType"].isInt32() or self.kernel["ProblemType"]["DestDataType"].isSingle():
1236 module.add(self.parentWriter.chooseGlobalRead(useBuffer, bps, sumIdx, \
1237 addr0, addr1, soffset=0, offset=0))
1238 elif self.kernel["ProblemType"]["DestDataType"].isDouble() or self.kernel["ProblemType"]["DestDataType"].isSingleComplex() :
1239 module.add(self.parentWriter.chooseGlobalRead(useBuffer, bps, sumIdx*2, \
1240 addr0, addr1, soffset=0, offset=0))
1241 elif self.kernel["ProblemType"]["DestDataType"].isDoubleComplex():
1242 module.add(self.parentWriter.chooseGlobalRead(useBuffer, bps, sumIdx*4, \
1243 addr0, addr1, soffset=0, offset=0))
1244 module.add(SWaitCnt(vscnt=0, comment="CheckStoreC, wait for stores to complete"))
1245 # Add checks for expected values:
1246 module.add(SMovB32(sgpr(self.tmpS01), self.parentWriter.db["CheckStoreC"], "expected value"))
1247 for elementIdx in range(0, len(self.batchElements)):
1248 sumIdx = self.ss.elementSumIdx[elementIdx]
1249 # Need to fix for other types:
1250 assert (self.kernel["ProblemType"]["DestDataType"].isSingle() or self.kernel["ProblemType"]["DestDataType"].isInt32())
1251 module.add(self.parentWriter.getCmpAssert(self.parentWriter.asmAssert.eq, vgpr(sumIdx), sgpr(self.tmpS01)))
1252
1253
1254 if self.edge and (self.atomic or not self.kernel["BufferStore"]):
1255 # subsequent batch must start with full exec mask
1256 # BufferStore doesn't need exec since it used buffer range checking when
1257 # possible
1258 module.add(self.getEdgeMovInstType()(EXEC(), -1, "full mask -> exec"))
1259
1260 if self.parentWriter.db["ConservativeWaitCnt"] & 0x40:
1261 module.add(SBarrier("debug"))
1262 module.add(SWaitCnt(vscnt=0, comment="ConservativeWaitCnt"))
1263 module.add(SBarrier("debug"))
1264
1265 def _emitAtomicAdd(self, module: Module):
1266 ########################################
1267 # first attempt write
1268 module.addComment1("issue first atomic writes")
1269 for elementIdx in range(len(self.batchElements)):
1270 addrCalc = self.ss.elementAddr[elementIdx]
1271 mask = self.ss.elementMask[elementIdx]
1272
1273 # apply in-bounds exec mask
1274 if self.edge:
1275 module.add(self.getEdgeMovInstType()(EXEC(), sgpr(mask, self.laneSGPRC), "sgprs -> exec (before atomic)"))
1276
1277 for avi in range(0, self.gwvw // self.atomicW):
1278 sumIdxV = self.ss.elementSumIdx[elementIdx] + avi
1279 newSumIdxV = sumIdxV - self.parentWriter.states.c.startVgprValu
1280 if self.parentWriter.do["GlobalWrite"]:
1281 if self.kernel["BufferStore"]:
1282 module.add(BufferAtomicAddF32(vgpr("ValuC+%u"%newSumIdxV), \
1283 vgpr(addrCalc.addrDVgpr,1), \
1284 sgpr("SrdD", 4), \
1285 0,
1286 MUBUFModifiers(offen=True, offset12=addrCalc.globalOffset),
1287 "attempt write avi=%u" % (avi)))
1288 else:
1289 pass # TODO:
1290
1291 if self.edge:
1292 module.add(self.getEdgeMovInstType()(EXEC(), -1, "full mask -> exec"))
1293
1294 def _emitCasAdd(self, module: Module):
1295 # TODO for atomic GWVW:
1296 # - Use vi to compute addresses, sumIdx.
1297 # - Need a solution for the mask. Can move to all buffer or can fix?
1298 element = self.batchElements[0]
1299 d1 = element[0]
1300 d0 = element[1]
1301 vc1 = element[2]
1302 vc0 = element[3]
1303 labels = self.parentWriter.labels
1304 labelString = "Global_Write%s%s_%u_%u_%u_%u" % ("_Beta" if self.beta else "", "_Edge" if self.edge else "", vc0, vc1, d0, d1 )
1305 labelComment = "Global_Write (Beta) (Edge) vc0 vc1 d0 d1"
1306 label = Label(labels.getName(labelString), labelComment)
1307 labelString += "_EarlyExit"
1308 labelAfterAtomicLoop = Label(labels.getName(labelString), labelComment)
1309
1310 ########################################
1311 # wait for batched load
1312 # TODO - we are always atomic here?
1313 module.add(SWaitCnt(vlcnt=0, vscnt=0, comment="wait C (atomic)"))
1314 ########################################
1315 # first attempt write
1316 module.addComment1("issue first atomic writes")
1317 for elementIdx, element in enumerate(self.batchElements):
1318 addrCalc = self.ss.elementAddr[elementIdx]
1319 mask = self.ss.elementMask[elementIdx]
1320
1321 # apply in-bounds exec mask
1322 if self.edge:
1323 module.add(self.getEdgeMovInstType()(EXEC(), sgpr(mask, self.parentWriter.states.laneSGPRCount), "sgprs -> exec (before atomic)"))
1324
1325 for avi in range(0, self.gwvw//self.atomicW):
1326 dataV = self.ss.elementData[elementIdx] + int(avi*self.ss.cfg.numVgprsPerDataPerVI)
1327 sumIdxV = self.ss.elementSumIdx[elementIdx] + avi
1328 ## number of src[s]/dst[s] register for DGEMM / SGEMM HGEMM
1329 vgprCnt = 2 if self.kernel["ProblemType"]["DestDataType"].isDouble() else 1
1330 if self.kernel["ProblemType"]["DestDataType"].numRegisters() < 1 and not self.kernel["_GlobalAccumulation"]:
1331 sumIdxV //= 2
1332 if self.kernel["ProblemType"]["DestDataType"].isDouble(): sumIdxV = sumIdxV * 2
1333 newSumIdxV = sumIdxV - self.parentWriter.states.c.startVgprValu
1334 bpm = self.parentWriter.states.bpeCexternal * self.atomicW
1335 # Calculate vgpr Index for 32-bit/64-bit instruction
1336 # DGEMM use SRCS[2] register
1337 vgprIdx = 1*(bpm//4)
1338 # for atomic, data[1] = original c, data[0] = new c
1339 module.add(self._chooseAddForAtomic(self.kernel, \
1340 vgpr(dataV+0,vgprCnt), vgpr(dataV+1*vgprIdx,vgprCnt), vgpr("ValuC+%u"%newSumIdxV,vgprCnt), \
1341 "desired value avi=%u"%avi))
1342
1343 # attempt write
1344 atomicDestVgpr = dataV if self.kernel["BufferStore"] else dataV+2
1345 if self.parentWriter.do["GlobalWrite"]:
1346 if self.kernel["BufferStore"]:
1347 # use cmpswap_x2 for DGEMM in CAS loop
1348 if self.kernel["ProblemType"]["DestDataType"].isDouble():
1349 module.add(BufferAtomicCmpswapB64(vgpr(dataV,4), \
1350 vgpr(addrCalc.addrDVgpr,1), \
1351 sgpr("SrdD", 4), \
1352 0,
1353 MUBUFModifiers(offen=True, offset12=addrCalc.globalOffset, glc=True),
1354 "attempt write avi=%u"%(avi)))
1355 else:
1356 # use cmpswap for SGEMM in CAS loop
1357 module.add(BufferAtomicCmpswapB32(vgpr(dataV,2), \
1358 vgpr(addrCalc.addrDVgpr,1), \
1359 sgpr("SrdD", 4), \
1360 0, \
1361 MUBUFModifiers(offen=True, offset12=addrCalc.globalOffset, glc=True), \
1362 "attempt write avi=%u"%(avi)))
1363 else:
1364 module.add(FlatAtomicCmpswapB32(vgpr(atomicDestVgpr), \
1365 vgpr(addrCalc.addrDVgpr,2), \
1366 vgpr(dataV,2),
1367 FLATModifiers(glc=True),
1368 "attempt write"))
1369 else:
1370 # Fake successful CAS swap
1371 module.add(VMovB32(vgpr(atomicDestVgpr), vgpr(dataV+1), "Fake successful CAS" ))
1372
1373 ########################################
1374 # wait for first attempt write
1375 module.add(SWaitCnt(vlcnt=0, vscnt=0, comment="wait for atomic writes"))
1376 ########################################
1377 # check first attempt
1378 module.addComment1("check success of writes, update masks")
1379 for elementIdx, element in enumerate(self.batchElements):
1380 mask = self.ss.elementMask[elementIdx]
1381
1382 # calculate new masks
1383 if self.edge:
1384 module.add(self.getEdgeMovInstType()(EXEC(), sgpr(mask, self.laneSGPRC), "sgprs -> exec"))
1385 for avi in range(0, self.gwvw // self.atomicW):
1386 dataV = self.ss.elementData[elementIdx] + int(avi * self.ss.cfg.numVgprsPerDataPerVI)
1387 atomicDestVgpr = dataV if self.kernel["BufferStore"] else dataV+2
1388 # need to apply element mask before comparison
1389 # so that all valid lanes are doing the cmp
1390 if avi == 0:
1391 # use u64 for DGEMM
1392 if self.kernel["ProblemType"]["DestDataType"].isDouble():
1393 module.add(VCmpNeU64(sgpr(self.tmpS01, self.laneSGPRC), vgpr(atomicDestVgpr,2), \
1394 vgpr(dataV+2,2), comment="c read during atomic == c read during prior load (avi=%u, first)"%avi))
1395 else:
1396 module.add(VCmpNeU32(sgpr(self.tmpS01, self.laneSGPRC), vgpr(atomicDestVgpr), \
1397 vgpr(dataV+1), comment="c read during atomic == c read during prior load (avi=%u, first)"%avi))
1398 else:
1399 if self.kernel["ProblemType"]["DestDataType"].isDouble():
1400 module.add(VCmpNeU64(sgpr(self.tmpS23, self.laneSGPRC), vgpr(atomicDestVgpr,2), \
1401 vgpr(dataV+2,2), comment="c read during atomic != c read during prior load"))
1402 else:
1403 module.add(VCmpNeU32(sgpr(self.tmpS23, self.laneSGPRC), vgpr(atomicDestVgpr), \
1404 vgpr(dataV+1), comment="c read during atomic == c read during prior load (avi=%u)"%avi))
1405 module.add(self.getEdgeOrInstType()(sgpr(self.tmpS01, self.laneSGPRC), \
1406 sgpr(self.tmpS01, self.laneSGPRC), sgpr(self.tmpS23, self.laneSGPRC), "combine with tmp mask"))
1407
1408 module.add(self.getEdgeAndInstType()(sgpr(mask, self.laneSGPRC), sgpr(self.tmpS01, self.laneSGPRC), sgpr(mask,self.laneSGPRC), "inBounds & must try again"))
1409
1410 else:
1411 for avi in range(0, self.gwvw//self.atomicW):
1412 dataV = self.ss.elementData[elementIdx] + int(avi*self.ss.cfg.numVgprsPerDataPerVI)
1413 atomicDestVgpr = dataV if self.kernel["BufferStore"] else dataV+2
1414 if self.kernel["ProblemType"]["DestDataType"].isDouble():
1415 module.add(VCmpNeU64(sgpr(mask, self.laneSGPRC), vgpr(atomicDestVgpr,2), \
1416 vgpr(dataV+2,2), comment="c read during atomic != c read during prior load"))
1417 else:
1418 module.add(VCmpNeU32(sgpr(mask, self.laneSGPRC), vgpr(atomicDestVgpr), \
1419 vgpr(dataV+1), comment="c read during atomic != c read during prior load"))
1420
1421 # or masks together to check early exit
1422 module.addComment1("or masks to check for exit")
1423 module.add(self.getEdgeMovInstType()(sgpr(self.tmpS01, self.laneSGPRC), 0, "empty mask"))
1424 for elementIdx in range(0, len(self.batchElements)):
1425 mask = self.ss.elementMask[elementIdx]
1426 module.add(self.getEdgeOrInstType()(sgpr(self.tmpS01, self.laneSGPRC), sgpr(mask, self.laneSGPRC), sgpr(self.tmpS01, self.laneSGPRC), "or to add threads"))
1427 module.add(self.getSOrSaveExecType()(sgpr(self.tmpS23,self.laneSGPRC), sgpr(self.tmpS01,self.laneSGPRC), "apply combined mask"))
1428 module.add(SCBranchExecZ(labelAfterAtomicLoop.getLabelName(), "if exec is zero skip loop"))
1429
1430 # begin atomic loop
1431 module.addComment1("atomic CAS loop")
1432 module.add(label)
1433
1434 module.addComment1("apply updated masks and issue writes again")
1435 for elementIdx in range(0, len(self.batchElements)):
1436 addrCalc = self.ss.elementAddr[elementIdx]
1437 addr = addrCalc.addrDVgpr
1438 mask = self.ss.elementMask[elementIdx]
1439 vgprCnt = 2 if self.kernel["ProblemType"]["DestDataType"].isDouble() else 1 # number of registers for f32/f64
1440 bpm = self.parentWriter.states.bpeCexternal * self.atomicW
1441 vgprIdx = 1*(bpm//4) # index register
1442
1443 for avi in range(0, self.gwvw//self.atomicW):
1444 dataV = self.ss.elementData[elementIdx] + int(avi*self.ss.cfg.numVgprsPerDataPerVI)
1445 atomicDestVgpr = dataV if self.kernel["BufferStore"] else dataV+2
1446 sumIdxV = self.ss.elementSumIdx[elementIdx] + avi
1447 if self.kernel["ProblemType"]["DestDataType"].numRegisters() < 1 and not self.kernel["_GlobalAccumulation"]:
1448 sumIdxV //= 2
1449 if self.kernel["ProblemType"]["DestDataType"].isDouble():
1450 sumIdxV = sumIdxV * 2
1451 newSumIdxV = sumIdxV - self.parentWriter.states.c.startVgprValu
1452
1453 # apply mask for element
1454 module.add(self.getEdgeMovInstType()(EXEC(), sgpr(mask,self.laneSGPRC), "must try again"))
1455 if self.kernel["ProblemType"]["DestDataType"].isDouble():
1456 #64-bit C val move by 2 32-bit instructions
1457 module.add(VMovB32(vgpr(dataV+2), vgpr(atomicDestVgpr), "dataV+2 = tmp (new original C)" ))
1458 module.add(VMovB32(vgpr(dataV+3), vgpr(atomicDestVgpr+1), "dataV+3 = tmp (new original C)" ))
1459 else:
1460 module.add(VMovB32(vgpr(dataV+1), vgpr(atomicDestVgpr), "dataV+1 = tmp (new original C)" ))
1461 module.add(self._chooseAddForAtomic(self.kernel, \
1462 vgpr(dataV+0,vgprCnt), vgpr(dataV+1*vgprIdx,vgprCnt), vgpr("ValuC+%u"%newSumIdxV,vgprCnt), \
1463 "newC = rC + originalC"))
1464 if self.parentWriter.do["GlobalWrite"]:
1465 if self.kernel["BufferStore"]:
1466 # Using no-ret version here?
1467 # cmpswap_x2 for DGEMM
1468 if self.kernel["ProblemType"]["DestDataType"].isDouble():
1469 module.add(BufferAtomicCmpswapB64(vgpr(dataV,4), \
1470 vgpr(addr,1), \
1471 sgpr("SrdD", 4), \
1472 0,
1473 MUBUFModifiers(offen=True, offset12=addrCalc.globalOffset, glc=True,),
1474 "try again"))
1475 else:
1476 module.add(BufferAtomicCmpswapB32(
1477 vgpr(dataV,2), \
1478 vgpr(addr,1), \
1479 sgpr("SrdD", 4), \
1480 0,
1481 MUBUFModifiers(offen=True, offset12=addrCalc.globalOffset, glc=True),
1482 "try again"))
1483 else:
1484 module.add(FlatAtomicCmpswapB32(vgpr(atomicDestVgpr), \
1485 vgpr(addr,2), \
1486 vgpr(dataV,2), \
1487 FLATModifiers(glc=True), \
1488 "try again"))
1489
1490 # wait for batched write
1491 module.add(SWaitCnt(vlcnt=0, vscnt=0, comment="wait for atomic writes"))
1492 # check batched write success
1493 module.addComment1("apply masks and check for success")
1494 for elementIdx in range(0, len(self.batchElements)):
1495 data = self.ss.elementData[elementIdx]
1496 mask = self.ss.elementMask[elementIdx]
1497 for avi in range(0, self.gwvw//self.atomicW):
1498 dataV = self.ss.elementData[elementIdx] + int(avi*self.ss.cfg.numVgprsPerDataPerVI)
1499 atomicDestVgpr = dataV if self.kernel["BufferStore"] else dataV+2
1500
1501 # apply mask for element
1502 module.add(self.getEdgeMovInstType()(EXEC(), sgpr(mask,self.laneSGPRC), "must try again"))
1503
1504 # compare success
1505 if self.kernel["ProblemType"]["DestDataType"].isDouble():
1506 module.add(VCmpNeU64(sgpr(self.tmpS01,self.laneSGPRC), vgpr(data+2,2), vgpr(atomicDestVgpr,2), \
1507 comment="c read during atomic != c read during prior load"))
1508 else:
1509 module.add(VCmpNeU32(sgpr(self.tmpS01,self.laneSGPRC), vgpr(data+1), vgpr(atomicDestVgpr), \
1510 comment="c read during atomic == c read during prior load"))
1511 # update element mask
1512 module.add(self.getEdgeAndInstType()(sgpr(mask,self.laneSGPRC), sgpr(self.tmpS01,self.laneSGPRC), sgpr(mask,self.laneSGPRC), "inBounds & must try again"))
1513
1514 # or masks together
1515 module.addComment1("or masks to check for exit")
1516 module.add(self.getEdgeMovInstType()(sgpr(self.tmpS01,self.laneSGPRC), 0, "empty mask"))
1517 for elementIdx in range(0, len(self.batchElements)):
1518 mask = self.ss.elementMask[elementIdx]
1519 module.add(self.getEdgeOrInstType()(sgpr(self.tmpS01,self.laneSGPRC), sgpr(mask,self.laneSGPRC), sgpr(self.tmpS01,self.laneSGPRC), "or to add threads"))
1520
1521 # apply combined masks and exit
1522 module.add(self.getSOrSaveExecType()(sgpr(self.tmpS23, self.laneSGPRC), sgpr(self.tmpS01,self.laneSGPRC), "apply combined mask"))
1523 module.add(SCBranchExecNZ(label.getLabelName(), "try again if not complete"))
1524 module.add(labelAfterAtomicLoop)
1525 module.add(self.getEdgeMovInstType()(EXEC(), -1, "full mask -> exec"))
1526
1527 def _checkAtomicPreconditions(self) -> bool:
1528 if self.atomic:
1529 # all kinds of code relies on this assumption:
1530 if self.atomicW > self.gwvw:
1531 return False
1532
1533 if (self.kernel["ProblemType"]["DataType"].isHalf() or self.kernel["ProblemType"]["DataType"].isBFloat16()) \
1534 and not self.kernel["_GlobalAccumulation"]:
1535 return self.atomicW >= 2
1536 return True
1537
1538 def _storeSyncOpt(self, module: Module):
1539 module.add(SSleep(self.kernel["StoreSyncOpt"] - 1, "optimization: sync and wait"))
1540 module.add(SBarrier())
1541
1542 def _applyAlpha(self, kernel, gwvw, elementSumIdx, elementIdx, tmpS01, usePK=False):
1543 module = Module("applyAlpha")
1544
1545 if kernel["_GlobalAccumulation"] == 'MultipleBuffer':
1546 return module
1547
1548 if self.parentWriter.do["ApplyAlpha"]:
1549 for vi in range(0, gwvw):
1550 sumIdxV = elementSumIdx[elementIdx] + vi
1551
1552 if kernel["ProblemType"]["ComputeDataType"].isHalf() and not kernel["ProblemType"]["HighPrecisionAccumulate"]:
1553 # (h,h,h,h,h,h), internal alpha is f16 (2-16bits)
1554 if sumIdxV%2:
1555 newSumIdx = sumIdxV // 2 - self.parentWriter.states.c.startVgprValu
1556 module.add(VMulPKF16(dst=vgpr("ValuC+%u"%(newSumIdx)), src0=sgpr("Alpha"), src1=vgpr("ValuC+%u"%(newSumIdx)), comment="*= alpha sumIdx=%u vi=%u"%(elementSumIdx[elementIdx], vi)))
1557
1558 # Int8 (TODO- Int8x4 not checked, but should be OK)
1559 elif kernel["ProblemType"]["ComputeDataType"].isInt32():
1560 newSumIdx = sumIdxV - self.parentWriter.states.c.startVgprValu
1561 # below assume we use v_mul_lo_u32. Could also use v_mul_i32_i24.
1562 # module.add(VMulI32I24(dst=vgpr("ValuC+%u"%newSumIdx), src0=sgpr("Alpha"), src1=vgpr("ValuC+%u"%newSumIdx), comment="*= alpha" )_
1563 module.add(VMulLOU32(dst=vgpr("ValuC+%u"%newSumIdx), src0=sgpr("Alpha"), src1=vgpr("ValuC+%u"%newSumIdx), comment="*= alpha" ))
1564 if usePK:
1565 module.add(VMulLOU32(dst=vgpr("ValuC+%u"%(newSumIdx+1)), src0=sgpr("Alpha"), src1=vgpr("ValuC+%u"%(newSumIdx+1)), comment="*= alpha" ))
1566 if self.parentWriter.db["ForceExpectedValue"]:
1567 module.add(VMovB32(dst=vgpr("ValuC+%u"%newSumIdx), src=self.parentWriter.db["ValueCExpectedValue"], comment="force expected value" ))
1568 if self.parentWriter.db["CheckValueC"]:
1569 module.add(SMovB32(dst=sgpr(tmpS01), src=self.parentWriter.db["ValueCExpectedValue"], comment="Move expected value"))
1570 module.add(self.parentWriter.getCmpAssert(self.parentWriter.asmAssert.eq, vgpr("ValuC+%u"%newSumIdx), sgpr(tmpS01)))
1571
1572 # sgemm, HPA-bfgemm(b,b,b,b,s,s), and HPA-hgemm(h,h,h,h,s,s)
1573 # (h,h,h,h,h,h) + HPA (will be converted to (h,h,h,h,s,s)), internal alpha is single
1574 elif kernel["ProblemType"]["ComputeDataType"].isSingle() or (kernel["ProblemType"]["ComputeDataType"].isHalf() and kernel["ProblemType"]["HighPrecisionAccumulate"]):
1575
1576 if kernel["ProblemType"]["DataType"].isInt8() and kernel["ProblemType"]["HighPrecisionAccumulate"]:
1577 if usePK or gwvw > 1:
1578 if vi % 2 == 0:
1579 module.add(VCvtI32toF32(dst=vgpr("ValuC+%u"%sumIdxV), src=vgpr("ValuC+%u"%sumIdxV), comment="convert to fp32" ))
1580 module.add(VCvtI32toF32(dst=vgpr("ValuC+%u"%(sumIdxV+1)), src=vgpr("ValuC+%u"%(sumIdxV+1)), comment="convert to fp32" ))
1581 else:
1582 module.add(VCvtI32toF32(dst=vgpr("ValuC+%u"%sumIdxV), src=vgpr("ValuC+%u"%sumIdxV), comment="convert to fp32" ))
1583
1584 newSumIdx = sumIdxV - self.parentWriter.states.c.startVgprValu
1585 # Use pk if possible
1586 if usePK or gwvw > 1:
1587 if newSumIdx % 2 == 0:
1588 module.add(VMulPKF32(dst=vgpr("ValuC+%u"%newSumIdx, 2), src0=sgpr("Alpha",2), src1=vgpr("ValuC+%u"%newSumIdx,2), vop3=VOP3PModifiers(op_sel_hi=[0,1,1]), comment="*= alpha (pk)"))
1589 else:
1590 module.add(VMulF32(dst=vgpr("ValuC+%u"%newSumIdx), src0=sgpr("Alpha"), src1=vgpr("ValuC+%u"%newSumIdx), comment="*= alpha" ))
1591 if self.parentWriter.db["ForceExpectedValue"]:
1592 module.add(VMovB32(dst=vgpr("ValuC+%u"%newSumIdx), src=self.parentWriter.db["ValueCExpectedValue"], comment="force expected value" ))
1593 if self.parentWriter.db["ForceVSerial"]:
1594 module.add(VMovB32(dst=vgpr("ValuC+%u"%newSumIdx), src=vgpr("Serial"), comment="force expected value to serial" ))
1595 if self.parentWriter.db["CheckValueC"]:
1596 module.add(SMovB32(dst=sgpr(tmpS01), src=self.parentWriter.db["ValueCExpectedValue"], comment="Move expected value"))
1597 module.add(self.parentWriter.getCmpAssert(self.parentWriter.asmAssert.eq, vgpr("ValuC+%u"%newSumIdx), sgpr(tmpS01)))
1598
1599 # dgemm
1600 elif kernel["ProblemType"]["ComputeDataType"].isDouble():
1601 newSumIdx = sumIdxV * 2 - self.parentWriter.states.c.startVgprValu
1602 module.add(VMulF64(dst=vgpr("ValuC+%u"%(newSumIdx),2), src0=sgpr("Alpha",2), src1=vgpr("ValuC+%u"%(newSumIdx),2), comment="*= alpha"))
1603 if usePK:
1604 module.add(VMulF64(dst=vgpr("ValuC+%u"%(newSumIdx+2),2), src0=sgpr("Alpha",2), src1=vgpr("ValuC+%u"%(newSumIdx+2),2), comment="*= alpha"))
1605
1606 # single precision complex
1607 elif kernel["ProblemType"]["ComputeDataType"].isSingleComplex():
1608 newSumIdx = sumIdxV * 2 - self.parentWriter.states.c.startVgprValu
1609 tmpVgpr = self.parentWriter.vgprPool.checkOut(1)
1610 module.add(VMovB32(dst=vgpr(tmpVgpr), src=vgpr("ValuC+%u"%(newSumIdx)), comment="store Cr"))
1611 module.add(VMulF32(dst=vgpr("ValuC+%u"%(newSumIdx)), src0=sgpr("Alpha"), src1=vgpr("ValuC+%u"%(newSumIdx)), comment="*= alpha ( Cr = Ar * Cr)"))
1612 module.add(VMacF32(dst=vgpr("ValuC+%u"%(newSumIdx)), src0=(sgpr("Alpha+1").getMinus()), src1=vgpr("ValuC+%u"%(newSumIdx+1)), comment="*= alpha ( Cr += -Ai * Ci )"))
1613 module.add(VMulF32(dst=vgpr("ValuC+%u"%(newSumIdx+1)), src0=sgpr("Alpha"), src1=vgpr("ValuC+%u"%(newSumIdx+1)), comment="*= alpha ( Ci = Ar * Ci)"))
1614 module.add(VMacF32(dst=vgpr("ValuC+%u"%(newSumIdx+1)), src0=sgpr("Alpha+1"), src1=vgpr(tmpVgpr), comment="*= alpha ( Ci += Ai * Cr_backup )"))
1615 self.parentWriter.vgprPool.checkIn(tmpVgpr)
1616
1617 # double precision complex
1618 elif kernel["ProblemType"]["ComputeDataType"].isDoubleComplex():
1619 newSumIdx = sumIdxV * 4 - self.parentWriter.states.c.startVgprValu
1620 vtmp1 = self.parentWriter.vgprPool.checkOutAligned(2, 2)
1621 vtmp2 = self.parentWriter.vgprPool.checkOutAligned(2, 2)
1622 # tmp1 = a.real * b.real
1623 module.add(VMulF64(dst=vgpr(vtmp1,2), src0=sgpr("Alpha+0",2), src1=vgpr("ValuC+%u"%(newSumIdx+0),2)))
1624 # tmp2 = a.imag * b.real
1625 module.add(VMulF64(dst=vgpr(vtmp2,2), src0=sgpr("Alpha+2",2), src1=vgpr("ValuC+%u"%(newSumIdx+0),2)))
1626 # c.real = a.real * b.real - a.imag * b.imag = tmp1 - a.imag * b.imag
1627 module.add(VFmaF64(dst=vgpr("ValuC+%u"%(newSumIdx+0),2), src0=sgpr("Alpha+2",2), src1=vgpr("ValuC+%u"%(newSumIdx+2),2), src2=vgpr(vtmp1,2)))
1628 # c.imag = a.real * b.imag + a.imag * b.real = a.real * b.imag + tmp2
1629 module.add(VFmaF64(dst=vgpr("ValuC+%u"%(newSumIdx+2),2), src0=sgpr("Alpha+0",2), src1=vgpr("ValuC+%u"%(newSumIdx+2),2), src2=vgpr(vtmp2,2)))
1630 self.parentWriter.vgprPool.checkIn(vtmp1)
1631 self.parentWriter.vgprPool.checkIn(vtmp2)
1632 return module
1633
1634 def _addSumAlphaWithCBeta(self, kernel, ss, gwvw, elementIdx, vc0, tmpVgpr, cvtVgprStruct):
1635 module = Module("addSumAlphaWithCBeta #elementIdx%u, vc0 %u"%(elementIdx, vc0))
1636 for vi in range(0, gwvw):
1637 dataV = ss.elementData[elementIdx] + int(vi*ss.cfg.numVgprsPerDataPerVI)
1638 sumIdxV = ss.elementSumIdx[elementIdx] + vi
1639 if kernel["ProblemType"]["DestDataType"].isHalf():
1640 if not kernel["ProblemType"]["HighPrecisionAccumulate"]:
1641 if self.parentWriter.states.asmCaps["HasWMMA_V1"] and kernel["EnableMatrixInstruction"]:
1642 dataV = ss.elementData[elementIdx] + int(vi / 2 * ss.cfg.numVgprsPerDataPerVI)
1643 if (vi % 2) == 0:
1644 module.add(VMulPKF16(dst=vgpr(dataV), src0=sgpr("Beta"), src1=vgpr(dataV+0), \
1645 comment="%s = C*beta ei=%u vi=%u"%(vgpr(dataV),elementIdx, vi)))
1646 else:
1647 module.add(VLShiftRightB32(dst=vgpr(dataV), shiftHex=16, src=vgpr(dataV), \
1648 comment="shift 16bit to get next half of packed ValueC"))
1649 # dataV+0 = new c = old c*beta + rC
1650 module.add(VAddPKF16(dst=vgpr("ValuC+%u"%(sumIdxV)), src0=vgpr(dataV), src1=vgpr("ValuC+%u"%(sumIdxV)), \
1651 comment="sum*alpha + C*beta"))
1652 elif sumIdxV%2==0 or (not ss.cfg.halfDataRegPerVI and gwvw==1):
1653 newSumIdxV = sumIdxV // 2 - self.parentWriter.states.c.startVgprValu
1654 # dataV+0 = new c = old c*beta
1655 module.add(VMulPKF16(dst=vgpr(dataV), src0=sgpr("Beta"), src1=vgpr(dataV+0), \
1656 comment="%s = C*beta ei=%u vi=%u"%(vgpr(dataV),elementIdx, vi)))
1657 # dataV+0 = new c = old c*beta + rC
1658 module.add(VAddPKF16(dst=vgpr("ValuC+%u"%(newSumIdxV)), src0=vgpr(dataV), src1=vgpr("ValuC+%u"%(newSumIdxV)), \
1659 comment="sum*alpha + C*beta"))
1660 else:
1661 pass # add will have been done previously
1662 else: # HPA
1663 newSumIdxV = sumIdxV - self.parentWriter.states.c.startVgprValu
1664 # dataV+0 = new c = old c*beta + rC
1665 # src0 = beta = f32 = opsel 00
1666 # src1 = dataV = f16.lo = opsel 10 or 11 depending on even/odd
1667 # src2 = sumIdxV = f32 = opsel 00
1668 dataCExternal = ss.elementData[elementIdx] + vi//2
1669 hi16 = (vi + gwvw*vc0) % 2
1670 module.add(self.parentWriter.states.mixinst(dst=vgpr("ValuC+%u"%newSumIdxV), src0=sgpr("Beta"), \
1671 src1=vgpr(dataCExternal), src2=vgpr("ValuC+%u"%newSumIdxV), \
1672 vop3=VOP3PModifiers(op_sel=[0,hi16,0], op_sel_hi=[0,1,0]),
1673 comment="//C*=beta"))
1674
1675 elif kernel["ProblemType"]["DestDataType"].isBFloat16():
1676 if kernel["ProblemType"]["HighPrecisionAccumulate"]:
1677 # dataV+0 = new c = old c*beta + rC
1678 # src0 = beta = f32 = opsel 00
1679 # src1 = dataV = f16.lo = opsel 10 or 11 depending on even/odd
1680 # src2 = sumIdxV = f32 = opsel 00
1681 dataCExternal = ss.elementData[elementIdx] + vi//2
1682 module.add(VCvtBF16toFP32(dst=vgpr(tmpVgpr), src=vgpr(dataCExternal), vgprMask=vgpr(cvtVgprStruct.vgprBf16Mask), vi=(vi)))
1683 newSumIdxV = sumIdxV - self.parentWriter.states.c.startVgprValu
1684 module.add(VMacF32(dst=vgpr("ValuC+%u"%newSumIdxV), src0=vgpr(tmpVgpr), src1=sgpr("Beta"), \
1685 comment="finalSum = sum*alpha + C*beta"))
1686 elif kernel["ProblemType"]["DestDataType"].isSingle():
1687 newSumIdxV = sumIdxV - self.parentWriter.states.c.startVgprValu
1688 module.add(VMacF32(dst=vgpr("ValuC+%u"%newSumIdxV), src0=vgpr(dataV+0), src1=sgpr("Beta"), \
1689 comment="finalSum = sum*alpha + C*beta"))
1690
1691 elif kernel["ProblemType"]["DestDataType"].isInt8():
1692 if kernel["ProblemType"]["HighPrecisionAccumulate"]:
1693 if (vi%4) != 3:
1694 module.add(VMovB32(dst=vgpr(tmpVgpr+1), src=hex(vi * 8), comment="value = %u"%(vi * 8)))
1695 module.add(VBfeI32(dst=vgpr(tmpVgpr), src0=vgpr(dataV+0), src1=vgpr(tmpVgpr+1), src2=8, comment="int8 to int32"))
1696 else:
1697 module.add(VAShiftRightI32(dst=vgpr(tmpVgpr), shiftHex=24, src=vgpr(dataV+0), comment="int8 to int32"))
1698
1699 newSumIdxV = sumIdxV - self.parentWriter.states.c.startVgprValu
1700 if kernel["ProblemType"]["ComputeDataType"].isSingle():
1701 module.add(VCvtI32toF32(dst=vgpr(tmpVgpr), src=vgpr(tmpVgpr), comment="convert to fp32" ))
1702 module.add(VMacF32(dst=vgpr("ValuC+%u"%newSumIdxV), src0=vgpr(tmpVgpr), src1=sgpr("Beta"), \
1703 comment="finalSum = sum*alpha + C*beta"))
1704 else:
1705 module.add(VMulLOU32(dst=vgpr(tmpVgpr), src0=sgpr("Beta"), src1=vgpr(tmpVgpr), comment="C = C*beta"))
1706 module.add(VAddU32(dst=vgpr("ValuC+%u"%newSumIdxV), src0=vgpr(tmpVgpr), src1=vgpr("ValuC+%u"%newSumIdxV), comment="finalSum = sum*alpha + C*beta"))
1707
1708 elif kernel["ProblemType"]["DestDataType"].isInt32():
1709 newSumIdxV = sumIdxV - self.parentWriter.states.c.startVgprValu
1710 if kernel["ProblemType"]["ComputeDataType"].isSingle():
1711 module.add(VCvtI32toF32(dst=vgpr(dataV+0), src=vgpr(dataV+0), comment="convert to fp32" ))
1712 module.add(VMacF32(dst=vgpr("ValuC+%u"%newSumIdxV), src0=vgpr(dataV+0), src1=sgpr("Beta"), comment="finalSum = sum*alpha + C*beta"))
1713 else:
1714 # assume we will need to replace v_mac_f32 with v_add_u32 and s_mul_lo_i32
1715 # v_mad_i32_i24
1716 # module.add(VMadI32I24(dst=vgpr("ValuC+%u"%sumIdxV), src0=vgpr(dataV+0), src1=sgpr("Beta"), src2=vgpr("ValuC+%u"%sumIdxV), \
1717 # comment="finalSum = sum*alpha + C*beta"))
1718 module.add(VMulLOU32(dst=vgpr(dataV+0), src0=sgpr("Beta"), src1=vgpr(dataV+0), comment="C = C*beta"))
1719 module.add(VAddU32(dst=vgpr("ValuC+%u"%newSumIdxV), src0=vgpr(dataV+0), src1=vgpr("ValuC+%u"%newSumIdxV), comment="finalSum = sum*alpha + C*beta"))
1720
1721 elif kernel["ProblemType"]["DestDataType"].isDouble():
1722 newSumIdxV = sumIdxV * 2 - self.parentWriter.states.c.startVgprValu
1723 # dataV+0 = new c = old c*beta
1724 module.add(VFmaF64(dst=vgpr("ValuC+%u"%(newSumIdxV),2), src0=vgpr(dataV+0,2), src1=sgpr("Beta",2), src2=vgpr("ValuC+%u"%(newSumIdxV),2), \
1725 comment="finalSum = sum*alpha + C*beta"))
1726
1727 # single precision complex
1728 elif kernel["ProblemType"]["DestDataType"].isSingleComplex():
1729 newSumIdxV = sumIdxV * 2 - self.parentWriter.states.c.startVgprValu
1730 module.add(VMacF32(dst=vgpr("ValuC+%u"%(newSumIdxV)), src0=vgpr(dataV+0), src1=sgpr("Beta"), comment="finalSum Cr += old Cr * Br"))
1731 module.add(VMacF32(dst=vgpr("ValuC+%u"%(newSumIdxV)), src0=vgpr(dataV+1), src1=sgpr("Beta+1").getMinus(), comment="finalSum Cr += old Ci * -Bi"))
1732 module.add(VMacF32(dst=vgpr("ValuC+%u"%(newSumIdxV+1)), src0=vgpr(dataV+1), src1=sgpr("Beta"), comment="finalSum Ci += old Ci * Br"))
1733 module.add(VMacF32(dst=vgpr("ValuC+%u"%(newSumIdxV+1)), src0=vgpr(dataV+0), src1=sgpr("Beta+1"), comment="finalSum Ci += old Cr * Bi"))
1734
1735 # double precision complex
1736 elif kernel["ProblemType"]["DestDataType"].isDoubleComplex():
1737 newSumIdxV = sumIdxV * 4 - self.parentWriter.states.c.startVgprValu
1738 module.add(VFmaF64(dst=vgpr("ValuC+%u"%(newSumIdxV+0),2), src0=vgpr(dataV+0,2), src1=sgpr("Beta+0",2), src2=vgpr("ValuC+%u"%(newSumIdxV+0),2), comment="c.real += a.real * b.real"))
1739 module.add(VFmaF64(dst=vgpr("ValuC+%u"%(newSumIdxV+0),2), src0=vgpr(dataV+2,2), src1=sgpr("Beta+2",2), src2=vgpr("ValuC+%u"%(newSumIdxV+0),2), comment="c.real -= a.imag * b.imag"))
1740 module.add(VFmaF64(dst=vgpr("ValuC+%u"%(newSumIdxV+2),2), src0=vgpr(dataV+0,2), src1=sgpr("Beta+2",2), src2=vgpr("ValuC+%u"%(newSumIdxV+2),2), comment="c.imag += a.real * b.imag"))
1741 module.add(VFmaF64(dst=vgpr("ValuC+%u"%(newSumIdxV+2),2), src0=vgpr(dataV+2,2), src1=sgpr("Beta+0",2), src2=vgpr("ValuC+%u"%(newSumIdxV+2),2), comment="c.imag += a.imag * b.real"))
1742
1743 # float8 precision
1744 elif kernel["ProblemType"]["DestDataType"].isAnyFloat8():
1745 if kernel["ProblemType"]["HighPrecisionAccumulate"]:
1746 newSumIdxV = sumIdxV - self.parentWriter.states.c.startVgprValu
1747 # Generate single f32 code if edge is detected.
1748 isPK = False
1749 if ((vi + 1) == self.gwvw) and ((self.gwvw % 2) == 1):
1750 if self.parentWriter.states.archCaps["VOP3ByteSel"]:
1751 sb = 0 if self.gwvw == 1 else 1
1752 if not self.amdClangVersion.major >= 19:
1753 module.add(VCvtFP8toF32(dst=vgpr(tmpVgpr), src=vgpr(dataV), vop3=VOP3PModifiers(op_sel=[0,sb])))
1754 else:
1755 module.add(VCvtFP8toF32(dst=vgpr(tmpVgpr), src=vgpr(dataV), vop3=VOP3PModifiers(byte_sel=[sb])))
1756 else:
1757 sb = SelectBit.BYTE_0 if self.gwvw == 1 else SelectBit.BYTE_2
1758 module.add(VCvtFP8toF32(dst=vgpr(tmpVgpr), src=vgpr(dataV), sdwa=SDWAModifiers(src0_sel=sb)))
1759 # Original packed route
1760 elif vi%2 == 1:
1761 continue
1762 else:
1763 isPK = True
1764 if self.parentWriter.states.archCaps["NoSDWA"]:
1765 # Enable WORD_0 of 2-nd VGPR with vi=4 for vw=8
1766 sb = 0 if vi%4 == 0 else 1
1767 module.add(VCvtPkFP8toF32(dst=vgpr(tmpVgpr, 2), src=vgpr(dataV), vop3=VOP3PModifiers(op_sel=[sb])))
1768 else:
1769 # Enable WORD_0 of 2-nd VGPR with vi=4 for vw=8
1770 sb = SelectBit.WORD_0 if vi%4 == 0 else SelectBit.WORD_1
1771 module.add(VCvtPkFP8toF32(dst=vgpr(tmpVgpr, 2), src=vgpr(dataV), sdwa=SDWAModifiers(src0_sel=sb)))
1772 module.add(SNop(waitState=0))
1773 if kernel["ProblemType"]["ComputeDataType"].isSingle():
1774 module.add(VMacF32(dst=vgpr("ValuC+%u"%newSumIdxV), src0=vgpr(tmpVgpr), src1=sgpr("Beta"), comment="finalSum = sum*alpha + C*beta"))
1775 if isPK:
1776 module.add(VMacF32(dst=vgpr("ValuC+%u"%(newSumIdxV+1)), src0=vgpr(tmpVgpr+1), src1=sgpr("Beta"), comment="finalSum = sum*alpha + C*beta (PK)"))
1777 # bfloat8 precision
1778 elif kernel["ProblemType"]["DestDataType"].isAnyBFloat8():
1779 if kernel["ProblemType"]["HighPrecisionAccumulate"]:
1780 newSumIdxV = sumIdxV - self.parentWriter.states.c.startVgprValu
1781 # Generate single f32 code if edge is detected.
1782 isPK = False
1783 if ((vi + 1) == self.gwvw) and ((self.gwvw % 2) == 1):
1784 if self.parentWriter.states.archCaps["VOP3ByteSel"]:
1785 sb = 0 if self.gwvw == 1 else 1
1786 if not self.amdClangVersion.major >= 19:
1787 module.add(VCvtBF8toF32(dst=vgpr(tmpVgpr), src=vgpr(dataV), vop3=VOP3PModifiers(op_sel=[0,sb])))
1788 else:
1789 module.add(VCvtBF8toF32(dst=vgpr(tmpVgpr), src=vgpr(dataV), vop3=VOP3PModifiers(byte_sel=[sb])))
1790 else:
1791 sb = SelectBit.BYTE_0 if self.gwvw == 1 else SelectBit.BYTE_2
1792 module.add(VCvtBF8toF32(dst=vgpr(tmpVgpr), src=vgpr(dataV), sdwa=SDWAModifiers(src0_sel=sb)))
1793 # Original packed route
1794 elif vi%2 == 1:
1795 continue
1796 else:
1797 isPK = True
1798 if self.parentWriter.states.archCaps["NoSDWA"]:
1799 # Enable WORD_0 of 2-nd VGPR with vi=4 for vw=8
1800 sb = 0 if vi%4 == 0 else 1
1801 module.add(VCvtPkBF8toF32(dst=vgpr(tmpVgpr, 2), src=vgpr(dataV), vop3=VOP3PModifiers(op_sel=[sb])))
1802 else:
1803 # Enable WORD_0 of 2-nd VGPR with vi=4 for vw=8
1804 sb = SelectBit.WORD_0 if vi%4 == 0 else SelectBit.WORD_1
1805 module.add(VCvtPkBF8toF32(dst=vgpr(tmpVgpr, 2), src=vgpr(dataV), sdwa=SDWAModifiers(src0_sel=sb)))
1806 module.add(SNop(waitState=0))
1807 if kernel["ProblemType"]["ComputeDataType"].isSingle():
1808 module.add(VMacF32(dst=vgpr("ValuC+%u"%newSumIdxV), src0=vgpr(tmpVgpr), src1=sgpr("Beta"), comment="finalSum = sum*alpha + C*beta"))
1809 if isPK:
1810 module.add(VMacF32(dst=vgpr("ValuC+%u"%(newSumIdxV+1)), src0=vgpr(tmpVgpr+1), src1=sgpr("Beta"), comment="finalSum = sum*alpha + C*beta (PK)"))
1811 return module
1812
1813 def copyData(computeDataType, elementSumIdx, gwvw, vgprStart, direction=0):
1814 module = Module("Copy Data")
1815 vi = 0
1816 while vi < gwvw:
1817 sumIdxV = elementSumIdx + vi
1818 if computeDataType.isHalf() or computeDataType.isBFloat16():
1819 if (sumIdxV % 2 != 0):
1820 vi += 1
1821 continue
1822 vgprIdx = elementSumIdx + vi // 2
1823 if (vi + 1 < gwvw) and ((vgprStart + (vi // 2)) % 2 == 0) and (vgprIdx % 2 == 0):
1824 module.add(VMovB64(dst=vgpr(vgprStart + (vi // 2), 2), src=vgpr(vgprIdx, 2)))
1825 vi += 2
1826 else:
1827 module.add(VMovB32(dst=vgpr(vgprStart + (vi // 2)), src=vgpr(vgprIdx)))
1828 vi += 1
1829 elif computeDataType.isSingle() or computeDataType.isInt32():
1830 vgprIdx = sumIdxV
1831 if (vi + 1 < gwvw) and ((vgprStart + vi) % 2 == 0) and (vgprIdx % 2 == 0):
1832 module.add(VMovB64(dst=vgpr(vgprStart + vi, 2), src=vgpr(vgprIdx, 2)))
1833 vi += 2
1834 else:
1835 module.add(VMovB32(dst=vgpr(vgprStart + vi), src=vgpr(vgprIdx)))
1836 vi += 1
1837 elif computeDataType.isDouble():
1838 vgprIdx = elementSumIdx + vi * 2
1839 module.add(VMovB64(dst=vgpr(vgprStart + vi * 2, 2), src=vgpr(vgprIdx, 2)))
1840 vi += 1
1841 else:
1842 assert 0
1843
1844 if direction == 1:
1845 for i in module.items():
1846 srcs = i.srcs
1847 tmp = srcs[0]
1848 srcs[0] = i.dst
1849 i.dst = tmp
1850 i.srcs = srcs
1851 return module
1852
1853 def convertData(gwvw, elementSumIdx, cvtType: CvtType, roundType: RoundType = RoundType.ROUND_UP, inputPrefix="", prefixOffset=0):
1854 module = Module("ConvertData")
1855 for vi in range(0, gwvw):
1856 sumIdxV = elementSumIdx + vi
1857 formatVgpr = formatting(sumIdxV, inputPrefix, prefixOffset)
1858 if cvtType == CvtType.CVT_F32_to_I32:
1859 if roundType == RoundType.ROUND_TO_NEAREST_EVEN:
1860 module.add(VRndneF32(dst=vgpr(formatVgpr), src=vgpr(formatVgpr), comment=" round to even"))
1861 module.add(VCvtF32toI32(dst=vgpr(formatVgpr), src=vgpr(formatVgpr), comment=" convert fp32 to i32"))
1862 elif cvtType == CvtType.CVT_I32_to_F32:
1863 module.add(VCvtI32toF32(dst=vgpr(formatVgpr), src=vgpr(formatVgpr), comment=" convert to fp32"))
1864 else:
1865 #TODO add other convert types here.
1866 assert 0
1867 return module