Coverage for cuda/core/texture/_mipmapped_array.pyx: 87.14%
70 statements
« prev ^ index » next coverage.py v7.15.2, created at 2026-07-29 01:38 +0000
« prev ^ index » next coverage.py v7.15.2, created at 2026-07-29 01:38 +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) 1acbdemnlkhifg
68 self.shape = _validate_array_shape(self.shape) 1acbdelkhifg
69 self.num_levels = int(self.num_levels) 1acbdekhifg
70 if self.num_levels < 1: 1acbdekhifg
71 raise ValueError(f"num_levels must be >= 1, got {self.num_levels}") 1k
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( 1o
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 lvl = int(level) 1cbde
112 if lvl < 0: 1cbde
113 raise ValueError(f"level must be >= 0, got {lvl}") 1b
114 if lvl >= <int>self._num_levels: 1cbde
115 raise ValueError( 1jb
116 f"level ({lvl}) must be < num_levels ({self._num_levels})" 1b
117 )
119 cdef OpaqueArrayHandle h_level = create_array_level_handle(self._handle, <unsigned int>lvl) 1cde
120 if not h_level: 1cde
121 HANDLE_RETURN(get_last_error())
122 # The returned OpaqueArray is non-owning; its C++ box embeds this mipmap's
123 # handle, so the parent's storage structurally outlives the level view
124 # (no Python parent reference needed).
125 return _array_from_handle(h_level, self._device_id) 1cde
127 @property
128 def handle(self):
129 """The underlying ``CUmipmappedArray`` as an integer."""
130 return as_intptr(self._handle) 1ag
132 @property
133 def shape(self):
134 """Base-level (level 0) allocation shape, in elements."""
135 return self._shape 1a
137 @property
138 def format(self):
139 """The element :class:`~cuda.core.typing.ArrayFormatType`."""
140 return _CU_TO_ARRAYFORMAT[self._format] 1a
142 @property
143 def num_channels(self):
144 """Channels per element (1, 2, or 4)."""
145 return self._num_channels 1a
147 @property
148 def num_levels(self):
149 """Number of mip levels."""
150 return int(self._num_levels) 1abf
152 @property
153 def is_surface_load_store(self):
154 """True if this mipmap (and each of its levels) was created with
155 ``CUDA_ARRAY3D_SURFACE_LDST`` and can back a :class:`SurfaceObject`."""
156 return self._surface_load_store 1a
158 @property
159 def device(self):
160 """The :class:`Device` this mipmap was allocated on."""
161 from cuda.core._device import Device 1a
162 return Device(self._device_id) 1a
164 cpdef close(self):
165 """Release this object's reference to the underlying ``CUmipmappedArray``.
167 Destruction (``cuMipmappedArrayDestroy``) happens via the handle's
168 deleter when the last reference is dropped. A level :class:`OpaqueArray`
169 from :meth:`get_level` holds its own reference to this mipmap's storage,
170 so it stays valid until both it and this object are released. Idempotent.
171 """
172 self._handle.reset() 1acbdhifg
174 def __enter__(self):
175 return self
177 def __exit__(self, exc_type, exc, tb):
178 self.close()
180 def __repr__(self):
181 return (
182 f"MipmappedArray(shape={self._shape}, "
183 f"format={_CU_TO_ARRAYFORMAT[self._format].name}, "
184 f"num_channels={self._num_channels}, "
185 f"num_levels={self._num_levels})"
186 )
189def _create_mipmapped_array(options):
190 """Allocate a new :class:`MipmappedArray` on the current device.
192 Backs :meth:`cuda.core.Device.create_mipmapped_array`. ``options`` is a
193 :class:`MipmappedArrayOptions` (or a mapping accepted by it); its fields are
194 validated at construction.
195 """
196 cdef object opts = check_or_create_options( 1acbdehifg
197 MipmappedArrayOptions, options, "Mipmapped array options" 1acbdehifg
198 )
199 shape_t = opts.shape 1acbdehifg
201 cdef cydriver.CUarray_format c_format = <cydriver.CUarray_format>_ARRAYFORMAT_TO_CU[opts.format] 1acbdehifg
202 cdef int rank = len(shape_t) 1acbdehifg
203 cdef unsigned int flags = (
204 cydriver.CUDA_ARRAY3D_SURFACE_LDST if opts.is_surface_load_store else 0 1acbdehifg
205 )
206 cdef unsigned int c_levels = <unsigned int>opts.num_levels 1acbdehifg
208 # Mipmap creation uses the 3D descriptor regardless of rank; lower-rank
209 # shapes use Height=0/Depth=0 sentinels, matching cuArray3DCreate.
210 cdef cydriver.CUDA_ARRAY3D_DESCRIPTOR desc3d = cydriver.CUDA_ARRAY3D_DESCRIPTOR(
211 Width=<size_t>shape_t[0], 1acbdehifg
212 Height=<size_t>(shape_t[1] if rank >= 2 else 0), 1acbdehifg
213 Depth=<size_t>(shape_t[2] if rank >= 3 else 0), 1acbdehifg
214 Format=c_format, 1acbdehifg
215 NumChannels=<unsigned int>opts.num_channels, 1acbdehifg
216 Flags=flags, 1acbdehifg
217 )
219 cdef MipmappedArrayHandle h = create_mipmapped_array_handle(desc3d, c_levels) 1acbdehifg
220 if not h: 1acbdehifg
221 HANDLE_RETURN(get_last_error())
223 cdef MipmappedArray self = MipmappedArray.__new__(MipmappedArray) 1acbdehifg
224 self._handle = h 1acbdehifg
225 self._shape = shape_t 1acbdehifg
226 self._format = c_format 1acbdehifg
227 self._num_channels = opts.num_channels 1acbdehifg
228 self._num_levels = <unsigned int>opts.num_levels 1acbdehifg
229 self._surface_load_store = bool(opts.is_surface_load_store) 1acbdehifg
230 self._device_id = _get_current_device_id() 1acbdehifg
231 return self 1acbdehifg