Debian Codegraph @

tensilelite/Tensile/TensileBenchmarkClusterScripts.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 os
26
27 class ScriptHelper(object):
28 """
29 Helper class to facilitate formatting when
30 writing bash scripts.
31 """
32
33 @classmethod
34 def genLine(cls, text):
35 return str("{0}\n").format(text)
36
37 @classmethod
38 def genComment(cls, text):
39 return cls.genLine(str("#") + str(text))
40
41 @classmethod
42 def genEcho(cls, text):
43 return cls.genLine(str("echo \"{0}\";").format(str(text)))
44
45 @classmethod
46 def makeExecutable(cls, path):
47 mode = os.stat(path).st_mode
48 mode |= (mode & 0o444) >> 2 # copy R bits to X
49 os.chmod(path, mode)
50
51 class ScriptWriter(object):
52 """
53 A script writing utility class that holds a string
54 buffer and wraps writing to the buffer.
55 Has factory functions to build scripts with regular
56 workflow interface.
57 """
58 def __init__(self):
59 self._buffer = ""
60
61 def writeLine(self, text):
62 self._buffer += ScriptHelper.genLine(text)
63
64 def writeComment(self, text):
65 self._buffer += ScriptHelper.genComment(text)
66
67 def writeEcho(self, text):
68 self._buffer += ScriptHelper.genEcho(text)
69
70 def dumpToFile(self, fileName, outputDir = "."):
71 scriptPath = os.path.join(outputDir, fileName)
72 with open(scriptPath, "w") as f:
73 f.write(self._buffer)
74 ScriptHelper.makeExecutable(scriptPath)
75
76 def __str__(self):
77 return self._buffer
78
79 @classmethod
80 def writeScript(bufferClass, writerClass, fileName, outputDir = "."):
81 buffer = bufferClass()
82 writerClass.writeHeader(buffer)
83 writerClass.writeBody(buffer)
84 writerClass.writeEpilogue(buffer)
85 buffer.dumpToFile(fileName, outputDir)
86
87 @classmethod
88 def previewScript(bufferClass, writerClass):
89 buffer = bufferClass()
90 writerClass.writeHeader(buffer)
91 writerClass.writeBody(buffer)
92 writerClass.writeEpilogue(buffer)
93 print(buffer)
94
95 @classmethod
96 def writeBenchmarkNodeScript(cls, fileName, outputDir="."):
97 cls.writeScript(BenchmarkNodeWriter, fileName, outputDir)
98
99 @classmethod
100 def writeBenchmarkTaskScript(cls, fileName, outputDir="."):
101 cls.writeScript(BenchmarkTaskWriter, fileName, outputDir)
102
103 @classmethod
104 def writeBenchmarkJobScript(cls, fileName, outputDir="."):
105 cls.writeScript(BenchmarkJobWriter, fileName, outputDir)
106
107
108 class BenchmarkNodeWriter(object):
109 """
110 Node host run script.
111 Creates an instance of the docker image and
112 mounts the logs, results and tasks directories
113 and finally invokes the benchmark on the
114 supplied yaml.
115 """
116 @staticmethod
117 def __initHeader(sBuffer):
118 sBuffer.writeComment("!/bin/bash")
119 sBuffer.writeComment("Benchmark node script")
120 sBuffer.writeComment("Actual host task to be run by a SLURM worker node")
121 sBuffer.writeLine("")
122
123 @staticmethod
124 def __initializeFuncs(sBuffer):
125 sBuffer.writeComment("Funcs")
126 sBuffer.writeLine("usage() { echo \"Usage: $0 [-i <path_to_docker_image>] [-l <log_dir>] [-r <result_dir>] [-t <task_dir>]\" 1>&2; exit 1; }")
127 sBuffer.writeLine("failAndExit() { echo \"FAILED: $1\" 1>&2; exit 1; }")
128 sBuffer.writeLine("")
129
130 @staticmethod
131 def __parseArgs(sBuffer):
132 sBuffer.writeComment("Parse arguments")
133 sBuffer.writeLine("while getopts i:l:r:t: flag")
134 sBuffer.writeLine("do")
135 sBuffer.writeLine(" case \"${flag}\" in")
136 sBuffer.writeLine(" i) dockerImagePath=${OPTARG};;")
137 sBuffer.writeLine(" l) logDir=${OPTARG};;")
138 sBuffer.writeLine(" r) resultDir=${OPTARG};;")
139 sBuffer.writeLine(" t) taskDir=${OPTARG};;")
140 sBuffer.writeLine(" *) usage;;")
141 sBuffer.writeLine(" esac")
142 sBuffer.writeLine("done")
143 sBuffer.writeLine("[ -z \"${dockerImagePath}\" ] || [ -z \"${logDir}\" ] || [ -z \"${resultDir}\" ] || [ -z \"${taskDir}\" ] && usage;")
144 sBuffer.writeLine("[ -d \"${logDir}\" ] && [ -d \"${resultDir}\" ] && [ -d \"${taskDir}\" ] || failAndExit \"Directory not found\";")
145 sBuffer.writeLine("[ -f \"${dockerImagePath}\" ] || failAndExit \"Docker image not found: $dockerImagePath\";")
146 sBuffer.writeEcho("Docker image path: $dockerImagePath")
147 sBuffer.writeEcho("Path to log: $logDir")
148 sBuffer.writeEcho("Path to task: $taskDir")
149 sBuffer.writeEcho("Path to result: $resultDir")
150 sBuffer.writeLine("")
151
152 @staticmethod
153 def __loadDockerImage(sBuffer):
154 sBuffer.writeComment("Import docker image")
155 sBuffer.writeComment("Successful output is \"Loaded image: imageName:TAG\"")
156 sBuffer.writeEcho("Loading docker image...")
157 sBuffer.writeLine("dockerLoadOutput=`docker load < $dockerImagePath || failAndExit \"Importing docker image\"`")
158 sBuffer.writeLine("")
159 sBuffer.writeEcho("Docker Load Result: $dockerLoadOutput")
160 sBuffer.writeLine("[ -z \"${dockerLoadOutput}\" ] && failAndExit \"Loading docker image $dockerImagePath\"")
161 sBuffer.writeLine("")
162 sBuffer.writeComment("Split the output on ':' or spaces")
163 sBuffer.writeComment("Capture the docker image name and tag")
164 sBuffer.writeLine("outputSplit=(${dockerLoadOutput//:/ })")
165 sBuffer.writeLine("dockerName=${outputSplit[2]}")
166 sBuffer.writeLine("dockerTag=${outputSplit[3]}")
167 sBuffer.writeLine("")
168 sBuffer.writeComment("Find docker image record with correct name and tag")
169 sBuffer.writeLine("dockerImageQuery=`docker images | grep -i \"$dockerName\" | grep -i \"$dockerTag\"`")
170 sBuffer.writeLine("[ -z \"${dockerImageQuery}\" ] && failAndExit \"Finding docker image record for $dockerName:$dockerTag\"")
171 sBuffer.writeLine("")
172 sBuffer.writeComment("Get docker image ID")
173 sBuffer.writeLine("outputSplit=(${dockerImageQuery// / })")
174 sBuffer.writeLine("dockerImageId=${outputSplit[2]}")
175 sBuffer.writeLine("[ -z \"${dockerImageId}\" ] && failAndExit \"Finding docker image id for $dockerName:$dockerTag\"")
176 sBuffer.writeEcho("Success: Loaded Image ID: ${dockerImageId}")
177 sBuffer.writeLine("")
178
179 @staticmethod
180 def __runTask(sBuffer):
181 sBuffer.writeComment("Check the task dir exists")
182 sBuffer.writeLine("")
183 sBuffer.writeComment("Run container with mounted taskDir")
184 sBuffer.writeEcho("Running container... (this might take some time):")
185 sBuffer.writeLine("runCmd=\"docker run --rm --network=host --device=/dev/kfd --device=/dev/dri --group-add video --cap-add=SYS_PTRACE --security-opt seccomp=unconfined -v \"$taskDir\":\"/TaskDir\" -v \"$resultDir\":\"/ResultDir\" -v \"$logDir\":\"/LogDir\" $dockerImageId\"")
186 sBuffer.writeEcho("$runCmd")
187 sBuffer.writeLine("$runCmd")
188 sBuffer.writeLine("returnCode=$?")
189
190 @staticmethod
191 def __exit(sBuffer):
192 sBuffer.writeEcho("Done!")
193 sBuffer.writeLine("exit $returnCode")
194
195 @classmethod
196 def writeHeader(cls, sBuffer):
197 cls.__initHeader(sBuffer)
198
199 @classmethod
200 def writeBody(cls, sBuffer):
201 cls.__initializeFuncs(sBuffer)
202 cls.__parseArgs(sBuffer)
203 cls.__loadDockerImage(sBuffer)
204 cls.__runTask(sBuffer)
205
206 @classmethod
207 def writeEpilogue(cls, sBuffer):
208 cls.__exit(sBuffer)
209
210 class BenchmarkTaskWriter(object):
211 """
212 SLURM specific script.
213 Invokes the 'srun' command to queue a task.
214 SLURM environment variables tell us which
215 indexed task to run as part of the array.
216 The final task submitted is the node script
217 which will run on one of the hosts.
218 """
219 @staticmethod
220 def __initHeader(sBuffer):
221 sBuffer.writeComment("!/bin/bash")
222 sBuffer.writeComment("Benchmark task enqueue script")
223 sBuffer.writeComment("This script will configure and commit a single task to the cluster.")
224 sBuffer.writeComment("Intended to be the run target of SLURM SBATCH multiplexer")
225 sBuffer.writeLine("")
226
227 @staticmethod
228 def __initializeFuncs(sBuffer):
229 sBuffer.writeComment("Funcs")
230 sBuffer.writeLine("usage() { echo \"Usage: $0 [-i <image_dir>] [-l <logs_dir>] [-r <results_dir>] [-t <tasks_dir>] \" 1>&2; exit 1; }")
231 sBuffer.writeLine("failAndExit() { echo \"FAILED: $1\" 1>&2; exit 1; }")
232 sBuffer.writeLine("")
233
234 @staticmethod
235 def __parseArgs(sBuffer):
236 sBuffer.writeComment("Parse arguments")
237 sBuffer.writeLine("while getopts i:l:r:t: flag")
238 sBuffer.writeLine("do")
239 sBuffer.writeLine(" case \"${flag}\" in")
240 sBuffer.writeLine(" i) imageDir=${OPTARG};; ")
241 sBuffer.writeLine(" l) logsDir=${OPTARG};;")
242 sBuffer.writeLine(" r) resultsDir=${OPTARG};;")
243 sBuffer.writeLine(" t) tasksDir=${OPTARG};;")
244 sBuffer.writeLine(" *) usage;;")
245 sBuffer.writeLine(" esac")
246 sBuffer.writeLine("done")
247 sBuffer.writeLine("[ -z \"${imageDir}\" ] || [ -z \"${logsDir}\" ] || [ -z \"${resultsDir}\" ] || [ -z \"${tasksDir}\" ] && usage;")
248 sBuffer.writeLine("[ -d \"${imageDir}\" ] && [ -d \"${logsDir}\" ] && [ -d \"${resultsDir}\" ] && [ -d \"${tasksDir}\" ] || failAndExit \"Directory not found\";")
249 sBuffer.writeEcho("Image dir: $imageDir")
250 sBuffer.writeEcho("Logs dir: $logsDir")
251 sBuffer.writeEcho("Tasks dir: $tasksDir")
252 sBuffer.writeEcho("Results dir: $resultsDir")
253 sBuffer.writeLine("")
254
255 @staticmethod
256 def __configureTask(sBuffer):
257 sBuffer.writeComment("Setup task parameters")
258 sBuffer.writeLine("pushd $tasksDir")
259 sBuffer.writeLine("subDirs=(*)")
260 sBuffer.writeLine("taskName=${subDirs[$SLURM_ARRAY_TASK_ID]}")
261 sBuffer.writeLine("taskDir=$tasksDir/$taskName")
262 sBuffer.writeLine("taskResultDir=$resultsDir/$taskName")
263 sBuffer.writeLine("mkdir -p $taskResultDir")
264 sBuffer.writeLine("taskLogDir=$logsDir/$taskName")
265 sBuffer.writeLine("mkdir -p $taskLogDir")
266 sBuffer.writeLine("task=($taskDir/*.sh)")
267 sBuffer.writeLine("image=($imageDir/*.tar.gz)")
268 sBuffer.writeEcho("Task ID: $SLURM_ARRAY_TASK_ID / $SLURM_TASK_MAX")
269 sBuffer.writeEcho("Task Name: $taskName")
270 sBuffer.writeEcho("Host Name: `hostname`")
271 sBuffer.writeLine("")
272
273 @staticmethod
274 def __submitTask(sBuffer):
275 sBuffer.writeComment("Enqueue node task")
276 sBuffer.writeLine("srun -N 1 \"$task\" -i \"$image\" -l \"$taskLogDir\" -r \"$taskResultDir\" -t \"$taskDir\"")
277 sBuffer.writeLine("returnCode=$?")
278
279 @staticmethod
280 def __exit(sBuffer):
281 sBuffer.writeEcho("Done!")
282 sBuffer.writeLine("exit $returnCode")
283
284 @classmethod
285 def writeHeader(cls, sBuffer):
286 cls.__initHeader(sBuffer)
287
288 @classmethod
289 def writeBody(cls, sBuffer):
290 cls.__initializeFuncs(sBuffer)
291 cls.__parseArgs(sBuffer)
292 cls.__configureTask(sBuffer)
293 cls.__submitTask(sBuffer)
294
295 @classmethod
296 def writeEpilogue(cls, sBuffer):
297 cls.__exit(sBuffer)
298
299 class BenchmarkJobWriter(object):
300 """
301 SLURM specific script.
302 Invokes the 'sbatch' and allocates resources.
303 Will create an array of N tasks that will each
304 run one instance of the task script.
305 N = number of sub-folders inside task folder
306 Assumes one node per task.
307 Will wait until the entire batch is complete
308 before exiting.
309 NOTE: the wait feature requires that all task
310 scripts have a return code, or will hang forever!
311 """
312 @staticmethod
313 def __initHeader(sBuffer):
314 sBuffer.writeComment("!/bin/bash")
315 sBuffer.writeComment("Benchmark batch job script")
316 sBuffer.writeComment("This script will configure and submit a batch job to the cluster")
317 sBuffer.writeComment("This is the SLURM cluster benchmark entry-point")
318 sBuffer.writeLine("")
319
320 @staticmethod
321 def __initializeFuncs(sBuffer):
322 sBuffer.writeComment("Funcs")
323 sBuffer.writeLine("usage() { echo \"Usage: $0 [-i <image_dir>] [-l <logs_dir>] [-r <results_dir>] [-s <path_to_task_script>] [-t <tasks_dir>] \" 1>&2; exit 1; }")
324 sBuffer.writeLine("failAndExit() { echo \"FAILED: $1\" 1>&2; exit 1; }")
325 sBuffer.writeLine("")
326
327 @staticmethod
328 def __parseArgs(sBuffer):
329 sBuffer.writeComment("Parse arguments")
330 sBuffer.writeLine("while getopts i:l:r:s:t: flag")
331 sBuffer.writeLine("do")
332 sBuffer.writeLine(" case \"${flag}\" in")
333 sBuffer.writeLine(" i) imageDir=${OPTARG};;")
334 sBuffer.writeLine(" l) logsDir=${OPTARG};;")
335 sBuffer.writeLine(" r) resultsDir=${OPTARG};;")
336 sBuffer.writeLine(" s) taskScript=${OPTARG};;")
337 sBuffer.writeLine(" t) tasksDir=${OPTARG};;")
338 sBuffer.writeLine(" *) usage;;")
339 sBuffer.writeLine(" esac")
340 sBuffer.writeLine("done")
341 sBuffer.writeLine("[ -z \"${imageDir}\" ] || [ -z \"${logsDir}\" ] || [ -z \"${resultsDir}\" ] || [ -z \"${tasksDir}\" ] && usage;")
342 sBuffer.writeLine("[ -d \"${imageDir}\" ] && [ -d \"${logsDir}\" ] && [ -d \"${resultsDir}\" ] && [ -d \"${tasksDir}\" ] || failAndExit \"Directory not found\";")
343 sBuffer.writeLine("[ -f \"${taskScript}\" ] || failAndExit \"Task script not found\";")
344 sBuffer.writeEcho("Image dir: $imageDir")
345 sBuffer.writeEcho("Logs dir: $logsDir")
346 sBuffer.writeEcho("Tasks dir: $tasksDir")
347 sBuffer.writeEcho("Results dir: $resultsDir")
348 sBuffer.writeEcho("Enqueue script: $taskScript")
349 sBuffer.writeLine("")
350
351 @staticmethod
352 def __configureJob(sBuffer):
353 sBuffer.writeComment("Setup local environment")
354 sBuffer.writeComment("Get in the directory where this script lives")
355 sBuffer.writeLine("pushd $( dirname `greadlink -f ${BASH_SOURCE[0]} || readlink -f ${BASH_SOURCE[0]}` )")
356 sBuffer.writeComment("Enumerate the tasks and set up batch params based on task count")
357 sBuffer.writeLine("subDirs=($tasksDir/*)")
358 sBuffer.writeLine("let arraySize=${#subDirs[@]}")
359 sBuffer.writeLine("[ -z \"${arraySize}\" ] && failAndExit \"No task count\";")
360 sBuffer.writeLine("let arrayStart=0")
361 sBuffer.writeLine("let arrayEnd=$arraySize-1")
362 sBuffer.writeComment("Create logs directory for SLURM")
363 sBuffer.writeLine("slurmLogsDir=$logsDir/SLURM")
364 sBuffer.writeLine("mkdir -p $slurmLogsDir")
365 sBuffer.writeLine("")
366
367 @staticmethod
368 def __submitJob(sBuffer):
369 sBuffer.writeComment("Invoke batch request to SLURM")
370 sBuffer.writeComment("Will wait until the task completes before exiting")
371 sBuffer.writeLine("runCmd=\"sbatch --nodes=1 --array=$arrayStart-$arrayEnd -o $slurmLogsDir/slurm-%A_%a.out --wait $taskScript -i $imageDir -l $logsDir -r $resultsDir -t $tasksDir\"")
372 sBuffer.writeEcho("Submitting batch job to SLURM. This may take a while...")
373 sBuffer.writeEcho("$runCmd")
374 sBuffer.writeLine("$runCmd")
375 sBuffer.writeLine("returnCode=$?")
376 sBuffer.writeLine("popd")
377
378 @staticmethod
379 def __exit(sBuffer):
380 sBuffer.writeEcho("Done!")
381 sBuffer.writeLine("exit $returnCode")
382
383 @classmethod
384 def writeHeader(cls, sBuffer):
385 cls.__initHeader(sBuffer)
386
387 @classmethod
388 def writeBody(cls, sBuffer):
389 cls.__initializeFuncs(sBuffer)
390 cls.__parseArgs(sBuffer)
391 cls.__configureJob(sBuffer)
392 cls.__submitJob(sBuffer)
393
394 @classmethod
395 def writeEpilogue(cls, sBuffer):
396 cls.__exit(sBuffer)