|
| 1 | +//! DLPack interchange (the `DLManagedTensor` C ABI, v0.x): hand tensors to and take tensors from NumPy, PyTorch, JAX, |
| 2 | +//! CuPy and anything else that speaks the protocol. |
| 3 | +//! |
| 4 | +//! [`to_dlpack`] returns a heap `DLManagedTensor` whose `deleter` the consumer must call exactly once; [`from_dlpack`] |
| 5 | +//! consumes one (strided, offset and non-contiguous inputs included) and calls its deleter. |
| 6 | +//! |
| 7 | +//! ponytail: both directions copy the data (storage here can be reallocated behind its lock, so a borrowed pointer could |
| 8 | +//! dangle). Zero-copy export needs pinned storage; add it if exchange of very large arrays becomes a bottleneck. |
| 9 | +
|
| 10 | +use crate::dtype::{DType, bf16, f16}; |
| 11 | +use crate::error::{Error, Result}; |
| 12 | +use crate::tensor::Tensor; |
| 13 | +use std::ffi::c_void; |
| 14 | + |
| 15 | +pub const DL_CPU: i32 = 1; |
| 16 | +const CODE_INT: u8 = 0; |
| 17 | +const CODE_UINT: u8 = 1; |
| 18 | +const CODE_FLOAT: u8 = 2; |
| 19 | +const CODE_BFLOAT: u8 = 4; |
| 20 | +const CODE_BOOL: u8 = 6; |
| 21 | + |
| 22 | +#[repr(C)] |
| 23 | +#[derive(Clone, Copy, Debug)] |
| 24 | +pub struct DLDevice { |
| 25 | + pub device_type: i32, |
| 26 | + pub device_id: i32, |
| 27 | +} |
| 28 | + |
| 29 | +#[repr(C)] |
| 30 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 31 | +pub struct DLDataType { |
| 32 | + pub code: u8, |
| 33 | + pub bits: u8, |
| 34 | + pub lanes: u16, |
| 35 | +} |
| 36 | + |
| 37 | +#[repr(C)] |
| 38 | +pub struct DLTensor { |
| 39 | + pub data: *mut c_void, |
| 40 | + pub device: DLDevice, |
| 41 | + pub ndim: i32, |
| 42 | + pub dtype: DLDataType, |
| 43 | + pub shape: *mut i64, |
| 44 | + pub strides: *mut i64, |
| 45 | + pub byte_offset: u64, |
| 46 | +} |
| 47 | + |
| 48 | +#[repr(C)] |
| 49 | +pub struct DLManagedTensor { |
| 50 | + pub dl_tensor: DLTensor, |
| 51 | + pub manager_ctx: *mut c_void, |
| 52 | + pub deleter: Option<unsafe extern "C" fn(*mut DLManagedTensor)>, |
| 53 | +} |
| 54 | + |
| 55 | +fn err(m: impl Into<String>) -> Error { |
| 56 | + Error::Msg(format!("dlpack: {}", m.into())) |
| 57 | +} |
| 58 | + |
| 59 | +fn dl_type(d: DType) -> Result<DLDataType> { |
| 60 | + let (code, bits) = match d { |
| 61 | + DType::Bool => (CODE_BOOL, 8), |
| 62 | + DType::U8 => (CODE_UINT, 8), |
| 63 | + DType::U16 => (CODE_UINT, 16), |
| 64 | + DType::U32 => (CODE_UINT, 32), |
| 65 | + DType::U64 => (CODE_UINT, 64), |
| 66 | + DType::I8 => (CODE_INT, 8), |
| 67 | + DType::I16 => (CODE_INT, 16), |
| 68 | + DType::I32 => (CODE_INT, 32), |
| 69 | + DType::I64 => (CODE_INT, 64), |
| 70 | + DType::F16 => (CODE_FLOAT, 16), |
| 71 | + DType::F32 => (CODE_FLOAT, 32), |
| 72 | + DType::F64 => (CODE_FLOAT, 64), |
| 73 | + DType::BF16 => (CODE_BFLOAT, 16), |
| 74 | + DType::F8E4M3 | DType::F8E5M2 => return Err(err("8-bit floats have no DLPack type code; cast to f32 first")), |
| 75 | + }; |
| 76 | + Ok(DLDataType { code, bits, lanes: 1 }) |
| 77 | +} |
| 78 | + |
| 79 | +fn from_dl_type(t: DLDataType) -> Result<DType> { |
| 80 | + if t.lanes != 1 { |
| 81 | + return Err(err("vector (multi-lane) types are not supported")); |
| 82 | + } |
| 83 | + Ok(match (t.code, t.bits) { |
| 84 | + (CODE_BOOL, 8) => DType::Bool, |
| 85 | + (CODE_UINT, 8) => DType::U8, |
| 86 | + (CODE_UINT, 16) => DType::U16, |
| 87 | + (CODE_UINT, 32) => DType::U32, |
| 88 | + (CODE_UINT, 64) => DType::U64, |
| 89 | + (CODE_INT, 8) => DType::I8, |
| 90 | + (CODE_INT, 16) => DType::I16, |
| 91 | + (CODE_INT, 32) => DType::I32, |
| 92 | + (CODE_INT, 64) => DType::I64, |
| 93 | + (CODE_FLOAT, 16) => DType::F16, |
| 94 | + (CODE_FLOAT, 32) => DType::F32, |
| 95 | + (CODE_FLOAT, 64) => DType::F64, |
| 96 | + (CODE_BFLOAT, 16) => DType::BF16, |
| 97 | + (c, b) => return Err(err(format!("unsupported type code {c} with {b} bits"))), |
| 98 | + }) |
| 99 | +} |
| 100 | + |
| 101 | +/// The tensor's elements in logical (row-major) order as native-endian bytes. |
| 102 | +fn to_bytes(t: &Tensor) -> Result<Vec<u8>> { |
| 103 | + macro_rules! raw { |
| 104 | + ($ty:ty) => { |
| 105 | + t.to_vec::<$ty>()?.iter().flat_map(|v| v.to_ne_bytes()).collect() |
| 106 | + }; |
| 107 | + } |
| 108 | + Ok(match t.dtype() { |
| 109 | + DType::Bool => t.to_vec::<bool>()?.into_iter().map(u8::from).collect(), |
| 110 | + DType::U8 => t.to_vec::<u8>()?, |
| 111 | + DType::U16 => raw!(u16), |
| 112 | + DType::U32 => raw!(u32), |
| 113 | + DType::U64 => raw!(u64), |
| 114 | + DType::I8 => raw!(i8), |
| 115 | + DType::I16 => raw!(i16), |
| 116 | + DType::I32 => raw!(i32), |
| 117 | + DType::I64 => raw!(i64), |
| 118 | + DType::F32 => raw!(f32), |
| 119 | + DType::F64 => raw!(f64), |
| 120 | + DType::F16 => t.to_vec::<f16>()?.iter().flat_map(|v| v.to_bits().to_ne_bytes()).collect(), |
| 121 | + DType::BF16 => t.to_vec::<bf16>()?.iter().flat_map(|v| v.to_bits().to_ne_bytes()).collect(), |
| 122 | + DType::F8E4M3 | DType::F8E5M2 => return Err(err("8-bit floats have no DLPack type code; cast to f32 first")), |
| 123 | + }) |
| 124 | +} |
| 125 | + |
| 126 | +fn from_bytes(bytes: &[u8], dtype: DType, shape: &[usize]) -> Result<Tensor> { |
| 127 | + macro_rules! typed { |
| 128 | + ($ty:ty, $n:expr) => { |
| 129 | + Tensor::from_vec(bytes.chunks_exact($n).map(|c| <$ty>::from_ne_bytes(c.try_into().unwrap())).collect::<Vec<$ty>>(), shape) |
| 130 | + }; |
| 131 | + } |
| 132 | + match dtype { |
| 133 | + DType::Bool => Tensor::from_vec(bytes.iter().map(|&b| b != 0).collect::<Vec<bool>>(), shape), |
| 134 | + DType::U8 => Tensor::from_vec(bytes.to_vec(), shape), |
| 135 | + DType::U16 => typed!(u16, 2), |
| 136 | + DType::U32 => typed!(u32, 4), |
| 137 | + DType::U64 => typed!(u64, 8), |
| 138 | + DType::I8 => typed!(i8, 1), |
| 139 | + DType::I16 => typed!(i16, 2), |
| 140 | + DType::I32 => typed!(i32, 4), |
| 141 | + DType::I64 => typed!(i64, 8), |
| 142 | + DType::F32 => typed!(f32, 4), |
| 143 | + DType::F64 => typed!(f64, 8), |
| 144 | + DType::F16 => Tensor::from_vec(bytes.chunks_exact(2).map(|c| f16::from_bits(u16::from_ne_bytes([c[0], c[1]]))).collect::<Vec<f16>>(), shape), |
| 145 | + DType::BF16 => Tensor::from_vec(bytes.chunks_exact(2).map(|c| bf16::from_bits(u16::from_ne_bytes([c[0], c[1]]))).collect::<Vec<bf16>>(), shape), |
| 146 | + DType::F8E4M3 | DType::F8E5M2 => Err(err("8-bit floats have no DLPack type code")), |
| 147 | + } |
| 148 | +} |
| 149 | + |
| 150 | +struct Owner { |
| 151 | + _data: Vec<u8>, |
| 152 | + _shape: Vec<i64>, |
| 153 | +} |
| 154 | + |
| 155 | +unsafe extern "C" fn delete_owned(p: *mut DLManagedTensor) { |
| 156 | + if p.is_null() { |
| 157 | + return; |
| 158 | + } |
| 159 | + // SAFETY: `p` and its `manager_ctx` were produced by `Box::into_raw` in `to_dlpack`, and the DLPack contract has the |
| 160 | + // consumer call the deleter exactly once. |
| 161 | + unsafe { |
| 162 | + let m = Box::from_raw(p); |
| 163 | + drop(Box::from_raw(m.manager_ctx as *mut Owner)); |
| 164 | + } |
| 165 | +} |
| 166 | + |
| 167 | +/// Exports a copy of `t` (any layout, CPU data) as a `DLManagedTensor`. The caller owns the pointer and must hand it to a |
| 168 | +/// consumer or call its `deleter`. |
| 169 | +pub fn to_dlpack(t: &Tensor) -> Result<*mut DLManagedTensor> { |
| 170 | + let dtype = dl_type(t.dtype())?; |
| 171 | + let mut owner = Box::new(Owner { _data: to_bytes(t)?, _shape: t.shape().iter().map(|&d| d as i64).collect() }); |
| 172 | + let dl_tensor = DLTensor { |
| 173 | + data: owner._data.as_mut_ptr() as *mut c_void, |
| 174 | + device: DLDevice { device_type: DL_CPU, device_id: 0 }, |
| 175 | + ndim: owner._shape.len() as i32, |
| 176 | + dtype, |
| 177 | + shape: owner._shape.as_mut_ptr(), |
| 178 | + strides: std::ptr::null_mut(), |
| 179 | + byte_offset: 0, |
| 180 | + }; |
| 181 | + Ok(Box::into_raw(Box::new(DLManagedTensor { dl_tensor, manager_ctx: Box::into_raw(owner) as *mut c_void, deleter: Some(delete_owned) }))) |
| 182 | +} |
| 183 | + |
| 184 | +/// Imports (copies) a `DLManagedTensor` and calls its deleter, whether or not the import succeeds. |
| 185 | +/// |
| 186 | +/// # Safety |
| 187 | +/// `managed` must be a valid, not yet consumed `DLManagedTensor` whose `data`, `shape` and (if non-null) `strides` describe |
| 188 | +/// readable memory, as the DLPack protocol guarantees for a capsule received from a producer. |
| 189 | +pub unsafe fn from_dlpack(managed: *mut DLManagedTensor) -> Result<Tensor> { |
| 190 | + if managed.is_null() { |
| 191 | + return Err(err("null DLManagedTensor")); |
| 192 | + } |
| 193 | + // SAFETY: validity of the pointer and of what it describes is the caller's contract (see above). |
| 194 | + let result = unsafe { read(&(*managed).dl_tensor) }; |
| 195 | + // SAFETY: the tensor has not been consumed before (caller's contract); the deleter is called exactly once, here. |
| 196 | + unsafe { |
| 197 | + if let Some(d) = (*managed).deleter { |
| 198 | + d(managed); |
| 199 | + } |
| 200 | + } |
| 201 | + result |
| 202 | +} |
| 203 | + |
| 204 | +/// # Safety |
| 205 | +/// `t` must describe readable memory (see [`from_dlpack`]). |
| 206 | +unsafe fn read(t: &DLTensor) -> Result<Tensor> { |
| 207 | + if t.device.device_type != DL_CPU { |
| 208 | + return Err(err(format!("only CPU tensors can be imported (device type {})", t.device.device_type))); |
| 209 | + } |
| 210 | + let dtype = from_dl_type(t.dtype)?; |
| 211 | + let ndim = usize::try_from(t.ndim).map_err(|_| err("negative ndim"))?; |
| 212 | + if ndim > 0 && t.shape.is_null() { |
| 213 | + return Err(err("null shape")); |
| 214 | + } |
| 215 | + // SAFETY: `shape` (and `strides` when non-null) hold `ndim` entries per the DLPack contract. |
| 216 | + let shape: Vec<i64> = if ndim == 0 { Vec::new() } else { unsafe { std::slice::from_raw_parts(t.shape, ndim) }.to_vec() }; |
| 217 | + if shape.iter().any(|&d| d < 0) { |
| 218 | + return Err(err("negative dimension")); |
| 219 | + } |
| 220 | + let dims: Vec<usize> = shape.iter().map(|&d| d as usize).collect(); |
| 221 | + crate::limits::check_elements("dlpack import", &dims)?; |
| 222 | + let count: usize = dims.iter().product(); |
| 223 | + let esize = dtype.size_in_bytes(); |
| 224 | + let strides: Vec<i64> = if t.strides.is_null() { |
| 225 | + let mut s = vec![1i64; ndim]; |
| 226 | + for i in (0..ndim.saturating_sub(1)).rev() { |
| 227 | + s[i] = s[i + 1] * shape[i + 1]; |
| 228 | + } |
| 229 | + s |
| 230 | + } else { |
| 231 | + // SAFETY: as above. |
| 232 | + unsafe { std::slice::from_raw_parts(t.strides, ndim) }.to_vec() |
| 233 | + }; |
| 234 | + if count > 0 && t.data.is_null() { |
| 235 | + return Err(err("null data")); |
| 236 | + } |
| 237 | + let base = (t.data as *const u8).wrapping_add(t.byte_offset as usize); |
| 238 | + let mut bytes = Vec::with_capacity(count * esize); |
| 239 | + let mut idx = vec![0i64; ndim]; |
| 240 | + for _ in 0..count { |
| 241 | + let off: i64 = idx.iter().zip(&strides).map(|(i, s)| i * s).sum(); |
| 242 | + // SAFETY: every index is inside `shape`, so the element lies inside the producer's buffer. |
| 243 | + bytes.extend_from_slice(unsafe { std::slice::from_raw_parts(base.offset(off as isize * esize as isize), esize) }); |
| 244 | + for d in (0..ndim).rev() { |
| 245 | + idx[d] += 1; |
| 246 | + if idx[d] < shape[d] { |
| 247 | + break; |
| 248 | + } |
| 249 | + idx[d] = 0; |
| 250 | + } |
| 251 | + } |
| 252 | + from_bytes(&bytes, dtype, &dims) |
| 253 | +} |
| 254 | + |
| 255 | +#[cfg(test)] |
| 256 | +mod tests { |
| 257 | + use super::*; |
| 258 | + |
| 259 | + #[test] |
| 260 | + fn every_supported_dtype_round_trips_including_views() { |
| 261 | + let base = Tensor::from_slice(&[1.5f32, -2.0, 3.25, 4.0, 5.5, -6.0], &[2, 3]).unwrap(); |
| 262 | + for d in [DType::F32, DType::F64, DType::F16, DType::BF16, DType::I8, DType::I16, DType::I32, DType::I64, DType::U8, DType::U16, DType::U32, DType::U64, DType::Bool] { |
| 263 | + let t = base.abs().unwrap().to_dtype(d).unwrap().transpose(0, 1).unwrap(); // a non-contiguous view |
| 264 | + let p = to_dlpack(&t).unwrap(); |
| 265 | + // SAFETY: `p` was just produced by `to_dlpack` and is consumed once. |
| 266 | + let back = unsafe { from_dlpack(p) }.unwrap(); |
| 267 | + assert_eq!(back.dtype(), d); |
| 268 | + assert_eq!(back.shape(), [3, 2]); |
| 269 | + assert_eq!(back.to_dtype(DType::F64).unwrap().to_vec::<f64>().unwrap(), t.to_dtype(DType::F64).unwrap().to_vec::<f64>().unwrap(), "{d:?}"); |
| 270 | + } |
| 271 | + let big = Tensor::from_slice(&[u64::MAX, (1 << 63) + 7], &[2]).unwrap(); |
| 272 | + // SAFETY: as above. |
| 273 | + let back = unsafe { from_dlpack(to_dlpack(&big).unwrap()) }.unwrap(); |
| 274 | + assert_eq!(back.to_vec::<u64>().unwrap(), vec![u64::MAX, (1 << 63) + 7]); |
| 275 | + assert!(to_dlpack(&base.to_dtype(DType::F8E4M3).unwrap()).is_err()); |
| 276 | + } |
| 277 | + |
| 278 | + static DELETED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); |
| 279 | + unsafe extern "C" fn count_delete(_p: *mut DLManagedTensor) { |
| 280 | + DELETED.fetch_add(1, std::sync::atomic::Ordering::SeqCst); |
| 281 | + } |
| 282 | + |
| 283 | + #[test] |
| 284 | + fn foreign_strided_tensors_are_read_through_strides_and_offset_and_always_deleted() { |
| 285 | + // a producer-owned 3x4 i32 buffer; expose rows reversed, every second column, starting past a 4-byte header |
| 286 | + let mut buf: Vec<i32> = vec![-1]; |
| 287 | + buf.extend(0..12); |
| 288 | + let mut shape = [3i64, 2]; |
| 289 | + let mut strides = [-4i64, 2]; |
| 290 | + let mut m = DLManagedTensor { |
| 291 | + dl_tensor: DLTensor { |
| 292 | + data: buf.as_mut_ptr() as *mut c_void, |
| 293 | + device: DLDevice { device_type: DL_CPU, device_id: 0 }, |
| 294 | + ndim: 2, |
| 295 | + dtype: DLDataType { code: CODE_INT, bits: 32, lanes: 1 }, |
| 296 | + shape: shape.as_mut_ptr(), |
| 297 | + strides: strides.as_mut_ptr(), |
| 298 | + byte_offset: 4 + 8 * 4, // skip the header, start at row 2 |
| 299 | + }, |
| 300 | + manager_ctx: std::ptr::null_mut(), |
| 301 | + deleter: Some(count_delete), |
| 302 | + }; |
| 303 | + // SAFETY: `m` describes `buf`, which outlives the call; the counting deleter frees nothing. |
| 304 | + let t = unsafe { from_dlpack(&mut m) }.unwrap(); |
| 305 | + assert_eq!(t.to_vec::<i32>().unwrap(), vec![8, 10, 4, 6, 0, 2]); |
| 306 | + // an unsupported device is refused, and the deleter still runs |
| 307 | + m.dl_tensor.device.device_type = 2; |
| 308 | + // SAFETY: as above. |
| 309 | + assert!(unsafe { from_dlpack(&mut m) }.is_err()); |
| 310 | + assert_eq!(DELETED.load(std::sync::atomic::Ordering::SeqCst), 2); |
| 311 | + } |
| 312 | +} |
0 commit comments