unigpu 0.3.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.
Files changed (94) hide show
  1. unigpu/__init__.py +75 -0
  2. unigpu/_version.py +7 -0
  3. unigpu/api.py +199 -0
  4. unigpu/backends/__init__.py +22 -0
  5. unigpu/backends/metal/__init__.py +85 -0
  6. unigpu/backends/metal/bridge.py +221 -0
  7. unigpu/backends/metal/driver.py +250 -0
  8. unigpu/backends/metal/imports.py +84 -0
  9. unigpu/backends/numba_backend/__init__.py +31 -0
  10. unigpu/backends/numba_backend/discovery.py +124 -0
  11. unigpu/backends/numba_backend/driver.py +174 -0
  12. unigpu/backends/numba_backend/imports.py +48 -0
  13. unigpu/backends/numba_backend/limitations.py +93 -0
  14. unigpu/backends/numba_backend/rebinding.py +164 -0
  15. unigpu/backends/numba_backend/simulator.py +89 -0
  16. unigpu/backends/opencl.py +289 -0
  17. unigpu/backends/sim/__init__.py +12 -0
  18. unigpu/backends/sim/analysis.py +16 -0
  19. unigpu/backends/sim/barrier.py +69 -0
  20. unigpu/backends/sim/checked.py +60 -0
  21. unigpu/backends/sim/cooperative.py +231 -0
  22. unigpu/backends/sim/diagnostics.py +21 -0
  23. unigpu/backends/sim/driver.py +87 -0
  24. unigpu/backends/sim/executor.py +161 -0
  25. unigpu/backends/sim/provider.py +66 -0
  26. unigpu/backends/sim/runtime.py +78 -0
  27. unigpu/backends/sim/strategy.py +17 -0
  28. unigpu/backends/translated.py +115 -0
  29. unigpu/backends/translation.py +79 -0
  30. unigpu/benchmark/__init__.py +30 -0
  31. unigpu/benchmark/cases.py +117 -0
  32. unigpu/benchmark/charts.py +117 -0
  33. unigpu/benchmark/measures.py +125 -0
  34. unigpu/benchmark/tables.py +76 -0
  35. unigpu/compiler/__init__.py +52 -0
  36. unigpu/compiler/coerce.py +29 -0
  37. unigpu/compiler/context.py +166 -0
  38. unigpu/compiler/dialects/__init__.py +12 -0
  39. unigpu/compiler/dialects/base.py +298 -0
  40. unigpu/compiler/dialects/metal.py +158 -0
  41. unigpu/compiler/dialects/opencl.py +120 -0
  42. unigpu/compiler/expressions.py +277 -0
  43. unigpu/compiler/function.py +178 -0
  44. unigpu/compiler/interface.py +93 -0
  45. unigpu/compiler/intrinsics/__init__.py +26 -0
  46. unigpu/compiler/intrinsics/atomics.py +108 -0
  47. unigpu/compiler/intrinsics/builtins.py +160 -0
  48. unigpu/compiler/intrinsics/indexing.py +48 -0
  49. unigpu/compiler/intrinsics/mathlib.py +103 -0
  50. unigpu/compiler/intrinsics/memory.py +101 -0
  51. unigpu/compiler/intrinsics/registry.py +112 -0
  52. unigpu/compiler/intrinsics/sync.py +54 -0
  53. unigpu/compiler/naming.py +49 -0
  54. unigpu/compiler/operators.py +227 -0
  55. unigpu/compiler/passes.py +15 -0
  56. unigpu/compiler/program.py +137 -0
  57. unigpu/compiler/scope.py +116 -0
  58. unigpu/compiler/signatures.py +123 -0
  59. unigpu/compiler/source.py +105 -0
  60. unigpu/compiler/statements.py +289 -0
  61. unigpu/compiler/text.py +34 -0
  62. unigpu/compiler/translators.py +59 -0
  63. unigpu/compiler/typeof.py +43 -0
  64. unigpu/compiler/types.py +190 -0
  65. unigpu/compiler/values.py +77 -0
  66. unigpu/compiler/writer.py +48 -0
  67. unigpu/core/__init__.py +0 -0
  68. unigpu/core/arguments.py +68 -0
  69. unigpu/core/cache.py +46 -0
  70. unigpu/core/code.py +63 -0
  71. unigpu/core/device.py +154 -0
  72. unigpu/core/dims.py +49 -0
  73. unigpu/core/driver.py +145 -0
  74. unigpu/core/families.py +31 -0
  75. unigpu/core/launch.py +74 -0
  76. unigpu/core/memory.py +295 -0
  77. unigpu/core/options.py +52 -0
  78. unigpu/core/provider.py +70 -0
  79. unigpu/core/registry.py +101 -0
  80. unigpu/core/report.py +58 -0
  81. unigpu/core/scope.py +49 -0
  82. unigpu/core/session.py +132 -0
  83. unigpu/core/streams.py +153 -0
  84. unigpu/dispatcher.py +175 -0
  85. unigpu/errors.py +85 -0
  86. unigpu/lang/__init__.py +48 -0
  87. unigpu/lang/runtime.py +93 -0
  88. unigpu/lang/stubs.py +282 -0
  89. unigpu/selftest.py +312 -0
  90. unigpu-0.3.0.dist-info/METADATA +451 -0
  91. unigpu-0.3.0.dist-info/RECORD +94 -0
  92. unigpu-0.3.0.dist-info/WHEEL +5 -0
  93. unigpu-0.3.0.dist-info/licenses/LICENSE +21 -0
  94. unigpu-0.3.0.dist-info/top_level.txt +1 -0
