-
Notifications
You must be signed in to change notification settings - Fork 311
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add dlpack support #1306
Draft
SunDoge
wants to merge
3
commits into
rust-ndarray:master
Choose a base branch
from
SunDoge:feat-dlpack
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Add dlpack support #1306
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,94 @@ | ||
use core::ptr::NonNull; | ||
use std::marker::PhantomData; | ||
|
||
use dlpark::prelude::*; | ||
|
||
use crate::{ArrayBase, Dimension, IntoDimension, IxDyn, ManagedArray, RawData}; | ||
|
||
impl<A, S, D> ToTensor for ArrayBase<S, D> | ||
where | ||
A: InferDtype, | ||
S: RawData<Elem = A>, | ||
D: Dimension, | ||
{ | ||
fn data_ptr(&self) -> *mut std::ffi::c_void { | ||
self.as_ptr() as *mut std::ffi::c_void | ||
} | ||
|
||
fn byte_offset(&self) -> u64 { | ||
0 | ||
} | ||
|
||
fn device(&self) -> Device { | ||
Device::CPU | ||
} | ||
|
||
fn dtype(&self) -> DataType { | ||
A::infer_dtype() | ||
} | ||
|
||
fn shape(&self) -> CowIntArray { | ||
dlpark::prelude::CowIntArray::from_owned( | ||
self.shape().into_iter().map(|&x| x as i64).collect(), | ||
) | ||
} | ||
|
||
fn strides(&self) -> Option<CowIntArray> { | ||
Some(dlpark::prelude::CowIntArray::from_owned( | ||
self.strides().into_iter().map(|&x| x as i64).collect(), | ||
)) | ||
} | ||
} | ||
|
||
pub struct ManagedRepr<A> { | ||
managed_tensor: ManagedTensor, | ||
_ty: PhantomData<A>, | ||
} | ||
|
||
impl<A> ManagedRepr<A> { | ||
pub fn new(managed_tensor: ManagedTensor) -> Self { | ||
Self { | ||
managed_tensor, | ||
_ty: PhantomData, | ||
} | ||
} | ||
|
||
pub fn as_slice(&self) -> &[A] { | ||
self.managed_tensor.as_slice() | ||
} | ||
|
||
pub fn as_ptr(&self) -> *const A { | ||
self.managed_tensor.data_ptr() as *const A | ||
} | ||
} | ||
|
||
unsafe impl<A> Sync for ManagedRepr<A> where A: Sync {} | ||
unsafe impl<A> Send for ManagedRepr<A> where A: Send {} | ||
|
||
impl<A> FromDLPack for ManagedArray<A, IxDyn> { | ||
fn from_dlpack(dlpack: NonNull<dlpark::ffi::DLManagedTensor>) -> Self { | ||
let managed_tensor = ManagedTensor::new(dlpack); | ||
let shape: Vec<usize> = managed_tensor | ||
.shape() | ||
.into_iter() | ||
.map(|x| *x as _) | ||
.collect(); | ||
|
||
let strides: Vec<usize> = match (managed_tensor.strides(), managed_tensor.is_contiguous()) { | ||
(Some(s), _) => s.into_iter().map(|&x| x as _).collect(), | ||
(None, true) => managed_tensor | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Later work, check compatibility of dlpack and ndarray strides, how they work, their domains etc. |
||
.calculate_contiguous_strides() | ||
.into_iter() | ||
.map(|x| x as _) | ||
.collect(), | ||
(None, false) => panic!("dlpack: invalid strides"), | ||
}; | ||
let ptr = managed_tensor.data_ptr() as *mut A; | ||
|
||
let managed_repr = ManagedRepr::<A>::new(managed_tensor); | ||
unsafe { | ||
ArrayBase::from_data_ptr(managed_repr, NonNull::new_unchecked(ptr)) | ||
.with_strides_dim(strides.into_dimension(), shape.into_dimension()) | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
#![cfg(feature = "dlpack")] | ||
|
||
use dlpark::prelude::*; | ||
use ndarray::ManagedArray; | ||
|
||
#[test] | ||
fn test_dlpack() { | ||
let arr = ndarray::arr1(&[1i32, 2, 3]); | ||
let ptr = arr.as_ptr(); | ||
let dlpack = arr.into_dlpack(); | ||
let arr2 = ManagedArray::<i32, _>::from_dlpack(dlpack); | ||
let ptr2 = arr2.as_ptr(); | ||
assert_eq!(ptr, ptr2); | ||
let arr3 = arr2.to_owned(); | ||
let ptr3 = arr3.as_ptr(); | ||
assert_ne!(ptr2, ptr3); | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this function takes a raw pointer (wrapped in NonNull) and it must be an unsafe function, otherwise we can trivially violate memory safety unfortunately.
The only way to remove this requirement - the requirement of using
unsafe
- would be if you have a "magical" function that can take an arbitrary pointer and say whether it's a valid, live, non-mutably aliased pointer to a tensor.Here's how to create a dangling bad pointer:
NonNull::new(1 as *mut u8 as *mut dlpark::ffi::DLManagedTensor)
does this code crash if we run with this pointer? I think it would..There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I agree with you.
from_dlpack
should be unsafe, and users should use it at their own risk.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I would say, we normally don't commit to public dependencies that are not stable (yes, not a very fair policy since ndarray itself is not so stable.), and dlpark is a public dependency here because it becomes part of our API. It could mean it takes a long time between version bumps.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Maybe we don't need to include
dlpark
as a dependency. We can create anArrayView
usingArrayView::from_shape_ptr
andManagedTensor
. I can implementToTensor
forArrayD
indlpark
with a new featurendarray
. I'll do some quick experiments.