Elffuss BraidHub

kikocis/kleidiai public

main · 6.4 KiBRawPermalink
1#!/usr/bin/env python3
2#
3# SPDX-FileCopyrightText: Copyright 2025-2026 Arm Limited and/or its affiliates <open-source-office@arm.com>
4#
5# SPDX-License-Identifier: Apache-2.0
6#
7"""
8Validate that every matmul, imatmul, or dwconv micro-kernel header has a benchmark registration.
9"""
10from __future__ import annotations
11
12import argparse
13import os
14import re
15import sys
16from collections import defaultdict
17from typing import Optional
18from typing import Sequence
19from typing import Set
20
21INCLUDE_RE = re.compile(r'^\s*#\s*include\s*["<]([^">]+)[">]')
22BLOCK_COMMENT_RE = re.compile(r"/\*.*?\*/", re.DOTALL)
23LINE_COMMENT_RE = re.compile(r"//.*?$", re.MULTILINE)
24
25SRC_EXTS = {".c", ".cc", ".cpp", ".cxx", ".h", ".hh", ".hpp", ".hxx"}
26
27
28def strip_comments(text: str) -> str:
29 text = BLOCK_COMMENT_RE.sub("", text)
30 text = LINE_COMMENT_RE.sub("", text)
31 return text
32
33
34def iter_files(root: str):
35 for dirpath, _, files in os.walk(root):
36 for filename in files:
37 if os.path.splitext(filename)[1].lower() in SRC_EXTS:
38 yield os.path.join(dirpath, filename)
39
40
41def classify_kernel(path: str) -> Optional[str]:
42 parts = path.split("/")
43 if not parts:
44 return None
45 head = parts[0]
46 if head == "dwconv":
47 return "dwconv"
48 if head != "matmul":
49 return None
50 if len(parts) > 1 and parts[1].startswith("imatmul"):
51 return "imatmul"
52 return "matmul"
53
54
55def gather_includes(
56 src_dir: str, include_prefix: str, kernel_types: Set[str]
57) -> Set[str]:
58 used: Set[str] = set()
59 # Normalize include prefix for comparison so that Windows and Unix paths match
60 prefix = include_prefix.replace("\\", "/").rstrip("/")
61 plen = len(prefix)
62 for path in iter_files(src_dir):
63 try:
64 with open(path, "r", encoding="utf-8", errors="ignore") as fh:
65 content = strip_comments(fh.read())
66 except OSError:
67 continue
68 for line in content.splitlines():
69 match = INCLUDE_RE.match(line)
70 if not match:
71 continue
72 inc = match.group(1).replace("\\", "/")
73 if not inc.startswith(prefix):
74 continue
75 rel = inc[plen + 1 :]
76 kernel_type = classify_kernel(rel)
77 if kernel_type in kernel_types:
78 used.add(rel)
79 return used
80
81
82def list_present(ukernels_dir: str, kernel_types: Set[str]) -> Set[str]:
83 # REVISIT: Use this list to extract the list of micro-kernels using the new API.
84 uker_apis = [
85 "matmul/kai_matmul",
86 "matmul/kai_matmul_pack_lhs",
87 "matmul/kai_matmul_pack_rhs",
88 ]
89
90 # These header files don't belong to any specific micro-kernel.
91 # They need to be ignored.
92 uker_api_headers = [
93 f"{name}{suffix}" for name in uker_apis for suffix in [".h", "_types.h"]
94 ]
95
96 present: Set[str] = set()
97 base = os.path.abspath(ukernels_dir)
98 for dirpath, _, files in os.walk(base):
99 for filename in files:
100 _, ext = os.path.splitext(filename)
101 if ext.lower() not in {".h", ".hh", ".hpp", ".hxx"}:
102 continue
103 rel_path = os.path.relpath(os.path.join(dirpath, filename), base).replace(
104 "\\", "/"
105 )
106 if rel_path.startswith(".."): # Skip anything outside the tree
107 continue
108 # Skip packing kernels and interface headers, as benchmarks only cover concrete micro-kernels
109 if "/pack/" in rel_path:
110 continue
111 if rel_path.endswith("_interface.h"):
112 continue
113 if rel_path in uker_api_headers:
114 continue
115 kernel_type = classify_kernel(rel_path)
116 if kernel_type in kernel_types:
117 present.add(rel_path)
118 return present
119
120
121def parse_kernel_types(values: Sequence[str]) -> Set[str]:
122 allowed = {"matmul", "imatmul", "dwconv"}
123 requested = set(value.lower() for value in values)
124 unknown = requested.difference(allowed)
125 if unknown:
126 raise SystemExit(
127 f"Unknown kernel types requested: {', '.join(sorted(unknown))}"
128 )
129 return requested
130
131
132def main(argv: Optional[Sequence[str]] = None) -> int:
133 parser = argparse.ArgumentParser(description=__doc__)
134 parser.add_argument(
135 "--benchmark-dir",
136 default="benchmark",
137 help="Directory to scan for benchmark micro-kernel registrations (default: %(default)s)",
138 )
139 parser.add_argument(
140 "--ukernels-dir",
141 default="kai/ukernels",
142 help="Directory containing micro-kernel headers (default: %(default)s)",
143 )
144 parser.add_argument(
145 "--kernel-types",
146 nargs="+",
147 default=["matmul", "imatmul", "dwconv"],
148 help="Kernel families to verify (default: %(default)s)",
149 )
150 args = parser.parse_args(argv)
151
152 kernel_types = parse_kernel_types(args.kernel_types)
153
154 repo_root = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
155
156 def resolve_dir(value: str, default: str) -> str:
157 raw = os.path.expanduser(value)
158 if value == default:
159 raw = os.path.join(repo_root, default)
160 return os.path.abspath(raw)
161
162 benchmark_dir = resolve_dir(args.benchmark_dir, parser.get_default("benchmark_dir"))
163 ukernels_dir = resolve_dir(args.ukernels_dir, parser.get_default("ukernels_dir"))
164
165 if not os.path.isdir(benchmark_dir):
166 raise SystemExit(f"Benchmark directory not found: {benchmark_dir}")
167 if not os.path.isdir(ukernels_dir):
168 raise SystemExit(f"Micro-kernel directory not found: {ukernels_dir}")
169
170 present = list_present(ukernels_dir, kernel_types)
171
172 include_prefix = os.path.relpath(ukernels_dir, repo_root).replace("\\", "/")
173 if include_prefix.startswith(".."):
174 raise SystemExit(
175 f"Micro-kernel directory must reside within the repo: {ukernels_dir}"
176 )
177
178 used = gather_includes(benchmark_dir, include_prefix, kernel_types)
179
180 unused = sorted(present - used)
181 if unused:
182 grouped = defaultdict(list)
183 for rel in unused:
184 grouped[classify_kernel(rel)].append(rel)
185 print("Missing benchmark registrations for the following micro-kernel headers:")
186 for kernel_type in sorted(grouped):
187 print(f"{kernel_type}:")
188 for rel in grouped[kernel_type]:
189 print(f" - {rel}")
190 return 1
191 return 0
192
193
194if __name__ == "__main__":
195 sys.exit(main())