Coverage for cuda/core/texture/_mipmapped_array.pyx: 87.50%
72 statements
« prev ^ index » next coverage.py v7.16.0, created at 2026-09-04 01:32 +0000
« prev ^ index » next coverage.py v7.16.0, created at 2026-09-04 01:32 +0000
1# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2#
3# SPDX-License-Identifier: Apache-2.0
5from __future__ import annotations
7from cuda.bindings cimport cydriver
8from cuda.core.texture._array cimport _array_from_handle
9from cuda.core.texture._array import (
10 _ARRAYFORMAT_TO_CU,
11 _CU_TO_ARRAYFORMAT,
12 _validate_array_shape,
13 _validate_format_channels,
14)
15from cuda.core._resource_handles cimport (
16 OpaqueArrayHandle,
17 MipmappedArrayHandle,
18 as_intptr,
19 create_array_level_handle,
20 create_mipmapped_array_handle,
21 get_last_error,
22)
23from cuda.core._utils.cuda_utils cimport (
24 HANDLE_RETURN,
25 _get_current_device_id,
26)
28from dataclasses import dataclass
30from cuda.core._utils.cuda_utils import check_or_create_options
33@dataclass
34class MipmappedArrayOptions:
35 """Options for :meth:`cuda.core.Device.create_mipmapped_array`.
37 Attributes
38 ----------
39 shape : tuple of int
40 ``(width,)``, ``(width, height)``, or ``(width, height, depth)`` in
41 elements, for the base (level 0) mip.
42 format : ArrayFormatType, str, or numpy.dtype
43 Element format. Accepts an :class:`~cuda.core.typing.ArrayFormatType`,
44 a plain string (e.g. ``"float32"``), or a NumPy dtype object.
45 num_channels : int
46 Channels per element. Must be 1, 2, or 4.
47 num_levels : int
48 Number of mip levels to allocate; must be >= 1. The driver caps this at
49 the log2 of the largest dimension; passing a larger value yields a
50 driver error.
51 is_surface_load_store : bool
52 If True, allocate with ``CUDA_ARRAY3D_SURFACE_LDST`` so individual
53 levels (obtained via :meth:`MipmappedArray.get_level`) can be bound as
54 a :class:`~cuda.core.texture.SurfaceObject` for kernel-side writes.
55 Default False.
57 .. versionadded:: 1.1.0
58 """
60 shape: tuple[int, ...]
61 format: object
62 num_channels: int
63 num_levels: int
64 is_surface_load_store: bool = False
66 def __post_init__(self):
67 self.format = _validate_format_channels(self.format, self.num_channels) 1facbdenomlijgh
68 self.shape = _validate_array_shape(self.shape) 1facbdemlijgh
69 self.num_levels = int(self.num_levels) 1facbdelijgh
70 if self.num_levels < 1: 1facbdelijgh
71 raise ValueError(f"num_levels must be >= 1, got {self.num_levels}") 1l
74cdef class MipmappedArray:
75 """A mipmapped CUDA array for texture/surface access across levels.
77 Wraps ``CUmipmappedArray``. Each mip level is a distinct, hardware-laid-out
78 allocation accessible only via a :class:`TextureObject` (or by retrieving
79 the level's :class:`OpaqueArray` and binding it as a :class:`SurfaceObject`).
80 Destroying the :class:`MipmappedArray` destroys all level arrays
81 implicitly, so the :class:`OpaqueArray` instances returned by :meth:`get_level`
82 are non-owning and hold a strong reference back to their parent.
84 Construct via :meth:`cuda.core.Device.create_mipmapped_array`.
86 .. versionadded:: 1.1.0
87 """
89 def __init__(self, *args, **kwargs):
90 raise RuntimeError( 1p
91 "MipmappedArray cannot be instantiated directly. "
92 "Use Device.create_mipmapped_array()."
93 )
95 def get_level(self, level):
96 """Return a non-owning :class:`OpaqueArray` view of the given mip level.
98 Parameters
99 ----------
100 level : int
101 Mip level index in ``[0, num_levels)``.
103 Returns
104 -------
105 OpaqueArray
106 A non-owning :class:`OpaqueArray` wrapping the level's ``CUarray``.
107 The :class:`MipmappedArray` is kept alive for the lifetime of the
108 returned :class:`OpaqueArray`; the underlying storage is released only
109 when this :class:`MipmappedArray` is destroyed.
110 """
111 MipmappedArray_check_open(self) 1fcbde
112 lvl = int(level) 1cbde
113 if lvl < 0: 1cbde
114 raise ValueError(f"level must be >= 0, got {lvl}") 1b
115 if lvl >= <int>self._num_levels: 1kcbde
116 raise ValueError( 1b
117 f"level ({lvl}) must be < num_levels ({self._num_levels})" 1b
118 )
120 cdef OpaqueArrayHandle h_level = create_array_level_handle(self._handle, <unsigned int>lvl) 1cde
121 if not h_level: 1cde
122 HANDLE_RETURN(get_last_error())
123 # The returned OpaqueArray is non-owning; its C++ box embeds this mipmap's
124 # handle, so the parent's storage structurally outlives the level view
125 # (no Python parent reference needed).
126 return _array_from_handle(h_level, self._device_id) 1cde
128 @property
129 def handle(self):
130 """The underlying ``CUmipmappedArray`` as an integer."""
131 return as_intptr(self._handle) 1ah
133 @property
134 def is_closed(self) -> bool:
135 """Whether this mipmapped array has been closed."""
136 return self._handle.get() == NULL 1f
138 @property
139 def shape(self):
140 """Base-level (level 0) allocation shape, in elements."""
141 return self._shape 1a
143 @property
144 def format(self):
145 """The element :class:`~cuda.core.typing.ArrayFormatType`."""
146 return _CU_TO_ARRAYFORMAT[self._format] 1a
148 @property
149 def num_channels(self):
150 """Channels per element (1, 2, or 4)."""
151 return self._num_channels 1a
153 @property
154 def num_levels(self):
155 """Number of mip levels."""
156 return int(self._num_levels) 1abg
158 @property
159 def is_surface_load_store(self):
160 """True if this mipmap (and each of its levels) was created with
161 ``CUDA_ARRAY3D_SURFACE_LDST`` and can back a :class:`SurfaceObject`."""
162 return self._surface_load_store 1a
164 @property
165 def device(self):
166 """The :class:`Device` this mipmap was allocated on."""
167 from cuda.core._device import Device 1a
168 return Device(self._device_id) 1a
170 cpdef close(self):
171 """Release this object's reference to the underlying ``CUmipmappedArray``.
173 Destruction (``cuMipmappedArrayDestroy``) happens via the handle's
174 deleter when the last reference is dropped. A level :class:`OpaqueArray`
175 from :meth:`get_level` holds its own reference to this mipmap's storage,
176 so it stays valid until both it and this object are released. Idempotent.
177 """
178 self._handle.reset() 1facbdijgh
180 def __enter__(self):
181 return self
183 def __exit__(self, exc_type, exc, tb):
184 self.close()
186 def __repr__(self):
187 return (
188 f"MipmappedArray(shape={self._shape}, "
189 f"format={_CU_TO_ARRAYFORMAT[self._format].name}, "
190 f"num_channels={self._num_channels}, "
191 f"num_levels={self._num_levels})"
192 )
194def _create_mipmapped_array(options):
195 """Allocate a new :class:`MipmappedArray` on the current device.
197 Backs :meth:`cuda.core.Device.create_mipmapped_array`. ``options`` is a
198 :class:`MipmappedArrayOptions` (or a mapping accepted by it); its fields are
199 validated at construction.
200 """
201 cdef object opts = check_or_create_options( 1facbdeijgh
202 MipmappedArrayOptions, options, "Mipmapped array options" 1facbdeijgh
203 )
204 shape_t = opts.shape 1facbdeijgh
206 cdef cydriver.CUarray_format c_format = <cydriver.CUarray_format>_ARRAYFORMAT_TO_CU[opts.format] 1facbdeijgh
207 cdef int rank = len(shape_t) 1facbdeijgh
208 cdef unsigned int flags = (
209 cydriver.CUDA_ARRAY3D_SURFACE_LDST if opts.is_surface_load_store else 0 1facbdeijgh
210 )
211 cdef unsigned int c_levels = <unsigned int>opts.num_levels 1facbdeijgh
213 # Mipmap creation uses the 3D descriptor regardless of rank; lower-rank
214 # shapes use Height=0/Depth=0 sentinels, matching cuArray3DCreate.
215 cdef cydriver.CUDA_ARRAY3D_DESCRIPTOR desc3d = cydriver.CUDA_ARRAY3D_DESCRIPTOR(
216 Width=<size_t>shape_t[0], 1facbdeijgh
217 Height=<size_t>(shape_t[1] if rank >= 2 else 0), 1facbdeijgh
218 Depth=<size_t>(shape_t[2] if rank >= 3 else 0), 1facbdeijgh
219 Format=c_format, 1facbdeijgh
220 NumChannels=<unsigned int>opts.num_channels, 1facbdeijgh
221 Flags=flags, 1facbdeijgh
222 )
224 cdef MipmappedArrayHandle h = create_mipmapped_array_handle(desc3d, c_levels) 1facbdeijgh
225 if not h: 1facbdeijgh
226 HANDLE_RETURN(get_last_error())
228 cdef MipmappedArray self = MipmappedArray.__new__(MipmappedArray) 1facbdeijgh
229 self._handle = h 1facbdeijgh
230 self._shape = shape_t 1facbdeijgh
231 self._format = c_format 1facbdeijgh
232 self._num_channels = opts.num_channels 1facbdeijgh
233 self._num_levels = <unsigned int>opts.num_levels 1facbdeijgh
234 self._surface_load_store = bool(opts.is_surface_load_store) 1facbdeijgh
235 self._device_id = _get_current_device_id() 1facbdeijgh
236 return self 1facbdeijgh