Debian Codegraph @

tensilelite/Tensile/Common/Architectures.py

raw symbols SCIP
1 ################################################################################
2 #
3 # Copyright (C) 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 import re
24 import collections
25
26 from pathlib import Path
27 from subprocess import run, PIPE
28 from typing import List, Optional, Set, Tuple, Union, NamedTuple, Dict
29
30 from .Types import IsaVersion
31 from .Utilities import print2
32
33 import rocisa
34
35 # Translate GPU targets to filter filenames in Tensile_LOGIC directory
36 architectureMap = {
37 "all": "_",
38 "gfx000": "none",
39 "gfx803": "r9nano",
40 "gfx900": "vega10",
41 "gfx906": "vega20",
42 "gfx906:xnack+": "vega20",
43 "gfx906:xnack-": "vega20",
44 "gfx908": "arcturus",
45 "gfx908:xnack+": "arcturus",
46 "gfx908:xnack-": "arcturus",
47 "gfx90a": "aldebaran",
48 "gfx90a:xnack+": "aldebaran",
49 "gfx90a:xnack-": "aldebaran",
50 "gfx942": "aquavanjaram",
51 "gfx942:xnack+": "aquavanjaram",
52 "gfx942:xnack-": "aquavanjaram",
53 "gfx950": "gfx950",
54 "gfx950:xnack+": "gfx950",
55 "gfx950:xnack-": "gfx950",
56 "gfx1010": "navi10",
57 "gfx1011": "navi12",
58 "gfx1012": "navi14",
59 "gfx1030": "navi21",
60 "gfx1100": "navi31",
61 "gfx1101": "navi32",
62 "gfx1102": "navi33",
63 "gfx1103": "gfx1103",
64 "gfx1150": "gfx1150",
65 "gfx1151": "gfx1151",
66 "gfx1200": "gfx1200",
67 "gfx1201": "gfx1201",
68 }
69
70 gfxVariantMap = {
71 "gfx906": ["gfx906:xnack+", "gfx906:xnack-"],
72 "gfx908": ["gfx908:xnack+", "gfx908:xnack-"],
73 "gfx90a": ["gfx90a:xnack+", "gfx90a:xnack-"],
74 "gfx942": ["gfx942:xnack+", "gfx942:xnack-"],
75 "gfx950": ["gfx950:xnack+", "gfx950:xnack-"],
76 }
77
78 SUPPORTED_ISA = [
79 IsaVersion(8, 0, 3),
80 IsaVersion(9, 0, 0),
81 IsaVersion(9, 0, 6),
82 IsaVersion(9, 0, 8),
83 IsaVersion(9, 0, 10),
84 IsaVersion(9, 4, 2),
85 IsaVersion(9, 5, 0),
86 IsaVersion(10, 1, 0),
87 IsaVersion(10, 1, 1),
88 IsaVersion(10, 1, 2),
89 IsaVersion(10, 3, 0),
90 IsaVersion(11, 0, 0),
91 IsaVersion(11, 0, 1),
92 IsaVersion(11, 0, 2),
93 IsaVersion(11, 0, 3),
94 IsaVersion(11, 5, 0),
95 IsaVersion(11, 5, 1),
96 IsaVersion(12, 0, 0),
97 IsaVersion(12, 0, 1),
98 ]
99
100 SUPPORTED_ARCH_DEVICE_IDS = {
101 "id=74a0": "gfx942",
102 "id=74a1": "gfx942",
103 "id=74a2": "gfx942",
104 "id=74a3": "gfx942",
105 "id=74a5": "gfx942",
106 "id=74a9": "gfx942",
107 "id=75a0": "gfx950",
108 "id=75a2": "gfx950",
109 "id=75a3": "gfx950",
110 # This dictionary should be extended to add device ID-based
111 # filtering support for other architectures.
112 }
113
114 SUPPORTED_ARCH_CU_COUNTS = {
115 "cu=20": "gfx942",
116 "cu=38": "gfx942",
117 "cu=64": "gfx942",
118 "cu=80": "gfx942",
119 "cu=96": "gfx942",
120 "cu=228": "gfx942",
121 "cu=304": "gfx942",
122 # This dictionary should be extended to add CU count-based
123 # filtering support for other architectures.
124 }
125
126 ARCH_DEVICE_ID_FALLBACKS = {
127 "id=75a2": ["id=75a0"],
128 "id=75a3": ["id=75a0"],
129 }
130
131 # Here, `None` refers to an unspecified CU count.
132 ARCH_CU_COUNT_FALLBACKS = {
133 "cu=20": None,
134 "cu=38": None,
135 "cu=64": None,
136 "cu=80": None,
137 "cu=96": None,
138 "cu=228": None,
139 "cu=304": None,
140 }
141
142
143 def isaToGfx(arch: IsaVersion) -> str:
144 """Converts an ISA version to a gfx architecture name.
145
146 Args:
147 arch: An object representing the major, minor, and step version of the ISA.
148
149 Returns:
150 The name of the GPU architecture (e.g., 'gfx906').
151 """
152 # Convert last digit to hex because reasons
153 name = str(arch[0]) + str(arch[1]) + ("%x" % arch[2])
154 return "gfx" + "".join(map(str, name))
155
156
157 SUPPORTED_GFX = [isaToGfx(isa) for isa in SUPPORTED_ISA]
158
159
160 def gfxToIsa(name: str) -> Optional[IsaVersion]:
161 """Extracts the ISA version from a given gfx architecture name.
162
163 Args:
164 name: The gfx name of the GPU architecture (e.g., 'gfx906').
165
166 Returns:
167 An object representing the major, minor, and step version of the ISA.
168 Returns None if the name does not match the expected pattern.
169 """
170 match = re.search(r"gfx([0-9a-fA-F]{3,})", name)
171 if not match:
172 return None
173 ipart = match.group(1)
174 step = int(ipart[-1], 16)
175
176 ipart = ipart[:-1]
177 minor = int(ipart[-1])
178
179 ipart = ipart[:-1]
180 major = int(ipart)
181 return IsaVersion(major, minor, step)
182
183
184 def gfxToSwCodename(gfxName: str) -> Optional[str]:
185 """Retrieves the common name for a given gfx architecture name.
186
187 Args:
188 gfxName: The name of the GPU architecture (e.g., gfx1100).
189
190 Returns:
191 The common name of the GPU architecture (e.g., navi31) if found in ``architectureMap``.
192 Returns None if the name is not found.
193 """
194 if gfxName in architectureMap:
195 return architectureMap[gfxName]
196 else:
197 for archKey in architectureMap:
198 if gfxName in archKey:
199 return architectureMap[archKey]
200 return None
201
202
203 def gfxToVariants(gfx: str) -> List[str]:
204 """Retrieves the list of variants for a given gfx architecture name.
205
206 Args:
207 gfx: The name of the GPU architecture (e.g., 'gfx906').
208
209 Returns:
210 List of variants for the GPU architecture.
211 """
212 return gfxVariantMap.get(gfx, [gfx])
213
214
215 def cliArchsToIsa(cliArchs: str) -> List[IsaVersion]:
216 """Maps the requested gfx architectures to ISA numbers.
217
218 Args:
219 archs: str of ";" or "_" separated gfx architectures (e.g., gfx1100 or gfx90a;gfx1101).
220
221 Returns:
222 List of tuples
223 """
224 archs = cliArchs.split(";") if ";" in cliArchs else cliArchs.split("_")
225 return SUPPORTED_ISA if "all" in archs else [gfxToIsa(''.join(map(str, arch))) for arch in archs]
226
227
228 def _detectGlobalCurrentISA(detectionTool, deviceId: int):
229 """
230 Returns returncode if detection failure
231 """
232 process = run([detectionTool], stdout=PIPE)
233 archList = []
234 for line in process.stdout.decode().split("\n"):
235 arch = gfxToIsa(line.strip())
236 if arch is not None:
237 if arch in SUPPORTED_ISA:
238 print(f"# Detected GPU {deviceId} with ISA: " + isaToGfx(arch))
239 archList.append(arch)
240 if process.returncode:
241 print(f"{detectionTool} exited with code {process.returncode}")
242 return archList[deviceId] if (len(archList) > 0 and process.returncode == 0) else process.returncode
243
244
245 def detectGlobalCurrentISA(deviceId: int, enumerator: str):
246 """Returns the ISA version for a given device.
247
248 Given an integer ID for a device, the ISA version tuple
249 of the form (X, Y, Z) is computed using first amdgpu-arch.
250 If amdgpu-arch fails, rocm_agent_enumerator is used.
251
252 Args:
253 deviceID: an integer indicating the device to inspect.
254
255 Raises:
256 Exception if both tools fail to detect ISA.
257 """
258 result = _detectGlobalCurrentISA(enumerator, deviceId)
259 if not isinstance(result, IsaVersion):
260 raise Exception("Failed to detect currect ISA")
261 return result
262
263
264 class ArchInfo(NamedTuple):
265 Name: str
266 Gfx: str
267 DeviceIds: Optional[Set[str]]
268 CUCount: Optional[str] = None
269
270
271 class LogicFileError(Exception):
272 def __init__(self, message="Expected line is either not present or is malformed"):
273 self.message = message
274 super().__init__(self.message)
275
276
277 def _extractArchInfo(file: Union[str, Path]) -> ArchInfo:
278 """
279 Extracts architecture predicate information from a given logic file.
280
281 The file is expected to have the following format:
282 - Line 0: Minimum required version (e.g., "- {MinimumRequiredVersion: 4.33.0}")
283 - Line 1: Code name of the architecture (e.g., "- aquavanjaram")
284 - Line 2: GFX name of the architecture or a map with variant details (e.g., "- gfx950" or "- {Architecture: gfx950, CUCount: 256}")
285 - Line 3: Device IDs (e.g., "- [Device 1234, Device 5678]")
286
287 Args:
288 file: Path to a logic file.
289 Returns:
290 ArchInfo: An object containing the extracted architecture predicates.
291 Raises:
292 LogicFileError: If the file does not match the expected format.
293 """
294
295 def l0(line: str):
296 if not re.match(r"- \{MinimumRequiredVersion", line):
297 raise LogicFileError(
298 f"Expected minimum required version:\n line: {line} file: {file}"
299 )
300
301 def l1(line: str):
302 return line[2:].strip()
303
304 def l2(line: str):
305 match1 = re.match(r"- \{Architecture: (\w+), CUCount: (\d+)\}", line)
306 match2 = re.match(r"- gfx(\w+)", line)
307 if match1:
308 architecture, cu_count = match1.groups()
309 return architecture, f"cu={cu_count}"
310 elif match2:
311 return line[2:].strip(), None
312 else:
313 raise LogicFileError(
314 f"Expected architecture and CU count, or only an archiecture: line: {line}"
315 )
316
317 def l3(line: str):
318 if re.match(r"- \[Device", line):
319 devIds = re.findall(r"Device (\w+)", line)
320 return set(f"id={id}" for id in devIds)
321 else:
322 raise LogicFileError(f"No device IDs found: line: {line}")
323
324 with open(file, "r") as f:
325 l0(f.readline())
326 name = l1(f.readline())
327 gfx, cu = l2(f.readline())
328 deviceIds = l3(f.readline())
329
330 try:
331 for id in deviceIds:
332 _verifyPredicate(id, gfx)
333 except ValueError as e:
334 raise LogicFileError(f"Invalid device ID found while parsing {file}: {e}")
335
336 return ArchInfo(Name=name, Gfx=gfx, DeviceIds=deviceIds, CUCount=cu)
337
338
339 def _verifyPredicate(predicateSpec: str, gfx: str) -> str:
340 """
341 Verifies that a predicate specification is valid.
342
343 Args:
344 predicateSpec: A string representing a predicate specification.
345 gfx: GFX architecture to validate device ID against.
346
347 Returns:
348 The validated predicate specification.
349 Raises:
350 ValueError: If the predicate specification is invalid or if device ID doesn't match GFX architecture.
351 """
352 msgPrefix = f"Invalid predicate: {predicateSpec}"
353 key, _, val = predicateSpec.partition("=")
354 if key == "id":
355 if predicateSpec not in SUPPORTED_ARCH_DEVICE_IDS:
356 raise ValueError(f"{msgPrefix}: device ID not supported")
357 if gfx and SUPPORTED_ARCH_DEVICE_IDS[predicateSpec] != gfx:
358 raise ValueError(f"{msgPrefix}: device ID is not associated with {gfx}")
359 elif key == "cu":
360 if predicateSpec not in SUPPORTED_ARCH_CU_COUNTS:
361 raise ValueError(f"{msgPrefix}: CU count not supported")
362 if gfx and SUPPORTED_ARCH_CU_COUNTS[predicateSpec] != gfx:
363 raise ValueError(f"{msgPrefix}: CU count is not associated with {gfx}")
364 else:
365 raise ValueError(f"{msgPrefix}: only device ID and CU count-based predicates are currently supported")
366 return predicateSpec
367
368
369 def splitArchsFromPredicates(archSpecs: List[str]) -> Tuple[List[str], Optional[Dict[str, List[str]]]]:
370 """
371 Splits a list of architecture specifications into architectures and their predicates.
372
373 Example inputs:
374 ["gfx942"] # No predicates
375 ["gfx942[id=74a0,id=74a1]"] # With device IDs
376 ["gfx942[cu=80,cu=96]"] # With CU counts
377 ["gfx942[id=74a0,cu=80]"] # With both
378
379 Args:
380 archSpecs: List of architecture specifications, optionally with predicates in square brackets
381
382 Returns:
383 Tuple of:
384 - List of architecture names
385 - Dictionary mapping architectures to their predicates (or None if no predicates)
386 """
387 # Match predicates in square brackets, e.g., [id=74a0,cu=80]
388 pattern = re.compile(r"\[(.*?)\]")
389
390 architectures = set()
391 predicateMap = collections.defaultdict(list)
392
393 for spec in archSpecs:
394 spec = spec.strip()
395 arch = spec # Default to full spec if no predicates
396
397 match = re.search(pattern, spec)
398 if match:
399 arch = spec[:match.start()].strip()
400 predicates = [p.strip().lower() for p in match.group(1).split(",")]
401 predicateMap[arch].extend(_verifyPredicate(p, arch) for p in predicates)
402
403 if arch not in architectureMap:
404 raise ValueError(f"Architecture {spec} not supported")
405
406 architectures.add(arch)
407
408 return list(architectures), predicateMap or None
409
410
411 def _addVariantMap(
412 gfxPredicateMap: Dict[str, Set[Tuple[Path, str]]], spec: str, path: Path, fname: str
413 ) -> bool:
414 """
415 Adds a logic file to a predicate map.
416
417 Args:
418 gfxPredicateMap: Nested dict mapping architectures to their predicate sets
419 spec: Predicate specification
420 path: Path to the logic file
421 fname: Filename of the logic file
422 Returns:
423 True if the logic file was added to the predicate map, False otherwise
424 """
425 if fname not in {x for _, x in gfxPredicateMap[spec]}:
426 gfxPredicateMap[spec].add((path, fname))
427 return True
428 return False
429
430
431 def _populateVariantMap(
432 predicateMap: Dict[str, Dict[str, Set[Tuple[Path, str]]]],
433 targetLogicFile: Path,
434 fallbackKey: str,
435 ):
436 """
437 Populates a predicate map with logic files, handling both exact matches and fallbacks.
438
439 For each logic file:
440 1. First tries to match against specific predicates (device IDs, CU counts)
441 2. If matched to any specific predicate, removes from fallbacks
442 3. If no specific matches, tries to add to fallbacks based on fallback rules
443
444 Args:
445 predicateMap: Nested dict mapping architectures to their predicate sets
446 targetLogicFile: Logic file to process
447 fallbackKey: Key used to store fallback matches
448 """
449 file = Path(targetLogicFile)
450 path, fname = file.parent, file.name
451
452 archinfo = _extractArchInfo(file)
453 if archinfo.Gfx not in predicateMap:
454 return
455
456 gfxPredicateMap = predicateMap[archinfo.Gfx]
457 requestedDevIds = {x for x in gfxPredicateMap if x.startswith("id=")}
458 requestedCUs = {x for x in gfxPredicateMap if x.startswith("cu=")}
459
460 fallbackDevIds = {
461 fallbackId
462 for v in requestedDevIds
463 if v in ARCH_DEVICE_ID_FALLBACKS
464 for fallbackId in ARCH_DEVICE_ID_FALLBACKS[v]
465 }
466 fallbackCUs = {ARCH_CU_COUNT_FALLBACKS[v] for v in requestedCUs if v in ARCH_CU_COUNT_FALLBACKS}
467
468 isCuFallback = not requestedCUs or archinfo.CUCount in fallbackCUs
469 isDevIdFallback = not requestedDevIds or (
470 archinfo.DeviceIds and any(fallbackId in archinfo.DeviceIds for fallbackId in fallbackDevIds)
471 )
472
473 if isCuFallback and isDevIdFallback:
474 # If the file name is not already in a requested predicate, then add it to the fallback set
475 if all(
476 fname not in {nm for _, nm in gfxPredicateMap[spec]}
477 for spec in gfxPredicateMap
478 if spec != fallbackKey
479 ):
480 gfxPredicateMap[fallbackKey].add((path, fname))
481 else:
482 removeFallbacks = []
483 for spec in gfxPredicateMap:
484 if spec != fallbackKey: # Don't try to add to fallback set here
485 if "id" in spec and archinfo.DeviceIds:
486 removeFallbacks.extend(
487 _addVariantMap(gfxPredicateMap, spec, path, fname)
488 for id in archinfo.DeviceIds
489 if id == spec
490 )
491 if "cu" in spec and archinfo.CUCount:
492 removeFallbacks.append(
493 _addVariantMap(gfxPredicateMap, spec, path, fname)
494 if archinfo.CUCount == spec
495 else False
496 )
497
498 if removeFallbacks and any(removeFallbacks):
499 gfxPredicateMap[fallbackKey] = {
500 x for x in gfxPredicateMap[fallbackKey] if x[1] != fname
501 }
502
503
504 def filterLogicFilesByPredicates(
505 logicFiles: List[str], variants: Dict[str, Dict[str, Set[Tuple[Path, str]]]]
506 ) -> List[str]:
507 """
508 Filters logic files based on the requested predicates.
509
510 Args:
511 logicFiles: List of logic file paths
512 variants: Dictionary mapping architectures to their predicate sets
513
514 Returns:
515 List of logic file paths that match the requested predicates
516 """
517 fallbackKey = "fallback"
518 # A `spec` here is a variant specification passed via the command line, e.g., "cu=64"
519 # This is how the code differentiates variants of the same gfx, as well as "fallback" files
520 variantMap = {gfx: {spec: set() for spec in specs} for gfx, specs in variants.items()}
521 for file in variantMap.values():
522 file[fallbackKey] = set()
523
524 for logicFile in logicFiles:
525 _populateVariantMap(variantMap, Path(logicFile), fallbackKey)
526
527 return [
528 str(p / file)
529 for gfxPredicateMap in variantMap.values()
530 for files in gfxPredicateMap.values()
531 for p, file in files
532 ]