Debian Codegraph @

tensilelite/Tensile/Components/SIA.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 import countInstruction, countGlobalRead, countLocalWrite, \
24 countDSStoreB128, countVMovB32
25 from rocisa.base import Item
26 from rocisa.code import Module, TextBlock
27 from rocisa.container import DSModifiers, HolderContainer, replaceHolder
28
29 from rocisa.instruction import SWaitCnt, SWaitAlu, DSStoreB128, DSStoreB64, DSStoreB32
30
31 from ..Common import roundUp, print2
32 from ..Component import SIA
33
34 from copy import deepcopy
35 from typing import Tuple
36
37 PRECISION = 100
38 class SIA3(SIA):
39 kernel = {"ScheduleIterAlg": 3}
40 def __call__(self):
41 assert(0)
42
43 def schedIntoIteration(self, writer, kernel, tensorParametersA, tensorParametersB, localWriteEndIter, firstIter, lastLoop, lastLc, globalReadIncACode, globalReadIncBCode, isNGLL):
44 # Get schedule information
45 numMfmaBetweenLWandBarrier, latencyLeft = getLocalWriteMFMAEnd(writer, kernel, tensorParametersA, tensorParametersB)
46 #########
47 # Internally assign an optimized LWPM value for PGR2
48 #########
49 # strategy is to distribute LW/GR as wide as possible to avoid hitting vmem FIFO
50 # LWPM = (LW_End - LW_Start) / numLW
51 if kernel["LocalWritePerMfma"] == -1:
52 lwStartMfmaIndex = getLocalWriteMFMAStart(writer, kernel, tensorParametersA, tensorParametersB, latencyLeft)
53 numLocalWriteModPerMfma = getNumLocalWritePerMfma(writer, kernel, lwStartMfmaIndex)
54 else:
55 numLocalWriteModPerMfma = roundUp(kernel["LocalWritePerMfma"]*PRECISION)
56
57 writer.states.numGlobalReadInsPerMfma, writer.states.numLocalWriteModPerMfma = calculateGRPMandLWPM(writer, kernel, numLocalWriteModPerMfma)
58 localWriteEndIter = fixLocalWriteEndMfmaIndex(writer, kernel, tensorParametersA, tensorParametersB, \
59 globalReadIncACode, globalReadIncBCode, numMfmaBetweenLWandBarrier, lastLoop)
60 numGlobalReadInsPerIter, numLocalWriteModPerIter, numEmptyGlobalReadIncCode = getScheduleParamMfma(writer)
61 numLocalWritesPerSched = writer.states.numLocalWriteModPerMfma
62 # Schedule global read
63 if not writer.states.scheduleGlobalRead:
64 itemsGRToSchedLater, lastLoadIter = noSchedGlobalRead(writer, kernel, globalReadIncACode, globalReadIncBCode)
65 writer.states.grEndMfmaIndex = 0
66 else:
67 itemsGRToSched, itemsGRToSchedLater = prepareGRInstToSched(writer, kernel, isNGLL)
68 itemsGRIncToSched = appendInstToSchedSIA3(writer, kernel, numEmptyGlobalReadIncCode, globalReadIncACode, globalReadIncBCode)
69 schedNumForIter0, endIter = getSchedNumForIter0SIA3(writer, kernel, itemsGRToSched, itemsGRIncToSched, numGlobalReadInsPerIter)
70 lastLoadIter = schedGlobalRead(writer, itemsGRToSched, itemsGRIncToSched, numGlobalReadInsPerIter, schedNumForIter0, endIter)
71 # Schedule local write
72 if not writer.states.scheduleLocalWrite:
73 noSchedLocalWrite(writer, kernel, tensorParametersA, tensorParametersB, localWriteEndIter)
74 writer.states.lwStartMfmaIndex = writer.states.lwEndMfmaIndex
75 else:
76 itemsLWToSched, numWritesToSched = prepareLWInstToSched(writer, kernel, numLocalWritesPerSched, isNGLL=isNGLL)
77 startIter = assignLWSchedIndexSIA3(writer, kernel, numLocalWritesPerSched, localWriteEndIter, numWritesToSched)
78 readsToWait, readsToWaitNGLL = getReadsToWait(writer, kernel)
79 # add waitcnt for DirectToVgpr + PGR1. Delaying wait for DirectToVgpr global read
80 if (kernel["DirectToVgprA"] or kernel["DirectToVgprB"]) and kernel["PrefetchGlobalRead"] == 1:
81 # DirectToVgpr + swapGlobalRead case, actual DTV load is in self.globalReadBCode (due to swap).
82 # Need to check self.globalReadBCode
83 readsToWaitDTV = len(list(writer.codes.globalReadB.middle.items()))
84 readsToWait += readsToWaitDTV
85 readsToWaitNGLL += readsToWaitDTV
86 # make sure numLocalWriteModPerIter is enough to schedule localwrite
87 startIterItem = numLocalWriteModPerIter - (writer.states.lwStartMfmaIndex % writer.states.numMfmaPerIter) * numLocalWritesPerSched
88 schedLocalWrite(writer, kernel, numLocalWriteModPerIter, numLocalWritesPerSched, localWriteEndIter, \
89 itemsGRToSchedLater, itemsLWToSched, startIter, readsToWait, readsToWaitNGLL, \
90 firstIter, lastLc, isNGLL, startIterItem)
91
92 class SIA2(SIA):
93 kernel = {"ScheduleIterAlg": 2}
94 def __call__(self):
95 assert(0)
96
97 def schedIntoIteration(self, writer, kernel, tensorParametersA, tensorParametersB, localWriteEndIter, firstIter, lastLoop, lastLc, globalReadIncACode, globalReadIncBCode, isNGLL):
98 # Get schedule information
99 numGlobalReadInsPerIter, numLocalWriteModPerIter, numEmptyGlobalReadIncCode = getScheduleParams(kernel)
100 numLocalWritesPerSched = numLocalWriteModPerIter
101 # Schedule global read
102 if not writer.states.scheduleGlobalRead:
103 itemsGRToSchedLater, lastLoadIter = noSchedGlobalRead(writer, kernel, globalReadIncACode, globalReadIncBCode)
104 else:
105 itemsGRToSched, itemsGRToSchedLater = prepareGRInstToSched(writer, kernel, isNGLL)
106 itemsGRIncToSched = appendInstToSchedDefault(numEmptyGlobalReadIncCode, globalReadIncACode, globalReadIncBCode)
107 schedNumForIter0, endIter = getSchedNumForIter0Default(itemsGRToSched, itemsGRIncToSched, numGlobalReadInsPerIter, localWriteEndIter)
108 lastLoadIter = schedGlobalRead(writer, itemsGRToSched, itemsGRIncToSched, numGlobalReadInsPerIter, schedNumForIter0, endIter)
109 # Schedule local write
110 if not writer.states.scheduleLocalWrite:
111 noSchedLocalWrite(writer, kernel, tensorParametersA, tensorParametersB, localWriteEndIter)
112 else:
113 itemsLWToSched, numWritesToSched = prepareLWInstToSched(writer, kernel, numLocalWritesPerSched)
114 startIter = assignLWSchedIndexDefault(writer, kernel, numLocalWritesPerSched, localWriteEndIter, lastLoadIter, numWritesToSched)
115 readsToWait, readsToWaitNGLL = getReadsToWait(writer, kernel)
116 schedLocalWrite(writer, kernel, numLocalWriteModPerIter, numLocalWritesPerSched, localWriteEndIter, \
117 itemsGRToSchedLater, itemsLWToSched, startIter, readsToWait, readsToWaitNGLL, \
118 firstIter, lastLc, isNGLL)
119
120 class SIA1(SIA):
121 kernel = {"ScheduleIterAlg": 1}
122 def __call__(self):
123 assert(0)
124
125 def schedIntoIteration(self, writer, kernel, tensorParametersA, tensorParametersB, localWriteEndIter, firstIter, lastLoop, lastLc, globalReadIncACode, globalReadIncBCode, isNGLL):
126 # Get schedule information
127 numGlobalReadInsPerIter, numLocalWriteModPerIter, numEmptyGlobalReadIncCode = getScheduleParams(kernel)
128 numLocalWritesPerSched = numLocalWriteModPerIter
129 # Schedule global read
130 if not writer.states.scheduleGlobalRead:
131 itemsGRToSchedLater, lastLoadIter = noSchedGlobalRead(writer, kernel, globalReadIncACode, globalReadIncBCode)
132 else:
133 itemsGRToSched, itemsGRToSchedLater = prepareGRInstToSched(writer, kernel, isNGLL)
134 itemsGRIncToSched = appendInstToSchedDefault(numEmptyGlobalReadIncCode, globalReadIncACode, globalReadIncBCode)
135 schedNumForIter0, endIter = getSchedNumForIter0Default(itemsGRToSched, itemsGRIncToSched, numGlobalReadInsPerIter, localWriteEndIter)
136 lastLoadIter = schedGlobalRead(writer, itemsGRToSched, itemsGRIncToSched, numGlobalReadInsPerIter, schedNumForIter0, endIter)
137 # Schedule local write
138 if not writer.states.scheduleLocalWrite:
139 noSchedLocalWrite(writer, kernel, tensorParametersA, tensorParametersB, localWriteEndIter)
140 else:
141 itemsLWToSched, numWritesToSched = prepareLWInstToSched(writer, kernel, numLocalWritesPerSched)
142 startIter = assignLWSchedIndexDefault(writer, kernel, numLocalWritesPerSched, localWriteEndIter, lastLoadIter, numWritesToSched)
143 readsToWait, readsToWaitNGLL = getReadsToWait(writer, kernel)
144 schedLocalWrite(writer, kernel, numLocalWriteModPerIter, numLocalWritesPerSched, localWriteEndIter, \
145 itemsGRToSchedLater, itemsLWToSched, startIter, readsToWait, readsToWaitNGLL, \
146 firstIter, lastLc, isNGLL)
147
148 ################################################################################
149 ################################################################################
150 ###
151 ### Schedule Parameters
152 ###
153 ################################################################################
154 ################################################################################
155
156 def checkLocalReadFIFO(localReadFIFO, miLatency, numWaves, numMFMA, blockWidth):
157 # Add space to avoid LR FIFO stall
158 # lrStallLatencyBuffer:
159 # 40 quad-cycle - 4 x miLatency for b128
160 # 20 quad-cycle - 4 x miLatency for b64 (equal to one miLatency)
161 # 10 quad-cycle - 4 x miLatency for b32 (no stall)
162 # so no stall happen for b64/b32/b16
163 if blockWidth < 4:
164 return False
165 # The FIFO length is 16 so that each wave has 16/numWaves buffer.
166 lrStallLatencyBuffer = roundUp(blockWidth) * 10 - ((16 / numWaves) * miLatency)
167 if len(localReadFIFO) < (16 / numWaves):
168 localReadFIFO.append(numMFMA)
169 else:
170 oldNumMFMA = localReadFIFO[0]
171 if (numMFMA - oldNumMFMA) * miLatency >= lrStallLatencyBuffer:
172 localReadFIFO.pop(0)
173 localReadFIFO.append(numMFMA)
174 else:
175 # FIFO is full
176 return True
177 return False
178
179 def getScheduleParams(kernel):
180 numGlobalReadInsPerIter = roundUp(kernel["GlobalReadPerMfma"] * PRECISION) if kernel["GlobalReadPerMfma"] > 0 else PRECISION
181 numLocalWriteModPerIter = roundUp(kernel["LocalWritePerMfma"] * PRECISION) if kernel["LocalWritePerMfma"] > 0 else PRECISION
182 numEmptyGlobalReadIncCode = numGlobalReadInsPerIter - 1
183 return numGlobalReadInsPerIter, numLocalWriteModPerIter, numEmptyGlobalReadIncCode
184
185 def getLocalWriteMFMAEnd(writer, kernel, tensorParametersA, tensorParametersB):
186 numMfmaPerIter = writer.states.numMfmaPerIter
187 #########
188 # Get localWriteEnd
189 #########
190 # assign parameter
191 # 1. we calculate number of mfma to prefetch localReads for next loop
192 # 2. we put a barrier before the last mfma
193 # 3. we put last localWrite before 2~3 mfma, then the barrier
194 # localReads followed following sequence to be scheduled
195 # ds_read[A][0], ds_read[B][0], ds_read[A][1:], ds_read[B][1:]
196 # NOTE: we need this sequence for new feature "breaking waitcnt"
197 # TODO: breaking waitcnt
198 writer.states.numMfmaForLR = 1
199 latencyLeft = writer.states.miLatencyLeft
200 miLatencyLeft = writer.states.miLatencyLeft
201 tPM = tensorParametersA["tpsMetadata"] if tensorParametersA["is_sparse"] else tensorParametersB["tpsMetadata"]
202
203 # we can skip some LR waitcnt
204 # Since the first mfma only use B[:1], so we only wait for B[0]
205 isLocalReadsOpt = False
206 tmpLatencyLeft = 0
207 tmpNumMfmaForLR = 0
208 localReadsNotWaited = writer.states.numReadsPerIterB // kernel["InnerUnroll"] - writer.states.numReadsPerUnrollB
209 if kernel["UnrollMajorLDSB"] and localReadsNotWaited > 0:
210 isLocalReadsOpt = True
211
212 # check instruction FIFO
213 localReadFIFO = []
214 numWaves = kernel["MIWaveGroup"][0] * kernel["MIWaveGroup"][1] * kernel["LocalSplitU"]
215
216 def calculateLatencyLeft(numReads, localReadBlockWidth, localReadLatency):
217 nonlocal localReadFIFO, numWaves, latencyLeft, miLatencyLeft
218 for _ in range(numReads):
219 while(checkLocalReadFIFO(localReadFIFO, writer.states.miLatency, numWaves, writer.states.numMfmaForLR, localReadBlockWidth)):
220 writer.states.numMfmaForLR += 1
221 latencyLeft -= localReadLatency*2
222 if latencyLeft < 0:
223 writer.states.numMfmaForLR += 1
224 latencyLeft = max(miLatencyLeft - localReadLatency*2,0)
225
226 for iui in range(kernel["InnerUnroll"]):
227 # ds_read[A][0]
228 calculateLatencyLeft(writer.states.numReadsPerUnrollA, tensorParametersA["localReadInstruction"].blockWidth, tensorParametersA["localReadInstruction"].issueLatency)
229 # ds_read[M][0]
230 if kernel["ProblemType"]["Sparse"] and not kernel["DirectToVgprSparseMetadata"]:
231 calculateLatencyLeft(writer.states.numReadsPerUnrollMetadata, tPM["localReadInstruction"].blockWidth, tPM["localReadInstruction"].issueLatency)
232 # ds_read[B][0]
233 calculateLatencyLeft(writer.states.numReadsPerUnrollB, tensorParametersB["localReadInstruction"].blockWidth, tensorParametersB["localReadInstruction"].issueLatency)
234 # ds_read[A][1:]
235 calculateLatencyLeft((writer.states.numReadsPerIterA//kernel["InnerUnroll"] - writer.states.numReadsPerUnrollA), tensorParametersA["localReadInstruction"].blockWidth, tensorParametersA["localReadInstruction"].issueLatency)
236 # ds_read[M][1:]
237 if kernel["ProblemType"]["Sparse"] and not kernel["DirectToVgprSparseMetadata"]:
238 calculateLatencyLeft((writer.states.numReadsPerIterMetadata//kernel["InnerUnroll"] - writer.states.numReadsPerUnrollMetadata), tPM["localReadInstruction"].blockWidth, tPM["localReadInstruction"].issueLatency)
239 # get the latency before B[:1]
240 if isLocalReadsOpt:
241 tmpLatencyLeft = latencyLeft
242 tmpNumMfmaForLR = writer.states.numMfmaForLR
243 # ds_read[B][1:]
244 calculateLatencyLeft((writer.states.numReadsPerIterB//kernel["InnerUnroll"] - writer.states.numReadsPerUnrollB), tensorParametersB["localReadInstruction"].blockWidth, tensorParametersB["localReadInstruction"].issueLatency)
245 # to calculate number of mfma we need to wait before data arrive from lds to vgpr.
246 # latency: 40 quad-cycle for 4 word, 20 quad-cycle for 2 word, 10 quad-cycle for 1 word / half word
247 writer.states.numMfmaForNextLoopLR = writer.states.numMfmaForLR
248 latencyForLR = roundUp(tensorParametersB["localReadInstruction"].blockWidth)*10
249 if isLocalReadsOpt:
250 latencyForLR = min(latencyForLR, (writer.states.numMfmaForLR - tmpNumMfmaForLR) * writer.states.miLatency)
251 latencyForLR -= max(tmpLatencyLeft,0) # remaining latency in mfma
252 else:
253 latencyForLR -= max(latencyLeft,0) # remaining latency in mfma
254 latencyForLR -= writer.states.miLatency # last LR will have 1 mfma latency
255 while latencyForLR > 0:
256 latencyForLR -= writer.states.miLatency
257 writer.states.numMfmaForNextLoopLR += 1
258 # final index definition
259 writer.states.numMfmaForNextLoopLR = min(writer.states.numMfmaForNextLoopLR,numMfmaPerIter-1)
260 writer.states.syncPlrMfmaIndex = numMfmaPerIter*(kernel["LoopIters"]-writer.states.numItersPLR+1) - writer.states.numMfmaForNextLoopLR - 1 if writer.states.numItersPLR else 0
261 numMfmaBetweenLWandBarrier = 2 if kernel["MatrixInstM"] == 32 else 3
262 writer.states.lwEndMfmaIndex = max(writer.states.syncPlrMfmaIndex - numMfmaBetweenLWandBarrier,0) if writer.states.numItersPLR else numMfmaPerIter*kernel["LoopIters"] - 1
263 if kernel["DirectToLds"] and kernel["PrefetchGlobalRead"] == 2:
264 # DirectToLds + PGR=2 case, lwEndMfmaIndex must be after the end of local read (excluding local reads for next iter)
265 lrEnd = min(writer.states.syncPlrMfmaIndex - 1, writer.states.numMfmaForNextLoopLR)
266 if writer.states.lwEndMfmaIndex < lrEnd:
267 writer.states.lwEndMfmaIndex = lrEnd
268 return numMfmaBetweenLWandBarrier, latencyLeft
269
270 def getLocalWriteMFMAStart(writer, kernel, tensorParametersA, tensorParametersB, latencyLeft):
271 numMfmaPerIter = writer.states.numMfmaPerIter
272
273 tPM = tensorParametersA["tpsMetadata"] if tensorParametersA["is_sparse"] else tensorParametersB["tpsMetadata"]
274 #########
275 # Get localWriteStart
276 #########
277 if not (kernel["1LDSBuffer"] or kernel["DirectToLds"]):
278 # TODO: replace here for real number of globalReadIncInst
279 numGRIncInst = 18 # Always on. Original logic: 12 if not kernel["StaggerU"] else 18
280 numInstPerMfma = max(roundUp(writer.states.miLatencyLeft/2),1)
281 numMfmaToSched = roundUp(numGRIncInst/numInstPerMfma)
282 lwStartMfmaIndex = 1 + numMfmaToSched
283 else:
284 # check instruction FIFO
285 localReadFIFO = []
286 numWaves = kernel["MIWaveGroup"][0] * kernel["MIWaveGroup"][1] * kernel["LocalSplitU"]
287 # for 1LDSB, we have to issue localwrites after localreads
288 if kernel["ClusterLocalRead"]:
289 # we have enough vgprBuffer to schedule localReads in the front of loop
290 numMfmaForCurrentLoopLR = 1
291 latencyLeft = writer.states.miLatencyLeft
292 for u in range(kernel["LoopIters"] - writer.states.numItersPLR):
293 doReadA = (u < kernel["LoopIters"] // writer.states.numIterPerCoalescedReadA - writer.states.numItersPLR) and not kernel["DirectToVgprA"]
294 doReadB = (u < kernel["LoopIters"] // writer.states.numIterPerCoalescedReadB - writer.states.numItersPLR) and not kernel["DirectToVgprB"]
295 doReadM = (u < kernel["LoopIters"] // writer.states.numIterPerCoalescedReadMetadata - writer.states.numItersPLR)
296 doReadM = doReadM and (kernel["ProblemType"]["Sparse"] and not kernel["DirectToVgprSparseMetadata"])
297
298 def calculateLatencyLeft(numReads, localReadBlockWidth, localReadLatency):
299 nonlocal localReadFIFO, numWaves, latencyLeft, numMfmaForCurrentLoopLR
300 for _ in range(numReads):
301 while(checkLocalReadFIFO(localReadFIFO, writer.states.miLatency, numWaves, numMfmaForCurrentLoopLR, localReadBlockWidth)):
302 numMfmaForCurrentLoopLR += 1
303 latencyLeft -= localReadLatency*2
304 if latencyLeft < 0:
305 numMfmaForCurrentLoopLR += 1
306 latencyLeft = max(writer.states.miLatencyLeft - localReadLatency*2,0)
307
308 for iui in range(kernel["InnerUnroll"]):
309 # ds_read[A][0]
310 calculateLatencyLeft(writer.states.numReadsPerUnrollA * doReadA, tensorParametersA["localReadInstruction"].blockWidth, tensorParametersA["localReadInstruction"].issueLatency)
311 # ds_read[M][0]
312 if doReadM:
313 calculateLatencyLeft(writer.states.numReadsPerUnrollMetadata * doReadM, tPM["localReadInstruction"].blockWidth, tPM["localReadInstruction"].issueLatency)
314 # ds_read[B][0]
315 calculateLatencyLeft(writer.states.numReadsPerUnrollB * doReadB, tensorParametersB["localReadInstruction"].blockWidth, tensorParametersB["localReadInstruction"].issueLatency)
316 # ds_read[A][1:]
317 calculateLatencyLeft((writer.states.numReadsPerIterA//kernel["InnerUnroll"] - writer.states.numReadsPerUnrollA) * doReadA, tensorParametersA["localReadInstruction"].blockWidth, tensorParametersA["localReadInstruction"].issueLatency)
318 # ds_read[M][1:]
319 if doReadM:
320 calculateLatencyLeft((writer.states.numReadsPerIterMetadata//kernel["InnerUnroll"] - writer.states.numReadsPerUnrollMetadata) * doReadM, tPM["localReadInstruction"].blockWidth, tPM["localReadInstruction"].issueLatency)
321 # ds_read[B][1:]
322 calculateLatencyLeft((writer.states.numReadsPerIterB//kernel["InnerUnroll"] - writer.states.numReadsPerUnrollB) * doReadB, tensorParametersB["localReadInstruction"].blockWidth, tensorParametersB["localReadInstruction"].issueLatency)
323 lwStartMfmaIndex = numMfmaForCurrentLoopLR
324 else:
325 lwStartMfmaIndex = numMfmaPerIter * (kernel["LoopIters"] - 1 - writer.states.numItersPLR) + writer.states.numMfmaForLR
326 # to calculate number of mfma we need to wait before data arrive from lds to vgpr.
327 # latency: 40 quad-cycle for 4 word, 20 quad-cycle for 2 word, 10 quad-cycle for 1 word / half word
328 if writer.states.numIterPerCoalescedReadB > writer.states.numIterPerCoalescedReadA:
329 latencyForLR = roundUp(tensorParametersA["localReadInstruction"].blockWidth) * 10
330 else:
331 latencyForLR = roundUp(tensorParametersB["localReadInstruction"].blockWidth) * 10
332 latencyForLR -= max(latencyLeft,0) # remaining latency in mfma
333 while latencyForLR > 0:
334 latencyForLR -= writer.states.miLatency
335 lwStartMfmaIndex += 1
336
337 if lwStartMfmaIndex > writer.states.lwEndMfmaIndex:
338 lwStartMfmaIndex = writer.states.lwEndMfmaIndex
339 return lwStartMfmaIndex
340
341 def getNumLocalWritePerMfma(writer, kernel, lwStartMfmaIndex):
342 #########
343 # Get LocalWritePerMfma
344 #########
345 numMfmaCanSched = writer.states.lwEndMfmaIndex - lwStartMfmaIndex + 1
346 numLoadsA = kernel["DepthU"]*kernel["MacroTileA"]//kernel["GlobalReadVectorWidthA"]//kernel["NumThreads"]
347 numLoadsB = kernel["DepthU"]*kernel["MacroTileB"]//kernel["GlobalReadVectorWidthB"]//kernel["NumThreads"]
348 if kernel["ProblemType"]["Sparse"] and not kernel["DirectToVgprSparseMetadata"]:
349 macroTile = kernel["MacroTileB"] if kernel["ProblemType"]["Sparse"] == 2 else kernel["MacroTileA"]
350 numLoadsM = kernel["DepthU"]*macroTile//kernel["GlobalReadVectorWidthMetadata"]//kernel["NumThreads"]
351 else:
352 numLoadsM = 0
353 writesToSched = (numLoadsA + numLoadsB + numLoadsM- 1) * PRECISION
354 oldValue = 0
355 newValue = PRECISION
356 loop = 0
357 # 1. number of padded writesToSched is (numWrites - 1) * 100 + 1
358 # LW ---99--- LW ---99--- LW
359 # 2. we need to pad it to multiple of LWPM
360 # LW ---99--- LW ---99--- LW --?--
361 # | ------- multiple of LWPM ---- |
362 # 3. if LWPM is not multiple of 100, we need extra empty instructions to schedule GR for PGR2
363 # LW ---99--- LW ---99--- LW --?-- --?--
364 # | ------- multiple of LWPM ---- |-LWPM-|
365 # 4. then we put GR into padded writesToSched
366 # put GR after LW + LWPM of empty inst, so that we can offset GR 1 mfma with LW if possible
367 # Ex. LWPM = 0.25
368 # LW --24- GR ------74------ LW --24- GR ------74------ LW --24- GR --24-
369 # mfma--24-mfma--24-mfma--24-mfma--24-mfma--24-mfma--24-mfma--24-mfma--24-mfma
370 # we need LWPM to get precise LWPM
371 # so we iterate formula 10 times to get LWPM
372 while oldValue != newValue and newValue > 0 and loop < 10:
373 loop += 1
374 oldValue = newValue
375 newValue = roundUp((writesToSched+1 + (oldValue - (writesToSched+1) % oldValue) + oldValue%PRECISION) / numMfmaCanSched)
376 return newValue
377
378 def calculateGRPMandLWPM(writer, kernel, numLocalWriteModPerMfma) -> Tuple[int, int]:
379 #####
380 # Assign GRPM and LWPM
381 #####
382 # HOW THIS WORK
383 # padding each globalReadInstruction to 100 with empty instruction,
384 # each mfma will schedule intructions GRPM*100 times from padded globalReadInstruction.
385 # Ex. GRPM = 0.5
386 # GR ---------99--------- GR --------99---------- GR
387 # mfma --49-- mfma --49-- mfma --49-- mfma --49-- mfma --49--
388 numGlobalReadInsPerMfma = roundUp(kernel["GlobalReadPerMfma"]*PRECISION)
389 # HOW THIS WORK
390 # padding each globalReadInstruction to 100 with empty instruction,
391 # each mfma will schedule intructions GRPM*100 times from padded globalReadInstruction.
392 # Ex. LWPM = 0.5
393 # LW ---------99--------- LW --------99---------- LW
394 # mfma --49-- mfma --49-- mfma --49-- mfma --49-- mfma --49--
395 if kernel["PrefetchGlobalRead"] == 1:
396 # In PGR1:
397 # Larger LWPM can provide more latency to hide global read
398 # However, larger LWPM may cause mfma bubbles
399 # we set LWPM to 1 unless it requires larger LWPM to enable 1LDSB
400 if kernel["1LDSBuffer"]:
401 numLocalWriteModPerMfma = max(numLocalWriteModPerMfma, PRECISION)
402 else:
403 numLocalWriteModPerMfma = PRECISION
404
405 return numGlobalReadInsPerMfma, numLocalWriteModPerMfma
406
407 def getScheduleParamMfma(writer):
408 numMfmaPerIter = writer.states.numMfmaPerIter
409 numGlobalReadInsPerIter = numMfmaPerIter * writer.states.numGlobalReadInsPerMfma
410 numLocalWriteModPerIter = numMfmaPerIter * writer.states.numLocalWriteModPerMfma
411 # if numGlobalReadInsPerMfma>1, we still want to schedule only 1 GlobalReadIncCode per mfma
412 # inserting empty CodeModule so that generator will schedule 1 GlobalReadIncCode 1 empty CodeModule if numGlobalReadInsPerMfma=2
413 numEmptyGlobalReadIncCode = writer.states.numGlobalReadInsPerMfma - 1
414 return numGlobalReadInsPerIter, numLocalWriteModPerIter, numEmptyGlobalReadIncCode
415
416 def fixLocalWriteEndMfmaIndex(writer, kernel, tPA, tPB, globalReadIncACode, globalReadIncBCode, numMfmaBetweenLWandBarrier, lastLoop):
417 numMfmaPerIter = writer.states.numMfmaPerIter
418 # If numLocalWriteModPerMfma is not multiple of 100,
419 # last globalread will be scheduled at lwEndMfmaIndex,
420 # and last localwrite will be scheduled at lwEndMfmaIndex - 1
421 # so we offset lwEndMfmaIndex by 1 mfma
422 if kernel["PrefetchGlobalRead"] == 2 and writer.states.numLocalWriteModPerMfma % PRECISION != 0:
423 numMfmaBetweenLWandBarrier -= 1
424
425 writer.states.lwEndMfmaIndex = max(writer.states.syncPlrMfmaIndex - numMfmaBetweenLWandBarrier,0) if writer.states.numItersPLR else numMfmaPerIter*kernel["LoopIters"] - 1
426 # adjust lwEndMfmaIndex for the following cases
427 # 1) PGR=2
428 # 2) last loop enabled case
429 # In these cases, lwEndMfmaIndex needs to be < numMfmaPerIter * (kernel["LoopIters"] - 1)
430 # to schedule global read for DTV after lwEndMfmaIndex or execute PostLoop after StoreC in NoLoadLoop
431 # kernel["LoopIters"] has to be > 1 to make this logic work.
432 if kernel["LoopIters"] > 1 and lastLoop:
433 writer.states.lwEndMfmaIndex = min(writer.states.lwEndMfmaIndex, numMfmaPerIter * (kernel["LoopIters"] - 1) - 1)
434 if kernel["DirectToLds"] and kernel["PrefetchGlobalRead"] == 2:
435 # DirectToLds + PGR=2 case, lwEndMfmaIndex must be after the end of local read (excluding local reads for next iter)
436 lrEnd = min(writer.states.syncPlrMfmaIndex - 1, writer.states.numMfmaForLR * (kernel["LoopIters"] - writer.states.numItersPLR))
437 if writer.states.lwEndMfmaIndex < lrEnd:
438 writer.states.lwEndMfmaIndex = lrEnd
439 localWriteEndIter = writer.states.lwEndMfmaIndex//numMfmaPerIter
440 localWriteEndIter = min(kernel["LoopIters"] - 1, localWriteEndIter)
441 assert localWriteEndIter < kernel["LoopIters"]
442 assert writer.states.lwEndMfmaIndex < numMfmaPerIter*kernel["LoopIters"]
443 return localWriteEndIter
444
445 ################################################################################
446 ################################################################################
447 ###
448 ### Schedule Global Read
449 ###
450 ################################################################################
451 ################################################################################
452
453 def noSchedGlobalRead(writer, kernel, globalReadIncACode, globalReadIncBCode):
454 # put everything in the header:
455 writer.codes.unrollLoopHeader.add(writer.codes.dtlsM0UpdateA)
456 writer.codes.unrollLoopHeader.add(writer.codes.globalReadA)
457 writer.codes.unrollLoopHeader.add(writer.codes.dtlsM0UpdateB)
458 writer.codes.unrollLoopHeader.add(writer.codes.globalReadB)
459 writer.codes.unrollLoopHeader.add(globalReadIncACode)
460 writer.codes.unrollLoopHeader.add(globalReadIncBCode)
461 # Dummy
462 itemsGRToSchedLater = []
463 lastLoadIter = 0
464 return itemsGRToSchedLater, lastLoadIter
465
466 def prepareGRInstToSched(writer, kernel, isNGLL):
467 writer.codes.unrollLoopHeader.add(writer.codes.globalReadA.header)
468 writer.codes.unrollLoopHeader.add(writer.codes.globalReadB.header)
469
470 # Add all loads from middle as individual schedulable items
471 # when using PGR2, put global read instruction right after corresponding localWrite instruction
472 if isNGLL and kernel["UnrollLoopSwapGlobalReadOrder"] == 1:
473 itemsGRToSched = []
474 itemsGRToSchedLater = []
475 elif kernel["PrefetchGlobalRead"] == 2:
476 itemsGRToSched = []
477 itemsGRToSchedLater = list(writer.codes.globalReadA.middle.items()) + \
478 list(writer.codes.globalReadB.middle.items())
479 else:
480 itemsGRToSched = list(writer.codes.globalReadA.middle.items()) + \
481 list(writer.codes.globalReadB.middle.items())
482 itemsGRToSchedLater = []
483
484 itemsGRToSchedTemp = []
485 for i in range(len(itemsGRToSched)):
486 itemsGRToSchedTemp.append(itemsGRToSched.pop(0))
487 for j in range(PRECISION-1):
488 itemsGRToSchedTemp.append(Module())
489 itemsGRToSched = itemsGRToSchedTemp
490 return itemsGRToSched, itemsGRToSchedLater
491
492
493 def appendInstToSchedSIA3(writer, kernel, numEmptyGlobalReadIncCode, globalReadIncACode, globalReadIncBCode):
494 itemsGRIncToSched = []
495 # for SIA3, we can break GlobalReadIncCode to avoid mfma bubbles
496 if kernel["PrefetchGlobalRead"] == 2:
497 # skip to schedule global read for PGR2 first mfma
498 for i in range(numEmptyGlobalReadIncCode+1):
499 imod = Module()
500 itemsGRIncToSched.append(imod)
501 numInst = countInstruction(globalReadIncACode) + countInstruction(globalReadIncBCode)
502 numInstPerMfma = max(roundUp(writer.states.miLatencyLeft/2),1)
503
504 globalReadIncItems = globalReadIncACode.flatitems() + globalReadIncBCode.flatitems()
505 numMfmaToSched = roundUp(numInst/numInstPerMfma)
506 for j in range(numMfmaToSched):
507 imod = Module()
508 count = 0
509 while globalReadIncItems and count < numInstPerMfma:
510 tempInst = globalReadIncItems.pop(0)
511 imod.add(tempInst)
512 if countInstruction(tempInst):
513 count += 1
514 itemsGRIncToSched.append(imod)
515 for i in range(numEmptyGlobalReadIncCode):
516 imod = Module()
517 itemsGRIncToSched.append(imod)
518 return itemsGRIncToSched
519
520 def appendInstToSchedDefault(numEmptyGlobalReadIncCode, globalReadIncACode, globalReadIncBCode):
521 itemsGRIncToSched = []
522 itemsGRIncToSched.append(globalReadIncACode)
523 for i in range(numEmptyGlobalReadIncCode):
524 imod = Module()
525 itemsGRIncToSched.append(imod)
526 itemsGRIncToSched.append(globalReadIncBCode)
527 for i in range(numEmptyGlobalReadIncCode):
528 imod = Module()
529 itemsGRIncToSched.append(imod)
530 return itemsGRIncToSched
531
532 def getSchedNumForIter0SIA3(writer, kernel, itemsGRToSched, itemsGRIncToSched, numGlobalReadInsPerIter):
533 numMfmaPerIter = writer.states.numMfmaPerIter
534 # Loop in PGR1: GlobalRead -> GlobalReadInc -> LocalWrite
535 # but GlobalReadInc shouldn't block LocalWrite so we count them out
536 # Loop in PGR2: GlobalReadInc -> LocalWrite/GlobalRead pair
537 # since LocalWrite/GlobalRead pair depends on GlobalReadInc, we count in only GlobalReadInc
538 if kernel["PrefetchGlobalRead"] == 2:
539 loadsToSched = len(itemsGRIncToSched)
540 else:
541 loadsToSched = len(itemsGRToSched)
542
543 # Here is to adjust scheduling silently in order to have validation pass.
544 # Better way is to use larger globalReadPerMfma.
545 ## schedule more instructions at first iteration if no enough mfma to schedule globalRead
546 writer.states.grEndMfmaIndex = max(0, roundUp(loadsToSched/writer.states.numGlobalReadInsPerMfma) - 1)
547 if writer.states.grEndMfmaIndex > writer.states.lwEndMfmaIndex:
548 schedNumForIter0 = numGlobalReadInsPerIter + (writer.states.grEndMfmaIndex - writer.states.lwEndMfmaIndex) * writer.states.numGlobalReadInsPerMfma
549 writer.states.grEndMfmaIndex = writer.states.lwEndMfmaIndex
550 else:
551 schedNumForIter0 = numGlobalReadInsPerIter
552 if kernel["PrefetchGlobalRead"] == 1:
553 globalReadIncEndMfmaIndex = writer.states.grEndMfmaIndex + roundUp(len(itemsGRIncToSched)/writer.states.numGlobalReadInsPerMfma)
554 endIter = roundUp((globalReadIncEndMfmaIndex+1)/numMfmaPerIter)
555 else:
556 endIter = roundUp((writer.states.grEndMfmaIndex+1)/numMfmaPerIter)
557 ## schedule more instructions at first iteration if no enough mfma to schedule globalRead + globalReadInc
558 if endIter > kernel["LoopIters"]:
559 endIter = kernel["LoopIters"]
560 if kernel["PrefetchGlobalRead"] == 1:
561 schedNumForIter0 += (globalReadIncEndMfmaIndex+1 - kernel["LoopIters"]*numMfmaPerIter) * writer.states.numGlobalReadInsPerMfma
562 return schedNumForIter0, endIter
563
564 # schedNumForIter0 SIA 1 or 2
565 # distribute the instructions in itemsGRToSched evenly as possible to iterations: perIterGlobalReadCode[0,endIter)
566 # last one is perIterGlobalReadCode[endIter-1],
567 # Ideally: endIter <= localWriteEndIter,
568 # then put M0 updateCode (if any) and first 'schedNumForIter0' GR-inst in perIterGlobalReadCode[0]
569 # put every numGlobalReadInsPerIter GR-insts in perIterGlobalReadCode[1]~[endIter-1]
570 # corner case: endIter > localWriteEndIter, set endIter = localWriteEndIter,in this case, schedNumForIter0 will > 1
571 # and perIterGlobalReadCode[0] would need to schedule more instructions
572 def getSchedNumForIter0Default(itemsGRToSched, itemsGRIncToSched, numGlobalReadInsPerIter, localWriteEndIter):
573 # reads and incs are scheduled in iters range(0..endIter)
574 endIter = roundUp((len(itemsGRToSched) + len(itemsGRIncToSched)) / numGlobalReadInsPerIter)
575 # FIXME:
576 # above formula precisely count number of GR + GRInc
577 # however it has regression issue with tuned yaml with default GRPM.
578 # below formula follows old logic to add 2 to the instruction count, so it may has larger schedNumForIter0
579 # we should use above formula with GRPM tuning for better performance
580 # NOTE: both formula pass validation test
581 endIter = roundUp((len(itemsGRToSched) + len(itemsGRIncToSched) + 2*PRECISION) / numGlobalReadInsPerIter)
582 if endIter > localWriteEndIter:
583 # Front-load some of the buffer loads if we don't have enough loop iters:
584 # could use a different/smarter algorithm to space out the loads?
585 schedNumForIter0 = (endIter-(localWriteEndIter) + 1) * numGlobalReadInsPerIter
586 endIter = localWriteEndIter
587 else:
588 # schedule b2b for readCnt > 2 (True for bigger TT)
589 schedNumForIter0 = numGlobalReadInsPerIter
590 return schedNumForIter0, endIter
591
592 def schedGlobalRead(writer, itemsGRToSched, itemsGRIncToSched, numGlobalReadInsPerIter, schedNumForIter0, endIter):
593 # insert dtlsM0UpdateACode dtlsM0UpdateBCode code
594 if writer.codes.globalReadA.middle.items():
595 writer.codes.globalReadA.middle.getItem(0).add(writer.codes.dtlsM0UpdateA, 0)
596 if writer.codes.globalReadB.middle.items():
597 writer.codes.globalReadB.middle.getItem(0).add(writer.codes.dtlsM0UpdateB, 0)
598
599 itemsGRToSched.extend(itemsGRIncToSched)
600 # append 'n' global load at a time
601 # append global load(S) first 'number of global load(s)' determined by schedNumForIter0
602 for item in itemsGRToSched[:schedNumForIter0]:
603 writer.codes.perIterGlobalRead[0].add(item)
604 itemsGRToSched = itemsGRToSched[schedNumForIter0:] # trim the scheduled GRs, do the rest in the following loop
605
606 lastLoadIter = 0
607 for u in range(1, endIter):
608 # append itemPerIter GR for each iteration,
609 # and trim the scheduled ones at the end of loop
610 itemPerIter = 1 * numGlobalReadInsPerIter
611 try:
612 for item in itemsGRToSched[:itemPerIter]:
613 writer.codes.perIterGlobalRead[u].add(item)
614 lastLoadIter = u
615 itemsGRToSched = itemsGRToSched[itemPerIter:]
616 except IndexError:
617 break # itemsGRToSched is 0-length, no code left to schedule
618
619 assert not itemsGRToSched # should have scheduled everything already, itemsGRToSched should be empty
620
621 writer.codes.perIterGlobalRead[endIter-1].add(writer.codes.globalReadA.footer)
622 writer.codes.perIterGlobalRead[endIter-1].add(writer.codes.globalReadB.footer)
623 return lastLoadIter
624
625 ################################################################################
626 ################################################################################
627 ###
628 ### Schedule Local Write
629 ###
630 ################################################################################
631 ################################################################################
632
633 def noSchedLocalWrite(writer, kernel, tensorParametersA, tensorParametersB, localWriteEndIter):
634 # if no scheduleLocalWrite - just add writes to localWritelocalWriteEndIter
635 # If PGR=0, writes have to be done immediately following the loads - no opportunity to schedule
636 # so don't add to schedule, these will be added separately and before the first iter
637 if kernel["PrefetchGlobalRead"]:
638 # do we need a module here? That would prevent these from being scheduled
639 imod = writer.codes.perIterLocalWrite[localWriteEndIter][1].add(Module())
640 imod.add(
641 writer._wait(kernel, tensorParametersA, tensorParametersB, 0, -1, -1, \
642 "1wait for global read"))
643 imod.addComment1("local write A")
644 imod.add(writer.codes.localWriteA)
645 imod.addComment1("local write B")
646 imod.add(writer.codes.localWriteB)
647
648 def prepareLWInstToSched(writer, kernel, numLocalWritesPerSched, isNGLL=False):
649 #################
650 # create a plan #
651 #################
652 itemsLWToSched = list(writer.codes.localWriteA.items()) + list(writer.codes.localWriteB.items())
653 numDummy = 0
654 insertDummyTop = False
655 if kernel["PrefetchGlobalRead"] == 2:
656 # PrefetchGlobalRead + DirectToLds/DirectToVgpr case, need to add dummy list to insert global read
657 lenA = len(list(writer.codes.globalReadA.middle.items()))
658 lenB = len(list(writer.codes.globalReadB.middle.items()))
659 lenAFooter = len(list(writer.codes.globalReadA.footer.items()))
660 lenBFooter = len(list(writer.codes.globalReadB.footer.items()))
661 # A/B swap check for DTV. NGLL case, no swap
662 swapped = writer.isSwapGlobalReadOrderForDtvOrDtl(kernel) and (not isNGLL)
663 insertDummyTop = True
664 if swapped:
665 # swap A and B (SwapGlobalReadOrder case, the actual content is swapped (B is in globalReadACode). Need adjustment)
666 lenA, lenB = lenB, lenA
667 if kernel["DirectToLdsA"] or kernel["DirectToVgprA"]:
668 if kernel["DirectToLdsA"]:
669 # PGR2 + DTLcase, footer code is added in middle. Need to subtract 1 (for footer inst)
670 lenA -= lenAFooter
671 numDummy += lenA
672 insertDummyTop = (not swapped)
673 if kernel["DirectToLdsB"] or kernel["DirectToVgprB"]:
674 if kernel["DirectToLdsB"]:
675 # PGR2 + DTLcase, footer code is added in middle. Need to subtract 1 (for footer inst)
676 lenB -= lenBFooter
677 numDummy += lenB
678 insertDummyTop = swapped
679 # extend localWrite by inserting empty Module
680 # See getNumLocalWritePerMfma for how this work
681 itemsLWToSchedTemp = []
682 counter = 0
683 itemsLWToSchedLength_1 = len(itemsLWToSched) - 1
684 for i in range(itemsLWToSchedLength_1 + numDummy):
685 if insertDummyTop:
686 if i < numDummy:
687 item = None
688 else:
689 item = itemsLWToSched.pop(0)
690 itemsLWToSchedTemp.append([counter, item])
691 else:
692 if i < itemsLWToSchedLength_1:
693 item = itemsLWToSched.pop(0)
694 itemsLWToSchedTemp.append([counter, item])
695 else:
696 item = None
697 counter += 1
698 skip = kernel["PrefetchGlobalRead"] == 2 and kernel["ProblemType"]["Sparse"] and kernel["DirectToVgprSparseMetadata"] \
699 and item.name.startswith("MetadataWrite") and countVMovB32(item)
700 if not skip:
701 for _ in range(PRECISION-1):
702 counter += 1
703 if itemsLWToSched or (numDummy and itemsLWToSchedLength_1 == -1):
704 if itemsLWToSched:
705 itemsLWToSchedTemp.append([counter, itemsLWToSched.pop(0)])
706 counter += 1
707 for i in range(numLocalWritesPerSched + numLocalWritesPerSched % PRECISION - counter % numLocalWritesPerSched):
708 counter += 1
709 itemsLWToSched = itemsLWToSchedTemp
710 if not itemsLWToSched:
711 itemsLWToSched.append([max(0, counter - 1), None])
712 elif itemsLWToSched[-1][0] != (counter - 1):
713 itemsLWToSched.append([counter - 1, None]) # end of the list if not equal to counter
714 # This counts the number of modules which contain a ds_write
715 # Scheduler below keeps all writes in the same module in same iteration
716 # so this is better match to what it is trying to do
717 # numWritesToSched = sum(1 for item in itemsLWToSched if countLocalWrite(item)
718 numWritesToSched = itemsLWToSched[-1][0]
719 return itemsLWToSched, numWritesToSched
720
721 def assignLWSchedIndexSIA3(writer, kernel, numLocalWritesPerSched, localWriteEndIter, numWritesToSched):
722 numMfmaPerIter = writer.states.numMfmaPerIter
723 writer.states.lwStartMfmaIndex = writer.states.lwEndMfmaIndex - max(1,roundUp(numWritesToSched/numLocalWritesPerSched)) + 1
724 if writer.states.lwStartMfmaIndex < writer.states.grEndMfmaIndex:
725 writer.states.lwStartMfmaIndex = writer.states.grEndMfmaIndex
726 # DirectToLds + PGR=2 case, lwStart must be after all local reads are done
727 if kernel["DirectToLds"] and kernel["PrefetchGlobalRead"] == 2:
728 lrEnd = min(writer.states.lwEndMfmaIndex, writer.states.numMfmaForLR * (kernel["LoopIters"] - writer.states.numItersPLR))
729 if writer.states.lwStartMfmaIndex < lrEnd:
730 writer.states.lwStartMfmaIndex = lrEnd
731 if kernel["1LDSBuffer"] or kernel["DirectToLds"]:
732 writer.states.sync1LdsMfmaIndex = max(writer.states.lwStartMfmaIndex - 1, 0)
733 startIter = writer.states.lwStartMfmaIndex//numMfmaPerIter
734 assert startIter < localWriteEndIter+1 # startIter should be at or before the endIter
735 return startIter
736
737 def assignLWSchedIndexDefault(writer, kernel, numLocalWritesPerSched, localWriteEndIter, lastLoadIter, numWritesToSched):
738 startIter = localWriteEndIter - roundUp(numWritesToSched/numLocalWritesPerSched) + 1
739 # - can't move a write past the load it depends on
740 # as a simplification, don't move writes past any loads
741 if startIter < lastLoadIter:
742 startIter = lastLoadIter
743 return startIter
744
745 def getReadsToWait(writer, kernel):
746 readsToWait = len(list(writer.codes.localWriteA.items())) + len(list(writer.codes.localWriteB.items()))
747 readsToWaitNGLL = readsToWait
748 return readsToWait, readsToWaitNGLL
749
750 def schedLocalWrite(writer, kernel, numLocalWriteModPerIter, numLocalWritesPerSched, localWriteEndIter, \
751 itemsGRToSchedLater, itemsLWToSched, startIter, readsToWait, readsToWaitNGLL, \
752 firstIter, lastLc, isNGLL, startIterItem = None):
753 # schedule here
754 localwriteCnt = 0
755 globalReadInstOffset = 0
756 additionalIndexList = {}
757 skip = 0
758 if itemsLWToSched and itemsLWToSched[0][0] == 0 and itemsLWToSched[0][1] is None:
759 itemsLWToSched.pop(0) # remove the dummy item
760
761 itemsLWToSchedIndexLast = 0
762 for u in range(startIter, localWriteEndIter+1):
763 itemsLWToSchedLength = itemsLWToSched[-1][0] if itemsLWToSched else 0
764 if u == localWriteEndIter:
765 itemPerIter = itemsLWToSchedLength # schedule all remaining activity
766 else:
767 itemPerIter = itemsLWToSchedIndexLast + numLocalWriteModPerIter - 1
768 # if localwrite is not multiple of numLocalWriteModPerIter, fill last iteration first.
769 # make sure numLocalWriteModPerIter is enough to schedule localwrite
770 # TODO: if numLocalWriteModPerIter is not enough to schedule localwrite, need smarter way to distribute localWrite
771 if u == startIter and startIterItem:
772 itemPerIter = startIterItem - 1
773 # Convert timeline index to map index
774 if itemsLWToSched:
775 foundIndex = -1
776 skipInsert = False
777 for index, [itemIndex, _] in enumerate(itemsLWToSched):
778 if itemPerIter == itemIndex:
779 skipInsert = True
780 foundIndex = index
781 break
782 if itemPerIter < itemIndex:
783 foundIndex = index
784 break
785 if not skipInsert: # Insert scheduling point if needed
786 if foundIndex != -1:
787 itemsLWToSched.insert(foundIndex, [itemPerIter, None])
788 itemPerIter = foundIndex + 1
789 else:
790 itemsLWToSched.append([itemPerIter, None])
791 itemPerIter = len(itemsLWToSched)
792 itemsLWToSchedLength = itemPerIter
793 else:
794 itemPerIter = foundIndex + 1
795
796 perIterLocalWriteCodeCounter = 0
797 perIterLocalWriteCodeNGLLCounter = 0
798
799 itemsLWToSchedLengthLeft = itemsLWToSchedLength - itemsLWToSchedIndexLast
800 itemsLWToSchedIndexForSplitDS = 0
801 for itemsLWToSchedIndex, item in itemsLWToSched[:itemPerIter]:
802 tmp = itemsLWToSchedIndexLast + numLocalWriteModPerIter
803 for gapIndex in range(itemsLWToSchedIndexLast, itemsLWToSchedIndex + 1):
804 imodList = []
805 imodNGLLList = []
806 # Use a module to ensure these pieces stay together in the sub-iter scheduler
807 if gapIndex == itemsLWToSchedIndex:
808 if item:
809 writesPerItem = countLocalWrite(item)
810 if kernel["ProblemType"]["Sparse"] and not writesPerItem:
811 writesPerItem = item.name.startswith("MetadataWrite") and countVMovB32(item)
812 if writesPerItem:
813 writesPerItem = countLocalWrite(item)
814 if kernel["ProblemType"]["Sparse"] and not writesPerItem:
815 writesPerItem = item.name.startswith("MetadataWrite") and countVMovB32(item)
816 # Split into several dsStore32
817 syncEndExpandedNumIndex = itemsLWToSchedIndexForSplitDS
818
819 if writer.states.numMfmaPerIter and u == (writer.states.lwEndMfmaIndex // writer.states.numMfmaPerIter):
820 syncEndExpandedNumIndex = numLocalWriteModPerIter
821 syncEndExpandedNumIndex *= ((writer.states.syncPlrMfmaIndex % writer.states.numMfmaPerIter) / writer.states.numMfmaPerIter)
822 syncEndExpandedNumIndex = roundUp(syncEndExpandedNumIndex)
823
824 itemNew, numItemNew, globalReadInstOffset = splitDSInstructionIntoSmaller(writer, kernel, item, numLocalWritesPerSched, syncEndExpandedNumIndex, itemsLWToSchedIndexForSplitDS) if writer.do["AutoSplitDsWrite"] else (None, 0, 0)
825 if itemsLWToSchedIndexForSplitDS + globalReadInstOffset <= itemsLWToSchedLengthLeft:
826 additionalIndexList.clear()
827 for i in range(numItemNew):
828 additionalIndexList[int(i * numLocalWritesPerSched + itemsLWToSchedIndexForSplitDS)] = itemNew[i]
829 else:
830 globalReadInstOffset = 0
831
832 imodList.append(TextBlock("/* sched write - iter %u writesPerItem=%u */\n"%(u,writesPerItem)))
833 imodNGLLList.append(TextBlock("/* sched write - iter %u writesPerItem=%u */\n"%(u,writesPerItem)))
834 # if writesPerItem>1 this indicates multiple LocalWrites in the same module
835 # this happens in some transpose cases. Here the first write needs to wait
836 # for the associated global read to finish, then the remaining writes can flow
837 # TODO - can schedule these writes across iters, should figure this out above
838 readsToWait = readsToWait - 1
839 readsToWaitNGLL = readsToWaitNGLL - 1
840 imodList.append(SWaitCnt(vlcnt=readsToWait, \
841 comment="wait for global read before writing to local"))
842 imodNGLLList.append(SWaitCnt(vlcnt=readsToWaitNGLL, \
843 comment="wait for global read before writing to local"))
844 # PK and StoreCUnroll is removed so you cannot find any HolderContainer in s_waitcnt
845 if kernel["PrefetchGlobalRead"]==2:
846 hasHolder, wcList = hasHolderInWaitCnt(item)
847 if hasHolder:
848 readsToWaitAdjust = readsToWait
849 if kernel["NoLdsWriteCode"] and kernel["PrefetchGlobalRead"]!=2:
850 # DirectToLds for both A and B case, use the number of global read for both A and B as vlcnt (only for PGR=1)
851 readsToWaitAdjust = len(list(writer.codes.globalReadA.middle.items())) + len(list(writer.codes.globalReadB.middle.items()))
852 for wc in wcList:
853 replaceHolder(wc, (readsToWaitAdjust))
854 if itemsLWToSchedIndexForSplitDS in additionalIndexList:
855 imodList.append(additionalIndexList[itemsLWToSchedIndexForSplitDS])
856 additionalIndexList.pop(itemsLWToSchedIndexForSplitDS)
857 elif gapIndex < itemsLWToSchedIndex or (not item):
858 pass
859 else:
860 imodList.append(item)
861 # schedule global instruction that need to be scheduled later
862 numGlobalReadA = kernel["NumLoadsPerpendicularA"] * kernel["NumLoadsCoalescedA"]
863 numGlobalReadB = kernel["NumLoadsPerpendicularB"] * kernel["NumLoadsCoalescedB"]
864 dtvReadNum = numGlobalReadA if kernel["DirectToVgprA"] else numGlobalReadB
865 totalNumGR = numGlobalReadA + numGlobalReadB
866 nondtvReadNum = totalNumGR - dtvReadNum
867
868 readCntA = 1
869 readCntB = 1
870 readCntA = 2 if kernel["DirectToVgprA"] and kernel["reorderGRInstForDTVA"] and \
871 kernel["NumLoadsCoalescedA"] % 2 == 0 else 1
872 readCntB = 2 if kernel["DirectToVgprB"] and kernel["reorderGRInstForDTVB"] and \
873 kernel["NumLoadsCoalescedB"] % 2 == 0 else 1
874
875 if kernel["DirectToVgprA"]: # In loop, load A first
876 readCnt = readCntA if (len(itemsGRToSchedLater) > nondtvReadNum) or isNGLL else readCntB
877 elif kernel["DirectToVgprB"]: # In loop, load B first
878 readCnt = readCntB if (len(itemsGRToSchedLater) > nondtvReadNum) or isNGLL else readCntA
879 else: # not kernel["DirectToVgprA"] and not kernel["DirectToVgprB"]
880 readCnt = 1
881
882 if localwriteCnt % PRECISION == ((numLocalWritesPerSched % PRECISION) + globalReadInstOffset):
883 if not skip:
884 globalReadInstOffset = 0
885 reads = 0
886 while itemsGRToSchedLater:
887 itemGR = itemsGRToSchedLater[0]
888 readsInc = countGlobalRead(itemGR)
889 reads = reads + readsInc
890 if reads > readCnt:
891 break
892 if kernel["ExpertSchedulingMode"] > 0:
893 imodList.append(SWaitAlu(vm_vsrc=0, comment="wait for local read to vgpr complete"))
894 # PK and StoreCUnroll is removed so you cannot find any HolderContainer in s_waitcnt
895 hasHolder, wcList = hasHolderInWaitCnt(itemGR)
896 if hasHolder:
897 for wc in wcList:
898 replaceHolder(wc, (readsToWait))
899 imodList.append(itemGR)
900 else:
901 imodList.append(itemGR)
902 readsToWait = readsToWait + readsInc # GR instruction increments vlcnt
903 itemsGRToSchedLater.pop(0)
904
905 if readCnt == 2:
906 skip = skip ^ 1
907 else:
908 skip = 0
909 localwriteCnt += 1
910 if gapIndex < itemsLWToSchedIndex or (not item):
911 pass
912 else:
913 imodNGLLList.append(deepcopy(item))
914
915 perIterLocalWriteCodeCounter += 1
916 perIterLocalWriteCodeNGLLCounter += 1
917 if imodList:
918 imod = Module("LocalWriteMod%u"%u)
919 imod.addItems(imodList)
920 writer.codes.perIterLocalWrite[u][0].append(perIterLocalWriteCodeCounter)
921 writer.codes.perIterLocalWrite[u][1].add(imod)
922 if lastLc:
923 # local write code for NGLL should be updated at the last lc
924 # in init acc opt case, the last inner loop generated is not for the last lc.
925 # in that case, local write code for NGLL is not as expected.
926 if imodNGLLList:
927 imodNGLL = Module("LocalWriteModNGLL%u"%u)
928 imodNGLL.addItems(imodNGLLList)
929 writer.codes.perIterLocalWriteCodeNGLL[u][0].append(perIterLocalWriteCodeNGLLCounter)
930 writer.codes.perIterLocalWriteCodeNGLL[u][1].add(imodNGLL)
931 itemsLWToSchedIndexForSplitDS += 1
932 itemsLWToSchedIndexLast = itemsLWToSchedIndex + 1
933 if writer.codes.perIterLocalWrite[u][0] and writer.codes.perIterLocalWrite[u][0][-1] != perIterLocalWriteCodeCounter:
934 writer.codes.perIterLocalWrite[u][0].append(perIterLocalWriteCodeCounter)
935 if lastLc and writer.codes.perIterLocalWriteCodeNGLL[u][0] and writer.codes.perIterLocalWriteCodeNGLL[u][0][-1] != perIterLocalWriteCodeNGLLCounter:
936 writer.codes.perIterLocalWriteCodeNGLL[u][0].append(perIterLocalWriteCodeNGLLCounter)
937 itemsLWToSched = itemsLWToSched[itemPerIter:]
938
939 # should never run out of items to schedule
940 assert not itemsLWToSched # should have scheduled everthing already
941
942 #For the sparse case, GR and LW are not in paired.
943 #Hence, we must add all the remaining GRs into imod at the end.
944 if kernel["ProblemType"]["Sparse"]:
945 while itemsGRToSchedLater:
946 itemGR = itemsGRToSchedLater[0]
947 imod.add(itemGR)
948 itemsGRToSchedLater.pop(0)
949
950 def splitDSInstructionIntoSmaller(writer, kernel, item, numLocalWritesPerSched, lenOfItems, currentModIdx):
951 if not item:
952 return None, 0, 0
953 if countDSStoreB128(item) != 1 or countInstruction(item) != 1:
954 # only support one b128
955 return None, 0, 0
956
957 itemList = item.flatitems()
958 instruction = next(filter(lambda inst: isinstance(inst, DSStoreB128), itemList))
959 miLatency = writer.states.miLatency
960 div = 1
961 dsOffset = 0
962
963 LocalWriteX = DSStoreB128
964 if DSStoreB128.issueLatency() < (miLatency - 1):
965 # no need to split
966 return None, 0, 0
967 elif DSStoreB64.issueLatency() < (miLatency - 1):
968 LocalWriteX = DSStoreB64
969 dsOffset = 8
970 div = 2
971 elif DSStoreB32.issueLatency() < (miLatency - 1):
972 LocalWriteX = DSStoreB32
973 dsOffset = 4
974 div = 4
975 else:
976 # miLatency is not enough
977 return None, 0, 0
978
979 if numLocalWritesPerSched * div >= PRECISION:
980 # no enough mfma to split
981 return None, 0, 0
982
983 if (currentModIdx + numLocalWritesPerSched * div) >= lenOfItems:
984 # no enough modules to schedule
985 return None, 0, 0
986
987 # LW b32 4-way bank conflict latency ~ 108 cycles
988 # round up with quad-cycle
989 finalLWCycles = roundUp(108 / 4)
990
991 # How many mfmas between 2 LWs
992 # the MFMA buffer must be larger then the latency
993 numMfmaBetweenLW = PRECISION // numLocalWritesPerSched
994 mfmaBuffer = numMfmaBetweenLW * miLatency
995 if mfmaBuffer <= finalLWCycles:
996 # no enough cycles between LWs
997 return None, 0, 0
998
999 extraSched = roundUp(finalLWCycles / miLatency)
1000 if (currentModIdx + numLocalWritesPerSched * (div - 1 + extraSched)) >= lenOfItems:
1001 # no enough cycles before barrier
1002 return None, 0, 0
1003
1004 addr = instruction.getParams()[0]
1005 srcr = instruction.getParams()[1]
1006 offs = instruction.getParams()[2]
1007 ds = instruction.ds
1008 writeInst = []
1009 for d in range(div):
1010 ds1 = DSModifiers(na=1, offset=ds.offset + dsOffset * d)
1011 r1 = deepcopy(srcr)
1012 r1.regNum //= div
1013 r1.regName.addOffset(4 // div * d)
1014 writeInst.append(LocalWriteX(dstAddr=addr, src=r1, ds=ds1, comment=instruction.comment + " splitted"))
1015
1016 print2(f"Split ds_write_b128 to 4xds_write_b32 for {str(instruction)}")
1017
1018 return writeInst, len(writeInst), numLocalWritesPerSched * (div - 1)
1019
1020
1021 ################################################################################
1022 ################################################################################
1023 ###
1024 ### Helper function
1025 ###
1026 ################################################################################
1027 ################################################################################
1028
1029 def hasHolderInWaitCnt(module: Item):
1030 wcList = []
1031 hasHolder = False
1032 if isinstance(module, Module):
1033 for item in module.items():
1034 tmpHasHolder, tmpList = hasHolderInWaitCnt(item)
1035 hasHolder = hasHolder or tmpHasHolder
1036 wcList.extend(tmpList)
1037 elif isinstance(module, SWaitCnt):
1038 wcList.append(module)
1039 if isinstance(module.dscnt, HolderContainer) or \
1040 isinstance(module.kmcnt, HolderContainer) or \
1041 isinstance(module.vlcnt, HolderContainer) or \
1042 isinstance(module.vscnt, HolderContainer):
1043 hasHolder = True
1044 return hasHolder, wcList