Debian Codegraph @

tensilelite/Tensile/Common/GlobalParameters.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 import itertools
26 import os.path
27 import subprocess
28 import time
29 from collections import OrderedDict
30 from copy import deepcopy
31 from typing import Dict
32
33 from Tensile import __version__
34
35 from .Architectures import isaToGfx
36 from .Types import IsaVersion, IsaInfo
37 from .Utilities import locateExe, versionIsCompatible, print1, print2, printExit, printWarning, \
38 getVerbosity
39 from .ValidParameters import validParameters
40
41 startTime = time.time()
42
43 globalParameters = OrderedDict()
44 globalParameters["MinimumRequiredVersion"] = (
45 "0.0.0" # which version of tensile is required to handle all the features required by this configuration file
46 )
47 globalParameters["PerformanceMetric"] = (
48 "DeviceEfficiency" # performance metric for benchmarking; one of {DeviceEfficiency, CUEfficiency}
49 )
50 globalParameters["ClientLogLevel"] = (
51 3 # the log level of client. 0=Error, 1=Terse, 2=Verbose, 3=Debug (Aligned with ResultReporter.hpp)
52 )
53 # benchmarking
54 globalParameters["KernelTime"] = False # T=use device timers, F=use host timers
55 globalParameters["PreciseKernelTime"] = (
56 True # T=On hip, use the timestamps for kernel start and stop rather than separate events. Can provide more accurate kernel timing. For GlobalSplitU kernels, recommend disabling this to provide consistent
57 )
58 # timing between GSU / non-GSU kernels
59 globalParameters["PinClocks"] = False # T=pin gpu clocks and fan, F=don't
60 globalParameters["HardwareMonitor"] = (
61 True # False: disable benchmarking client monitoring clocks using rocm-smi.
62 )
63 globalParameters["MinFlopsPerSync"] = (
64 1 # Minimum number of flops per sync to increase stability for small problems
65 )
66 globalParameters["NumBenchmarks"] = (
67 1 # how many benchmark data points to collect per problem/solution
68 )
69 globalParameters["SyncsPerBenchmark"] = (
70 1 # how iterations of the stream synchronization for-loop to do per benchmark data point
71 )
72 globalParameters["EnqueuesPerSync"] = 1 # how many solution enqueues to perform per synchronization
73 globalParameters["MaxEnqueuesPerSync"] = -1 # max solution enqueues to perform per synchronization
74 globalParameters["SleepPercent"] = (
75 300 # how long to sleep after every data point: 25 means 25% of solution time. Sleeping lets gpu cool down more.
76 )
77 globalParameters["SkipSlowSolutionRatio"] = 0.0 # Skip slow solution during warm-up stage.
78 # The valid range of this ratio is (0.0 ~ 1.0), and 0.0 means no skipping.
79 # Skip condition: warm-up time * ratio > current best sol's warm-up time
80 # Suggestion:
81 # Small size : 0.5
82 # Medium size: 0.75
83 # Large size : 0.9
84
85 # validation
86 globalParameters["NumElementsToValidate"] = (
87 128 # number of elements to validate, 128 will be evenly spaced out (with prime number stride) across C tensor
88 )
89 globalParameters["NumElementsToValidateWinner"] = (
90 0 # number of elements to validate in LibraryClient stage, the exact number to be validated is max(NumElementsToValidate,NumElementsToValidateWinner)
91 )
92 globalParameters["BoundsCheck"] = 0 # Bounds check
93 # 1: Perform bounds check to find out of bounds reads/writes. NumElementsToValidate must be -1.
94 # 2: Perform bounds check by front side guard page
95 # 3: Perform bounds check by back side guard page
96 # 4: Perform bounds check by both back and front side guard page
97
98 globalParameters["ValidationMaxToPrint"] = 4 # maximum number of mismatches to print
99 globalParameters["ValidationPrintValids"] = False # print matches too
100 # steps
101 globalParameters["ForceRedoBenchmarkProblems"] = (
102 True # if False and benchmarking already complete, then benchmarking will be skipped when tensile is re-run
103 )
104 globalParameters["ForceRedoLibraryLogic"] = (
105 True # if False and library logic already analyzed, then library logic will be skipped when tensile is re-run
106 )
107 globalParameters["ForceRedoLibraryClient"] = (
108 True # if False and library client already built, then building library client will be skipped when tensile is re-run
109 )
110
111 globalParameters["ShowProgressBar"] = (
112 True # if False and library client already built, then building library client will be skipped when tensile is re-run
113 )
114 globalParameters["SolutionSelectionAlg"] = (
115 1 # algorithm to determine which solutions to keep. 0=removeLeastImportantSolutions, 1=keepWinnerSolutions (faster)
116 )
117 globalParameters["GenerateSourcesAndExit"] = False # Exit after kernel source generation.
118 globalParameters["ExitOnFails"] = (
119 1 # 1: Exit after benchmark run if failures detected. 2: Exit during benchmark run.
120 )
121 globalParameters["CpuThreads"] = (
122 -1
123 ) # How many CPU threads to use for kernel generation. 0=no threading, -1 == nproc, N=min(nproc,N). TODO - 0 sometimes fails with a kernel name error? 0 does not check error codes correctly
124 globalParameters["NumWarmups"] = 0
125
126 globalParameters["PythonProfile"] = False # Enable python profiling
127
128 globalParameters["ISA"] = []
129
130 ########################################
131 # less common
132 ########################################
133 globalParameters["CMakeBuildType"] = (
134 "Release" # whether benchmark clients and library client should be release or debug
135 )
136 globalParameters["LogicFormat"] = "yaml" # set library backend (yaml, or json)
137 globalParameters["LibraryFormat"] = "yaml" # set library backend (yaml, or msgpack)
138
139 # True/False: CSV will/won't export WinnerGFlops, WinnerTimeUS, WinnerIdx, WinnerName.
140 # TODO - if no side-effect, we can set default to True. This can make analyzing "LibraryLogic" (AddFromCSV) faster
141 globalParameters["CSVExportWinner"] = False
142
143 # (When NumBenchmarks > 1). True: CSV will merge the rows of same Problem-ID. False: Each problem will write out "NumBenchmarks" rows
144 # In old client - No effect, since in old client, CSV file only exports the last benchmark, somehow is not correct because the previous benchmarks are discarded
145 # In new client - csv file exports "NumBenchmarks" rows for every problem. This also make the later analyzing slower
146 # Set this to "True" can merge the rows for same problem, hence can reduce the csv file size and speed up the later analyzing
147 # TODO - if side-effect, we can set default to True. This can make "getResults()" / "AddFromCSV()" faster
148 globalParameters["CSVMergeSameProblemID"] = False
149
150 # how to initialize tensor data
151 # serial-in-u will use a sequence that increments in the K dimension
152 # This is a predictable patterns that can be checked as the kernel runs to detect
153 # when the wrong data is being used.
154 # trig_float initializes with the sin function to have non-zero values in the mantissa
155 # and exponent. It cannot be used for int8 or int32. Need to use tensileAlmostEqual
156 # not tensileEqual for checking the result.
157 # See ClientWriter.py, the DataInitName(Enum) for a list of initialization patterns
158 # - Problem-Independent: 0=0, 1=1, 2=2, 3=rand, 4=Nan, 5=Infinity, 6=BadInput(Nan), 7=BadOutput(Inf), 16=RandomNarrow,
159 # 21=RandomNegPosLimited(-128~128 or -1~1), 23~26=Ind Cos/Sin Abs or Not
160 # - Problem-dependent: 8=SerialID, 9=SerialDim0, 10=SerialDim1, 11=Identity, 12~15= Cos/Sin, Abs or Not
161 # For A, B, C, D: All the InitMode (0~16) can be used
162 # For Alpha/Beta: Only problem-independent init (0~7, 16, 23~26) can be used,
163 # problem-dependent init (8~15) would cause a exception (Invalid InitMode) in New Client
164 globalParameters["DataInitTypeAB"] = 3
165 globalParameters["DataInitTypeA"] = -1
166 globalParameters["DataInitTypeB"] = -1
167 globalParameters["DataInitTypeC"] = 3
168 globalParameters["DataInitTypeD"] = 0
169 globalParameters["DataInitTypeE"] = 0
170 globalParameters["DataInitTypeAlpha"] = 2
171 globalParameters["DataInitTypeBeta"] = 2
172 globalParameters["DataInitTypeBias"] = 3
173 globalParameters["DataInitTypeScaleA"] = 2
174 globalParameters["DataInitTypeScaleB"] = 2
175 globalParameters["DataInitTypeScaleC"] = 2
176 globalParameters["DataInitTypeScaleD"] = 2
177 globalParameters["DataInitTypeScaleAlphaVec"] = 3
178 globalParameters["DataInitValueActivationArgs"] = [2.0, 2.0]
179 globalParameters["CEqualD"] = (
180 False # Set to true if testing for the case where the pointer to C is the same as D.
181 )
182 # When this parameter is set to 0, the Tensile client will use srand(time(NULL)).
183 # If not 0 the Tensile client will use srand(seed).
184 globalParameters["DataInitSeed"] = 0
185 globalParameters["PruneSparseMode"] = (
186 0 # Prune mode for Sparse Matrix: 0=random, 1=XX00, 2=X0X0, 3=0XX0, 4=X00X, 5=0X0X, 6=00XX
187 )
188
189 # build parameters
190 globalParameters["CMakeCXXFlags"] = "" # pass flags to cmake
191 globalParameters["CMakeCFlags"] = "" # pass flags to cmake
192 globalParameters["AsanBuild"] = False # build with asan
193 #globalParameters["SaveTemps"] = False # Generate intermediate results of hip kernels
194 globalParameters["KeepBuildTmp"] = False # If true, do not remove artifacts in build_tmp
195
196 # debug for assembly
197 #globalParameters["SplitGSU"] = False # Split GSU kernel into GSU1 and GSUM
198
199 # Tensor printing controls:
200 globalParameters["PrintTensorA"] = 0 # Print TensorA after initialization
201 globalParameters["PrintTensorB"] = 0 # Print TensorB after initialization
202 globalParameters["PrintTensorC"] = (
203 0 # Print TensorC. 0x1=after init; 0x2=after copy-back; 0x3=both
204 )
205 globalParameters["PrintTensorD"] = (
206 0 # Print TensorD. 0x1=after init; 0x2=after copy-back; 0x3=both
207 )
208 globalParameters["PrintTensorRef"] = (
209 0 # Print reference tensor. 0x1=after init; 0x2=after copy-back; 0x3=both
210 )
211 globalParameters["PrintTensorBias"] = 0 # Print TensorBias after initialization
212 globalParameters["PrintTensorScaleAlphaVec"] = 0 # Print TensorScaleAlphaVec after initialization
213 globalParameters["PrintTensorAmaxD"] = 0 # Print AmaxD after validation
214 globalParameters["PrintWinnersOnly"] = False # Only print the solutions which become the fastest
215 globalParameters["PrintCodeCommands"] = (
216 False # print the commands used to generate the code objects (asm,link,hip-clang, etc)
217 )
218 globalParameters["DumpTensors"] = (
219 False # If True, dump tensors to binary files instead of printing them.
220 )
221
222 # If PrintMax* is greater than the dimension, the middle elements will be replaced with "..."
223
224
225 # device selection
226 globalParameters["Platform"] = 0 # select opencl platform
227
228 # shouldn't need to change
229 globalParameters["ClientExecutionLockPath"] = (
230 None # Path for a file lock to ensure only one client is executed at once. filelock module is required if this is enabled.
231 )
232 globalParameters["LibraryUpdateFile"] = (
233 "" # File name for writing indices and speeds suitable for updating an existing library logic file
234 )
235 globalParameters["LibraryUpdateComment"] = (
236 False # Include solution name as a comment in the library update file
237 )
238
239 # internal, i.e., gets set during startup
240 globalParameters["ROCmSMIPath"] = None # /opt/rocm/bin/rocm-smi
241 globalParameters["HipClangVersion"] = "0.0.0"
242
243 # default runtime is selected based on operating system, user can override
244 if os.name == "nt":
245 globalParameters["RuntimeLanguage"] = "HIP"
246 else:
247 globalParameters["RuntimeLanguage"] = "HIP"
248
249 globalParameters["CodeObjectVersion"] = "4"
250
251 # perf model
252 globalParameters["PerfModelL2ReadHits"] = 0.0
253 globalParameters["PerfModelL2WriteHits"] = 0.15
254 globalParameters["PerfModelL2ReadBwMul"] = 2
255 globalParameters["PerfModelReadEfficiency"] = 0.85
256
257 # limitation for training
258 globalParameters["MaxWorkspaceSize"] = 128 * 1024 * 1024 # max workspace for training (128MB)
259 #globalParameters["MinKForGSU"] = 32 # min K size to use GlobalSplitU algorithm (only for HPA now)
260
261 # control if a solution is run for a given problem
262 globalParameters["GranularityThreshold"] = 0.0
263
264 globalParameters["PristineOnGPU"] = (
265 True # use Pristine memory on Tensile trainning verification or not
266 )
267
268 globalParameters["SeparateArchitectures"] = (
269 False # write Tensile library metadata to separate files for each architecture
270 )
271
272 globalParameters["LazyLibraryLoading"] = (
273 False # Load library and code object files when needed instead of at startup
274 )
275
276 globalParameters["EnableMarker"] = False # Enable Tensile markers
277
278 globalParameters["UseUserArgs"] = False
279
280 globalParameters["RotatingBufferSize"] = 0 # Size in MB
281 globalParameters["RotatingMode"] = (
282 0 # Default is 0, allocated in order A0B0C0D0..ANBNCNDN. 1 is in order A0 pad B0 pad .... AN pad BN pad.
283 )
284 # Mode 0 requires memcpy everytime when the problem changes to reset the data, but mode 1 doesn't.
285
286 globalParameters["BuildIdKind"] = "sha1"
287 globalParameters["AsmDebug"] = (
288 False # Set to True to keep debug information for compiled code objects
289 )
290
291 globalParameters["UseEffLike"] = True # Set to False to use winnerGFlops as the performance metric
292
293 # Save a copy - since pytest doesn't re-run this initialization code and YAML files can override global settings - odd things can happen
294 # we should do this here...
295 defaultGlobalParameters = deepcopy(globalParameters)
296
297
298 ################################################################################
299 # Tensile internal parameters
300 ################################################################################
301 # These parameters are not adjustable by the config yamls. They change with the
302 # generator versions
303 internalParameters = {
304 # Each universal kernel will generate one PostGSU(GlobalSplitUPGR) kernel
305 "GlobalSplitUPGR": 16
306 }
307
308 # These parameters are used in ContractionSolutions for user arguments support.
309 defaultInternalSupportParams = {
310 "KernArgsVersion": 2,
311 # Information about user input internal kernel argument support
312 # Change this to False if the CustomKernel does not support.
313 "SupportUserGSU": True,
314 # This is a little different from GSU because GSU is already a parameter,
315 # but WGM is not.
316 "SupportCustomWGM": True,
317 "SupportCustomStaggerU": True,
318 # Use GG as G's backend
319 "UseUniversalArgs": True,
320 }
321
322 # same parameter for all solution b/c depends only on compiler
323 defaultBenchmarkCommonParameters = [
324 {"InnerUnroll": [1]},
325 {"KernelLanguage": ["Assembly"]},
326 {"LdsPadA": [-1]},
327 {"LdsPadB": [-1]},
328 {"LdsPadMetadata": [0]},
329 {"LdsBlockSizePerPadA": [-1]},
330 {"LdsBlockSizePerPadB": [-1]},
331 {"LdsBlockSizePerPadMetadata": [0]},
332 {"TransposeLDS": [-1]},
333 {"MaxOccupancy": [40]},
334 {"MaxLDS": [-1]},
335 {"VectorWidthA": [-1]},
336 {"VectorWidthB": [-1]},
337 {"VectorStore": [-1]},
338 {"StoreVectorWidth": [-1]},
339 {"GlobalReadVectorWidthA": [-1]},
340 {"GlobalReadVectorWidthB": [-1]},
341 {"LocalReadVectorWidth": [-1]},
342 {"WaveSeparateGlobalReadA": [0]},
343 {"WaveSeparateGlobalReadB": [0]},
344 {"WaveSeparateGlobalReadMetadata": [0]},
345 {"UnrollLoopSwapGlobalReadOrder": [0]},
346 {"PrefetchGlobalRead": [1]},
347 {"PrefetchLocalRead": [1]},
348 {"ClusterLocalRead": [1]},
349 {"SuppressNoLoadLoop": [False]},
350 {"ExpandPointerSwap": [True]},
351 {"ScheduleGlobalRead": [1]},
352 {"ScheduleLocalWrite": [1]},
353 {"ScheduleIterAlg": [3]},
354 {"GlobalReadPerMfma": [1]},
355 {"LocalWritePerMfma": [-1]},
356 {"InterleaveAlpha": [0]},
357 {"OptNoLoadLoop": [1]},
358 {"BufferLoad": [True]},
359 {"BufferStore": [True]},
360 {"DirectToVgprA": [False]},
361 {"DirectToVgprB": [False]},
362 {"DirectToVgprSparseMetadata": [False]},
363 {"DirectToLds": [False]},
364 {"UseSgprForGRO": [-1]},
365 {"UseInstOffsetForGRO": [0]},
366 {"AssertSummationElementMultiple": [1]},
367 {"AssertFree0ElementMultiple": [1]},
368 {"AssertFree1ElementMultiple": [1]},
369 {"AssertAIGreaterThanEqual": [-1]},
370 {"AssertAILessThanEqual": [-1]},
371 {"StaggerU": [32]}, # recommend [0,32]
372 {"StaggerUStride": [256]}, # recommend 256 for V10,V20
373 {"StaggerUMapping": [0]}, # recommend [0,1]
374 {"MagicDivAlg": [2]},
375 {"GlobalSplitU": [1]},
376 {"GlobalSplitUAlgorithm": ["MultipleBuffer"]},
377 {"GlobalSplitUCoalesced": [False]},
378 {"GlobalSplitUWorkGroupMappingRoundRobin": [False]},
379 {"Use64bShadowLimit": [1]},
380 {"NumLoadsCoalescedA": [1]},
381 {"NumLoadsCoalescedB": [1]},
382 {"WorkGroup": [[16, 16, 1]]},
383 {"WorkGroupMapping": [8]},
384 {"WorkGroupMappingXCC": [1]},
385 {"WorkGroupMappingXCCGroup": [-1]},
386 {"ThreadTile": [[4, 4]]},
387 {"WavefrontSize": [64]},
388 {"MatrixInstruction": [[]]},
389 {"1LDSBuffer": [0]},
390 {"DepthU": [-1]},
391 {"NonTemporalE": [0]},
392 {"NonTemporalD": [0]},
393 {"NonTemporalC": [0]},
394 {"NonTemporalA": [0]},
395 {"NonTemporalB": [0]},
396 {"NonTemporalWS": [0]},
397 {"NonTemporalMetadata": [0]},
398 {"NonTemporal": [-1]},
399 {"PreloadKernArgs": [True]},
400 {"CustomKernelName": [""]},
401 {"NoReject": [False]},
402 {"StoreRemapVectorWidth": [0]},
403 {"SourceSwap": [False]},
404 {"StorePriorityOpt": [False]},
405 {"NumElementsPerBatchStore": [0]},
406 {"StoreSyncOpt": [0]},
407 {"GroupLoadStore": [False]},
408 {"MIArchVgpr": [False]},
409 {"StreamK": [0]},
410 {"StreamKAtomic": [0]},
411 {"StreamKXCCMapping": [0]},
412 {"DebugStreamK": [0]},
413 {"ActivationFused": [True]},
414 {"ActivationFuncCall": [True]},
415 {"ActivationAlt": [False]},
416 {"WorkGroupReduction": [False]},
417 {"ConvertAfterDS": [False]},
418 {"ForceDisableShadowInit": [False]},
419 {"LDSTrInst": [False]},
420 {"WaveSplitK": [ False ]},
421 {"MbskPrefetchMethod": [0]},
422 {"UseCustomMainLoopSchedule": [1]}
423 ]
424
425 # dictionary of defaults comprised of default option for each parameter
426 defaultSolution = {}
427 for paramDict in defaultBenchmarkCommonParameters:
428 for key, value in paramDict.items():
429 defaultSolution[key] = value[0]
430 # other non-benchmark options for solutions
431
432
433
434 defaultProblemSizes = [{"Range": [[2880], 0, 0]}]
435 defaultBenchmarkFinalProblemSizes = [{"Range": [[64, 64, 64, 512], 0, 0]}]
436 defaultBatchedProblemSizes = [{"Range": [[2880], 0, [1], 0]}]
437 defaultBatchedBenchmarkFinalProblemSizes = [{"Range": [[64, 64, 64, 512], 0, [1], 0]}]
438
439
440 defaultSolutionSummationSizes = [32, 64, 96, 128, 256, 512, 1024, 2048, 4096, 8192, 16192]
441
442
443 ################################################################################
444 # Default Analysis Parameters
445 ################################################################################
446 defaultAnalysisParameters = {
447 "ScheduleName": "Tensile",
448 "DeviceNames": "fallback",
449 "ArchitectureName": "gfx000",
450 "LibraryType": "GridBased",
451 "SolutionImportanceMin": 0.01, # = 0.01=1% total time saved by keeping this solution
452 }
453
454
455 ################################################################################
456 # Is query version compatible with current version
457 # a yaml file is compatible with tensile if
458 # tensile.major == yaml.major and tensile.minor.step > yaml.minor.step
459 ################################################################################
460 def restoreDefaultGlobalParameters():
461 """
462 Restores `globalParameters` back to defaults.
463 """
464 global globalParameters
465 global defaultGlobalParameters
466 # Can't just assign globalParameters = deepcopy(defaultGlobalParameters) because that would
467 # result in dangling references, specifically in Tensile.Tensile().
468 globalParameters.clear()
469 for key, value in deepcopy(defaultGlobalParameters).items():
470 globalParameters[key] = value
471
472
473 # hopefully the isaInfoMap keys only contain isas we plan to build and not all
474 def printCapabilitiesTable(isaInfoMap: Dict[str, IsaInfo]):
475 """
476 Prints a capability table for the given parameters and ISA information map.
477
478 Args:
479 supportedIsas: The ISAs to show in the table.
480 isaInfoMap: The ISA information map containing assembler and architecture capabilities.
481 """
482
483 def printTable(rows):
484 rows = [[str(cell) for cell in row] for row in rows]
485 colWidths = [max(len(cell) for cell in col) for col in zip(*rows)]
486
487 for row in rows:
488 print(" ".join(cell.ljust(width) for cell, width in zip(row, colWidths)))
489
490 def capRow(isaInfoMap, cap, capType):
491 return [cap] + [
492 "1" if cap in getattr(info, capType) and getattr(info, capType)[cap] else "-"
493 for info in isaInfoMap.values()
494 ]
495
496 gfxs = list(map(isaToGfx, isaInfoMap.keys()))
497 headerRow = ["Capability"] + gfxs
498
499 allAsmCaps = sorted(
500 set(itertools.chain(*[info.asmCaps for info in isaInfoMap.values()])),
501 key=lambda k: (k.split("_")[-1], k),
502 )
503 asmCapRows = [capRow(isaInfoMap, cap, "asmCaps") for cap in allAsmCaps]
504
505 allArchCaps = sorted(set(itertools.chain(*[info.archCaps for info in isaInfoMap.values()])))
506 archCapRows = [capRow(isaInfoMap, cap, "archCaps") for cap in allArchCaps]
507
508 printTable([headerRow] + asmCapRows + archCapRows)
509
510
511 def assignGlobalParameters(config, isaInfoMap: Dict[IsaVersion, IsaInfo]):
512 """
513 Assign Global Parameters
514 Each global parameter has a default parameter, and the user
515 can override them, those overridings happen here
516 """
517
518 global globalParameters
519
520 # Minimum Required Version
521 if "MinimumRequiredVersion" in config:
522 if not versionIsCompatible(config["MinimumRequiredVersion"]):
523 printExit(
524 "Config file requires version=%s is not compatible with current Tensile version=%s"
525 % (config["MinimumRequiredVersion"], __version__)
526 )
527
528 # User-specified global parameters
529 print2("GlobalParameters:")
530 for key in globalParameters:
531 defaultValue = globalParameters[key]
532 if key in config:
533 configValue = config[key]
534 if configValue == defaultValue:
535 print2(" %24s: %8s (same)" % (key, configValue))
536 else:
537 print2(" %24s: %8s (overriden)" % (key, configValue))
538 else:
539 print2(" %24s: %8s (unspecified)" % (key, defaultValue))
540
541 globalParameters["ROCmPath"] = "/opt/rocm"
542 if "ROCM_PATH" in os.environ:
543 globalParameters["ROCmPath"] = os.environ.get("ROCM_PATH")
544 if "TENSILE_ROCM_PATH" in os.environ:
545 globalParameters["ROCmPath"] = os.environ.get("TENSILE_ROCM_PATH")
546 if os.name == "nt" and "HIP_DIR" in os.environ:
547 globalParameters["ROCmPath"] = os.environ.get("HIP_DIR") # windows has no ROCM
548 globalParameters["CmakeCxxCompiler"] = None
549 if "CMAKE_CXX_COMPILER" in os.environ:
550 globalParameters["CmakeCxxCompiler"] = os.environ.get("CMAKE_CXX_COMPILER")
551 if "CMAKE_C_COMPILER" in os.environ:
552 globalParameters["CmakeCCompiler"] = os.environ.get("CMAKE_C_COMPILER")
553
554 globalParameters["ROCmBinPath"] = os.path.join(globalParameters["ROCmPath"], "bin")
555 try:
556 globalParameters["ROCmSMIPath"] = locateExe(globalParameters["ROCmBinPath"], "rocm-smi")
557 except OSError:
558 if os.name == "nt":
559 # rocm-smi is not presently supported on Windows so do not require it.
560 pass
561 else:
562 raise
563
564 if "AsanBuild" in config:
565 globalParameters["AsanBuild"] = config["AsanBuild"]
566
567 if "KeepBuildTmp" in config:
568 globalParameters["KeepBuildTmp"] = config["KeepBuildTmp"]
569
570 if "CodeObjectVersion" in config:
571 globalParameters["CodeObjectVersion"] = config["CodeObjectVersion"]
572
573 if getVerbosity() >= 1:
574 printCapabilitiesTable(isaInfoMap)
575
576 isaList = list(isaInfoMap.keys())
577 validParameters["ISA"] = [IsaVersion(0, 0, 0), *isaList]
578
579 # For ubuntu platforms, call dpkg to grep the version of hip-clang. This check is platform specific, and in the future
580 # additional support for yum, dnf zypper may need to be added. On these other platforms, the default version of
581 # '0.0.0' will persist
582
583 # Due to platform.linux_distribution() being deprecated, just try to run dpkg regardless.
584 # The alternative would be to install the `distro` package.
585 # See https://docs.python.org/3.7/library/platform.html#platform.linux_distribution
586
587 # The following try except block computes the hipcc version
588 # TODO: hipcc is deprecated, this block should be removed.
589 try:
590 compiler = "hipcc"
591 output = subprocess.run(
592 [compiler, "--version"], check=True,
593 stdout=subprocess.PIPE,
594 # Avoids some warning spam on Windows.
595 stderr=subprocess.DEVNULL,
596 ).stdout.decode()
597
598 for line in output.split("\n"):
599 if "HIP version" in line:
600 globalParameters["HipClangVersion"] = line.split()[2]
601 print1("# Found hipcc version " + globalParameters["HipClangVersion"])
602
603 except (subprocess.CalledProcessError, OSError) as e:
604 printWarning("Error: {} running {} {} ".format("hipcc", "--version", e))
605
606 # The following keys may be present in the config, but are not (or no longer) global parameters.
607 ignoreKeys = [
608 "Architecture",
609 "PrintLevel",
610 "Device",
611 "UseCompression",
612 "CxxCompiler",
613 "CCompiler",
614 "OffloadBundler",
615 "Assembler",
616 "LogicPath",
617 "LogicFilter",
618 "OutputPath",
619 "Experimental",
620 "GenSolTable",
621 ]
622 for key in config:
623 if key in ignoreKeys:
624 continue
625 value = config[key]
626 if key not in globalParameters:
627 printWarning("Global parameter %s = %s unrecognised." % (key, value))
628 globalParameters[key] = value
629
630
631 def setupRestoreClocks():
632 import atexit
633
634 def restoreClocks():
635 # Clocks will only be pinned if rocm-smi is available, therefore
636 # we only need to restore if found.
637 if globalParameters["PinClocks"]:
638 rsmi = globalParameters["ROCmSMIPath"]
639 if rsmi is not None:
640 subprocess.call([rsmi, "-d", "0", "--resetclocks"])
641 subprocess.call([rsmi, "-d", "0", "--setfan", "50"])
642
643 atexit.register(restoreClocks)
644
645 setupRestoreClocks()