serveutil 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
serveutil/__init__.py ADDED
@@ -0,0 +1,13 @@
1
+ """Collect and explore serving profiles."""
2
+
3
+ from .overview import export, kernel_label
4
+
5
+ __all__ = ["export", "kernel_label", "profile", "trace_handler", "instrument", "observe"]
6
+
7
+
8
+ def __getattr__(name):
9
+ if name in {"profile", "trace_handler", "instrument", "observe"}:
10
+ from . import recording
11
+
12
+ return getattr(recording, name)
13
+ raise AttributeError(name)
serveutil/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
serveutil/analysis.py ADDED
@@ -0,0 +1,233 @@
1
+ """Interval arithmetic for finding GPU timeline regions worth inspecting."""
2
+
3
+ from bisect import bisect_right
4
+
5
+
6
+ def union(intervals):
7
+ merged = []
8
+ for start, end in sorted(intervals):
9
+ if end <= start:
10
+ continue
11
+ if merged and start <= merged[-1][1]:
12
+ merged[-1][1] = max(end, merged[-1][1])
13
+ else:
14
+ merged.append([start, end])
15
+ return merged
16
+
17
+
18
+ def subtract(intervals, occupied):
19
+ """Both inputs are sorted, disjoint half-open intervals."""
20
+ ends = [e for _, e in occupied]
21
+ for start, end in intervals:
22
+ cursor = start
23
+ index = bisect_right(ends, start)
24
+ while index < len(occupied) and occupied[index][0] < end:
25
+ left, right = occupied[index]
26
+ if left > cursor:
27
+ yield cursor, left
28
+ cursor = max(cursor, right)
29
+ index += 1
30
+ if cursor < end:
31
+ yield cursor, end
32
+
33
+
34
+ def findings(events, rank):
35
+ gpu = [e for e in events if e["kind"] in {"compute", "communication", "copy"}]
36
+ result = []
37
+ devices = {e["device"] for e in gpu}
38
+ for device in devices:
39
+ groups = {}
40
+ for event in gpu:
41
+ if event["device"] == device:
42
+ groups.setdefault(event["kind"], []).append(
43
+ (event["ts"], event["ts"] + event["dur"])
44
+ )
45
+ busy = union(span for spans in groups.values() for span in spans)
46
+ gaps = [
47
+ (prev[1], nxt[0])
48
+ for prev, nxt in zip(busy, busy[1:])
49
+ if nxt[0] - prev[1] >= 100
50
+ ]
51
+ observations = []
52
+ if len(gaps) >= 2:
53
+ observations.extend(
54
+ (
55
+ "Repeated GPU gap",
56
+ start,
57
+ end,
58
+ "No recorded GPU work on this device between adjacent activities. Compare host launches and synchronization.",
59
+ )
60
+ for start, end in gaps
61
+ )
62
+ for start, end in subtract(
63
+ union(groups.get("communication", [])), union(groups.get("compute", []))
64
+ ):
65
+ if end - start >= 100:
66
+ observations.append(
67
+ (
68
+ "Exposed communication",
69
+ start,
70
+ end,
71
+ "Collective activity with no overlapping recorded compute on this device. Inspect dependencies and message size.",
72
+ )
73
+ )
74
+ for label, start, end, reason in observations:
75
+ result.append(
76
+ dict(
77
+ name=label,
78
+ ts=start,
79
+ dur=end - start,
80
+ device=device,
81
+ rank=rank,
82
+ reason=reason,
83
+ )
84
+ )
85
+ return sorted(result, key=lambda item: -item["dur"])[:100]
86
+
87
+
88
+ def matmul_work(name, args):
89
+ """Fused multiply-add counts twice. Only match explicit dense GEMM shapes."""
90
+ shapes = args.get("Input Dims") or []
91
+ types = args.get("Input type") or []
92
+ if name not in {
93
+ "aten::mm",
94
+ "aten::bmm",
95
+ "aten::addmm",
96
+ "aten::_int_mm",
97
+ "aten::_scaled_mm",
98
+ }:
99
+ return None
100
+ index = 1 if name == "aten::addmm" else 0
101
+ try:
102
+ left, right = shapes[index : index + 2]
103
+ dtype = str(types[index]).split("::")[-1].lower()
104
+ right_type = str(types[index + 1]).split("::")[-1].lower()
105
+ if right_type != dtype:
106
+ return None
107
+ dtype = {"signed char": "int8", "unsigned char": "uint8", "char": "int8"}.get(
108
+ dtype, dtype
109
+ )
110
+ floating = {
111
+ "half",
112
+ "float",
113
+ "double",
114
+ "float16",
115
+ "float32",
116
+ "float64",
117
+ "bfloat16",
118
+ }
119
+ integer = dtype in {
120
+ "char",
121
+ "byte",
122
+ "short",
123
+ "int",
124
+ "long",
125
+ "int8",
126
+ "int16",
127
+ "int32",
128
+ "int64",
129
+ "uint8",
130
+ }
131
+ if not (integer or dtype in floating or dtype.startswith("float8_")):
132
+ return None
133
+ if (
134
+ len(left) != len(right)
135
+ or len(left) not in (2, 3)
136
+ or left[:-2] != right[:-2]
137
+ ):
138
+ return None
139
+ if left[-1] != right[-2] or min(*left, *right) <= 0:
140
+ return None
141
+ batch = left[0] if len(left) == 3 else 1
142
+ count = 2 * batch * left[-2] * left[-1] * right[-1]
143
+ return dict(
144
+ **({"operations": count} if integer else {"flops": count}),
145
+ rate_unit="TOP/s" if integer else "TFLOP/s",
146
+ dtype=dtype,
147
+ shape=[left, right],
148
+ method="Dense GEMM input shapes; one multiply-add counts as two operations",
149
+ )
150
+ except (IndexError, TypeError, ValueError):
151
+ return None
152
+
153
+
154
+ def saturation(series):
155
+ """Flag sustained device-counter saturation against a measured, comparable baseline."""
156
+ result = []
157
+ for s in series:
158
+ ref = s.get("baseline")
159
+ if not ref or s["unit"] != "GB/s" or ref["value"] <= 0:
160
+ continue
161
+ run = []
162
+
163
+ def flush():
164
+ if len(run) < 3:
165
+ return
166
+ minimum = min(p[1] for p in run)
167
+ result.append(
168
+ dict(
169
+ name="Sustained bandwidth pressure",
170
+ ts=run[0][2],
171
+ dur=run[-1][0] - run[0][2],
172
+ device=s["device"],
173
+ rank=s.get("node") or "local",
174
+ node=s.get("node"),
175
+ metric=s["name"],
176
+ source=s["source"],
177
+ reason=f"{len(run)} consecutive samples at or above 90% of the measured reference.",
178
+ minimum_GB_s=minimum,
179
+ reference_GB_s=ref["value"],
180
+ scope=s["scope"],
181
+ )
182
+ )
183
+
184
+ for point in s["points"]:
185
+ if run and point[2] - run[-1][0] > 0.5 * (point[0] - point[2]):
186
+ flush()
187
+ run.clear()
188
+ if point[1] >= 0.9 * ref["value"]:
189
+ run.append(point)
190
+ else:
191
+ flush()
192
+ run.clear()
193
+ flush()
194
+ return result
195
+
196
+
197
+ def rank_skew(traces):
198
+ """Compare only uniquely identified copies of a logical step in the same role."""
199
+ import re
200
+ from collections import defaultdict
201
+ from statistics import median
202
+
203
+ groups = defaultdict(lambda: defaultdict(list))
204
+ for trace in traces:
205
+ for e in trace["events"]:
206
+ if e["kind"] != "stage":
207
+ continue
208
+ args = e.get("args", {})
209
+ step = args.get("step_id")
210
+ if step is None:
211
+ step = args.get("iteration_id")
212
+ if step is None and re.fullmatch(r"ProfilerStep#\d+", e["name"]):
213
+ step = e["name"]
214
+ if step is not None:
215
+ key = trace.get("role"), e.get("domain"), str(step), e["name"]
216
+ groups[key][trace["rank"]].append(e)
217
+ for (_, domain, step, _), by_rank in groups.items():
218
+ if len(by_rank) < 2 or any(len(vals) != 1 for vals in by_rank.values()):
219
+ continue
220
+ for rank, (event,) in by_rank.items():
221
+ typical = median(vals[0]["dur"] for r, vals in by_rank.items() if r != rank)
222
+ if event["dur"] - typical >= 100 and event["dur"] >= 1.5 * typical:
223
+ yield dict(
224
+ name="Longer rank step",
225
+ ts=event["ts"],
226
+ dur=event["dur"],
227
+ rank=rank,
228
+ device=event["device"],
229
+ step=step,
230
+ domain=domain,
231
+ peer_median_us=typical,
232
+ reason="This identified step took at least 1.5× the peer median and 100 µs longer.",
233
+ )
serveutil/bundle.py ADDED
@@ -0,0 +1,74 @@
1
+ """A capture is an immutable directory of inputs with a rebuildable report."""
2
+
3
+ import gzip
4
+ import json
5
+ import os
6
+ import socket
7
+ import tempfile
8
+ import time
9
+ import uuid
10
+ from pathlib import Path
11
+
12
+
13
+ def write_json(path, data):
14
+ path = Path(path)
15
+ with tempfile.NamedTemporaryFile(
16
+ mode="w", encoding="utf-8", dir=path.parent, suffix=".tmp", delete=False
17
+ ) as stream:
18
+ temp = Path(stream.name)
19
+ try:
20
+ json.dump(
21
+ data, stream, ensure_ascii=False, allow_nan=False, separators=(",", ":")
22
+ )
23
+ stream.flush()
24
+ stream.close()
25
+ os.replace(temp, path)
26
+ finally:
27
+ temp.unlink(missing_ok=True)
28
+
29
+
30
+ def open_text(path):
31
+ return (gzip.open if Path(path).suffix.lower() == ".gz" else open)(
32
+ path, "rt", encoding="utf-8"
33
+ )
34
+
35
+
36
+ class Capture:
37
+ def __init__(self, output, engine):
38
+ parent = Path(output)
39
+ parent.mkdir(parents=True, exist_ok=True)
40
+ self.path = parent / (
41
+ time.strftime("%Y%m%d-%H%M%S") + "-" + uuid.uuid4().hex[:8]
42
+ )
43
+ self.path.mkdir()
44
+ (self.path / "traces").mkdir()
45
+ self.manifest = dict(
46
+ schema="serveutil.capture/1",
47
+ engine=engine,
48
+ host=socket.gethostname(),
49
+ started_ns=time.time_ns(),
50
+ status="recording",
51
+ traces=[],
52
+ )
53
+ self.save()
54
+
55
+ def save(self):
56
+ write_json(self.path / "capture.json", self.manifest)
57
+
58
+ def add_trace(self, path, rank=None, *, activities=None):
59
+ trace = {"file": str(path.relative_to(self.path)), "rank": rank}
60
+ if activities is not None:
61
+ trace["activities"] = sorted(activities)
62
+ self.manifest["traces"].append(trace)
63
+ self.save()
64
+
65
+ def finish(self, error=None):
66
+ self.manifest["ended_ns"] = time.time_ns()
67
+ self.manifest["status"] = "failed" if error else "complete"
68
+ if error:
69
+ self.manifest["error"] = str(error)
70
+ self.save()
71
+ if error is None and self.manifest["traces"]:
72
+ from .report import render
73
+
74
+ render(self.path, self.path / "report.html")