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/runtime.py
ADDED
|
@@ -0,0 +1,592 @@
|
|
|
1
|
+
"""WebGPU compute kernel runner with fused single-submit dispatch, sessions, and VRAM tracking."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import gc
|
|
6
|
+
import struct
|
|
7
|
+
import threading
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any, Self
|
|
11
|
+
|
|
12
|
+
import numpy as np
|
|
13
|
+
import wgpu
|
|
14
|
+
|
|
15
|
+
from gpu_shift.device import get_device
|
|
16
|
+
|
|
17
|
+
_BUFFER_LOCK = threading.Lock()
|
|
18
|
+
_ACTIVE_BUFFERS = 0
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class GpuLimitError(ValueError):
|
|
22
|
+
"""Raised when a single dispatch exceeds WebGPU workgroup or buffer size limits."""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _check_device_limits(
|
|
26
|
+
device: Any,
|
|
27
|
+
gx: int,
|
|
28
|
+
gy: int,
|
|
29
|
+
gz: int,
|
|
30
|
+
storage_sizes: list[int],
|
|
31
|
+
uniform_sizes: list[int],
|
|
32
|
+
) -> None:
|
|
33
|
+
limits = getattr(device, "limits", None) or {}
|
|
34
|
+
max_wg = int(limits.get("max-compute-workgroups-per-dimension") or 65535)
|
|
35
|
+
if gx > max_wg or gy > max_wg or gz > max_wg:
|
|
36
|
+
raise GpuLimitError(
|
|
37
|
+
f"Workgroup count ({gx}, {gy}, {gz}) exceeds device limit "
|
|
38
|
+
f"max-compute-workgroups-per-dimension={max_wg}."
|
|
39
|
+
)
|
|
40
|
+
max_storage = int(limits.get("max-storage-buffer-binding-size") or 134_217_728)
|
|
41
|
+
for size in storage_sizes:
|
|
42
|
+
if size > max_storage:
|
|
43
|
+
raise GpuLimitError(
|
|
44
|
+
f"Storage buffer size ({size:,} B) exceeds device limit "
|
|
45
|
+
f"max-storage-buffer-binding-size={max_storage:,} B."
|
|
46
|
+
)
|
|
47
|
+
max_uniform = int(limits.get("max-uniform-buffer-binding-size") or 65_536)
|
|
48
|
+
for size in uniform_sizes:
|
|
49
|
+
if size > max_uniform:
|
|
50
|
+
raise GpuLimitError(
|
|
51
|
+
f"Uniform buffer size ({size:,} B) exceeds device limit "
|
|
52
|
+
f"max-uniform-buffer-binding-size={max_uniform:,} B."
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass(frozen=True)
|
|
57
|
+
class VramSnapshot:
|
|
58
|
+
"""Real GPU resource snapshot from wgpu.diagnostics.object_counts."""
|
|
59
|
+
|
|
60
|
+
kernel_active_buffers: int
|
|
61
|
+
wgpu_buffers: int
|
|
62
|
+
wgpu_textures: int
|
|
63
|
+
wgpu_bind_groups: int
|
|
64
|
+
wgpu_pipelines: int
|
|
65
|
+
wgpu_shaders: int
|
|
66
|
+
resource_mem_bytes: int
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def snapshot_vram(*, run_gc: bool = True) -> VramSnapshot:
|
|
70
|
+
"""Capture live GPU resource counts and VRAM bytes from wgpu-native."""
|
|
71
|
+
if run_gc:
|
|
72
|
+
gc.collect()
|
|
73
|
+
counts = wgpu.diagnostics.object_counts.get_dict()
|
|
74
|
+
return VramSnapshot(
|
|
75
|
+
kernel_active_buffers=active_buffer_count(),
|
|
76
|
+
wgpu_buffers=int(counts.get("Buffer", {}).get("count", 0)),
|
|
77
|
+
wgpu_textures=int(counts.get("Texture", {}).get("count", 0)),
|
|
78
|
+
wgpu_bind_groups=int(counts.get("BindGroup", {}).get("count", 0)),
|
|
79
|
+
wgpu_pipelines=int(counts.get("ComputePipeline", {}).get("count", 0)),
|
|
80
|
+
wgpu_shaders=int(counts.get("ShaderModule", {}).get("count", 0)),
|
|
81
|
+
resource_mem_bytes=int(counts.get("total", {}).get("resource_mem", 0)),
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def active_buffer_count() -> int:
|
|
86
|
+
"""Return the number of currently live GPU buffers allocated via ComputeKernel."""
|
|
87
|
+
with _BUFFER_LOCK:
|
|
88
|
+
return _ACTIVE_BUFFERS
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _track_alloc() -> None:
|
|
92
|
+
global _ACTIVE_BUFFERS
|
|
93
|
+
with _BUFFER_LOCK:
|
|
94
|
+
_ACTIVE_BUFFERS += 1
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _track_free() -> None:
|
|
98
|
+
global _ACTIVE_BUFFERS
|
|
99
|
+
with _BUFFER_LOCK:
|
|
100
|
+
_ACTIVE_BUFFERS = max(0, _ACTIVE_BUFFERS - 1)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def ceil_div(total: int, group_size: int) -> int:
|
|
104
|
+
"""Return ceil(total / group_size) for positive integers."""
|
|
105
|
+
if group_size <= 0:
|
|
106
|
+
raise ValueError("group_size must be positive")
|
|
107
|
+
if total <= 0:
|
|
108
|
+
return 0
|
|
109
|
+
return (total + group_size - 1) // group_size
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def pad_uniform_bytes(data: bytes) -> bytes:
|
|
113
|
+
"""Pad uniform buffer bytes to a non-empty multiple of 16 bytes (WebGPU rule)."""
|
|
114
|
+
if len(data) == 0:
|
|
115
|
+
return b"\x00" * 16
|
|
116
|
+
rem = len(data) % 16
|
|
117
|
+
if rem == 0:
|
|
118
|
+
return data
|
|
119
|
+
return data + (b"\x00" * (16 - rem))
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def pack_uniforms(fmt: str, *values: Any) -> bytes:
|
|
123
|
+
"""Pack scalar values with struct.pack (little-endian by default) and 16-byte pad."""
|
|
124
|
+
full_fmt = fmt if fmt.startswith(("<", ">", "=", "!", "@")) else f"<{fmt}"
|
|
125
|
+
return pad_uniform_bytes(struct.pack(full_fmt, *values))
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _align4(nbytes: int) -> int:
|
|
129
|
+
return (nbytes + 3) & ~3
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _read_staging_into_array(
|
|
133
|
+
staging_buf: Any,
|
|
134
|
+
nbytes: int,
|
|
135
|
+
shape: tuple[int, ...],
|
|
136
|
+
dtype: np.dtype[Any],
|
|
137
|
+
out: np.ndarray | None = None,
|
|
138
|
+
) -> np.ndarray:
|
|
139
|
+
"""Map staging buffer, copy directly into an aligned NumPy array without bytearray overhead."""
|
|
140
|
+
try:
|
|
141
|
+
staging_buf.map_sync("READ_NOSYNC")
|
|
142
|
+
except (TypeError, ValueError):
|
|
143
|
+
staging_buf.map_sync(wgpu.MapMode.READ)
|
|
144
|
+
try:
|
|
145
|
+
mv = staging_buf.read_mapped(0, nbytes, copy=False)
|
|
146
|
+
try:
|
|
147
|
+
src_arr = np.frombuffer(mv, dtype=dtype).reshape(shape)
|
|
148
|
+
if out is not None:
|
|
149
|
+
np.copyto(out, src_arr)
|
|
150
|
+
return out
|
|
151
|
+
dst_arr = np.empty(shape, dtype=dtype)
|
|
152
|
+
np.copyto(dst_arr, src_arr)
|
|
153
|
+
return dst_arr
|
|
154
|
+
finally:
|
|
155
|
+
del mv
|
|
156
|
+
finally:
|
|
157
|
+
staging_buf.unmap()
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def validate_wgsl(
|
|
161
|
+
wgsl_code: str,
|
|
162
|
+
entry_point: str = "main",
|
|
163
|
+
power_preference: str = "high-performance",
|
|
164
|
+
) -> tuple[bool, str | None]:
|
|
165
|
+
"""Compile a WGSL compute shader and pipeline to verify validity."""
|
|
166
|
+
try:
|
|
167
|
+
_, device = get_device(power_preference=power_preference)
|
|
168
|
+
shader = device.create_shader_module(code=wgsl_code)
|
|
169
|
+
device.create_compute_pipeline(
|
|
170
|
+
layout="auto",
|
|
171
|
+
compute={"module": shader, "entry_point": entry_point},
|
|
172
|
+
)
|
|
173
|
+
return True, None
|
|
174
|
+
except Exception as exc: # noqa: BLE001
|
|
175
|
+
return False, f"{type(exc).__name__}: {exc}"
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
class ComputeSession:
|
|
179
|
+
"""Reusable GPU buffer & BindGroup workspace for multi-frame / batch loops.
|
|
180
|
+
|
|
181
|
+
Use via `with kernel.session() as sess:`. Buffers and bind groups are reused
|
|
182
|
+
across dispatches of identical byte sizes and deterministically destroyed on exit
|
|
183
|
+
so 0 B of VRAM remain resident afterwards.
|
|
184
|
+
"""
|
|
185
|
+
|
|
186
|
+
def __init__(self, kernel: ComputeKernel) -> None:
|
|
187
|
+
self._kernel = kernel
|
|
188
|
+
self._lock = threading.Lock()
|
|
189
|
+
self._layout_key: tuple[tuple[str, int, int], ...] | None = None
|
|
190
|
+
self._input_bufs: dict[int, Any] = {}
|
|
191
|
+
self._output_bufs: dict[int, Any] = {}
|
|
192
|
+
self._staging_bufs: dict[int, Any] = {}
|
|
193
|
+
self._uniform_bufs: dict[int, Any] = {}
|
|
194
|
+
self._bind_group: Any | None = None
|
|
195
|
+
self._closed = False
|
|
196
|
+
|
|
197
|
+
def __enter__(self) -> Self:
|
|
198
|
+
return self
|
|
199
|
+
|
|
200
|
+
def __exit__(self, _exc_type: object, _exc: object, _tb: object) -> None:
|
|
201
|
+
self.close()
|
|
202
|
+
|
|
203
|
+
def _release_buffers(self) -> None:
|
|
204
|
+
all_bufs = [
|
|
205
|
+
*self._input_bufs.values(),
|
|
206
|
+
*self._output_bufs.values(),
|
|
207
|
+
*self._staging_bufs.values(),
|
|
208
|
+
*self._uniform_bufs.values(),
|
|
209
|
+
]
|
|
210
|
+
self._input_bufs.clear()
|
|
211
|
+
self._output_bufs.clear()
|
|
212
|
+
self._staging_bufs.clear()
|
|
213
|
+
self._uniform_bufs.clear()
|
|
214
|
+
self._bind_group = None
|
|
215
|
+
self._layout_key = None
|
|
216
|
+
for buf in all_bufs:
|
|
217
|
+
try:
|
|
218
|
+
buf.destroy()
|
|
219
|
+
finally:
|
|
220
|
+
_track_free()
|
|
221
|
+
|
|
222
|
+
def close(self) -> None:
|
|
223
|
+
"""Destroy every GPU buffer held by this session immediately."""
|
|
224
|
+
with self._lock:
|
|
225
|
+
if not self._closed:
|
|
226
|
+
self._closed = True
|
|
227
|
+
self._release_buffers()
|
|
228
|
+
|
|
229
|
+
def dispatch(
|
|
230
|
+
self,
|
|
231
|
+
*,
|
|
232
|
+
inputs: dict[int, np.ndarray],
|
|
233
|
+
outputs: dict[int, tuple[tuple[int, ...], Any]],
|
|
234
|
+
workgroups: int | tuple[int, int, int],
|
|
235
|
+
uniforms: dict[int, bytes | bytearray | np.ndarray] | None = None,
|
|
236
|
+
out_arrays: dict[int, np.ndarray] | None = None,
|
|
237
|
+
) -> dict[int, np.ndarray]:
|
|
238
|
+
"""Run one compute pass reusing GPU buffers and BindGroup when sizes match."""
|
|
239
|
+
with self._lock:
|
|
240
|
+
return self._dispatch_locked(
|
|
241
|
+
inputs=inputs,
|
|
242
|
+
outputs=outputs,
|
|
243
|
+
workgroups=workgroups,
|
|
244
|
+
uniforms=uniforms,
|
|
245
|
+
out_arrays=out_arrays,
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
def _dispatch_locked(
|
|
249
|
+
self,
|
|
250
|
+
*,
|
|
251
|
+
inputs: dict[int, np.ndarray],
|
|
252
|
+
outputs: dict[int, tuple[tuple[int, ...], Any]],
|
|
253
|
+
workgroups: int | tuple[int, int, int],
|
|
254
|
+
uniforms: dict[int, bytes | bytearray | np.ndarray] | None = None,
|
|
255
|
+
out_arrays: dict[int, np.ndarray] | None = None,
|
|
256
|
+
) -> dict[int, np.ndarray]:
|
|
257
|
+
if self._closed:
|
|
258
|
+
raise RuntimeError("Cannot dispatch on a closed ComputeSession.")
|
|
259
|
+
|
|
260
|
+
if isinstance(workgroups, int):
|
|
261
|
+
gx, gy, gz = workgroups, 1, 1
|
|
262
|
+
else:
|
|
263
|
+
gx, gy, gz = workgroups
|
|
264
|
+
|
|
265
|
+
if gx <= 0 or gy <= 0 or gz <= 0:
|
|
266
|
+
return {
|
|
267
|
+
binding: np.empty(shape, dtype=dtype)
|
|
268
|
+
for binding, (shape, dtype) in outputs.items()
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
device, pipeline, bind_group_layout = self._kernel._ensure_pipeline()
|
|
272
|
+
|
|
273
|
+
contig_inputs: dict[int, np.ndarray] = {}
|
|
274
|
+
layout_parts: list[tuple[str, int, int]] = []
|
|
275
|
+
for binding in sorted(inputs):
|
|
276
|
+
contig = np.ascontiguousarray(inputs[binding])
|
|
277
|
+
if contig.nbytes == 0:
|
|
278
|
+
raise ValueError(
|
|
279
|
+
f"Input buffer at binding {binding} is empty (0 bytes); "
|
|
280
|
+
"handle empty arrays on CPU before dispatch."
|
|
281
|
+
)
|
|
282
|
+
contig_inputs[binding] = contig
|
|
283
|
+
layout_parts.append(("in", binding, _align4(contig.nbytes)))
|
|
284
|
+
|
|
285
|
+
out_meta: dict[int, tuple[tuple[int, ...], np.dtype[Any], int, int]] = {}
|
|
286
|
+
for binding in sorted(outputs):
|
|
287
|
+
shape, dtype_like = outputs[binding]
|
|
288
|
+
dt = np.dtype(dtype_like)
|
|
289
|
+
nbytes = int(np.prod(shape, dtype=np.int64)) * dt.itemsize
|
|
290
|
+
if nbytes == 0:
|
|
291
|
+
raise ValueError(
|
|
292
|
+
f"Output buffer at binding {binding} is empty (0 bytes); "
|
|
293
|
+
"handle empty outputs on CPU before dispatch."
|
|
294
|
+
)
|
|
295
|
+
aligned = _align4(nbytes)
|
|
296
|
+
out_meta[binding] = (tuple(shape), dt, nbytes, aligned)
|
|
297
|
+
layout_parts.append(("out", binding, aligned))
|
|
298
|
+
|
|
299
|
+
padded_uniforms: dict[int, bytes] = {}
|
|
300
|
+
if uniforms:
|
|
301
|
+
for binding in sorted(uniforms):
|
|
302
|
+
udata = uniforms[binding]
|
|
303
|
+
raw_bytes = (
|
|
304
|
+
np.ascontiguousarray(udata).tobytes()
|
|
305
|
+
if isinstance(udata, np.ndarray)
|
|
306
|
+
else bytes(udata)
|
|
307
|
+
)
|
|
308
|
+
padded = pad_uniform_bytes(raw_bytes)
|
|
309
|
+
padded_uniforms[binding] = padded
|
|
310
|
+
layout_parts.append(("uni", binding, len(padded)))
|
|
311
|
+
|
|
312
|
+
storage_sizes = [_align4(c.nbytes) for c in contig_inputs.values()] + [
|
|
313
|
+
meta[3] for meta in out_meta.values()
|
|
314
|
+
]
|
|
315
|
+
uniform_sizes = [len(p) for p in padded_uniforms.values()]
|
|
316
|
+
_check_device_limits(device, gx, gy, gz, storage_sizes, uniform_sizes)
|
|
317
|
+
|
|
318
|
+
key = tuple(layout_parts)
|
|
319
|
+
if key != self._layout_key:
|
|
320
|
+
self._release_buffers()
|
|
321
|
+
try:
|
|
322
|
+
bind_entries: list[dict[str, Any]] = []
|
|
323
|
+
for binding, contig in contig_inputs.items():
|
|
324
|
+
buf = device.create_buffer(
|
|
325
|
+
size=_align4(contig.nbytes),
|
|
326
|
+
usage=wgpu.BufferUsage.STORAGE | wgpu.BufferUsage.COPY_DST,
|
|
327
|
+
)
|
|
328
|
+
self._input_bufs[binding] = buf
|
|
329
|
+
_track_alloc()
|
|
330
|
+
bind_entries.append({"binding": binding, "resource": {"buffer": buf}})
|
|
331
|
+
|
|
332
|
+
for binding, (_shape, _dt, _nbytes, aligned) in out_meta.items():
|
|
333
|
+
out_buf = device.create_buffer(
|
|
334
|
+
size=aligned,
|
|
335
|
+
usage=wgpu.BufferUsage.STORAGE | wgpu.BufferUsage.COPY_SRC,
|
|
336
|
+
)
|
|
337
|
+
self._output_bufs[binding] = out_buf
|
|
338
|
+
_track_alloc()
|
|
339
|
+
|
|
340
|
+
stg_buf = device.create_buffer(
|
|
341
|
+
size=aligned,
|
|
342
|
+
usage=wgpu.BufferUsage.COPY_DST | wgpu.BufferUsage.MAP_READ,
|
|
343
|
+
)
|
|
344
|
+
self._staging_bufs[binding] = stg_buf
|
|
345
|
+
_track_alloc()
|
|
346
|
+
bind_entries.append({"binding": binding, "resource": {"buffer": out_buf}})
|
|
347
|
+
|
|
348
|
+
for binding, padded in padded_uniforms.items():
|
|
349
|
+
u_buf = device.create_buffer(
|
|
350
|
+
size=len(padded),
|
|
351
|
+
usage=wgpu.BufferUsage.UNIFORM | wgpu.BufferUsage.COPY_DST,
|
|
352
|
+
)
|
|
353
|
+
self._uniform_bufs[binding] = u_buf
|
|
354
|
+
_track_alloc()
|
|
355
|
+
bind_entries.append({"binding": binding, "resource": {"buffer": u_buf}})
|
|
356
|
+
|
|
357
|
+
bind_entries.sort(key=lambda entry: entry["binding"])
|
|
358
|
+
self._bind_group = device.create_bind_group(
|
|
359
|
+
layout=bind_group_layout,
|
|
360
|
+
entries=bind_entries,
|
|
361
|
+
)
|
|
362
|
+
self._layout_key = key
|
|
363
|
+
except Exception:
|
|
364
|
+
self._release_buffers()
|
|
365
|
+
raise
|
|
366
|
+
|
|
367
|
+
for binding, contig in contig_inputs.items():
|
|
368
|
+
device.queue.write_buffer(self._input_bufs[binding], 0, contig)
|
|
369
|
+
for binding, padded in padded_uniforms.items():
|
|
370
|
+
device.queue.write_buffer(self._uniform_bufs[binding], 0, padded)
|
|
371
|
+
|
|
372
|
+
encoder = device.create_command_encoder()
|
|
373
|
+
compute_pass = encoder.begin_compute_pass()
|
|
374
|
+
compute_pass.set_pipeline(pipeline)
|
|
375
|
+
compute_pass.set_bind_group(0, self._bind_group)
|
|
376
|
+
compute_pass.dispatch_workgroups(gx, gy, gz)
|
|
377
|
+
compute_pass.end()
|
|
378
|
+
|
|
379
|
+
for binding, (_shape, _dt, _nbytes, aligned) in out_meta.items():
|
|
380
|
+
encoder.copy_buffer_to_buffer(
|
|
381
|
+
self._output_bufs[binding], 0, self._staging_bufs[binding], 0, aligned
|
|
382
|
+
)
|
|
383
|
+
|
|
384
|
+
device.queue.submit([encoder.finish()])
|
|
385
|
+
|
|
386
|
+
results: dict[int, np.ndarray] = {}
|
|
387
|
+
for binding, (shape, dt, nbytes, _aligned) in out_meta.items():
|
|
388
|
+
target_out = out_arrays.get(binding) if out_arrays else None
|
|
389
|
+
results[binding] = _read_staging_into_array(
|
|
390
|
+
self._staging_bufs[binding], nbytes, shape, dt, out=target_out
|
|
391
|
+
)
|
|
392
|
+
return results
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
class ComputeKernel:
|
|
396
|
+
"""Reusable WebGPU compute shader wrapper with fused single-submit dispatch and zero leaks."""
|
|
397
|
+
|
|
398
|
+
def __init__(
|
|
399
|
+
self,
|
|
400
|
+
wgsl_code: str,
|
|
401
|
+
entry_point: str = "main",
|
|
402
|
+
power_preference: str = "high-performance",
|
|
403
|
+
) -> None:
|
|
404
|
+
self.wgsl_code = wgsl_code
|
|
405
|
+
self.entry_point = entry_point
|
|
406
|
+
self.power_preference = power_preference
|
|
407
|
+
self._lock = threading.Lock()
|
|
408
|
+
self._device: Any | None = None
|
|
409
|
+
self._pipeline: Any | None = None
|
|
410
|
+
self._bind_group_layout: Any | None = None
|
|
411
|
+
|
|
412
|
+
@classmethod
|
|
413
|
+
def from_file(
|
|
414
|
+
cls,
|
|
415
|
+
wgsl_path: str | Path,
|
|
416
|
+
entry_point: str = "main",
|
|
417
|
+
power_preference: str = "high-performance",
|
|
418
|
+
) -> ComputeKernel:
|
|
419
|
+
path = Path(wgsl_path)
|
|
420
|
+
code = path.read_text(encoding="utf-8")
|
|
421
|
+
return cls(code, entry_point=entry_point, power_preference=power_preference)
|
|
422
|
+
|
|
423
|
+
def session(self) -> ComputeSession:
|
|
424
|
+
"""Create a context-managed ComputeSession that reuses buffers across tight loops."""
|
|
425
|
+
return ComputeSession(self)
|
|
426
|
+
|
|
427
|
+
def _ensure_pipeline(self) -> tuple[Any, Any, Any]:
|
|
428
|
+
with self._lock:
|
|
429
|
+
if (
|
|
430
|
+
self._device is None
|
|
431
|
+
or self._pipeline is None
|
|
432
|
+
or self._bind_group_layout is None
|
|
433
|
+
):
|
|
434
|
+
_, device = get_device(power_preference=self.power_preference)
|
|
435
|
+
shader = device.create_shader_module(code=self.wgsl_code)
|
|
436
|
+
pipeline = device.create_compute_pipeline(
|
|
437
|
+
layout="auto",
|
|
438
|
+
compute={"module": shader, "entry_point": self.entry_point},
|
|
439
|
+
)
|
|
440
|
+
self._device = device
|
|
441
|
+
self._pipeline = pipeline
|
|
442
|
+
self._bind_group_layout = pipeline.get_bind_group_layout(0)
|
|
443
|
+
return self._device, self._pipeline, self._bind_group_layout
|
|
444
|
+
|
|
445
|
+
def dispatch(
|
|
446
|
+
self,
|
|
447
|
+
*,
|
|
448
|
+
inputs: dict[int, np.ndarray],
|
|
449
|
+
outputs: dict[int, tuple[tuple[int, ...], Any]],
|
|
450
|
+
workgroups: int | tuple[int, int, int],
|
|
451
|
+
uniforms: dict[int, bytes | bytearray | np.ndarray] | None = None,
|
|
452
|
+
out_arrays: dict[int, np.ndarray] | None = None,
|
|
453
|
+
) -> dict[int, np.ndarray]:
|
|
454
|
+
"""Upload inputs, run compute + copy in one queue submit, read outputs, destroy all buffers.
|
|
455
|
+
|
|
456
|
+
Args:
|
|
457
|
+
inputs: Mapping of WGSL @binding(i) -> read-only NumPy storage array.
|
|
458
|
+
outputs: Mapping of WGSL @binding(i) -> (shape, dtype) for read_write output.
|
|
459
|
+
workgroups: 1D count or (gx, gy, gz) dispatch tuple.
|
|
460
|
+
uniforms: Optional mapping of WGSL @binding(i) -> bytes or NumPy array.
|
|
461
|
+
out_arrays: Optional pre-allocated host NumPy output arrays to copy into.
|
|
462
|
+
"""
|
|
463
|
+
if isinstance(workgroups, int):
|
|
464
|
+
gx, gy, gz = workgroups, 1, 1
|
|
465
|
+
else:
|
|
466
|
+
gx, gy, gz = workgroups
|
|
467
|
+
|
|
468
|
+
if gx <= 0 or gy <= 0 or gz <= 0:
|
|
469
|
+
return {
|
|
470
|
+
binding: np.empty(shape, dtype=dtype)
|
|
471
|
+
for binding, (shape, dtype) in outputs.items()
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
device, pipeline, bind_group_layout = self._ensure_pipeline()
|
|
475
|
+
|
|
476
|
+
# Pre-validate inputs, outputs, uniforms, and device limits before allocating VRAM
|
|
477
|
+
contig_inputs: dict[int, np.ndarray] = {}
|
|
478
|
+
storage_sizes: list[int] = []
|
|
479
|
+
for binding, arr in inputs.items():
|
|
480
|
+
contig = np.ascontiguousarray(arr)
|
|
481
|
+
if contig.nbytes == 0:
|
|
482
|
+
raise ValueError(
|
|
483
|
+
f"Input buffer at binding {binding} is empty (0 bytes); "
|
|
484
|
+
"handle empty arrays on CPU before dispatch."
|
|
485
|
+
)
|
|
486
|
+
contig_inputs[binding] = contig
|
|
487
|
+
storage_sizes.append(_align4(contig.nbytes))
|
|
488
|
+
|
|
489
|
+
out_meta: dict[int, tuple[tuple[int, ...], np.dtype[Any], int, int]] = {}
|
|
490
|
+
for binding, (shape, dtype_like) in outputs.items():
|
|
491
|
+
dt = np.dtype(dtype_like)
|
|
492
|
+
nbytes = int(np.prod(shape, dtype=np.int64)) * dt.itemsize
|
|
493
|
+
if nbytes == 0:
|
|
494
|
+
raise ValueError(
|
|
495
|
+
f"Output buffer at binding {binding} is empty (0 bytes); "
|
|
496
|
+
"handle empty outputs on CPU before dispatch."
|
|
497
|
+
)
|
|
498
|
+
aligned = _align4(nbytes)
|
|
499
|
+
out_meta[binding] = (tuple(shape), dt, nbytes, aligned)
|
|
500
|
+
storage_sizes.append(aligned)
|
|
501
|
+
|
|
502
|
+
padded_uniforms: dict[int, bytes] = {}
|
|
503
|
+
uniform_sizes: list[int] = []
|
|
504
|
+
if uniforms:
|
|
505
|
+
for binding, udata in uniforms.items():
|
|
506
|
+
raw_bytes = (
|
|
507
|
+
np.ascontiguousarray(udata).tobytes()
|
|
508
|
+
if isinstance(udata, np.ndarray)
|
|
509
|
+
else bytes(udata)
|
|
510
|
+
)
|
|
511
|
+
padded = pad_uniform_bytes(raw_bytes)
|
|
512
|
+
padded_uniforms[binding] = padded
|
|
513
|
+
uniform_sizes.append(len(padded))
|
|
514
|
+
|
|
515
|
+
_check_device_limits(device, gx, gy, gz, storage_sizes, uniform_sizes)
|
|
516
|
+
|
|
517
|
+
allocated: list[Any] = []
|
|
518
|
+
bind_entries: list[dict[str, Any]] = []
|
|
519
|
+
out_specs: dict[int, tuple[Any, Any, tuple[int, ...], np.dtype[Any], int, int]] = {}
|
|
520
|
+
|
|
521
|
+
try:
|
|
522
|
+
# Input read-only storage buffers
|
|
523
|
+
for binding, contig in contig_inputs.items():
|
|
524
|
+
buf = device.create_buffer_with_data(
|
|
525
|
+
data=contig,
|
|
526
|
+
usage=wgpu.BufferUsage.STORAGE,
|
|
527
|
+
)
|
|
528
|
+
allocated.append(buf)
|
|
529
|
+
_track_alloc()
|
|
530
|
+
bind_entries.append({"binding": binding, "resource": {"buffer": buf}})
|
|
531
|
+
|
|
532
|
+
# Output read_write storage buffers + fused MAP_READ staging buffers
|
|
533
|
+
for binding, (shape, dt, nbytes, aligned) in out_meta.items():
|
|
534
|
+
buf = device.create_buffer(
|
|
535
|
+
size=aligned,
|
|
536
|
+
usage=wgpu.BufferUsage.STORAGE | wgpu.BufferUsage.COPY_SRC,
|
|
537
|
+
)
|
|
538
|
+
allocated.append(buf)
|
|
539
|
+
_track_alloc()
|
|
540
|
+
|
|
541
|
+
stg = device.create_buffer(
|
|
542
|
+
size=aligned,
|
|
543
|
+
usage=wgpu.BufferUsage.COPY_DST | wgpu.BufferUsage.MAP_READ,
|
|
544
|
+
)
|
|
545
|
+
allocated.append(stg)
|
|
546
|
+
_track_alloc()
|
|
547
|
+
|
|
548
|
+
out_specs[binding] = (buf, stg, shape, dt, nbytes, aligned)
|
|
549
|
+
bind_entries.append({"binding": binding, "resource": {"buffer": buf}})
|
|
550
|
+
|
|
551
|
+
# Uniform buffers (automatically 16-byte padded)
|
|
552
|
+
for binding, padded in padded_uniforms.items():
|
|
553
|
+
buf = device.create_buffer_with_data(
|
|
554
|
+
data=padded,
|
|
555
|
+
usage=wgpu.BufferUsage.UNIFORM,
|
|
556
|
+
)
|
|
557
|
+
allocated.append(buf)
|
|
558
|
+
_track_alloc()
|
|
559
|
+
bind_entries.append({"binding": binding, "resource": {"buffer": buf}})
|
|
560
|
+
|
|
561
|
+
bind_entries.sort(key=lambda entry: entry["binding"])
|
|
562
|
+
bind_group = device.create_bind_group(
|
|
563
|
+
layout=bind_group_layout,
|
|
564
|
+
entries=bind_entries,
|
|
565
|
+
)
|
|
566
|
+
|
|
567
|
+
# Fuse compute dispatch and output staging copies into a single queue submission
|
|
568
|
+
encoder = device.create_command_encoder()
|
|
569
|
+
compute_pass = encoder.begin_compute_pass()
|
|
570
|
+
compute_pass.set_pipeline(pipeline)
|
|
571
|
+
compute_pass.set_bind_group(0, bind_group)
|
|
572
|
+
compute_pass.dispatch_workgroups(gx, gy, gz)
|
|
573
|
+
compute_pass.end()
|
|
574
|
+
|
|
575
|
+
for buf, stg, _shape, _dt, _nbytes, aligned in out_specs.values():
|
|
576
|
+
encoder.copy_buffer_to_buffer(buf, 0, stg, 0, aligned)
|
|
577
|
+
|
|
578
|
+
device.queue.submit([encoder.finish()])
|
|
579
|
+
|
|
580
|
+
results: dict[int, np.ndarray] = {}
|
|
581
|
+
for binding, (_buf, stg, shape, dt, nbytes, _aligned) in out_specs.items():
|
|
582
|
+
target_out = out_arrays.get(binding) if out_arrays else None
|
|
583
|
+
results[binding] = _read_staging_into_array(
|
|
584
|
+
stg, nbytes, shape, dt, out=target_out
|
|
585
|
+
)
|
|
586
|
+
return results
|
|
587
|
+
finally:
|
|
588
|
+
for buf in allocated:
|
|
589
|
+
try:
|
|
590
|
+
buf.destroy()
|
|
591
|
+
finally:
|
|
592
|
+
_track_free()
|