Coverage for cuda/core/_memoryview.pyx: 90.68%
751 statements
« prev ^ index » next coverage.py v7.18.0, created at 2026-12-03 01:06 +0000
« prev ^ index » next coverage.py v7.18.0, created at 2026-12-03 01:06 +0000
1# SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2#
3# SPDX-License-Identifier: Apache-2.0
5from __future__ import annotations
7cimport cython
8from ._dlpack cimport *
9from ._dlpack import classify_dl_device
10from libc.stdint cimport intptr_t
11from cuda.core._layout cimport _StridedLayout, get_strides_ptr
12from cuda.core._stream import Stream
14import ctypes
15import functools
16import sys
17import warnings
18from collections.abc import Callable # no-cython-lint # used in string annotations below
19from typing import TYPE_CHECKING, Any # no-cython-lint # used in string annotations below
21if TYPE_CHECKING:
22 from cuda.core._tensor_map import TensorMapDescriptorOptions
24import numpy
26from cuda.bindings cimport cydriver
27from cuda.core._rt cimport (
28 EventHandle,
29 create_event_handle_for_stream,
30 as_cu,
31 get_last_error,
32)
34from cuda.core._utils.cuda_utils import handle_return, driver
35from cuda.core._utils.cuda_utils cimport HANDLE_RETURN
38from cuda.core._memory import Buffer
39from cuda.core._memory._buffer cimport Buffer as cyBuffer, Buffer_check_open
42# ---------------------------------------------------------------------------
43# Lazy tensor bridge (avoids loading _tensor_bridge.so until torch is used)
44# ---------------------------------------------------------------------------
46cdef object _tensor_bridge = None
47# Cache: type(obj) -> True/False for the torch tensor check.
48# Once a type is seen, we never re-check.
49cdef dict _torch_type_cache = {}
50cdef object _torch_tensor_type = None
51# Tri-state: None = not checked, True/False = result of version check
52cdef object _torch_version_ok = None
54cdef inline bint _torch_version_check():
55 """Return True if torch >= 2.3. Memoized.
57 Lower bound: AOTI functions we use were introduced in PyTorch 2.3.
59 No upper bound. The dispatch in ``_tensor_bridge.view_as_torch_tensor``
60 selects between two safe paths per torch version:
62 * torch >= 2.14 -- stable PyObject->Tensor C ABI shim
63 (``torch_tensor_from_pyobject`` + ``aoti_torch_delete_tensor_object``);
64 part of torch's stable contract, so any 2.14+ release is covered.
65 * torch 2.3-2.13 -- ``pyobj_to_aten_handle`` pointer-arithmetic trick,
66 validated against the two known THPVariable layouts
67 (``c10::MaybeOwned<at::Tensor>`` for 2.3-2.9; ``at::Tensor`` directly
68 for 2.10-2.13; see ``_get_cdata_extra_offset`` in ``_tensor_bridge.pyx``).
69 """
70 global _torch_version_ok
71 if _torch_version_ok is not None:
72 return <bint>_torch_version_ok
73 torch = sys.modules.get("torch")
74 if torch is None:
75 _torch_version_ok = False
76 return False
77 try:
78 major, minor = int(torch.__version__.split(".")[0]), \
79 int(torch.__version__.split(".")[1])
80 _torch_version_ok = (major, minor) >= (2, 3)
81 except (ValueError, IndexError):
82 _torch_version_ok = False
83 return <bint>_torch_version_ok
86cdef object _get_torch_tensor_type():
87 global _torch_tensor_type
88 cdef object tensor_type
89 with cython.critical_section(_torch_type_cache):
90 tensor_type = _torch_tensor_type
91 if tensor_type is None:
92 torch = sys.modules.get("torch")
93 tensor_type = getattr(torch, "Tensor", None)
94 if tensor_type is None:
95 # Torch may be imported after an earlier protocol-only call.
96 return None
97 # The critical section only protects the check-and-set of the
98 # cached global; the Python-level lookups above run outside it.
99 with cython.critical_section(_torch_type_cache):
100 if _torch_tensor_type is None:
101 _torch_tensor_type = tensor_type
102 else:
103 tensor_type = _torch_tensor_type
104 if not _torch_version_check():
105 return None
106 return tensor_type
109cdef inline bint _is_torch_tensor(object obj):
110 cdef type tp = type(obj) 2bbebhbsb@ , 8 # $ 7 [ ] ^ _ cb% ' ( ) * / : ; = ? N Q R O ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbecVbacUbP g qbrbl Db5 nb9 3 lbTbW X Y Z 0 1 ` . gbibkbpbU V ! jbm d S 2 4 K w x z A B G H I J C D E F y M L s h 6 kce f fcb k n t o p u q r i v hcgc~bc j a ic
111 cdef object cached = _torch_type_cache.get(tp) 2bbebhbsb@ , 8 # $ 7 [ ] ^ _ cb% ' ( ) * / : ; = ? N Q R O ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbecVbacUbP g qbrbl Db5 nb9 3 lbTbW X Y Z 0 1 ` . gbibkbpbU V ! jbm d S 2 4 K w x z A B G H I J C D E F y M L s h 6 kce f fcb k n t o p u q r i v hcgc~bc j a ic
112 if cached is not None: 2bbebhbsb@ , 8 # $ 7 [ ] ^ _ cb% ' ( ) * / : ; = ? N Q R O ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbecVbacUbP g qbrbl Db5 nb9 3 lbTbW X Y Z 0 1 ` . gbibkbpbU V ! jbm d S 2 4 K w x z A B G H I J C D E F y M L s h 6 kce f fcb k n t o p u q r i v hcgc~bc j a ic
113 return <bint>cached 2T bbhbsb@ , 8 # $ 7 [ ] ^ _ cb% ' ( ) * / : ; = ? Q R O ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbecP qbrbl 5 nb9 3 W X Y Z 0 1 ` gbibkbpbU V ! jbm S 2 4 K w x z A B G H I J C D E F y M L s h 6 kce f b k n t o p u q r i v c j a
114 cdef str mod = tp.__module__ or "" 2bbeb, 8 $ cbN VbacUbg l DblbTb. d h e f fcb k i v hcgc~bj a ic
115 cdef object tensor_type
116 cdef bint result = mod.startswith("torch") and hasattr(obj, "data_ptr") 2bbeb, 8 $ cbN VbacUbg l DblbTb. d h e f fcb k i v hcgc~bj a ic
117 if result: 2bbeb, 8 $ cbN VbacUbg l DblbTb. d h e f fcb k i v hcgc~bj a ic
118 tensor_type = _get_torch_tensor_type()
119 # The bridge requires a real Tensor, not just Tensor-like attributes.
120 result = tensor_type is not None and issubclass(tp, tensor_type)
121 _torch_type_cache[tp] = result # setdefault not needed for bools 2bbeb, 8 $ cbN VbacUbg l DblbTb. d h e f fcb k i v hcgc~bj a ic
122 return result 2bbeb, 8 $ cbN VbacUbg l DblbTb. d h e f fcb k i v hcgc~bj a ic
125cdef object _get_tensor_bridge():
126 """Bootstrap AOTI symbols, then import _tensor_bridge on first use."""
127 global _tensor_bridge
128 if _tensor_bridge is not None:
129 return _tensor_bridge
130 torch_C = sys.modules.get("torch._C")
131 if torch_C is None:
132 raise RuntimeError(
133 "torch._C is not loaded; cannot initialise the tensor bridge. "
134 "Make sure PyTorch is imported before passing a torch.Tensor.")
135 ctypes.CDLL(torch_C.__file__, mode=ctypes.RTLD_GLOBAL)
136 from cuda.core import _tensor_bridge as tb
137 _tensor_bridge = tb
138 return _tensor_bridge
141try:
142 from ml_dtypes import bfloat16
143except ImportError:
144 bfloat16 = None
146# TODO(leofang): support NumPy structured dtypes
149cdef extern from "Python.h":
150 ctypedef struct PyTypeObject:
151 void* tp_dict
152 void PyType_Modified(PyTypeObject*)
155cdef DLPackExchangeAPI _SMV_DLPACK_EXCHANGE_API
156cdef bint _SMV_DLPACK_EXCHANGE_API_INITED = False
157_SMV_DLPACK_EXCHANGE_API_CAPSULE = cpython.PyCapsule_New(
158 <void*>&_SMV_DLPACK_EXCHANGE_API,
159 b"dlpack_exchange_api",
160 NULL,
161)
164cdef class StridedMemoryView:
165 """A class holding metadata of a strided dense array/tensor.
167 A :obj:`StridedMemoryView` instance can be created in three ways:
169 1. Using the :obj:`args_viewable_as_strided_memory` decorator (recommended)
170 2. Explicit construction relying on DLPack or CUDA Array Interface, see below.
171 3. From :obj:`~_memory.Buffer` and shape and size tuples (see
172 :meth:`from_buffer` classmethod)
174 ``StridedMemoryView(obj, stream_ptr)`` can be used to create a view from
175 objects supporting either DLPack (up to v1.0) or CUDA Array Interface
176 (CAI) v3. When wrapping an arbitrary object it will try the DLPack protocol
177 first, then the CAI protocol. A :obj:`BufferError` is raised if neither is
178 supported.
180 Since either way would take a consumer stream, for DLPack it is passed to
181 ``obj.__dlpack__()`` as-is (except for :obj:`None`, see below); for CAI, a
182 stream order will be established between the consumer stream and the
183 producer stream (from ``obj.__cuda_array_interface__()["stream"]``), as if
184 ``cudaStreamWaitEvent`` is called by this method.
186 To opt-out of the stream ordering operation in either DLPack or CAI,
187 please pass ``stream_ptr=-1``. Note that this deviates (on purpose)
188 from the semantics of ``obj.__dlpack__(stream=None, ...)`` since ``cuda.core``
189 does not encourage using the (legacy) default/null stream, but is
190 consistent with the CAI's semantics. For DLPack, ``stream=-1`` will be
191 internally passed to ``obj.__dlpack__()`` instead.
193 Parameters
194 ----------
195 obj : Any
196 Any objects that supports either DLPack (up to v1.0) or CUDA Array
197 Interface (v3).
198 stream_ptr: int
199 The pointer address (as Python `int`) to the **consumer** stream.
200 Stream ordering will be properly established unless ``-1`` is passed.
203 Attributes
204 -----------
205 ptr : int
206 Pointer to the tensor buffer (as a Python `int`).
207 device_id : int
208 The device ID for where the tensor is located. It is -1 for CPU tensors
209 (meaning those only accessible from the host).
210 is_device_accessible : bool
211 Whether the tensor data can be accessed on the GPU.
212 readonly: bool
213 Whether the tensor data can be modified in place.
214 exporting_obj : Any
215 A reference to the original tensor object that is being viewed.
216 If the view is created with :meth:`from_buffer`,
217 it will be the Buffer instance passed to the method.
219 """
220 def __init__(self, obj: object = None, stream_ptr: int | None = None) -> None:
221 cdef str clsname = self.__class__.__name__ 2{ | } ~ abmcZbdbfb
222 if obj is not None: 2{ | } ~ abmcZbdbfb
223 # populate self's attributes
224 if check_has_dlpack(obj): 2{ | } ~ abZbdbfb
225 warnings.warn( 2{ | } ~ abdbfb
226 f"Constructing a {clsname} directly from a DLPack-supporting object is deprecated; " 2{ | } ~ abdbfb
227 "Use `StridedMemoryView.from_dlpack` or `StridedMemoryView.from_any_interface` instead.",
228 DeprecationWarning, 2{ | } ~ abdbfb
229 stacklevel=2,
230 )
231 view_as_dlpack(obj, stream_ptr, self) 2{ | } ~ abdbfb
232 else:
233 warnings.warn( 2Zb
234 f"Constructing a {clsname} directly from a CUDA-array-interface-supporting object is deprecated; " 2Zb
235 "Use `StridedMemoryView.from_cuda_array_interface` or `StridedMemoryView.from_any_interface` instead.",
236 DeprecationWarning, 2Zb
237 stacklevel=2,
238 )
239 view_as_cai(obj, stream_ptr, self) 2Zb
240 else:
241 warnings.warn( 2T mc
242 f"Constructing an empty {clsname} is deprecated; " 2mc
243 "use one of the classmethods `from_dlpack`, `from_cuda_array_interface` or `from_any_interface` "
244 "to construct a StridedMemoryView from an object",
245 DeprecationWarning, 2mc
246 stacklevel=2,
247 )
249 @classmethod
250 def from_dlpack(cls, obj: object, stream_ptr: int | None=None) -> StridedMemoryView:
251 """Create a view from an object supporting the `DLPack <https://dmlc.github.io/dlpack/latest/>`_ protocol.
253 Parameters
254 ----------
255 obj : object
256 An object implementing the `DLPack <https://dmlc.github.io/dlpack/latest/>`_ protocol
257 (via ``__dlpack__``).
258 stream_ptr : int, optional
259 Stream pointer for synchronization. If ``None``, no synchronization is performed.
260 """
261 cdef StridedMemoryView buf = StridedMemoryView.__new__(cls) 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? Q R O g qbrbl 5 nb9 3 W X Y Z 0 1 ` . gbibpbU V jbm d K w x z A B G H I J C D E F y M L s h 6 kce f fcb k n t o p u q r i v hcgc~bc j a ic
262 if _is_torch_tensor(obj): 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? Q R O g qbrbl 5 nb9 3 W X Y Z 0 1 ` . gbibpbU V jbm d K w x z A B G H I J C D E F y M L s h 6 kce f fcb k n t o p u q r i v hcgc~bc j a ic
263 _get_tensor_bridge().view_as_torch_tensor(obj, stream_ptr, buf)
264 return buf
265 view_as_dlpack(obj, stream_ptr, buf) 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? Q R O g qbrbl 5 nb9 3 W X Y Z 0 1 ` . gbibpbU V jbm d K w x z A B G H I J C D E F y M L s h 6 kce f fcb k n t o p u q r i v hcgc~bc j a ic
266 return buf 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? Q R O g qbrbl 5 nb9 3 W X Y Z 0 1 ` . gbibpbU V jbm d K w x z A B G H I J C D E F y M L s h 6 e f b k n t o p u q r i v c j a
268 @classmethod
269 def from_cuda_array_interface(cls, obj: object, stream_ptr: int | None=None) -> StridedMemoryView:
270 """Create a view from an object supporting the `__cuda_array_interface__ <https://numba.readthedocs.io/en/stable/cuda/cuda_array_interface.html>`_ protocol.
272 Parameters
273 ----------
274 obj : object
275 An object implementing the `__cuda_array_interface__ <https://numba.readthedocs.io/en/stable/cuda/cuda_array_interface.html>`_ protocol.
276 stream_ptr : int, optional
277 Stream pointer for synchronization. If ``None``, no synchronization is performed.
278 """
279 cdef StridedMemoryView buf = StridedMemoryView.__new__(cls) 2$ 7 [ ] ^ _ cbN VbacUbDblbTb
280 if _is_torch_tensor(obj): 2$ 7 [ ] ^ _ cbN VbacUbDblbTb
281 _get_tensor_bridge().view_as_torch_tensor(obj, stream_ptr, buf)
282 return buf
283 view_as_cai(obj, stream_ptr, buf) 2$ 7 [ ] ^ _ cbN VbacUbDblbTb
284 return buf 2$ 7 [ ] ^ _ cbN VbUbDblb
286 @classmethod
287 def from_array_interface(cls, obj: object) -> StridedMemoryView:
288 """Create a view from an object supporting the `__array_interface__ <https://numpy.org/doc/stable/reference/arrays.interface.html>`_ protocol.
290 Parameters
291 ----------
292 obj : object
293 An object implementing the `__array_interface__ <https://numpy.org/doc/stable/reference/arrays.interface.html>`_ protocol (e.g., a numpy array).
294 """
295 cdef StridedMemoryView buf = StridedMemoryView.__new__(cls) 2ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbecP kb! S 2 4 h e f
296 if _is_torch_tensor(obj): 2ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbecP kb! S 2 4 h e f
297 _get_tensor_bridge().view_as_torch_tensor(obj, None, buf)
298 return buf
299 view_as_array_interface(obj, buf) 2ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbecP kb! S 2 4 h e f
300 return buf 2ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbP kb! S 2 4 h e f
302 @classmethod
303 def from_any_interface(cls, obj: object, stream_ptr: int | None = None) -> StridedMemoryView:
304 """Create a view by automatically selecting the best available protocol.
306 Tries `DLPack <https://dmlc.github.io/dlpack/latest/>`_ first, then falls back to
307 `__cuda_array_interface__ <https://numba.readthedocs.io/en/stable/cuda/cuda_array_interface.html>`_.
308 ``torch.Tensor`` objects are transparently handled via a fast AOTI path
309 regardless of which protocol is selected.
311 Parameters
312 ----------
313 obj : object
314 An object implementing `DLPack <https://dmlc.github.io/dlpack/latest/>`_ or
315 `__cuda_array_interface__ <https://numba.readthedocs.io/en/stable/cuda/cuda_array_interface.html>`_.
316 stream_ptr : int, optional
317 Stream pointer for synchronization. If ``None``, no synchronization is performed.
318 """
319 if check_has_dlpack(obj): 2bbebhbsb@ , 8 # $ 7 [ ] ^ _ cb/ : ; = ? scQ R O qbrbl 5 nb9 3 ` . pbU V jbm K w x z A B G H I J C D E F y M L s b k n t o p u q r i v c j a
320 return cls.from_dlpack(obj, stream_ptr) 2bbebhbsb@ , 8 # / : ; = ? Q R O qbrbl 5 nb9 3 ` . pbU V jbm K w x z A B G H I J C D E F y M L s b k n t o p u q r i v c j a
321 return cls.from_cuda_array_interface(obj, stream_ptr) 2$ 7 [ ] ^ _ cb
323 @classmethod
324 def from_buffer(
325 cls,
326 cyBuffer buffer not None : Buffer,
327 shape : tuple[int, ...],
328 strides : tuple[int, ...] | None = None,
329 *,
330 itemsize : int | None = None,
331 dtype : numpy.dtype | None = None,
332 is_readonly : bool = False
333 ) -> StridedMemoryView:
334 """
335 Creates a :obj:`StridedMemoryView` instance from a :obj:`~_memory.Buffer` and shape and strides tuples.
336 The Buffer can be either allocation coming from a :obj:`MemoryResource` or an external allocation
337 wrapped in a :obj:`~_memory.Buffer` object with ``Buffer.from_handle(ptr, size, owner=...)``.
339 .. caution::
340 When creating a :obj:`StridedMemoryView` from a :obj:`~_memory.Buffer`,
341 no synchronization is performed. It is the user's responsibility to ensure
342 the data in ``buffer`` is properly synchronized when consuming the view.
344 Parameters
345 ----------
346 buffer : :obj:`~_memory.Buffer`
347 The buffer to create the view from.
348 shape : :obj:`tuple`
349 The layout describing the shape, strides and itemsize of the elements in
350 the buffer.
351 strides : :obj:`tuple`
352 The layout describing the shape, strides and itemsize of the elements in
353 the buffer.
354 dtype : :obj:`numpy.dtype`
355 Optional dtype.
356 If specified, the dtype's itemsize must match the layout's itemsize.
357 is_readonly : bool, optional
358 Whether the mark the view as readonly.
359 """
360 cdef StridedMemoryView view = StridedMemoryView.__new__(cls) 2ccdcmbob3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|blcpcncWbXbjcbc+ tbYb-
361 if itemsize is None and dtype is None: 2ccdcmbob3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|blcpcncWbXbjcbc+ tbYb-
362 raise ValueError("Either itemsize or dtype must be specified") 2pc
363 if itemsize is not None and dtype is not None and itemsize != dtype.itemsize: 2ccdcmbob3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|blcncWbXbjcbc+ tbYb-
364 raise ValueError( 2nc
365 f"itemsize ({itemsize}) does not match dtype.itemsize ({dtype.itemsize})" 2T nc
366 )
367 # (itemsize is None XOR dtype is None) OR they are equal
368 view_buffer_strided( 2ccdcmbob3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|blcWbXbjcbc+ tbYb-
369 view,
370 buffer,
371 _StridedLayout(shape=shape, strides=strides, itemsize=getattr(dtype, "itemsize", itemsize)), 2ccdcmbob3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|blcWbXbjcbc+ tbYb-
372 dtype,
373 is_readonly, 2ccdcmbob3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|blcWbXbjcbc+ tbYb-
374 )
375 return view 2ccdcmbob3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|bWbXbbc+ tbYb-
377 def __dealloc__(self) -> None:
378 if self.dl_tensor == NULL: 2T ccdcbbebhbsb@ , mb8 # $ 7 [ ] ^ _ cbob% ' ( ) * / : ; = ? { | } ~ abN Q R O ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbec3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|blcpcncWbXbjcbcVbacUbP g qbrbl + mcZbDbtb5 nb9 3 lbTbW X Y Z 0 1 dbfb` . gbibkbpbU V Yb- }b! jb0b1b2bd S 2 4 K w x z A B G H I J C D E F y M L s h 6 kce f fcb k n t o p u q r i v hcgc~bc j a ic
379 return 2ccdcmb$ 7 [ ] ^ _ cbobN Q R O ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbec3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|blcpcncWbXbjcbcVbacUbP + mcZbDbtbnb9 3 lbTbW X Y Z 0 1 kbYb- ! d S 2 4 h 6 kce f fchcgc~bc ic
381 if cpython.PyCapsule_IsValid( 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 dbfb` . gbibpbU V }bjb0b1b2bd K w x z A B G H I J C D E F y M L s h 6 e f b k n t o p u q r i v c j a
382 self.metadata, DLPACK_VERSIONED_TENSOR_USED_NAME): 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 dbfb` . gbibpbU V }bjb0b1b2bd K w x z A B G H I J C D E F y M L s h 6 e f b k n t o p u q r i v c j a
383 data = cpython.PyCapsule_GetPointer( 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 dbfb` . gbibpbU V }bjb0b1b2bd K w x z A B G H I J C D E F y M L s h 6 e f k n t o p u q r v c j a
384 self.metadata, DLPACK_VERSIONED_TENSOR_USED_NAME) 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 dbfb` . gbibpbU V }bjb0b1b2bd K w x z A B G H I J C D E F y M L s h 6 e f k n t o p u q r v c j a
385 dlm_tensor_ver = <DLManagedTensorVersioned*>data 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 dbfb` . gbibpbU V }bjb0b1b2bd K w x z A B G H I J C D E F y M L s h 6 e f k n t o p u q r v c j a
386 if dlm_tensor_ver.deleter != NULL: 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 dbfb` . gbibpbU V }bjb0b1b2bd K w x z A B G H I J C D E F y M L s h 6 e f k n t o p u q r v c j a
387 dlm_tensor_ver.deleter(dlm_tensor_ver) 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 dbfb` . gbibpbU V jbd K w x z A B G H I J C D E F y M L s h 6 e f k n t o p u q r c j a
388 elif cpython.PyCapsule_IsValid( 1bia
389 self.metadata, DLPACK_TENSOR_USED_NAME): 1bia
390 data = cpython.PyCapsule_GetPointer( 1bia
391 self.metadata, DLPACK_TENSOR_USED_NAME) 1bia
392 dlm_tensor = <DLManagedTensor*>data 1bia
393 if dlm_tensor.deleter != NULL: 1Tbia
394 dlm_tensor.deleter(dlm_tensor) 1ba
396 def view(
397 self, layout : _StridedLayout | None = None, dtype : numpy.dtype | None = None
398 ) -> StridedMemoryView:
399 """
400 Creates a new view with adjusted layout and dtype.
401 Same as calling :meth:`from_buffer` with the current buffer.
402 """
403 cdef StridedMemoryView view = StridedMemoryView.__new__(self.__class__) 2Q R O WbXbnb9 3 W X Y Z 0 1 d 6 c
404 if layout is None and dtype is None: 2Q R O WbXbnb9 3 W X Y Z 0 1 d 6 c
405 return self 2nb
406 if layout is None: 2Q R O WbXb9 3 W X Y Z 0 1 d 6 c
407 layout = self.get_layout() 1QRO93d6c
408 if dtype is None: 2Q R O WbXb9 3 W X Y Z 0 1 d 6 c
409 dtype = self.get_dtype() 2WbXbW X Y Z 0 1
410 view_buffer_strided(view, self.get_buffer(), layout, dtype, self.readonly) 2Q R O WbXb9 3 W X Y Z 0 1 d 6 c
411 return view 2Q R O WbXb3 W X Y Z 0 1 d 6 c
413 def as_tensor_map(
414 self,
415 box_dim: tuple[int, ...] | None = None,
416 *,
417 options: TensorMapDescriptorOptions | None = None,
418 element_strides: tuple[int, ...] | None = None,
419 data_type: object = None,
420 interleave: object = None,
421 swizzle: object = None,
422 l2_promotion: object = None,
423 oob_fill: object = None,
424 ) -> object:
425 """Create a tiled :obj:`TensorMapDescriptor` from this view.
427 This is the public entry point for creating tiled tensor map
428 descriptors in ``cuda.core``. Pass either ``box_dim`` and the
429 individual keyword arguments directly, or provide bundled tiled
430 options via ``options=``.
431 """
432 from cuda.core._tensor_map import TensorMapDescriptor 2, mb8 # $ 7 cbob
434 kwargs = {} 2, mb8 # $ 7 cbob
435 if options is not None: 2T , mb8 # $ 7 cbob
436 kwargs["options"] = options
437 if element_strides is not None: 2, mb8 # $ 7 cbob
438 kwargs["element_strides"] = element_strides 1,8#
439 if data_type is not None: 2, mb8 # $ 7 cbob
440 kwargs["data_type"] = data_type 1,8#$
441 if interleave is not None: 2T , mb8 # $ 7 cbob
442 kwargs["interleave"] = interleave 1,
443 if swizzle is not None: 2, mb8 # $ 7 cbob
444 kwargs["swizzle"] = swizzle 1,
445 if l2_promotion is not None: 2, mb8 # $ 7 cbob
446 kwargs["l2_promotion"] = l2_promotion 1,
447 if oob_fill is not None: 2, mb8 # $ 7 cbob
448 kwargs["oob_fill"] = oob_fill 1,
449 return TensorMapDescriptor._from_tiled(self, box_dim, **kwargs) 2, mb8 # $ 7 cbob
451 def copy_from(
452 self,
453 StridedMemoryView other not None: StridedMemoryView,
454 stream: Stream | None,
455 allocator: object = None,
456 blocking: bool | None = None,
457 ) -> None:
458 """
459 Copies the data from the other view into this view.
461 The copy can be performed between following memory spaces:
462 host-to-device, device-to-host, device-to-device (on the same device).
464 Parameters
465 ----------
466 other : StridedMemoryView
467 The view to copy data from.
468 stream : Stream | None, optional
469 The stream to schedule the copy on.
470 allocator : MemoryResource | None, optional
471 If temporary buffers are needed, the specified memory resources
472 will be used to allocate the memory. If not specified, default
473 resources will be used.
474 blocking : bool | None, optional
475 Whether the call should block until the copy is complete.
476 * ``True``: the ``stream`` is synchronized with the host at the end of the call,
477 blocking until the copy is complete.
478 * ``False``: if possible, the call returns immediately once the copy is scheduled.
479 However, in some cases of host-to-device or device-to-host copies, the call may
480 still synchronize with the host if necessary.
481 * ``None`` (default):
482 * for device-to-device, it defaults to ``False`` (non-blocking),
483 * for host-to-device or device-to-host, it defaults to ``True`` (blocking).
484 """
485 raise NotImplementedError("Sorry, not supported: copy_from") 2qb
487 def copy_to(
488 self,
489 StridedMemoryView other not None: StridedMemoryView,
490 stream: Stream | None = None,
491 allocator: object = None,
492 blocking: bool | None = None,
493 ) -> None:
494 """
495 Copies the data from this view into the ``other`` view.
497 For details, see :meth:`copy_from`.
498 """
499 raise NotImplementedError("Sorry, not supported: copy_to") 2rb
501 def __dlpack__(
502 self,
503 *,
504 stream: int | None = None,
505 max_version: tuple[int, int] | None = None,
506 dl_device: tuple[int, int] | None = None,
507 copy: bool | None = None,
508 ) -> object:
509 # Similar to Buffer.__dlpack__: no implicit synchronization is performed.
510 if dl_device is not None: 2hbN Q R O P g l + d S 2 4 K w x z A B G H I J C D E F y M L s h e f b k n t o p u q r i v c j a
511 raise BufferError("Sorry, not supported: dl_device other than None") 2hb
512 if copy is True: 2hbN Q R O P g l + d S 2 4 K w x z A B G H I J C D E F y M L s h e f b k n t o p u q r i v c j a
513 raise BufferError("Sorry, not supported: copy=True") 2hb
515 cdef bint versioned
516 if max_version is None: 2hbN Q R O P g l + d S 2 4 K w x z A B G H I J C D E F y M L s h e f b k n t o p u q r i v c j a
517 versioned = False 1NQRO+Lbia
518 else:
519 if not isinstance(max_version, tuple) or len(max_version) != 2: 2hbP g l d S 2 4 K w x z A B G H I J C D E F y M s h e f b k n t o p u q r v c j a
520 raise BufferError(f"Expected max_version tuple[int, int], got {max_version}") 2hb
521 versioned = max_version >= (1, 0) 1PgldS24KwxzABGHIJCDEFyMshefbkntopuqrvcja
523 # NOTE: stream is accepted for protocol compatibility but not used.
524 cdef object capsule = _smv_make_py_capsule(self, versioned) 1NQROPgl+dS24KwxzABGHIJCDEFyMLshefbkntopuqrivcja
525 return capsule 1NPgldSKwxzABGHIJCDEFyMLshefbkntopuqrivcja
527 def __dlpack_device__(self) -> tuple[int, int]:
528 cdef _DLDeviceType device_type
529 cdef int32_t device_id
530 _smv_get_dl_device(self, &device_type, &device_id) 2bbebmb8 # $ 7 [ ] ^ _ obN l S h e f b k n t o p u q r i v c j a
531 return (<int>device_type, int(device_id)) 2bbebmb8 # $ 7 [ ] ^ _ obN l S h e f b k n t o p u q r i v c j a
533 @property
534 def _layout(self) -> _StridedLayout:
535 """
536 The layout of the tensor. For StridedMemoryView created from DLPack or CAI,
537 the layout is inferred from the tensor object's metadata.
538 """
539 return self.get_layout() 23b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|bWbXbmc3 W X Y Z 0 1
541 @property
542 def size(self) -> int:
543 return self.get_layout().get_volume() 2% ' ( ) * / : ; = ? { | } ~ abubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbVb
545 @property
546 def shape(self) -> tuple[int, ...]:
547 """
548 Shape of the tensor.
549 """
550 return self.get_layout().get_shape_tuple() 2ccdc@ % ' ( ) * / : ; = ? { | } ~ abubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCb3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|bWbXbVbUbP g ZbDbtb5 lbW X Y Z 0 1 dbfb` . gbibm b k c j
552 @property
553 def strides(self) -> tuple[int, ...] | None:
554 """
555 Strides of the tensor (in **counts**, not bytes).
556 """
557 return self.get_layout().get_strides_tuple() 2@ % ' ( ) * / : ; = ? { | } ~ abubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCb3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|bVbUbP g tb5
559 @property
560 def dtype(self) -> numpy.dtype | None:
561 """
562 Data type of the tensor.
564 Supports standard NumPy dtypes as well as narrow data types (e.g., ``bfloat16``)
565 when the optional `ml_dtypes <https://github.com/jax-ml/ml_dtypes>`_ package is
566 installed. If ``ml_dtypes`` is not available and such a tensor is encountered,
567 a :obj:`NotImplementedError` will be raised.
568 """
569 return self.get_dtype() 2ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCb3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|bbcP g tb5 3 W X Y Z 0 1 d 2 4 n t o p u q r
571 def __repr__(self) -> str:
572 return (f"StridedMemoryView(ptr={self.ptr},\n" 2P g tb5
573 + f" shape={self.shape},\n" 2P g tb5
574 + f" strides={self.strides},\n" 2P g tb5
575 + f" itemsize={self._layout.itemsize},\n" 2P g tb5
576 + f" dtype={get_simple_repr(self.dtype)},\n" 2P g tb5
577 + f" device_id={self.device_id},\n" 2P g tb5
578 + f" is_device_accessible={self.is_device_accessible},\n" 2P g tb5
579 + f" readonly={self.readonly},\n" 2P g tb5
580 + f" exporting_obj={get_simple_repr(self.exporting_obj)})") 2P g tb5
582 @cython.critical_section
583 cdef inline _StridedLayout get_layout(self):
584 cdef _StridedLayout layout
585 if self._layout is None: 2ccdc@ 8 # $ 7 [ ] ^ _ cbob% ' ( ) * / : ; = ? { | } ~ abN Q R O ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbec3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|bWbXbVbacUbP g l + mcZbDbtb5 9 3 lbTbW X Y Z 0 1 dbfb` . gbibkbU V Yb- ! m d S 2 4 K w x z A B G H I J C D E F y M L s h 6 e f b k n t o p u q r i v c j a
586 if self.dl_tensor: 2@ 8 # $ 7 [ ] ^ _ cb% ' ( ) * / : ; = ? { | } ~ abN Q R O ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbecVbacUbP g l mcZbDb5 9 3 lbTbW X Y Z 0 1 dbfb` . gbibkbU V ! m d S 2 4 K w x z A B G H I J C D E F y M L s h 6 e f b k n t o p u q r i v c j a
587 layout = layout_from_dlpack(self.dl_tensor) 2T @ 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g l 5 9 3 W X Y Z 0 1 dbfb` . gbibU V m d K w x z A B G H I J C D E F y M L s 6 e f b k n t o p u q r i v c j a
588 elif self.metadata is not None: 2$ 7 [ ] ^ _ cbN ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbecVbacUbP mcZbDblbTbkb! S 2 4 h e f
589 layout = layout_from_cai(self.metadata) 2$ 7 [ ] ^ _ cbN ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbecVbacUbP ZbDblbTbkb! S 2 4 h e f
590 else:
591 raise ValueError("Cannot infer layout from the exporting object") 2T mc
592 if self._layout is None: 2@ 8 # $ 7 [ ] ^ _ cb% ' ( ) * / : ; = ? { | } ~ abN Q R O ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbVbUbP g l ZbDb5 9 3 lbTbW X Y Z 0 1 dbfb` . gbibkbU V ! m d S 2 4 K w x z A B G H I J C D E F y M L s h 6 e f b k n t o p u q r i v c j a
593 self._layout = layout 2@ 8 # $ 7 [ ] ^ _ cb% ' ( ) * / : ; = ? { | } ~ abN Q R O ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbVbUbP g l ZbDb5 9 3 lbTbW X Y Z 0 1 dbfb` . gbibkbU V ! m d S 2 4 K w x z A B G H I J C D E F y M L s h 6 e f b k n t o p u q r i v c j a
594 return self._layout 2ccdc@ 8 # $ 7 [ ] ^ _ cbob% ' ( ) * / : ; = ? { | } ~ abN Q R O ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCb3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|bWbXbVbUbP g l + ZbDbtb5 9 3 lbTbW X Y Z 0 1 dbfb` . gbibkbU V Yb- ! m d S 2 4 K w x z A B G H I J C D E F y M L s h 6 e f b k n t o p u q r i v c j a
596 cdef inline object get_buffer(self):
597 """
598 Returns Buffer instance with the underlying data.
599 If the SMV was created from a Buffer, it will return the same Buffer instance.
600 If the SMV was imported via DLPack, it will return a new instance owned by this view.
601 Otherwise, it will create a new instance with owner set to the exporting object.
602 """
603 cdef object buffer
604 with cython.critical_section(self): 2mb$ 7 [ ] ^ _ obN Q R O WbXb9 3 W X Y Z 0 1 d 6 c
605 buffer = self._buffer 2mb$ 7 [ ] ^ _ obN Q R O WbXb9 3 W X Y Z 0 1 d 6 c
606 if buffer is None: 2mb$ 7 [ ] ^ _ obN Q R O WbXb9 3 W X Y Z 0 1 d 6 c
607 if isinstance(self.exporting_obj, Buffer): 1$7[]^_NQRO93WXYZ01d6c
608 buffer = self.exporting_obj 16
609 elif self.dl_tensor != NULL: 1T$7[]^_NQRO93WXYZ01dc
610 # This view holds the consumed capsule and calls its deleter in
611 # __dealloc__; the exporting object need not keep the memory alive.
612 # Not cached: a cached Buffer owned by self would form a cycle.
613 return Buffer.from_handle(self.ptr, 0, owner=self) 1TQRO93WXYZ01dc
614 else:
615 buffer = Buffer.from_handle(self.ptr, 0, owner=self.exporting_obj) 1$7[]^_N
616 with cython.critical_section(self): 1$7[]^_N6
617 if self._buffer is None: 1$7[]^_N6
618 self._buffer = buffer 1$7[]^_N6
619 else:
620 buffer = self._buffer
621 return buffer 2T mb$ 7 [ ] ^ _ obN WbXb6
623 cdef inline object get_dtype(self):
624 cdef object dtype
625 with cython.critical_section(self): 2mb7 obN Q R O ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCb3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|bWbXbbcP g l + tb5 3 W X Y Z 0 1 kbU V Yb- ! m d S 2 4 K w x z A B G H I J C D E F y M L s h e f b k n t o p u q r i v c j a
626 dtype = self._dtype 2mb7 obN Q R O ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCb3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|bWbXbbcP g l + tb5 3 W X Y Z 0 1 kbU V Yb- ! m d S 2 4 K w x z A B G H I J C D E F y M L s h e f b k n t o p u q r i v c j a
627 if dtype is None: 2mb7 obN Q R O ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCb3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|bWbXbbcP g l + tb5 3 W X Y Z 0 1 kbU V Yb- ! m d S 2 4 K w x z A B G H I J C D E F y M L s h e f b k n t o p u q r i v c j a
628 if self.dl_tensor != NULL: 2mb7 N ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbP g l + tb5 W X Y Z 0 1 kbU V Yb- ! m d S 2 4 K w x z A B G H I J C D E F y M L s h e f b k n t o p u q r i v c j a
629 dtype = dtype_dlpack_to_numpy(&self.dl_tensor.dtype) 1gl5WXYZ01UVmdKwxzABGHIJCDEFyMLsefbkntopuqrivcja
630 elif isinstance(self.metadata, int): 2mb7 N ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbP + tbkbYb- ! S 2 4 h e f
631 # AOTI dtype code stored by the torch tensor bridge
632 dtype = _get_tensor_bridge().resolve_aoti_dtype(
633 self.metadata)
634 elif self.metadata is not None: 2mb7 N ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbP + tbkbYb- ! S 2 4 h e f
635 dtype = _typestr2dtype(self.metadata["typestr"]) 27 N ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbP kb! S 2 4 h e f
636 with cython.critical_section(self): 2mb7 N ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbP g l + tb5 W X Y Z 0 1 kbU V Yb- ! m d S 2 4 K w x z A B G H I J C D E F y M L s h e f b k n t o p u q r i v c j a
637 if self._dtype is None: 2mb7 N ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbP g l + tb5 W X Y Z 0 1 kbU V Yb- ! m d S 2 4 K w x z A B G H I J C D E F y M L s h e f b k n t o p u q r i v c j a
638 self._dtype = dtype 2mb7 N ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbP g l + tb5 W X Y Z 0 1 kbU V Yb- ! m d S 2 4 K w x z A B G H I J C D E F y M L s h e f b k n t o p u q r i v c j a
639 else:
640 dtype = self._dtype
641 return dtype 2mb7 obN Q R O ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCb3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|bWbXbbcP g l + tb5 3 W X Y Z 0 1 kbU V Yb- ! m d S 2 4 K w x z A B G H I J C D E F y M L s h e f b k n t o p u q r i v c j a
644cdef void _smv_pycapsule_deleter(object capsule) noexcept:
645 cdef DLManagedTensor* dlm_tensor
646 cdef DLManagedTensorVersioned* dlm_tensor_ver
647 # Do not invoke the deleter on a used capsule.
648 if cpython.PyCapsule_IsValid(capsule, DLPACK_TENSOR_UNUSED_NAME): 2T N P g l }b0b1b2bd S K w x z A B G H I J C D E F y M L s h e f b k n t o p u q r c j a
649 dlm_tensor = <DLManagedTensor*>( 1NL
650 cpython.PyCapsule_GetPointer(capsule, DLPACK_TENSOR_UNUSED_NAME) 1NL
651 )
652 if dlm_tensor.deleter: 1NL
653 dlm_tensor.deleter(dlm_tensor) 1NL
654 elif cpython.PyCapsule_IsValid(capsule, DLPACK_VERSIONED_TENSOR_UNUSED_NAME): 2P g l }b0b1b2bd S K w x z A B G H I J C D E F y M s h e f b k n t o p u q r c j a
655 dlm_tensor_ver = <DLManagedTensorVersioned*>( 1s
656 cpython.PyCapsule_GetPointer(capsule, DLPACK_VERSIONED_TENSOR_UNUSED_NAME) 1s
657 )
658 if dlm_tensor_ver.deleter: 1s
659 dlm_tensor_ver.deleter(dlm_tensor_ver) 1s
662cdef inline void _smv_release_export_resources(void* manager_ctx, int64_t* shape_ptr) noexcept with gil:
663 if shape_ptr: 1NQROPgl+-!dS24KwxzABGHIJCDEFyMLshefbkntopuqrivcja
664 stdlib.free(shape_ptr) 1NPgldSKwxzABGHIJCDEFyLshefbkntopuqrivcja
665 if manager_ctx: 1NQROPgl+-!dS24KwxzABGHIJCDEFyMLshefbkntopuqrivcja
666 cpython.Py_DECREF(<object>manager_ctx) 1NQROPgl+-!dS24KwxzABGHIJCDEFyMLshefbkntopuqrivcja
669cdef void _smv_deleter(DLManagedTensor* tensor) noexcept with gil:
670 if tensor: 1NQRO+24Lbia
671 _smv_release_export_resources(tensor.manager_ctx, tensor.dl_tensor.shape) 1NQRO+Lbia
672 tensor.manager_ctx = NULL 1NQRO+Lbia
673 stdlib.free(tensor) 1TNQRO+Lbia
676cdef void _smv_versioned_deleter(DLManagedTensorVersioned* tensor) noexcept with gil:
677 if tensor: 1QROPgl+-!dS24KwxzABGHIJCDEFyMshefbkntopuqrvcja
678 _smv_release_export_resources(tensor.manager_ctx, tensor.dl_tensor.shape) 1TPgl-!dS24KwxzABGHIJCDEFyMshefbkntopuqrvcja
679 tensor.manager_ctx = NULL 1Pgl-!dS24KwxzABGHIJCDEFyMshefbkntopuqrvcja
680 stdlib.free(tensor) 1Pgl-!dS24KwxzABGHIJCDEFyMshefbkntopuqrvcja
683cdef inline DLManagedTensorVersioned* _smv_allocate_dlm_tensor_versioned() except? NULL:
684 cdef DLManagedTensorVersioned* dlm_tensor_ver = NULL 1Pgl-!mdS24KwxzABGHIJCDEFyMshefbkntopuqrvcja
685 dlm_tensor_ver = <DLManagedTensorVersioned*>stdlib.malloc(sizeof(DLManagedTensorVersioned)) 1Pgl-!mdS24KwxzABGHIJCDEFyMshefbkntopuqrvcja
686 if dlm_tensor_ver == NULL: 1Pgl-!mdS24KwxzABGHIJCDEFyMshefbkntopuqrvcja
687 raise MemoryError()
688 dlm_tensor_ver.dl_tensor.shape = NULL 1Pgl-!mdS24KwxzABGHIJCDEFyMshefbkntopuqrvcja
689 dlm_tensor_ver.manager_ctx = NULL 1Pgl-!mdS24KwxzABGHIJCDEFyMshefbkntopuqrvcja
690 return dlm_tensor_ver 1Pgl-!mdS24KwxzABGHIJCDEFyMshefbkntopuqrvcja
693cdef inline DLManagedTensor* _smv_allocate_dlm_tensor() except? NULL:
694 cdef DLManagedTensor* dlm_tensor = NULL 1NQRO+Lbia
695 dlm_tensor = <DLManagedTensor*>stdlib.malloc(sizeof(DLManagedTensor)) 1NQRO+Lbia
696 if dlm_tensor == NULL: 1NQRO+Lbia
697 raise MemoryError()
698 dlm_tensor.dl_tensor.shape = NULL 1NQRO+Lbia
699 dlm_tensor.manager_ctx = NULL 1NQRO+Lbia
700 return dlm_tensor 1NQRO+Lbia
703cdef inline int _smv_dtype_numpy_to_dlpack(object dtype_obj, DLDataType* out_dtype) except -1:
704 cdef object np_dtype = numpy.dtype(dtype_obj) 2N Q R O P g l kbU V ! m d S 2 4 K w x z A B G H I J C D E F y M L s h e f b k n t o p u q r i v c j a
705 if np_dtype.fields is not None: 2N Q R O P g l kbU V ! m d S 2 4 K w x z A B G H I J C D E F y M L s h e f b k n t o p u q r i v c j a
706 raise BufferError("Structured dtypes are not supported for DLPack export") 1R
707 if not np_dtype.isnative and np_dtype.byteorder not in ("=", "|"): 2N Q O P g l kbU V ! m d S 2 4 K w x z A B G H I J C D E F y M L s h e f b k n t o p u q r i v c j a
708 raise BufferError("Non-native-endian dtypes are not supported for DLPack export") 2Q kb!
710 cdef str kind = np_dtype.kind 1NOPglUVmdS24KwxzABGHIJCDEFyMLshefbkntopuqrivcja
711 cdef int bits = np_dtype.itemsize * 8 1NOPglUVmdS24KwxzABGHIJCDEFyMLshefbkntopuqrivcja
712 cdef uint8_t code
713 if kind == "b": 1NOPglUVmdS24KwxzABGHIJCDEFyMLshefbkntopuqrivcja
714 if bits != 8: 1K
715 raise BufferError(f"Unsupported bool dtype itemsize: {np_dtype.itemsize}")
716 code = <uint8_t>kDLBool 1K
717 elif kind == "i": 1NOPglUVmdS24wxzABGHIJCDEFyMLshefbkntopuqrivcja
718 if bits not in (8, 16, 32, 64): 1PglUVdSGHIJLshbkntopuqrivcja
719 raise BufferError(f"Unsupported signed integer dtype: {np_dtype}")
720 code = <uint8_t>kDLInt 1PglUVdSGHIJLshbkntopuqrivcja
721 elif kind == "u": 1NOm24wxzABCDEFyMef
722 if bits not in (8, 16, 32, 64): 1CDEF
723 raise BufferError(f"Unsupported unsigned integer dtype: {np_dtype}")
724 code = <uint8_t>kDLUInt 1CDEF
725 elif kind == "f": 1NOm24wxzAByMef
726 if bits not in (16, 32, 64): 1Nm4zABef
727 raise BufferError(f"Unsupported floating dtype: {np_dtype}") 14
728 code = <uint8_t>kDLFloat 1NmzABef
729 elif kind == "c": 1O2wxyM
730 if bits not in (64, 128): 12wxyM
731 raise BufferError(f"Unsupported complex dtype: {np_dtype}") 12
732 code = <uint8_t>kDLComplex 1wxyM
733 elif np_dtype.type is bfloat16: 1O
734 # ml_dtypes bfloat16 has kind "V", so the kind chain cannot reach it;
735 # the byte-order check above has already run for it.
736 code = <uint8_t>kDLBfloat
737 else:
738 raise BufferError(f"Unsupported dtype for DLPack export: {np_dtype}") 1O
740 out_dtype.code = code 1NPglUVmdSKwxzABGHIJCDEFyMLshefbkntopuqrivcja
741 out_dtype.bits = <uint8_t>bits 1NPglUVmdSKwxzABGHIJCDEFyMLshefbkntopuqrivcja
742 out_dtype.lanes = <uint16_t>1 1NPglUVmdSKwxzABGHIJCDEFyMLshefbkntopuqrivcja
743 return 0 1NPglUVmdSKwxzABGHIJCDEFyMLshefbkntopuqrivcja
746cdef inline int _smv_get_dl_device(
747 StridedMemoryView view,
748 _DLDeviceType* out_device_type,
749 int32_t* out_device_id,
750) except -1:
751 cdef _DLDeviceType device_type
752 cdef int32_t device_id
753 cdef object buf
754 if view.dl_tensor != NULL: 2bbebmb8 # $ 7 [ ] ^ _ obN P g l U V m d S K w x z A B G H I J C D E F y M L s h e f b k n t o p u q r i v c j a
755 device_type = view.dl_tensor.device.device_type 2bbeb8 # g l U V m K w x z A B G H I J C D E F y M L s e f b k n t o p u q r i v c j a
756 if device_type == _kDLCUDA: 2bbeb8 # g l U V m K w x z A B G H I J C D E F y M L s e f b k n t o p u q r i v c j a
757 device_id = view.dl_tensor.device.device_id 18#
758 else:
759 # CPU, CUDAHost, and CUDAManaged use device_id=0 in DLPack.
760 device_id = 0 2bbebg l U V m K w x z A B G H I J C D E F y M L s e f b k n t o p u q r i v c j a
761 elif view.is_device_accessible: 2mb$ 7 [ ] ^ _ obN P d S h e f
762 buf = view.get_buffer() 2mb$ 7 [ ] ^ _ obN
763 dev_type, dev_id = classify_dl_device(buf) 2mb$ 7 [ ] ^ _ obN
764 device_type = <_DLDeviceType>dev_type 2mb$ 7 [ ] ^ _ obN
765 device_id = <int32_t>dev_id 2mb$ 7 [ ] ^ _ obN
766 else:
767 device_type = _kDLCPU 1PdShef
768 device_id = 0 1PdShef
770 out_device_type[0] = device_type 2bbebmb8 # $ 7 [ ] ^ _ obN P g l U V m d S K w x z A B G H I J C D E F y M L s h e f b k n t o p u q r i v c j a
771 out_device_id[0] = device_id 2bbebmb8 # $ 7 [ ] ^ _ obN P g l U V m d S K w x z A B G H I J C D E F y M L s h e f b k n t o p u q r i v c j a
772 return 0 2bbebmb8 # $ 7 [ ] ^ _ obN P g l U V m d S K w x z A B G H I J C D E F y M L s h e f b k n t o p u q r i v c j a
775cdef inline int _smv_setup_dl_tensor_common(
776 DLTensor* dl_tensor,
777 StridedMemoryView view,
778 _StridedLayout layout,
779) except -1:
780 cdef object dtype_obj = view.get_dtype() 2N Q R O P g l + kbU V Yb- ! m d S 2 4 K w x z A B G H I J C D E F y M L s h e f b k n t o p u q r i v c j a
781 if dtype_obj is None: 2N Q R O P g l + kbU V Yb- ! m d S 2 4 K w x z A B G H I J C D E F y M L s h e f b k n t o p u q r i v c j a
782 raise BufferError( 2+ Yb-
783 "Cannot export StridedMemoryView via DLPack without dtype information; "
784 "create the view with dtype specified."
785 )
786 _smv_dtype_numpy_to_dlpack(dtype_obj, &dl_tensor.dtype) 2N Q R O P g l kbU V ! m d S 2 4 K w x z A B G H I J C D E F y M L s h e f b k n t o p u q r i v c j a
787 _smv_get_dl_device(view, &dl_tensor.device.device_type, &dl_tensor.device.device_id) 1NPglUVmdSKwxzABGHIJCDEFyMLshefbkntopuqrivcja
789 cdef int ndim = layout.base.ndim 1NPglUVmdSKwxzABGHIJCDEFyMLshefbkntopuqrivcja
790 dl_tensor.ndim = ndim 1NPglUVmdSKwxzABGHIJCDEFyMLshefbkntopuqrivcja
791 if layout.get_volume() == 0: 1NPglUVmdSKwxzABGHIJCDEFyMLshefbkntopuqrivcja
792 dl_tensor.data = NULL 1y
793 else:
794 dl_tensor.data = <void*><intptr_t>view.ptr 1NPglUVmdSKwxzABGHIJCDEFMLshefbkntopuqrivcja
795 dl_tensor.byte_offset = 0 1NPglUVmdSKwxzABGHIJCDEFyMLshefbkntopuqrivcja
796 return 0 1NPglUVmdSKwxzABGHIJCDEFyMLshefbkntopuqrivcja
799cdef inline int _smv_setup_dl_tensor(DLTensor* dl_tensor, StridedMemoryView view) except -1:
800 cdef _StridedLayout layout = view.get_layout() 1NQROPgl+-!mdS24KwxzABGHIJCDEFyMLshefbkntopuqrivcja
801 _smv_setup_dl_tensor_common(dl_tensor, view, layout) 1NQROPgl+-!mdS24KwxzABGHIJCDEFyMLshefbkntopuqrivcja
803 cdef int i
804 cdef int64_t* shape_strides = NULL 1NPglmdSKwxzABGHIJCDEFyMLshefbkntopuqrivcja
805 cdef int64_t* strides_src = NULL 1NPglmdSKwxzABGHIJCDEFyMLshefbkntopuqrivcja
806 cdef int ndim = dl_tensor.ndim 1NPglmdSKwxzABGHIJCDEFyMLshefbkntopuqrivcja
807 if ndim == 0: 1NPglmdSKwxzABGHIJCDEFyMLshefbkntopuqrivcja
808 dl_tensor.shape = NULL 1M
809 dl_tensor.strides = NULL 1M
810 else:
811 # DLPack v1.2+ requires non-NULL strides for ndim != 0.
812 shape_strides = <int64_t*>stdlib.malloc(sizeof(int64_t) * 2 * ndim) 1NPglmdSKwxzABGHIJCDEFyLshefbkntopuqrivcja
813 if shape_strides == NULL: 1NPglmdSKwxzABGHIJCDEFyLshefbkntopuqrivcja
814 raise MemoryError()
815 try: 1NPglmdSKwxzABGHIJCDEFyLshefbkntopuqrivcja
816 strides_src = get_strides_ptr(layout.base) 1NPglmdSKwxzABGHIJCDEFyLshefbkntopuqrivcja
817 for i in range(ndim): 1NPglmdSKwxzABGHIJCDEFyLshefbkntopuqrivcja
818 shape_strides[i] = layout.base.shape[i] 1NPglmdSKwxzABGHIJCDEFyLshefbkntopuqrivcja
819 shape_strides[i + ndim] = strides_src[i] 1NPglmdSKwxzABGHIJCDEFyLshefbkntopuqrivcja
820 except Exception:
821 stdlib.free(shape_strides)
822 raise
823 dl_tensor.shape = shape_strides 1NPglmdSKwxzABGHIJCDEFyLshefbkntopuqrivcja
824 dl_tensor.strides = shape_strides + ndim 1NPglmdSKwxzABGHIJCDEFyLshefbkntopuqrivcja
825 return 0 1NPglmdSKwxzABGHIJCDEFyMLshefbkntopuqrivcja
828cdef inline int _smv_setup_dltensor_borrowed(DLTensor* dl_tensor, StridedMemoryView view) except -1:
829 cdef _StridedLayout layout = view.get_layout() 2kbU V Yb
830 _smv_setup_dl_tensor_common(dl_tensor, view, layout) 2kbU V Yb
832 if dl_tensor.ndim == 0: 1UV
833 dl_tensor.shape = NULL 1U
834 dl_tensor.strides = NULL 1U
835 else:
836 dl_tensor.shape = layout.base.shape 1V
837 # For temporary/non-owning exchange we provide explicit strides.
838 dl_tensor.strides = get_strides_ptr(layout.base) 1V
839 return 0 1UV
842cdef inline int _smv_fill_managed_tensor_versioned(
843 DLManagedTensorVersioned* dlm_tensor_ver,
844 StridedMemoryView view,
845) except -1:
846 cpython.Py_INCREF(view) 1Pgl-!mdS24KwxzABGHIJCDEFyMshefbkntopuqrvcja
847 dlm_tensor_ver.manager_ctx = <void*>view 1Pgl-!mdS24KwxzABGHIJCDEFyMshefbkntopuqrvcja
848 dlm_tensor_ver.deleter = _smv_versioned_deleter 1Pgl-!mdS24KwxzABGHIJCDEFyMshefbkntopuqrvcja
849 dlm_tensor_ver.version.major = DLPACK_MAJOR_VERSION 1Pgl-!mdS24KwxzABGHIJCDEFyMshefbkntopuqrvcja
850 dlm_tensor_ver.version.minor = DLPACK_MINOR_VERSION 1Pgl-!mdS24KwxzABGHIJCDEFyMshefbkntopuqrvcja
851 dlm_tensor_ver.flags = DLPACK_FLAG_BITMASK_READ_ONLY if view.readonly else 0 1Pgl-!mdS24KwxzABGHIJCDEFyMshefbkntopuqrvcja
852 _smv_setup_dl_tensor(&dlm_tensor_ver.dl_tensor, view) 1Pgl-!mdS24KwxzABGHIJCDEFyMshefbkntopuqrvcja
853 return 0 1PglmdSKwxzABGHIJCDEFyMshefbkntopuqrvcja
856cdef inline int _smv_fill_managed_tensor(
857 DLManagedTensor* dlm_tensor,
858 StridedMemoryView view,
859) except -1:
860 cpython.Py_INCREF(view) 1NQRO+Lbia
861 dlm_tensor.manager_ctx = <void*>view 1NQRO+Lbia
862 dlm_tensor.deleter = _smv_deleter 1NQRO+Lbia
863 _smv_setup_dl_tensor(&dlm_tensor.dl_tensor, view) 1NQRO+Lbia
864 return 0 1NLbia
867cdef object _smv_make_py_capsule(StridedMemoryView view, bint versioned):
868 cdef DLManagedTensor* dlm_tensor = NULL 1NQROPgl+dS24KwxzABGHIJCDEFyMLshefbkntopuqrivcja
869 cdef DLManagedTensorVersioned* dlm_tensor_ver = NULL 1NQROPgl+dS24KwxzABGHIJCDEFyMLshefbkntopuqrivcja
870 cdef object capsule = None 1NQROPgl+dS24KwxzABGHIJCDEFyMLshefbkntopuqrivcja
871 cdef void* tensor_ptr = NULL 1NQROPgl+dS24KwxzABGHIJCDEFyMLshefbkntopuqrivcja
872 cdef const char* capsule_name
873 try: 1NQROPgl+dS24KwxzABGHIJCDEFyMLshefbkntopuqrivcja
874 if versioned: 1NQROPgl+dS24KwxzABGHIJCDEFyMLshefbkntopuqrivcja
875 dlm_tensor_ver = _smv_allocate_dlm_tensor_versioned() 1PgldS24KwxzABGHIJCDEFyMshefbkntopuqrvcja
876 _smv_fill_managed_tensor_versioned(dlm_tensor_ver, view) 1PgldS24KwxzABGHIJCDEFyMshefbkntopuqrvcja
877 tensor_ptr = <void*>dlm_tensor_ver 1PgldSKwxzABGHIJCDEFyMshefbkntopuqrvcja
878 capsule_name = DLPACK_VERSIONED_TENSOR_UNUSED_NAME 1PgldSKwxzABGHIJCDEFyMshefbkntopuqrvcja
879 else:
880 dlm_tensor = _smv_allocate_dlm_tensor() 1NQRO+Lbia
881 _smv_fill_managed_tensor(dlm_tensor, view) 1NQRO+Lbia
882 tensor_ptr = <void*>dlm_tensor 1NLbia
883 capsule_name = DLPACK_TENSOR_UNUSED_NAME 1NLbia
884 capsule = cpython.PyCapsule_New(tensor_ptr, capsule_name, _smv_pycapsule_deleter) 1NPgldSKwxzABGHIJCDEFyMLshefbkntopuqrivcja
885 except Exception: 1QRO+24
886 if capsule is None: 1QRO+24
887 _smv_deleter(dlm_tensor) 1QRO+24
888 _smv_versioned_deleter(dlm_tensor_ver) 1QRO+24
889 raise 1QRO+24
890 return capsule 1NPgldSKwxzABGHIJCDEFyMLshefbkntopuqrivcja
893cdef inline StridedMemoryView _smv_from_dlpack_capsule(object capsule, object exporting_obj):
894 cdef void* data = NULL 2}bm 0b1b2b
895 cdef DLTensor* dl_tensor = NULL 2}bm 0b1b2b
896 cdef DLManagedTensorVersioned* dlm_tensor_ver = NULL 2}bm 0b1b2b
897 cdef DLManagedTensor* dlm_tensor = NULL 2}bm 0b1b2b
898 cdef bint is_readonly = False 2}bm 0b1b2b
899 cdef const char* used_name = NULL 2}bm 0b1b2b
900 if cpython.PyCapsule_IsValid(capsule, DLPACK_VERSIONED_TENSOR_UNUSED_NAME): 2}bm 0b1b2b
901 data = cpython.PyCapsule_GetPointer(capsule, DLPACK_VERSIONED_TENSOR_UNUSED_NAME) 2}bm 0b1b2b
902 dlm_tensor_ver = <DLManagedTensorVersioned*>data 2}bm 0b1b2b
903 dl_tensor = &dlm_tensor_ver.dl_tensor 2}bm 0b1b2b
904 is_readonly = bool((dlm_tensor_ver.flags & DLPACK_FLAG_BITMASK_READ_ONLY) != 0) 2}bm 0b1b2b
905 used_name = DLPACK_VERSIONED_TENSOR_USED_NAME 2}bm 0b1b2b
906 elif cpython.PyCapsule_IsValid(capsule, DLPACK_TENSOR_UNUSED_NAME):
907 data = cpython.PyCapsule_GetPointer(capsule, DLPACK_TENSOR_UNUSED_NAME)
908 dlm_tensor = <DLManagedTensor*>data
909 dl_tensor = &dlm_tensor.dl_tensor
910 is_readonly = False
911 used_name = DLPACK_TENSOR_USED_NAME
912 else:
913 raise BufferError("Invalid DLPack capsule")
915 cpython.PyCapsule_SetName(capsule, used_name) 2}bm 0b1b2b
917 cdef StridedMemoryView view = StridedMemoryView.__new__(StridedMemoryView) 2}bm 0b1b2b
918 view.dl_tensor = dl_tensor 2}bm 0b1b2b
919 view.metadata = capsule 2}bm 0b1b2b
920 view.ptr = <intptr_t>(dl_tensor.data) + <intptr_t>(dl_tensor.byte_offset) 2}bm 0b1b2b
921 view.readonly = is_readonly 2}bm 0b1b2b
922 view.exporting_obj = exporting_obj 2}bm 0b1b2b
923 if dl_tensor.device.device_type == _kDLCPU: 2}bm 0b1b2b
924 view.device_id = -1 1m
925 view.is_device_accessible = False 1m
926 elif dl_tensor.device.device_type in (_kDLCUDA, _kDLCUDAHost, _kDLCUDAManaged): 20b
927 view.device_id = dl_tensor.device.device_id 20b1b2b
928 view.is_device_accessible = True 20b1b2b
929 else:
930 raise BufferError("device not supported") 2}b
931 return view 2m 0b1b2b
934cdef int _smv_managed_tensor_allocator(
935 DLTensor* prototype,
936 DLManagedTensorVersioned** out,
937 void* error_ctx,
938 void (*SetError)(void* error_ctx, const char* kind, const char* message) noexcept,
939) noexcept with gil:
940 if out != NULL: 2qc
941 out[0] = NULL 2qc
942 if SetError != NULL: 2qc
943 SetError(error_ctx, b"NotImplementedError", b"managed_tensor_allocator is not supported by StridedMemoryView")
944 cpython.PyErr_SetString(NotImplementedError, b"managed_tensor_allocator is not supported by StridedMemoryView") 2qc
945 return -1 2qc
948cdef int _smv_managed_tensor_from_py_object_no_sync(
949 void* py_object,
950 DLManagedTensorVersioned** out,
951) except -1 with gil:
952 cdef DLManagedTensorVersioned* dlm_tensor_ver = NULL 2- ! jbm
953 if out == NULL: 2- ! jbm
954 raise RuntimeError("out cannot be NULL") 2jb
955 out[0] = NULL 2- ! jbm
956 cdef object obj = <object>py_object 2- ! jbm
957 if not isinstance(obj, StridedMemoryView): 2- ! jbm
958 raise TypeError("py_object must be a StridedMemoryView") 2jb
959 try: 1-!m
960 dlm_tensor_ver = _smv_allocate_dlm_tensor_versioned() 1-!m
961 _smv_fill_managed_tensor_versioned(dlm_tensor_ver, <StridedMemoryView>obj) 1-!m
962 except BaseException: 1-!
963 # Rollback must also run for KeyboardInterrupt.
964 _smv_versioned_deleter(dlm_tensor_ver) 1-!
965 raise 1-!
966 out[0] = dlm_tensor_ver 1m
967 return 0 1m
970cdef int _smv_managed_tensor_to_py_object_no_sync(
971 DLManagedTensorVersioned* tensor,
972 void** out_py_object,
973) except -1 with gil:
974 if out_py_object == NULL: 2}bm 0b1b2bCctc
975 raise RuntimeError("out_py_object cannot be NULL") 2Cc
976 out_py_object[0] = NULL 2}bm 0b1b2btc
977 if tensor == NULL: 2}bm 0b1b2btc
978 raise RuntimeError("tensor cannot be NULL") 2tc
979 cdef object capsule = cpython.PyCapsule_New( 2}bm 0b1b2b
980 <void*>tensor,
981 DLPACK_VERSIONED_TENSOR_UNUSED_NAME,
982 _smv_pycapsule_deleter,
983 )
984 cdef object py_view = _smv_from_dlpack_capsule(capsule, capsule) 2}bm 0b1b2b
985 cpython.Py_INCREF(py_view) 2m 0b1b2b
986 out_py_object[0] = <void*>py_view 2m 0b1b2b
987 return 0 2m 0b1b2b
990cdef int _smv_dltensor_from_py_object_no_sync(
991 void* py_object,
992 DLTensor* out,
993) except -1 with gil:
994 if out == NULL: 2kbpbU ucV Yb
995 raise RuntimeError("out cannot be NULL") 2pb
996 cdef object obj = <object>py_object 2kbU ucV Yb
997 if not isinstance(obj, StridedMemoryView): 2kbU ucV Yb
998 raise TypeError("py_object must be a StridedMemoryView") 2uc
999 _smv_setup_dltensor_borrowed(out, <StridedMemoryView>obj) 2kbU V Yb
1000 return 0 1UV
1003cdef int _smv_current_work_stream(
1004 _DLDeviceType device_type,
1005 int32_t device_id,
1006 void** out_current_stream,
1007) except -1 with gil:
1008 if out_current_stream == NULL: 2Dcxc
1009 raise RuntimeError("out_current_stream cannot be NULL") 2Dc
1010 # cuda.core has no global/current stream state today.
1011 out_current_stream[0] = NULL 2xc
1012 return 0 2xc
1015cdef void _init_smv_dlpack_exchange_api():
1016 global _SMV_DLPACK_EXCHANGE_API_INITED
1017 if _SMV_DLPACK_EXCHANGE_API_INITED:
1018 return
1019 _SMV_DLPACK_EXCHANGE_API.header.version.major = DLPACK_MAJOR_VERSION
1020 _SMV_DLPACK_EXCHANGE_API.header.version.minor = DLPACK_MINOR_VERSION
1021 _SMV_DLPACK_EXCHANGE_API.header.prev_api = NULL
1022 _SMV_DLPACK_EXCHANGE_API.managed_tensor_allocator = _smv_managed_tensor_allocator
1023 _SMV_DLPACK_EXCHANGE_API.managed_tensor_from_py_object_no_sync = _smv_managed_tensor_from_py_object_no_sync
1024 _SMV_DLPACK_EXCHANGE_API.managed_tensor_to_py_object_no_sync = _smv_managed_tensor_to_py_object_no_sync
1025 _SMV_DLPACK_EXCHANGE_API.dltensor_from_py_object_no_sync = _smv_dltensor_from_py_object_no_sync
1026 _SMV_DLPACK_EXCHANGE_API.current_work_stream = _smv_current_work_stream
1027 _SMV_DLPACK_EXCHANGE_API_INITED = True
1030_init_smv_dlpack_exchange_api()
1031# cdef classes are immutable types in Cython 3, so inject these attributes
1032# directly into the type dict.
1033(<dict>(<PyTypeObject*>StridedMemoryView).tp_dict)["__dlpack_c_exchange_api__"] = _SMV_DLPACK_EXCHANGE_API_CAPSULE
1034(<dict>(<PyTypeObject*>StridedMemoryView).tp_dict)["__c_dlpack_exchange_api__"] = _SMV_DLPACK_EXCHANGE_API_CAPSULE
1035PyType_Modified(<PyTypeObject*>StridedMemoryView)
1038cdef str get_simple_repr(obj):
1039 # TODO: better handling in np.dtype objects
1040 cdef object obj_class
1041 cdef str obj_repr
1042 if isinstance(obj, type): 2P g tb5
1043 obj_class = obj 1Pg
1044 else:
1045 obj_class = obj.__class__ 2P g tb5
1046 if obj_class.__module__ in (None, "builtins"): 2P g tb5
1047 obj_repr = obj_class.__name__ 2tb
1048 else:
1049 obj_repr = f"{obj_class.__module__}.{obj_class.__name__}" 2P g tb5
1050 return obj_repr 2P g tb5
1054cdef bint check_has_dlpack(obj) except*:
1055 cdef bint has_dlpack
1056 if hasattr(obj, "__dlpack__") and hasattr(obj, "__dlpack_device__"): 2bbebhbsb@ , 8 # $ 7 [ ] ^ _ cb% ' ( ) * / : ; = ? { | } ~ abscQ R O qbrbl ZbocDb5 nb9 3 dbfb` . pbU V jbm K w x z A B G H I J C D E F y M L s b k n t o p u q r i v c j a
1057 has_dlpack = True 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O qbrbl 5 nb9 3 dbfb` . pbU V jbm K w x z A B G H I J C D E F y M L s b k n t o p u q r i v c j a
1058 elif hasattr(obj, "__cuda_array_interface__"): 2$ 7 [ ] ^ _ cbscZbocDb
1059 has_dlpack = False 2$ 7 [ ] ^ _ cbZbocDb
1060 else:
1061 raise BufferError( 2sc
1062 "the input object does not support any data exchange protocol")
1063 return has_dlpack 2bbebhbsb@ , 8 # $ 7 [ ] ^ _ cb% ' ( ) * / : ; = ? { | } ~ abQ R O qbrbl ZbocDb5 nb9 3 dbfb` . pbU V jbm K w x z A B G H I J C D E F y M L s b k n t o p u q r i v c j a
1066cdef class _StridedMemoryViewProxy:
1067 cdef readonly:
1068 object obj
1069 bint has_dlpack
1071 def __init__(self, obj: object) -> None:
1072 self.obj = obj 2% ' ( ) * ocDb
1073 self.has_dlpack = check_has_dlpack(obj) 2% ' ( ) * ocDb
1075 cpdef StridedMemoryView view(self, stream_ptr=None):
1076 if self.has_dlpack: 2% ' ( ) * Db
1077 return StridedMemoryView.from_dlpack(self.obj, stream_ptr) 1%'()*
1078 else:
1079 return StridedMemoryView.from_cuda_array_interface(self.obj, stream_ptr) 2Db
1082cdef StridedMemoryView view_as_dlpack(obj, stream_ptr, view=None):
1083 cdef int dldevice, device_id
1084 cdef bint is_device_accessible, is_readonly = False 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 dbfb` . gbibpbU V jbm d K w x z A B G H I J C D E F y M L s h 6 kce f fcb k n t o p u q r i v hcgc~bc j a ic
1085 is_device_accessible = False 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 dbfb` . gbibpbU V jbm d K w x z A B G H I J C D E F y M L s h 6 kce f fcb k n t o p u q r i v hcgc~bc j a ic
1086 # Callers may pass an int-convertible stream wrapper (e.g. numba-cuda's
1087 # CUstream). Normalize it so the -1 and truthiness checks below see an int.
1088 if stream_ptr is not None: 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 dbfb` . gbibpbU V jbm d K w x z A B G H I J C D E F y M L s h 6 kce f fcb k n t o p u q r i v hcgc~bc j a ic
1089 stream_ptr = int(stream_ptr) 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 dbfb` . gbibpbU V jbm d K w x z A B G H I J C D E F y M L s h 6 b k n t o p u q r i v hcgc~bc j a ic
1090 dldevice, device_id = obj.__dlpack_device__() 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 dbfb` . gbibpbU V jbm d K w x z A B G H I J C D E F y M L s h 6 kce f fcb k n t o p u q r i v hcgc~bc j a ic
1091 if dldevice == _kDLCPU: 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 dbfb` . gbibpbU V jbm d K w x z A B G H I J C D E F y M L s h 6 kce f fcb k n t o p u q r i v hcgc~bc j a ic
1092 if device_id != 0: 2hbsb@ , % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 dbfb` . gbibpbU V jbm d K w x z A B G H I J C D E F y M L s h kcb k n t o p u q r i v hc~bc j a
1093 raise ValueError(f"__dlpack_device__() reported device_id {device_id} for a kDLCPU tensor; expected 0") 2hc
1094 device_id = -1 2hbsb@ , % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 dbfb` . gbibpbU V jbm d K w x z A B G H I J C D E F y M L s h kcb k n t o p u q r i v ~bc j a
1095 if stream_ptr is None: 2hbsb@ , % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 dbfb` . gbibpbU V jbm d K w x z A B G H I J C D E F y M L s h kcb k n t o p u q r i v ~bc j a
1096 raise BufferError("stream=None is ambiguous with view()") 2kc
1097 elif stream_ptr == -1: 2hbsb@ , % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 dbfb` . gbibpbU V jbm d K w x z A B G H I J C D E F y M L s h b k n t o p u q r i v ~bc j a
1098 stream_ptr = None 2hbsb@ , % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 db` gbpbU V jbm d K w x z A B G H I J C D E F y M L s h b k n t o p u q r i v ~bc j a
1099 elif dldevice == _kDLCUDA:
1100 if device_id < 0: 28 # 6 fcgc
1101 raise ValueError( 2gc
1102 f"__dlpack_device__() reported device_id {device_id} for a kDLCUDA tensor; expected 0 or more") 2gc
1103 is_device_accessible = True 28 # 6 fc
1104 # no need to check other stream values, it's a pass-through
1105 if stream_ptr is None: 28 # 6 fc
1106 raise BufferError("stream=None is ambiguous with view()") 2fc
1107 elif dldevice in (_kDLCUDAHost, _kDLCUDAManaged): 1e
1108 is_device_accessible = True 2bbebe f
1109 # just do a pass-through without any checks, as pinned/managed memory can be
1110 # accessed on both host and device
1111 else:
1112 raise BufferError("device not supported") 2ic
1114 cdef object capsule
1115 try: 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 dbfb` . gbibpbU V jbm d K w x z A B G H I J C D E F y M L s h 6 e f b k n t o p u q r i v ~bc j a
1116 capsule = obj.__dlpack__( 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 dbfb` . gbibpbU V jbm d K w x z A B G H I J C D E F y M L s h 6 e f b k n t o p u q r i v ~bc j a
1117 stream=int(stream_ptr) if stream_ptr else None, 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 dbfb` . gbibpbU V jbm d K w x z A B G H I J C D E F y M L s h 6 e f b k n t o p u q r i v ~bc j a
1118 max_version=(DLPACK_MAJOR_VERSION, DLPACK_MINOR_VERSION)) 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 dbfb` . gbibpbU V jbm d K w x z A B G H I J C D E F y M L s h 6 e f b k n t o p u q r i v ~bc j a
1119 except TypeError: 1bia
1120 capsule = obj.__dlpack__( 1bia
1121 stream=int(stream_ptr) if stream_ptr else None) 1bia
1123 cdef void* data = NULL 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 dbfb` . gbibpbU V jbm d K w x z A B G H I J C D E F y M L s h 6 e f b k n t o p u q r i v ~bc j a
1124 cdef DLTensor* dl_tensor = NULL 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 dbfb` . gbibpbU V jbm d K w x z A B G H I J C D E F y M L s h 6 e f b k n t o p u q r i v ~bc j a
1125 cdef DLManagedTensorVersioned* dlm_tensor_ver
1126 cdef DLManagedTensor* dlm_tensor
1127 cdef const char *used_name = NULL 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 dbfb` . gbibpbU V jbm d K w x z A B G H I J C D E F y M L s h 6 e f b k n t o p u q r i v ~bc j a
1128 if cpython.PyCapsule_IsValid( 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 dbfb` . gbibpbU V jbm d K w x z A B G H I J C D E F y M L s h 6 e f b k n t o p u q r i v ~bc j a
1129 capsule, DLPACK_VERSIONED_TENSOR_UNUSED_NAME):
1130 data = cpython.PyCapsule_GetPointer( 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 dbfb` . gbibpbU V jbm d K w x z A B G H I J C D E F y M L s h 6 e f b k n t o p u q r i v c j a
1131 capsule, DLPACK_VERSIONED_TENSOR_UNUSED_NAME)
1132 dlm_tensor_ver = <DLManagedTensorVersioned*>data 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 dbfb` . gbibpbU V jbm d K w x z A B G H I J C D E F y M L s h 6 e f b k n t o p u q r i v c j a
1133 dl_tensor = &dlm_tensor_ver.dl_tensor 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 dbfb` . gbibpbU V jbm d K w x z A B G H I J C D E F y M L s h 6 e f b k n t o p u q r i v c j a
1134 is_readonly = bool((dlm_tensor_ver.flags & DLPACK_FLAG_BITMASK_READ_ONLY) != 0) 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 dbfb` . gbibpbU V jbm d K w x z A B G H I J C D E F y M L s h 6 e f b k n t o p u q r i v c j a
1135 used_name = DLPACK_VERSIONED_TENSOR_USED_NAME 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 dbfb` . gbibpbU V jbm d K w x z A B G H I J C D E F y M L s h 6 e f b k n t o p u q r i v c j a
1136 elif cpython.PyCapsule_IsValid( 2b i ~ba
1137 capsule, DLPACK_TENSOR_UNUSED_NAME):
1138 data = cpython.PyCapsule_GetPointer( 1bia
1139 capsule, DLPACK_TENSOR_UNUSED_NAME)
1140 dlm_tensor = <DLManagedTensor*>data 1bia
1141 dl_tensor = &dlm_tensor.dl_tensor 1bia
1142 is_readonly = False 1bia
1143 used_name = DLPACK_TENSOR_USED_NAME 1bia
1144 else:
1145 raise ValueError(f"__dlpack__() returned {capsule!r}, not an unconsumed DLPack capsule") 2~b
1147 cpython.PyCapsule_SetName(capsule, used_name) 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 dbfb` . gbibpbU V jbm d K w x z A B G H I J C D E F y M L s h 6 e f b k n t o p u q r i v c j a
1149 cdef StridedMemoryView buf = StridedMemoryView() if view is None else view 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 dbfb` . gbibpbU V jbm d K w x z A B G H I J C D E F y M L s h 6 e f b k n t o p u q r i v c j a
1150 buf.dl_tensor = dl_tensor 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 dbfb` . gbibpbU V jbm d K w x z A B G H I J C D E F y M L s h 6 e f b k n t o p u q r i v c j a
1151 buf.metadata = capsule 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 dbfb` . gbibpbU V jbm d K w x z A B G H I J C D E F y M L s h 6 e f b k n t o p u q r i v c j a
1152 buf.ptr = <intptr_t>(dl_tensor.data) + <intptr_t>(dl_tensor.byte_offset) 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 dbfb` . gbibpbU V jbm d K w x z A B G H I J C D E F y M L s h 6 e f b k n t o p u q r i v c j a
1153 buf.device_id = device_id 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 dbfb` . gbibpbU V jbm d K w x z A B G H I J C D E F y M L s h 6 e f b k n t o p u q r i v c j a
1154 buf.is_device_accessible = is_device_accessible 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 dbfb` . gbibpbU V jbm d K w x z A B G H I J C D E F y M L s h 6 e f b k n t o p u q r i v c j a
1155 buf.readonly = is_readonly 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 dbfb` . gbibpbU V jbm d K w x z A B G H I J C D E F y M L s h 6 e f b k n t o p u q r i v c j a
1156 buf.exporting_obj = obj 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 dbfb` . gbibpbU V jbm d K w x z A B G H I J C D E F y M L s h 6 e f b k n t o p u q r i v c j a
1158 return buf 2bbebhbsb@ , 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g qbrbl 5 nb9 3 W X Y Z 0 1 dbfb` . gbibpbU V jbm d K w x z A B G H I J C D E F y M L s h 6 e f b k n t o p u q r i v c j a
1161@functools.lru_cache
1162def _typestr2dtype(str typestr) -> numpy.dtype:
1163 return numpy.dtype(typestr) 27 cbubvbwbxbybzbAbBbCbacUblbkb! S 2 4
1166@functools.lru_cache
1167def _typestr2itemsize(str typestr) -> int:
1168 return _typestr2dtype(typestr).itemsize 27 cbubvbwbxbybzbAbBbCbacUblbkb! S 2 4
1171cdef object dtype_dlpack_to_numpy(DLDataType* dtype):
1172 cdef int bits = dtype.bits 1gl5WXYZ01UVmdKwxzABGHIJCDEFyMLsefbkntopuqrivcja
1173 if dtype.lanes != 1: 1gl5WXYZ01UVmdKwxzABGHIJCDEFyMLsefbkntopuqrivcja
1174 # TODO: return a NumPy structured dtype?
1175 raise NotImplementedError( 1q
1176 f'vector dtypes (lanes={dtype.lanes}) is not supported') 1q
1177 if dtype.code == kDLUInt: 1gl5WXYZ01UVmdKwxzABGHIJCDEFyMLsefbkntopuqrivcja
1178 if bits == 8: 1CDEFr
1179 np_dtype = numpy.uint8 1C
1180 elif bits == 16:
1181 np_dtype = numpy.uint16 1D
1182 elif bits == 32:
1183 np_dtype = numpy.uint32 1E
1184 elif bits == 64:
1185 np_dtype = numpy.uint64 1F
1186 else:
1187 raise TypeError('uint{} is not supported.'.format(bits)) 1r
1188 elif dtype.code == kDLInt:
1189 if bits == 8: 1gl5WXYZ01UVdGHIJLsbkntopuqrivcja
1190 np_dtype = numpy.int8 1G
1191 elif bits == 16:
1192 np_dtype = numpy.int16 1UH
1193 elif bits == 32:
1194 np_dtype = numpy.int32 1gl5WXYZ01VdILsbkntopuqrivcja
1195 elif bits == 64:
1196 np_dtype = numpy.int64 1J
1197 else:
1198 raise TypeError('int{} is not supported.'.format(bits)) 1u
1199 elif dtype.code == kDLFloat:
1200 if bits == 16: 1mzABefp
1201 np_dtype = numpy.float16 1z
1202 elif bits == 32:
1203 np_dtype = numpy.float32 1Aef
1204 elif bits == 64:
1205 np_dtype = numpy.float64 1mB
1206 else:
1207 raise TypeError('float{} is not supported.'.format(bits)) 1p
1208 elif dtype.code == kDLComplex:
1209 # TODO(leofang): support complex32
1210 if bits == 64: 1wxyMo
1211 np_dtype = numpy.complex64 1w
1212 elif bits == 128:
1213 np_dtype = numpy.complex128 1xyM
1214 else:
1215 raise TypeError('complex{} is not supported.'.format(bits)) 1o
1216 elif dtype.code == kDLBool:
1217 if bits == 8: 1Kn
1218 np_dtype = numpy.bool_ 1K
1219 else:
1220 raise TypeError(f'{bits}-bit bool is not supported') 1n
1221 elif dtype.code == kDLBfloat:
1222 if bfloat16 is not None:
1223 np_dtype = numpy.dtype("bfloat16")
1224 else:
1225 raise NotImplementedError(
1226 'Support for bfloat16 within cuda-core requires `ml_dtypes`'
1227 'to be installed.'
1228 )
1229 else:
1230 raise TypeError('Unsupported dtype. dtype code: {}'.format(dtype.code)) 1t
1232 # We want the dtype object not just the type object
1233 return numpy.dtype(np_dtype) 1gl5WXYZ01UVmdKwxzABGHIJCDEFyMLsefbkntopuqrivcja
1236cpdef StridedMemoryView view_as_cai(obj, stream_ptr, view=None):
1237 cdef dict cai_data = obj.__cuda_array_interface__ 2$ 7 [ ] ^ _ cbvcrcyczcN VbacUbZbDblbTb
1238 if cai_data.get("version", 0) < 3: 2$ 7 [ ] ^ _ cbvcrcyczcN VbacUbZbDblbTb
1239 raise BufferError("only CUDA Array Interface v3 or above is supported") 2yczc
1240 if cai_data.get("mask") is not None: 2$ 7 [ ] ^ _ cbvcrcN VbacUbZbDblbTb
1241 raise BufferError("mask is not supported") 2vc
1242 if stream_ptr is None: 2$ 7 [ ] ^ _ cbrcN VbacUbZbDblbTb
1243 raise BufferError("stream=None is ambiguous with view()") 2rc
1245 cdef StridedMemoryView buf = StridedMemoryView() if view is None else view 2$ 7 [ ] ^ _ cbN VbacUbZbDblbTb
1246 buf.exporting_obj = obj 2$ 7 [ ] ^ _ cbN VbacUbZbDblbTb
1247 buf.metadata = cai_data 2$ 7 [ ] ^ _ cbN VbacUbZbDblbTb
1248 buf.dl_tensor = NULL 2$ 7 [ ] ^ _ cbN VbacUbZbDblbTb
1249 # Validate shape/strides/typestr eagerly so constructor paths fail fast.
1250 buf.get_layout() 2$ 7 [ ] ^ _ cbN VbacUbZbDblbTb
1251 buf.ptr, buf.readonly = cai_data["data"] 2$ 7 [ ] ^ _ cbN VbUbZbDblbTb
1252 buf.is_device_accessible = True 2$ 7 [ ] ^ _ cbN VbUbZbDblbTb
1253 if buf.ptr != 0: 2$ 7 [ ] ^ _ cbN VbUbZbDblbTb
1254 buf.device_id = handle_return( 2$ 7 [ ] ^ _ cbN lb
1255 driver.cuPointerGetAttribute( 2$ 7 [ ] ^ _ cbN lb
1256 driver.CUpointer_attribute.CU_POINTER_ATTRIBUTE_DEVICE_ORDINAL, 2$ 7 [ ] ^ _ cbN lb
1257 buf.ptr)) 2$ 7 [ ] ^ _ cbN lb
1258 else:
1259 buf.device_id = handle_return(driver.cuCtxGetDevice()) 2VbUbZbDbTb
1261 cdef intptr_t producer_s, consumer_s
1262 cdef EventHandle h_event
1263 stream_ptr = int(stream_ptr) 2$ 7 [ ] ^ _ cbN VbUbZbDblbTb
1264 if stream_ptr != -1: 2$ 7 [ ] ^ _ cbN VbUbZbDblbTb
1265 stream = cai_data.get("stream") 2lbTb
1266 if stream is not None: 2lbTb
1267 producer_s = <intptr_t>(stream) 2lbTb
1268 consumer_s = <intptr_t>(stream_ptr) 2lbTb
1269 if producer_s <= 0: 2lbTb
1270 raise ValueError( 2Tb
1271 f"__cuda_array_interface__ reported stream {stream}; expected None or a positive stream handle") 2Tb
1272 # establish stream order
1273 if producer_s != consumer_s: 2lb
1274 with nogil: 2lb
1275 # The event must belong to the producer stream's context to
1276 # be recorded on it, whatever context is current here.
1277 h_event = create_event_handle_for_stream( 2lb
1278 <cydriver.CUstream>producer_s, cydriver.CUevent_flags.CU_EVENT_DISABLE_TIMING)
1279 if not h_event: 2lb
1280 HANDLE_RETURN(get_last_error())
1281 HANDLE_RETURN(cydriver.cuEventRecord( 2lb
1282 as_cu(h_event), <cydriver.CUstream>producer_s))
1283 HANDLE_RETURN(cydriver.cuStreamWaitEvent( 2lb
1284 <cydriver.CUstream>consumer_s, as_cu(h_event), 0))
1285 elif _is_torch_tensor(obj):
1286 # PyTorch's __cuda_array_interface__ reports version 2 and
1287 # omits the "stream" field, so the standard CAI sync path
1288 # above is a no-op for torch tensors. This is unsafe: the
1289 # consumer has no guarantee that the producer's work is
1290 # visible. We fix this by querying PyTorch's current CUDA
1291 # stream via the AOTI stable C ABI and performing the same
1292 # event-based stream ordering.
1293 _get_tensor_bridge().sync_torch_stream(
1294 buf.device_id, <intptr_t>(stream_ptr))
1296 return buf 2$ 7 [ ] ^ _ cbN VbUbZbDblb
1299cpdef StridedMemoryView view_as_array_interface(obj, view=None):
1300 cdef dict data = obj.__array_interface__ 2wcAcBcubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbecP kb! S 2 4 h e f
1301 if data.get("version", 0) < 3: 2wcAcBcubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbecP kb! S 2 4 h e f
1302 raise BufferError("only NumPy Array Interface v3 or above is supported") 2AcBc
1303 if data.get("mask") is not None: 2wcubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbecP kb! S 2 4 h e f
1304 raise BufferError("mask is not supported") 2wc
1306 cdef StridedMemoryView buf = StridedMemoryView() if view is None else view 2ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbecP kb! S 2 4 h e f
1307 buf.exporting_obj = obj 2ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbecP kb! S 2 4 h e f
1308 buf.metadata = data 2ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbecP kb! S 2 4 h e f
1309 buf.dl_tensor = NULL 2ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbecP kb! S 2 4 h e f
1310 # Validate shape/strides/typestr eagerly so constructor paths fail fast.
1311 buf.get_layout() 2ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbecP kb! S 2 4 h e f
1312 buf.ptr, buf.readonly = data["data"] 2ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbP kb! S 2 4 h e f
1313 buf.is_device_accessible = False 2ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbP kb! S 2 4 h e f
1314 buf.device_id = -1 2ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbP kb! S 2 4 h e f
1315 return buf 2ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbP kb! S 2 4 h e f
1318def args_viewable_as_strided_memory(arg_indices: tuple[int, ...]) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
1319 """
1320 Decorator to create proxy objects to :obj:`StridedMemoryView` for the
1321 specified positional arguments.
1323 This allows array/tensor attributes to be accessed inside the function
1324 implementation, while keeping the function body array-library-agnostic (if
1325 desired).
1327 Inside the decorated function, the specified arguments become instances
1328 of an (undocumented) proxy type, regardless of its original source. A
1329 :obj:`StridedMemoryView` instance can be obtained by passing the (consumer)
1330 stream pointer (as a Python `int`) to the proxies's ``view()`` method. For
1331 example:
1333 .. code-block:: python
1335 @args_viewable_as_strided_memory((1,))
1336 def my_func(arg0, arg1, arg2, stream: Stream):
1337 # arg1 can be any object supporting DLPack or CUDA Array Interface
1338 view = arg1.view(stream.handle)
1339 assert isinstance(view, StridedMemoryView)
1340 ...
1342 Parameters
1343 ----------
1344 arg_indices : tuple
1345 The indices of the target positional arguments.
1346 """
1347 def wrapped_func_with_indices(func: "Callable") -> "Callable": 1%'()*
1348 @functools.wraps(func) 1%'()*
1349 def wrapped_func(*args, **kwargs) -> object:
1350 args = list(args) 1%'()*
1351 cdef int idx
1352 for idx in arg_indices: 1%'()*
1353 args[idx] = _StridedMemoryViewProxy(args[idx]) 1%'()*
1354 return func(*args, **kwargs) 1%'()*
1355 return wrapped_func 1%'()*
1356 return wrapped_func_with_indices 1%'()*
1359cdef inline _StridedLayout layout_from_dlpack(DLTensor* dl_tensor):
1360 cdef _StridedLayout layout = _StridedLayout.__new__(_StridedLayout) 2@ 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g l 5 9 3 W X Y Z 0 1 dbfb` . gbibU V m d K w x z A B G H I J C D E F y M L s 6 e f b k n t o p u q r i v c j a
1361 cdef int nbits = dl_tensor.dtype.bits * dl_tensor.dtype.lanes 2@ 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g l 5 9 3 W X Y Z 0 1 dbfb` . gbibU V m d K w x z A B G H I J C D E F y M L s 6 e f b k n t o p u q r i v c j a
1362 cdef int itemsize = nbits >> 3 2@ 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g l 5 9 3 W X Y Z 0 1 dbfb` . gbibU V m d K w x z A B G H I J C D E F y M L s 6 e f b k n t o p u q r i v c j a
1363 if (itemsize << 3) != nbits: 2@ 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g l 5 9 3 W X Y Z 0 1 dbfb` . gbibU V m d K w x z A B G H I J C D E F y M L s 6 e f b k n t o p u q r i v c j a
1364 raise ValueError("dl_tensor.dtype.bits must be a multiple of 8") 1j
1365 layout.init_from_ptr(dl_tensor.ndim, dl_tensor.shape, dl_tensor.strides, itemsize) 2@ 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g l 5 9 3 W X Y Z 0 1 dbfb` . gbibU V m d K w x z A B G H I J C D E F y M L s 6 e f b k n t o p u q r i v c j a
1366 return layout 2@ 8 # % ' ( ) * / : ; = ? { | } ~ abQ R O g l 5 9 3 W X Y Z 0 1 dbfb` . gbibU V m d K w x z A B G H I J C D E F y M L s 6 e f b k n t o p u q r i v c j a
1369cdef _StridedLayout layout_from_cai(object metadata):
1370 cdef _StridedLayout layout = _StridedLayout.__new__(_StridedLayout) 2$ 7 [ ] ^ _ cbN ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbecVbacUbP ZbDblbTbkb! S 2 4 h e f
1371 cdef object shape = metadata["shape"] 2$ 7 [ ] ^ _ cbN ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbecVbacUbP ZbDblbTbkb! S 2 4 h e f
1372 cdef object strides = metadata.get("strides") 2$ 7 [ ] ^ _ cbN ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbecVbacUbP ZbDblbTbkb! S 2 4 h e f
1373 cdef int itemsize = _typestr2itemsize(metadata["typestr"]) 2$ 7 [ ] ^ _ cbN ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbecVbacUbP ZbDblbTbkb! S 2 4 h e f
1374 layout.init_from_tuple(shape, strides, itemsize, True) 2$ 7 [ ] ^ _ cbN ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbecVbacUbP ZbDblbTbkb! S 2 4 h e f
1375 return layout 2$ 7 [ ] ^ _ cbN ubvbEbwbFbxbGbybzbAbHbIbJbKbLbMbNbObPbQbRbSbBbCbVbUbP ZbDblbTbkb! S 2 4 h e f
1378cdef inline intptr_t get_data_ptr(object buffer, _StridedLayout layout) except? 0:
1379 return <intptr_t>(int(buffer.handle)) + layout.get_slice_offset_in_bytes() 2ccdcmbobQ R O 3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|bWbXbbc+ tb3 W X Y Z 0 1 Yb- d 6 c
1382cdef inline int view_buffer_strided(
1383 StridedMemoryView view,
1384 object buffer,
1385 _StridedLayout layout,
1386 object dtype,
1387 bint is_readonly,
1388) except -1:
1389 if isinstance(buffer, Buffer): 2ccdcmbobQ R O 3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|blcWbXbjcbc+ tb9 3 W X Y Z 0 1 Yb- d 6 c
1390 Buffer_check_open(<cyBuffer>buffer) 2ccdcmbobQ R O 3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|blcWbXbjcbc+ tb9 3 W X Y Z 0 1 Yb- d 6 c
1391 if dtype is not None: 2ccdcmbobQ R O 3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|blcWbXbjcbc+ tb9 3 W X Y Z 0 1 Yb- d 6 c
1392 dtype = numpy.dtype(dtype) 2ccdcobQ R O 3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|blcWbXbjcbc9 3 W X Y Z 0 1 d 6 c
1393 if dtype.itemsize != layout.itemsize: 2ccdcobQ R O 3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|blcWbXbjcbc9 3 W X Y Z 0 1 d 6 c
1394 raise ValueError( 19
1395 f"The dtype's itemsize ({dtype.itemsize}) does not match the layout's " 19
1396 f"itemsize ({layout.itemsize})." 19
1397 )
1398 # Check the layout's offset range [min_offset, max_offset] fits
1399 # within the [0, buffer.size - 1] range.
1400 # The required_size_in_bytes fails if min_offset < 0.
1401 # NB. For external memory, both positive and negative offsets can be valid,
1402 # but for a proper check we'd need to know both size and data offset,
1403 # while neither is reported by the packages.
1404 cdef bint is_allocated = buffer.memory_resource is not None 2ccdcmbobQ R O 3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|blcWbXbjcbc+ tb3 W X Y Z 0 1 Yb- d 6 c
1405 if is_allocated and buffer.size < layout.get_required_size_in_bytes(): 2ccdcmbobQ R O 3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|blcWbXbjcbc+ tb3 W X Y Z 0 1 Yb- d 6 c
1406 raise ValueError( 2jc
1407 f"Buffer size is too small for the layout. " 2jc
1408 f"Expected at least {layout.get_required_size_in_bytes()} bytes, " 2jc
1409 f"got {buffer.size} bytes." 2jc
1410 )
1411 # set the public attributes
1412 view.ptr = get_data_ptr(buffer, layout) 2ccdcmbobQ R O 3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|bWbXbbc+ tb3 W X Y Z 0 1 Yb- d 6 c
1413 view.device_id = buffer.device_id 2ccdcmbobQ R O 3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|bWbXbbc+ tb3 W X Y Z 0 1 Yb- d 6 c
1414 view.is_device_accessible = buffer.is_device_accessible 2ccdcmbobQ R O 3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|bWbXbbc+ tb3 W X Y Z 0 1 Yb- d 6 c
1415 view.readonly = is_readonly 2ccdcmbobQ R O 3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|bWbXbbc+ tb3 W X Y Z 0 1 Yb- d 6 c
1416 view.exporting_obj = view._buffer = buffer 2ccdcmbobQ R O 3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|bWbXbbc+ tb3 W X Y Z 0 1 Yb- d 6 c
1417 # no dlpack/cai metadata
1418 view.dl_tensor = NULL 2ccdcmbobQ R O 3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|bWbXbbc+ tb3 W X Y Z 0 1 Yb- d 6 c
1419 view.metadata = None 2ccdcmbobQ R O 3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|bWbXbbc+ tb3 W X Y Z 0 1 Yb- d 6 c
1420 # we get the layout from the caller
1421 view._layout = layout 2ccdcmbobQ R O 3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|bWbXbbc+ tb3 W X Y Z 0 1 Yb- d 6 c
1422 view._dtype = dtype 2ccdcmbobQ R O 3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|bWbXbbc+ tb3 W X Y Z 0 1 Yb- d 6 c
1423 return 0 2ccdcmbobQ R O 3b4b5b6b7b8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|bWbXbbc+ tb3 W X Y Z 0 1 Yb- d 6 c