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/scan.py ADDED
@@ -0,0 +1,380 @@
1
+ """Scan a Python workload (cProfile + AST heuristics) to rank GPU offload candidates."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ import json
7
+ import os
8
+ import subprocess
9
+ import sys
10
+ import sysconfig
11
+ import tempfile
12
+ from dataclasses import dataclass
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ _IO_NET_NAMES = {
17
+ "open",
18
+ "requests",
19
+ "urllib",
20
+ "socket",
21
+ "http",
22
+ "sqlite3",
23
+ "subprocess",
24
+ "psycopg",
25
+ "psycopg2",
26
+ "pymongo",
27
+ "aiohttp",
28
+ "httpx",
29
+ }
30
+ _NUMERIC_NAMES = {
31
+ "np",
32
+ "numpy",
33
+ "math",
34
+ "scipy",
35
+ "exp",
36
+ "sqrt",
37
+ "sin",
38
+ "cos",
39
+ "sum",
40
+ "dot",
41
+ "matmul",
42
+ "einsum",
43
+ "pad",
44
+ "zeros",
45
+ "zeros_like",
46
+ "empty",
47
+ }
48
+ _ALREADY_ACCEL_NAMES = {"njit", "jit", "vectorize", "torch", "jax", "cupy", "triton"}
49
+
50
+
51
+ @dataclass(frozen=True)
52
+ class ScanCandidate:
53
+ """One ranked CPU bottleneck candidate for GPU offloading."""
54
+
55
+ source_file: Path
56
+ source_rel: str
57
+ function_name: str
58
+ lineno: int
59
+ ncalls: int
60
+ tottime_ms: float
61
+ cumtime_ms: float
62
+ time_share_pct: float
63
+ score: int
64
+ stageable: bool
65
+ reasons: tuple[str, ...]
66
+ suggested_command: str
67
+
68
+
69
+ @dataclass(frozen=True)
70
+ class ScanResult:
71
+ """Ranked scan summary for a Python command."""
72
+
73
+ command: tuple[str, ...]
74
+ project_root: Path
75
+ total_ms: float
76
+ candidates: tuple[ScanCandidate, ...]
77
+
78
+
79
+ def _is_user_file(file_path: Path, project_root: Path) -> bool:
80
+ try:
81
+ resolved = file_path.resolve()
82
+ except OSError:
83
+ return False
84
+ if not resolved.is_file():
85
+ return False
86
+
87
+ # Exclude stdlib, site-packages, and gpu_shift itself
88
+ stdlib = Path(sysconfig.get_paths().get("stdlib", "")).resolve()
89
+ pkg_dir = Path(__file__).resolve().parent
90
+ parts_lower = {p.lower() for p in resolved.parts}
91
+ if "site-packages" in parts_lower or ".venv" in parts_lower:
92
+ return False
93
+ if resolved == stdlib or stdlib in resolved.parents:
94
+ return False
95
+ if pkg_dir in resolved.parents:
96
+ return False
97
+ return resolved == project_root or project_root in resolved.parents
98
+
99
+
100
+ def _is_shifted_index(slice_node: ast.AST, loop_var: str) -> bool:
101
+ """Return True if slice_node is `loop_var - k` or `loop_var + k` (k != 0)."""
102
+ if isinstance(slice_node, ast.BinOp) and isinstance(slice_node.op, (ast.Sub, ast.Add)):
103
+ left, right = slice_node.left, slice_node.right
104
+ if (
105
+ isinstance(left, ast.Name)
106
+ and left.id == loop_var
107
+ and isinstance(right, ast.Constant)
108
+ and isinstance(right.value, int)
109
+ and right.value != 0
110
+ ):
111
+ return True
112
+ return False
113
+
114
+
115
+ def _has_serial_loop_dependency(func_node: ast.FunctionDef) -> bool:
116
+ """Detect loop-carried sequential dependencies (e.g. out[i] = out[i-1] + x[i])."""
117
+ for node in ast.walk(func_node):
118
+ if not isinstance(node, ast.For) or not isinstance(node.target, ast.Name):
119
+ continue
120
+ loop_var = node.target.id
121
+ written_arrays: set[str] = set()
122
+ shifted_reads: set[str] = set()
123
+ scalar_accumulators: set[str] = set()
124
+ written_values_by_var: set[str] = set()
125
+
126
+ for stmt in node.body:
127
+ if isinstance(stmt, ast.AugAssign) and isinstance(stmt.target, ast.Name):
128
+ scalar_accumulators.add(stmt.target.id)
129
+ elif isinstance(stmt, ast.Assign):
130
+ for tgt in stmt.targets:
131
+ if (
132
+ isinstance(tgt, ast.Subscript)
133
+ and isinstance(tgt.value, ast.Name)
134
+ and isinstance(tgt.slice, ast.Name)
135
+ and tgt.slice.id == loop_var
136
+ ):
137
+ written_arrays.add(tgt.value.id)
138
+ if isinstance(stmt.value, ast.Name):
139
+ written_values_by_var.add(stmt.value.id)
140
+ for sub in ast.walk(stmt.value):
141
+ if (
142
+ isinstance(sub, ast.Subscript)
143
+ and isinstance(sub.value, ast.Name)
144
+ and _is_shifted_index(sub.slice, loop_var)
145
+ ):
146
+ shifted_reads.add(sub.value.id)
147
+ elif isinstance(tgt, ast.Name):
148
+ # Detect `acc = acc + x[i]` pattern
149
+ for sub in ast.walk(stmt.value):
150
+ if isinstance(sub, ast.Name) and sub.id == tgt.id:
151
+ scalar_accumulators.add(tgt.id)
152
+ break
153
+
154
+ # Pattern 1: out[i] reads out[i - 1] (or out[i + 1])
155
+ if written_arrays & shifted_reads:
156
+ return True
157
+ # Pattern 2: scalar running accumulator written to out[i] each step
158
+ if written_arrays and (scalar_accumulators & written_values_by_var):
159
+ return True
160
+ return False
161
+
162
+
163
+ def _analyze_function_ast(
164
+ file_path: Path,
165
+ func_name: str,
166
+ lineno: int,
167
+ ) -> tuple[bool, int, list[str]]:
168
+ """Inspect a function via AST and return (is_top_level, base_score, reasons)."""
169
+ try:
170
+ source = file_path.read_text(encoding="utf-8")
171
+ tree = ast.parse(source, filename=str(file_path))
172
+ except (OSError, SyntaxError):
173
+ return False, 0, ["Could not parse source"]
174
+
175
+ top_level_node: ast.FunctionDef | None = None
176
+ any_node: ast.FunctionDef | None = None
177
+
178
+ for stmt in tree.body:
179
+ if isinstance(stmt, ast.FunctionDef) and stmt.name == func_name:
180
+ top_level_node = stmt
181
+ break
182
+
183
+ if top_level_node is not None:
184
+ any_node = top_level_node
185
+ else:
186
+ for node in ast.walk(tree):
187
+ if (
188
+ isinstance(node, ast.FunctionDef)
189
+ and node.name == func_name
190
+ and abs(node.lineno - lineno) <= 2
191
+ ):
192
+ any_node = node
193
+ break
194
+
195
+ if any_node is None:
196
+ return False, 0, ["Function definition not found"]
197
+
198
+ is_top_level = top_level_node is not None
199
+ score = 0
200
+ reasons: list[str] = []
201
+
202
+ has_loop = False
203
+ has_nested_loop = False
204
+ uses_numeric = False
205
+ has_subscript = False
206
+ has_binop = False
207
+ has_io_net = False
208
+ already_accel = False
209
+ has_serial_dep = _has_serial_loop_dependency(any_node)
210
+
211
+ for dec in any_node.decorator_list:
212
+ dec_text = ast.unparse(dec)
213
+ if any(tok in dec_text for tok in _ALREADY_ACCEL_NAMES):
214
+ already_accel = True
215
+
216
+ def _walk_loops(node: ast.AST, depth: int) -> None:
217
+ nonlocal has_loop, has_nested_loop
218
+ for child in ast.iter_child_nodes(node):
219
+ if isinstance(child, (ast.For, ast.While)):
220
+ has_loop = True
221
+ if depth >= 1:
222
+ has_nested_loop = True
223
+ _walk_loops(child, depth + 1)
224
+ else:
225
+ _walk_loops(child, depth)
226
+
227
+ _walk_loops(any_node, 0)
228
+
229
+ for node in ast.walk(any_node):
230
+ if isinstance(node, ast.Name):
231
+ if node.id in _NUMERIC_NAMES:
232
+ uses_numeric = True
233
+ if node.id in _IO_NET_NAMES:
234
+ has_io_net = True
235
+ if node.id in _ALREADY_ACCEL_NAMES:
236
+ already_accel = True
237
+ elif isinstance(node, ast.Attribute):
238
+ if node.attr in _NUMERIC_NAMES:
239
+ uses_numeric = True
240
+ if node.attr in _IO_NET_NAMES:
241
+ has_io_net = True
242
+ elif isinstance(node, ast.Subscript):
243
+ has_subscript = True
244
+ elif isinstance(node, ast.BinOp):
245
+ has_binop = True
246
+
247
+ if has_loop:
248
+ score += 25
249
+ reasons.append("contains loop")
250
+ if has_nested_loop:
251
+ score += 15
252
+ reasons.append("nested loop")
253
+ if uses_numeric:
254
+ score += 25
255
+ reasons.append("numeric/NumPy workload")
256
+ if has_subscript and has_binop:
257
+ score += 15
258
+ reasons.append("array/math operations")
259
+
260
+ if has_io_net:
261
+ score -= 60
262
+ reasons.append("I/O or network bound")
263
+ if has_serial_dep:
264
+ score -= 55
265
+ reasons.append("loop-carried serial dependency (not GPU-parallel)")
266
+ if already_accel:
267
+ score -= 50
268
+ reasons.append("already JIT/GPU accelerated")
269
+ if not is_top_level:
270
+ score -= 20
271
+ reasons.append("not top-level function")
272
+
273
+ return is_top_level, max(0, min(80, score)), reasons
274
+
275
+
276
+ def scan_command(
277
+ cmd: list[str],
278
+ *,
279
+ project_root: Path | None = None,
280
+ top_k: int = 8,
281
+ ) -> ScanResult:
282
+ """Run a Python command under cProfile and rank GPU offload candidates."""
283
+ cleaned = list(cmd)
284
+ if cleaned and cleaned[0] == "--":
285
+ cleaned = cleaned[1:]
286
+ if not cleaned:
287
+ raise ValueError("Provide a Python command after `--` (e.g. `gpu-shift scan -- python demo.py`).")
288
+
289
+ first = Path(cleaned[0]).name.lower()
290
+ if first in {"python", "python3", "python.exe", "python3.exe", "py", "py.exe"}:
291
+ cleaned = cleaned[1:]
292
+ if not cleaned:
293
+ raise ValueError("No script or -m module found after python executable.")
294
+
295
+ root = (project_root or Path.cwd()).resolve()
296
+
297
+ with tempfile.TemporaryDirectory(prefix="gpu_shift_scan_") as tmp_dir:
298
+ out_json = Path(tmp_dir) / "scan.json"
299
+ scanner_cmd = [
300
+ sys.executable,
301
+ "-m",
302
+ "gpu_shift._scanner",
303
+ "--out-json",
304
+ str(out_json),
305
+ "--",
306
+ *cleaned,
307
+ ]
308
+ env = os.environ.copy()
309
+ env["GPU_SHIFT_MODE"] = "cpu"
310
+ proc = subprocess.run(
311
+ scanner_cmd,
312
+ env=env,
313
+ capture_output=True,
314
+ text=True,
315
+ check=False,
316
+ )
317
+ if proc.returncode != 0:
318
+ raise RuntimeError(
319
+ f"Scan command failed (exit {proc.returncode}).\n"
320
+ f"STDOUT:\n{proc.stdout}\nSTDERR:\n{proc.stderr}"
321
+ )
322
+ raw_stats: list[dict[str, Any]] = json.loads(out_json.read_text(encoding="utf-8"))
323
+
324
+ total_ms = max((float(s["cumtime_ms"]) for s in raw_stats), default=0.0)
325
+ candidates: list[ScanCandidate] = []
326
+
327
+ for stat in raw_stats:
328
+ fn_name = str(stat["func_name"])
329
+ if fn_name.startswith("<") or fn_name in {"main", "_run_target"}:
330
+ continue
331
+ file_path = Path(str(stat["filename"]))
332
+ if not _is_user_file(file_path, root):
333
+ continue
334
+
335
+ resolved = file_path.resolve()
336
+ try:
337
+ rel_posix = resolved.relative_to(root).as_posix()
338
+ except ValueError:
339
+ rel_posix = resolved.name
340
+
341
+ cum_ms = float(stat["cumtime_ms"])
342
+ tot_ms = float(stat["tottime_ms"])
343
+ share = (cum_ms / total_ms * 100.0) if total_ms > 0 else 0.0
344
+
345
+ is_top_level, ast_score, reasons = _analyze_function_ast(
346
+ resolved, fn_name, int(stat["lineno"])
347
+ )
348
+ # Don't boost I/O-bound or serial-loop functions merely for slow wall time
349
+ non_gpu = (
350
+ "I/O or network bound" in reasons
351
+ or "loop-carried serial dependency (not GPU-parallel)" in reasons
352
+ )
353
+ time_bonus = 0 if non_gpu else int(min(20.0, share * 0.5))
354
+ final_score = max(0, min(100, ast_score + time_bonus))
355
+ stageable = is_top_level and not non_gpu
356
+
357
+ candidates.append(
358
+ ScanCandidate(
359
+ source_file=resolved,
360
+ source_rel=rel_posix,
361
+ function_name=fn_name,
362
+ lineno=int(stat["lineno"]),
363
+ ncalls=int(stat["ncalls"]),
364
+ tottime_ms=tot_ms,
365
+ cumtime_ms=cum_ms,
366
+ time_share_pct=share,
367
+ score=final_score,
368
+ stageable=stageable,
369
+ reasons=tuple(reasons),
370
+ suggested_command=f"gpu-shift stage {rel_posix} --fn {fn_name}",
371
+ )
372
+ )
373
+
374
+ candidates.sort(key=lambda c: (c.score, c.cumtime_ms), reverse=True)
375
+ return ScanResult(
376
+ command=tuple(cleaned),
377
+ project_root=root,
378
+ total_ms=total_ms,
379
+ candidates=tuple(candidates[:top_k]),
380
+ )
gpu_shift/setup.py ADDED
@@ -0,0 +1,245 @@
1
+ """Register gpu-shift MCP server and SKILL.md with installed coding agents."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import shutil
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ SUPPORTED_AGENTS = ("claude", "cursor", "gemini", "codex", "opencode")
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class AgentSetupAction:
16
+ """One agent configuration action performed (or planned in dry-run)."""
17
+
18
+ agent: str
19
+ detected: bool
20
+ mcp_config_path: Path | None
21
+ skill_path: Path | None
22
+ backup_path: Path | None
23
+ status: str
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class SetupResult:
28
+ """Summary of `gpu-shift setup` / `gpu-shift setup --remove`."""
29
+
30
+ remove: bool
31
+ dry_run: bool
32
+ actions: tuple[AgentSetupAction, ...]
33
+
34
+
35
+ def load_skill_markdown() -> str:
36
+ """Load the bundled SKILL.md content."""
37
+ bundled = Path(__file__).resolve().parent / "skill_data" / "SKILL.md"
38
+ if bundled.is_file():
39
+ return bundled.read_text(encoding="utf-8")
40
+ repo_skill = Path(__file__).resolve().parent.parent.parent / "skills" / "gpu-shift" / "SKILL.md"
41
+ if repo_skill.is_file():
42
+ return repo_skill.read_text(encoding="utf-8")
43
+ raise FileNotFoundError("Bundled SKILL.md not found.")
44
+
45
+
46
+ def _backup_if_needed(path: Path, *, backup: bool, dry_run: bool) -> Path | None:
47
+ if not backup or not path.is_file():
48
+ return None
49
+ bak = path.with_name(path.name + ".gpu-shift.bak")
50
+ if not bak.exists() and not dry_run:
51
+ shutil.copy2(path, bak)
52
+ return bak
53
+
54
+
55
+ def _update_json_mcp(
56
+ config_path: Path,
57
+ *,
58
+ key_path: tuple[str, ...],
59
+ entry: dict[str, Any],
60
+ remove: bool,
61
+ backup: bool,
62
+ dry_run: bool,
63
+ ) -> tuple[bool, Path | None]:
64
+ existed = config_path.is_file()
65
+ if existed:
66
+ data = json.loads(config_path.read_text(encoding="utf-8"))
67
+ if not isinstance(data, dict):
68
+ raise ValueError(f"Expected JSON object in {config_path}")
69
+ else:
70
+ if remove:
71
+ return False, None
72
+ data = {}
73
+
74
+ bak = _backup_if_needed(config_path, backup=backup, dry_run=dry_run)
75
+
76
+ cursor: dict[str, Any] = data
77
+ for key in key_path:
78
+ nxt = cursor.get(key)
79
+ if not isinstance(nxt, dict):
80
+ if remove:
81
+ return False, bak
82
+ nxt = {}
83
+ cursor[key] = nxt
84
+ cursor = nxt
85
+
86
+ if remove:
87
+ if "gpu-shift" not in cursor:
88
+ return False, bak
89
+ del cursor["gpu-shift"]
90
+ else:
91
+ cursor["gpu-shift"] = entry
92
+
93
+ if not dry_run:
94
+ config_path.parent.mkdir(parents=True, exist_ok=True)
95
+ config_path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
96
+ return True, bak
97
+
98
+
99
+ def _install_or_remove_skill(
100
+ skill_path: Path,
101
+ *,
102
+ skill_text: str,
103
+ remove: bool,
104
+ dry_run: bool,
105
+ ) -> bool:
106
+ if remove:
107
+ if not skill_path.is_file():
108
+ return False
109
+ if not dry_run:
110
+ skill_path.unlink()
111
+ parent = skill_path.parent
112
+ if parent.is_dir() and not any(parent.iterdir()):
113
+ parent.rmdir()
114
+ return True
115
+
116
+ if not dry_run:
117
+ skill_path.parent.mkdir(parents=True, exist_ok=True)
118
+ skill_path.write_text(skill_text, encoding="utf-8")
119
+ return True
120
+
121
+
122
+ def setup_agents(
123
+ *,
124
+ home_dir: Path | None = None,
125
+ agents: list[str] | None = None,
126
+ remove: bool = False,
127
+ dry_run: bool = False,
128
+ backup: bool = True,
129
+ ) -> SetupResult:
130
+ """Register (or remove) gpu-shift MCP server and SKILL.md for coding agents."""
131
+ home = (home_dir or Path.home()).resolve()
132
+ skill_text = load_skill_markdown()
133
+ selected = tuple(agents) if agents else SUPPORTED_AGENTS
134
+ explicit = agents is not None
135
+ actions: list[AgentSetupAction] = []
136
+
137
+ std_mcp_entry = {"command": "gpu-shift", "args": ["mcp"]}
138
+ opencode_mcp_entry = {"type": "local", "command": ["gpu-shift", "mcp"]}
139
+
140
+ for agent in selected:
141
+ if agent == "claude":
142
+ mcp_path = home / ".claude.json"
143
+ skill_path = home / ".claude" / "skills" / "gpu-shift" / "SKILL.md"
144
+ detected = mcp_path.is_file() or (home / ".claude").is_dir()
145
+ if not detected and not explicit:
146
+ actions.append(AgentSetupAction(agent, False, None, None, None, "skipped (not installed)"))
147
+ continue
148
+ changed_mcp, bak = _update_json_mcp(
149
+ mcp_path,
150
+ key_path=("mcpServers",),
151
+ entry=std_mcp_entry,
152
+ remove=remove,
153
+ backup=backup,
154
+ dry_run=dry_run,
155
+ )
156
+ changed_skill = _install_or_remove_skill(
157
+ skill_path, skill_text=skill_text, remove=remove, dry_run=dry_run
158
+ )
159
+ status = _format_status(remove, dry_run, changed_mcp or changed_skill)
160
+ actions.append(AgentSetupAction(agent, detected, mcp_path, skill_path, bak, status))
161
+
162
+ elif agent == "cursor":
163
+ mcp_path = home / ".cursor" / "mcp.json"
164
+ detected = (home / ".cursor").is_dir()
165
+ if not detected and not explicit:
166
+ actions.append(AgentSetupAction(agent, False, None, None, None, "skipped (not installed)"))
167
+ continue
168
+ changed_mcp, bak = _update_json_mcp(
169
+ mcp_path,
170
+ key_path=("mcpServers",),
171
+ entry=std_mcp_entry,
172
+ remove=remove,
173
+ backup=backup,
174
+ dry_run=dry_run,
175
+ )
176
+ status = _format_status(remove, dry_run, changed_mcp)
177
+ actions.append(AgentSetupAction(agent, detected, mcp_path, None, bak, status))
178
+
179
+ elif agent == "gemini":
180
+ mcp_path = home / ".gemini" / "settings.json"
181
+ skill_path = home / ".gemini" / "antigravity" / "skills" / "gpu-shift" / "SKILL.md"
182
+ detected = (home / ".gemini").is_dir()
183
+ if not detected and not explicit:
184
+ actions.append(AgentSetupAction(agent, False, None, None, None, "skipped (not installed)"))
185
+ continue
186
+ changed_mcp, bak = _update_json_mcp(
187
+ mcp_path,
188
+ key_path=("mcpServers",),
189
+ entry=std_mcp_entry,
190
+ remove=remove,
191
+ backup=backup,
192
+ dry_run=dry_run,
193
+ )
194
+ changed_skill = _install_or_remove_skill(
195
+ skill_path, skill_text=skill_text, remove=remove, dry_run=dry_run
196
+ )
197
+ status = _format_status(remove, dry_run, changed_mcp or changed_skill)
198
+ actions.append(AgentSetupAction(agent, detected, mcp_path, skill_path, bak, status))
199
+
200
+ elif agent == "codex":
201
+ skill_path = home / ".codex" / "skills" / "gpu-shift" / "SKILL.md"
202
+ detected = (home / ".codex").is_dir()
203
+ if not detected and not explicit:
204
+ actions.append(AgentSetupAction(agent, False, None, None, None, "skipped (not installed)"))
205
+ continue
206
+ changed_skill = _install_or_remove_skill(
207
+ skill_path, skill_text=skill_text, remove=remove, dry_run=dry_run
208
+ )
209
+ status = _format_status(remove, dry_run, changed_skill)
210
+ actions.append(AgentSetupAction(agent, detected, None, skill_path, None, status))
211
+
212
+ elif agent == "opencode":
213
+ mcp_path = home / ".config" / "opencode" / "opencode.json"
214
+ skill_path = home / ".config" / "opencode" / "skills" / "gpu-shift" / "SKILL.md"
215
+ detected = (home / ".config" / "opencode").is_dir()
216
+ if not detected and not explicit:
217
+ actions.append(AgentSetupAction(agent, False, None, None, None, "skipped (not installed)"))
218
+ continue
219
+ changed_mcp, bak = _update_json_mcp(
220
+ mcp_path,
221
+ key_path=("mcp", "servers"),
222
+ entry=opencode_mcp_entry,
223
+ remove=remove,
224
+ backup=backup,
225
+ dry_run=dry_run,
226
+ )
227
+ changed_skill = _install_or_remove_skill(
228
+ skill_path, skill_text=skill_text, remove=remove, dry_run=dry_run
229
+ )
230
+ status = _format_status(remove, dry_run, changed_mcp or changed_skill)
231
+ actions.append(AgentSetupAction(agent, detected, mcp_path, skill_path, bak, status))
232
+ else:
233
+ raise ValueError(
234
+ f"Unsupported agent '{agent}'. Choose from: {', '.join(SUPPORTED_AGENTS)}"
235
+ )
236
+
237
+ return SetupResult(remove=remove, dry_run=dry_run, actions=tuple(actions))
238
+
239
+
240
+ def _format_status(remove: bool, dry_run: bool, changed: bool) -> str:
241
+ if not changed:
242
+ return "unchanged"
243
+ if dry_run:
244
+ return "would remove" if remove else "would install"
245
+ return "removed" if remove else "installed"
@@ -0,0 +1,56 @@
1
+ ---
2
+ name: gpu-shift
3
+ description: Shift slow Python/NumPy CPU loops to any GPU via WebGPU/WGSL with deterministic verification, native VRAM leak soaking, and transfer-inclusive crossover benchmarking. Use when asked to accelerate slow Python/NumPy code on GPU, scan CPU bottlenecks for GPU offload, or verify a WGSL compute port.
4
+ ---
5
+
6
+ # GPU Offloading with gpu-shift
7
+
8
+ `gpu-shift` gives you ground truth; you write the WGSL shader (`kernel.wgsl`) and thin wrapper (`port.py`). Move one hot numerical function at a time, and call a port done only when `check` passes.
9
+
10
+ Use the `gpu-shift` CLI or its MCP tools (`gpu_doctor`, `gpu_scan`, `gpu_stage`, `gpu_capture`, `gpu_diff`, `gpu_bench`, `gpu_check`, `gpu_enable`, `gpu_disable`, `gpu_report`).
11
+
12
+ ## Fast Path: `run`
13
+
14
+ When the user points at a slow Python command:
15
+
16
+ ```bash
17
+ gpu-shift run -- python app.py
18
+ # Read kernels/<fn>/TASK.md, implement kernel.wgsl + port.py, then re-run:
19
+ gpu-shift run -- python app.py
20
+ ```
21
+
22
+ The first run scans, stages, captures CPU ground truth + GPU edge cases, and pauses at `needs_port`. Once you implement `kernel.wgsl` and `port.py`, the second run verifies `diff`, runs `check` (including 15-dispatch native VRAM soak), benchmarks crossover `min_elements`, and enables the port only if GPU beats CPU.
23
+
24
+ ## Step-by-Step Loop
25
+
26
+ 1. **Check hardware:** `gpu-shift doctor`
27
+ 2. **Find the hot loop:** `gpu-shift scan -- python app.py`
28
+ - Skip I/O-bound, network-bound, or already JIT/GPU-accelerated functions.
29
+ 3. **Stage without editing original code:** `gpu-shift stage path/to/file.py --fn my_fn`
30
+ 4. **Capture ground truth + GPU traps:** `gpu-shift capture kernels/my_fn -- python app.py`
31
+ - Captures real inputs/outputs into `.npz` plus 7 synthetic edge cases (`1x1`, prime `17x13`, zeros, constant, negative/wide, non-contiguous view, `NaN`/`Inf`).
32
+ 5. **Write `kernel.wgsl` and `port.py`:**
33
+ - Use `ComputeKernel.from_file(...)`, `ceil_div(...)`, and `pack_uniforms(...)` from `gpu_shift.runtime` so every GPU buffer is destroyed in `finally`.
34
+ - Never edit the original `.py` file manually.
35
+ - Always guard thread indices against array bounds (`if (x >= params.width || y >= params.height) { return; }`).
36
+ - Handle 0-element arrays on CPU before calling `ComputeKernel.dispatch(...)`.
37
+ - Convert non-contiguous inputs via `np.ascontiguousarray(..., dtype=np.float32)`.
38
+ - Match WGSL uniform struct alignment (pad to 16-byte multiples; `pack_uniforms` pads automatically).
39
+ - Guard divisions against zero (`select`) for Metal/Vulkan/D3D12 portability, and chunk huge workloads so no single dispatch exceeds the 2-second Windows TDR limit.
40
+ - Do not rely on `v != v` to detect NaN in WGSL (finite-math compilers on Vulkan/SPIR-V can optimize it away); use `bitcast<u32>(v)` bitmasks (`(b & 0x7F800000u) == 0x7F800000u`) or guard non-finite inputs in `port.py`.
41
+ - Keep `workgroupBarrier()` in top-level uniform control flow (never inside an `if (...) { ... return; }` branch) for D3D12/WARP compatibility.
42
+ 6. **Verify parity:** `gpu-shift diff kernels/my_fn`
43
+ - Fix every mismatch until 100% of captured and edge cases pass.
44
+ 7. **Measure transfer-inclusive speed and crossover:** `gpu-shift bench kernels/my_fn`
45
+ - Updates `min_elements` in `manifest.json`. If CPU is faster at all tested sizes, report that honestly and do not force GPU.
46
+ 8. **Run release check:** `gpu-shift check kernels/my_fn`
47
+ - Checks file presence, source SHA-256 freshness, WGSL compilation, 100% diff pass, and 0 leaked GPU objects / 0 B VRAM growth across 15 dispatches.
48
+ 9. **Enable safely and generate PR report:**
49
+ - `gpu-shift enable kernels/my_fn` (reversible byte-for-byte with `gpu-shift disable kernels/my_fn`)
50
+ - `gpu-shift report kernels/my_fn` (writes `report/REPORT.md` and `report/card.svg`)
51
+
52
+ ## Runtime Safety Switches
53
+ - Default (`auto`): GPU for inputs >= `min_elements`, CPU below threshold or if no GPU is present.
54
+ - `GPU_SHIFT_MODE=cpu`: Force CPU.
55
+ - `GPU_SHIFT_MODE=shadow`: Run both, return CPU output, warn on numerical divergence.
56
+ - `GPU_SHIFT_MODE=gpu`: Force GPU.