Debian Codegraph @

tensilelite/Tensile/TensileBenchmarkCluster.py

raw symbols SCIP
1 ################################################################################
2 #
3 # Copyright (C) 2022 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 shlex, subprocess
26 import sys
27 import os
28 import argparse
29
30 from .BenchmarkSplitter import BenchmarkSplitter
31 from .Configuration import ProjectConfig
32 from .TensileBenchmarkClusterScripts import ScriptWriter
33 from Tensile.Utilities.merge import mergePartialLogics
34
35 try:
36 import mgzip as gzip
37 except ImportError:
38 print("Package mgzip not found: docker zipping will be slow. Install pip3 install mgzip to improve performance.")
39
40 # Fallback package import
41 import gzip
42
43 class BenchmarkImplSLURM(object):
44
45 # baseImage: remote URL to rocm build
46 # dockerFilePath: path to docker file for slurm tensile build
47 # tag: name:TAG of new image
48 # outDir: where to export the new image
49 # tensile<Fork/Branch/Commit>: tensile code to use on github
50 @staticmethod
51 def __createTensileBenchmarkContainer(baseImage, dockerFilePath, tag, outDir, logDir, tensileFork, tensileBranch, tensileCommit):
52 """
53 Build a docker container with a specific
54 ROCm image, Tensile branch and tag. Docker
55 will pre-build the Tensile Client and
56 configure the container to run the benchmark.
57 """
58 # Save stdout and stderr to file
59 with open(os.path.join(logDir, "dockerBuildLog.log"), 'w') as logFile:
60
61 # Docker build command
62 buildCmd = str("\
63 docker build \
64 -t {0} \
65 --pull -f {1} \
66 --build-arg user_uid=$UID \
67 --build-arg base_image={2} \
68 --build-arg tensile_fork={3} \
69 --build-arg tensile_branch={4} \
70 --build-arg tensile_commit={5} \
71 . ").format(tag, dockerFilePath, baseImage, tensileFork, tensileBranch, tensileCommit)
72
73 # Build container and save output streams
74 print("Building docker image: {0} ...".format(tag))
75 print(buildCmd)
76 subprocess.check_call(shlex.split(buildCmd), stdout=logFile, stderr=logFile)
77 print("Done building docker image!")
78
79 # Docker save command
80 imageBaseName = tag.split(':')[0]
81 archivePath = os.path.join(outDir, imageBaseName + str(".tar.gz"))
82 saveCmd = str("docker save {0}").format(tag)
83
84 # Docker will save .tar binary to stdout as long as it's not attached to console.
85 # Pipe stdout into gzip to get smaller .tar.gz archive
86 print("Saving docker image: {0} to {1} ...".format(tag, archivePath))
87
88 with gzip.open(archivePath, 'wb') as zipFile:
89 with subprocess.Popen(shlex.split(saveCmd), stdout=subprocess.PIPE, stderr=logFile) as proc:
90 zipFile.write(proc.stdout.read())
91
92 print("Done saving docker image!")
93
94 @staticmethod
95 def __createClusterBenchmarkScripts(baseDir, tasksDir, taskScriptName, jobScriptName):
96 """
97 Build SLURM specific scripts.
98 Entrypoint is the 'sbatch' command, which will request resources and
99 enqueue several taskScripts.
100 TaskScripts each enqueue a benchmark run to
101 the cluster with 'srun'.
102 NodeScripts are the actual host code on each node to run the benchmark.
103 In this case, they will load the docker image and mount directories
104 that contain the .yaml file, and the results.
105 """
106 # Entrypoint - SLURM specific
107 ScriptWriter.writeBenchmarkJobScript(jobScriptName, baseDir)
108
109 # Job submission script - SLURM specific
110 ScriptWriter.writeBenchmarkTaskScript(taskScriptName, baseDir)
111
112 # Move each individual config into it's own subfolder and create the node host script
113 # These scripts are NOT SLURM specific but rely on the implementation of the executable.
114 configFiles = [f for f in os.listdir(tasksDir) if os.path.isfile(os.path.join(tasksDir, f))]
115 for f in configFiles:
116 (baseFileName, _) = os.path.splitext(f)
117 configSubdir = os.path.join(tasksDir, baseFileName)
118 try:
119 os.makedirs(configSubdir)
120 except:
121 pass
122 os.rename(os.path.join(tasksDir, f), os.path.join(configSubdir, f))
123 ScriptWriter.writeBenchmarkNodeScript(baseFileName + ".sh", configSubdir)
124
125 @classmethod
126 def initializeConfig(cls, config):
127 """
128 Store SLURM backend-specific configurations.
129 These can all be overridden via commandline
130 """
131 # Dirs
132 rootTensileDir = config["RootTensileDir"]
133
134 # SLURM config
135 baseSection = config.createSection("SLURM")
136
137 # Script names
138 section = baseSection.createSection("SCRIPTS")
139 section.createValue("JobScriptName", "runBenchmark.sh")
140 section.createValue("TaskScriptName", "enqueueTask.sh")
141
142 # Docker build
143 section = baseSection.createSection("DOCKER")
144 section.createValue("DockerBaseImage", "compute-artifactory.amd.com:5000/rocm-plus-docker/compute-rocm-dkms-amd-feature-targetid:3004-STG1")
145 section.createValue("DockerBuildFile", os.path.join(rootTensileDir, "docker", "dockerfile-tensile-tuning-slurm"))
146 section.createValue("DockerImageName", "tensile-tuning-cluster-executable")
147 section.createValue("DockerImageTag", "TEST")
148 section.createValue("TensileFork", "ROCmSoftwarePlatform")
149 section.createValue("TensileBranch", "develop")
150 section.createValue("TensileCommit", "HEAD")
151
152 @classmethod
153 def generateBenchmark(cls, config):
154 """
155 Build executables used in SLURM backend,
156 based on configuration parameters
157 """
158 # Dirs
159 (baseDir, tasksDir, imageDir, logsDir) = \
160 (config["BenchmarkBaseDir"], \
161 config["BenchmarkTasksDir"], \
162 config["BenchmarkImageDir"], \
163 config["BenchmarkLogsDir"])
164
165 # Create the base image for task executable in image dir
166 sConfig = config["SLURM"]["DOCKER"]
167 cls.__createTensileBenchmarkContainer( \
168 sConfig["DockerBaseImage"], \
169 sConfig["DockerBuildFile"], \
170 "{0}:{1}".format(sConfig["DockerImageName"], sConfig["DockerImageTag"]), \
171 imageDir, \
172 logsDir, \
173 sConfig["TensileFork"], \
174 sConfig["TensileBranch"], \
175 sConfig["TensileCommit"])
176
177 # Create the scripts that will be used to invoke the benchmark in base dir
178 # Create the scripts that node hosts will run in the tasks dir
179 sConfig = config["SLURM"]["SCRIPTS"]
180 cls.__createClusterBenchmarkScripts( \
181 baseDir, \
182 tasksDir, \
183 sConfig["TaskScriptName"], \
184 sConfig["JobScriptName"])
185
186 @classmethod
187 def preInvokeBenchmark(cls, config):
188 pass
189
190 @classmethod
191 def invokeBenchmark(cls, config):
192
193 # Dirs
194 (baseDir, tasksDir, imageDir, resultsDir, logsDir) = \
195 (config["BenchmarkBaseDir"], \
196 config["BenchmarkTasksDir"], \
197 config["BenchmarkImageDir"], \
198 config["BenchmarkResultsDir"], \
199 config["BenchmarkLogsDir"])
200
201 # Entry point script
202 scriptName = config["SLURM"]["SCRIPTS"]["JobScriptName"]
203 runScriptPath = os.path.join(baseDir, scriptName)
204
205 # Enqueue script
206 enqueueScriptName = config["SLURM"]["SCRIPTS"]["TaskScriptName"]
207 enqueueScriptPath = os.path.join(baseDir, enqueueScriptName)
208
209 # Log file
210 (name, ext) = os.path.splitext(scriptName)
211 logFilePath = os.path.join(logsDir, name + ".log")
212
213 invokeCmd = str("\
214 {0} \
215 -i {1} \
216 -l {2} \
217 -r {3} \
218 -s {4} \
219 -t {5}").format(runScriptPath, imageDir, logsDir, resultsDir, enqueueScriptPath, tasksDir)
220
221 with open(logFilePath, "wt") as logFile:
222 subprocess.check_call(shlex.split(invokeCmd), stdout=logFile, stderr=logFile)
223
224 @classmethod
225 def postInvokeBenchmark(cls, benchmarkObj):
226 pass
227
228
229 class TensileBenchmarkCluster(object):
230 """
231 This is the main driver class for building and running
232 benchmarks with a cluster-configured backend.
233
234 The general workflow (main):
235 - Deploy benchmark
236 - Invoke benchmark
237 - Merge results
238
239 Expected backend interface:
240 - initializeConfig
241 - generateBenchmark
242 - preInvokeBenchmark
243 - invokeBenchmark
244 - postInvokeBenchmark
245
246 Other notes:
247 - The command line provides full control over
248 workflow and configuration.
249 - You can choose different backends as they
250 become available
251 - Workflow steps may be selected individually
252 - Any part of configuration may be overidden
253 by command line args.
254 """
255
256 def __init__(self, cmdlineArgs):
257 self._config = ProjectConfig()
258 self.__initializeConfig(cmdlineArgs)
259
260 def __initializeConfig(self, cmdlineArgs):
261
262 """
263 Initialize configuration parameters needed
264 to build and run the benchmark.
265 """
266
267 # 1. Parse command line
268 args = self.__parseArgs(cmdlineArgs)
269
270 # 2. Setup default configurations that depend on inputs
271 # Directories
272 self._config.createValue("RootTensileDir", os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
273 self._config.createValue("BenchmarkLogicPath", args.BenchmarkLogicPath)
274 self._config.createValue("BenchmarkBaseDir", args.DeploymentPath)
275 self._config.createValue("BenchmarkTasksDir", os.path.join(args.DeploymentPath, "Tasks"))
276 self._config.createValue("BenchmarkImageDir", os.path.join(args.DeploymentPath, "Image"))
277 self._config.createValue("BenchmarkResultsDir", os.path.join(args.DeploymentPath, "Results"))
278 self._config.createValue("BenchmarkFinalLogicDir", os.path.join(args.DeploymentPath, "Results", "Final"))
279 self._config.createValue("BenchmarkLogsDir", os.path.join(args.DeploymentPath, "Logs"))
280
281 # Benchmarking
282 self._config.createValue("BenchmarkTaskSize", 10) # Sizes per benchmark file
283 self._config.addConstraint("BenchmarkTaskSize > 0")
284
285 self._config.createValue("RunDeployStep", True and (not args.RunOnly and not args.ResultsOnly and not args.RunAndResultsOnly))
286 self._config.createValue("RunBenchmarkStep", True and (not args.DeployOnly and not args.ResultsOnly))
287 self._config.createValue("RunResultsStep", True and (not args.DeployOnly and not args.RunOnly))
288 self._config.addConstraint("RunDeployStep or RunBenchmarkStep or RunResultsStep")
289
290 # Results merging settings
291 self._config.createValue("FinalLogicForceMerge", False)
292 self._config.createValue("FinalLogicTrim", True)
293
294 # Initialize the backend implementation
295 if args.ClusterBackend.lower() == "slurm":
296 self._backendImpl = BenchmarkImplSLURM
297 else:
298 raise NotImplementedError("Cluster backend not recognized")
299
300 # 3. Setup backend configuration
301 self._backendImpl.initializeConfig(self._config)
302
303 # 4. Override requested config parameters
304 overrideArgs = {}
305 for key, value in args.benchmark_parameters:
306 overrideArgs[key] = value
307 self.__overrideConfig(overrideArgs)
308
309 self._config.checkConstraints()
310
311 @staticmethod
312 def __parseArgs(cmdlineArgs):
313 """
314 Parse input arguments to call script
315 """
316
317 def splitExtraParameters(par):
318 """
319 Allows the --benchmark-parameters option to specify any parameters from the command line.
320 """
321 (key, value) = par.split("=")
322 value = eval(value)
323 return (key, value)
324
325 # Parse incoming args
326 argParser = argparse.ArgumentParser()
327 argParser.add_argument("BenchmarkLogicPath", help="Path to benchmark config .yaml files.")
328 argParser.add_argument("DeploymentPath", help="Where to deploy benchmarking files. Should target a directory on shared nfs mount of cluster.")
329 argParser.add_argument("--cluster-backend", dest="ClusterBackend", type=str, default="slurm", help="Choose backend plugin to run benchmark")
330 argParser.add_argument("--deploy-only", dest="DeployOnly", action="store_true", default=False, help="Deploy benchmarking files only without running or reducing results")
331 argParser.add_argument("--run-only", dest="RunOnly", action="store_true", default=False, help="Run benchmark without deploying or reducing results")
332 argParser.add_argument("--results-only", dest="ResultsOnly", action="store_true", default=False, help="Reduce results without deploying or running")
333 argParser.add_argument("--run-and-results-only", dest="RunAndResultsOnly", action="store_true", default=False, help="Run benchmark and reduce results without deploying")
334 argParser.add_argument("--benchmark-parameters", nargs="+", type=splitExtraParameters, default=[], help="Pairs of X=Y assignments. Note: if Y is a string, then it must have escaped quotes \\\"Y\\\"")
335 return argParser.parse_args()
336
337 def __overrideConfig(self, args):
338 """
339 Assign Benchmark Parameters
340 Each parameter has a default parameter, and the user
341 can override them, those overridings happen here
342 """
343 for key in args:
344 value = args[key]
345 if key not in self._config:
346 print("Warning: Benchmark parameter {0} = {1} unrecognised.".format( key, value ))
347 else:
348 self._config[key] = value
349
350 def __generateClusterBenchmark(self):
351 """
352 Generate everything for the benchmark to run
353 """
354 # Ensure that we have all directories
355 self.ensurePath(self.baseDir())
356 self.ensurePath(self.tasksDir())
357 self.ensurePath(self.imageDir())
358 self.ensurePath(self.resultsDir())
359 self.ensurePath(self.finalLogicDir())
360 self.ensurePath(self.logsDir())
361
362 # Split master config into smaller task-sized configs
363 # These are stored under the tasks dir
364 BenchmarkSplitter.splitBenchmarkBySizes( \
365 self._config["BenchmarkLogicPath"], \
366 self.tasksDir(), \
367 self._config["BenchmarkTaskSize"], \
368 suffixFormat="{:04d}") # Support lots of jobs up to 9999
369
370 # Delegate to the backend implementation to generate everything it needs for the benchmark run
371 self._backendImpl.generateBenchmark(self._config)
372
373 def __runClusterBenchmark(self):
374 """
375 Invoke backend benchmark
376 """
377 # Delegate to the backend implementation to invoke
378 self._backendImpl.preInvokeBenchmark(self._config)
379 self._backendImpl.invokeBenchmark(self._config)
380 self._backendImpl.postInvokeBenchmark(self._config)
381
382 def __combineClusterBenchmarkResults(self):
383 """
384 Combine all partial results into the final
385 kernel logic.
386 Each partial result is expected to be under
387 the base/ResultsDir/<PART>/3_LibraryLogic
388 directory.
389 """
390 (resultsDir, finalLogicDir) = (self.resultsDir(), self.finalLogicDir())
391
392 # Find the partial logic .yaml files
393 # These are in each result directory under 3_LibraryLogic
394 resultsDirs = [os.path.join(resultsDir, d, "3_LibraryLogic") for d in os.listdir(resultsDir) if os.path.isdir(os.path.join(resultsDir, d, "3_LibraryLogic"))]
395
396 resultsFiles = []
397 for d in resultsDirs:
398 resultsFiles += [os.path.join(d, f) for f in os.listdir(d) if os.path.isfile(os.path.join(d, f)) ]
399
400 if len(resultsDirs) != len(resultsFiles):
401 print("Warning: inconsistent number of expected results. Check that results are complete.")
402
403 mergePartialLogics(
404 resultsFiles, \
405 finalLogicDir, \
406 self._config["FinalLogicForceMerge"], \
407 self._config["FinalLogicTrim"])
408
409 def workflowSteps(self):
410 """
411 Helper function to easily receive a tuple of important
412 workflow step indicators
413 """
414 return( \
415 self._config["RunDeployStep"], \
416 self._config["RunBenchmarkStep"], \
417 self._config["RunResultsStep"])
418
419 def config(self):
420 return self._config
421
422 def rootTensileDir(self):
423 return self.config()["RootTensileDir"]
424
425 def baseDir(self):
426 return self.config()["BenchmarkBaseDir"]
427
428 def tasksDir(self):
429 return self.config()["BenchmarkTasksDir"]
430
431 def imageDir(self):
432 return self.config()["BenchmarkImageDir"]
433
434 def resultsDir(self):
435 return self.config()["BenchmarkResultsDir"]
436
437 def finalLogicDir(self):
438 return self.config()["BenchmarkFinalLogicDir"]
439
440 def logsDir(self):
441 return self.config()["BenchmarkLogsDir"]
442
443 @staticmethod
444 def ensurePath(path):
445 """
446 Helper function to create path if necessary
447 """
448 try:
449 os.makedirs(path)
450 except OSError:
451 pass
452 return path
453
454 def main(self):
455
456 """
457 Main driver for benchmark:
458 - Deploy
459 - Run
460 - Results
461 """
462 (doDeploy, doBenchmark, doResults) = self.workflowSteps()
463
464 # Deploy
465 if doDeploy is True:
466 print("Preparing benchmarking files...")
467 self.__generateClusterBenchmark()
468 print("Finished preparing benchmarking files")
469
470 # Benchmark invoke
471 if doBenchmark is True:
472 print("Running benchmark tasks (this might take a while)...")
473 self.__runClusterBenchmark()
474 print("Finished benchmark tasks")
475
476 # Combining results
477 if doResults is True:
478 print("Combining benchmark results...")
479 self.__combineClusterBenchmarkResults()
480 print("Final logic file saved to: {0}".format(self.finalLogicDir()))
481
482 print("Finished")
483
484 def main():
485 entryPoint = TensileBenchmarkCluster(sys.argv[1:])
486 entryPoint.main()