| 1 | #!/usr/bin/python3 |
| 2 | |
| 3 | # |
| 4 | # SPDX-FileCopyrightText: Copyright 2025-2026 Arm Limited and/or its affiliates <open-source-office@arm.com> |
| 5 | # |
| 6 | # SPDX-License-Identifier: Apache-2.0 |
| 7 | # |
| 8 | import argparse |
| 9 | import datetime |
| 10 | import logging |
| 11 | import os |
| 12 | import queue |
| 13 | import random |
| 14 | import re |
| 15 | import sys |
| 16 | import threading |
| 17 | import time |
| 18 | from concurrent.futures import ThreadPoolExecutor |
| 19 | from pathlib import Path |
| 20 | |
| 21 | # Default arguments |
| 22 | DEFAULT_ARGS = "" |
| 23 | |
| 24 | # Command to run gemm |
| 25 | BINARY = "./gemm" |
| 26 | |
| 27 | LAST_ERROR = 0 |
| 28 | time_id = datetime.datetime.now().strftime("%Y-%m-%d_%H:%M:%S") |
| 29 | SOAKDIR = f"soak-{time_id}" |
| 30 | |
| 31 | # Test Plan |
| 32 | test_plan = set() |
| 33 | failed_tests = set() |
| 34 | |
| 35 | |
| 36 | class ThreadManager: |
| 37 | def __init__(self, maxthreads, queuesize): |
| 38 | self.maxthreads = maxthreads |
| 39 | self.queuesize = queuesize |
| 40 | self.executor = ThreadPoolExecutor(max_workers=maxthreads) |
| 41 | self.executor._work_queue = queue.Queue(maxsize=queuesize) |
| 42 | self.lock = threading.Lock() |
| 43 | self.futures = queue.Queue() |
| 44 | |
| 45 | def queue_work(self, func, args): |
| 46 | logging.debug("Queueing work in the ThreadManager...") |
| 47 | |
| 48 | # Clean the futures log as we queue to raise errors early |
| 49 | while not self.futures.empty() and self.futures.queue[0].done(): |
| 50 | future = self.futures.get() |
| 51 | |
| 52 | # This call raises exception if thread couldn't run for some reason. |
| 53 | # This is especially necessary if there is a syntax issue |
| 54 | # within the function being called. This ensures we return |
| 55 | # a non-zero code to the caller. |
| 56 | future.result() |
| 57 | |
| 58 | future = self.executor.submit(func, *args) |
| 59 | self.futures.put(future) |
| 60 | |
| 61 | def shutdown(self): |
| 62 | logging.debug("Shutting Down the ThreadManager...") |
| 63 | |
| 64 | for future in self.futures.queue: |
| 65 | # See queue_work() for explanation of this call. |
| 66 | future.result() |
| 67 | |
| 68 | self.executor.shutdown() |
| 69 | |
| 70 | |
| 71 | def log_error(tm, cmdline, output): |
| 72 | global LAST_ERROR |
| 73 | |
| 74 | with tm.lock: |
| 75 | try: |
| 76 | os.makedirs(SOAKDIR) |
| 77 | except FileExistsError: |
| 78 | pass |
| 79 | |
| 80 | filename = "{}/soak-error-{}.log".format(SOAKDIR, LAST_ERROR) |
| 81 | with open(filename, "w") as f: |
| 82 | f.write("Error log {}:\n".format(LAST_ERROR)) |
| 83 | f.write("Command line: {}\n".format(cmdline)) |
| 84 | f.write("Output:\n") |
| 85 | f.write(output) |
| 86 | |
| 87 | LAST_ERROR += 1 |
| 88 | |
| 89 | |
| 90 | def do_gemm_cmd(args): |
| 91 | cmd = f"{BINARY} {DEFAULT_ARGS} {args}" |
| 92 | logging.debug(f"do_gemm_cmd: \t{cmd}") |
| 93 | |
| 94 | sp = os.popen(cmd) |
| 95 | output = sp.read() |
| 96 | returncode = sp.close() |
| 97 | |
| 98 | if returncode is not None: |
| 99 | if returncode == -512: |
| 100 | raise KeyboardInterrupt |
| 101 | |
| 102 | return output + "Error/crash: return code = {}\n".format(returncode) |
| 103 | |
| 104 | return output |
| 105 | |
| 106 | |
| 107 | def get_kern_list(): |
| 108 | lines = do_gemm_cmd("").split("\n") |
| 109 | |
| 110 | kerns = [] |
| 111 | |
| 112 | state = "waiting" |
| 113 | for l in lines: |
| 114 | l = l.rstrip() |
| 115 | if state == "waiting": |
| 116 | if l == "List of available kernels:": |
| 117 | state = "active" |
| 118 | elif state == "active": |
| 119 | if len(l) > 0 and l[0] == "\t": |
| 120 | kerns.append(l[1:].split(" ")[0]) |
| 121 | else: |
| 122 | return kerns |
| 123 | |
| 124 | raise Exception("Unable to parse kernel list.") |
| 125 | |
| 126 | |
| 127 | class testcase(object): |
| 128 | def __repr__(self): |
| 129 | if self.dump_file: |
| 130 | return f"testcase(dump, file={self.dump_file})" |
| 131 | elif self.args.run_test_plan: |
| 132 | return f"testcase(extra_args={self.extra_args})" |
| 133 | elif self.conv: |
| 134 | return f"testcase(conv, ID={self.ID}, type={self.conv_type}, bias={self.bias}, act={self.act})" |
| 135 | else: |
| 136 | return f"testcase(gemm, M={self.M}, N={self.N}, K={self.K}, batch={self.batches}, multi={self.multis}, bias={self.bias}, act={self.act})" |
| 137 | |
| 138 | def __init__(self, args, dump_file=None, extra_args=""): |
| 139 | self.conv = args.conv |
| 140 | self.dump_file = dump_file |
| 141 | self.args = args |
| 142 | self.extra_args = extra_args |
| 143 | |
| 144 | if self.dump_file: |
| 145 | print(f"Initializing testcase from dump file: {dump_file} {extra_args}") |
| 146 | return |
| 147 | |
| 148 | if self.args.run_test_plan: |
| 149 | logging.debug("Running testcase from the test plan") |
| 150 | return |
| 151 | |
| 152 | repeat = True |
| 153 | |
| 154 | self.threads = random.choice(["", "-t 2", "-t 4", "-t 7"]) |
| 155 | self.cpu = random.choice( |
| 156 | [ |
| 157 | "", |
| 158 | "-C 0x4111d050", |
| 159 | "-C 0x4111d030", |
| 160 | "-C 0x461f0010", |
| 161 | "-C 0x410fd440", |
| 162 | "-C 0x410fd460", |
| 163 | ] |
| 164 | ) |
| 165 | self.bias = random.choice(["", "-b", "-A"]) |
| 166 | self.act = random.choice(["", "-a relu", "-a relu6", "-a relu7"]) |
| 167 | self.fast = random.choice(["", "-f"]) |
| 168 | self.fixed_format = random.choice(["", "-P"]) |
| 169 | |
| 170 | self.extra_args = f"{self.extra_args} {self.threads} {self.bias} {self.act} {self.fast} {self.fixed_format} {self.cpu}" |
| 171 | |
| 172 | if self.conv: |
| 173 | self.ID = random.randrange(1, 2**31) |
| 174 | self.conv_type = random.choice( |
| 175 | ["-V convolution", "-V indirect", "-V im2row"] |
| 176 | ) |
| 177 | |
| 178 | print( |
| 179 | f"Initializing testcase: ID={self.ID}, conv={self.conv_type}, {self.extra_args}" |
| 180 | ) |
| 181 | else: |
| 182 | while repeat: |
| 183 | Krange = random.choice([(1, 33), (32, 200), (200, 2000)]) |
| 184 | Mrange = random.choice([(1, 4), (3, 100), (101, 2000)]) |
| 185 | Nrange = random.choice([(1, 33), (32, 201), (200, 2000)]) |
| 186 | |
| 187 | self.M = random.randrange(Mrange[0], Mrange[1]) |
| 188 | if args.gemv: |
| 189 | self.M = 1 |
| 190 | self.N = random.randrange(Nrange[0], Nrange[1]) |
| 191 | self.K = random.randrange(Krange[0], Krange[1]) |
| 192 | self.multis = random.randrange(1, 3) |
| 193 | self.batches = random.randrange(1, 3) |
| 194 | self.pre = "" |
| 195 | self.trans = "" |
| 196 | |
| 197 | if args.nobatch: |
| 198 | self.batches = 1 |
| 199 | |
| 200 | # Don't allow really big test cases (>1B macs) |
| 201 | totalmacs = self.M * self.N * self.K * self.multis * self.batches |
| 202 | if totalmacs < 100000000: |
| 203 | repeat = False |
| 204 | |
| 205 | print( |
| 206 | f"Initializing testcase: M={self.M}, N={self.N}, K={self.K}, multis={self.multis}, batches={self.batches} {self.extra_args}" |
| 207 | ) |
| 208 | |
| 209 | def main_args(self): |
| 210 | if self.dump_file: |
| 211 | main_args = f"-O {self.dump_file} {self.extra_args}" |
| 212 | elif self.args.run_test_plan: |
| 213 | main_args = f"{self.extra_args}" |
| 214 | elif self.conv: |
| 215 | main_args = ( |
| 216 | f"-D {self.args.suite} -n {self.ID} {self.conv_type} {self.extra_args}" |
| 217 | ) |
| 218 | else: |
| 219 | main_args = f"-M {self.M} -N {self.N} -K {self.K} -y {self.batches} -z {self.multis} {self.extra_args}" |
| 220 | |
| 221 | return re.sub(r"\s+", " ", main_args).strip() |
| 222 | |
| 223 | def get_subkernels(self, kernel): |
| 224 | logging.debug("get_subkernels()") |
| 225 | lines = do_gemm_cmd( |
| 226 | "{} {} -q {}".format(self.main_args(), self.extra_args, kernel) |
| 227 | ).split("\n") |
| 228 | subkerns = [] |
| 229 | |
| 230 | state = "waiting" |
| 231 | for l in lines: |
| 232 | l = l.rstrip() |
| 233 | if state == "waiting": |
| 234 | if l == "Available kernels:": |
| 235 | state = "active" |
| 236 | elif state == "active": |
| 237 | if len(l) > 0 and l[0] == "\t": |
| 238 | subkerns.append(l[2:].split(" ")[0]) |
| 239 | else: |
| 240 | break |
| 241 | |
| 242 | return subkerns |
| 243 | |
| 244 | def run(self, tm, kernel, subkernel, brief): |
| 245 | logging.debug("run()") |
| 246 | |
| 247 | main_args = self.main_args() |
| 248 | if subkernel is None: |
| 249 | thecmdline = f"{main_args} -c {kernel}" |
| 250 | else: |
| 251 | thecmdline = f"{main_args} -F {subkernel} -c {kernel}" |
| 252 | |
| 253 | output = do_gemm_cmd(thecmdline) |
| 254 | |
| 255 | if output.find("Compare OK") > -1: |
| 256 | if not brief: |
| 257 | print( |
| 258 | "Kernel {}, subkernel {} passed OK with {}".format( |
| 259 | kernel, subkernel, main_args |
| 260 | ) |
| 261 | ) |
| 262 | |
| 263 | if self.args.test_plan_file and not args.run_test_plan: |
| 264 | test_plan.add(main_args) |
| 265 | |
| 266 | elif output.find("Winograd: Unsupported kernel size:") > -1: |
| 267 | print( |
| 268 | "Kernel {}, subkernel {} skipped (unsupported size).".format( |
| 269 | kernel, subkernel |
| 270 | ) |
| 271 | ) |
| 272 | elif output.find("does not support convolution problems, aborting.") > -1: |
| 273 | print( |
| 274 | "Kernel {}, subkernel {} skipped (non-convolution kernel).".format( |
| 275 | kernel, subkernel |
| 276 | ) |
| 277 | ) |
| 278 | elif output.find("kai_ops_wrapper:") > -1 or output.find("Depthwise:") > -1: |
| 279 | print( |
| 280 | "Kernel {}, subkernel {} skipped (bad size).".format(kernel, subkernel) |
| 281 | ) |
| 282 | elif output.find("emory allocation error.") > -1: |
| 283 | print( |
| 284 | "Kernel {}, subkernel {}: Aborted (memory allocation error).".format( |
| 285 | kernel, subkernel |
| 286 | ) |
| 287 | ) |
| 288 | elif ( |
| 289 | output.find( |
| 290 | "Accumulated value too large - test data not reassociation safe" |
| 291 | ) |
| 292 | > -1 |
| 293 | ): |
| 294 | print(f"Kernel {kernel}, subkernel {subkernel} skipped (bad data).") |
| 295 | else: |
| 296 | print( |
| 297 | "Kernel {}, subkernel {}: Unexpected output, created error log.".format( |
| 298 | kernel, subkernel |
| 299 | ) |
| 300 | ) |
| 301 | log_error(tm, thecmdline, output) |
| 302 | |
| 303 | if self.args.test_plan_file: |
| 304 | failed_tests.add(main_args) |
| 305 | |
| 306 | |
| 307 | def run_one_kernel(tm, case, k, args): |
| 308 | logging.debug(f"run_one_kernel() with {k}") |
| 309 | subkerns = case.get_subkernels(k) |
| 310 | logging.debug(f"Subkernels of {k}: {subkerns}") |
| 311 | |
| 312 | if len(subkerns) == 0 and args.legacy: |
| 313 | case.run(tm, k, None, args.brief) |
| 314 | |
| 315 | for sk in subkerns: |
| 316 | if sk.find(args.subkernel_filter) != -1: |
| 317 | case.run(tm, k, sk, args.brief) |
| 318 | |
| 319 | |
| 320 | def make_case(tm, kerns, args, dump_file=None, extra_args=""): |
| 321 | logging.debug("Making Case...") |
| 322 | case = testcase(args, dump_file, extra_args) |
| 323 | logging.debug(f"Case: {case}") |
| 324 | |
| 325 | for k in kerns: |
| 326 | if k.find(args.kernel_filter) != -1: |
| 327 | logging.debug(f"\tQueueing the case for kernel {k}") |
| 328 | tm.queue_work(run_one_kernel, (tm, case, k, args)) |
| 329 | |
| 330 | |
| 331 | if __name__ == "__main__": |
| 332 | start = time.time() |
| 333 | |
| 334 | parser = argparse.ArgumentParser() |
| 335 | parser.add_argument( |
| 336 | "--brief", |
| 337 | help="Don't print 'OK' results for individual kernels", |
| 338 | action="store_true", |
| 339 | ) |
| 340 | parser.add_argument("--binary", help="Set binary to run", default=BINARY) |
| 341 | parser.add_argument("--threads", help="Set thread count", default=1, type=int) |
| 342 | parser.add_argument( |
| 343 | "--conv", help="Generate convolution testcases", action="store_true" |
| 344 | ) |
| 345 | parser.add_argument("--kernel_filter", help="Set kernel filter", default="") |
| 346 | parser.add_argument("--subkernel_filter", help="Set subkernel filter", default="") |
| 347 | parser.add_argument("--gemv", help="Force GEMV cases (M==1)", action="store_true") |
| 348 | parser.add_argument("--legacy", help="Run legacy kernels", action="store_true") |
| 349 | parser.add_argument("--nobatch", help="Force batches==1", action="store_true") |
| 350 | parser.add_argument( |
| 351 | "--suite", |
| 352 | help="Which suite to use (for convolution cases)", |
| 353 | default="random_conv2d", |
| 354 | ) |
| 355 | parser.add_argument( |
| 356 | "--dumpdir", help="Directory of dumps to run", default=None, type=str |
| 357 | ) |
| 358 | parser.add_argument( |
| 359 | "--case_limit", help="Max test cases to generate/run", default=None, type=int |
| 360 | ) |
| 361 | parser.add_argument( |
| 362 | "--log-level", default="info", choices=["debug", "info", "warning", "error"] |
| 363 | ) |
| 364 | parser.add_argument( |
| 365 | "--test_plan_file", |
| 366 | help="File that stores/will store the test configs", |
| 367 | default=None, |
| 368 | type=str, |
| 369 | ) |
| 370 | parser.add_argument( |
| 371 | "--run_test_plan", help="Run a pre-determined set of tests", action="store_true" |
| 372 | ) |
| 373 | parser.add_argument( |
| 374 | "--skip_cases", |
| 375 | help="Number of test cases to skip in the test plan", |
| 376 | default=0, |
| 377 | type=int, |
| 378 | ) |
| 379 | |
| 380 | args = parser.parse_args() |
| 381 | |
| 382 | if args.run_test_plan: |
| 383 | assert args.test_plan_file != None |
| 384 | assert not args.nobatch |
| 385 | assert not args.gemv |
| 386 | |
| 387 | assert args.skip_cases >= 0 |
| 388 | |
| 389 | if args.skip_cases != 0: |
| 390 | assert ( |
| 391 | args.run_test_plan |
| 392 | ), "We can only skip the tests in a deterministic test plan" |
| 393 | |
| 394 | # Setup logging |
| 395 | numeric_level = getattr(logging, args.log_level.upper(), logging.INFO) |
| 396 | logging.basicConfig(level=numeric_level, format="%(levelname)s: %(message)s") |
| 397 | |
| 398 | BINARY = args.binary |
| 399 | |
| 400 | kerns = get_kern_list() |
| 401 | |
| 402 | tm = ThreadManager(args.threads, args.threads * 3) |
| 403 | |
| 404 | total_cases = 0 |
| 405 | |
| 406 | if args.dumpdir: |
| 407 | logging.info("Test Dump Mode") |
| 408 | directory = Path(args.dumpdir) |
| 409 | |
| 410 | for file in directory.iterdir(): |
| 411 | if file.is_file: |
| 412 | parts = file.name.split("-") |
| 413 | if parts[1] == "fast": |
| 414 | args_base = "-f" |
| 415 | else: |
| 416 | args_base = "" |
| 417 | |
| 418 | make_case(tm, [parts[0]], args, dump_file=file, extra_args=args_base) |
| 419 | make_case( |
| 420 | tm, [parts[0]], args, dump_file=file, extra_args=f"-P {args_base}" |
| 421 | ) |
| 422 | elif args.run_test_plan: |
| 423 | logging.info("Test Plan Mode") |
| 424 | |
| 425 | with open(args.test_plan_file, "r") as f: |
| 426 | lines = f.readlines() |
| 427 | |
| 428 | tests = [line.strip() for line in lines if line.strip()] |
| 429 | logging.info(f"Number of Test Cases: {len(tests)}") |
| 430 | |
| 431 | # Skip & Limit |
| 432 | tests = tests[args.skip_cases :] |
| 433 | tests = tests[: args.case_limit] |
| 434 | logging.info(f"Number of Test Cases After Skip & Limit: {len(tests)}") |
| 435 | |
| 436 | for test in tests: |
| 437 | make_case(tm, kerns, args, extra_args=test) |
| 438 | else: |
| 439 | logging.info("Random Test Mode") |
| 440 | |
| 441 | while True: |
| 442 | print("{} case(s) processed, {} error(s)".format(total_cases, LAST_ERROR)) |
| 443 | total_cases += 1 |
| 444 | make_case(tm, kerns, args) |
| 445 | if args.case_limit is not None and total_cases >= args.case_limit: |
| 446 | break |
| 447 | |
| 448 | tm.shutdown() |
| 449 | |
| 450 | if failed_tests: |
| 451 | logging.info("Failed Tests") |
| 452 | for test in failed_tests: |
| 453 | logging.info(f"\t{test}") |
| 454 | |
| 455 | # If a test plan file is given and we're not running from it, |
| 456 | # save the test configurations to this file. |
| 457 | if args.test_plan_file and not args.run_test_plan: |
| 458 | with open(args.test_plan_file, "w") as file: |
| 459 | for test_case in test_plan.difference(failed_tests): |
| 460 | file.write(f"{test_case}\n") |
| 461 | |
| 462 | print(f"Complete: errors={LAST_ERROR}") |
| 463 | |
| 464 | end = time.time() |
| 465 | logging.info(f"Elapsed Time: {end - start:.4f} seconds") |
| 466 | |
| 467 | sys.exit(LAST_ERROR > 0) |