wgpu-shift 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.
- gpu_shift/__init__.py +19 -0
- gpu_shift/__main__.py +8 -0
- gpu_shift/_capturer.py +191 -0
- gpu_shift/_scanner.py +71 -0
- gpu_shift/bench.py +321 -0
- gpu_shift/capture.py +669 -0
- gpu_shift/check.py +224 -0
- gpu_shift/cli.py +609 -0
- gpu_shift/demo.py +272 -0
- gpu_shift/device.py +170 -0
- gpu_shift/diff.py +510 -0
- gpu_shift/manifest.py +171 -0
- gpu_shift/mcp_server.py +352 -0
- gpu_shift/report.py +218 -0
- gpu_shift/run.py +206 -0
- gpu_shift/runtime.py +592 -0
- gpu_shift/scan.py +380 -0
- gpu_shift/setup.py +245 -0
- gpu_shift/skill_data/SKILL.md +56 -0
- gpu_shift/stage.py +248 -0
- gpu_shift/switch.py +268 -0
- wgpu_shift-0.1.0.dist-info/METADATA +125 -0
- wgpu_shift-0.1.0.dist-info/RECORD +26 -0
- wgpu_shift-0.1.0.dist-info/WHEEL +4 -0
- wgpu_shift-0.1.0.dist-info/entry_points.txt +3 -0
- wgpu_shift-0.1.0.dist-info/licenses/LICENSE +21 -0
gpu_shift/__init__.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""gpu-shift: WebGPU/WGSL offload harness for Python/NumPy."""
|
|
2
|
+
|
|
3
|
+
from gpu_shift.runtime import (
|
|
4
|
+
ComputeKernel,
|
|
5
|
+
ComputeSession,
|
|
6
|
+
GpuLimitError,
|
|
7
|
+
ceil_div,
|
|
8
|
+
pack_uniforms,
|
|
9
|
+
)
|
|
10
|
+
|
|
11
|
+
__version__ = "0.1.0"
|
|
12
|
+
__all__ = [
|
|
13
|
+
"ComputeKernel",
|
|
14
|
+
"ComputeSession",
|
|
15
|
+
"GpuLimitError",
|
|
16
|
+
"__version__",
|
|
17
|
+
"ceil_div",
|
|
18
|
+
"pack_uniforms",
|
|
19
|
+
]
|
gpu_shift/__main__.py
ADDED
gpu_shift/_capturer.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""Subprocess helper invoked by `gpu-shift capture`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import ast
|
|
7
|
+
import importlib.abc
|
|
8
|
+
import importlib.machinery
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import runpy
|
|
12
|
+
import sys
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from gpu_shift.capture import _clone_value, serialize_case
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class _CallRecorder:
|
|
20
|
+
def __init__(self, out_dir: Path, max_calls: int) -> None:
|
|
21
|
+
self.out_dir = out_dir
|
|
22
|
+
self.max_calls = max_calls
|
|
23
|
+
self.entries: list[dict[str, Any]] = []
|
|
24
|
+
|
|
25
|
+
def wrap(self, fn: Any) -> Any:
|
|
26
|
+
if getattr(fn, "_gpu_shift_recording_", False):
|
|
27
|
+
return fn
|
|
28
|
+
raw_fn = getattr(fn, "__gpu_shift_original__", fn)
|
|
29
|
+
|
|
30
|
+
def _wrapped(*args: Any, **kwargs: Any) -> Any:
|
|
31
|
+
if len(self.entries) >= self.max_calls:
|
|
32
|
+
return raw_fn(*args, **kwargs)
|
|
33
|
+
saved_args = _clone_value(args)
|
|
34
|
+
saved_kwargs = _clone_value(kwargs)
|
|
35
|
+
result = raw_fn(*args, **kwargs)
|
|
36
|
+
idx = len(self.entries)
|
|
37
|
+
entry = serialize_case(
|
|
38
|
+
self.out_dir,
|
|
39
|
+
case_id=idx,
|
|
40
|
+
label=f"captured_{idx}",
|
|
41
|
+
kind="captured",
|
|
42
|
+
args=saved_args,
|
|
43
|
+
kwargs=saved_kwargs,
|
|
44
|
+
expected=_clone_value(result),
|
|
45
|
+
)
|
|
46
|
+
self.entries.append(entry)
|
|
47
|
+
return result
|
|
48
|
+
|
|
49
|
+
_wrapped._gpu_shift_recording_ = True # type: ignore[attr-defined]
|
|
50
|
+
return _wrapped
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class _WrappingLoader(importlib.abc.Loader):
|
|
54
|
+
def __init__(self, inner: Any, target_fn: str, recorder: _CallRecorder) -> None:
|
|
55
|
+
self._inner = inner
|
|
56
|
+
self._target_fn = target_fn
|
|
57
|
+
self._recorder = recorder
|
|
58
|
+
|
|
59
|
+
def create_module(self, spec: Any) -> Any:
|
|
60
|
+
if hasattr(self._inner, "create_module"):
|
|
61
|
+
return self._inner.create_module(spec)
|
|
62
|
+
return None
|
|
63
|
+
|
|
64
|
+
def exec_module(self, module: Any) -> None:
|
|
65
|
+
self._inner.exec_module(module)
|
|
66
|
+
fn = getattr(module, self._target_fn, None)
|
|
67
|
+
if callable(fn):
|
|
68
|
+
setattr(module, self._target_fn, self._recorder.wrap(fn))
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class _TargetImportHook(importlib.abc.MetaPathFinder):
|
|
72
|
+
def __init__(self, target_file: Path, target_fn: str, recorder: _CallRecorder) -> None:
|
|
73
|
+
self._target_file = target_file.resolve()
|
|
74
|
+
self._target_fn = target_fn
|
|
75
|
+
self._recorder = recorder
|
|
76
|
+
self._in_hook = False
|
|
77
|
+
|
|
78
|
+
def find_spec(self, fullname: str, path: Any, target: Any = None) -> Any:
|
|
79
|
+
if self._in_hook:
|
|
80
|
+
return None
|
|
81
|
+
self._in_hook = True
|
|
82
|
+
try:
|
|
83
|
+
spec = importlib.machinery.PathFinder.find_spec(fullname, path, target)
|
|
84
|
+
if spec is not None and spec.origin and spec.loader is not None:
|
|
85
|
+
try:
|
|
86
|
+
origin_path = Path(spec.origin).resolve()
|
|
87
|
+
except OSError:
|
|
88
|
+
return spec
|
|
89
|
+
if origin_path == self._target_file:
|
|
90
|
+
spec.loader = _WrappingLoader(
|
|
91
|
+
spec.loader, self._target_fn, self._recorder
|
|
92
|
+
)
|
|
93
|
+
return spec
|
|
94
|
+
finally:
|
|
95
|
+
self._in_hook = False
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _exec_target_script_directly(
|
|
99
|
+
script_path: Path,
|
|
100
|
+
target_fn: str,
|
|
101
|
+
recorder: _CallRecorder,
|
|
102
|
+
) -> None:
|
|
103
|
+
"""Execute a script that itself defines target_fn, wrapping target_fn right after def."""
|
|
104
|
+
source = script_path.read_text(encoding="utf-8")
|
|
105
|
+
tree = ast.parse(source, filename=str(script_path))
|
|
106
|
+
|
|
107
|
+
new_body: list[ast.stmt] = []
|
|
108
|
+
for stmt in tree.body:
|
|
109
|
+
new_body.append(stmt)
|
|
110
|
+
if isinstance(stmt, ast.FunctionDef) and stmt.name == target_fn:
|
|
111
|
+
wrap_stmt = ast.Assign(
|
|
112
|
+
targets=[ast.Name(id=target_fn, ctx=ast.Store())],
|
|
113
|
+
value=ast.Call(
|
|
114
|
+
func=ast.Name(id="__gpu_shift_record_wrap__", ctx=ast.Load()),
|
|
115
|
+
args=[ast.Name(id=target_fn, ctx=ast.Load())],
|
|
116
|
+
keywords=[],
|
|
117
|
+
),
|
|
118
|
+
)
|
|
119
|
+
new_body.append(wrap_stmt)
|
|
120
|
+
|
|
121
|
+
tree.body = new_body
|
|
122
|
+
ast.fix_missing_locations(tree)
|
|
123
|
+
code = compile(tree, str(script_path), "exec")
|
|
124
|
+
|
|
125
|
+
script_dir = str(script_path.parent)
|
|
126
|
+
if script_dir not in sys.path:
|
|
127
|
+
sys.path.insert(0, script_dir)
|
|
128
|
+
|
|
129
|
+
globals_dict: dict[str, Any] = {
|
|
130
|
+
"__name__": "__main__",
|
|
131
|
+
"__file__": str(script_path),
|
|
132
|
+
"__package__": None,
|
|
133
|
+
"__gpu_shift_record_wrap__": recorder.wrap,
|
|
134
|
+
}
|
|
135
|
+
exec(code, globals_dict) # noqa: S102
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def main(argv: list[str] | None = None) -> int:
|
|
139
|
+
parser = argparse.ArgumentParser(prog="gpu_shift._capturer")
|
|
140
|
+
parser.add_argument("--target-file", required=True)
|
|
141
|
+
parser.add_argument("--target-fn", required=True)
|
|
142
|
+
parser.add_argument("--out-dir", required=True)
|
|
143
|
+
parser.add_argument("--out-index", required=True)
|
|
144
|
+
parser.add_argument("--max-calls", type=int, default=16)
|
|
145
|
+
parser.add_argument("cmd", nargs=argparse.REMAINDER)
|
|
146
|
+
args = parser.parse_args(argv)
|
|
147
|
+
|
|
148
|
+
cmd = list(args.cmd)
|
|
149
|
+
if cmd and cmd[0] == "--":
|
|
150
|
+
cmd = cmd[1:]
|
|
151
|
+
if not cmd:
|
|
152
|
+
print("No command provided to _capturer.", file=sys.stderr)
|
|
153
|
+
return 2
|
|
154
|
+
|
|
155
|
+
os.environ["GPU_SHIFT_MODE"] = "cpu"
|
|
156
|
+
target_file = Path(args.target_file).resolve()
|
|
157
|
+
out_dir = Path(args.out_dir).resolve()
|
|
158
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
159
|
+
recorder = _CallRecorder(out_dir=out_dir, max_calls=args.max_calls)
|
|
160
|
+
|
|
161
|
+
hook = _TargetImportHook(target_file, args.target_fn, recorder)
|
|
162
|
+
sys.meta_path.insert(0, hook)
|
|
163
|
+
|
|
164
|
+
try:
|
|
165
|
+
if cmd[0] == "-m" and len(cmd) >= 2:
|
|
166
|
+
mod_name = cmd[1]
|
|
167
|
+
sys.argv = [mod_name, *cmd[2:]]
|
|
168
|
+
runpy.run_module(mod_name, run_name="__main__", alter_sys=True)
|
|
169
|
+
else:
|
|
170
|
+
script_path = Path(cmd[0]).resolve()
|
|
171
|
+
sys.argv = [str(script_path), *cmd[1:]]
|
|
172
|
+
script_dir = str(script_path.parent)
|
|
173
|
+
if script_dir not in sys.path:
|
|
174
|
+
sys.path.insert(0, script_dir)
|
|
175
|
+
if script_path == target_file:
|
|
176
|
+
_exec_target_script_directly(script_path, args.target_fn, recorder)
|
|
177
|
+
else:
|
|
178
|
+
runpy.run_path(str(script_path), run_name="__main__")
|
|
179
|
+
finally:
|
|
180
|
+
if hook in sys.meta_path:
|
|
181
|
+
sys.meta_path.remove(hook)
|
|
182
|
+
|
|
183
|
+
Path(args.out_index).write_text(
|
|
184
|
+
json.dumps(recorder.entries, indent=2) + "\n",
|
|
185
|
+
encoding="utf-8",
|
|
186
|
+
)
|
|
187
|
+
return 0
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
if __name__ == "__main__":
|
|
191
|
+
raise SystemExit(main())
|
gpu_shift/_scanner.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""Subprocess helper invoked by `gpu-shift scan` to run cProfile."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import cProfile
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import runpy
|
|
10
|
+
import sys
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _run_target(cmd: list[str]) -> None:
|
|
16
|
+
if cmd[0] == "-m" and len(cmd) >= 2:
|
|
17
|
+
mod_name = cmd[1]
|
|
18
|
+
sys.argv = [mod_name, *cmd[2:]]
|
|
19
|
+
runpy.run_module(mod_name, run_name="__main__", alter_sys=True)
|
|
20
|
+
else:
|
|
21
|
+
script_path = Path(cmd[0]).resolve()
|
|
22
|
+
sys.argv = [str(script_path), *cmd[1:]]
|
|
23
|
+
script_dir = str(script_path.parent)
|
|
24
|
+
if script_dir not in sys.path:
|
|
25
|
+
sys.path.insert(0, script_dir)
|
|
26
|
+
runpy.run_path(str(script_path), run_name="__main__")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def main(argv: list[str] | None = None) -> int:
|
|
30
|
+
parser = argparse.ArgumentParser(prog="gpu_shift._scanner")
|
|
31
|
+
parser.add_argument("--out-json", required=True)
|
|
32
|
+
parser.add_argument("cmd", nargs=argparse.REMAINDER)
|
|
33
|
+
args = parser.parse_args(argv)
|
|
34
|
+
|
|
35
|
+
cmd = list(args.cmd)
|
|
36
|
+
if cmd and cmd[0] == "--":
|
|
37
|
+
cmd = cmd[1:]
|
|
38
|
+
if not cmd:
|
|
39
|
+
print("No command provided to _scanner.", file=sys.stderr)
|
|
40
|
+
return 2
|
|
41
|
+
|
|
42
|
+
os.environ["GPU_SHIFT_MODE"] = "cpu"
|
|
43
|
+
profiler = cProfile.Profile()
|
|
44
|
+
profiler.enable()
|
|
45
|
+
try:
|
|
46
|
+
_run_target(cmd)
|
|
47
|
+
finally:
|
|
48
|
+
profiler.disable()
|
|
49
|
+
|
|
50
|
+
entries: list[dict[str, Any]] = []
|
|
51
|
+
for stat in profiler.getstats():
|
|
52
|
+
code = stat.code
|
|
53
|
+
if isinstance(code, str):
|
|
54
|
+
continue
|
|
55
|
+
entries.append(
|
|
56
|
+
{
|
|
57
|
+
"filename": code.co_filename,
|
|
58
|
+
"lineno": int(code.co_firstlineno),
|
|
59
|
+
"func_name": code.co_name,
|
|
60
|
+
"ncalls": int(stat.callcount),
|
|
61
|
+
"tottime_ms": float(stat.inlinetime) * 1000.0,
|
|
62
|
+
"cumtime_ms": float(stat.totaltime) * 1000.0,
|
|
63
|
+
}
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
Path(args.out_json).write_text(json.dumps(entries, indent=2) + "\n", encoding="utf-8")
|
|
67
|
+
return 0
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
if __name__ == "__main__":
|
|
71
|
+
raise SystemExit(main())
|
gpu_shift/bench.py
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
"""End-to-end CPU vs GPU benchmarking and automatic crossover threshold detection."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import statistics
|
|
6
|
+
import time
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
|
|
13
|
+
from gpu_shift.capture import _clone_value, load_captured_cases
|
|
14
|
+
from gpu_shift.device import AdapterInfo, get_device
|
|
15
|
+
from gpu_shift.manifest import (
|
|
16
|
+
load_manifest,
|
|
17
|
+
load_original_function,
|
|
18
|
+
load_port_function,
|
|
19
|
+
save_manifest,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True)
|
|
24
|
+
class BenchPoint:
|
|
25
|
+
"""Measured CPU vs GPU latency for one input size or recorded case."""
|
|
26
|
+
|
|
27
|
+
label: str
|
|
28
|
+
shape: tuple[int, ...]
|
|
29
|
+
elements: int
|
|
30
|
+
cpu_ms: float
|
|
31
|
+
gpu_ms: float
|
|
32
|
+
speedup: float
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True)
|
|
36
|
+
class BenchResult:
|
|
37
|
+
"""Benchmark summary including automatic crossover recommendation."""
|
|
38
|
+
|
|
39
|
+
unit_dir: Path
|
|
40
|
+
unit_name: str
|
|
41
|
+
adapter: AdapterInfo
|
|
42
|
+
recorded_points: tuple[BenchPoint, ...]
|
|
43
|
+
sweep_points: tuple[BenchPoint, ...]
|
|
44
|
+
crossover_elements: int | None
|
|
45
|
+
max_speedup: float
|
|
46
|
+
verdict: str
|
|
47
|
+
manifest_updated: bool
|
|
48
|
+
is_software_adapter: bool = False
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def primary_array_elements(args: tuple[Any, ...], kwargs: dict[str, Any]) -> int:
|
|
52
|
+
"""Return element count of the first NumPy array argument (0 if none)."""
|
|
53
|
+
for arg in args:
|
|
54
|
+
if isinstance(arg, np.ndarray):
|
|
55
|
+
return int(arg.size)
|
|
56
|
+
for val in kwargs.values():
|
|
57
|
+
if isinstance(val, np.ndarray):
|
|
58
|
+
return int(val.size)
|
|
59
|
+
return 0
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _primary_array(args: tuple[Any, ...], kwargs: dict[str, Any]) -> np.ndarray | None:
|
|
63
|
+
for arg in args:
|
|
64
|
+
if isinstance(arg, np.ndarray):
|
|
65
|
+
return arg
|
|
66
|
+
for val in kwargs.values():
|
|
67
|
+
if isinstance(val, np.ndarray):
|
|
68
|
+
return val
|
|
69
|
+
return None
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _time_callable(
|
|
73
|
+
fn: Any,
|
|
74
|
+
args: tuple[Any, ...],
|
|
75
|
+
kwargs: dict[str, Any],
|
|
76
|
+
*,
|
|
77
|
+
warmup: int,
|
|
78
|
+
repeats: int,
|
|
79
|
+
min_warmup_ms: float = 0.0,
|
|
80
|
+
) -> float:
|
|
81
|
+
warm_start = time.perf_counter()
|
|
82
|
+
warm_iters = 0
|
|
83
|
+
while warm_iters < warmup or (
|
|
84
|
+
min_warmup_ms > 0.0
|
|
85
|
+
and warm_iters < 24
|
|
86
|
+
and (time.perf_counter() - warm_start) * 1000.0 < min_warmup_ms
|
|
87
|
+
):
|
|
88
|
+
fn(*args, **kwargs)
|
|
89
|
+
warm_iters += 1
|
|
90
|
+
samples_ms: list[float] = []
|
|
91
|
+
for _ in range(repeats):
|
|
92
|
+
t0 = time.perf_counter()
|
|
93
|
+
fn(*args, **kwargs)
|
|
94
|
+
samples_ms.append((time.perf_counter() - t0) * 1000.0)
|
|
95
|
+
return float(statistics.median(samples_ms))
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _all_arrays(args: tuple[Any, ...], kwargs: dict[str, Any]) -> list[np.ndarray]:
|
|
99
|
+
found: list[np.ndarray] = [a for a in args if isinstance(a, np.ndarray)]
|
|
100
|
+
found.extend(v for v in kwargs.values() if isinstance(v, np.ndarray))
|
|
101
|
+
return found
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _scaled_args(
|
|
105
|
+
template_args: tuple[Any, ...],
|
|
106
|
+
template_kwargs: dict[str, Any],
|
|
107
|
+
target_shape: tuple[int, ...],
|
|
108
|
+
rng: np.random.Generator,
|
|
109
|
+
) -> tuple[tuple[Any, ...], dict[str, Any]]:
|
|
110
|
+
new_args = list(_clone_value(template_args))
|
|
111
|
+
new_kwargs = dict(_clone_value(template_kwargs))
|
|
112
|
+
primary = _primary_array(template_args, template_kwargs)
|
|
113
|
+
primary_n = target_shape[0] if target_shape else 1
|
|
114
|
+
|
|
115
|
+
def _build(orig: np.ndarray) -> np.ndarray:
|
|
116
|
+
if primary is not None and orig.ndim == primary.ndim:
|
|
117
|
+
shape = target_shape
|
|
118
|
+
elif orig.ndim == 1:
|
|
119
|
+
shape = (primary_n,)
|
|
120
|
+
elif orig.ndim == 2 and orig.shape[1] <= 4:
|
|
121
|
+
shape = (primary_n, orig.shape[1])
|
|
122
|
+
else:
|
|
123
|
+
shape = target_shape
|
|
124
|
+
if np.issubdtype(orig.dtype, np.floating):
|
|
125
|
+
return rng.uniform(0.0, 1.0, size=shape).astype(orig.dtype)
|
|
126
|
+
return rng.integers(0, 100, size=shape, dtype=orig.dtype)
|
|
127
|
+
|
|
128
|
+
replaced = False
|
|
129
|
+
for idx, arg in enumerate(new_args):
|
|
130
|
+
if isinstance(arg, np.ndarray):
|
|
131
|
+
new_args[idx] = _build(arg)
|
|
132
|
+
replaced = True
|
|
133
|
+
if not replaced:
|
|
134
|
+
for key, val in new_kwargs.items():
|
|
135
|
+
if isinstance(val, np.ndarray):
|
|
136
|
+
new_kwargs[key] = _build(val)
|
|
137
|
+
break
|
|
138
|
+
return tuple(new_args), new_kwargs
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _default_sweep_shapes(
|
|
142
|
+
template: np.ndarray,
|
|
143
|
+
all_arrays: list[np.ndarray] | None = None,
|
|
144
|
+
) -> list[tuple[int, ...]]:
|
|
145
|
+
arrays = all_arrays or [template]
|
|
146
|
+
if template.ndim <= 1:
|
|
147
|
+
return [(n,) for n in (256, 1024, 4096, 16384, 65536, 262144, 1048576)]
|
|
148
|
+
if template.ndim == 2:
|
|
149
|
+
if template.shape[1] <= 4:
|
|
150
|
+
cols = template.shape[1]
|
|
151
|
+
return [(n, cols) for n in (64, 256, 512, 1024, 2048, 4096)]
|
|
152
|
+
# Multi-matrix workload (e.g. pairwise distances (N, D) x (M, D)): keep D fixed
|
|
153
|
+
two_d = [a for a in arrays if a.ndim == 2]
|
|
154
|
+
if len(two_d) >= 2 and all(a.shape[1] == template.shape[1] for a in two_d):
|
|
155
|
+
d = template.shape[1]
|
|
156
|
+
return [(n, d) for n in (32, 64, 128, 256, 512, 1024)]
|
|
157
|
+
return [(s, s) for s in (16, 32, 64, 128, 256, 512)]
|
|
158
|
+
trailing = template.shape[2:]
|
|
159
|
+
return [(s, s, *trailing) for s in (16, 32, 64, 128, 256, 512)]
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def find_crossover(
|
|
163
|
+
points: list[BenchPoint],
|
|
164
|
+
min_speedup: float = 1.15,
|
|
165
|
+
) -> int | None:
|
|
166
|
+
"""Return smallest element count where GPU stays faster than CPU."""
|
|
167
|
+
ordered = sorted(points, key=lambda p: p.elements)
|
|
168
|
+
for idx, point in enumerate(ordered):
|
|
169
|
+
if point.speedup >= min_speedup and all(
|
|
170
|
+
later.speedup >= 1.0 for later in ordered[idx:]
|
|
171
|
+
):
|
|
172
|
+
return point.elements
|
|
173
|
+
return None
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def bench_unit(
|
|
177
|
+
unit_dir: Path,
|
|
178
|
+
*,
|
|
179
|
+
warmup: int = 2,
|
|
180
|
+
repeats: int = 5,
|
|
181
|
+
sweep: bool = True,
|
|
182
|
+
max_single_cpu_ms: float = 1500.0,
|
|
183
|
+
min_crossover_speedup: float = 1.15,
|
|
184
|
+
update_manifest: bool = True,
|
|
185
|
+
) -> BenchResult:
|
|
186
|
+
"""Benchmark end-to-end CPU vs GPU latency and compute crossover min_elements."""
|
|
187
|
+
resolved = unit_dir.resolve()
|
|
188
|
+
manifest = load_manifest(resolved)
|
|
189
|
+
_, cases = load_captured_cases(resolved)
|
|
190
|
+
|
|
191
|
+
cpu_fn = load_original_function(resolved, manifest)
|
|
192
|
+
gpu_fn = load_port_function(resolved, manifest)
|
|
193
|
+
|
|
194
|
+
adapter, _ = get_device(power_preference=manifest.power_preference)
|
|
195
|
+
adapter_info = AdapterInfo.from_wgpu(adapter)
|
|
196
|
+
|
|
197
|
+
captured_cases = [c for c in cases if c.kind == "captured"] or cases[:1]
|
|
198
|
+
|
|
199
|
+
recorded_points: list[BenchPoint] = []
|
|
200
|
+
for case in captured_cases:
|
|
201
|
+
arr = _primary_array(case.args, case.kwargs)
|
|
202
|
+
shape = tuple(arr.shape) if arr is not None else ()
|
|
203
|
+
elements = int(arr.size) if arr is not None else 0
|
|
204
|
+
cpu_ms = _time_callable(
|
|
205
|
+
cpu_fn, case.args, case.kwargs, warmup=warmup, repeats=repeats
|
|
206
|
+
)
|
|
207
|
+
gpu_ms = _time_callable(
|
|
208
|
+
gpu_fn, case.args, case.kwargs, warmup=warmup, repeats=repeats, min_warmup_ms=60.0
|
|
209
|
+
)
|
|
210
|
+
speedup = cpu_ms / gpu_ms if gpu_ms > 0 else 0.0
|
|
211
|
+
recorded_points.append(
|
|
212
|
+
BenchPoint(
|
|
213
|
+
label=case.label,
|
|
214
|
+
shape=shape,
|
|
215
|
+
elements=elements,
|
|
216
|
+
cpu_ms=cpu_ms,
|
|
217
|
+
gpu_ms=gpu_ms,
|
|
218
|
+
speedup=speedup,
|
|
219
|
+
)
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
sweep_points: list[BenchPoint] = []
|
|
223
|
+
template_case = captured_cases[0]
|
|
224
|
+
template_arr = _primary_array(template_case.args, template_case.kwargs)
|
|
225
|
+
|
|
226
|
+
if sweep and template_arr is not None:
|
|
227
|
+
rng = np.random.default_rng(42)
|
|
228
|
+
template_arrays = _all_arrays(template_case.args, template_case.kwargs)
|
|
229
|
+
for target_shape in _default_sweep_shapes(template_arr, template_arrays):
|
|
230
|
+
s_args, s_kwargs = _scaled_args(
|
|
231
|
+
template_case.args, template_case.kwargs, target_shape, rng
|
|
232
|
+
)
|
|
233
|
+
# Quick single probe to avoid multi-second CPU stalls on large grids
|
|
234
|
+
t0 = time.perf_counter()
|
|
235
|
+
cpu_fn(*s_args, **s_kwargs)
|
|
236
|
+
probe_cpu_ms = (time.perf_counter() - t0) * 1000.0
|
|
237
|
+
|
|
238
|
+
if probe_cpu_ms > max_single_cpu_ms:
|
|
239
|
+
# Still measure once accurately on GPU vs the single CPU probe
|
|
240
|
+
gpu_ms = _time_callable(
|
|
241
|
+
gpu_fn,
|
|
242
|
+
s_args,
|
|
243
|
+
s_kwargs,
|
|
244
|
+
warmup=1,
|
|
245
|
+
repeats=max(2, repeats),
|
|
246
|
+
min_warmup_ms=60.0,
|
|
247
|
+
)
|
|
248
|
+
cpu_ms = probe_cpu_ms
|
|
249
|
+
else:
|
|
250
|
+
eff_repeats = repeats if probe_cpu_ms < 150.0 else 3
|
|
251
|
+
eff_warmup = warmup if probe_cpu_ms < 150.0 else 1
|
|
252
|
+
cpu_ms = _time_callable(
|
|
253
|
+
cpu_fn, s_args, s_kwargs, warmup=eff_warmup, repeats=eff_repeats
|
|
254
|
+
)
|
|
255
|
+
gpu_ms = _time_callable(
|
|
256
|
+
gpu_fn,
|
|
257
|
+
s_args,
|
|
258
|
+
s_kwargs,
|
|
259
|
+
warmup=eff_warmup,
|
|
260
|
+
repeats=eff_repeats,
|
|
261
|
+
min_warmup_ms=60.0,
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
elements = int(np.prod(target_shape))
|
|
265
|
+
speedup = cpu_ms / gpu_ms if gpu_ms > 0 else 0.0
|
|
266
|
+
shape_str = "x".join(str(d) for d in target_shape)
|
|
267
|
+
sweep_points.append(
|
|
268
|
+
BenchPoint(
|
|
269
|
+
label=shape_str,
|
|
270
|
+
shape=target_shape,
|
|
271
|
+
elements=elements,
|
|
272
|
+
cpu_ms=cpu_ms,
|
|
273
|
+
gpu_ms=gpu_ms,
|
|
274
|
+
speedup=speedup,
|
|
275
|
+
)
|
|
276
|
+
)
|
|
277
|
+
if probe_cpu_ms > max_single_cpu_ms:
|
|
278
|
+
break
|
|
279
|
+
|
|
280
|
+
all_points = [*sweep_points, *recorded_points]
|
|
281
|
+
crossover = find_crossover(
|
|
282
|
+
sweep_points if sweep_points else recorded_points,
|
|
283
|
+
min_speedup=min_crossover_speedup,
|
|
284
|
+
)
|
|
285
|
+
max_speedup = max((p.speedup for p in all_points), default=0.0)
|
|
286
|
+
|
|
287
|
+
is_software = not adapter_info.is_hardware
|
|
288
|
+
manifest_updated = False
|
|
289
|
+
if update_manifest and crossover is not None and not is_software:
|
|
290
|
+
manifest.min_elements = crossover
|
|
291
|
+
save_manifest(resolved, manifest)
|
|
292
|
+
manifest_updated = True
|
|
293
|
+
|
|
294
|
+
if is_software:
|
|
295
|
+
verdict = (
|
|
296
|
+
f"Software CPU emulator detected ({adapter_info.device}); "
|
|
297
|
+
f"results do not reflect real GPU hardware (peak ratio {max_speedup:.2f}x)"
|
|
298
|
+
)
|
|
299
|
+
elif crossover is not None:
|
|
300
|
+
verdict = (
|
|
301
|
+
f"GPU faster from {crossover:,} elements "
|
|
302
|
+
f"(peak {max_speedup:.2f}x on {adapter_info.device})"
|
|
303
|
+
)
|
|
304
|
+
else:
|
|
305
|
+
verdict = (
|
|
306
|
+
f"CPU faster at tested sizes (peak GPU ratio {max_speedup:.2f}x on "
|
|
307
|
+
f"{adapter_info.device})"
|
|
308
|
+
)
|
|
309
|
+
|
|
310
|
+
return BenchResult(
|
|
311
|
+
unit_dir=resolved,
|
|
312
|
+
unit_name=manifest.name,
|
|
313
|
+
adapter=adapter_info,
|
|
314
|
+
recorded_points=tuple(recorded_points),
|
|
315
|
+
sweep_points=tuple(sweep_points),
|
|
316
|
+
crossover_elements=None if is_software else crossover,
|
|
317
|
+
max_speedup=max_speedup,
|
|
318
|
+
verdict=verdict,
|
|
319
|
+
manifest_updated=manifest_updated,
|
|
320
|
+
is_software_adapter=is_software,
|
|
321
|
+
)
|