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/diff.py ADDED
@@ -0,0 +1,510 @@
1
+ """Replay recorded CPU cases against the GPU port and verify numerical parity."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ import numpy as np
10
+
11
+ from gpu_shift.capture import CapturedCase, load_captured_cases
12
+ from gpu_shift.manifest import (
13
+ is_source_stale,
14
+ load_manifest,
15
+ load_port_function,
16
+ )
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class CaseDiffResult:
21
+ """Comparison outcome for a single recorded case."""
22
+
23
+ case_id: int
24
+ label: str
25
+ kind: str
26
+ passed: bool
27
+ max_abs_err: float
28
+ max_rel_err: float
29
+ reason: str | None = None
30
+ first_mismatch_index: tuple[int, ...] | None = None
31
+ actual_sample: float | None = None
32
+ expected_sample: float | None = None
33
+ dtype_downgraded: bool = False
34
+ hint: str | None = None
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class DiffResult:
39
+ """Overall numerical verification report for a unit."""
40
+
41
+ unit_dir: Path
42
+ unit_name: str
43
+ passed: bool
44
+ stale: bool
45
+ rtol: float
46
+ atol: float
47
+ passed_count: int
48
+ failed_count: int
49
+ total_count: int
50
+ max_abs_err: float
51
+ max_rel_err: float
52
+ cases: tuple[CaseDiffResult, ...]
53
+ error: str | None = None
54
+ dtype_downgraded: bool = False
55
+ hints: tuple[str, ...] = ()
56
+
57
+
58
+ def _has_float64_to_float32(actual: Any, expected: Any) -> bool:
59
+ if isinstance(actual, np.ndarray) and isinstance(expected, np.ndarray):
60
+ return expected.dtype == np.float64 and actual.dtype == np.float32
61
+ if isinstance(actual, (tuple, list)) and isinstance(expected, (tuple, list)):
62
+ return any(
63
+ _has_float64_to_float32(a, e) for a, e in zip(actual, expected, strict=False)
64
+ )
65
+ return False
66
+
67
+
68
+ def compare_outputs(
69
+ actual: Any,
70
+ expected: Any,
71
+ *,
72
+ rtol: float,
73
+ atol: float,
74
+ ) -> tuple[bool, float, float, str | None, tuple[int, ...] | None, float | None, float | None]:
75
+ """Compare GPU output against recorded CPU reference output."""
76
+ if isinstance(expected, np.ndarray):
77
+ if not isinstance(actual, np.ndarray):
78
+ return (
79
+ False,
80
+ float("inf"),
81
+ float("inf"),
82
+ f"Expected np.ndarray, got {type(actual).__name__}",
83
+ None,
84
+ None,
85
+ None,
86
+ )
87
+ if actual.shape != expected.shape:
88
+ return (
89
+ False,
90
+ float("inf"),
91
+ float("inf"),
92
+ f"Shape mismatch: actual {actual.shape} != expected {expected.shape}",
93
+ None,
94
+ None,
95
+ None,
96
+ )
97
+
98
+ # Check dtype category compatibility
99
+ exp_float = np.issubdtype(expected.dtype, np.floating)
100
+ act_float = np.issubdtype(actual.dtype, np.floating)
101
+ exp_bool = expected.dtype == np.bool_
102
+ act_bool = actual.dtype == np.bool_
103
+ if exp_bool != act_bool:
104
+ return (
105
+ False,
106
+ float("inf"),
107
+ float("inf"),
108
+ f"Dtype mismatch: actual {actual.dtype} != expected {expected.dtype}",
109
+ None,
110
+ None,
111
+ None,
112
+ )
113
+ if not exp_float and not act_float and actual.dtype != expected.dtype:
114
+ return (
115
+ False,
116
+ float("inf"),
117
+ float("inf"),
118
+ f"Dtype mismatch: actual {actual.dtype} != expected {expected.dtype}",
119
+ None,
120
+ None,
121
+ None,
122
+ )
123
+
124
+ if expected.size == 0:
125
+ return True, 0.0, 0.0, None, None, None, None
126
+
127
+ if exp_bool:
128
+ diff_mask = actual != expected
129
+ if np.any(diff_mask):
130
+ idx = tuple(int(i) for i in np.argwhere(diff_mask)[0])
131
+ return (
132
+ False,
133
+ 1.0,
134
+ 1.0,
135
+ f"Boolean mismatch at index {idx}",
136
+ idx,
137
+ float(actual[idx]),
138
+ float(expected[idx]),
139
+ )
140
+ return True, 0.0, 0.0, None, None, None, None
141
+
142
+ act_f = actual.astype(np.float64, copy=False)
143
+ exp_f = expected.astype(np.float64, copy=False)
144
+
145
+ # Verify NaN and +/-Inf positions match identically
146
+ nan_mismatch = np.isnan(act_f) != np.isnan(exp_f)
147
+ if np.any(nan_mismatch):
148
+ idx = tuple(int(i) for i in np.argwhere(nan_mismatch)[0])
149
+ return (
150
+ False,
151
+ float("inf"),
152
+ float("inf"),
153
+ f"NaN mismatch at index {idx}: actual={act_f[idx]}, expected={exp_f[idx]}",
154
+ idx,
155
+ float(act_f[idx]),
156
+ float(exp_f[idx]),
157
+ )
158
+
159
+ posinf_mismatch = np.isposinf(act_f) != np.isposinf(exp_f)
160
+ neginf_mismatch = np.isneginf(act_f) != np.isneginf(exp_f)
161
+ inf_mismatch = posinf_mismatch | neginf_mismatch
162
+ if np.any(inf_mismatch):
163
+ idx = tuple(int(i) for i in np.argwhere(inf_mismatch)[0])
164
+ return (
165
+ False,
166
+ float("inf"),
167
+ float("inf"),
168
+ f"Inf mismatch at index {idx}: actual={act_f[idx]}, expected={exp_f[idx]}",
169
+ idx,
170
+ float(act_f[idx]),
171
+ float(exp_f[idx]),
172
+ )
173
+
174
+ finite_mask = np.isfinite(exp_f)
175
+ if not np.any(finite_mask):
176
+ return True, 0.0, 0.0, None, None, None, None
177
+
178
+ abs_diff = np.zeros_like(exp_f)
179
+ abs_diff[finite_mask] = np.abs(act_f[finite_mask] - exp_f[finite_mask])
180
+ tol = atol + rtol * np.abs(exp_f)
181
+ bad_mask = finite_mask & (abs_diff > tol)
182
+
183
+ max_abs = float(np.max(abs_diff[finite_mask]))
184
+ denom = np.maximum(np.abs(exp_f[finite_mask]), 1e-12)
185
+ max_rel = float(np.max(abs_diff[finite_mask] / denom))
186
+
187
+ if np.any(bad_mask):
188
+ idx = tuple(int(i) for i in np.argwhere(bad_mask)[0])
189
+ return (
190
+ False,
191
+ max_abs,
192
+ max_rel,
193
+ (
194
+ f"Value mismatch at index {idx}: "
195
+ f"actual={act_f[idx]:.6g}, expected={exp_f[idx]:.6g} "
196
+ f"(max_abs_err={max_abs:.2e}, max_rel_err={max_rel:.2e})"
197
+ ),
198
+ idx,
199
+ float(act_f[idx]),
200
+ float(exp_f[idx]),
201
+ )
202
+
203
+ return True, max_abs, max_rel, None, None, None, None
204
+
205
+ if isinstance(expected, (tuple, list)):
206
+ if not isinstance(actual, type(expected)) or len(actual) != len(expected):
207
+ return (
208
+ False,
209
+ float("inf"),
210
+ float("inf"),
211
+ f"Container mismatch: actual {type(actual).__name__} vs expected {type(expected).__name__}",
212
+ None,
213
+ None,
214
+ None,
215
+ )
216
+ worst_abs = 0.0
217
+ worst_rel = 0.0
218
+ for item_idx, (a_item, e_item) in enumerate(zip(actual, expected, strict=True)):
219
+ ok, a_err, r_err, reason, idx, a_s, e_s = compare_outputs(
220
+ a_item, e_item, rtol=rtol, atol=atol
221
+ )
222
+ worst_abs = max(worst_abs, a_err)
223
+ worst_rel = max(worst_rel, r_err)
224
+ if not ok:
225
+ return False, worst_abs, worst_rel, f"Item [{item_idx}]: {reason}", idx, a_s, e_s
226
+ return True, worst_abs, worst_rel, None, None, None, None
227
+
228
+ if isinstance(expected, (float, np.floating)):
229
+ act_arr = np.asarray(actual, dtype=np.float64)
230
+ exp_arr = np.asarray(expected, dtype=np.float64)
231
+ return compare_outputs(act_arr, exp_arr, rtol=rtol, atol=atol)
232
+
233
+ if actual != expected:
234
+ return (
235
+ False,
236
+ float("inf"),
237
+ float("inf"),
238
+ f"Scalar mismatch: actual={actual!r} != expected={expected!r}",
239
+ None,
240
+ None,
241
+ None,
242
+ )
243
+ return True, 0.0, 0.0, None, None, None, None
244
+
245
+
246
+ def _diagnose_mismatch(
247
+ actual: Any,
248
+ expected: Any,
249
+ *,
250
+ label: str,
251
+ reason: str | None,
252
+ rtol: float,
253
+ atol: float,
254
+ ) -> str | None:
255
+ """Infer an actionable WGSL/port debugging hint from the failure pattern."""
256
+ if label == "edge_non_contiguous":
257
+ return (
258
+ "Non-contiguous input failed - ensure port.py converts inputs with "
259
+ "np.ascontiguousarray(..., dtype=np.float32)."
260
+ )
261
+
262
+ if isinstance(expected, (tuple, list)) and isinstance(actual, (tuple, list)):
263
+ if len(actual) != len(expected):
264
+ return (
265
+ f"Expected {len(expected)} return values (tuple/list), got {len(actual)} - "
266
+ "match the original function's return tuple in port.py."
267
+ )
268
+ for a_item, e_item in zip(actual, expected, strict=True):
269
+ sub_hint = _diagnose_mismatch(
270
+ a_item, e_item, label=label, reason=reason, rtol=rtol, atol=atol
271
+ )
272
+ if sub_hint is not None:
273
+ return sub_hint
274
+ return None
275
+
276
+ if not isinstance(expected, np.ndarray) or not isinstance(actual, np.ndarray):
277
+ return None
278
+
279
+ if actual.shape != expected.shape:
280
+ return (
281
+ f"Output shape {actual.shape} != expected {expected.shape} - "
282
+ "verify outputs={binding: (shape, dtype)} in ComputeKernel.dispatch()."
283
+ )
284
+
285
+ if not (np.issubdtype(expected.dtype, np.floating) or np.issubdtype(expected.dtype, np.integer)):
286
+ return None
287
+
288
+ act_f = actual.astype(np.float64, copy=False)
289
+ exp_f = expected.astype(np.float64, copy=False)
290
+
291
+ if reason and ("NaN mismatch" in reason or "Inf mismatch" in reason):
292
+ if label == "edge_nan_inf":
293
+ return (
294
+ "Non-finite input trap failed - WGSL finite-math can optimize `v != v` away; "
295
+ "detect NaN/Inf via bitcast<u32>(v) (0x7F800000u mask) or guard non-finite inputs in port.py."
296
+ )
297
+ return (
298
+ "Unexpected NaN/Inf in GPU output - guard divisions against zero with "
299
+ "select() and check exp()/sqrt() input bounds."
300
+ )
301
+
302
+ finite_mask = np.isfinite(exp_f) & np.isfinite(act_f)
303
+ if not np.any(finite_mask):
304
+ return None
305
+
306
+ # 1. All-zero output when expected has non-zero values
307
+ if np.all(act_f[finite_mask] == 0.0) and np.any(np.abs(exp_f[finite_mask]) > max(atol, 1e-6)):
308
+ return (
309
+ "GPU output is all zeros - check workgroup count (ceil_div), "
310
+ "output @binding index, and 16-byte uniform struct padding."
311
+ )
312
+
313
+ tol = atol + rtol * np.abs(exp_f)
314
+ bad_mask = np.zeros_like(finite_mask)
315
+ bad_mask[finite_mask] = (
316
+ np.abs(act_f[finite_mask] - exp_f[finite_mask]) > tol[finite_mask]
317
+ )
318
+ if not np.any(bad_mask):
319
+ return None
320
+
321
+ # 2. Border-only mismatch on 2D/3D spatial arrays (interior matches cleanly)
322
+ if exp_f.ndim in (2, 3) and exp_f.shape[0] >= 6 and exp_f.shape[1] >= 6:
323
+ for border in (1, 2):
324
+ if exp_f.shape[0] > 2 * border + 1 and exp_f.shape[1] > 2 * border + 1:
325
+ interior = bad_mask[border:-border, border:-border]
326
+ if not np.any(interior):
327
+ return (
328
+ f"Only outer {border}-pixel border mismatches while interior matches - "
329
+ "check boundary clamp(), padding mode, or shared-memory halo indices."
330
+ )
331
+
332
+ # 3. Constant additive offset across all elements
333
+ deltas = act_f[finite_mask] - exp_f[finite_mask]
334
+ if deltas.size >= 4:
335
+ mean_delta = float(np.mean(deltas))
336
+ std_delta = float(np.std(deltas))
337
+ if abs(mean_delta) > max(atol * 5.0, 1e-4) and std_delta <= max(1e-3 * abs(mean_delta), atol):
338
+ return (
339
+ f"Constant additive offset detected ({mean_delta:+.4g}) - "
340
+ "check bias/offset term or sign in WGSL formula."
341
+ )
342
+
343
+ # 4. Constant multiplicative scale factor
344
+ nonzero = finite_mask & (np.abs(exp_f) > max(atol * 10.0, 1e-4))
345
+ if int(np.sum(nonzero)) >= 4:
346
+ ratios = act_f[nonzero] / exp_f[nonzero]
347
+ med_ratio = float(np.median(ratios))
348
+ std_ratio = float(np.std(ratios))
349
+ if abs(med_ratio - 1.0) > max(rtol * 5.0, 1e-2) and std_ratio <= 1e-2 * max(abs(med_ratio), 1.0):
350
+ return (
351
+ f"Constant scale factor detected (~{med_ratio:.4g}x) - "
352
+ "check normalization denominator or kernel weight multiplier."
353
+ )
354
+
355
+ if "prime" in label or "1x1" in label:
356
+ return (
357
+ "Odd or 1x1 dimension failed - check WGSL bounds guard "
358
+ "(if (x >= width || y >= height) { return; }) and workgroup dispatch size."
359
+ )
360
+
361
+ return None
362
+
363
+
364
+ def _run_case(
365
+ case: CapturedCase,
366
+ port_fn: Any,
367
+ *,
368
+ rtol: float,
369
+ atol: float,
370
+ ) -> CaseDiffResult:
371
+ try:
372
+ actual = port_fn(*case.args, **case.kwargs)
373
+ except Exception as exc: # noqa: BLE001
374
+ if case.expected_exception is not None and type(exc).__name__ == case.expected_exception:
375
+ return CaseDiffResult(
376
+ case_id=case.case_id,
377
+ label=case.label,
378
+ kind=case.kind,
379
+ passed=True,
380
+ max_abs_err=0.0,
381
+ max_rel_err=0.0,
382
+ )
383
+ return CaseDiffResult(
384
+ case_id=case.case_id,
385
+ label=case.label,
386
+ kind=case.kind,
387
+ passed=False,
388
+ max_abs_err=float("inf"),
389
+ max_rel_err=float("inf"),
390
+ reason=f"Raised {type(exc).__name__}: {exc}",
391
+ )
392
+
393
+ if case.expected_exception is not None:
394
+ return CaseDiffResult(
395
+ case_id=case.case_id,
396
+ label=case.label,
397
+ kind=case.kind,
398
+ passed=False,
399
+ max_abs_err=float("inf"),
400
+ max_rel_err=float("inf"),
401
+ reason=f"Expected exception {case.expected_exception}, but port returned normally",
402
+ )
403
+
404
+ ok, max_abs, max_rel, reason, idx, act_s, exp_s = compare_outputs(
405
+ actual, case.expected, rtol=rtol, atol=atol
406
+ )
407
+ downgraded = _has_float64_to_float32(actual, case.expected)
408
+ hint = (
409
+ None
410
+ if ok
411
+ else _diagnose_mismatch(
412
+ actual,
413
+ case.expected,
414
+ label=case.label,
415
+ reason=reason,
416
+ rtol=rtol,
417
+ atol=atol,
418
+ )
419
+ )
420
+ return CaseDiffResult(
421
+ case_id=case.case_id,
422
+ label=case.label,
423
+ kind=case.kind,
424
+ passed=ok,
425
+ max_abs_err=max_abs,
426
+ max_rel_err=max_rel,
427
+ reason=reason,
428
+ first_mismatch_index=idx,
429
+ actual_sample=act_s,
430
+ expected_sample=exp_s,
431
+ dtype_downgraded=downgraded,
432
+ hint=hint,
433
+ )
434
+
435
+
436
+ def diff_unit(
437
+ unit_dir: Path,
438
+ *,
439
+ rtol: float | None = None,
440
+ atol: float | None = None,
441
+ allow_stale: bool = False,
442
+ ) -> DiffResult:
443
+ """Replay all recorded cases for a unit and report numerical accuracy."""
444
+ resolved = unit_dir.resolve()
445
+ manifest = load_manifest(resolved)
446
+ eff_rtol = manifest.rtol if rtol is None else rtol
447
+ eff_atol = manifest.atol if atol is None else atol
448
+
449
+ index_data, cases = load_captured_cases(resolved)
450
+ stale = is_source_stale(resolved, manifest) or (
451
+ index_data.get("source_sha256") != manifest.source_sha256
452
+ )
453
+
454
+ if stale and not allow_stale:
455
+ return DiffResult(
456
+ unit_dir=resolved,
457
+ unit_name=manifest.name,
458
+ passed=False,
459
+ stale=True,
460
+ rtol=eff_rtol,
461
+ atol=eff_atol,
462
+ passed_count=0,
463
+ failed_count=len(cases),
464
+ total_count=len(cases),
465
+ max_abs_err=float("inf"),
466
+ max_rel_err=float("inf"),
467
+ cases=(),
468
+ error=(
469
+ "Original source file changed since capture (stale). "
470
+ "Re-run `gpu-shift capture` before diffing."
471
+ ),
472
+ )
473
+
474
+ port_fn = load_port_function(resolved, manifest)
475
+ results: list[CaseDiffResult] = []
476
+ worst_abs = 0.0
477
+ worst_rel = 0.0
478
+
479
+ for case in cases:
480
+ res = _run_case(case, port_fn, rtol=eff_rtol, atol=eff_atol)
481
+ results.append(res)
482
+ if np.isfinite(res.max_abs_err):
483
+ worst_abs = max(worst_abs, res.max_abs_err)
484
+ if np.isfinite(res.max_rel_err):
485
+ worst_rel = max(worst_rel, res.max_rel_err)
486
+
487
+ passed_count = sum(1 for r in results if r.passed)
488
+ failed_count = len(results) - passed_count
489
+ overall = failed_count == 0 and len(results) > 0
490
+ unique_hints: list[str] = []
491
+ for r in results:
492
+ if r.hint and r.hint not in unique_hints:
493
+ unique_hints.append(r.hint)
494
+
495
+ return DiffResult(
496
+ unit_dir=resolved,
497
+ unit_name=manifest.name,
498
+ passed=overall,
499
+ stale=stale,
500
+ rtol=eff_rtol,
501
+ atol=eff_atol,
502
+ passed_count=passed_count,
503
+ failed_count=failed_count,
504
+ total_count=len(results),
505
+ max_abs_err=worst_abs,
506
+ max_rel_err=worst_rel,
507
+ cases=tuple(results),
508
+ dtype_downgraded=any(r.dtype_downgraded for r in results),
509
+ hints=tuple(unique_hints),
510
+ )
gpu_shift/manifest.py ADDED
@@ -0,0 +1,171 @@
1
+ """Unit manifest management, source fingerprinting, and dynamic loading."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import importlib.util
7
+ import json
8
+ import os
9
+ import re
10
+ import sys
11
+ from collections.abc import Callable
12
+ from dataclasses import asdict, dataclass
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ MANIFEST_FILENAME = "manifest.json"
17
+ SWITCH_BLOCK_RE = re.compile(
18
+ r"\r?\n?# >>> gpu-shift:begin [^\r\n]+\r?\n.*?# <<< gpu-shift:end [^\r\n]+\r?\n?",
19
+ re.DOTALL,
20
+ )
21
+
22
+
23
+ @dataclass
24
+ class UnitManifest:
25
+ """Persistent metadata for a gpu-shift port unit."""
26
+
27
+ name: str
28
+ source_file: str
29
+ function_name: str
30
+ source_sha256: str
31
+ rtol: float = 1e-4
32
+ atol: float = 1e-5
33
+ min_elements: int = 0
34
+ enabled: bool = False
35
+ last_check_passed: bool = False
36
+ power_preference: str = "high-performance"
37
+ schema_version: int = 1
38
+
39
+ def to_dict(self) -> dict[str, Any]:
40
+ return asdict(self)
41
+
42
+ @classmethod
43
+ def from_dict(cls, data: dict[str, Any]) -> UnitManifest:
44
+ return cls(
45
+ name=str(data["name"]),
46
+ source_file=str(data["source_file"]),
47
+ function_name=str(data["function_name"]),
48
+ source_sha256=str(data["source_sha256"]),
49
+ rtol=float(data.get("rtol", 1e-4)),
50
+ atol=float(data.get("atol", 1e-5)),
51
+ min_elements=int(data.get("min_elements", 0)),
52
+ enabled=bool(data.get("enabled", False)),
53
+ last_check_passed=bool(data.get("last_check_passed", False)),
54
+ power_preference=str(data.get("power_preference", "high-performance")),
55
+ schema_version=int(data.get("schema_version", 1)),
56
+ )
57
+
58
+
59
+ def strip_switch_blocks(source_text: str) -> str:
60
+ """Remove gpu-shift enable/disable wrapper blocks from source text."""
61
+ return SWITCH_BLOCK_RE.sub("", source_text)
62
+
63
+
64
+ def compute_source_sha256(source_path: Path) -> str:
65
+ """Compute SHA-256 of the clean original source (ignoring switch blocks)."""
66
+ raw = source_path.read_text(encoding="utf-8")
67
+ clean = strip_switch_blocks(raw)
68
+ normalized = clean.replace("\r\n", "\n")
69
+ return hashlib.sha256(normalized.encode("utf-8")).hexdigest()
70
+
71
+
72
+ def resolve_source_path(unit_dir: Path, manifest: UnitManifest) -> Path:
73
+ """Resolve the original Python source file path from a unit directory."""
74
+ return (unit_dir.resolve() / manifest.source_file).resolve()
75
+
76
+
77
+ def make_relative_posix(target: Path, start: Path) -> str:
78
+ """Return a POSIX-style relative path from start directory to target."""
79
+ rel = os.path.relpath(target.resolve(), start.resolve())
80
+ return Path(rel).as_posix()
81
+
82
+
83
+ def load_manifest(unit_dir: Path) -> UnitManifest:
84
+ """Load manifest.json from a unit directory."""
85
+ manifest_path = unit_dir / MANIFEST_FILENAME
86
+ if not manifest_path.is_file():
87
+ raise FileNotFoundError(f"Unit manifest not found: {manifest_path}")
88
+ data = json.loads(manifest_path.read_text(encoding="utf-8"))
89
+ return UnitManifest.from_dict(data)
90
+
91
+
92
+ def save_manifest(unit_dir: Path, manifest: UnitManifest) -> Path:
93
+ """Save manifest.json to a unit directory."""
94
+ unit_dir.mkdir(parents=True, exist_ok=True)
95
+ manifest_path = unit_dir / MANIFEST_FILENAME
96
+ manifest_path.write_text(
97
+ json.dumps(manifest.to_dict(), indent=2) + "\n",
98
+ encoding="utf-8",
99
+ )
100
+ return manifest_path
101
+
102
+
103
+ def is_source_stale(unit_dir: Path, manifest: UnitManifest) -> bool:
104
+ """Return True if the original source file changed since recording."""
105
+ source_path = resolve_source_path(unit_dir, manifest)
106
+ if not source_path.is_file():
107
+ return True
108
+ return compute_source_sha256(source_path) != manifest.source_sha256
109
+
110
+
111
+ def load_python_module(path: Path, unique_name: str) -> Any:
112
+ """Load an arbitrary Python file as a module without polluting imports."""
113
+ resolved = path.resolve()
114
+ parent_dir = str(resolved.parent)
115
+ added_sys_path = False
116
+ if parent_dir not in sys.path:
117
+ sys.path.insert(0, parent_dir)
118
+ added_sys_path = True
119
+
120
+ try:
121
+ spec = importlib.util.spec_from_file_location(unique_name, resolved)
122
+ if spec is None or spec.loader is None:
123
+ raise ImportError(f"Could not create module spec for {resolved}")
124
+ module = importlib.util.module_from_spec(spec)
125
+ spec.loader.exec_module(module)
126
+ return module
127
+ finally:
128
+ if added_sys_path and parent_dir in sys.path:
129
+ sys.path.remove(parent_dir)
130
+
131
+
132
+ def load_original_function(unit_dir: Path, manifest: UnitManifest) -> Callable[..., Any]:
133
+ """Load the original CPU function, guaranteeing GPU_SHIFT_MODE=cpu."""
134
+ source_path = resolve_source_path(unit_dir, manifest)
135
+ mod_name = f"_gpu_shift_orig_{manifest.name}_{abs(hash(source_path))}"
136
+ module = load_python_module(source_path, mod_name)
137
+ fn = getattr(module, manifest.function_name, None)
138
+ if fn is None or not callable(fn):
139
+ raise AttributeError(
140
+ f"Function '{manifest.function_name}' not found in {source_path}"
141
+ )
142
+
143
+ # Unwrap if the file currently has an enabled switch wrapper.
144
+ raw_fn = getattr(fn, "__gpu_shift_original__", fn)
145
+
146
+ def _cpu_only(*args: Any, **kwargs: Any) -> Any:
147
+ prev = os.environ.get("GPU_SHIFT_MODE")
148
+ os.environ["GPU_SHIFT_MODE"] = "cpu"
149
+ try:
150
+ return raw_fn(*args, **kwargs)
151
+ finally:
152
+ if prev is None:
153
+ os.environ.pop("GPU_SHIFT_MODE", None)
154
+ else:
155
+ os.environ["GPU_SHIFT_MODE"] = prev
156
+
157
+ return _cpu_only
158
+
159
+
160
+ def load_port_function(unit_dir: Path, manifest: UnitManifest | None = None) -> Callable[..., Any]:
161
+ """Load the GPU port's run_gpu function from <unit_dir>/port.py."""
162
+ port_path = unit_dir.resolve() / "port.py"
163
+ if not port_path.is_file():
164
+ raise FileNotFoundError(f"Port file not found: {port_path}")
165
+ unit_name = manifest.name if manifest is not None else unit_dir.name
166
+ mod_name = f"_gpu_shift_port_{unit_name}_{abs(hash(port_path))}"
167
+ module = load_python_module(port_path, mod_name)
168
+ fn = getattr(module, "run_gpu", None)
169
+ if fn is None or not callable(fn):
170
+ raise AttributeError(f"Callable 'run_gpu' not found in {port_path}")
171
+ return fn