1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
//! Transferable TMA descriptors and independently retained backing allocations.
use singe_cuda_sys::driver as sys;
use crate::{
context::Context,
error::{Error, Result},
submission::{AccessMode, Resources},
try_ffi,
types::DevicePtr,
utility::{driver_enum, to_u32, to_usize},
view::{DeviceRegionProvider, DeviceRepr, NoUninitDeviceRepr, OwnedDeviceRegion},
};
driver_enum! {
/// Tensor map data type
pub enum TensorMapDataType: sys::CUtensorMapDataType {
/// Unsigned 8-bit integer elements.
U8 = CU_TENSOR_MAP_DATA_TYPE_UINT8,
/// Unsigned 16-bit integer elements.
U16 = CU_TENSOR_MAP_DATA_TYPE_UINT16,
/// Unsigned 32-bit integer elements.
U32 = CU_TENSOR_MAP_DATA_TYPE_UINT32,
/// Signed 32-bit integer elements.
I32 = CU_TENSOR_MAP_DATA_TYPE_INT32,
/// Unsigned 64-bit integer elements.
U64 = CU_TENSOR_MAP_DATA_TYPE_UINT64,
/// Signed 64-bit integer elements.
I64 = CU_TENSOR_MAP_DATA_TYPE_INT64,
/// 16-bit floating-point elements.
F16 = CU_TENSOR_MAP_DATA_TYPE_FLOAT16,
/// 32-bit floating-point elements.
F32 = CU_TENSOR_MAP_DATA_TYPE_FLOAT32,
/// 64-bit floating-point elements.
F64 = CU_TENSOR_MAP_DATA_TYPE_FLOAT64,
/// 16-bit brain floating-point elements.
Bf16 = CU_TENSOR_MAP_DATA_TYPE_BFLOAT16,
/// 32-bit floating-point elements with subnormal values flushed to zero.
F32Ftz = CU_TENSOR_MAP_DATA_TYPE_FLOAT32_FTZ,
/// TensorFloat-32 elements.
Tf32 = CU_TENSOR_MAP_DATA_TYPE_TFLOAT32,
/// TensorFloat-32 elements with subnormal values flushed to zero.
Tf32Ftz = CU_TENSOR_MAP_DATA_TYPE_TFLOAT32_FTZ,
/// Groups of sixteen unsigned 4-bit values packed into eight bytes, with no gaps between groups.
U4x16Align8 = CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN8B,
/// Groups of sixteen unsigned 4-bit values in 16-byte-aligned storage, with eight padding bytes after each eight-byte packed group.
U4x16Align16 = CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B,
/// Groups of sixteen unsigned 6-bit values in 16-byte-aligned storage, with four padding bytes after each twelve-byte packed group.
U6x16Align16 = CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B,
}
}
driver_enum! {
/// Tensor map interleave layout type
#[derive(Default)]
pub enum Interleave: sys::CUtensorMapInterleave {
/// No channel interleaving.
#[default]
None = CU_TENSOR_MAP_INTERLEAVE_NONE,
/// Interleaves channels in 16-byte groups, such as eight 16-bit channels per group.
Bytes16 = CU_TENSOR_MAP_INTERLEAVE_16B,
/// Interleaves channels in 32-byte groups, such as sixteen 16-bit channels per group.
Bytes32 = CU_TENSOR_MAP_INTERLEAVE_32B,
}
}
driver_enum! {
/// Tensor map swizzling mode of shared memory banks
#[derive(Default)]
pub enum Swizzle: sys::CUtensorMapSwizzle {
/// No shared-memory swizzling.
#[default]
None = CU_TENSOR_MAP_SWIZZLE_NONE,
/// Swizzles 16-byte chunks within a 32-byte span.
Bytes32 = CU_TENSOR_MAP_SWIZZLE_32B,
/// Swizzles 16-byte chunks within a 64-byte span.
Bytes64 = CU_TENSOR_MAP_SWIZZLE_64B,
/// Swizzles 16-byte chunks within a 128-byte span.
Bytes128 = CU_TENSOR_MAP_SWIZZLE_128B,
/// Swizzles 32-byte chunks within a 128-byte span.
Bytes128Atom32 = CU_TENSOR_MAP_SWIZZLE_128B_ATOM_32B,
/// Swizzles 32-byte chunks within a 128-byte span and exchanges the lower and upper eight bytes of each 16-byte unit on alternate rows.
Bytes128Atom32Flip8 = CU_TENSOR_MAP_SWIZZLE_128B_ATOM_32B_FLIP_8B,
/// Swizzles 64-byte chunks within a 128-byte span.
Bytes128Atom64 = CU_TENSOR_MAP_SWIZZLE_128B_ATOM_64B,
}
}
driver_enum! {
/// Tensor map L2 promotion type
#[derive(Default)]
pub enum L2Promotion: sys::CUtensorMapL2promotion {
/// No L2 fetch-size promotion.
#[default]
None = CU_TENSOR_MAP_L2_PROMOTION_NONE,
/// Fills L2 requests from DRAM at 64-byte granularity.
Bytes64 = CU_TENSOR_MAP_L2_PROMOTION_L2_64B,
/// Fills L2 requests from DRAM at 128-byte granularity.
Bytes128 = CU_TENSOR_MAP_L2_PROMOTION_L2_128B,
/// Fills L2 requests from DRAM at 256-byte granularity.
Bytes256 = CU_TENSOR_MAP_L2_PROMOTION_L2_256B,
}
}
driver_enum! {
/// Tensor map out-of-bounds fill type
#[derive(Default)]
pub enum OutOfBoundsFill: sys::CUtensorMapFloatOOBfill {
/// Fills out-of-bounds elements with zero.
#[default]
Zero = CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE,
/// Fills out-of-bounds elements with the special NaN value that requests zero contribution to FMA.
/// Only floating-point tensor data types support this mode.
NanRequestZeroFma = CU_TENSOR_MAP_FLOAT_OOB_FILL_NAN_REQUEST_ZERO_FMA,
}
}
driver_enum! {
/// Tensor-map image-to-column loading width.
#[derive(Default)]
pub enum Im2colWideMode: sys::CUtensorMapIm2ColWideMode {
/// Loads along the W dimension using the element count in `pixelsPerColumn`.
#[default]
Width = CU_TENSOR_MAP_IM2COL_WIDE_MODE_W,
/// Uses native W128 loading along the W dimension; `pixelsPerColumn` is ignored.
Width128 = CU_TENSOR_MAP_IM2COL_WIDE_MODE_W128,
}
}
driver_enum! {
/// Tensor map swizzling mode of shared memory banks
#[derive(Default)]
pub enum Im2colWideSwizzle: sys::CUtensorMapSwizzle {
/// Swizzles 16-byte chunks within a 64-byte span.
#[default]
Bytes64 = CU_TENSOR_MAP_SWIZZLE_64B,
/// Swizzles 16-byte chunks within a 128-byte span.
Bytes128 = CU_TENSOR_MAP_SWIZZLE_128B,
/// Swizzles 32-byte chunks within a 128-byte span.
Bytes128Atom32 = CU_TENSOR_MAP_SWIZZLE_128B_ATOM_32B,
}
}
/// Interleaving, shared-memory swizzling, L2 promotion, and out-of-bounds behavior for tensor-map encoding.
///
/// `S` restricts the swizzle choices accepted by the selected encoding mode.
/// Defaults use no interleaving, the default swizzle for `S`, no L2 promotion, and zero fill.
#[derive(Debug, Clone, Copy, Default)]
pub struct TensorMapOptions<S = Swizzle> {
/// Channel interleave layout of the global tensor.
pub interleave: Interleave,
/// Shared-memory bank swizzle pattern supported by the encoding mode.
pub swizzle: S,
/// L2 fetch-size promotion used for tensor accesses.
pub l2_promotion: L2Promotion,
/// Value used for out-of-bounds tensor elements.
pub out_of_bounds_fill: OutOfBoundsFill,
}
/// Fastest-varying dimension first; byte strides omit the implicit dimension-zero stride.
#[derive(Debug, Clone, Copy)]
pub struct TensorMapLayout<'a> {
/// Scalar or packed element format of the global tensor.
pub data_type: TensorMapDataType,
/// Element count along each axis, fastest-varying first.
/// Each must lie in `1..=2^32`; supported ranks depend on the encoding mode.
pub dimensions: &'a [u64],
/// Byte strides for axes one through rank minus one.
/// The dimension-zero stride is implicit.
/// Each supplied stride must be positive, a multiple of 16, and less than `2^40`.
pub byte_strides: &'a [u64],
/// Traversal step along every axis, with one entry per dimension.
/// Each must lie in `1..=8`; CUDA ignores the first step when interleaving is disabled.
pub element_strides: &'a [u32],
}
impl TensorMapLayout<'_> {
fn validate(&self, minimum_rank: usize) -> Result<u32> {
let rank = self.dimensions.len();
if !(minimum_rank..=5).contains(&rank) {
return Err(Error::out_of_range("tensor map rank"));
}
if self.byte_strides.len() != rank - 1 {
return Err(Error::length_mismatch(
"byte strides",
rank - 1,
self.byte_strides.len(),
));
}
if self.element_strides.len() != rank {
return Err(Error::length_mismatch(
"element strides",
rank,
self.element_strides.len(),
));
}
if self
.dimensions
.iter()
.any(|&dimension| dimension == 0 || dimension > 1 << 32)
{
return Err(Error::out_of_range("tensor map dimension"));
}
for &stride in self.byte_strides {
if stride == 0 || stride >= 1 << 40 {
return Err(Error::out_of_range("tensor map byte stride"));
}
if !stride.is_multiple_of(16) {
return Err(Error::misaligned("tensor map byte stride", 16));
}
}
if self
.element_strides
.iter()
.any(|&stride| !(1..=8).contains(&stride))
{
return Err(Error::out_of_range("tensor map element stride"));
}
to_u32(rank, "tensor map rank")
}
fn required_bytes(&self) -> Result<u64> {
self.validate(1)?;
let width = self.dimensions[0];
let row = match self.data_type {
TensorMapDataType::U4x16Align8 => Some(width.div_ceil(2)),
TensorMapDataType::U4x16Align16 | TensorMapDataType::U6x16Align16 => {
width.div_ceil(16).checked_mul(16)
}
TensorMapDataType::U8 => Some(width),
TensorMapDataType::U16 | TensorMapDataType::F16 | TensorMapDataType::Bf16 => {
width.checked_mul(2)
}
TensorMapDataType::U32
| TensorMapDataType::I32
| TensorMapDataType::F32
| TensorMapDataType::F32Ftz
| TensorMapDataType::Tf32
| TensorMapDataType::Tf32Ftz => width.checked_mul(4),
TensorMapDataType::U64 | TensorMapDataType::I64 | TensorMapDataType::F64 => {
width.checked_mul(8)
}
}
.ok_or_else(|| Error::out_of_range("tensor map row bytes"))?;
self.dimensions[1..].iter().zip(self.byte_strides).try_fold(
row,
|bytes, (&dimension, &stride)| {
(dimension - 1)
.checked_mul(stride)
.and_then(|offset| bytes.checked_add(offset))
.ok_or_else(|| Error::out_of_range("tensor map byte span"))
},
)
}
}
/// Spatial pixel-box corners and channel counts for image-to-column tensor-map encoding.
///
/// Each corner slice must have rank minus two entries.
#[derive(Debug, Clone, Copy)]
pub struct Im2colBox<'a> {
/// Spatial coordinates of the lower pixel-box corner.
pub lower_corner: &'a [i32],
/// Spatial coordinates of the upper pixel-box corner.
pub upper_corner: &'a [i32],
/// Number of channels per pixel.
pub channels_per_pixel: u32,
/// Number of pixels per output column.
pub pixels_per_column: u32,
}
/// Width-only pixel-box bounds and channel counts for wide image-to-column encoding.
///
/// The box has a size of one along its depth and height axes.
/// Native wide encoding requires compute capability 10.0 or higher.
#[derive(Debug, Clone, Copy)]
pub struct Im2colWideBox {
/// Width coordinate offset of the left box corner.
pub lower_width: i32,
/// Width coordinate offset of the right box corner.
pub upper_width: i32,
/// Number of channels per pixel.
pub channels_per_pixel: u32,
/// Number of pixels per output column; ignored in W128 mode.
pub pixels_per_column: u32,
/// Native W or W128 width-loading mode.
pub mode: Im2colWideMode,
}
/// CUDA-aligned descriptor bytes suitable for kernel arguments and device transfer.
/// This value owns no backing memory and makes no initialization or access claim.
#[derive(Debug, Clone, Copy)]
#[repr(transparent)]
pub struct TensorMapDescriptor(sys::CUtensorMap);
// SAFETY: the descriptor is a transparent 128-byte-aligned array of sixteen `u64` words, with no padding, host pointers, or Rust ownership.
unsafe impl DeviceRepr for TensorMapDescriptor {}
// SAFETY: every byte of the native descriptor array is initialized, by `Default` or by the encoding call.
unsafe impl NoUninitDeviceRepr for TensorMapDescriptor {}
impl TensorMapDescriptor {
/// Borrows the native descriptor bytes without retaining backing memory.
#[must_use]
pub fn as_raw(&self) -> &sys::CUtensorMap {
&self.0
}
/// Returns the native descriptor bytes by value without retaining backing memory.
#[must_use]
pub fn into_raw(self) -> sys::CUtensorMap {
self.0
}
/// Wraps initialized native tensor-map descriptor bytes without retaining their backing memory.
///
/// # Safety
///
/// The value must be a successfully encoded CUDA tensor map with initialized descriptor bytes.
#[must_use]
pub unsafe fn from_raw(raw: sys::CUtensorMap) -> Self {
Self(raw)
}
/// Encodes a tiled layout at a raw global address.
///
/// # Safety
///
/// The address must satisfy CUDA's global-memory, alignment and layout restrictions.
/// Retain backing memory and establish initialization and ordering before device use.
///
/// # Errors
///
/// Returns an error if the rank, a dimension size, a byte stride, or a traversal stride is unsupported, a slice length does not match the rank, a byte stride is not a multiple of 16 bytes, `context` cannot be bound, or CUDA rejects the layout, options, address, or device.
/// The box must have one size per tensor dimension, each in `1..=256`.
pub unsafe fn encode_tiled(
context: &Context,
address: DevicePtr,
layout: TensorMapLayout<'_>,
box_dimensions: &[u32],
options: TensorMapOptions,
) -> Result<Self> {
let rank = layout.validate(1)?;
let rank_len = to_usize(rank, "tensor map rank")?;
if box_dimensions.len() != rank_len {
return Err(Error::length_mismatch(
"box dimensions",
rank_len,
box_dimensions.len(),
));
}
if box_dimensions
.iter()
.any(|&dimension| !(1..=256).contains(&dimension))
{
return Err(Error::out_of_range("box dimension"));
}
context.bind()?;
let mut raw = sys::CUtensorMap::default();
// SAFETY: `validate` checked that the layout slices and `box_dimensions` hold `rank` entries, `raw` is a local output, and the caller guarantees the address meets CUDA's restrictions.
unsafe {
try_ffi!(sys::cuTensorMapEncodeTiled(
&raw mut raw,
layout.data_type.into(),
rank,
address.as_raw().cast(),
layout.dimensions.as_ptr(),
layout.byte_strides.as_ptr(),
box_dimensions.as_ptr(),
layout.element_strides.as_ptr(),
options.interleave.into(),
options.swizzle.into(),
options.l2_promotion.into(),
options.out_of_bounds_fill.into()
))?;
}
Ok(Self(raw))
}
/// Encodes an im2col layout with rank-minus-two spatial box corners.
///
/// # Safety
///
/// Uphold [`Self::encode_tiled`]'s memory and lifetime contract for this layout.
///
/// # Errors
///
/// Returns an error if the rank, a dimension size, a byte stride, or a traversal stride is unsupported, a slice length does not match the rank, a byte stride is not a multiple of 16 bytes, `context` cannot be bound, or CUDA rejects the layout, options, address, or device.
/// The tensor rank must be three through five, and both corner slices must have rank minus two entries.
pub unsafe fn encode_im2col(
context: &Context,
address: DevicePtr,
layout: TensorMapLayout<'_>,
pixel_box: Im2colBox<'_>,
options: TensorMapOptions,
) -> Result<Self> {
let rank = layout.validate(3)?;
let corner_len = to_usize(rank, "tensor map rank")? - 2;
if pixel_box.lower_corner.len() != corner_len {
return Err(Error::length_mismatch(
"lower corner",
corner_len,
pixel_box.lower_corner.len(),
));
}
if pixel_box.upper_corner.len() != corner_len {
return Err(Error::length_mismatch(
"upper corner",
corner_len,
pixel_box.upper_corner.len(),
));
}
context.bind()?;
let mut raw = sys::CUtensorMap::default();
// SAFETY: the layout slices hold `rank` entries and both corners `rank - 2`, as checked above, `raw` is a local output, and the caller guarantees the address meets CUDA's restrictions.
unsafe {
try_ffi!(sys::cuTensorMapEncodeIm2col(
&raw mut raw,
layout.data_type.into(),
rank,
address.as_raw().cast(),
layout.dimensions.as_ptr(),
layout.byte_strides.as_ptr(),
pixel_box.lower_corner.as_ptr(),
pixel_box.upper_corner.as_ptr(),
pixel_box.channels_per_pixel,
pixel_box.pixels_per_column,
layout.element_strides.as_ptr(),
options.interleave.into(),
options.swizzle.into(),
options.l2_promotion.into(),
options.out_of_bounds_fill.into()
))?;
}
Ok(Self(raw))
}
/// Encodes wide-im2col layouts on devices supporting the native mode.
///
/// # Safety
///
/// Uphold [`Self::encode_tiled`]'s memory and lifetime contract for this layout.
///
/// # Errors
///
/// Returns an error if the rank, a dimension size, a byte stride, or a traversal stride is unsupported, a slice length does not match the rank, a byte stride is not a multiple of 16 bytes, `context` cannot be bound, or CUDA rejects the layout, options, address, or device.
/// The tensor rank must be three through five; CUDA additionally validates the width box and wide-loading mode.
pub unsafe fn encode_im2col_wide(
context: &Context,
address: DevicePtr,
layout: TensorMapLayout<'_>,
pixel_box: Im2colWideBox,
options: TensorMapOptions<Im2colWideSwizzle>,
) -> Result<Self> {
let rank = layout.validate(3)?;
context.bind()?;
let mut raw = sys::CUtensorMap::default();
// SAFETY: `validate` checked that the layout slices hold `rank` entries, `raw` is a local output, and the caller guarantees the address meets CUDA's restrictions.
unsafe {
try_ffi!(sys::cuTensorMapEncodeIm2colWide(
&raw mut raw,
layout.data_type.into(),
rank,
address.as_raw().cast(),
layout.dimensions.as_ptr(),
layout.byte_strides.as_ptr(),
pixel_box.lower_width,
pixel_box.upper_width,
pixel_box.channels_per_pixel,
pixel_box.pixels_per_column,
layout.element_strides.as_ptr(),
options.interleave.into(),
pixel_box.mode.into(),
options.swizzle.into(),
options.l2_promotion.into(),
options.out_of_bounds_fill.into()
))?;
}
Ok(Self(raw))
}
/// Replaces the global base while preserving the encoded layout.
///
/// # Safety
///
/// The new storage must satisfy the original descriptor's size, alignment and memory restrictions.
/// Existing descriptor copies and in-flight users are unaffected and retain their own lifetime obligations.
///
/// # Errors
///
/// Returns an error if `context` cannot be bound or CUDA rejects the replacement address for the descriptor's encoded layout.
pub unsafe fn replace_address(&mut self, context: &Context, address: DevicePtr) -> Result<()> {
context.bind()?;
// SAFETY: `self.0` is an encoded descriptor borrowed exclusively, and the caller guarantees the new address satisfies its encoded layout.
unsafe {
try_ffi!(sys::cuTensorMapReplaceAddress(
&raw mut self.0,
address.as_raw().cast()
))
}
}
}
/// Host ownership accompanying a transferable tensor-map descriptor.
#[derive(Debug)]
pub struct RetainedTensorMap<O: DeviceRegionProvider + Send + Sync + 'static> {
descriptor: TensorMapDescriptor,
region: OwnedDeviceRegion<O>,
required_bytes: usize,
}
impl<O: DeviceRegionProvider + Send + Sync + 'static> RetainedTensorMap<O> {
fn encode(
region: OwnedDeviceRegion<O>,
layout: TensorMapLayout<'_>,
encode: impl FnOnce(&Context, DevicePtr) -> Result<TensorMapDescriptor>,
) -> Result<Self> {
let required_bytes = to_usize(layout.required_bytes()?, "tensor map byte span")?;
if required_bytes > region.byte_len() {
return Err(Error::buffer_too_small(
"device region",
required_bytes,
region.byte_len(),
));
}
// SAFETY: the address is the start of `region`, a live allocation in `region.context()` that the returned map retains.
let descriptor = encode(region.context(), unsafe {
DevicePtr::from_raw(region.region().as_ptr().cast())
})?;
Ok(Self {
descriptor,
region,
required_bytes,
})
}
/// Encodes a tiled tensor map while retaining its backing device region.
///
/// Checks that the region covers the byte span described by `layout`.
/// Retention does not establish initialization or order later device accesses.
///
/// # Errors
///
/// Returns an error if the region is smaller than the layout's byte span, the span overflows, or [`TensorMapDescriptor::encode_tiled`] fails.
pub fn tiled(
region: OwnedDeviceRegion<O>,
layout: TensorMapLayout<'_>,
box_dimensions: &[u32],
options: TensorMapOptions,
) -> Result<Self> {
// SAFETY: `encode` checks that the region covers the layout's byte span and retains it with the descriptor.
Self::encode(region, layout, |context, address| unsafe {
TensorMapDescriptor::encode_tiled(context, address, layout, box_dimensions, options)
})
}
/// Encodes an image-to-column tensor map while retaining its backing device region.
///
/// Checks that the region covers the byte span described by `layout`.
/// Retention does not establish initialization or order later device accesses.
///
/// # Errors
///
/// Returns an error if the region is smaller than the layout's byte span, the span overflows, or [`TensorMapDescriptor::encode_im2col`] fails.
pub fn im2col(
region: OwnedDeviceRegion<O>,
layout: TensorMapLayout<'_>,
pixel_box: Im2colBox<'_>,
options: TensorMapOptions,
) -> Result<Self> {
// SAFETY: `encode` checks that the region covers the layout's byte span and retains it with the descriptor.
Self::encode(region, layout, |context, address| unsafe {
TensorMapDescriptor::encode_im2col(context, address, layout, pixel_box, options)
})
}
/// Encodes a wide image-to-column tensor map while retaining its backing device region.
///
/// Checks that the region covers the byte span described by `layout`.
/// Retention does not establish initialization or order later device accesses.
///
/// # Errors
///
/// Returns an error if the region is smaller than the layout's byte span, the span overflows, or [`TensorMapDescriptor::encode_im2col_wide`] fails.
pub fn im2col_wide(
region: OwnedDeviceRegion<O>,
layout: TensorMapLayout<'_>,
pixel_box: Im2colWideBox,
options: TensorMapOptions<Im2colWideSwizzle>,
) -> Result<Self> {
// SAFETY: `encode` checks that the region covers the layout's byte span and retains it with the descriptor.
Self::encode(region, layout, |context, address| unsafe {
TensorMapDescriptor::encode_im2col_wide(context, address, layout, pixel_box, options)
})
}
/// Borrows the transferable descriptor.
///
/// Copies of its bytes do not retain this object or the backing region.
#[must_use]
pub fn descriptor(&self) -> &TensorMapDescriptor {
&self.descriptor
}
/// Borrows the owned backing region retained alongside the descriptor.
#[must_use]
pub fn region(&self) -> &OwnedDeviceRegion<O> {
&self.region
}
/// Creates a resource ledger retaining the backing region and declaring `mode` access to it.
///
/// The declaration preserves region readiness but does not initialize storage or grant access permissions.
#[must_use]
pub fn resources(&self, mode: AccessMode) -> Resources {
let mut resources = Resources::new();
resources.retain_access(self.region.clone(), mode);
resources
}
/// Replaces the descriptor's base address and retained backing region, preserving its encoded layout.
///
/// Previously copied descriptors still point to the old region.
/// Keep that region alive for any executions that use those copies.
///
/// # Errors
///
/// Returns an error if the new region belongs to another context, is too short for the encoded layout, or its context cannot be bound, or if CUDA rejects the replacement address.
/// The retained region changes only after replacement succeeds.
pub fn replace_region(&mut self, region: OwnedDeviceRegion<O>) -> Result<()> {
if region.context() != self.region.context() {
return Err(Error::MemoryContextMismatch);
}
if self.required_bytes > region.byte_len() {
return Err(Error::buffer_too_small(
"device region",
self.required_bytes,
region.byte_len(),
));
}
// SAFETY: the new region is in the descriptor's context and covers the encoded byte span, as checked above, and `self` retains it after replacement.
unsafe {
self.descriptor.replace_address(
region.context(),
DevicePtr::from_raw(region.region().as_ptr().cast()),
)?;
}
self.region = region;
Ok(())
}
}