-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrapids-template-instantiation-reporter.py
230 lines (190 loc) · 7.02 KB
/
rapids-template-instantiation-reporter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
#!/usr/bin/env python3
import argparse
import subprocess
from subprocess import PIPE
import shutil
from collections import Counter
from pathlib import Path
def log(msg, verbose=True):
if verbose:
print(msg)
def run(*args, **kwargs):
return subprocess.run(list(args), check=True, **kwargs)
def progress(iterable, display=True):
if display:
print()
for i, it in enumerate(iterable):
if display:
print(f"\rProgress: {i}", end="", flush=True)
yield it
if display:
print()
def extract_template(line):
# Example line:
# Function void raft::random::detail::rmat_gen_kernel<long, double>(T1 *, T1 *, T1 *, const T2 *, T1, T1, T1, T1, raft::random::RngState):
line = line.replace("Function", "").replace("void", "").strip()
if "<" in line:
line = line.split("<")[0]
# Example return: raft::random::detail::rmat_gen_kernel
return line
def get_kernels(cuobjdump, cu_filt, grep, object_file_path):
try:
# Executes:
# > cuobjdump -res-usage file | cu++filt | grep Function
step1 = run(cuobjdump, "-res-usage", object_file_path, stdout=PIPE)
step2 = run(cu_filt, input=step1.stdout, stdout=PIPE)
step3 = run(grep, "Function", input=step2.stdout, stdout=PIPE)
out_str = step3.stdout.decode(encoding="utf-8", errors="strict")
return [extract_template(line) for line in out_str.splitlines()]
except Exception as e:
print(e)
return []
def get_object_files(ninja, build_dir, target):
# Executes:
# > ninja -C build/dir -t input <target>
build_dir = Path(build_dir)
out = run(ninja, "-C", build_dir, "-t", "inputs", target, stdout=PIPE)
out_str = out.stdout.decode(encoding="utf-8", errors="strict")
target_path = build_dir / target
# If the target exists and is an object file, add it to the list of
# candidates.
if target_path.exists() and str(target_path).endswith(".o"):
additional_objects = [target_path]
else:
additional_objects = []
return [
str(build_dir / line.strip())
for line in out_str.splitlines()
if line.endswith(".o")
] + additional_objects
def main(
build_dir,
target,
top_n,
skip_details=False,
skip_kernels=False,
skip_objects=False,
display_progress=True,
verbose=True,
):
# Check that we have the right binaries in the environment.
binary_names = ["ninja", "grep", "cuobjdump", "cu++filt"]
binaries = list(map(shutil.which, binary_names))
ninja, grep, cuobjdump, cu_filt = binaries
fail_on_bins = any(b is None for b in binaries)
if fail_on_bins:
for path, name in zip(binaries, binary_names):
if path is None:
print(f"Could not find {name}. Make sure {name} is in PATH.")
exit(1)
for path, name in zip(binaries, binary_names):
log(f"Found {name}: {path}", verbose=verbose)
# Get object files from target:
object_files = get_object_files(ninja, build_dir, target)
# Compute the counts of each object-kernel combination
get_kernel_bins = (cuobjdump, cu_filt, grep)
obj_kernel_tuples = (
(obj, kernel)
for obj in object_files
for kernel in get_kernels(*get_kernel_bins, obj)
)
obj_kernel_counts = Counter(
tup for tup in progress(obj_kernel_tuples, display=display_progress)
)
# Create an index with the kernel counts per object and the object count per kernel:
obj2kernel = dict()
kernel2obj = dict()
kernel_counts = Counter()
obj_counts = Counter()
for (obj, kernel), count in obj_kernel_counts.items():
# Update the obj2kernel and kernel2obj index:
obj2kernel_ctr = obj2kernel.setdefault(obj, Counter())
kernel2obj_ctr = kernel2obj.setdefault(kernel, Counter())
obj2kernel_ctr += Counter({kernel: count})
kernel2obj_ctr += Counter({obj: count})
# Update counters:
kernel_counts += Counter({kernel: count})
obj_counts += Counter({obj: count})
# Print summary statistics
if not skip_objects:
print("\nObjects with most kernels")
print("=========================\n")
for obj, total_count in obj_counts.most_common()[:top_n]:
print(
f"{total_count:4d} kernel instances in {obj} ({len(obj2kernel[obj])} kernel templates)"
)
if not skip_kernels:
print("\nKernels with most instances")
print("===========================\n")
for kernel, total_count in kernel_counts.most_common()[:top_n]:
print(
f"{total_count:4d} instances of {kernel} in {len(kernel2obj[kernel])} objects."
)
if skip_details:
return
if not skip_objects:
print("\nDetails: Objects")
print("================\n")
for obj, total_count in obj_counts.most_common()[:top_n]:
print(
f"{total_count:4d} kernel instances in {obj} across {len(obj2kernel[obj])} templates:"
)
for kernel, c in obj2kernel[obj].most_common():
print(f" {c:4d}: {kernel}")
print()
if not skip_kernels:
print("\nDetails: Kernels")
print("================\n")
for kernel, total_count in kernel_counts.most_common()[:top_n]:
print(
f"{total_count:4d} instances of {kernel} in {len(kernel2obj[kernel])} objects:"
)
for obj, c in kernel2obj[kernel].most_common():
print(f" {c:4d}: {obj}")
print()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("target", type=str, help="The ninja target to investigate")
parser.add_argument(
"--build-dir",
type=str,
default="./",
help="Build directory",
)
parser.add_argument(
"--top-n",
type=int,
default=None,
help="Log only top N most common objects/kernels",
)
parser.add_argument(
"--skip-details",
action="store_true",
help="Show a summary of statistics, but no details.",
)
parser.set_defaults(skip_details=False)
parser.add_argument(
"--no-progress", action="store_true", help="Do not show progress indication"
)
parser.set_defaults(no_progress=False)
parser.add_argument(
"--skip-objects", action="store_true", help="Do not show statistics on objects"
)
parser.set_defaults(skip_objects=False)
parser.add_argument(
"--skip-kernels", action="store_true", help="Do not show statistics on kernels"
)
parser.set_defaults(skip_kernels=False)
parser.add_argument("--verbose", action="store_true")
parser.set_defaults(verbose=False)
args = parser.parse_args()
main(
args.build_dir,
args.target,
args.top_n,
skip_details=args.skip_details,
skip_kernels=args.skip_kernels,
skip_objects=args.skip_objects,
display_progress=not args.no_progress,
verbose=args.verbose,
)