gpusync 0.1.0__cp310-abi3-win_amd64.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.
gpusync/__init__.py ADDED
@@ -0,0 +1,101 @@
1
+ """GPUsync — write GPU kernels in Python and run them on any GPU.
2
+
3
+ import numpy as np
4
+ import gpusync as gs
5
+
6
+ @gs.kernel
7
+ def normalize(x: gs.f32[:], mean: gs.f32, std: gs.f32) -> gs.f32[:]:
8
+ return (x - mean) / std
9
+
10
+ x = np.random.rand(1_000_000).astype(np.float32)
11
+ y = normalize(x, x.mean(), x.std()) # gs.Array: computation launched on the GPU
12
+ print(y[:5]) # waits for the end and copies back
13
+
14
+ Status: milestone M6 (element-wise, indexed, explicit mode with atomics; no size limit; await, DLPack; CUDA).
15
+ See docs/ and ARCHITECTURE.md.
16
+ """
17
+
18
+ def _nvrtc_dirs() -> None:
19
+ """Folders of the NVIDIA pip wheels (`nvidia-cuda-nvrtc-cu12`…) where the CUDA backend looks for NVRTC,
20
+ besides the CUDA toolkit and the PATH. Read when the first kernel is compiled with CUDA."""
21
+ import glob
22
+ import os
23
+ import sys
24
+
25
+ if "GPUSYNC_NVRTC_DIRS" in os.environ: # chosen by the user (empty: no wheel)
26
+ return
27
+ found = []
28
+ for base in sys.path:
29
+ for pattern in ("nvidia/*/bin", "nvidia/*/lib", "nvidia/*/bin/*", "nvidia/*/lib/*"):
30
+ for d in glob.glob(os.path.join(base or ".", pattern)):
31
+ if os.path.isdir(d) and glob.glob(os.path.join(d, "*nvrtc*")):
32
+ found.append(d)
33
+ if found:
34
+ os.environ["GPUSYNC_NVRTC_DIRS"] = os.pathsep.join(found)
35
+
36
+
37
+ _nvrtc_dirs()
38
+
39
+ # The graphics engine `gpusync.gfx` is a separate package (gpusync-gfx) that adds `gpusync/gfx/`: installed
40
+ # next to the library or elsewhere on sys.path (editable mode), it is found as a subpackage.
41
+ __path__ = __import__("pkgutil").extend_path(__path__, __name__)
42
+
43
+ from . import _core # noqa: E402
44
+ from ._array import Array
45
+ from ._core import (
46
+ BackendStatus,
47
+ Device,
48
+ DeviceError,
49
+ GpusyncError,
50
+ KernelSyntaxError,
51
+ ShapeMismatch,
52
+ TypeMismatch,
53
+ UnsupportedFeature,
54
+ __version__,
55
+ )
56
+ from ._device import (
57
+ CompatibilityWarning,
58
+ backends,
59
+ batch,
60
+ default_device,
61
+ device,
62
+ devices,
63
+ set_default_device,
64
+ set_memory_budget,
65
+ sync,
66
+ )
67
+ from ._kernel import Kernel, OutOfBounds, OutOfMemory, kernel
68
+ from ._math import * # noqa: F403 (sqrt, exp, … usable in kernels)
69
+ from ._math import __all__ as _math_all
70
+ from ._types import Out, f32, f64, i32, i64, u32, u64
71
+ from ._window import Window
72
+
73
+ __all__ = [
74
+ "kernel", "Kernel", "Array", "Window", "batch", "sync",
75
+ "devices", "backends", "Device", "BackendStatus",
76
+ "device", "default_device", "set_default_device", "set_memory_budget",
77
+ "f32", "f64", "i32", "u32", "i64", "u64", "Out",
78
+ "CompatibilityWarning", "OutOfMemory", "OutOfBounds",
79
+ "GpusyncError", "KernelSyntaxError", "TypeMismatch", "ShapeMismatch", "UnsupportedFeature", "DeviceError",
80
+ "__version__",
81
+ *_math_all,
82
+ ]
83
+
84
+
85
+ def __getattr__(name: str):
86
+ if name == "gfx":
87
+ # `gs.gfx`: loaded on first access, if installed
88
+ import importlib
89
+
90
+ try:
91
+ mod = importlib.import_module(".gfx", __name__)
92
+ except ModuleNotFoundError as e:
93
+ if e.name != f"{__name__}.gfx":
94
+ raise
95
+ raise ImportError(
96
+ "gs.gfx: the graphics engine is a separate package. Install it: pip install gpusync-gfx "
97
+ "(from the repository: pip install -e gfx)"
98
+ ) from None
99
+ globals()["gfx"] = mod
100
+ return mod
101
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
gpusync/__main__.py ADDED
@@ -0,0 +1,26 @@
1
+ """`python -m gpusync`: diagnostic of the backends and devices of this machine."""
2
+
3
+ import platform
4
+
5
+ import gpusync as gs
6
+
7
+
8
+ def _size(n):
9
+ return f"{n / 2**30:.1f} GB" if n is not None else "?"
10
+
11
+
12
+ def main() -> None:
13
+ print(f"gpusync {gs.__version__} — {platform.system()} {platform.machine()}, Python {platform.python_version()}\n")
14
+ for st in gs.backends():
15
+ state = f"{len(st.devices)} device(s)" if st.available else f"unavailable: {st.error}"
16
+ print(f"[{st.name}] {state}")
17
+ for d in st.devices:
18
+ flags = ", ".join(f for f, on in (("f64", d.f64), ("unified memory", d.unified_memory)) if on) or "—"
19
+ print(f" {d.id:<10} {d.name}")
20
+ print(f" {d.kind}, {d.vendor or '?'}, {d.version or '?'} | memory {_size(d.memory_bytes)}, "
21
+ f"buffer max {_size(d.max_buffer_bytes)} | {flags}")
22
+ print(f"\nDefault device: {gs.devices()[0] if gs.devices() else 'none'}")
23
+
24
+
25
+ if __name__ == "__main__":
26
+ main()
gpusync/_array.py ADDED
@@ -0,0 +1,197 @@
1
+ """`gs.Array`: result of a kernel, kept on the device until it is read (§4.6).
2
+
3
+ - passing a `gs.Array` to another kernel: no copy to the host;
4
+ - `np.asarray(y)`, `y.numpy()`, `y[i]`, `print(y)`: wait for the computation and copy back;
5
+ - on unified memory (OpenCL), the returned NumPy array *is* the result's memory (zero-copy);
6
+ - `await y`: waits for the computation without blocking the asyncio loop (wait on a thread, GIL released);
7
+ - `np.from_dlpack(y)`, `torch.from_dlpack(y)`: DLPack export (host memory, no copy);
8
+ - `y.save("r.npy")`: writes the result to a .npy file, chunk by chunk from the GPU;
9
+ - `y + 1`, `y == 2`, `-y`, `np.add(y, 1)`: NumPy operators and ufuncs, computed on the host after reading,
10
+ return a NumPy array (to stay on the GPU, write a kernel).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import asyncio
16
+ import math
17
+ import threading
18
+
19
+ import numpy as np
20
+
21
+
22
+ class Array(np.lib.mixins.NDArrayOperatorsMixin):
23
+ __slots__ = ("_handle", "_host", "_shape", "_dtype", "_size", "_ready", "_lock", "_check", "device")
24
+ __array_priority__ = 1000
25
+
26
+ def __init__(self, handle, host: np.ndarray | None, device: str, *, shape=None, dtype=None) -> None:
27
+ self._handle = handle # _core.DeviceArray, or None if already in host memory
28
+ self._host = host # final destination (None until a host read is requested)
29
+ if host is not None:
30
+ self._shape = host.shape
31
+ self._dtype = host.dtype
32
+ self._size = host.size
33
+ else:
34
+ self._shape = tuple(shape)
35
+ self._dtype = np.dtype(dtype)
36
+ self._size = math.prod(self._shape)
37
+ self._ready = handle is None
38
+ self._lock = threading.Lock() # read possible from a thread (await) and from the main thread
39
+ self._check = None # explicit mode: checks that no write was rejected
40
+ self.device = device
41
+
42
+ # ── shape and type: known without waiting for the computation ──
43
+ @property
44
+ def shape(self) -> tuple:
45
+ return self._shape
46
+
47
+ @property
48
+ def dtype(self) -> np.dtype:
49
+ return self._dtype
50
+
51
+ @property
52
+ def ndim(self) -> int:
53
+ return len(self._shape)
54
+
55
+ @property
56
+ def size(self) -> int:
57
+ return self._size
58
+
59
+ @property
60
+ def nbytes(self) -> int:
61
+ return self._size * self._dtype.itemsize
62
+
63
+ @property
64
+ def mode(self) -> str:
65
+ """Execution mode (§9.1): "direct" (zero-copy), "resident" (kept on the GPU), "flux" (chunk by chunk,
66
+ already in its destination) or "cpu"."""
67
+ return self._handle.mode if self._handle is not None else "host"
68
+
69
+ @property
70
+ def zero_copy(self) -> bool:
71
+ """Is the result computed directly in the NumPy array's memory (Direct mode)?"""
72
+ return self.mode == "direct"
73
+
74
+ # ── reading ──
75
+ def numpy(self) -> np.ndarray:
76
+ """Waits for the computation and returns the result as a NumPy array."""
77
+ if not self._ready:
78
+ with self._lock:
79
+ if not self._ready:
80
+ if self._host is None:
81
+ self._host = np.empty(self._shape, dtype=self._dtype)
82
+ self._handle.read_into(self._host.ctypes.data)
83
+ self._ready = True
84
+ if self._check is not None:
85
+ self._check()
86
+ return self._host
87
+
88
+ @property
89
+ def ready(self) -> bool:
90
+ """Has the result already been read (no wait to expect)?"""
91
+ return self._ready
92
+
93
+ def __await__(self):
94
+ """`await y`: waits for the computation and the read on a thread, then returns `y` (ready)."""
95
+ return self._wait().__await__()
96
+
97
+ async def _wait(self):
98
+ if not self._ready:
99
+ await asyncio.get_running_loop().run_in_executor(None, self.numpy)
100
+ return self
101
+
102
+ # ── operators: NumPy's, on the read result (§4.6) ──
103
+ __hash__ = object.__hash__ # `==` compares values, but a gs.Array stays usable as a key (identity)
104
+
105
+ def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
106
+ """`y + 1`, `y == 2`, `np.maximum(y, 0)`…: waits for the computation, reads the result and lets NumPy do it."""
107
+ def host(v):
108
+ return v.numpy() if isinstance(v, Array) else v
109
+
110
+ inputs = tuple(host(v) for v in inputs)
111
+ if "out" in kwargs:
112
+ kwargs["out"] = tuple(host(v) for v in kwargs["out"])
113
+ return getattr(ufunc, method)(*inputs, **kwargs)
114
+
115
+ # ── interoperability ──
116
+ def __dlpack__(self, *, stream=None, max_version=None, dl_device=None, copy=None):
117
+ """DLPack export of the result in host memory (waits for the computation, no copy)."""
118
+ host = self.numpy()
119
+ kw = {k: v for k, v in (("max_version", max_version), ("dl_device", dl_device), ("copy", copy)) if v is not None}
120
+ try:
121
+ return host.__dlpack__(stream=stream, **kw)
122
+ except TypeError: # NumPy < 2: only `stream` is accepted
123
+ return host.__dlpack__(stream=stream)
124
+
125
+ def __dlpack_device__(self):
126
+ return self._host.__dlpack_device__() if self._host is not None else (1, 0)
127
+
128
+ def save(self, path) -> None:
129
+ """Writes the result to a .npy file (np.load reads it back). A result kept on the GPU is
130
+ copied back chunk by chunk straight into the file, without a full copy in RAM."""
131
+ mm = np.lib.format.open_memmap(path, mode="w+", dtype=self.dtype, shape=self.shape)
132
+ if self._ready or mm.size == 0:
133
+ mm[...] = self._host
134
+ else:
135
+ with self._lock:
136
+ if self._ready:
137
+ mm[...] = self._host
138
+ else:
139
+ self._handle.read_into(mm.ctypes.data)
140
+ mm.flush()
141
+ del mm
142
+ if self._check is not None:
143
+ self._check()
144
+
145
+ def __array__(self, dtype=None, copy=None):
146
+ a = self.numpy()
147
+ if dtype is not None and np.dtype(dtype) != a.dtype:
148
+ return a.astype(dtype)
149
+ return a.copy() if copy else a
150
+
151
+ def __len__(self) -> int:
152
+ if not self._shape:
153
+ raise TypeError("len() of unsized object")
154
+ return self._shape[0]
155
+
156
+ def __getitem__(self, key):
157
+ return self.numpy()[key]
158
+
159
+ def __iter__(self):
160
+ return iter(self.numpy())
161
+
162
+ # ── reductions: computed on the host by NumPy, after reading (§4.6) ──
163
+ def sum(self, axis=None, **kw):
164
+ return self.numpy().sum(axis=axis, **kw)
165
+
166
+ def mean(self, axis=None, **kw):
167
+ return self.numpy().mean(axis=axis, **kw)
168
+
169
+ def min(self, axis=None, **kw):
170
+ return self.numpy().min(axis=axis, **kw)
171
+
172
+ def max(self, axis=None, **kw):
173
+ return self.numpy().max(axis=axis, **kw)
174
+
175
+ def std(self, axis=None, **kw):
176
+ return self.numpy().std(axis=axis, **kw)
177
+
178
+ def __repr__(self) -> str:
179
+ body = np.array2string(self.numpy(), separator=", ", prefix="gs.Array(")
180
+ return f"gs.Array({body}, dtype={self.dtype}, device='{self.device}')"
181
+
182
+ def __str__(self) -> str:
183
+ return str(self.numpy())
184
+
185
+
186
+ class Results(tuple):
187
+ """Outputs of a kernel with several outputs: a tuple of gs.Array, awaitable in one go
188
+ (`mean, std = await stats(x)`)."""
189
+
190
+ __slots__ = ()
191
+
192
+ def __await__(self):
193
+ return self._wait().__await__()
194
+
195
+ async def _wait(self):
196
+ await asyncio.gather(*self)
197
+ return self
gpusync/_ast.py ADDED
@@ -0,0 +1,197 @@
1
+ """Python function → JSON description for the Rust frontend (see crates/gpusync-frontend).
2
+
3
+ Python provides what only it knows: the source, the signature (evaluated annotations), the
4
+ global constants and the modules used. Typing and validation are done in Rust.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import ast
10
+ import builtins
11
+ import inspect
12
+ import json
13
+ import math
14
+ import textwrap
15
+ import types
16
+ import typing
17
+
18
+ from ._types import ArrayType, DType, OutType
19
+
20
+
21
+ class KernelDeclarationError(Exception):
22
+ """Error in a kernel's declaration (signature): converted into gs.KernelSyntaxError."""
23
+
24
+
25
+ def _dump(node):
26
+ if isinstance(node, ast.Constant):
27
+ v = node.value
28
+ if isinstance(v, bool):
29
+ kind, rep = "bool", str(v)
30
+ elif isinstance(v, int):
31
+ kind, rep = "int", repr(v)
32
+ elif isinstance(v, float):
33
+ kind, rep = "float", repr(v)
34
+ elif isinstance(v, str):
35
+ kind, rep = "str", ""
36
+ else:
37
+ kind, rep = "other", ""
38
+ return {"_type": "Constant", "value": {"kind": kind, "repr": rep}, "lineno": getattr(node, "lineno", 0)}
39
+ if isinstance(node, ast.AST):
40
+ d = {"_type": type(node).__name__}
41
+ for field, value in ast.iter_fields(node):
42
+ d[field] = _dump(value)
43
+ if hasattr(node, "lineno"):
44
+ d["lineno"] = node.lineno
45
+ return d
46
+ if isinstance(node, list):
47
+ return [_dump(x) for x in node]
48
+ return node
49
+
50
+
51
+ def _const_json(value):
52
+ if isinstance(value, bool):
53
+ return {"kind": "bool", "repr": str(value)}
54
+ if isinstance(value, int):
55
+ return {"kind": "int", "repr": repr(value)}
56
+ if isinstance(value, float):
57
+ return {"kind": "float", "repr": repr(value)}
58
+ return None
59
+
60
+
61
+ def _scope(func) -> dict:
62
+ """Names visible from `func`: builtins, globals, then closure variables (like
63
+ inspect.getclosurevars, without disassembling the code: 40 % less analysis time)."""
64
+ g = func.__globals__
65
+ b = g.get("__builtins__", builtins)
66
+ scope = dict(b.__dict__ if isinstance(b, types.ModuleType) else b)
67
+ scope.update(g)
68
+ for name, cell in zip(func.__code__.co_freevars, func.__closure__ or ()):
69
+ try:
70
+ scope[name] = cell.cell_contents
71
+ except ValueError: # closure variable not assigned yet
72
+ pass
73
+ return scope
74
+
75
+
76
+ def return_types(func, ret) -> tuple[list, bool]:
77
+ """Declared outputs: ([ArrayType], tuple?) for `-> gs.f32[:]` or `-> (gs.f32[:], gs.i32[:])`."""
78
+ if isinstance(ret, ArrayType):
79
+ return [ret], False
80
+ items = None
81
+ if isinstance(ret, tuple):
82
+ items = ret
83
+ elif typing.get_origin(ret) is tuple:
84
+ items = typing.get_args(ret)
85
+ if items and all(isinstance(r, ArrayType) for r in items):
86
+ return list(items), True
87
+ raise KernelDeclarationError(
88
+ f"'{func.__name__}': give the output type, e.g. -> gs.f32[:] (element-wise), "
89
+ '-> gs.f32["n", "n"] (with gs.index()) or -> (gs.f32[:], gs.f32[:]) (several outputs)'
90
+ )
91
+
92
+
93
+ def kernel_spec(func, grid=None, group=None, cells=None) -> tuple[dict, list]:
94
+ """Returns (JSON spec for the frontend, list of parameters [(name, kind, DType, dims)])."""
95
+ try:
96
+ lines, start = inspect.getsourcelines(func)
97
+ except (OSError, TypeError) as e:
98
+ raise KernelDeclarationError(
99
+ f"source of '{func.__name__}' not found ({e}): a kernel must be defined in a file or a notebook"
100
+ ) from None
101
+ source = textwrap.dedent("".join(lines))
102
+ tree = ast.parse(source)
103
+ fdef = next((n for n in tree.body if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))), None)
104
+ if not isinstance(fdef, ast.FunctionDef):
105
+ raise KernelDeclarationError("@gs.kernel applies to a function (def), not async def")
106
+
107
+ a = fdef.args
108
+ if a.vararg or a.kwarg or a.kwonlyargs or a.posonlyargs or a.defaults:
109
+ raise KernelDeclarationError(
110
+ f"'{func.__name__}': plain parameters only (no *args, **kwargs, default values or keyword-only parameters)"
111
+ )
112
+ annotations = inspect.get_annotations(func, eval_str=True)
113
+ params = []
114
+ fills = {} # gs.Out: start value
115
+ for arg in a.args:
116
+ ann = annotations.get(arg.arg)
117
+ if isinstance(ann, OutType):
118
+ if grid is None:
119
+ raise KernelDeclarationError(
120
+ f"parameter '{arg.arg}': gs.Out is used with an explicit grid, e.g. @gs.kernel(grid=\"x\")"
121
+ )
122
+ params.append((arg.arg, "out", ann.array.dtype, ann.array.dims))
123
+ fills[arg.arg] = ann.fill
124
+ elif isinstance(ann, ArrayType):
125
+ params.append((arg.arg, "array", ann.dtype, ann.dims))
126
+ elif isinstance(ann, DType):
127
+ params.append((arg.arg, "scalar", ann, None))
128
+ elif ann is None:
129
+ raise KernelDeclarationError(
130
+ f"parameter '{arg.arg}' has no type: annotate it, e.g. {arg.arg}: gs.f32[:] (array) or {arg.arg}: gs.f32 (scalar)"
131
+ )
132
+ else:
133
+ raise KernelDeclarationError(f"parameter '{arg.arg}': type {ann!r} not supported (gs.f32[:], gs.f32, gs.i32…)")
134
+ if grid is None:
135
+ outs, _ = return_types(func, annotations.get("return"))
136
+ else:
137
+ outs = []
138
+ if annotations.get("return") is not None:
139
+ raise KernelDeclarationError(
140
+ f"'{func.__name__}': with grid=, the results are the gs.Out parameters; remove the return type (-> ...)"
141
+ )
142
+ if not any(k == "out" for _, k, _, _ in params):
143
+ raise KernelDeclarationError(
144
+ f"'{func.__name__}': with grid=, declare at least one output, e.g. counts: gs.Out[gs.i32[10]]"
145
+ )
146
+
147
+ # Free names: numeric global constants and the gs / math modules.
148
+ import gpusync
149
+
150
+ names = {n.id for n in ast.walk(fdef) if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Load)}
151
+ scope = _scope(func)
152
+ constants, modules = {}, {}
153
+ for name in names:
154
+ if name not in scope:
155
+ continue
156
+ value = scope[name]
157
+ if isinstance(value, types.ModuleType):
158
+ if value is gpusync:
159
+ modules[name] = "gpusync"
160
+ elif value is math:
161
+ modules[name] = "math"
162
+ elif (c := _const_json(value)) is not None:
163
+ constants[name] = c
164
+
165
+ spec = {
166
+ "name": func.__name__,
167
+ "filename": inspect.getsourcefile(func) or "<unknown>",
168
+ "line_offset": start - 1,
169
+ "params": [
170
+ {"name": n, "kind": k, "dtype": d.name, **({"dims": list(dims)} if k != "scalar" else {})}
171
+ for n, k, d, dims in params
172
+ ],
173
+ "outputs": [{"dtype": o.dtype.name, "dims": list(o.dims)} for o in outs],
174
+ "grid": None if grid is None else (grid if isinstance(grid, str) else list(grid)),
175
+ "group": group,
176
+ "cells": cells,
177
+ "body": _dump(fdef.body),
178
+ "constants": constants,
179
+ "modules": modules,
180
+ }
181
+ spec["_fills"] = fills
182
+ return spec, params
183
+
184
+
185
+ def kernel_json(func, grid=None, group=None, cells=None) -> tuple[str, list, list, bool, dict]:
186
+ """(JSON spec, parameters, outputs [ArrayType], is the output a tuple?, start value
187
+ of each gs.Out).
188
+
189
+ Explicit mode (`grid=`): the outputs are the gs.Out parameters (a tuple if there are several).
190
+ """
191
+ spec, params = kernel_spec(func, grid, group, cells)
192
+ fills = spec.pop("_fills")
193
+ if grid is not None:
194
+ outs = [ArrayType(d, dims) for _, k, d, dims in params if k == "out"]
195
+ return json.dumps(spec), params, outs, len(outs) > 1, fills
196
+ outs, is_tuple = return_types(func, inspect.get_annotations(func, eval_str=True).get("return"))
197
+ return json.dumps(spec), params, outs, is_tuple, fills
gpusync/_core.pyd ADDED
Binary file