Debian Codegraph @

tensilelite/Tensile/Tests/common/test_config.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 os
26 import pytest
27 import subprocess
28 import yaml
29
30 from Tensile import Tensile
31 from Tensile.Common.DataType import DataType
32
33 ################################################################################
34 # Locate Executables
35 # rocm-smi, hip-clang, rocm_agent_enumerator
36 ################################################################################
37 def isExe( filePath ):
38 return os.path.isfile(filePath) and os.access(filePath, os.X_OK)
39
40 def locateExe( defaultPath, exeName ): # /opt/rocm/bin, hip-clang
41 # look in path first
42 for path in os.environ["PATH"].split(os.pathsep):
43 exePath = os.path.join(path, exeName)
44 if isExe(exePath):
45 return exePath
46 # look in default path second
47 exePath = os.path.join(defaultPath, exeName)
48 if isExe(exePath):
49 return exePath
50 return None
51
52 def walkDict(root, path=""):
53 """
54 Recursively walks a structure which may consist of dictionaries, lists,
55 and other objects. Yields (object, path) for each object in the
56 structure.
57 """
58 yield root, path
59 if isinstance(root, dict):
60 for key, value in root.items():
61 keypath = key
62 if path != "":
63 keypath = path + "." + str(keypath)
64 yield from walkDict(value, keypath)
65 elif isinstance(root, list):
66 for i,obj in enumerate(root):
67 keypath = str(i)
68 if path != "":
69 keypath = path + "." + keypath
70 yield from walkDict(obj, keypath)
71
72 def markNamed(name):
73 """
74 Gets a mark by a name contained in a variable.
75 """
76 return getattr(pytest.mark, name)
77
78 def configMarks(filepath, rootDir, availableArchs):
79 """
80 Returns a list of marks to add to a particular YAML config path. Currently gets a mark for:
81
82 - Root directory name. This separates tests into pre_checkin, nightly, etc.
83 - Expected failures. Include 'xfail' in the name of the YAML file.
84 - Anything in yaml["TestParameters"]["marks"]
85 - validate / validateAll - whether the test validates (all?) results.
86 - Data type(s) used in the YAML
87 - Problem type(s) used in the YAML
88 - Kernel language(s) used in the YAML
89 """
90 relpath = os.path.relpath(filepath, rootDir)
91 components = relpath.split(os.path.sep)
92
93 # First part of directory - nightly, pre-checkin, etc.
94 marks = list([markNamed(component) for component in components[:-1]])
95
96 if 'xfail' in relpath or 'wip' in relpath:
97 marks.append(pytest.mark.xfail)
98 if 'disabled' in relpath:
99 marks.append(pytest.mark.skip)
100
101 try:
102 with open(filepath) as f:
103 doc = yaml.load(f, yaml.SafeLoader)
104 except yaml.parser.ParserError:
105 marks.append(pytest.mark.syntax_error)
106 return marks
107
108 if "TestParameters" in doc:
109 if "marks" in doc["TestParameters"]:
110 marks += [markNamed(m) for m in doc["TestParameters"]["marks"]]
111
112 # Architecture specific xfail marks
113 for arch in availableArchs:
114 ArchFail = "xfail-%s" % arch
115 if markNamed(ArchFail) in marks:
116 marks.append(pytest.mark.xfail)
117 ArchSkip = "skip-%s" % arch
118 if markNamed(ArchSkip) in marks:
119 marks.append(pytest.mark.skip)
120
121 validate = True
122 validateAll = False
123 try:
124 if doc["GlobalParameters"]['NumElementsToValidate'] == 0:
125 validate = False
126 if doc["GlobalParameters"]['NumElementsToValidate'] == -1:
127 validateAll = True
128 except KeyError:
129 pass
130
131 if validate:
132 marks.append(pytest.mark.validate)
133 if validateAll:
134 marks.append(pytest.mark.validateAll)
135
136 dataTypes = set([problem[0]["DataType"] for problem in doc["BenchmarkProblems"]])
137 operationTypes = set([problem[0]["OperationType"] for problem in doc["BenchmarkProblems"]])
138
139 languages = set()
140 #print ("***doc=", doc)
141 for obj, path in walkDict(doc):
142 #print (" obj=", obj, "path=", path)
143 if "KernelLanguage" in path and isinstance(obj, str):
144 languages.add(obj)
145
146 for l in languages:
147 marks.append(markNamed(l))
148
149 for dt in dataTypes:
150 dataType = DataType(dt)
151 marks.append(markNamed(dataType.toName()))
152
153 for operationType in operationTypes:
154 marks.append(markNamed(operationType))
155
156 return marks
157
158 def findAvailableArchs():
159 availableArchs = []
160 rocmpath = "/opt/rocm"
161 if "ROCM_PATH" in os.environ:
162 rocmpath = os.environ.get("ROCM_PATH")
163 if "TENSILE_ROCM_PATH" in os.environ:
164 rocmpath = os.environ.get("TENSILE_ROCM_PATH")
165 rocmAgentEnum = os.path.join(rocmpath, "bin/rocm_agent_enumerator")
166 output = subprocess.check_output([rocmAgentEnum, "-t", "GPU"])
167 lines = output.decode().splitlines()
168 for line in lines:
169 line = line.strip()
170 if (not line in availableArchs) and (not "gfx000" in line):
171 availableArchs.append(line)
172 return availableArchs
173
174 def findConfigs(rootDir=None):
175 """
176 Walks rootDir (defaults to trying to find Tensile/Tests) and returns a
177 list of test parameters, one for each YAML file.
178 """
179 if rootDir == None:
180 rootDir = os.path.dirname(os.path.dirname(__file__))
181 printRoot = os.path.dirname(os.path.dirname(rootDir))
182 else:
183 printRoot = rootDir
184
185 availableArchs = findAvailableArchs()
186 globaParamArchsStr = ';'.join(availableArchs)
187 os.environ["PyTestBuildArchNames"] = globaParamArchsStr
188
189 params = []
190 for (dirpath, dirnames, filenames) in os.walk(rootDir):
191 for filename in filenames:
192 # Skip build client script
193 if filename == "build_client.yaml":
194 continue
195 # filter out yamls in logic_yaml since they are not meant for Tensile.py
196 elif filename.endswith('.yaml') and "logic_yaml" not in dirpath:
197 filepath = os.path.join(rootDir, dirpath, filename)
198 if not "test_data" in filepath:
199 marks = configMarks(filepath, rootDir, availableArchs)
200 relpath = os.path.relpath(filepath, printRoot)
201 params.append(pytest.param(filepath, marks=marks, id=relpath))
202 return params
203
204 @pytest.mark.parametrize("config", findConfigs())
205 def test_config(tensile_args, config, tmpdir):
206 Tensile.Tensile([config, tmpdir.strpath, *tensile_args])