Skip to main content

PyTensor

Struct PyTensor 

Source
pub struct PyTensor { /* private fields */ }
Expand description

A tensor imported from Python via the DLPack protocol.

This type wraps a DLManagedTensor received from a Python object (typically a PyTorch, JAX, or NumPy tensor) and provides safe access to the tensor’s metadata and data pointer.

§Lifetime

The tensor data is valid as long as this PyTensor is alive. When dropped, the tensor’s deleter is called to notify the producer.

§Example

use pyo3::prelude::*;
use pyo3_dlpack::PyTensor;

#[pyfunction]
fn process(py: Python<'_>, obj: &Bound<'_, PyAny>) -> PyResult<()> {
    let tensor = PyTensor::from_pyany(py, obj)?;

    println!("Shape: {:?}", tensor.shape());
    println!("Device: {:?}", tensor.device());
    println!("Dtype: {:?}", tensor.dtype());

    if tensor.device().is_cpu() {
        // Safe to access data on CPU
        let ptr = tensor.data_ptr() as *const f32;
        // ...
    }

    Ok(())
}

Implementations§

Source§

impl PyTensor

Source

pub fn from_pyany(_py: Python<'_>, obj: &Bound<'_, PyAny>) -> PyResult<Self>

Create a PyTensor from a Python object that supports the DLPack protocol.

This calls __dlpack__() on the object to get a DLPack capsule, then extracts the tensor information.

§Arguments
  • py - Python GIL token
  • obj - A Python object that implements __dlpack__() (e.g., PyTorch tensor)
§Errors

Returns an error if:

  • The object doesn’t have a __dlpack__ method
  • The returned capsule is invalid
  • The capsule doesn’t contain a valid DLManagedTensor
Source

pub fn from_capsule(capsule: &Bound<'_, PyCapsule>) -> PyResult<Self>

Create a PyTensor directly from a DLPack PyCapsule.

§Arguments
  • capsule - A PyCapsule containing a DLManagedTensor
§Errors

Returns an error if the capsule is invalid or has the wrong name.

Source

pub fn device(&self) -> DLDevice

Get the device where the tensor data resides.

Source

pub fn dtype(&self) -> DLDataType

Get the data type of the tensor elements.

Source

pub fn ndim(&self) -> usize

Get the number of dimensions.

Source

pub fn shape(&self) -> &[i64]

Get the shape as a slice.

The length of the slice equals ndim().

Source

pub fn strides(&self) -> Option<&[i64]>

Get the strides as a slice, or None for contiguous tensors.

Strides are in number of elements (not bytes). If None, the tensor is assumed to be in compact row-major order.

Source

pub fn is_contiguous(&self) -> bool

Check if the tensor is contiguous in row-major (C) order.

Source

pub fn data_ptr(&self) -> *mut c_void

Get the raw data pointer.

For GPU tensors, this is a device pointer that cannot be directly dereferenced on the CPU.

The pointer is adjusted by byte_offset().

Source

pub fn data_ptr_raw(&self) -> *mut c_void

Get the raw data pointer without byte offset adjustment.

Source

pub fn byte_offset(&self) -> u64

Get the byte offset from the raw data pointer.

Source

pub fn numel(&self) -> usize

Get the total number of elements in the tensor.

Source

pub fn itemsize(&self) -> usize

Get the size of one element in bytes.

Source

pub fn nbytes(&self) -> usize

Get the total size of the tensor data in bytes.

Trait Implementations§

Source§

impl Debug for PyTensor

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Drop for PyTensor

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl Send for PyTensor

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> Ungil for T
where T: Send,