unigpu/__init__.py ADDED
@@ -0,0 +1,75 @@
1
+ """unigpu — GPU programming in Python, one API for CUDA, ROCm, OpenCL and Metal.
2
+
3
+ Kernels are written as with ``numba.cuda`` and run on every detected
4
+ platform:
5
+
6
+ ========= =========================================== ==========================
7
+ backend hardware how
8
+ ========= =========================================== ==========================
9
+ ``cuda`` NVIDIA GPUs numba-cuda
10
+ ``hip`` AMD GPUs (ROCm) numba-hip
11
+ ``metal`` Apple GPUs (macOS, iPadOS) translated to Metal
12
+ ``opencl`` any OpenCL device (GPU, CPU, FPGA) translated to OpenCL C
13
+ ``sim`` the CPU, without any dependency Python simulator
14
+ ========= =========================================== ==========================
15
+
16
+ Example ::
17
+
18
+ import numpy as np
19
+ import unigpu as gpu
20
+
21
+ @gpu.jit
22
+ def addition(a, b, c):
23
+ i = gpu.grid(1)
24
+ if i < c.size:
25
+ c[i] = a[i] + b[i]
26
+
27
+ a = np.arange(1000, dtype=np.float32)
28
+ d_a = gpu.to_device(a)
29
+ d_c = gpu.device_array_like(a)
30
+ addition[(a.size + 255) // 256, 256](d_a, d_a, d_c)
31
+ print(d_c.copy_to_host())
32
+ """
33
+
34
+ from .api import (
35
+ DeviceList, close, default_stream, detect, device_array, device_array_like, device_scope,
36
+ event,
37
+ event_elapsed_time, get_current_device, get_platforms, gpus, is_available, list_devices,
38
+ select_device, stream, synchronize, to_device, translate,
39
+ )
40
+ from .core.device import Device, DeviceInfo, DeviceType, Platform
41
+ from .core.memory import DeviceArray
42
+ from .core.streams import Event, Stream
43
+ from .dispatcher import ConfiguredKernel, DeviceFunction, Kernel, jit
44
+ from .errors import (
45
+ CompilationError, DeviceMemoryError, DeviceNotFoundError, DivergentBarrierError,
46
+ KernelContextError, LaunchError, TranslationError, UnigpuError, UnigpuPerformanceWarning,
47
+ )
48
+ from .lang import (
49
+ atomic, blockDim, blockIdx, boolean, const, float16, float32, float64, grid, gridDim,
50
+ gridsize, int8, int16, int32, int64, local, shared, syncthreads, syncthreads_and,
51
+ syncthreads_count, syncthreads_or, threadIdx, uint8, uint16, uint32, uint64,
52
+ )
53
+
54
+ from ._version import __version__ as __version__ # re-exported (source: _version.py)
55
+
56
+ __all__ = [
57
+ # kernel language
58
+ "threadIdx", "blockIdx", "blockDim", "gridDim", "grid", "gridsize", "syncthreads",
59
+ "syncthreads_count", "syncthreads_and", "syncthreads_or", "shared", "local", "const",
60
+ "atomic", "float16", "float32", "float64", "int8", "int16", "int32", "int64", "uint8",
61
+ "uint16", "uint32", "uint64", "boolean",
62
+ # compilation
63
+ "jit", "Kernel", "ConfiguredKernel", "DeviceFunction", "translate",
64
+ # memory, streams, events
65
+ "to_device", "device_array", "device_array_like", "DeviceArray", "synchronize", "stream",
66
+ "default_stream", "event", "event_elapsed_time", "Stream", "Event",
67
+ # platforms and devices
68
+ "get_platforms", "list_devices", "select_device", "get_current_device", "gpus",
69
+ "DeviceList", "device_scope", "detect", "is_available", "close", "Platform", "Device",
70
+ "DeviceInfo", "DeviceType",
71
+ # errors
72
+ "UnigpuError", "DeviceNotFoundError", "KernelContextError", "LaunchError",
73
+ "DeviceMemoryError", "TranslationError", "CompilationError", "DivergentBarrierError",
74
+ "UnigpuPerformanceWarning",
75
+ ]
unigpu/_version.py ADDED
@@ -0,0 +1,7 @@
1
+ """unigpu's version (single source: also read by ``pyproject.toml``).
2
+
3
+ Shown by ``detect()`` and by the self-test: it lets you check, on an iPad or
4
+ in Colab, that the latest copy of the code is the one running.
5
+ """
6
+
7
+ __version__ = "0.3.0"
unigpu/api.py ADDED
@@ -0,0 +1,199 @@
1
+ """Public host-side functions (same names and signatures as ``numba.cuda``)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Callable, Iterator, List, Optional, Sequence
6
+
7
+ import numpy as np
8
+
9
+ from .compiler import DIALECTS
10
+ from .compiler import types as T
11
+ from .core.device import Device, DeviceType, Platform
12
+ from .core.memory import DeviceArray
13
+ from .core.registry import DeviceSpec
14
+ from .core.report import describe
15
+ from .core.scope import DeviceScope
16
+ from .core.session import Session, get_session
17
+ from .core.streams import Event, Stream, event_elapsed_time # noqa: F401 (re-export)
18
+ from .errors import DeviceNotFoundError, UnigpuError
19
+
20
+
21
+ # ---------------------------------------------------------------------------
22
+ # Memory
23
+ # ---------------------------------------------------------------------------
24
+ def _driver():
25
+ return get_session().driver()
26
+
27
+
28
+ def to_device(obj: Any, stream: Any = 0, copy: bool = True,
29
+ to: Optional[DeviceArray] = None) -> DeviceArray:
30
+ """Copy a NumPy array to device memory (``cudaMemcpy`` host → GPU).
31
+
32
+ :param copy: if false, only allocate an array of the same shape and type.
33
+ :param to: existing device array to copy into.
34
+ """
35
+ if to is not None:
36
+ to.copy_to_device(obj, stream)
37
+ return to
38
+ host = np.asarray(obj)
39
+ if not copy:
40
+ return _driver().device_array(host.shape, host.dtype)
41
+ return _driver().to_device(host, stream)
42
+
43
+
44
+ def device_array(shape: Any, dtype: Any = np.float64, strides: Any = None,
45
+ order: str = "C", stream: Any = 0) -> DeviceArray:
46
+ """Allocate an uninitialized array on the device (``cudaMalloc``).
47
+
48
+ As in numba, the default type is ``float64``; only C order is
49
+ supported.
50
+ """
51
+ if order != "C" or strides is not None:
52
+ raise UnigpuError("only contiguous arrays in C order are supported")
53
+ return _driver().device_array(shape, dtype)
54
+
55
+
56
+ def device_array_like(ary: Any, stream: Any = 0) -> DeviceArray:
57
+ """Allocate an array with the same shape and type as ``ary``."""
58
+ return _driver().device_array(ary.shape, ary.dtype)
59
+
60
+
61
+ def synchronize() -> None:
62
+ """Wait until every command of the current device has completed."""
63
+ _driver().synchronize()
64
+
65
+
66
+ # ---------------------------------------------------------------------------
67
+ # Streams and events
68
+ # ---------------------------------------------------------------------------
69
+ def stream() -> Stream:
70
+ """Create a new stream (command queue) on the current device."""
71
+ return _driver().create_stream()
72
+
73
+
74
+ def default_stream() -> Stream:
75
+ """Default stream of the current device."""
76
+ return _driver().default_stream
77
+
78
+
79
+ def event(timing: bool = True) -> Event:
80
+ """Create an event (to synchronize or to time)."""
81
+ return _driver().create_event(timing)
82
+
83
+
84
+ # ---------------------------------------------------------------------------
85
+ # Platforms and devices
86
+ # ---------------------------------------------------------------------------
87
+ def get_platforms() -> List[Platform]:
88
+ """Platforms available on this machine (``clGetPlatformIDs``)."""
89
+ return get_session().registry.get_platforms()
90
+
91
+
92
+ def list_devices(device_type: DeviceType = DeviceType.ALL) -> List[Device]:
93
+ """Available devices, across all platforms."""
94
+ return get_session().registry.list_devices(device_type)
95
+
96
+
97
+ def select_device(spec: DeviceSpec) -> Device:
98
+ """Choose the current device.
99
+
100
+ ``spec``: a :class:`Device`, its rank in :func:`list_devices`, a
101
+ :class:`DeviceType`, or a string ``"opencl"``, ``"cuda:1"``,
102
+ ``"opencl:0:1"``, ``"sim"``...
103
+ """
104
+ return get_session().select_device(spec)
105
+
106
+
107
+ def get_current_device() -> Device:
108
+ """Current device (chosen automatically on first use)."""
109
+ return get_session().current_device()
110
+
111
+
112
+ def close() -> None:
113
+ """Close the open drivers and forget the chosen device."""
114
+ get_session().close()
115
+
116
+
117
+ def is_available() -> bool:
118
+ """True if a real device (other than the simulator) is available."""
119
+ return any(d.device_type != DeviceType.SIMULATOR for d in list_devices())
120
+
121
+
122
+ def detect() -> bool:
123
+ """Print the detected platforms and devices; true if there is at least one."""
124
+ session = get_session()
125
+ print(describe(session.registry))
126
+ try:
127
+ print(f"Current device: {session.current_device()!r}")
128
+ except DeviceNotFoundError:
129
+ return False
130
+ return True
131
+
132
+
133
+ def device_scope(device: Device) -> DeviceScope:
134
+ """``with device_scope(device):`` makes ``device`` current inside the block."""
135
+ return DeviceScope(device, get_session())
136
+
137
+
138
+ class DeviceList(Sequence):
139
+ """List of devices (``cuda.gpus``); ``gpus.current`` is the current device.
140
+
141
+ Each element is a :class:`DeviceScope`: ``with gpus[1]:`` temporarily
142
+ makes device 1 the current one, ``gpus[1].name`` is the name of the device.
143
+
144
+ :param session: gives the session whose devices are listed.
145
+ """
146
+
147
+ def __init__(self, session: Callable[[], Session]):
148
+ self._session = session
149
+
150
+ def _devices(self) -> List[Device]:
151
+ return self._session().registry.list_devices()
152
+
153
+ def __getitem__(self, index: int) -> DeviceScope: # type: ignore[override]
154
+ return DeviceScope(self._devices()[index], self._session())
155
+
156
+ def __len__(self) -> int:
157
+ return len(self._devices())
158
+
159
+ def __iter__(self) -> Iterator[DeviceScope]:
160
+ return (DeviceScope(device, self._session()) for device in self._devices())
161
+
162
+ @property
163
+ def current(self) -> Device:
164
+ return self._session().current_device()
165
+
166
+ def __repr__(self) -> str:
167
+ return f"<DeviceList {self._devices()!r}>"
168
+
169
+
170
+ gpus = DeviceList(get_session)
171
+
172
+
173
+ # ---------------------------------------------------------------------------
174
+ # Translation without a device
175
+ # ---------------------------------------------------------------------------
176
+ def translate(kernel: Any, *args: Any, target: str = "opencl") -> str:
177
+ """OpenCL C or Metal code of a kernel, **without any device**.
178
+
179
+ The arguments only serve to determine the types (NumPy arrays or
180
+ scalars); without arguments, the first declared signature is used ::
181
+
182
+ print(unigpu.translate(addition, a, b, c, target="metal"))
183
+ """
184
+ from .compiler import translate as translate_program
185
+
186
+ try:
187
+ dialect_class = DIALECTS[target]
188
+ except KeyError:
189
+ raise ValueError(f"unknown target: {target!r} "
190
+ f"(targets: {', '.join(DIALECTS)})") from None
191
+ dialect = dialect_class(default_float=T.FLOAT64)
192
+ if args:
193
+ argtypes = kernel.argument_types(args, dialect.default_float)
194
+ elif kernel.signatures:
195
+ argtypes = kernel.signatures[0].args
196
+ else:
197
+ raise UnigpuError("translate(): give example arguments or declare a "
198
+ "signature in @jit(...)")
199
+ return translate_program(kernel.py_func, argtypes, dialect).source
@@ -0,0 +1,22 @@
1
+ """Execution backends.
2
+
3
+ Order of discovery (and of preference between devices of the same type):
4
+ CUDA, HIP, Metal, OpenCL, simulator.
5
+ """
6
+
7
+ from typing import List
8
+
9
+ from ..core.provider import PlatformProvider
10
+ from .metal import MetalProvider
11
+ from .numba_backend import cuda_provider, hip_provider
12
+ from .opencl import OpenCLProvider
13
+ from .sim import SimProvider
14
+
15
+
16
+ def default_providers() -> List[PlatformProvider]:
17
+ """Platform providers used by default."""
18
+ return [cuda_provider(), hip_provider(), MetalProvider(), OpenCLProvider(), SimProvider()]
19
+
20
+
21
+ __all__ = ["MetalProvider", "OpenCLProvider", "SimProvider", "cuda_provider",
22
+ "default_providers", "hip_provider"]
@@ -0,0 +1,85 @@
1
+ """Metal backend: Apple GPUs, on a Mac (macOS) as well as on an iPad (iPadOS).
2
+
3
+ Kernels are translated to Metal Shading Language. To talk to Objective-C,
4
+ the backend uses the first available library:
5
+
6
+ 1. PyObjC (``pip install pyobjc-framework-Metal``, macOS);
7
+ 2. rubicon-objc (``pip install rubicon-objc``, pure Python: macOS, iPadOS);
8
+ 3. ``objc_util``, shipped with the Pythonista app (iPadOS).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import platform
14
+ import sys
15
+ from typing import Callable, List, Sequence
16
+
17
+ from ...core.provider import BackendUnavailableError, PlatformProvider
18
+ from .bridge import (
19
+ CtypesBridge, ObjCBridge, PyObjCBridge, objc_property, pythonista_bridge, rubicon_bridge,
20
+ )
21
+ from .driver import MetalDevice, MetalDriver, MetalPlatform, device_info
22
+
23
+ #: Apple systems where Metal exists ("ios": iPadOS/iOS, Python ≥ 3.13).
24
+ APPLE_PLATFORMS = ("darwin", "ios")
25
+ #: Names returned by ``platform.system()``, depending on the Python app for iPad.
26
+ APPLE_SYSTEMS = ("Darwin", "iOS", "iPadOS")
27
+
28
+
29
+ def is_apple_platform() -> bool:
30
+ """True on macOS, iPadOS and iOS (whatever the way Python names them)."""
31
+ return sys.platform in APPLE_PLATFORMS or platform.system() in APPLE_SYSTEMS
32
+
33
+
34
+ def _pyobjc_bridge() -> ObjCBridge:
35
+ import Metal
36
+ return PyObjCBridge(Metal)
37
+
38
+
39
+ #: Bridges tried in order.
40
+ BRIDGE_FACTORIES: Sequence[Callable[[], ObjCBridge]] = (_pyobjc_bridge, rubicon_bridge,
41
+ pythonista_bridge)
42
+
43
+
44
+ def load_bridge(factories: Sequence[Callable[[], ObjCBridge]] = BRIDGE_FACTORIES) -> ObjCBridge:
45
+ """First usable Objective-C bridge.
46
+
47
+ :raises BackendUnavailableError: outside macOS/iPadOS, or without an
48
+ Objective-C library; the message then gives the reason of each failure
49
+ (for instance "No module named '_ctypes'" if Python has no ``ctypes``).
50
+ """
51
+ if not is_apple_platform():
52
+ raise BackendUnavailableError("Metal only exists on Apple devices "
53
+ "(macOS, iPadOS)")
54
+ reasons = []
55
+ for factory in factories:
56
+ try:
57
+ return factory()
58
+ except ImportError as error:
59
+ reasons.append(str(error))
60
+ raise BackendUnavailableError("no Objective-C library: install "
61
+ "pyobjc-framework-Metal (macOS) or rubicon-objc "
62
+ f"(macOS, iPadOS) [{'; '.join(reasons)}]")
63
+
64
+
65
+ class MetalProvider(PlatformProvider):
66
+ """Discover the Metal GPUs.
67
+
68
+ :param loader: function returning the Objective-C bridge (replaceable in tests).
69
+ """
70
+
71
+ backend = "metal"
72
+ label = "Apple Metal (PyObjC, rubicon-objc or Pythonista)"
73
+
74
+ def __init__(self, loader: Callable[[], ObjCBridge] = load_bridge):
75
+ super().__init__()
76
+ self._loader = loader
77
+
78
+ def _discover_platforms(self) -> List[MetalPlatform]:
79
+ return [MetalPlatform(self._loader())]
80
+
81
+
82
+ __all__ = ["APPLE_PLATFORMS", "APPLE_SYSTEMS", "BRIDGE_FACTORIES", "CtypesBridge", "MetalDevice",
83
+ "MetalDriver", "MetalPlatform", "MetalProvider", "ObjCBridge", "PyObjCBridge",
84
+ "device_info", "is_apple_platform", "load_bridge", "objc_property",
85
+ "pythonista_bridge", "rubicon_bridge"]
@@ -0,0 +1,221 @@
1
+ """Bridges to Objective-C: PyObjC (macOS) and rubicon-objc (macOS, iPadOS, iOS).
2
+
3
+ The Metal driver only uses the "flat" call syntax shared by both libraries
4
+ (``device.newBufferWithLength_options_(n, mode)``), and the function
5
+ :func:`objc_send` for messages without arguments. The few operations that
6
+ really differ (list of GPUs, error parameters, access to a buffer's memory)
7
+ are grouped in :class:`ObjCBridge`, one class per library (Adapter pattern).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import ctypes
13
+ from abc import ABC, abstractmethod
14
+ from typing import Any, List, Optional, Tuple
15
+
16
+ import numpy as np
17
+
18
+ from .imports import import_module
19
+
20
+ #: Value of ``MTLResourceStorageModeShared`` (memory shared by CPU and GPU).
21
+ STORAGE_MODE_SHARED = 0
22
+
23
+
24
+ def objc_send(obj: Any, selector: str) -> Any:
25
+ """Send ``obj`` the message ``selector``, which has no arguments; return the result.
26
+
27
+ PyObjC and objc_util present these messages as methods to call
28
+ (``buffer.contents()``). rubicon-objc turns them into properties whose
29
+ value is already there (``buffer.contents``) as soon as the class, often a
30
+ private Apple class, declares them so: this cannot be known in advance.
31
+ This function works in both cases; the message is sent once.
32
+ """
33
+ value = getattr(obj, selector)
34
+ return value() if callable(value) else value
35
+
36
+
37
+ #: Reading an Objective-C property means sending the message of its getter.
38
+ objc_property = objc_send
39
+
40
+
41
+ def array_length(array: Any) -> int:
42
+ """Number of elements of an ``NSArray``.
43
+
44
+ ``len()`` first: rubicon-objc presents an ``NSArray`` as a Python list,
45
+ whose ``count`` attribute is the method ``list.count(value)`` and not the
46
+ Objective-C property. Otherwise (``objc_util``...), the ``count`` property.
47
+ """
48
+ try:
49
+ return len(array)
50
+ except TypeError:
51
+ return int(objc_property(array, "count"))
52
+
53
+
54
+ def size_tuple(value: Any) -> Tuple[int, int, int]:
55
+ """Components ``(width, height, depth)`` of an ``MTLSize``."""
56
+ if hasattr(value, "width"):
57
+ return int(value.width), int(value.height), int(value.depth)
58
+ return tuple(int(getattr(value, field[0])) for field in value._fields_)[:3]
59
+
60
+
61
+ def describe_error(error: Any) -> Optional[str]:
62
+ """Text of an ``NSError`` (``None`` if there is no error)."""
63
+ return None if error is None else str(objc_property(error, "localizedDescription"))
64
+
65
+
66
+ class ObjCBridge(ABC):
67
+ """Metal operations that depend on the Objective-C library in use."""
68
+
69
+ #: Name of the library (shown by ``detect()``).
70
+ name = "?"
71
+
72
+ @abstractmethod
73
+ def devices(self) -> List[Any]:
74
+ """Available Metal GPUs."""
75
+
76
+ @abstractmethod
77
+ def compile_options(self) -> Any:
78
+ """New ``MTLCompileOptions`` object."""
79
+
80
+ @abstractmethod
81
+ def new_library(self, device: Any, source: str, options: Any) -> Tuple[Any, Optional[str]]:
82
+ """Compile Metal Shading Language: ``(library or None, error)``."""
83
+
84
+ @abstractmethod
85
+ def new_pipeline(self, device: Any, function: Any) -> Tuple[Any, Optional[str]]:
86
+ """Create a compute pipeline: ``(pipeline or None, error)``."""
87
+
88
+ @abstractmethod
89
+ def host_view(self, buffer: Any) -> np.ndarray:
90
+ """Bytes of an ``MTLBuffer`` seen from the host (writable view, no copy)."""
91
+
92
+ def size(self, width: int, height: int, depth: int) -> Any:
93
+ """``MTLSize`` value (a tuple is enough for both libraries)."""
94
+ return (width, height, depth)
95
+
96
+
97
+ class PyObjCBridge(ObjCBridge):
98
+ """PyObjC bridge (``pip install pyobjc-framework-Metal``, macOS).
99
+
100
+ :param metal: PyObjC's ``Metal`` module (or a test double).
101
+ """
102
+
103
+ name = "PyObjC"
104
+
105
+ def __init__(self, metal: Any):
106
+ self.metal = metal
107
+
108
+ def devices(self) -> List[Any]:
109
+ copy_all = getattr(self.metal, "MTLCopyAllDevices", None)
110
+ devices = list(copy_all()) if copy_all else []
111
+ if not devices:
112
+ default = self.metal.MTLCreateSystemDefaultDevice()
113
+ devices = [default] if default is not None else []
114
+ return devices
115
+
116
+ def compile_options(self) -> Any:
117
+ return self.metal.MTLCompileOptions.new()
118
+
119
+ def new_library(self, device, source, options):
120
+ library, error = device.newLibraryWithSource_options_error_(source, options, None)
121
+ return library, describe_error(error)
122
+
123
+ def new_pipeline(self, device, function):
124
+ pipeline, error = device.newComputePipelineStateWithFunction_error_(function, None)
125
+ return pipeline, describe_error(error)
126
+
127
+ def host_view(self, buffer) -> np.ndarray:
128
+ length = objc_property(buffer, "length")
129
+ return np.frombuffer(buffer.contents().as_buffer(length), dtype=np.uint8)
130
+
131
+ def size(self, width, height, depth):
132
+ return self.metal.MTLSizeMake(width, height, depth)
133
+
134
+
135
+ class CtypesBridge(ObjCBridge):
136
+ """Generic bridge for the Objective-C libraries built on ctypes.
137
+
138
+ Serves rubicon-objc (macOS, iPadOS, iOS: Pyto, a-Shell, Carnets...) and
139
+ ``objc_util`` (Pythonista, iPadOS). Both accept PyObjC's flat syntax; only
140
+ the way to find Metal's C functions and the type of pointers differ.
141
+
142
+ :param name: displayed name of the library.
143
+ :param objc_class: Objective-C class constructor (``ObjCClass``).
144
+ :param objc_instance: wrapper of an object pointer (``ObjCInstance``).
145
+ :param symbols: object giving access to the C functions of the Metal framework.
146
+ :param pointer_type: ctypes type of an object pointer (``objc_id``...).
147
+ """
148
+
149
+ def __init__(self, name: str, *, objc_class: Any, objc_instance: Any, symbols: Any,
150
+ pointer_type: Any = ctypes.c_void_p):
151
+ self.name = name
152
+ self._class = objc_class
153
+ self._wrap = objc_instance
154
+ self._pointer = pointer_type
155
+ self._functions = {}
156
+ for symbol in ("MTLCreateSystemDefaultDevice", "MTLCopyAllDevices"):
157
+ function = getattr(symbols, symbol, None)
158
+ if function is not None:
159
+ function.restype, function.argtypes = pointer_type, []
160
+ self._functions[symbol] = function
161
+
162
+ def _instance(self, pointer: Any) -> Any:
163
+ return self._wrap(pointer) if pointer else None
164
+
165
+ def devices(self) -> List[Any]:
166
+ copy_all = self._functions.get("MTLCopyAllDevices")
167
+ array = self._instance(copy_all()) if copy_all else None
168
+ devices = ([array.objectAtIndex_(i) for i in range(array_length(array))]
169
+ if array is not None else [])
170
+ if not devices:
171
+ default = self._instance(self._functions["MTLCreateSystemDefaultDevice"]())
172
+ devices = [default] if default is not None else []
173
+ return devices
174
+
175
+ def compile_options(self) -> Any:
176
+ return objc_send(self._class("MTLCompileOptions"), "new")
177
+
178
+ def _call_with_error(self, method: Any, *args: Any) -> Tuple[Any, Optional[str]]:
179
+ error = self._pointer()
180
+ result = method(*args, ctypes.byref(error))
181
+ return result, describe_error(self._instance(error) if error.value else None)
182
+
183
+ def new_library(self, device, source, options):
184
+ return self._call_with_error(device.newLibraryWithSource_options_error_, source,
185
+ options)
186
+
187
+ def new_pipeline(self, device, function):
188
+ return self._call_with_error(device.newComputePipelineStateWithFunction_error_,
189
+ function)
190
+
191
+ def host_view(self, buffer) -> np.ndarray:
192
+ length = objc_property(buffer, "length")
193
+ address = objc_send(buffer, "contents") # a property for rubicon on iPad
194
+ memory = (ctypes.c_uint8 * length).from_address(getattr(address, "value", address))
195
+ return np.ctypeslib.as_array(memory)
196
+
197
+
198
+ def rubicon_bridge() -> CtypesBridge:
199
+ """rubicon-objc bridge (``pip install rubicon-objc``, pure Python).
200
+
201
+ rubicon-objc is found even when Python does not see its installation
202
+ folder yet (see :mod:`.imports`).
203
+
204
+ :raises ImportError: if rubicon-objc is not installed, or if Python has no ``ctypes``.
205
+ """
206
+ objc = import_module("rubicon.objc")
207
+ runtime = import_module("rubicon.objc.runtime")
208
+ return CtypesBridge("rubicon-objc", objc_class=objc.ObjCClass,
209
+ objc_instance=objc.ObjCInstance,
210
+ symbols=runtime.load_library("Metal"), pointer_type=runtime.objc_id)
211
+
212
+
213
+ def pythonista_bridge() -> CtypesBridge:
214
+ """``objc_util`` bridge, shipped with Pythonista (iPadOS, iOS).
215
+
216
+ :raises ImportError: outside Pythonista.
217
+ """
218
+ import objc_util
219
+ objc_util.load_framework("Metal")
220
+ return CtypesBridge("objc_util (Pythonista)", objc_class=objc_util.ObjCClass,
221
+ objc_instance=objc_util.ObjCInstance, symbols=objc_util.c)