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/stage.py
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
"""Stage an isolated kernels/<fn>/ unit without modifying original source files."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import ast
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from gpu_shift.manifest import (
|
|
10
|
+
UnitManifest,
|
|
11
|
+
compute_source_sha256,
|
|
12
|
+
make_relative_posix,
|
|
13
|
+
save_manifest,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class FunctionInfo:
|
|
19
|
+
"""Extracted AST metadata for a target Python function."""
|
|
20
|
+
|
|
21
|
+
name: str
|
|
22
|
+
signature: str
|
|
23
|
+
arg_names: tuple[str, ...]
|
|
24
|
+
lineno: int
|
|
25
|
+
end_lineno: int
|
|
26
|
+
source_code: str
|
|
27
|
+
docstring: str | None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True)
|
|
31
|
+
class StageResult:
|
|
32
|
+
"""Result returned by create_stage."""
|
|
33
|
+
|
|
34
|
+
unit_dir: Path
|
|
35
|
+
manifest_path: Path
|
|
36
|
+
wgsl_path: Path
|
|
37
|
+
port_path: Path
|
|
38
|
+
task_path: Path
|
|
39
|
+
function: FunctionInfo
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def inspect_function(source_file: Path, function_name: str) -> FunctionInfo:
|
|
43
|
+
"""Inspect a top-level Python function via AST without executing user code."""
|
|
44
|
+
resolved = source_file.resolve()
|
|
45
|
+
if not resolved.is_file():
|
|
46
|
+
raise FileNotFoundError(f"Source file not found: {resolved}")
|
|
47
|
+
|
|
48
|
+
text = resolved.read_text(encoding="utf-8")
|
|
49
|
+
tree = ast.parse(text, filename=str(resolved))
|
|
50
|
+
lines = text.splitlines()
|
|
51
|
+
|
|
52
|
+
target: ast.FunctionDef | None = None
|
|
53
|
+
for node in tree.body:
|
|
54
|
+
if isinstance(node, ast.FunctionDef) and node.name == function_name:
|
|
55
|
+
target = node
|
|
56
|
+
break
|
|
57
|
+
|
|
58
|
+
if target is None:
|
|
59
|
+
raise ValueError(
|
|
60
|
+
f"Top-level function '{function_name}' not found in {resolved}"
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
signature = ast.unparse(target.args)
|
|
64
|
+
all_args = [
|
|
65
|
+
*(a.arg for a in target.args.posonlyargs),
|
|
66
|
+
*(a.arg for a in target.args.args),
|
|
67
|
+
*(a.arg for a in target.args.kwonlyargs),
|
|
68
|
+
]
|
|
69
|
+
start = target.lineno
|
|
70
|
+
end = target.end_lineno or target.lineno
|
|
71
|
+
source_code = "\n".join(lines[start - 1 : end])
|
|
72
|
+
docstring = ast.get_docstring(target)
|
|
73
|
+
|
|
74
|
+
return FunctionInfo(
|
|
75
|
+
name=function_name,
|
|
76
|
+
signature=signature,
|
|
77
|
+
arg_names=tuple(all_args),
|
|
78
|
+
lineno=start,
|
|
79
|
+
end_lineno=end,
|
|
80
|
+
source_code=source_code,
|
|
81
|
+
docstring=docstring,
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _render_kernel_wgsl(fn: FunctionInfo) -> str:
|
|
86
|
+
return f"""// WebGPU compute shader for `{fn.name}`.
|
|
87
|
+
// Edit this file together with port.py, then run:
|
|
88
|
+
// gpu-shift diff <unit_dir>
|
|
89
|
+
// gpu-shift bench <unit_dir>
|
|
90
|
+
// gpu-shift check <unit_dir>
|
|
91
|
+
|
|
92
|
+
@group(0) @binding(0)
|
|
93
|
+
var<storage, read> src: array<f32>;
|
|
94
|
+
|
|
95
|
+
@group(0) @binding(1)
|
|
96
|
+
var<storage, read_write> dst: array<f32>;
|
|
97
|
+
|
|
98
|
+
@compute @workgroup_size(64)
|
|
99
|
+
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {{
|
|
100
|
+
let idx = gid.x;
|
|
101
|
+
if (idx >= arrayLength(&src)) {{
|
|
102
|
+
return;
|
|
103
|
+
}}
|
|
104
|
+
dst[idx] = src[idx];
|
|
105
|
+
}}
|
|
106
|
+
"""
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _render_port_py(fn: FunctionInfo) -> str:
|
|
110
|
+
return f'''"""GPU port wrapper for `{fn.name}`.
|
|
111
|
+
|
|
112
|
+
Implement `run_gpu` to match the original function signature and behavior.
|
|
113
|
+
Use `ComputeKernel` from `gpu_shift.runtime` so all GPU buffers are
|
|
114
|
+
automatically cleaned up on every dispatch.
|
|
115
|
+
"""
|
|
116
|
+
|
|
117
|
+
from __future__ import annotations
|
|
118
|
+
|
|
119
|
+
from pathlib import Path
|
|
120
|
+
|
|
121
|
+
import numpy as np
|
|
122
|
+
|
|
123
|
+
from gpu_shift.runtime import ComputeKernel, ceil_div, pack_uniforms
|
|
124
|
+
|
|
125
|
+
_KERNEL = ComputeKernel.from_file(Path(__file__).with_name("kernel.wgsl"))
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def run_gpu({fn.signature}):
|
|
129
|
+
"""WebGPU/WGSL implementation of `{fn.name}`."""
|
|
130
|
+
raise NotImplementedError(
|
|
131
|
+
"Port not implemented yet. Edit kernel.wgsl and port.py, then run "
|
|
132
|
+
"`gpu-shift diff` and `gpu-shift check`."
|
|
133
|
+
)
|
|
134
|
+
'''
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _render_task_md(
|
|
138
|
+
fn: FunctionInfo,
|
|
139
|
+
source_rel: str,
|
|
140
|
+
unit_dir: Path,
|
|
141
|
+
rtol: float,
|
|
142
|
+
atol: float,
|
|
143
|
+
) -> str:
|
|
144
|
+
unit_display = unit_dir.as_posix()
|
|
145
|
+
return f"""# GPU Port Task: `{fn.name}`
|
|
146
|
+
|
|
147
|
+
## Target
|
|
148
|
+
- Source file: `{source_rel}` (lines {fn.lineno}-{fn.end_lineno})
|
|
149
|
+
- Function: `{fn.name}({fn.signature})`
|
|
150
|
+
- Tolerances: `rtol={rtol}`, `atol={atol}`
|
|
151
|
+
|
|
152
|
+
## Original CPU Implementation
|
|
153
|
+
|
|
154
|
+
```python
|
|
155
|
+
{fn.source_code}
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
## What to Edit
|
|
159
|
+
1. Implement the WGSL compute shader in `kernel.wgsl`.
|
|
160
|
+
2. Implement `run_gpu({fn.signature})` in `port.py` using `ComputeKernel`.
|
|
161
|
+
3. Do NOT edit the original source file by hand (`gpu-shift enable` handles it after `check` passes).
|
|
162
|
+
|
|
163
|
+
## Rules for Reliable WGSL Ports
|
|
164
|
+
- Always guard thread indices against array/image bounds (captured cases include odd/prime dimensions like `17x13` and `1x1`).
|
|
165
|
+
- Handle empty arrays (0 elements) on CPU before calling `ComputeKernel.dispatch`.
|
|
166
|
+
- Convert input arrays to contiguous `np.float32` (or matching WGSL dtype) inside `port.py`; pack uniform structs with `pack_uniforms(...)` (automatically 16-byte padded).
|
|
167
|
+
- Keep `workgroupBarrier()` in top-level uniform control flow (never inside `if (...) {{ ... return; }}`) for D3D12/WARP portability.
|
|
168
|
+
- Keep the exact output shape and dtype expected by callers.
|
|
169
|
+
|
|
170
|
+
## Verification Loop
|
|
171
|
+
|
|
172
|
+
```bash
|
|
173
|
+
gpu-shift capture {unit_display} -- <your command>
|
|
174
|
+
gpu-shift diff {unit_display}
|
|
175
|
+
gpu-shift bench {unit_display}
|
|
176
|
+
gpu-shift check {unit_display}
|
|
177
|
+
gpu-shift enable {unit_display}
|
|
178
|
+
```
|
|
179
|
+
"""
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def create_stage(
|
|
183
|
+
source_file: Path,
|
|
184
|
+
function_name: str,
|
|
185
|
+
unit_dir: Path | None = None,
|
|
186
|
+
*,
|
|
187
|
+
rtol: float = 1e-4,
|
|
188
|
+
atol: float = 1e-5,
|
|
189
|
+
power_preference: str = "high-performance",
|
|
190
|
+
overwrite: bool = False,
|
|
191
|
+
) -> StageResult:
|
|
192
|
+
"""Create a self-contained kernels/<fn>/ unit without editing source_file."""
|
|
193
|
+
resolved_source = source_file.resolve()
|
|
194
|
+
fn_info = inspect_function(resolved_source, function_name)
|
|
195
|
+
|
|
196
|
+
target_dir = (
|
|
197
|
+
unit_dir.resolve()
|
|
198
|
+
if unit_dir is not None
|
|
199
|
+
else (Path.cwd() / "kernels" / function_name).resolve()
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
if target_dir.exists() and any(target_dir.iterdir()) and not overwrite:
|
|
203
|
+
raise FileExistsError(
|
|
204
|
+
f"Unit directory already exists and is not empty: {target_dir}. "
|
|
205
|
+
"Pass --overwrite to recreate it."
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
target_dir.mkdir(parents=True, exist_ok=True)
|
|
209
|
+
source_rel = make_relative_posix(resolved_source, target_dir)
|
|
210
|
+
sha256 = compute_source_sha256(resolved_source)
|
|
211
|
+
|
|
212
|
+
manifest = UnitManifest(
|
|
213
|
+
name=function_name,
|
|
214
|
+
source_file=source_rel,
|
|
215
|
+
function_name=function_name,
|
|
216
|
+
source_sha256=sha256,
|
|
217
|
+
rtol=rtol,
|
|
218
|
+
atol=atol,
|
|
219
|
+
min_elements=0,
|
|
220
|
+
enabled=False,
|
|
221
|
+
last_check_passed=False,
|
|
222
|
+
power_preference=power_preference,
|
|
223
|
+
)
|
|
224
|
+
|
|
225
|
+
manifest_path = save_manifest(target_dir, manifest)
|
|
226
|
+
wgsl_path = target_dir / "kernel.wgsl"
|
|
227
|
+
port_path = target_dir / "port.py"
|
|
228
|
+
task_path = target_dir / "TASK.md"
|
|
229
|
+
|
|
230
|
+
wgsl_path.write_text(_render_kernel_wgsl(fn_info), encoding="utf-8")
|
|
231
|
+
port_path.write_text(_render_port_py(fn_info), encoding="utf-8")
|
|
232
|
+
try:
|
|
233
|
+
unit_display = target_dir.relative_to(Path.cwd().resolve()).as_posix()
|
|
234
|
+
except ValueError:
|
|
235
|
+
unit_display = target_dir.name
|
|
236
|
+
task_path.write_text(
|
|
237
|
+
_render_task_md(fn_info, source_rel, Path(unit_display), rtol, atol),
|
|
238
|
+
encoding="utf-8",
|
|
239
|
+
)
|
|
240
|
+
|
|
241
|
+
return StageResult(
|
|
242
|
+
unit_dir=target_dir,
|
|
243
|
+
manifest_path=manifest_path,
|
|
244
|
+
wgsl_path=wgsl_path,
|
|
245
|
+
port_path=port_path,
|
|
246
|
+
task_path=task_path,
|
|
247
|
+
function=fn_info,
|
|
248
|
+
)
|
gpu_shift/switch.py
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
"""Reversible enable/disable switcher and runtime crossover/fallback router."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import functools
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import warnings
|
|
9
|
+
from collections.abc import Callable
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from gpu_shift.bench import primary_array_elements
|
|
15
|
+
from gpu_shift.device import clear_device_cache, has_hardware_gpu
|
|
16
|
+
from gpu_shift.diff import compare_outputs
|
|
17
|
+
from gpu_shift.manifest import (
|
|
18
|
+
load_manifest,
|
|
19
|
+
load_port_function,
|
|
20
|
+
make_relative_posix,
|
|
21
|
+
resolve_source_path,
|
|
22
|
+
save_manifest,
|
|
23
|
+
)
|
|
24
|
+
from gpu_shift.runtime import GpuLimitError
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True)
|
|
28
|
+
class SwitchResult:
|
|
29
|
+
"""Outcome of enable_unit or disable_unit."""
|
|
30
|
+
|
|
31
|
+
unit_dir: Path
|
|
32
|
+
source_file: Path
|
|
33
|
+
function_name: str
|
|
34
|
+
enabled: bool
|
|
35
|
+
changed: bool
|
|
36
|
+
message: str
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _mode_for_unit_key(unit_env_key: str) -> str:
|
|
40
|
+
val = os.environ.get(unit_env_key) or os.environ.get("GPU_SHIFT_MODE")
|
|
41
|
+
return "auto" if val is None else val.strip().lower()
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def wrap_function(
|
|
45
|
+
original_fn: Callable[..., Any],
|
|
46
|
+
*,
|
|
47
|
+
unit_rel_path: str,
|
|
48
|
+
source_file: str,
|
|
49
|
+
) -> Callable[..., Any]:
|
|
50
|
+
"""Wrap an original CPU function with crossover routing, shadow mode, and CPU fallback."""
|
|
51
|
+
unit_dir = (Path(source_file).resolve().parent / unit_rel_path).resolve()
|
|
52
|
+
unit_name = original_fn.__name__
|
|
53
|
+
unit_env_key = f"GPU_SHIFT_UNIT_{unit_name.upper()}"
|
|
54
|
+
|
|
55
|
+
state: dict[str, Any] = {
|
|
56
|
+
"loaded": False,
|
|
57
|
+
"unavailable": False,
|
|
58
|
+
"hardware_checked": False,
|
|
59
|
+
"has_hardware": False,
|
|
60
|
+
"manifest": None,
|
|
61
|
+
"port_fn": None,
|
|
62
|
+
"min_elements": 0,
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
def _ensure_loaded(*, require_hardware: bool = False) -> bool:
|
|
66
|
+
if not state["loaded"]:
|
|
67
|
+
state["loaded"] = True
|
|
68
|
+
try:
|
|
69
|
+
manifest = load_manifest(unit_dir)
|
|
70
|
+
port_fn = load_port_function(unit_dir, manifest)
|
|
71
|
+
state["manifest"] = manifest
|
|
72
|
+
state["port_fn"] = port_fn
|
|
73
|
+
state["min_elements"] = int(manifest.min_elements)
|
|
74
|
+
except Exception: # noqa: BLE001
|
|
75
|
+
state["unavailable"] = True
|
|
76
|
+
return False
|
|
77
|
+
if state["unavailable"]:
|
|
78
|
+
return False
|
|
79
|
+
if require_hardware:
|
|
80
|
+
if not state["hardware_checked"]:
|
|
81
|
+
state["hardware_checked"] = True
|
|
82
|
+
manifest = state["manifest"]
|
|
83
|
+
state["has_hardware"] = has_hardware_gpu(manifest.power_preference)
|
|
84
|
+
return bool(state["has_hardware"])
|
|
85
|
+
return True
|
|
86
|
+
|
|
87
|
+
@functools.wraps(original_fn)
|
|
88
|
+
def _wrapped(*args: Any, **kwargs: Any) -> Any:
|
|
89
|
+
mode = _mode_for_unit_key(unit_env_key)
|
|
90
|
+
|
|
91
|
+
if mode == "cpu":
|
|
92
|
+
return original_fn(*args, **kwargs)
|
|
93
|
+
|
|
94
|
+
if mode == "gpu":
|
|
95
|
+
if not _ensure_loaded(require_hardware=False):
|
|
96
|
+
raise RuntimeError(
|
|
97
|
+
f"GPU_SHIFT_MODE=gpu requested, but GPU port at {unit_dir} failed to load."
|
|
98
|
+
)
|
|
99
|
+
return state["port_fn"](*args, **kwargs)
|
|
100
|
+
|
|
101
|
+
if mode == "shadow":
|
|
102
|
+
cpu_out = original_fn(*args, **kwargs)
|
|
103
|
+
if _ensure_loaded(require_hardware=False):
|
|
104
|
+
manifest = state["manifest"]
|
|
105
|
+
try:
|
|
106
|
+
gpu_out = state["port_fn"](*args, **kwargs)
|
|
107
|
+
ok, _, _, reason, _, _, _ = compare_outputs(
|
|
108
|
+
gpu_out,
|
|
109
|
+
cpu_out,
|
|
110
|
+
rtol=manifest.rtol,
|
|
111
|
+
atol=manifest.atol,
|
|
112
|
+
)
|
|
113
|
+
if not ok:
|
|
114
|
+
warnings.warn(
|
|
115
|
+
f"[gpu-shift shadow] '{unit_name}' mismatch: {reason}",
|
|
116
|
+
RuntimeWarning,
|
|
117
|
+
stacklevel=2,
|
|
118
|
+
)
|
|
119
|
+
except Exception as exc: # noqa: BLE001
|
|
120
|
+
warnings.warn(
|
|
121
|
+
f"[gpu-shift shadow] '{unit_name}' GPU error: {exc}",
|
|
122
|
+
RuntimeWarning,
|
|
123
|
+
stacklevel=2,
|
|
124
|
+
)
|
|
125
|
+
return cpu_out
|
|
126
|
+
|
|
127
|
+
# Default "auto" mode: require real hardware GPU, check crossover, keep single-call
|
|
128
|
+
# limit overflows on CPU without permanently disabling GPU for normal calls.
|
|
129
|
+
if not _ensure_loaded(require_hardware=True):
|
|
130
|
+
return original_fn(*args, **kwargs)
|
|
131
|
+
|
|
132
|
+
min_elem = state["min_elements"]
|
|
133
|
+
if min_elem > 0 and primary_array_elements(args, kwargs) < min_elem:
|
|
134
|
+
return original_fn(*args, **kwargs)
|
|
135
|
+
|
|
136
|
+
try:
|
|
137
|
+
return state["port_fn"](*args, **kwargs)
|
|
138
|
+
except GpuLimitError:
|
|
139
|
+
# Oversized input for this single call: fall back to CPU, keep GPU active.
|
|
140
|
+
return original_fn(*args, **kwargs)
|
|
141
|
+
except Exception: # noqa: BLE001
|
|
142
|
+
clear_device_cache()
|
|
143
|
+
state["unavailable"] = True
|
|
144
|
+
return original_fn(*args, **kwargs)
|
|
145
|
+
|
|
146
|
+
_wrapped.__gpu_shift_original__ = original_fn # type: ignore[attr-defined]
|
|
147
|
+
return _wrapped
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _block_pattern(function_name: str) -> re.Pattern[str]:
|
|
151
|
+
escaped = re.escape(function_name)
|
|
152
|
+
return re.compile(
|
|
153
|
+
rf"\r?\n# >>> gpu-shift:begin {escaped}\r?\n"
|
|
154
|
+
rf".*?# <<< gpu-shift:end {escaped}(?:\r?\n)?",
|
|
155
|
+
re.DOTALL,
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _render_switch_block(function_name: str, unit_rel_posix: str, newline: str, trailing_nl: bool) -> str:
|
|
160
|
+
lines = [
|
|
161
|
+
f"# >>> gpu-shift:begin {function_name}",
|
|
162
|
+
f"from gpu_shift.switch import wrap_function as _gpu_shift_wrap_{function_name}",
|
|
163
|
+
f"{function_name} = _gpu_shift_wrap_{function_name}(",
|
|
164
|
+
f" {function_name},",
|
|
165
|
+
f' unit_rel_path="{unit_rel_posix}",',
|
|
166
|
+
" source_file=__file__,",
|
|
167
|
+
")",
|
|
168
|
+
f"# <<< gpu-shift:end {function_name}",
|
|
169
|
+
]
|
|
170
|
+
body = newline.join(lines)
|
|
171
|
+
return f"{newline}{body}{newline if trailing_nl else ''}"
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def enable_unit(unit_dir: Path, *, force: bool = False) -> SwitchResult:
|
|
175
|
+
"""Enable a verified GPU port by appending a reversible wrapper block to source_file."""
|
|
176
|
+
resolved_unit = unit_dir.resolve()
|
|
177
|
+
manifest = load_manifest(resolved_unit)
|
|
178
|
+
|
|
179
|
+
if not manifest.last_check_passed and not force:
|
|
180
|
+
raise RuntimeError(
|
|
181
|
+
f"Unit '{manifest.name}' has not passed `gpu-shift check`. "
|
|
182
|
+
"Run `gpu-shift check` first (or pass --force)."
|
|
183
|
+
)
|
|
184
|
+
|
|
185
|
+
source_path = resolve_source_path(resolved_unit, manifest)
|
|
186
|
+
if not source_path.is_file():
|
|
187
|
+
raise FileNotFoundError(f"Original source file not found: {source_path}")
|
|
188
|
+
|
|
189
|
+
raw_bytes = source_path.read_bytes()
|
|
190
|
+
text = raw_bytes.decode("utf-8")
|
|
191
|
+
|
|
192
|
+
pattern = _block_pattern(manifest.function_name)
|
|
193
|
+
if pattern.search(text):
|
|
194
|
+
manifest.enabled = True
|
|
195
|
+
save_manifest(resolved_unit, manifest)
|
|
196
|
+
return SwitchResult(
|
|
197
|
+
unit_dir=resolved_unit,
|
|
198
|
+
source_file=source_path,
|
|
199
|
+
function_name=manifest.function_name,
|
|
200
|
+
enabled=True,
|
|
201
|
+
changed=False,
|
|
202
|
+
message=f"Unit '{manifest.name}' is already enabled in {source_path.name}.",
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
newline = "\r\n" if "\r\n" in text else "\n"
|
|
206
|
+
trailing_nl = text.endswith("\n")
|
|
207
|
+
unit_rel = make_relative_posix(resolved_unit, source_path.parent)
|
|
208
|
+
block = _render_switch_block(
|
|
209
|
+
manifest.function_name, unit_rel, newline=newline, trailing_nl=trailing_nl
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
updated_text = text + block
|
|
213
|
+
source_path.write_bytes(updated_text.encode("utf-8"))
|
|
214
|
+
|
|
215
|
+
manifest.enabled = True
|
|
216
|
+
save_manifest(resolved_unit, manifest)
|
|
217
|
+
|
|
218
|
+
return SwitchResult(
|
|
219
|
+
unit_dir=resolved_unit,
|
|
220
|
+
source_file=source_path,
|
|
221
|
+
function_name=manifest.function_name,
|
|
222
|
+
enabled=True,
|
|
223
|
+
changed=True,
|
|
224
|
+
message=(
|
|
225
|
+
f"Enabled '{manifest.function_name}' in {source_path.name} "
|
|
226
|
+
f"(min_elements={manifest.min_elements})."
|
|
227
|
+
),
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def disable_unit(unit_dir: Path) -> SwitchResult:
|
|
232
|
+
"""Remove the gpu-shift wrapper block, restoring source_file byte-for-byte."""
|
|
233
|
+
resolved_unit = unit_dir.resolve()
|
|
234
|
+
manifest = load_manifest(resolved_unit)
|
|
235
|
+
source_path = resolve_source_path(resolved_unit, manifest)
|
|
236
|
+
if not source_path.is_file():
|
|
237
|
+
raise FileNotFoundError(f"Original source file not found: {source_path}")
|
|
238
|
+
|
|
239
|
+
raw_bytes = source_path.read_bytes()
|
|
240
|
+
text = raw_bytes.decode("utf-8")
|
|
241
|
+
pattern = _block_pattern(manifest.function_name)
|
|
242
|
+
|
|
243
|
+
if not pattern.search(text):
|
|
244
|
+
manifest.enabled = False
|
|
245
|
+
save_manifest(resolved_unit, manifest)
|
|
246
|
+
return SwitchResult(
|
|
247
|
+
unit_dir=resolved_unit,
|
|
248
|
+
source_file=source_path,
|
|
249
|
+
function_name=manifest.function_name,
|
|
250
|
+
enabled=False,
|
|
251
|
+
changed=False,
|
|
252
|
+
message=f"Unit '{manifest.name}' was not enabled in {source_path.name}.",
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
restored_text = pattern.sub("", text, count=1)
|
|
256
|
+
source_path.write_bytes(restored_text.encode("utf-8"))
|
|
257
|
+
|
|
258
|
+
manifest.enabled = False
|
|
259
|
+
save_manifest(resolved_unit, manifest)
|
|
260
|
+
|
|
261
|
+
return SwitchResult(
|
|
262
|
+
unit_dir=resolved_unit,
|
|
263
|
+
source_file=source_path,
|
|
264
|
+
function_name=manifest.function_name,
|
|
265
|
+
enabled=False,
|
|
266
|
+
changed=True,
|
|
267
|
+
message=f"Disabled '{manifest.function_name}' in {source_path.name} (restored original).",
|
|
268
|
+
)
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: wgpu-shift
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Move slow Python/NumPy CPU loops to any GPU via WebGPU/WGSL with deterministic verification, native VRAM leak soaking, and crossover benchmarking.
|
|
5
|
+
Project-URL: Homepage, https://github.com/boraiks/gpu-shift
|
|
6
|
+
Project-URL: Repository, https://github.com/boraiks/gpu-shift
|
|
7
|
+
Project-URL: Issues, https://github.com/boraiks/gpu-shift/issues
|
|
8
|
+
Author: Bora
|
|
9
|
+
License: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: benchmark,coding-agent,compute-shader,gpu,mcp,numpy,webgpu,wgpu,wgsl
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Intended Audience :: Science/Research
|
|
15
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
22
|
+
Classifier: Topic :: Scientific/Engineering
|
|
23
|
+
Classifier: Topic :: Software Development :: Testing
|
|
24
|
+
Requires-Python: >=3.11
|
|
25
|
+
Requires-Dist: numpy>=1.26
|
|
26
|
+
Requires-Dist: wgpu>=0.19
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
|
|
29
|
+
<p align="center">
|
|
30
|
+
<picture>
|
|
31
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/boraiks/gpu-shift/main/docs/assets/banner-dark.png">
|
|
32
|
+
<source media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/boraiks/gpu-shift/main/docs/assets/banner.png">
|
|
33
|
+
<img src="https://raw.githubusercontent.com/boraiks/gpu-shift/main/docs/assets/banner.png" width="560" alt="gpu-shift">
|
|
34
|
+
</picture>
|
|
35
|
+
</p>
|
|
36
|
+
|
|
37
|
+
<p align="center"><sub>English · <a href="https://github.com/boraiks/gpu-shift/blob/main/docs/README_TR.md">Türkçe</a></sub></p>
|
|
38
|
+
|
|
39
|
+
<p align="center"><b>Shift slow CPU loops onto any GPU - no CUDA, no guesswork.</b><br>
|
|
40
|
+
Point it at your script: it finds the hotspot, captures real CPU truth, and verifies every GPU port<br>
|
|
41
|
+
for accuracy, zero VRAM leaks, and real end-to-end speedup before turning it on.</p>
|
|
42
|
+
|
|
43
|
+
<p align="center">
|
|
44
|
+
<a href="https://pypi.org/project/wgpu-shift/"><img src="https://img.shields.io/pypi/v/wgpu-shift?color=2563EB&label=PyPI" alt="PyPI - wgpu-shift"></a>
|
|
45
|
+
<img src="https://img.shields.io/badge/python-3.11%2B-2563EB?logo=python&logoColor=white" alt="Python 3.11+">
|
|
46
|
+
<img src="https://img.shields.io/badge/NVIDIA%20%C2%B7%20AMD%20%C2%B7%20Intel%20%C2%B7%20Apple%20Silicon-no%20CUDA-10B981" alt="Works on NVIDIA, AMD, Intel, and Apple Silicon without CUDA">
|
|
47
|
+
<a href="https://github.com/boraiks/gpu-shift/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-555" alt="MIT license"></a>
|
|
48
|
+
</p>
|
|
49
|
+
|
|
50
|
+
<p align="center"><b><a href="#use-it-on-your-code">Install</a></b> · <a href="#try-it-now">Live demo</a> · <a href="https://github.com/boraiks/gpu-shift/blob/main/docs/real-world.md">Real-world ports</a> · <a href="https://github.com/boraiks/gpu-shift/blob/main/docs/how-it-works.md">How it works</a> · <a href="https://github.com/boraiks/gpu-shift/blob/main/evals/README.md">Eval suite</a> · <a href="https://github.com/boraiks/gpu-shift/blob/main/DECISIONS.md">Decisions</a></p>
|
|
51
|
+
|
|
52
|
+
<p align="center">
|
|
53
|
+
<img src="https://raw.githubusercontent.com/boraiks/gpu-shift/main/docs/assets/demo.gif" alt="1:1 real-time benchmark comparing original scikit-image and SciPy CPU functions against gpu-shift GPU ports: GPU completes in 0.04 to 0.07 s while CPU takes 5.01 to 5.11 s, with all 24 captured cases matching and 0 VRAM leaks." width="780">
|
|
54
|
+
<br>
|
|
55
|
+
<sub>1:1 real-time run on an RTX 4060 Laptop GPU, data transfers included. <a href="https://github.com/boraiks/gpu-shift/blob/main/docs/real-world.md">How it was measured</a>.</sub>
|
|
56
|
+
</p>
|
|
57
|
+
|
|
58
|
+
`gpu-shift` (PyPI package: `wgpu-shift`) is not an auto-compiler. You (or your coding agent) write the GPU shader one function at a time; `gpu-shift` finds what is slow, proves outputs match CPU, checks for 0 B VRAM leaks, and keeps small or transfer-bound inputs on CPU automatically. Built on `wgpu-py`, so the same port runs on NVIDIA, AMD, Intel, and Apple Silicon without CUDA.
|
|
59
|
+
|
|
60
|
+
| Upstream library, same output as CPU | Original CPU | With `gpu-shift` |
|
|
61
|
+
| --- | ---: | ---: |
|
|
62
|
+
| [`scikit-image`](https://github.com/boraiks/gpu-shift/blob/main/docs/real-world.md#1-scikit-image-0260---denoise_bilateral) `denoise_bilateral` (512x512, 50 frames) | 5.01 s | **0.04 s (121x)** |
|
|
63
|
+
| [`scipy.signal.convolve2d`](https://github.com/boraiks/gpu-shift/blob/main/docs/real-world.md#2-scipy-1181---scipysignalconvolve2d) (1024x1024, 20 frames) | 5.06 s | **0.06 s (88x)** |
|
|
64
|
+
| [`scipy.spatial.distance.cdist`](https://github.com/boraiks/gpu-shift/blob/main/docs/real-world.md#3-scipy-1181---scipyspatialdistancecdist) (2048x128, 20 calls) | 5.11 s | **0.07 s (72x)** |
|
|
65
|
+
|
|
66
|
+
Reproduce locally: `uv run --with scipy --with scikit-image python benchmarks/real_world/run_all.py`
|
|
67
|
+
|
|
68
|
+
## Try it now
|
|
69
|
+
|
|
70
|
+
Test your own GPU in 15 seconds, no clone required:
|
|
71
|
+
|
|
72
|
+
```sh
|
|
73
|
+
uvx wgpu-shift demo
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
*(Windows Smart App Control: `uv run --with wgpu-shift python -m gpu_shift demo`)*
|
|
77
|
+
|
|
78
|
+
## Use it on your code
|
|
79
|
+
|
|
80
|
+
Install once from PyPI (`wgpu-shift` installs both `gpu-shift` and `wgpu-shift` commands) and wire it into your coding agent (Claude Code, Antigravity/Gemini, Codex, Cursor, or OpenCode):
|
|
81
|
+
|
|
82
|
+
```sh
|
|
83
|
+
pip install wgpu-shift # or: uv tool install wgpu-shift
|
|
84
|
+
gpu-shift setup # backs up existing configs; undo anytime with `gpu-shift setup --remove`
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Or run directly from the terminal without touching your source file until checks pass:
|
|
88
|
+
|
|
89
|
+
```sh
|
|
90
|
+
gpu-shift run -- python app.py # 1. scans hotspot, captures CPU truth + edge traps, writes TASK.md
|
|
91
|
+
# implement kernels/<fn>/kernel.wgsl + port.py (yourself or via your agent), then re-run:
|
|
92
|
+
gpu-shift run -- python app.py # 2. runs diff, VRAM check, transfer-inclusive bench, enables if faster
|
|
93
|
+
gpu-shift disable kernels/<fn> # reverts the original file byte-for-byte
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
At runtime, `GPU_SHIFT_MODE=auto|cpu|shadow|gpu` lets you compare or force either backend, and machines without a hardware GPU fall back to CPU silently. Full CLI reference (`scan`, `stage`, `capture`, `diff`, `bench`, `check`, `report`) and built-in examples live in [How it works](https://github.com/boraiks/gpu-shift/blob/main/docs/how-it-works.md).
|
|
97
|
+
|
|
98
|
+
<p align="center">
|
|
99
|
+
<img src="https://raw.githubusercontent.com/boraiks/gpu-shift/main/docs/assets/check.gif" alt="gpu-shift check verifying source freshness, WGSL compilation, 8/8 numerical diff, and 0 B VRAM growth, followed by gpu-shift run keeping tiny_add on CPU when transfer cost dominates." width="780">
|
|
100
|
+
<br>
|
|
101
|
+
<sub><code>check</code> enforces parity and 0 B VRAM growth; <code>run</code> keeps lightweight ops on CPU when transfer cost dominates.</sub>
|
|
102
|
+
</p>
|
|
103
|
+
|
|
104
|
+
## Languages
|
|
105
|
+
|
|
106
|
+
| Language | Status | Notes |
|
|
107
|
+
| --- | --- | --- |
|
|
108
|
+
| **Python / NumPy** | Ready (`v0.1`) | CLI, MCP server, `SKILL.md`, 8-task eval suite, and runtime safety guards |
|
|
109
|
+
| **TypeScript / JavaScript** | Planned | Same WGSL kernel and verification loop for Node.js / Deno / Bun |
|
|
110
|
+
| **Rust** | Planned | `wgpu` crate bridge sharing `kernel.wgsl` and checks |
|
|
111
|
+
| **C / C++** | Planned | `wgpu-native` C ABI bridge for hot numerical loops |
|
|
112
|
+
|
|
113
|
+
Also planned: optional `triton` / `mlx` backends. Contributions welcome.
|
|
114
|
+
|
|
115
|
+
## Docs
|
|
116
|
+
|
|
117
|
+
- [How it works](https://github.com/boraiks/gpu-shift/blob/main/docs/how-it-works.md) - CLI reference, agent setup paths, runtime modes, and built-in examples
|
|
118
|
+
- [Real-world ports](https://github.com/boraiks/gpu-shift/blob/main/docs/real-world.md) - `scikit-image` and `SciPy` timings, optimizations, and upstream quirks caught by `diff`
|
|
119
|
+
- [Python eval suite](https://github.com/boraiks/gpu-shift/blob/main/evals/README.md) - 8 labeled tasks covering 1D/2D/3D arrays, multi-output tuples, and CPU/serial-loop traps
|
|
120
|
+
- [Design decisions](https://github.com/boraiks/gpu-shift/blob/main/DECISIONS.md) - trade-offs and non-goals
|
|
121
|
+
- [Contributing](https://github.com/boraiks/gpu-shift/blob/main/CONTRIBUTING.md) - local dev setup and codebase layout
|
|
122
|
+
|
|
123
|
+
## License
|
|
124
|
+
|
|
125
|
+
[MIT](https://github.com/boraiks/gpu-shift/blob/main/LICENSE). Shaders and ports generated in your own repository belong to you.
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
gpu_shift/__init__.py,sha256=u3BMhkCSfSyOAZOGrMn8Ou5N57k03KYoDid1RGxBfE0,346
|
|
2
|
+
gpu_shift/__main__.py,sha256=GoqoT73WHfoOoUukAkU4e5nUlUvGhbq_8Osj7VgfO14,177
|
|
3
|
+
gpu_shift/_capturer.py,sha256=EkkCQNYaPP1q0ED7l0EZtpL40zK4NGqkq7lnHIHRuKI,6496
|
|
4
|
+
gpu_shift/_scanner.py,sha256=ETB7EYc2Ehes-GQWJfN60BPaaOeth4VUJoxXLk6LNqI,2051
|
|
5
|
+
gpu_shift/bench.py,sha256=agKS8HYU2q9WmKvKJzPeuDlSarNL5iHuchn-7fE_RP0,10859
|
|
6
|
+
gpu_shift/capture.py,sha256=C9_nimknyfUiBh6U8SMgvNfbftqqXjjmGRoV_mDYdPo,23092
|
|
7
|
+
gpu_shift/check.py,sha256=BAeFskMERjFwigSOIY3xlrJr4nkNIEA1eC8r1rMmomo,7490
|
|
8
|
+
gpu_shift/cli.py,sha256=_YcWp5SoLMgsUx2MZXy5MatlhMK3wN0VnxBknIXYfdA,21626
|
|
9
|
+
gpu_shift/demo.py,sha256=ZnP0Yqgr_I29UWhuhK0_fQ3Wq25pKK_DLwDwjeDlqic,8451
|
|
10
|
+
gpu_shift/device.py,sha256=cLaNAAayDTE2OsoH280Q7QHNh8hg7cVcl2lfM5a3ZYk,5353
|
|
11
|
+
gpu_shift/diff.py,sha256=-_1PTCqaoZsVK46qJ-IvoYuamcqyc1T_WPyzlraClvk,17281
|
|
12
|
+
gpu_shift/manifest.py,sha256=7rYhnCOAtsxhz2XpDoF4GHPoBQUda4P85BpMpkMytaM,6248
|
|
13
|
+
gpu_shift/mcp_server.py,sha256=dtNxAXXpTT3_-SIvOiU_KbzW9-icROSMaMrbUoAC0nA,12585
|
|
14
|
+
gpu_shift/report.py,sha256=WadprlmiJLu56fbnHTWb32l5UePPfHmDziQq5sKgAb0,8805
|
|
15
|
+
gpu_shift/run.py,sha256=nPWtMO9A-1EOtsevhZu19qbod5lx0rtHu-9arHrinbA,7117
|
|
16
|
+
gpu_shift/runtime.py,sha256=G1OE8DEtRB5rLM239dJmLus8CGBDsvc5trIf7cwf-1U,22528
|
|
17
|
+
gpu_shift/scan.py,sha256=-lAFlD-B4A-FXRNMJ4zURWXsE99TXDMBHQbmHPgf8x0,12187
|
|
18
|
+
gpu_shift/setup.py,sha256=U1gB2It4UWBK73_N6CixRc-9mD2UWzX-PJduEmaG-bI,8859
|
|
19
|
+
gpu_shift/stage.py,sha256=bhJUSsOAN5nHJdsFcuUv6xGDcdaMvdOiQ_Zs0WA7tuo,7160
|
|
20
|
+
gpu_shift/switch.py,sha256=F-MKsHWywESefvd23ssEjV6I4yZxj7fWK9eo-z2pK50,9381
|
|
21
|
+
gpu_shift/skill_data/SKILL.md,sha256=gIwNYA3v1kq43hxe0LEmpvbRp9jWZxEs4EUdRXfjuSs,4070
|
|
22
|
+
wgpu_shift-0.1.0.dist-info/METADATA,sha256=7VkINcHE_aRAV3hrJxOIg3hPfBZrGafvPJxliQTnz6Y,8215
|
|
23
|
+
wgpu_shift-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
24
|
+
wgpu_shift-0.1.0.dist-info/entry_points.txt,sha256=no8WiGmICdN4PYC9PBmuL5vz7-cQZtepj3Do4E8Fkj0,81
|
|
25
|
+
wgpu_shift-0.1.0.dist-info/licenses/LICENSE,sha256=xofjiyK3m5vHwAFQDsmg_SMnsIAN1SsjV5tHG37l-tg,1079
|
|
26
|
+
wgpu_shift-0.1.0.dist-info/RECORD,,
|