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/capture.py
ADDED
|
@@ -0,0 +1,669 @@
|
|
|
1
|
+
"""Capture deterministic CPU reference cases (.npz) and GPU edge-case traps."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import math
|
|
7
|
+
import os
|
|
8
|
+
import subprocess
|
|
9
|
+
import sys
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
|
|
16
|
+
from gpu_shift.manifest import (
|
|
17
|
+
compute_source_sha256,
|
|
18
|
+
load_manifest,
|
|
19
|
+
load_original_function,
|
|
20
|
+
resolve_source_path,
|
|
21
|
+
save_manifest,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
CASES_DIRNAME = "cases"
|
|
25
|
+
INDEX_FILENAME = "index.json"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True)
|
|
29
|
+
class CapturedCase:
|
|
30
|
+
"""Loaded captured case ready for diff or bench."""
|
|
31
|
+
|
|
32
|
+
case_id: int
|
|
33
|
+
label: str
|
|
34
|
+
kind: str
|
|
35
|
+
args: tuple[Any, ...]
|
|
36
|
+
kwargs: dict[str, Any]
|
|
37
|
+
expected: Any
|
|
38
|
+
expected_exception: str | None = None
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(frozen=True)
|
|
42
|
+
class CaptureResult:
|
|
43
|
+
"""Summary returned by capture_unit / capture_samples."""
|
|
44
|
+
|
|
45
|
+
unit_dir: Path
|
|
46
|
+
cases_dir: Path
|
|
47
|
+
captured_count: int
|
|
48
|
+
edge_count: int
|
|
49
|
+
skipped_edge_count: int
|
|
50
|
+
total_count: int
|
|
51
|
+
source_sha256: str
|
|
52
|
+
warnings: tuple[str, ...] = ()
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _encode_value(value: Any, arrays: dict[str, np.ndarray], prefix: str) -> dict[str, Any]:
|
|
56
|
+
if isinstance(value, np.ndarray):
|
|
57
|
+
key = prefix
|
|
58
|
+
arrays[key] = np.ascontiguousarray(value)
|
|
59
|
+
return {
|
|
60
|
+
"type": "array",
|
|
61
|
+
"key": key,
|
|
62
|
+
"shape": list(value.shape),
|
|
63
|
+
"dtype": str(value.dtype),
|
|
64
|
+
}
|
|
65
|
+
if isinstance(value, np.generic):
|
|
66
|
+
return _encode_value(value.item(), arrays, prefix)
|
|
67
|
+
if isinstance(value, bool) or value is None or isinstance(value, (int, str)):
|
|
68
|
+
return {"type": "scalar", "value": value}
|
|
69
|
+
if isinstance(value, float):
|
|
70
|
+
if math.isnan(value):
|
|
71
|
+
return {"type": "float_special", "value": "nan"}
|
|
72
|
+
if math.isinf(value):
|
|
73
|
+
return {"type": "float_special", "value": "inf" if value > 0 else "-inf"}
|
|
74
|
+
return {"type": "scalar", "value": value}
|
|
75
|
+
if isinstance(value, tuple):
|
|
76
|
+
return {
|
|
77
|
+
"type": "tuple",
|
|
78
|
+
"items": [
|
|
79
|
+
_encode_value(item, arrays, f"{prefix}_{idx}")
|
|
80
|
+
for idx, item in enumerate(value)
|
|
81
|
+
],
|
|
82
|
+
}
|
|
83
|
+
if isinstance(value, list):
|
|
84
|
+
return {
|
|
85
|
+
"type": "list",
|
|
86
|
+
"items": [
|
|
87
|
+
_encode_value(item, arrays, f"{prefix}_{idx}")
|
|
88
|
+
for idx, item in enumerate(value)
|
|
89
|
+
],
|
|
90
|
+
}
|
|
91
|
+
raise TypeError(
|
|
92
|
+
f"Unsupported value type for recording ({prefix}): {type(value).__name__}. "
|
|
93
|
+
"Supported types: np.ndarray, int, float, bool, str, None, tuple, list."
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _decode_value(spec: dict[str, Any], npz: Any) -> Any:
|
|
98
|
+
kind = spec["type"]
|
|
99
|
+
if kind == "array":
|
|
100
|
+
arr = np.array(npz[spec["key"]], copy=True)
|
|
101
|
+
view = spec.get("view")
|
|
102
|
+
if view == "flip_0" and arr.ndim >= 1 and arr.shape[0] > 1:
|
|
103
|
+
arr = arr[::-1]
|
|
104
|
+
elif view == "transpose" and arr.ndim >= 2:
|
|
105
|
+
arr = arr.T
|
|
106
|
+
return arr
|
|
107
|
+
if kind == "scalar":
|
|
108
|
+
return spec["value"]
|
|
109
|
+
if kind == "float_special":
|
|
110
|
+
token = spec["value"]
|
|
111
|
+
if token == "nan":
|
|
112
|
+
return float("nan")
|
|
113
|
+
if token == "inf":
|
|
114
|
+
return float("inf")
|
|
115
|
+
return float("-inf")
|
|
116
|
+
if kind == "tuple":
|
|
117
|
+
return tuple(_decode_value(item, npz) for item in spec["items"])
|
|
118
|
+
if kind == "list":
|
|
119
|
+
return [_decode_value(item, npz) for item in spec["items"]]
|
|
120
|
+
raise ValueError(f"Unknown recorded value type: {kind}")
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def serialize_case(
|
|
124
|
+
cases_dir: Path,
|
|
125
|
+
case_id: int,
|
|
126
|
+
label: str,
|
|
127
|
+
kind: str,
|
|
128
|
+
args: tuple[Any, ...],
|
|
129
|
+
kwargs: dict[str, Any],
|
|
130
|
+
expected: Any = None,
|
|
131
|
+
expected_exception: str | None = None,
|
|
132
|
+
view_overrides: dict[str, str] | None = None,
|
|
133
|
+
) -> dict[str, Any]:
|
|
134
|
+
"""Serialize one recorded input/output pair into case_NNN.npz + index entry."""
|
|
135
|
+
arrays: dict[str, np.ndarray] = {}
|
|
136
|
+
arg_specs = [
|
|
137
|
+
_encode_value(arg, arrays, f"arg_{idx}") for idx, arg in enumerate(args)
|
|
138
|
+
]
|
|
139
|
+
kwarg_specs = {
|
|
140
|
+
k: _encode_value(v, arrays, f"kw_{k}") for k, v in kwargs.items()
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
if view_overrides:
|
|
144
|
+
for spec in arg_specs:
|
|
145
|
+
if spec.get("type") == "array" and spec["key"] in view_overrides:
|
|
146
|
+
mode = view_overrides[spec["key"]]
|
|
147
|
+
spec["view"] = mode
|
|
148
|
+
if mode == "flip_0" and arrays[spec["key"]].ndim >= 1 and arrays[spec["key"]].shape[0] > 1:
|
|
149
|
+
arrays[spec["key"]] = np.ascontiguousarray(arrays[spec["key"]][::-1])
|
|
150
|
+
elif mode == "transpose" and arrays[spec["key"]].ndim >= 2:
|
|
151
|
+
arrays[spec["key"]] = np.ascontiguousarray(arrays[spec["key"]].T)
|
|
152
|
+
for spec in kwarg_specs.values():
|
|
153
|
+
if spec.get("type") == "array" and spec["key"] in view_overrides:
|
|
154
|
+
mode = view_overrides[spec["key"]]
|
|
155
|
+
spec["view"] = mode
|
|
156
|
+
if mode == "flip_0" and arrays[spec["key"]].ndim >= 1 and arrays[spec["key"]].shape[0] > 1:
|
|
157
|
+
arrays[spec["key"]] = np.ascontiguousarray(arrays[spec["key"]][::-1])
|
|
158
|
+
elif mode == "transpose" and arrays[spec["key"]].ndim >= 2:
|
|
159
|
+
arrays[spec["key"]] = np.ascontiguousarray(arrays[spec["key"]].T)
|
|
160
|
+
|
|
161
|
+
out_spec: dict[str, Any] | None = None
|
|
162
|
+
if expected_exception is None:
|
|
163
|
+
out_spec = _encode_value(expected, arrays, "out")
|
|
164
|
+
|
|
165
|
+
npz_name = f"case_{case_id:03d}.npz"
|
|
166
|
+
np.savez(cases_dir / npz_name, **arrays)
|
|
167
|
+
|
|
168
|
+
return {
|
|
169
|
+
"id": case_id,
|
|
170
|
+
"label": label,
|
|
171
|
+
"kind": kind,
|
|
172
|
+
"npz": npz_name,
|
|
173
|
+
"args": arg_specs,
|
|
174
|
+
"kwargs": kwarg_specs,
|
|
175
|
+
"output": out_spec,
|
|
176
|
+
"expected_exception": expected_exception,
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def load_captured_cases(unit_dir: Path) -> tuple[dict[str, Any], list[CapturedCase]]:
|
|
181
|
+
"""Load cases/index.json and decode all captured cases."""
|
|
182
|
+
cases_dir = unit_dir.resolve() / CASES_DIRNAME
|
|
183
|
+
index_path = cases_dir / INDEX_FILENAME
|
|
184
|
+
if not index_path.is_file():
|
|
185
|
+
raise FileNotFoundError(
|
|
186
|
+
f"No captured cases found at {index_path}. Run `gpu-shift capture` first."
|
|
187
|
+
)
|
|
188
|
+
|
|
189
|
+
index_data = json.loads(index_path.read_text(encoding="utf-8"))
|
|
190
|
+
cases: list[CapturedCase] = []
|
|
191
|
+
|
|
192
|
+
for entry in index_data.get("cases", []):
|
|
193
|
+
npz_path = cases_dir / entry["npz"]
|
|
194
|
+
with np.load(npz_path, allow_pickle=False) as npz:
|
|
195
|
+
args = tuple(_decode_value(spec, npz) for spec in entry["args"])
|
|
196
|
+
kwargs = {
|
|
197
|
+
k: _decode_value(spec, npz) for k, spec in entry["kwargs"].items()
|
|
198
|
+
}
|
|
199
|
+
expected = (
|
|
200
|
+
None
|
|
201
|
+
if entry.get("expected_exception") is not None
|
|
202
|
+
else _decode_value(entry["output"], npz)
|
|
203
|
+
)
|
|
204
|
+
cases.append(
|
|
205
|
+
CapturedCase(
|
|
206
|
+
case_id=int(entry["id"]),
|
|
207
|
+
label=str(entry["label"]),
|
|
208
|
+
kind=str(entry["kind"]),
|
|
209
|
+
args=args,
|
|
210
|
+
kwargs=kwargs,
|
|
211
|
+
expected=expected,
|
|
212
|
+
expected_exception=entry.get("expected_exception"),
|
|
213
|
+
)
|
|
214
|
+
)
|
|
215
|
+
return index_data, cases
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _clone_value(val: Any) -> Any:
|
|
219
|
+
if isinstance(val, np.ndarray):
|
|
220
|
+
return val.copy()
|
|
221
|
+
if isinstance(val, tuple):
|
|
222
|
+
return tuple(_clone_value(v) for v in val)
|
|
223
|
+
if isinstance(val, list):
|
|
224
|
+
return [_clone_value(v) for v in val]
|
|
225
|
+
return val
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _make_shape(template: np.ndarray, target_dims: tuple[int, ...]) -> tuple[int, ...]:
|
|
229
|
+
"""Build a compatible edge shape preserving small fixed trailing dims (e.g. XYZ/RGBA)."""
|
|
230
|
+
if template.ndim == 0:
|
|
231
|
+
return ()
|
|
232
|
+
if template.ndim == 1:
|
|
233
|
+
return (target_dims[0],)
|
|
234
|
+
if template.ndim == 2:
|
|
235
|
+
if template.shape[1] <= 4:
|
|
236
|
+
return (target_dims[0], template.shape[1])
|
|
237
|
+
return (target_dims[0], target_dims[1])
|
|
238
|
+
# Preserve trailing channel dimensions (e.g. HxWxC)
|
|
239
|
+
return (target_dims[0], target_dims[1], *template.shape[2:])
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _synthesize_edge_inputs(
|
|
243
|
+
template_args: tuple[Any, ...],
|
|
244
|
+
template_kwargs: dict[str, Any],
|
|
245
|
+
) -> list[tuple[str, tuple[Any, ...], dict[str, Any], dict[str, str]]]:
|
|
246
|
+
"""Generate GPU-specific edge-case inputs from a recorded template call."""
|
|
247
|
+
# Find array positions in positional args
|
|
248
|
+
array_indices = [
|
|
249
|
+
idx for idx, val in enumerate(template_args) if isinstance(val, np.ndarray)
|
|
250
|
+
]
|
|
251
|
+
if not array_indices:
|
|
252
|
+
return []
|
|
253
|
+
|
|
254
|
+
rng = np.random.default_rng(20261122)
|
|
255
|
+
variants: list[tuple[str, tuple[Any, ...], dict[str, Any], dict[str, str]]] = []
|
|
256
|
+
|
|
257
|
+
def _replace_arrays(
|
|
258
|
+
builder: Any,
|
|
259
|
+
view_mode: str | None = None,
|
|
260
|
+
) -> tuple[tuple[Any, ...], dict[str, Any], dict[str, str]]:
|
|
261
|
+
new_args = list(_clone_value(template_args))
|
|
262
|
+
overrides: dict[str, str] = {}
|
|
263
|
+
for idx in array_indices:
|
|
264
|
+
orig = template_args[idx]
|
|
265
|
+
arr = builder(orig)
|
|
266
|
+
new_args[idx] = arr
|
|
267
|
+
if view_mode is not None:
|
|
268
|
+
overrides[f"arg_{idx}"] = view_mode
|
|
269
|
+
return tuple(new_args), dict(_clone_value(template_kwargs)), overrides
|
|
270
|
+
|
|
271
|
+
# 1. 1x1 minimum single-element shape
|
|
272
|
+
def _one_elem(orig: np.ndarray) -> np.ndarray:
|
|
273
|
+
shape = _make_shape(orig, (1, 1))
|
|
274
|
+
if np.issubdtype(orig.dtype, np.floating):
|
|
275
|
+
return np.full(shape, 0.5, dtype=orig.dtype)
|
|
276
|
+
return np.ones(shape, dtype=orig.dtype)
|
|
277
|
+
|
|
278
|
+
variants.append(("edge_1x1", *_replace_arrays(_one_elem)))
|
|
279
|
+
|
|
280
|
+
# 2. Prime dimensions not divisible by 8/16/64 workgroup sizes (17x13)
|
|
281
|
+
def _prime_shape(orig: np.ndarray) -> np.ndarray:
|
|
282
|
+
shape = _make_shape(orig, (17, 13))
|
|
283
|
+
if np.issubdtype(orig.dtype, np.floating):
|
|
284
|
+
return rng.uniform(0.0, 1.0, size=shape).astype(orig.dtype)
|
|
285
|
+
return rng.integers(0, 10, size=shape, dtype=orig.dtype)
|
|
286
|
+
|
|
287
|
+
variants.append(("edge_prime_17x13", *_replace_arrays(_prime_shape)))
|
|
288
|
+
|
|
289
|
+
# 3. All zeros
|
|
290
|
+
def _zeros(orig: np.ndarray) -> np.ndarray:
|
|
291
|
+
shape = _make_shape(orig, (17, 13))
|
|
292
|
+
return np.zeros(shape, dtype=orig.dtype)
|
|
293
|
+
|
|
294
|
+
variants.append(("edge_zeros", *_replace_arrays(_zeros)))
|
|
295
|
+
|
|
296
|
+
# 4. Constant non-zero values
|
|
297
|
+
def _constant(orig: np.ndarray) -> np.ndarray:
|
|
298
|
+
shape = _make_shape(orig, (16, 16))
|
|
299
|
+
val = 0.42 if np.issubdtype(orig.dtype, np.floating) else 7
|
|
300
|
+
return np.full(shape, val, dtype=orig.dtype)
|
|
301
|
+
|
|
302
|
+
variants.append(("edge_constant", *_replace_arrays(_constant)))
|
|
303
|
+
|
|
304
|
+
# 5. Negative and wide finite values (float only)
|
|
305
|
+
if any(np.issubdtype(template_args[i].dtype, np.floating) for i in array_indices):
|
|
306
|
+
|
|
307
|
+
def _neg_and_wide(orig: np.ndarray) -> np.ndarray:
|
|
308
|
+
shape = _make_shape(orig, (17, 13))
|
|
309
|
+
if np.issubdtype(orig.dtype, np.floating):
|
|
310
|
+
arr = rng.uniform(-5.0, 5.0, size=shape).astype(orig.dtype)
|
|
311
|
+
arr.flat[0] = np.asarray(-100.0, dtype=orig.dtype)
|
|
312
|
+
if arr.size > 1:
|
|
313
|
+
arr.flat[-1] = np.asarray(100.0, dtype=orig.dtype)
|
|
314
|
+
return arr
|
|
315
|
+
return rng.integers(-10, 10, size=shape, dtype=orig.dtype)
|
|
316
|
+
|
|
317
|
+
variants.append(("edge_neg_and_wide", *_replace_arrays(_neg_and_wide)))
|
|
318
|
+
|
|
319
|
+
# 6. Non-contiguous reversed view
|
|
320
|
+
def _non_contig(orig: np.ndarray) -> np.ndarray:
|
|
321
|
+
shape = _make_shape(orig, (19, 15))
|
|
322
|
+
if np.issubdtype(orig.dtype, np.floating):
|
|
323
|
+
base = rng.uniform(0.0, 1.0, size=shape).astype(orig.dtype)
|
|
324
|
+
else:
|
|
325
|
+
base = rng.integers(0, 10, size=shape, dtype=orig.dtype)
|
|
326
|
+
return base[::-1] if base.ndim >= 1 and base.shape[0] > 1 else base
|
|
327
|
+
|
|
328
|
+
variants.append(("edge_non_contiguous", *_replace_arrays(_non_contig, view_mode="flip_0")))
|
|
329
|
+
|
|
330
|
+
# 7. NaN / Inf probe (float only; skipped automatically if original raises)
|
|
331
|
+
if any(np.issubdtype(template_args[i].dtype, np.floating) for i in array_indices):
|
|
332
|
+
|
|
333
|
+
def _nan_inf(orig: np.ndarray) -> np.ndarray:
|
|
334
|
+
shape = _make_shape(orig, (9, 9))
|
|
335
|
+
if np.issubdtype(orig.dtype, np.floating):
|
|
336
|
+
arr = rng.uniform(0.0, 1.0, size=shape).astype(orig.dtype)
|
|
337
|
+
arr.flat[0] = np.nan
|
|
338
|
+
if arr.size > 1:
|
|
339
|
+
arr.flat[1] = np.inf
|
|
340
|
+
if arr.size > 2:
|
|
341
|
+
arr.flat[2] = -np.inf
|
|
342
|
+
return arr
|
|
343
|
+
return np.zeros(shape, dtype=orig.dtype)
|
|
344
|
+
|
|
345
|
+
variants.append(("edge_nan_inf", *_replace_arrays(_nan_inf)))
|
|
346
|
+
|
|
347
|
+
return variants
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def _run_capture_subprocess(
|
|
351
|
+
source_path: Path,
|
|
352
|
+
function_name: str,
|
|
353
|
+
cases_dir: Path,
|
|
354
|
+
from_cmd: list[str],
|
|
355
|
+
max_calls: int,
|
|
356
|
+
) -> list[dict[str, Any]]:
|
|
357
|
+
"""Run user command under gpu_shift._capturer to capture real calls."""
|
|
358
|
+
cmd = list(from_cmd)
|
|
359
|
+
if not cmd:
|
|
360
|
+
raise ValueError("Provide a command to execute after `--`.")
|
|
361
|
+
|
|
362
|
+
# Strip leading python executable token if user passed `python script.py ...`
|
|
363
|
+
first = Path(cmd[0]).name.lower()
|
|
364
|
+
if first in {"python", "python3", "python.exe", "python3.exe", "py", "py.exe"}:
|
|
365
|
+
cmd = cmd[1:]
|
|
366
|
+
if not cmd:
|
|
367
|
+
raise ValueError("Capture command has no script or -m target after python.")
|
|
368
|
+
|
|
369
|
+
raw_index_path = cases_dir / "_captured.json"
|
|
370
|
+
capturer_cmd = [
|
|
371
|
+
sys.executable,
|
|
372
|
+
"-m",
|
|
373
|
+
"gpu_shift._capturer",
|
|
374
|
+
"--target-file",
|
|
375
|
+
str(source_path.resolve()),
|
|
376
|
+
"--target-fn",
|
|
377
|
+
function_name,
|
|
378
|
+
"--out-dir",
|
|
379
|
+
str(cases_dir.resolve()),
|
|
380
|
+
"--out-index",
|
|
381
|
+
str(raw_index_path.resolve()),
|
|
382
|
+
"--max-calls",
|
|
383
|
+
str(max_calls),
|
|
384
|
+
"--",
|
|
385
|
+
*cmd,
|
|
386
|
+
]
|
|
387
|
+
|
|
388
|
+
env = os.environ.copy()
|
|
389
|
+
env["GPU_SHIFT_MODE"] = "cpu"
|
|
390
|
+
proc = subprocess.run(
|
|
391
|
+
capturer_cmd,
|
|
392
|
+
env=env,
|
|
393
|
+
capture_output=True,
|
|
394
|
+
text=True,
|
|
395
|
+
check=False,
|
|
396
|
+
)
|
|
397
|
+
if proc.returncode != 0:
|
|
398
|
+
raise RuntimeError(
|
|
399
|
+
f"Capture command failed (exit {proc.returncode}).\n"
|
|
400
|
+
f"STDOUT:\n{proc.stdout}\nSTDERR:\n{proc.stderr}"
|
|
401
|
+
)
|
|
402
|
+
|
|
403
|
+
if not raw_index_path.is_file():
|
|
404
|
+
return []
|
|
405
|
+
entries = json.loads(raw_index_path.read_text(encoding="utf-8"))
|
|
406
|
+
raw_index_path.unlink(missing_ok=True)
|
|
407
|
+
return list(entries)
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def _values_equal(a: Any, b: Any) -> bool:
|
|
411
|
+
if isinstance(a, np.ndarray) and isinstance(b, np.ndarray):
|
|
412
|
+
if a.shape != b.shape or a.dtype != b.dtype:
|
|
413
|
+
return False
|
|
414
|
+
if np.issubdtype(a.dtype, np.floating):
|
|
415
|
+
return bool(np.allclose(a, b, rtol=1e-7, atol=1e-8, equal_nan=True))
|
|
416
|
+
return bool(np.array_equal(a, b))
|
|
417
|
+
if isinstance(a, (tuple, list)) and isinstance(b, type(a)) and len(a) == len(b):
|
|
418
|
+
return all(_values_equal(x, y) for x, y in zip(a, b, strict=True))
|
|
419
|
+
return bool(a == b)
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def _probe_cpu_safety(
|
|
423
|
+
orig_fn: Any,
|
|
424
|
+
template_args: tuple[Any, ...],
|
|
425
|
+
template_kwargs: dict[str, Any],
|
|
426
|
+
) -> tuple[str, ...]:
|
|
427
|
+
"""Run two identical CPU calls to detect in-place input mutation or non-determinism."""
|
|
428
|
+
found: list[str] = []
|
|
429
|
+
args1 = _clone_value(template_args)
|
|
430
|
+
kwargs1 = _clone_value(template_kwargs)
|
|
431
|
+
args2 = _clone_value(template_args)
|
|
432
|
+
kwargs2 = _clone_value(template_kwargs)
|
|
433
|
+
try:
|
|
434
|
+
out1 = orig_fn(*args1, **kwargs1)
|
|
435
|
+
mutated = any(
|
|
436
|
+
not _values_equal(before, after)
|
|
437
|
+
for before, after in zip(template_args, args1, strict=True)
|
|
438
|
+
if isinstance(before, np.ndarray)
|
|
439
|
+
) or any(
|
|
440
|
+
not _values_equal(template_kwargs[k], kwargs1[k])
|
|
441
|
+
for k in template_kwargs
|
|
442
|
+
if isinstance(template_kwargs[k], np.ndarray)
|
|
443
|
+
)
|
|
444
|
+
if mutated:
|
|
445
|
+
found.append(
|
|
446
|
+
"Function mutates input array(s) in-place; callers expecting in-place "
|
|
447
|
+
"updates need port.py to mirror those mutations or stay on CPU."
|
|
448
|
+
)
|
|
449
|
+
out2 = orig_fn(*args2, **kwargs2)
|
|
450
|
+
if not _values_equal(out1, out2):
|
|
451
|
+
found.append(
|
|
452
|
+
"Non-deterministic function detected (two identical CPU calls returned "
|
|
453
|
+
"different outputs); diff verification may fail unless randomness is seeded."
|
|
454
|
+
)
|
|
455
|
+
except Exception as exc: # noqa: BLE001
|
|
456
|
+
found.append(f"CPU safety probe skipped due to {type(exc).__name__}: {exc}")
|
|
457
|
+
return tuple(found)
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def _clear_cases_dir(cases_dir: Path) -> None:
|
|
461
|
+
cases_dir.mkdir(parents=True, exist_ok=True)
|
|
462
|
+
for item in cases_dir.iterdir():
|
|
463
|
+
if item.is_file():
|
|
464
|
+
item.unlink()
|
|
465
|
+
|
|
466
|
+
|
|
467
|
+
def capture_samples(
|
|
468
|
+
unit_dir: Path,
|
|
469
|
+
samples: list[tuple[tuple[Any, ...], dict[str, Any]]],
|
|
470
|
+
*,
|
|
471
|
+
include_edge_cases: bool = True,
|
|
472
|
+
) -> CaptureResult:
|
|
473
|
+
"""Capture explicit (args, kwargs) samples plus generated GPU edge cases."""
|
|
474
|
+
resolved_unit = unit_dir.resolve()
|
|
475
|
+
manifest = load_manifest(resolved_unit)
|
|
476
|
+
source_path = resolve_source_path(resolved_unit, manifest)
|
|
477
|
+
orig_fn = load_original_function(resolved_unit, manifest)
|
|
478
|
+
|
|
479
|
+
cases_dir = resolved_unit / CASES_DIRNAME
|
|
480
|
+
_clear_cases_dir(cases_dir)
|
|
481
|
+
|
|
482
|
+
entries: list[dict[str, Any]] = []
|
|
483
|
+
next_id = 0
|
|
484
|
+
|
|
485
|
+
for idx, (args, kwargs) in enumerate(samples):
|
|
486
|
+
call_args = _clone_value(args)
|
|
487
|
+
call_kwargs = _clone_value(kwargs)
|
|
488
|
+
result = orig_fn(*call_args, **call_kwargs)
|
|
489
|
+
entries.append(
|
|
490
|
+
serialize_case(
|
|
491
|
+
cases_dir,
|
|
492
|
+
case_id=next_id,
|
|
493
|
+
label=f"captured_{idx}",
|
|
494
|
+
kind="captured",
|
|
495
|
+
args=args,
|
|
496
|
+
kwargs=kwargs,
|
|
497
|
+
expected=result,
|
|
498
|
+
)
|
|
499
|
+
)
|
|
500
|
+
next_id += 1
|
|
501
|
+
|
|
502
|
+
captured_count = len(entries)
|
|
503
|
+
edge_count = 0
|
|
504
|
+
skipped_edge_count = 0
|
|
505
|
+
safety_warnings: tuple[str, ...] = ()
|
|
506
|
+
|
|
507
|
+
if samples:
|
|
508
|
+
template_args, template_kwargs = samples[0]
|
|
509
|
+
safety_warnings = _probe_cpu_safety(orig_fn, template_args, template_kwargs)
|
|
510
|
+
|
|
511
|
+
if include_edge_cases and samples:
|
|
512
|
+
template_args, template_kwargs = samples[0]
|
|
513
|
+
for label, e_args, e_kwargs, view_overrides in _synthesize_edge_inputs(
|
|
514
|
+
template_args, template_kwargs
|
|
515
|
+
):
|
|
516
|
+
try:
|
|
517
|
+
with np.errstate(invalid="ignore", over="ignore", divide="ignore"):
|
|
518
|
+
e_result = orig_fn(*_clone_value(e_args), **_clone_value(e_kwargs))
|
|
519
|
+
except Exception: # noqa: BLE001
|
|
520
|
+
skipped_edge_count += 1
|
|
521
|
+
continue
|
|
522
|
+
entries.append(
|
|
523
|
+
serialize_case(
|
|
524
|
+
cases_dir,
|
|
525
|
+
case_id=next_id,
|
|
526
|
+
label=label,
|
|
527
|
+
kind="edge",
|
|
528
|
+
args=e_args,
|
|
529
|
+
kwargs=e_kwargs,
|
|
530
|
+
expected=e_result,
|
|
531
|
+
view_overrides=view_overrides,
|
|
532
|
+
)
|
|
533
|
+
)
|
|
534
|
+
next_id += 1
|
|
535
|
+
edge_count += 1
|
|
536
|
+
|
|
537
|
+
sha256 = compute_source_sha256(source_path)
|
|
538
|
+
manifest.source_sha256 = sha256
|
|
539
|
+
manifest.last_check_passed = False
|
|
540
|
+
save_manifest(resolved_unit, manifest)
|
|
541
|
+
|
|
542
|
+
index_payload = {
|
|
543
|
+
"schema_version": 1,
|
|
544
|
+
"unit": manifest.name,
|
|
545
|
+
"function": manifest.function_name,
|
|
546
|
+
"source_sha256": sha256,
|
|
547
|
+
"warnings": list(safety_warnings),
|
|
548
|
+
"cases": entries,
|
|
549
|
+
}
|
|
550
|
+
(cases_dir / INDEX_FILENAME).write_text(
|
|
551
|
+
json.dumps(index_payload, indent=2) + "\n",
|
|
552
|
+
encoding="utf-8",
|
|
553
|
+
)
|
|
554
|
+
|
|
555
|
+
return CaptureResult(
|
|
556
|
+
unit_dir=resolved_unit,
|
|
557
|
+
cases_dir=cases_dir,
|
|
558
|
+
captured_count=captured_count,
|
|
559
|
+
edge_count=edge_count,
|
|
560
|
+
skipped_edge_count=skipped_edge_count,
|
|
561
|
+
total_count=len(entries),
|
|
562
|
+
source_sha256=sha256,
|
|
563
|
+
warnings=safety_warnings,
|
|
564
|
+
)
|
|
565
|
+
|
|
566
|
+
|
|
567
|
+
def capture_unit(
|
|
568
|
+
unit_dir: Path,
|
|
569
|
+
*,
|
|
570
|
+
from_cmd: list[str] | None = None,
|
|
571
|
+
max_calls: int = 16,
|
|
572
|
+
include_edge_cases: bool = True,
|
|
573
|
+
) -> CaptureResult:
|
|
574
|
+
"""Capture real workload calls from a command and add GPU edge-case traps."""
|
|
575
|
+
if not from_cmd:
|
|
576
|
+
raise ValueError(
|
|
577
|
+
"Provide `-- <python command>` so gpu-shift can capture real inputs."
|
|
578
|
+
)
|
|
579
|
+
|
|
580
|
+
resolved_unit = unit_dir.resolve()
|
|
581
|
+
manifest = load_manifest(resolved_unit)
|
|
582
|
+
source_path = resolve_source_path(resolved_unit, manifest)
|
|
583
|
+
|
|
584
|
+
cases_dir = resolved_unit / CASES_DIRNAME
|
|
585
|
+
_clear_cases_dir(cases_dir)
|
|
586
|
+
|
|
587
|
+
captured_entries = _run_capture_subprocess(
|
|
588
|
+
source_path=source_path,
|
|
589
|
+
function_name=manifest.function_name,
|
|
590
|
+
cases_dir=cases_dir,
|
|
591
|
+
from_cmd=from_cmd,
|
|
592
|
+
max_calls=max_calls,
|
|
593
|
+
)
|
|
594
|
+
if not captured_entries:
|
|
595
|
+
raise RuntimeError(
|
|
596
|
+
f"Function '{manifest.function_name}' in {source_path} was never called "
|
|
597
|
+
f"during command: {' '.join(from_cmd)}"
|
|
598
|
+
)
|
|
599
|
+
|
|
600
|
+
entries = list(captured_entries)
|
|
601
|
+
next_id = len(entries)
|
|
602
|
+
captured_count = len(entries)
|
|
603
|
+
edge_count = 0
|
|
604
|
+
skipped_edge_count = 0
|
|
605
|
+
|
|
606
|
+
# Decode first captured call as template for safety probing & edge-case synthesis
|
|
607
|
+
first = entries[0]
|
|
608
|
+
with np.load(cases_dir / first["npz"], allow_pickle=False) as npz:
|
|
609
|
+
template_args = tuple(_decode_value(s, npz) for s in first["args"])
|
|
610
|
+
template_kwargs = {
|
|
611
|
+
k: _decode_value(s, npz) for k, s in first["kwargs"].items()
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
orig_fn = load_original_function(resolved_unit, manifest)
|
|
615
|
+
safety_warnings = _probe_cpu_safety(orig_fn, template_args, template_kwargs)
|
|
616
|
+
|
|
617
|
+
if include_edge_cases:
|
|
618
|
+
for label, e_args, e_kwargs, view_overrides in _synthesize_edge_inputs(
|
|
619
|
+
template_args, template_kwargs
|
|
620
|
+
):
|
|
621
|
+
try:
|
|
622
|
+
with np.errstate(invalid="ignore", over="ignore", divide="ignore"):
|
|
623
|
+
e_result = orig_fn(*_clone_value(e_args), **_clone_value(e_kwargs))
|
|
624
|
+
except Exception: # noqa: BLE001
|
|
625
|
+
skipped_edge_count += 1
|
|
626
|
+
continue
|
|
627
|
+
entries.append(
|
|
628
|
+
serialize_case(
|
|
629
|
+
cases_dir,
|
|
630
|
+
case_id=next_id,
|
|
631
|
+
label=label,
|
|
632
|
+
kind="edge",
|
|
633
|
+
args=e_args,
|
|
634
|
+
kwargs=e_kwargs,
|
|
635
|
+
expected=e_result,
|
|
636
|
+
view_overrides=view_overrides,
|
|
637
|
+
)
|
|
638
|
+
)
|
|
639
|
+
next_id += 1
|
|
640
|
+
edge_count += 1
|
|
641
|
+
|
|
642
|
+
sha256 = compute_source_sha256(source_path)
|
|
643
|
+
manifest.source_sha256 = sha256
|
|
644
|
+
manifest.last_check_passed = False
|
|
645
|
+
save_manifest(resolved_unit, manifest)
|
|
646
|
+
|
|
647
|
+
index_payload = {
|
|
648
|
+
"schema_version": 1,
|
|
649
|
+
"unit": manifest.name,
|
|
650
|
+
"function": manifest.function_name,
|
|
651
|
+
"source_sha256": sha256,
|
|
652
|
+
"warnings": list(safety_warnings),
|
|
653
|
+
"cases": entries,
|
|
654
|
+
}
|
|
655
|
+
(cases_dir / INDEX_FILENAME).write_text(
|
|
656
|
+
json.dumps(index_payload, indent=2) + "\n",
|
|
657
|
+
encoding="utf-8",
|
|
658
|
+
)
|
|
659
|
+
|
|
660
|
+
return CaptureResult(
|
|
661
|
+
unit_dir=resolved_unit,
|
|
662
|
+
cases_dir=cases_dir,
|
|
663
|
+
captured_count=captured_count,
|
|
664
|
+
edge_count=edge_count,
|
|
665
|
+
skipped_edge_count=skipped_edge_count,
|
|
666
|
+
total_count=len(entries),
|
|
667
|
+
source_sha256=sha256,
|
|
668
|
+
warnings=safety_warnings,
|
|
669
|
+
)
|