Debian Codegraph @

tensilelite/Tensile/LibraryLogic.py

raw symbols SCIP
1 ################################################################################
2 #
3 # Copyright (C) 2022-2025 Advanced Micro Devices, Inc. All rights reserved.
4 #
5 # Permission is hereby granted, free of charge, to any person obtaining a copy
6 # of this software and associated documentation files (the "Software"), to deal
7 # in the Software without restriction, including without limitation the rights
8 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 # copies of the Software, and to permit persons to whom the Software is
10 # furnished to do so, subject to the following conditions:
11 #
12 # The above copyright notice and this permission notice shall be included in
13 # all copies or substantial portions of the Software.
14 #
15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 # SOFTWARE.
22 #
23 ################################################################################
24
25 from pathlib import Path
26 from typing import Dict
27 from . import LibraryIO
28 from . import SolutionSelectionLibrary
29 from Tensile.Common import print1, print2, HR, printExit, \
30 assignParameterWithDefault, ProgressBar, printWarning, ensurePath, \
31 LIBRARY_LOGIC_DIR, BENCHMARK_DATA_DIR, getVerbosity, IsaInfo
32 from Tensile.Common.GlobalParameters import defaultAnalysisParameters, globalParameters, startTime
33 from Tensile.SolutionStructs.Naming import getKernelNameMin, getSolutionNameMin, getSolutionNameFull
34
35 from copy import deepcopy
36 from sys import stdout
37
38 import array
39 import csv
40 import os
41 import time
42 import math
43
44 ################################################################################
45 # Analyze Problem Type
46 ################################################################################
47 def analyzeProblemType(problemType, problemSizeGroups, inputParameters, libraryLogicPath, splitGSU: bool):
48 print2(HR)
49 print1("# Analyzing: %s" % problemType)
50
51 enableTileSelection = problemType["TileAwareSelection"]
52 solutionsList = []
53 problemSizesList = []
54 dataFileNameList = []
55 selectionFileNameList = []
56
57 for problemSizeGroup in problemSizeGroups:
58 problemSizes = problemSizeGroup[0]
59 dataFileName = problemSizeGroup[1]
60 dataFileNameList.append(dataFileName)
61 solutionsFileName = problemSizeGroup[2]
62 #print " problemSizes:", problemSizes
63 #print "# DataFileName:", dataFileName
64 #print " solutionsFileName:", solutionsFileName
65 if enableTileSelection:
66 selectionFileName = problemSizeGroup[3]
67 selectionFileNameList.append(selectionFileName)
68
69 ######################################
70 # Read Solutions
71 # (problemSizes, solutions) are already read and kept in problemSizeGroups, no need to call LibraryIO.readSolutions(solutionsFileName) again
72 solutions = problemSizeGroup[4]
73 problemSizesList.append(problemSizes)
74 solutionsList.append(solutions)
75 print1("# Read: %s" % (solutionsFileName))
76 print2("# ProblemSizes: %s" % problemSizes)
77 print2("# Solutions:")
78 solutionIdx = 0
79 for solution in solutions:
80 print2("# (%u) %s" % (solutionIdx, getSolutionNameMin(solution, splitGSU)))
81 solutionIdx += 1
82 print2(HR)
83
84 ######################################
85 # Create Logic Analyzer
86 logicAnalyzer = LogicAnalyzer( problemType, problemSizesList, solutionsList, \
87 dataFileNameList, inputParameters, splitGSU)
88
89 selectionSolutionsIdsList = None
90 selectionSolutions = None
91
92 validSelectionSolutions = []
93
94 ######################################
95 # Remove invalid solutions
96 logicAnalyzer.removeInvalidSolutions()
97
98 ######################################
99 # Remove least important solutions
100 if inputParameters["LibraryType"] == "FreeSize" or inputParameters["LibraryType"] == "Prediction":
101 logicAnalyzer.deReferenceSolutions()
102 elif globalParameters["SolutionSelectionAlg"] == 0:
103 logicAnalyzer.removeLeastImportantSolutions()
104 elif globalParameters["SolutionSelectionAlg"] == 1:
105 logicAnalyzer.keepWinnerSolutions()
106 else:
107 printExit("Bad KeepLogic=%u"%globalParameters["KeepLogic"])
108
109 # print raw data
110 if getVerbosity() >= 2:
111 line = "After Removals:\n"
112 numOther = 1
113 for size in logicAnalyzer.numProblemSizes:
114 numOther *= size
115 numCols = logicAnalyzer.numProblemSizes[1]
116 if numCols == 0: numCols = 1
117 numOther //= numCols
118 for row in range(0, numOther):
119 for col in range(0, numCols):
120 for sol in range(0, logicAnalyzer.numSolutions):
121 line += "% 5.0f" % logicAnalyzer.data[sol + logicAnalyzer.numSolutions*(col + row*numCols)]
122 line += "; "
123 line += "\n"
124 print(line)
125
126 for i in range(0, len(logicAnalyzer.solutions)):
127 s = logicAnalyzer.solutions[i]
128 s["SolutionIndex"] = i
129 s["SolutionNameMin"] = getSolutionNameMin(s, splitGSU)
130 s["KernelNameMin"] = getKernelNameMin(s, splitGSU)
131 print1("(%2u) %s : %s" % (i, s["SolutionNameMin"], getSolutionNameFull(s, splitGSU)))
132
133 if enableTileSelection:
134 validSelectionSolutions = SolutionSelectionLibrary.analyzeSolutionSelection(problemType, selectionFileNameList, \
135 logicAnalyzer.numSolutionsPerGroup, logicAnalyzer.solutionGroupMap, solutionsList)
136
137 validSelectionSolutionsIncluded = []
138 validSelectionSolutionsRemainder = []
139 selectionSolutionsIds = set([])
140 for validSelectionSolution in validSelectionSolutions:
141 (validSolution, validSolutionInfo) = validSelectionSolution
142 if validSolution in logicAnalyzer.solutions:
143 validExactSolutionIndex = logicAnalyzer.solutions.index(validSolution)
144 selectionSolutionsIds.add(validExactSolutionIndex)
145 validExactSolution = logicAnalyzer.solutions[validExactSolutionIndex]
146 validSelectionSolutionsIncluded.append((validExactSolution, validSolutionInfo))
147 else:
148 validSelectionSolutionsRemainder.append(validSelectionSolution)
149
150 selectionSolutions = []
151 for i in range(0 ,len(validSelectionSolutionsIncluded)):
152 validSelectionSolution = validSelectionSolutionsIncluded[i]
153 (validSolution, validSolutionInfo) = validSelectionSolution
154 validSolution["Ideals"] = validSolutionInfo
155
156 solutionsStartIndex = len(logicAnalyzer.solutions)
157
158 for i in range(0, len(validSelectionSolutionsRemainder)):
159 validSelectionSolution = validSelectionSolutionsRemainder[i]
160 (validSolution, validSolutionInfo) = validSelectionSolution
161 selectionSolutionIndex = solutionsStartIndex + i
162 selectionSolutionsIds.add(selectionSolutionIndex)
163 validSolution["SolutionNameMin"] = getSolutionNameMin(validSolution, splitGSU)
164 validSolution["KernelNameMin"] = getKernelNameMin(validSolution, splitGSU)
165 validSolution["Ideals"] = validSolutionInfo
166 selectionSolutions.append(validSolution)
167
168 selectionSolutionsIdsList = list(selectionSolutionsIds)
169
170 ######################################
171 # Correct outliers
172 """
173 if inputParameters["SmoothOutliers"]:
174 logicAnalyzer.smoothOutliers()
175 """
176 numProblemSizes = logicAnalyzer.numProblemSizes
177 # print all 2D
178 numPermutations = 1
179 permutations = []
180 for i in range(0, logicAnalyzer.numIndices):
181 if i != logicAnalyzer.idx0 and i != logicAnalyzer.idx1:
182 numPermutations *= numProblemSizes[i]
183 #print numPermutations
184 for j in range(0, numPermutations):
185 pIdx = j
186 permutation = []
187 for i in range(0, logicAnalyzer.numIndices):
188 if i != logicAnalyzer.idx0 and i != logicAnalyzer.idx1:
189 npsi = numProblemSizes[i]
190 permutation.append(pIdx%npsi)
191 pIdx /= numProblemSizes[i]
192 permutations.append(permutation)
193 #print permutations
194 for permutation in permutations:
195 logicAnalyzer.print2D(permutation, libraryLogicPath)
196
197 ######################################
198 # Range Logic
199 if inputParameters["LibraryType"] != "FreeSize" and inputParameters["LibraryType"] != "Prediction":
200 indexOrder = logicAnalyzer.indexOrder
201 else:
202 indexOrder = None
203
204 ######################################
205 # Range Logic
206 if inputParameters["LibraryType"] != "FreeSize" and inputParameters["LibraryType"] != "Prediction":
207 rangeLogic = logicAnalyzer.enRule(0, logicAnalyzer.globalIndexRange)
208 print2("# Final Range Logic:")
209 print2(rangeLogic)
210 logicComplexity = [0]*logicAnalyzer.numIndices
211 logicAnalyzer.scoreLogicComplexity(rangeLogic, logicComplexity)
212 print2("# Range Logic Complexity: %s" % logicComplexity)
213 score = logicAnalyzer.scoreRangeForLogic( \
214 logicAnalyzer.globalIndexRange, rangeLogic)
215 print1("\n# Score: %.0f ms" % (score/1000))
216 logicAnalyzer.prepareLogic(rangeLogic) # convert indices to sizes, -1
217 else:
218 rangeLogic = None
219
220 ######################################
221 # Exact Logic
222 if inputParameters["LibraryType"] != "FreeSize" and inputParameters["LibraryType"] != "Prediction":
223 exactLogic = logicAnalyzer.exactWinners
224 print1("# Exact Logic:\n")
225 print1("%s"%exactLogic)
226 else:
227 exactLogic = None
228
229 #selectionSolutionsIdsList = list(selectionSolutionsIds)
230 return (problemType, logicAnalyzer.solutions, indexOrder, \
231 exactLogic, rangeLogic, selectionSolutions, selectionSolutionsIdsList, logicAnalyzer.perfMetric, \
232 None)
233
234
235
236 ################################################################################
237 # LogicAnalyzer
238 ################################################################################
239 class LogicAnalyzer:
240
241 ##############################################################################
242 ##############################################################################
243 ###
244 ### Entry / Top-Level Functions
245 ###
246 ##############################################################################
247 ##############################################################################
248
249 ##############################################################################
250 # ENTRY: Init
251 ##############################################################################
252 def __init__(self, problemType, problemSizesList, solutionsList, \
253 dataFileNameList, inputParameters, splitGSU: bool):
254
255 # parameters
256 self.parameters = inputParameters
257 self.splitGSU = splitGSU
258
259 # problem type
260 self.problemType = problemType
261 self.idx0 = self.problemType["Index0"]
262 self.idx1 = self.problemType["Index1"]
263 self.idxU = self.problemType["IndexUnroll"]
264
265 # merge solutions from size groups
266 # solutions needs to be a set, and offset needs to be mapping
267 print1("# Merging Solutions:")
268 self.numSolutionsPerGroup = []
269 self.solutionGroupMap = []
270 self.solutions = []
271 solutionsHash = {} # for accelerating lookups
272
273 totalSolutions = 0
274 for solutionGroupIdx in range(0, len(solutionsList)):
275 solutionGroup = solutionsList[solutionGroupIdx]
276 totalSolutions += len(solutionGroup)
277 progressBar = ProgressBar(totalSolutions)
278 for solutionGroupIdx in range(0, len(solutionsList)):
279 solutionGroup = solutionsList[solutionGroupIdx]
280 self.numSolutionsPerGroup.append(len(solutionGroup))
281 self.solutionGroupMap.append({})
282 for solutionIdx in range(0, len(solutionGroup)):
283 solution = solutionGroup[solutionIdx]
284 if not solution in solutionsHash:
285 sIdx = len(self.solutions) # the one we are about to add
286 self.solutions.append(solution)
287 solutionsHash[solution] = sIdx
288 else:
289 sIdx = solutionsHash[solution]
290
291 self.solutionGroupMap[solutionGroupIdx][solutionIdx] = sIdx
292 progressBar.increment()
293 self.numSolutions = len(self.solutions)
294 self.solutionNames = []
295 self.solutionTiles = []
296 for solution in self.solutions:
297 self.solutionNames.append(getSolutionNameMin(solution, self.splitGSU))
298 self.solutionTiles.append("%ux%u"%(solution["MacroTile0"], solution["MacroTile1"]))
299 self.flopsPerMac = self.problemType["DataType"].flopsPerMac()
300
301 # merge problem sizes from size groups
302 #self.numIndices = len(problemSizesList[0].numProblemSizes)
303 self.numIndices = self.problemType["TotalIndices"] + problemType["NumIndicesLD"]
304 unifiedProblemSizes = []
305 for i in range(0, self.numIndices):
306 unifiedProblemSizes.append(set())
307 self.exactProblemSizes = set()
308 self.rangeProblemSizes = set()
309 for problemSizes in problemSizesList:
310 # add exacts
311 for problem in problemSizes.exacts:
312 self.exactProblemSizes.add(tuple(problem.sizes))
313
314 # add ranges
315 #print "ProblemSizes", problemSizes.sizes
316 #FIXME-problem
317 self.rangeProblemSizes.update([tuple(problem.sizes) for problem in problemSizes.problems])
318 for rangeSize in problemSizes.ranges:
319 # Treat ranges as pile of exacts:
320 for rsize in rangeSize.problemSizes:
321 self.exactProblemSizes.add(tuple(rsize))
322 for i in range(0, len(unifiedProblemSizes)):
323 unifiedProblemSizes[i] = sorted(list(unifiedProblemSizes[i]))
324 print2("UnifiedProblemSizes: %s" % unifiedProblemSizes)
325 print2("ExactProblemSizes: %s" % self.exactProblemSizes)
326 print2("RangeProblemSizes: %s" % self.rangeProblemSizes)
327
328 # problem size index <-> size
329 self.problemSizeToIndex = []
330 self.problemIndexToSize = []
331 self.numProblemSizes = []
332 for i in range(0, self.numIndices):
333 self.problemSizeToIndex.append({})
334 self.problemIndexToSize.append([])
335 for j in range(0, len(unifiedProblemSizes[i])):
336 size = unifiedProblemSizes[i][j]
337 self.problemSizeToIndex[i][size] = j
338 self.problemIndexToSize[i].append(size)
339 self.numProblemSizes.append(len(unifiedProblemSizes[i]))
340 print1("# NumProblemSizes: %s" % self.numProblemSizes)
341
342 # total size of data array
343 self.totalProblems = 1
344 for numProblems in self.numProblemSizes:
345 self.totalProblems *= numProblems
346 self.totalSize = self.totalProblems * self.numSolutions
347 print2("TotalProblems: %u" % self.totalProblems)
348 print2("TotalSolutions: %u" % self.numSolutions)
349 print2("TotalSize: %u" % self.totalSize)
350 # data is a 2D array [problemIdx][solutionIdx] which stores perf data in gflops for
351 # the specified solution
352 self.data = array.array('f', [-2]*self.totalSize)
353
354 # Each entry in exactWinners is a 2D array [solutionIdx, perf]
355 self.exactWinners = {}
356
357 """
358 # map problem sizes -> index
359 self.problemSizeToIndex = []
360 self.problemIndexToSize = []
361 sizedIdx = 0
362 mappedIdx = 0
363 for i in range(0, self.numIndices):
364 self.problemSizeToIndex.append({})
365 self.problemIndexToSize.append([])
366 if self.problemSizes.indexIsSized[i]:
367 index = self.problemSizes.indicesSized[sizedIdx]
368 sizedIdx += 1
369 else:
370 index = self.problemSizes.indicesSized[ \
371 self.problemSizes.indicesMapped[mappedIdx]]
372 mappedIdx += 1
373 currentSize = index[0]
374 currentStride = index[1]
375 idx = 0
376 while currentSize <= index[3]:
377 self.problemSizeToIndex[i][currentSize] = idx
378 self.problemIndexToSize[i].append(currentSize)
379 currentSize += currentStride
380 currentStride += index[2]
381 idx += 1
382 """
383 #self.rangeIndicesFree = range(0, self.problemType["NumIndicesC"])
384 #self.rangeIndicesSummation = range(self.problemType["NumIndicesC"], \
385 # self.problemType["TotalIndices"])
386 self.indexOrder = self.recommendedIndexOrder()
387 print2("IndexOrder: %s" % self.indexOrder)
388 self.globalIndexRange = []
389 for i in range(0, self.numIndices):
390 self.globalIndexRange.append([0, self.numProblemSizes[i]])
391 self.problemIndicesForGlobalRange \
392 = self.problemIndicesForRange(self.globalIndexRange)
393 self.tab = [""]*self.numIndices
394
395 ######################################
396 # Read Data From CSV
397 for fileIdx in range(0, len(dataFileNameList)):
398 dataFileName = dataFileNameList[fileIdx]
399 self.addFromCSV(dataFileName, self.numSolutionsPerGroup[fileIdx], \
400 self.solutionGroupMap[fileIdx])
401
402
403
404 #print self.data
405 # map exact problem sizes to solutions
406 print1("# ExactWinners: %s" % self.exactWinners)
407
408
409 ##############################################################################
410 # ENTRY: Add From CSV
411 ##############################################################################
412 def addFromCSV(self, dataFileName, numSolutions, solutionMap):
413
414 # open file
415 print("reading datafile", dataFileName)
416 try:
417 dataFile = open(dataFileName, "r")
418 except IOError:
419 printExit("Can't open \"%s\" to get data" % dataFileName )
420
421 # column indices
422 csvFile = csv.reader(dataFile)
423 problemSizeStartIdx = 1
424 # notice that for OperationType != GEMM, the numIndices = 0
425 totalSizeIdx = problemSizeStartIdx + self.numIndices
426
427 # need to take care if the loaded csv is the export-winner-version
428 csvHasWinner = "_CSVWinner" in dataFileName
429 csvHasWinnerColumn = True
430
431 # iterate over rows
432 rowIdx = 0
433 deviceMaxFreq = None
434 for row in csvFile:
435 rowIdx+=1
436 if rowIdx == 1:
437 # get unit (gflops or gflops/cu) of benchmark data
438 perfUnit = row[0]
439 if perfUnit == "GFlops":
440 self.perfMetric = "DeviceEfficiency"
441 elif perfUnit == "GFlopsPerCU":
442 self.perfMetric = "CUEfficiency"
443 else:
444 printWarning("Performance unit %s in %s is unrecognized: assuming GFlops (device efficiency)" % (perfUnit, dataFileName))
445 self.perfMetric = "DeviceEfficiency"
446
447 if csvHasWinner:
448 try:
449 # These two columns only appear when using WinnerCSV
450 columnOfWinnerGFlops = row.index(" WinnerGFlops")
451 columnOfWinnerIdx = row.index(" WinnerIdx")
452 except ValueError as e:
453 csvHasWinnerColumn = False
454 print1(f"Error: Could not find WinnerGFlops or WinnerIdx column in CSV file: {e}")
455
456 # get the length of each row, and derive the first column of the solution instead of using wrong "solutionStartIdx = totalSizeIdx + 1"
457 rowLength = len(row)
458 solutionStartIdx = rowLength - numSolutions
459 continue
460 else:
461 #if len(row) < rowLength:
462 # printWarning("CSV File %s row %u doesn't have %u elements; ignoring remainer of file." \
463 # % (dataFileName, rowIdx, rowLength) )
464 # break
465
466 # get problem size
467 problemSize = []
468 for i in range(problemSizeStartIdx, totalSizeIdx):
469 problemSize.append(int(row[i]))
470 problemSize = tuple(problemSize)
471 # Exact Problem Size
472 if problemSize in self.exactProblemSizes:
473
474 if csvHasWinner and csvHasWinnerColumn:
475 # Faster. Get the winner info from csv directly, avoid an extra loop
476 winnerGFlops = float(row[columnOfWinnerGFlops])
477 winnerIdx = int(row[columnOfWinnerIdx])
478 else:
479 # Old code. TODO - Can we get rid of this in the future?
480 # solution gflops
481 solutionIdx = 0
482 winnerIdx = -1
483 winnerGFlops = -1
484 for i in range(solutionStartIdx, rowLength):
485 gflops = float(row[i])
486 if gflops > winnerGFlops:
487 winnerIdx = solutionIdx
488 winnerGFlops = gflops
489 solutionIdx += 1
490
491 if globalParameters["UseEffLike"]:
492 if not deviceMaxFreq:
493 deviceMaxFreq = read_max_freq()
494
495 # calculate effLike
496 # effLike = winnerGFlops / Frequency(MHz)
497 try:
498 if not deviceMaxFreq or deviceMaxFreq <= 0 or math.isnan(deviceMaxFreq):
499 performance_metric = round(float(winnerGFlops))
500 print("Error when retrieving device frequency, fall back to winnerGFlops.")
501 else:
502 performance_metric = round(float(winnerGFlops) / deviceMaxFreq, 2)
503 except:
504 print1("Error: Could not convert winnerGFlops to float.")
505 performance_metric = float('nan')
506 else:
507 try:
508 performance_metric = float(winnerGFlops)
509 except:
510 print1("Error: Could not convert winnerGFlops to float.")
511 performance_metric = float('nan')
512
513 if winnerIdx != -1:
514 if problemSize in self.exactWinners:
515 if winnerGFlops > self.exactWinners[problemSize][1]:
516 #print "update exact", problemSize, "CSV index=", winnerIdx, self.exactWinners[problemSize], "->", solutionMap[winnerIdx], winnerGFlops
517 self.exactWinners[problemSize] = [solutionMap[winnerIdx], performance_metric]
518 else:
519 self.exactWinners[problemSize] = [solutionMap[winnerIdx], performance_metric]
520 #print "new exact", problemSize, "CSV index=", winnerIdx, self.exactWinners[problemSize]
521
522 # Range Problem Size
523 elif problemSize in self.rangeProblemSizes:
524 problemIndices = []
525 for i in range(0, self.numIndices):
526 problemIndices.append(self.problemSizeToIndex[i][problemSize[i]])
527 serialIdx = self.indicesToSerial(0, problemIndices)
528 # solution gflops
529 solutionIdx = 0
530 for i in range(solutionStartIdx, rowLength):
531 gflops = float(row[i])
532 self.data[serialIdx+solutionMap[solutionIdx]] = gflops
533 solutionIdx += 1
534
535 # Unknown Problem Size
536 else:
537 printExit("Huh? %s has ProblemSize %s which isn't in its yaml" \
538 % ( dataFileName, list(problemSize)) )
539 #print self.data
540
541
542 ##############################################################################
543 # ENTRY: Remove Invalid Solutions
544 ##############################################################################
545 def removeInvalidSolutions(self):
546 #problemIndices = [0]*self.numIndices
547 allSolutionValid = False
548 while not allSolutionValid:
549 invalidIdx = -1
550 for problemIndices in self.problemIndicesForGlobalRange:
551 problemSerial = self.indicesToSerial(0, problemIndices)
552 for solutionIdx in range(0, self.numSolutions):
553 gflops = self.data[problemSerial+solutionIdx]
554 if gflops == 0:
555 invalidIdx = solutionIdx
556 break
557 if invalidIdx >= 0:
558 print1("# Removing Invalid Solution: %u %s" \
559 % (invalidIdx, self.solutionNames[invalidIdx]) )
560 self.removeSolution(invalidIdx)
561 else:
562 allSolutionValid = True
563
564 ##############################################################################
565 # ENTRY: Dereference ProblemType and Solutions
566 ##############################################################################
567 def deReferenceSolutions(self):
568 self.solutions = deepcopy(self.solutions)
569
570 ##############################################################################
571 # ENTRY: Original KeepLogic algorithm: Remove Least Important Solutions,
572 # one at a time. Stop when leastImportantSolution indicates no more
573 # solutions can be removed, which appears to be when the solution
574 # is used by an exact problem or is the only possible solution for some
575 # problem or doesn't improve the a solution by > SolutionImportanceMin%
576 ##############################################################################
577 def removeLeastImportantSolutions(self):
578 # Remove least important solutions
579 start = time.time()
580 while len(self.solutions) > 1:
581 lisTuple = self.leastImportantSolution()
582 if lisTuple != None:
583 lisIdx = lisTuple[0]
584 lisPercSaved = lisTuple[1]
585 lisPercWins = lisTuple[2]
586 lisPercTime = lisTuple[3]
587 if lisPercSaved < self.parameters["SolutionImportanceMin"] or lisPercWins == 0:
588 print1("# Removing Unimportant Solution %u/%u: %s ( %f%% wins, %f%% ms time, %f%% ms saved" \
589 % (lisIdx, self.numSolutions, self.solutionNames[lisIdx], 100*lisPercWins, 100*lisPercTime, 100*lisPercSaved) )
590 self.removeSolution(lisIdx)
591 continue
592 else:
593 break
594 else: # no more lis, remainders are exact winner
595 break
596 stop = time.time()
597 print("removeLeastImportantSolutions elapsed time = %.1f secs" % (stop - start))
598
599
600 ##############################################################################
601 # ENTRY: Alternate KeepLogic algorithm that keeps the fastest for each
602 # exact and range. Other solutions are removed.
603 ##############################################################################
604 def keepWinnerSolutions(self):
605
606 # solution indexes for the winners:
607 winners = set()
608
609 solutionImportance = []
610 for i in range(0, self.numSolutions):
611 solutionImportance.append([i, 0, 0, 0, False])
612 problemSizes = [0]*self.numIndices
613 print("problemIndicesForGlobalRange", self.problemIndicesForGlobalRange)
614 for problemIndices in self.problemIndicesForGlobalRange:
615 for i in range(0, self.numIndices):
616 problemSizes[i] = self.problemIndexToSize[i][problemIndices[i]]
617 totalFlops = self.flopsPerMac
618 for size in problemSizes:
619 totalFlops *= size
620
621 problemSerial = self.indicesToSerial(0, problemIndices)
622 winnerIdx = -1
623 winnerGFlops = -1e6
624 for solutionIdx in range(0, self.numSolutions):
625 solutionSerialIdx = problemSerial + solutionIdx
626 solutionGFlops = self.data[solutionSerialIdx]
627 if solutionGFlops > winnerGFlops:
628 winnerIdx = solutionIdx
629 winnerGFlops = solutionGFlops
630
631 winners.add(winnerIdx)
632
633 # Always keep the exact sizes:
634 for exactProblem in self.exactWinners:
635 winnerIdx = self.exactWinners[exactProblem][0]
636 #print "keepWinnerSolution adding exact", exactProblem, winnerIdx
637 winners.add(winnerIdx)
638
639 print("Winners", winners)
640 self.pruneSolutions(winners)
641
642
643
644 ##############################################################################
645 # ENTRY: En Rule
646 # currentIndexIndex = 0, 1, 2, 3...
647 # currentIndexRange will have only 1 size for prior indices (unless initial)
648 #
649 # Rule:
650 # [128, [
651 # [64, [
652 # [16, 0],
653 # [2880,1]
654 # ]
655 # ],
656 # [96, [
657 # [16, 0],
658 # [64, 1]
659 # ]
660 # ]
661 # ]
662 # ], another
663 #
664 #
665 ##############################################################################
666 def enRule(self, currentIndexIndex, currentIndexRange):
667 cii = currentIndexIndex
668 if currentIndexIndex == 0:
669 self.tab[cii] = "[] "
670 elif currentIndexIndex == 1:
671 self.tab[cii] = "[%2u] " % ( \
672 currentIndexRange[self.indexOrder[0]][0])
673 elif currentIndexIndex == 2:
674 self.tab[cii] = "[%2u,%2u] " % ( \
675 currentIndexRange[self.indexOrder[0]][0], \
676 currentIndexRange[self.indexOrder[1]][0])
677 elif currentIndexIndex == 3:
678 self.tab[cii] = "[%2u,%2u,%2u] " % ( \
679 currentIndexRange[self.indexOrder[0]][0], \
680 currentIndexRange[self.indexOrder[1]][0], \
681 currentIndexRange[self.indexOrder[2]][0])
682 elif currentIndexIndex == 4:
683 self.tab[cii] = "[%2u,%2u,%2u,%2u] " % ( \
684 currentIndexRange[self.indexOrder[0]][0], \
685 currentIndexRange[self.indexOrder[1]][0], \
686 currentIndexRange[self.indexOrder[2]][0], \
687 currentIndexRange[self.indexOrder[3]][0])
688 tab = self.tab[cii]
689 if getVerbosity() == 1:
690 stdout.write("\n%s"%tab)
691 currentIndex = self.indexOrder[currentIndexIndex]
692 print2("%senRule(%s)" % (tab, currentIndexRange))
693 nextIndexIndex = currentIndexIndex+1
694 nextIndexRange = deepcopy(currentIndexRange)
695 isLastIndex = currentIndexIndex == self.numIndices-1
696 ruleList = []
697
698 ########################################
699 # SingleProblem
700 ########################################
701 if currentIndexRange[currentIndex][1] \
702 - currentIndexRange[currentIndex][0] == 1:
703
704 ########################################
705 # SingleProblem & LastIndex
706 # this is last index, so just return fastest solution
707 ########################################
708 if isLastIndex:
709 print2("%sSingleProblem & LastIndex" % tab)
710 winnerIdx = self.winnerForRange(currentIndexRange)
711 if winnerIdx < 0:
712 print2("%sSingleProblem & LastIndex :: winnerIdx<0; returning" % (tab) )
713 return None
714 ruleList.append([-1, winnerIdx])
715 if getVerbosity() == 1:
716 stdout.write("%")
717
718 ########################################
719 # SingleProblem & NotLastIndex
720 # this isn't last index, so just recursively return next index
721 ########################################
722 else:
723 print2("%sSingleProblem & NotLastIndex" % tab)
724 # % (tab, nextIndexRange) )
725 nextRule = self.enRule(nextIndexIndex, nextIndexRange)
726 if nextRule == None:
727 print2("%sSingleProblem & NotLastIndex :: nextRule==None; returning" % (tab) )
728 return None
729 rule = [ -1, nextRule ]
730 ruleList.append(rule)
731 if getVerbosity() == 1:
732 stdout.write("%")
733
734 else:
735 ########################################
736 # MultiProblem
737 # Create Initial Rule
738 ########################################
739
740 if isLastIndex:
741 ########################################
742 # MultiProblem & LastIndex
743 # InitialRule using winnerForRange()
744 ########################################
745 print2("%sMultiProblem & LastIndex" % tab)
746 winnerIdx = -1
747 for problemIndex in range(currentIndexRange[currentIndex][0], \
748 currentIndexRange[currentIndex][1]):
749 nextIndexRange[currentIndex][0] = problemIndex
750 nextIndexRange[currentIndex][1] = problemIndex+1
751 winnerIdx = self.winnerForRange(nextIndexRange)
752 initialRule = [ currentIndexRange[currentIndex][0], winnerIdx]
753 if winnerIdx >= 0:
754 break
755 if winnerIdx < 0:
756 print2("%sMultiProblem & LastIndex :: winnerIdx<0; returning" % (tab) )
757 return None
758
759 else:
760 ########################################
761 # MultiProblem & NotLastIndex
762 # InitialRule using enRule()
763 ########################################
764 print2("%sMultiProblem & NotLastIndex" % tab)
765
766 # create initial rule
767 winnerIdx = -1
768 nextRule = None
769 for problemIndex in range(currentIndexRange[currentIndex][0], \
770 currentIndexRange[currentIndex][1]):
771 nextIndexRange[currentIndex][0] = problemIndex
772 nextIndexRange[currentIndex][1] = problemIndex+1
773 nextRule = self.enRule(nextIndexIndex, nextIndexRange)
774 # break when found initial rule
775 if nextRule != None:
776 break
777
778 if nextRule == None:
779 printWarning("%sMultiProblem & NotLastIndex :: nextRule==None; returning" % (tab) )
780 return None
781 initialRule = [ currentIndexRange[currentIndex][0], nextRule ]
782 ruleList.append(initialRule)
783 print2("%sMultiProblem::InitialRuleList=%s" % (tab, ruleList))
784 if getVerbosity() == 1:
785 stdout.write("#")
786
787 ########################################
788 # MultiProblem
789 # Append Rules to Initial Rule
790 ########################################
791 print2("%sMultiProblem::Improving Rule" % tab)
792 for problemIndex in range(currentIndexRange[currentIndex][0]+1, \
793 currentIndexRange[currentIndex][1]):
794 nextIndexRange[currentIndex][0] = problemIndex
795 nextIndexRange[currentIndex][1] = problemIndex+1
796 priorRule = ruleList[len(ruleList)-1]
797 priorRuleForSize = deepcopy(priorRule)
798 priorRuleForSize[0] = problemIndex
799
800 if isLastIndex:
801 ########################################
802 # nextRule using winnersForRange()
803 winnerIdx = self.winnerForRange(nextIndexRange)
804 print2("%sMultiProblem::ImproveRule[%u]::LastIndex::WinnerIdx=%u for %s" % (tab, problemIndex, winnerIdx, nextIndexRange))
805 # if no solutions benchmarked for this problem size, continue
806 if winnerIdx < 0:
807 ruleList[len(ruleList)-1][0] = problemIndex # NO_UPDATE
808 print2("%sUpdating range b/c None" % tab)
809 if getVerbosity() == 1:
810 stdout.write(" ")
811 continue
812 else:
813 candidateRule = [ problemIndex, winnerIdx]
814 else:
815 ########################################
816 # nextRule using enRule()
817 nextRule = self.enRule(nextIndexIndex, nextIndexRange)
818 print2("%sMultiProblem::ImproveRule[%u]::NotLastIndex::NextRule=%s for %s; %s" % (tab, problemIndex, nextRule, nextIndexIndex, nextIndexRange))
819 if nextRule == None:
820 ruleList[len(ruleList)-1][0] = problemIndex # NO_UPDATE
821 print2("%sUpdating b/c None" % tab)
822 if getVerbosity() == 1:
823 stdout.write(" ")
824 continue
825 else:
826 candidateRule = [ problemIndex, nextRule ]
827
828 ########################################
829 # candidate same as prior
830 if candidateRule[1] == priorRule[1]:
831 print2("%sCandidateRule==PriorRule; just updating prior" % (tab))
832 ruleList[len(ruleList)-1][0] = problemIndex # NO_UPDATE
833 if getVerbosity() == 1:
834 stdout.write(" ")
835 continue
836
837 ########################################
838 # compare candidate vs prior
839 else:
840 print2("%sCandidateRule!=PriorRule; appending rule assuming its better" % (tab))
841
842 """
843 priorRuleScore = self.scoreRangeForLogic(nextIndexRange, \
844 [priorRuleForSize])
845 logicComplexity = [0]*self.numIndices
846 self.scoreLogicComplexity( \
847 [priorRuleForSize], logicComplexity)
848 priorRuleScore += self.parameters["BranchPenalty"] \
849 * sum(logicComplexity)
850 # score candidate
851 candidateRuleScore = self.scoreRangeForLogic(nextIndexRange, \
852 [candidateRule])
853 #print "CRS", candidateRuleScore
854 logicComplexity = [0]*self.numIndices
855 self.scoreLogicComplexity( \
856 [candidateRule], logicComplexity)
857 candidateRuleScore += self.parameters["BranchPenalty"] \
858 * sum(logicComplexity)
859 candidateRuleScore += self.parameters["BranchPenalty"] # penalize
860 candidateFaster = candidateRuleScore < priorRuleScore
861 print2("%sP[%2u]: %s %s~%.0fus < %s~%.0fus" % (tab, problemIndex, \
862 "wins" if candidateFaster else "same", \
863 candidateRule, candidateRuleScore, priorRuleForSize, \
864 priorRuleScore ))
865 """
866
867 ########################################
868 # candidate wins
869 #print candidateRuleScore, priorRuleScore
870 if True: # or candidateRuleScore < priorRuleScore:
871 ruleList.append(candidateRule)
872 print2("%sAppending b/c Different" % tab)
873 if getVerbosity() == 1:
874 stdout.write("#")
875
876 ########################################
877 # prior wins
878 else:
879 print2("%sPrior Rule Wins" % tab)
880 if getVerbosity() == 1:
881 stdout.write(".")
882 ruleList[len(ruleList)-1][0] = problemIndex # NO_UPDATE
883
884 print2("%sReturning RuleList: %s" % (tab, ruleList))
885 return ruleList
886
887
888
889 ##############################################################################
890 ##############################################################################
891 ###
892 ### Mid-Level Functions
893 ###
894 ##############################################################################
895 ##############################################################################
896
897
898
899 ##############################################################################
900 # Prepare Logic
901 # convert threshold indices to sizes
902 # last threshold = -1
903 ##############################################################################
904 def prepareLogic(self, logic):
905 depth = self.getLogicDepth(logic)
906 if depth == 0: return
907 indexIndex = self.numIndices - depth
908 index = self.indexOrder[indexIndex]
909 for i in range(0, len(logic)):
910 if i == len(logic)-1:
911 logic[i][0] = -1
912 else:
913 logic[i][0] = self.problemIndexToSize[index][logic[i][0]]
914 self.prepareLogic(logic[i][1])
915
916
917 ##############################################################################
918 # Print2D
919 ##############################################################################
920 def print2D(self, indices, libraryLogicPath):
921 indicesIdx = 0
922 problemIndices = []
923 for i in range(0, self.numIndices):
924 if i == self.idx0:
925 problemIndices.append(-1)
926 elif i == self.idx1:
927 problemIndices.append(-1)
928 else:
929 problemIndices.append(indices[indicesIdx])
930 indicesIdx += 1
931
932 winnerIndices = []
933 w = "winner"
934 g = "gflops"
935 f = "faster"
936 s = "second"
937 sss = []
938 for sIdx in range(0, self.numSolutions):
939 sss.append("Sol[%u]" % sIdx)
940 for j in range(0, self.numProblemSizes[1]):
941 w += ",%4u" % self.problemIndexToSize[1][j]
942 g += ",%4u" % self.problemIndexToSize[1][j]
943 f += ",%4u" % self.problemIndexToSize[1][j]
944 s += ",%4u" % self.problemIndexToSize[1][j]
945 for sIdx in range(0, self.numSolutions):
946 sss[sIdx] += ",%4u" % self.problemIndexToSize[1][j]
947 w += "\n"
948 g += "\n"
949 f += "\n"
950 s += "\n"
951 for sIdx in range(0, self.numSolutions):
952 sss[sIdx] += "\n"
953 for i in range(0, self.numProblemSizes[0]):
954 problemIndices[self.idx0] = i
955 w += "%4u" % self.problemIndexToSize[0][i]
956 g += "%4u" % self.problemIndexToSize[0][i]
957 f += "%4u" % self.problemIndexToSize[0][i]
958 s += "%4u" % self.problemIndexToSize[0][i]
959 for sIdx in range(0, self.numSolutions):
960 sss[sIdx] += "%4u" % self.problemIndexToSize[0][i]
961 for j in range(0, self.numProblemSizes[1]):
962 problemIndices[self.idx1] = j
963 problemSerial = self.indicesToSerial(0, problemIndices)
964 for sIdx in range(0, self.numSolutions):
965 sss[sIdx] += ",%f" % self.data[problemSerial+sIdx]
966 winnerIdx = 0
967 secondIdx = 1
968 winnerGFlops = self.data[problemSerial+0]
969 secondGFlops = 1e-9
970 for solutionIdx in range(1, self.numSolutions):
971 solutionSerialIdx = problemSerial + solutionIdx
972 solutionGFlops = self.data[solutionSerialIdx]
973 if solutionGFlops > winnerGFlops:
974 secondIdx = winnerIdx
975 secondGFlops = winnerGFlops
976 winnerIdx = solutionIdx
977 winnerGFlops = solutionGFlops
978 elif solutionGFlops > secondGFlops:
979 secondIdx = solutionIdx
980 secondGFlops = solutionGFlops
981
982 if winnerIdx not in winnerIndices:
983 winnerIndices.append(winnerIdx)
984 w += ",%4u" % winnerIdx
985 g += ",%f" % winnerGFlops
986 f += ",%f" % (winnerGFlops/secondGFlops)
987 s += ",%4u" % (secondIdx)
988 w += "\n"
989 g += "\n"
990 f += "\n"
991 s += "\n"
992 for sIdx in range(0, self.numSolutions):
993 sss[sIdx] += "\n"
994
995 w += "\n\n"
996 g += "\n\n"
997 f += "\n\n"
998 s += "\n\n"
999 for sIdx in range(0, self.numSolutions):
1000 sss[sIdx] += "\n\n"
1001 w += "Winners:\n"
1002 for winnerIdx in winnerIndices:
1003 w += "%4u, %s, %s\n" % (winnerIdx, self.solutionTiles[winnerIdx], self.solutionNames[winnerIdx])
1004
1005 printFileName = "Winner2D"
1006 for idx in indices:
1007 printFileName += "_%u" % idx
1008 printFileName += ".csv"
1009 printFile = open(os.path.join(libraryLogicPath, printFileName), "w")
1010 printFile.write( w )
1011 printFile.write( g )
1012 printFile.write( f )
1013 printFile.write( s )
1014 for sIdx in range(0, self.numSolutions):
1015 printFile.write( sss[sIdx] )
1016 printFile.close()
1017
1018
1019 ##############################################################################
1020 # Least Important Solution
1021 ##############################################################################
1022 def leastImportantSolution(self):
1023 solutionImportance = []
1024 for i in range(0, self.numSolutions):
1025 solutionImportance.append([i, 0, 0, 0, False])
1026 problemSizes = [0]*self.numIndices
1027 totalSavedMs = 0
1028 totalExecMs = 0
1029 totalWins = 0
1030 for problemIndices in self.problemIndicesForGlobalRange:
1031 for i in range(0, self.numIndices):
1032 problemSizes[i] = self.problemIndexToSize[i][problemIndices[i]]
1033 totalFlops = self.flopsPerMac
1034 for size in problemSizes:
1035 totalFlops *= size
1036
1037 problemSerial = self.indicesToSerial(0, problemIndices)
1038 winnerIdx = -1
1039 winnerGFlops = -1e6
1040 secondGFlops = -1e9
1041 for solutionIdx in range(0, self.numSolutions):
1042 solutionSerialIdx = problemSerial + solutionIdx
1043 solutionGFlops = self.data[solutionSerialIdx]
1044 if solutionGFlops > winnerGFlops:
1045 secondGFlops = winnerGFlops
1046 winnerIdx = solutionIdx
1047 winnerGFlops = solutionGFlops
1048 elif solutionGFlops > secondGFlops:
1049 secondGFlops = solutionGFlops
1050
1051 winnerTimeMs = totalFlops / winnerGFlops / 1000000.0
1052 secondTimeMs = totalFlops / secondGFlops / 1000000.0
1053 if winnerGFlops > 0 and secondGFlops > 0:
1054 solutionImportance[winnerIdx][1] += (secondTimeMs - winnerTimeMs)
1055 totalSavedMs += secondTimeMs - winnerTimeMs
1056 if winnerGFlops > 0:
1057 solutionImportance[winnerIdx][2] += 1
1058 solutionImportance[winnerIdx][3] += winnerTimeMs
1059 totalExecMs += winnerTimeMs
1060 totalWins += 1
1061 if secondGFlops <= 0:
1062 solutionImportance[winnerIdx][4] = True # this is only valid solution for this problem size, keep it
1063
1064
1065 # print data before sorting
1066 for i in range(0, self.numSolutions):
1067 print2("[%2u] %s: %e saved, %u wins, %u time, %s" \
1068 % (solutionImportance[i][0], \
1069 self.solutionNames[solutionImportance[i][0]], \
1070 solutionImportance[i][1], \
1071 solutionImportance[i][2], \
1072 solutionImportance[i][3], \
1073 "singular" if solutionImportance[i][4] else "" ) )
1074
1075 totalSavedMs = max(1, totalSavedMs)
1076 solutionImportance.sort(key=lambda x: x[1])
1077 for i in range(0, self.numSolutions):
1078 solutionIdx = solutionImportance[i][0]
1079 canRemove = not solutionImportance[i][4] # don't remove if is only win for any size
1080 for exactProblem in self.exactWinners:
1081 winnerIdx = self.exactWinners[exactProblem][0]
1082 if solutionIdx == winnerIdx: # exact winners are important
1083 canRemove = False
1084 break
1085 if canRemove:
1086 idx = solutionImportance[i][0]
1087 if totalSavedMs > 0:
1088 percSaved = 1.0 * solutionImportance[i][1] / totalSavedMs
1089 else:
1090 percSaved = 0
1091 if totalWins > 0:
1092 percWins = 1.0 * solutionImportance[i][2] / totalWins
1093 else:
1094 percWins = 0
1095 if totalExecMs > 0:
1096 percTime = 1.0 * solutionImportance[i][3] / totalExecMs
1097 else:
1098 percTime = 0
1099 return ( idx, percSaved, percWins, percTime )
1100 return None
1101
1102
1103 ##############################################################################
1104 # Remove Solution
1105 ##############################################################################
1106 def removeSolution(self, removeSolutionIdx):
1107
1108 # temporarily move current to old
1109 oldSolutions = deepcopy(self.solutions)
1110 oldNumSolutions = self.numSolutions
1111 oldData = deepcopy(self.data)
1112
1113 # update solutions
1114 self.solutions = []
1115 for i in range(0, oldNumSolutions):
1116 if i != removeSolutionIdx:
1117 self.solutions.append(oldSolutions[i])
1118 self.solutionNames = []
1119 self.solutionTiles = []
1120 for solution in self.solutions:
1121 self.solutionNames.append(getSolutionNameMin(solution, self.splitGSU))
1122 self.solutionTiles.append("%ux%u"%(solution["MacroTile0"], \
1123 solution["MacroTile1"]))
1124 self.numSolutions = len(self.solutions)
1125
1126 # update data
1127 self.totalSize = self.totalProblems * self.numSolutions
1128 self.data = array.array('f', [0]*self.totalSize)
1129 for problemIndex in range(0, self.totalProblems):
1130 newSolutionIdx = 0
1131 for oldSolutionIdx in range(0, oldNumSolutions):
1132 if oldSolutionIdx != removeSolutionIdx:
1133 self.data[problemIndex*self.numSolutions+newSolutionIdx] \
1134 = oldData[problemIndex*oldNumSolutions+oldSolutionIdx]
1135 newSolutionIdx += 1
1136
1137 # update exact Winners
1138 for problemSize in self.exactWinners:
1139 if self.exactWinners[problemSize][0] >= removeSolutionIdx:
1140 self.exactWinners[problemSize][0] -= 1
1141
1142
1143 ##############################################################################
1144 # Prune a list of solutions, keeping only the indices specified in
1145 # keepSolutions. keepSolutions is a set not a list
1146 ##############################################################################
1147 def pruneSolutions(self, keepSolutions):
1148
1149 removeSolutionIdxList = []
1150 solutionMapNewToOld = [] # dense mapping
1151 solutionMapOldToNew = [-1] * self.numSolutions
1152
1153 # temporarily move current to old
1154 oldSolutions = deepcopy(self.solutions)
1155 oldNumSolutions = self.numSolutions
1156 oldData = deepcopy(self.data)
1157 # update solutions
1158 self.solutions = []
1159 for i in range(0, oldNumSolutions):
1160 if i in keepSolutions:
1161 solutionMapNewToOld.append(i)
1162 solutionMapOldToNew[i] = len(self.solutions)
1163 self.solutions.append(oldSolutions[i])
1164 else:
1165 removeSolutionIdxList.append(i)
1166
1167 self.solutionNames = []
1168 self.solutionTiles = []
1169 for solution in self.solutions:
1170 self.solutionNames.append(getSolutionNameMin(solution, self.splitGSU))
1171 self.solutionTiles.append("%ux%u"%(solution["MacroTile0"], \
1172 solution["MacroTile1"]))
1173 self.numSolutions = len(self.solutions)
1174
1175 # update data
1176 self.totalSize = self.totalProblems * self.numSolutions
1177 self.data = array.array('f', [0]*self.totalSize)
1178 for problemIndex in range(0, self.totalProblems):
1179 for newSolutionIdx in range(0, self.numSolutions):
1180 oldSolutionIdx = solutionMapNewToOld[newSolutionIdx]
1181 self.data[problemIndex*self.numSolutions+newSolutionIdx] \
1182 = oldData[problemIndex*oldNumSolutions+oldSolutionIdx]
1183
1184 # update exact Winners
1185 for problemSize in self.exactWinners:
1186 #print "prune updating exacWinner", problemSize, \
1187 # "from ", self.exactWinners[problemSize][0], \
1188 # "to ", solutionMapOldToNew[self.exactWinners[problemSize][0]]
1189 self.exactWinners[problemSize][0] = \
1190 solutionMapOldToNew[self.exactWinners[problemSize][0]]
1191 if self.exactWinners[problemSize][0] == -1:
1192 print(("warning: exactWinner[", problemSize, "] == -1"))
1193 if self.exactWinners[problemSize][0] >= self.numSolutions:
1194 print(("warning: exactWinner[", problemSize, "] "))
1195
1196
1197 ##############################################################################
1198 # Score Range For Logic
1199 ##############################################################################
1200 def scoreRangeForLogic(self, indexRange, logic):
1201 depth = self.getLogicDepth(logic)
1202 depth = self.numIndices - depth
1203 fullLogic = deepcopy(logic)
1204 for i in range(0, depth):
1205 fullLogic = [[-1, fullLogic]]
1206 return self.scoreRangeForFullLogic(depth, indexRange, fullLogic)
1207
1208 ##############################################################################
1209 # Score Range For Full Logic
1210 ##############################################################################
1211 def scoreRangeForFullLogic(self, depth, indexRange, logic):
1212 score = 0
1213 for problemIndices in self.problemIndicesForRange(indexRange):
1214 problemSerial = self.indicesToSerial(0, problemIndices)
1215 totalFlops = self.totalFlopsForProblemIndices(problemIndices)
1216 solutionIdx = self.getSolutionForProblemIndicesUsingLogic( \
1217 problemIndices, logic)
1218 if solutionIdx == None:
1219 printWarning("SolutionIdx = None. This should never happen.")
1220 continue
1221 solutionGFlops = self.data[problemSerial + solutionIdx]
1222 solutionGFlops = max(1E-9, solutionGFlops)
1223 timeUs = totalFlops / solutionGFlops / 1000
1224 score += timeUs
1225 return score
1226
1227 ##############################################################################
1228 # Get Solution For Problem Indices Using Logic
1229 ##############################################################################
1230 def getSolutionForProblemIndicesUsingLogic(self, problemIndices, logic):
1231 currentProblemIndices = self.toIndexOrder(problemIndices)
1232 currentLogic = logic
1233 for i in range(0, self.numIndices):
1234 currentSizeIndex = currentProblemIndices[0]
1235 for j in range(0, len(currentLogic)):
1236 if currentLogic[j][0] < 0:
1237 currentProblemIndices = currentProblemIndices[1:]
1238 currentLogic = currentLogic[j][1]
1239 break
1240 if currentLogic[j][0] >= 0:
1241 if currentSizeIndex <= currentLogic[j][0]:
1242 currentProblemIndices = currentProblemIndices[1:]
1243 currentLogic = currentLogic[j][1]
1244 break
1245 return currentLogic
1246
1247
1248 ##############################################################################
1249 ##############################################################################
1250 ###
1251 ### Helper / Low-Level Functions
1252 ###
1253 ##############################################################################
1254 ##############################################################################
1255
1256
1257 ##############################################################################
1258 # Get Winner For Problem
1259 def getWinnerForProblem(self, problemIndices):
1260 problemSerial = self.indicesToSerial(0, problemIndices)
1261 winnerIdx = -1
1262 winnerGFlops = -1
1263 for solutionIdx in range(0, self.numSolutions):
1264 solutionSerialIdx = problemSerial + solutionIdx
1265 solutionGFlops = self.data[solutionSerialIdx]
1266 solutionGFlops = max(1E-9, solutionGFlops)
1267 if solutionGFlops > winnerGFlops:
1268 winnerIdx = solutionIdx
1269 winnerGFlops = solutionGFlops
1270 # print "Winner %u %f" % (winnerIdx, winnerGFlops)
1271 return (winnerIdx, winnerGFlops)
1272
1273
1274 ##############################################################################
1275 # Winner For Range, -1 if nothing benchmarked
1276 def winnerForRange(self, indexRange):
1277 if self.numSolutions == 1:
1278 return 0
1279 else:
1280 scores = self.scoreRangeForSolutions(indexRange)
1281 winnerIdx = 0
1282 hasWinner = False
1283 for solutionIdx in range(1, self.numSolutions):
1284 if scores[solutionIdx] < scores[winnerIdx]:
1285 winnerIdx = solutionIdx
1286 hasWinner = True
1287 elif scores[solutionIdx] > scores[winnerIdx]:
1288 hasWinner = True
1289 else:
1290 pass # still no winner
1291
1292 return winnerIdx if hasWinner else -1
1293
1294
1295 ##############################################################################
1296 # Score (microseconds) Range For Solutions
1297 def scoreRangeForSolutions(self, indexRange):
1298 scores = [0]*self.numSolutions
1299 for problemIndices in self.problemIndicesForRange(indexRange):
1300 problemSerial = self.indicesToSerial(0, problemIndices)
1301 totalFlops = self.totalFlopsForProblemIndices(problemIndices)
1302 for solutionIdx in range(0, self.numSolutions):
1303 gflops = self.data[problemSerial+solutionIdx]
1304 if gflops > 0:
1305 timeUs = totalFlops / gflops / 1000
1306 else: # this solution not benchmarked for this size, therefore set
1307 # its score to +inf so that its automatically disqualified
1308 timeUs = float("inf")
1309 scores[solutionIdx] += timeUs
1310 return scores
1311
1312
1313 ##############################################################################
1314 # Score Logic Complexity
1315 def scoreLogicComplexity(self, logic, logicComplexity):
1316 depth = self.getLogicDepth(logic)
1317 if depth == 0: return
1318 depth = self.numIndices - depth
1319 for i in range(0, len(logic)):
1320 logicComplexity[depth] += 1
1321 self.scoreLogicComplexity(logic[i][1], logicComplexity)
1322
1323
1324 ##############################################################################
1325 # Get Logic Depth
1326 def getLogicDepth(self, logic):
1327 obj = logic
1328 depth = 0
1329 while isinstance(obj, list):
1330 obj = obj[0][1]
1331 depth += 1
1332 return depth
1333
1334
1335 ##############################################################################
1336 # To Index Order
1337 def toIndexOrder(self, problemIndices):
1338 ordered = []
1339 for i in self.indexOrder:
1340 ordered.append(problemIndices[i])
1341 return ordered
1342
1343
1344 ##############################################################################
1345 # Total Flops For Problem Indices
1346 def totalFlopsForProblemIndices(self, problemIndices):
1347 totalFlops = self.flopsPerMac
1348 for i in range(0, self.numIndices):
1349 totalFlops *= self.problemIndexToSize[i][problemIndices[i]]
1350 return totalFlops
1351
1352
1353 ##############################################################################
1354 # Recommended Index Order
1355 # TODO, this may depend on transposes
1356 def recommendedIndexOrder(self):
1357 order = []
1358 for i in range(0, self.problemType["TotalIndices"]):
1359 if i != self.idxU and i != self.idx1 and i != self.idx0:
1360 order.append(i)
1361 order.append(self.idxU)
1362 order.append(self.idx0)
1363 order.append(self.idx1)
1364 return order
1365
1366 ##############################################################################
1367 # Problem Indices For Range
1368 def problemIndicesForRange(self, indexRange):
1369 problemIndexList = []
1370 # early return for empty set
1371 for i in range(0, self.numIndices):
1372 if indexRange[i][0] == indexRange[i][1]:
1373 return []
1374 problemIndices = []
1375 for idx in indexRange:
1376 problemIndices.append(idx[0])
1377 moreProblems = True
1378 while moreProblems:
1379 problemIndexList.append(deepcopy(problemIndices))
1380 # next problem
1381 problemIndices[0] += 1
1382 for i in range(0, self.numIndices):
1383 if problemIndices[i] >= indexRange[i][1]:
1384 if i == self.numIndices-1:
1385 moreProblems = False
1386 break
1387 else:
1388 problemIndices[i] = indexRange[i][0]
1389 problemIndices[i+1] += 1
1390 else:
1391 break
1392 return problemIndexList
1393
1394
1395 ##############################################################################
1396 # Get Item
1397 def __getitem__(self, indexTuple):
1398 indices = indexTuple[0] # in analysis order
1399 solutionIdx = indexTuple[1]
1400 serial = self.indicesToSerial(solutionIdx, indices)
1401 return self.data[serial]
1402
1403
1404 ##############################################################################
1405 # Set Item
1406 def __setitem__(self, indexTuple, value):
1407 indices = indexTuple[0] # in analysis order
1408 solutionIdx = indexTuple[1]
1409 serial = self.indicesToSerial(solutionIdx, indices )
1410 self.data[serial] = value
1411
1412
1413 ##############################################################################
1414 # Indices -> Serial
1415 def indicesToSerial(self, solutionIdx, indices ):
1416 serial = 0
1417 stride = 1
1418 serial += solutionIdx * stride
1419 stride *= self.numSolutions
1420 for i in range(0, self.numIndices):
1421 serial += indices[i] * stride
1422 stride *= self.numProblemSizes[i]
1423 return serial
1424
1425
1426 def generateLogic(
1427 config,
1428 benchmarkDataPath,
1429 libraryLogicPath,
1430 cxxCompiler: str,
1431 splitGSU: bool,
1432 printSolutionRejectionReason: bool,
1433 printIndexAssignmentInfo: bool,
1434 isaInfoMap: Dict[str, IsaInfo]
1435 ):
1436
1437 libraryLogicPath = ensurePath(libraryLogicPath)
1438
1439 print2("# LibraryLogic config: %s" % config)
1440 print2("# DefaultAnalysisParameters: " % defaultAnalysisParameters)
1441
1442 # Assign Defaults
1443 analysisParameters = {}
1444 for parameter in defaultAnalysisParameters:
1445 assignParameterWithDefault(analysisParameters, parameter, config, \
1446 defaultAnalysisParameters)
1447
1448 print1("")
1449 print1(HR)
1450 currentTime = time.time()
1451 elapsedTime = currentTime - startTime
1452 print1("# Analysing data in %s - %.3fs" % (benchmarkDataPath, elapsedTime) )
1453 for parameter in analysisParameters:
1454 print2("# %s: %s" % (parameter, analysisParameters[parameter]))
1455 print1(HR)
1456 print1("")
1457
1458 ##############################################################################
1459 # Determine Which Problem Types
1460 ##############################################################################
1461 problemTypes = {}
1462 if not os.path.exists(benchmarkDataPath):
1463 printExit("Path doesn't exist: %s" % benchmarkDataPath)
1464 fileNames = os.listdir(benchmarkDataPath)
1465 fileNames = sorted(fileNames)
1466 for fileName in fileNames:
1467 if os.path.splitext(fileName)[1] == ".csv":
1468 fileBase = os.path.splitext( \
1469 os.path.join(benchmarkDataPath, \
1470 fileName))[0]
1471 dataFileName = fileBase + ".csv"
1472 solutionsFileName = fileBase + ".yaml"
1473 selectionFileName = fileBase + ".gsp"
1474 if not os.path.exists(dataFileName):
1475 printExit("%s doesn't exist for %s" % (dataFileName, fileBase) )
1476 if not os.path.exists(solutionsFileName):
1477 printExit("%s doesn't exist for %s" % (solutionsFileName, fileBase) )
1478 (problemSizes, solutions) = LibraryIO.parseSolutionsFile(
1479 solutionsFileName,
1480 cxxCompiler,
1481 splitGSU,
1482 printSolutionRejectionReason,
1483 printIndexAssignmentInfo,
1484 isaInfoMap
1485 )
1486 if len(solutions) == 0:
1487 printExit("%s doesn't contains any solutions." % (solutionsFileName) )
1488 problemType = solutions[0]["ProblemType"]
1489 if problemType not in problemTypes:
1490 problemTypes[problemType] = []
1491 problemTypes[problemType].append( (problemSizes, \
1492 dataFileName, solutionsFileName, selectionFileName, solutions) )
1493
1494 for problemType in problemTypes:
1495 logicTuple = analyzeProblemType(problemType, problemTypes[problemType], analysisParameters, libraryLogicPath, splitGSU)
1496
1497 filename = os.path.join(libraryLogicPath, \
1498 "{}_{}".format(analysisParameters["ScheduleName"], str(problemType)))
1499
1500 print2("# writing library logic YAML {}".format(filename))
1501 data = LibraryIO.createLibraryLogic(analysisParameters["ScheduleName"], \
1502 analysisParameters["ArchitectureName"], analysisParameters["DeviceNames"], analysisParameters["LibraryType"], logicTuple)
1503
1504 if globalParameters["LogicFormat"] == "yaml":
1505 LibraryIO.writeYAML(filename + ".yaml", data, explicit_start=False, explicit_end=False)
1506 elif globalParameters["LogicFormat"] == "json":
1507 LibraryIO.write(filename, data, "json")
1508 else:
1509 printExit("Unrecognized LogicFormat", globalParameters["LogicFormat"])
1510
1511 currentTime = time.time()
1512 elapsedTime = currentTime - startTime
1513 print1("%s\n# Finish Analysing data to %s in %.3fs\n%s" % (HR, os.path.split(libraryLogicPath)[0], elapsedTime, HR) )
1514
1515
1516 ##############################################################################
1517 # Error handling for frequency issues
1518 ##############################################################################
1519 def handle_frequency_issue(message):
1520 print1(message)
1521 print1("Input the frequency manually to proceed.")
1522
1523 while True:
1524 frequency_input = input("Frequency: ").strip()
1525 if frequency_input == "":
1526 print1("Frequency cannot be empty")
1527 continue
1528 try:
1529 frequency = float(frequency_input)
1530 if frequency > 0:
1531 return frequency
1532 else:
1533 print1("Frequency cannot be negative or zero.")
1534 except ValueError:
1535 print1("Invalid frequency.Please input a valid frequency.")
1536
1537 def read_max_freq():
1538 try:
1539 max_freq = os.environ.get("MAX_FREQ")
1540 if max_freq is None or max_freq.strip() == "":
1541 raise ValueError("Environment variable 'MAX_FREQ' is not set or is empty.")
1542
1543 return float(max_freq)
1544 except ValueError as ve:
1545 print(f"Error: {ve}") # Handle invalid or missing value
1546 return None
1547 except Exception as e:
1548 print(f"Unexpected error: {e}") # Handle any other unexpected errors
1549 return None
1550
1551 ################################################################################
1552 ################################################################################
1553 ###
1554 ### Main
1555 ###
1556 ################################################################################
1557 ################################################################################
1558 def main(
1559 config,
1560 cxxCompiler: str,
1561 outputPath: Path,
1562 splitGSU: bool,
1563 printSolutionRejectionReason: bool,
1564 printIndexAssignmentInfo: bool,
1565 isaInfoMap: Dict[str, IsaInfo]
1566 ):
1567 benchmarkDataPath = outputPath / BENCHMARK_DATA_DIR
1568 libraryLogicPath = outputPath / LIBRARY_LOGIC_DIR
1569 generateLogic(
1570 config,
1571 benchmarkDataPath,
1572 libraryLogicPath,
1573 cxxCompiler,
1574 splitGSU,
1575 printSolutionRejectionReason,
1576 printIndexAssignmentInfo,
1577 isaInfoMap
1578 )