use alloc::{
boxed::Box,
string::ToString,
vec::Vec,
};
use burn::{
Tensor,
prelude::{
Bool,
Float,
Int,
Shape,
SliceArg,
TensorData,
},
tensor::{
DType,
Device,
Slice,
kind::Basic,
},
};
use crate::{
burner::{
descriptors::{
TensorDesc,
TensorKindDesc,
TensorRankType,
},
module::HasDType,
tensor::dynamic::RankHandler,
},
errors::{
BunsenError,
BunsenResult,
ConstraintError,
Rule,
SlicingError,
},
rust_ext::CloneBox,
zspace::check_slices_bounds,
};
pub fn slice_dyn<const R: usize, K: Basic>(
tensor: Tensor<R, K>,
slices: &[Slice],
) -> Tensor<R, K> {
let mut tensor = tensor;
for (dim, slice) in slices.iter().enumerate() {
tensor = tensor.slice_dim(dim, *slice);
}
tensor
}
pub trait ValuesArg: Sized {
fn into_values(
self,
device: &Device,
) -> BunsenResult<DynTensor>;
}
impl<T: Into<DynTensor>> ValuesArg for T {
fn into_values(
self,
device: &Device,
) -> BunsenResult<DynTensor> {
self.into().to_device(device)
}
}
impl ValuesArg for TensorData {
fn into_values(
self,
device: &Device,
) -> BunsenResult<DynTensor> {
DynTensor::from_data(self, device)
}
}
#[derive(Debug, Clone)]
pub struct DynTensor {
shape: Shape,
dtype: DType,
kind: TensorKindDesc,
device: Device,
tensor: Box<dyn CloneBox>,
}
impl<const R: usize, K> From<Tensor<R, K>> for DynTensor
where
K: 'static + Basic,
{
fn from(val: Tensor<R, K>) -> Self {
DynTensor::new(val)
}
}
impl From<&DynTensor> for TensorDesc {
fn from(val: &DynTensor) -> Self {
TensorDesc::new(val.dtype, val.shape())
}
}
impl From<&DynTensor> for TensorRankType {
fn from(val: &DynTensor) -> Self {
TensorRankType::new(val.dtype, val.shape.rank())
}
}
impl HasDType for DynTensor {
fn dtype(&self) -> DType {
self.dtype
}
}
impl DynTensor {
pub fn new<const R: usize, K>(tensor: Tensor<R, K>) -> Self
where
K: Basic + 'static,
{
Self {
shape: tensor.shape(),
dtype: tensor.dtype(),
kind: tensor.dtype().into(),
device: tensor.device(),
tensor: Box::new(tensor),
}
}
pub fn rank(&self) -> usize {
self.shape.rank()
}
pub fn shape(&self) -> Shape {
self.shape.clone()
}
pub fn num_elements(&self) -> usize {
self.shape.num_elements()
}
pub fn size_estimate(&self) -> usize {
self.dtype.size() * self.num_elements()
}
pub fn dtype(&self) -> DType {
self.dtype
}
pub fn kind(&self) -> TensorKindDesc {
self.kind
}
pub fn device(&self) -> Device {
self.device.clone()
}
pub fn downcast_ref<const R: usize, K>(&self) -> Option<&Tensor<R, K>>
where
K: 'static + Basic,
{
self.tensor.downcast_ref::<Tensor<R, K>>()
}
pub fn downcast_clone<const R: usize, K>(&self) -> Option<Tensor<R, K>>
where
K: 'static + Basic,
{
self.downcast_ref::<R, K>().cloned()
}
pub fn unwrap<const R: usize, K>(self) -> Tensor<R, K>
where
K: 'static + Basic,
{
self.unwrap_clone()
}
pub fn unwrap_clone<const R: usize, K>(&self) -> Tensor<R, K>
where
K: 'static + Basic,
{
self.downcast_clone::<R, K>()
.expect("downcast_clone failed")
}
pub fn slice<S>(
self,
slices: S,
) -> BunsenResult<Self>
where
S: SliceArg,
{
let rank = self.rank();
let slices: Vec<Slice> = slices.into_slices(&self.shape);
check_slices_bounds(&self.shape(), &slices)?;
struct SliceHandler {
this: DynTensor,
slices: Vec<Slice>,
}
impl RankHandler for SliceHandler {
type Output = DynTensor;
fn call<const R: usize>(self) -> BunsenResult<Self::Output> {
Ok(match self.this.kind {
TensorKindDesc::Float => self
.this
.unwrap_clone::<R, Float>()
.slice(&self.slices)
.into(),
TensorKindDesc::Int => self
.this
.unwrap_clone::<R, Int>()
.slice(&self.slices)
.into(),
TensorKindDesc::Bool => self
.this
.unwrap_clone::<R, Bool>()
.slice(&self.slices)
.into(),
})
}
}
SliceHandler { this: self, slices }.dyn_call(rank)
}
pub fn slice_dyn(
self,
slices: &[Slice],
) -> BunsenResult<Self> {
let rank = self.rank();
check_slices_bounds(&self.shape(), slices)?;
struct SliceDynHandler<'a> {
this: DynTensor,
slices: &'a [Slice],
}
impl<'a> RankHandler for SliceDynHandler<'a> {
type Output = DynTensor;
fn call<const R: usize>(self) -> BunsenResult<Self::Output> {
Ok(match self.this.kind {
TensorKindDesc::Float => {
slice_dyn(self.this.unwrap_clone::<R, Float>(), self.slices).into()
}
TensorKindDesc::Int => {
slice_dyn(self.this.unwrap_clone::<R, Int>(), self.slices).into()
}
TensorKindDesc::Bool => {
slice_dyn(self.this.unwrap_clone::<R, Bool>(), self.slices).into()
}
})
}
}
SliceDynHandler { this: self, slices }.dyn_call(rank)
}
pub fn slice_assign<const R2: usize, S, V>(
self,
slices: S,
values: V,
) -> BunsenResult<Self>
where
S: SliceArg,
V: ValuesArg,
{
let rank = self.rank();
let slices: [Slice; R2] =
slices
.into_slices(&self.shape)
.try_into()
.map_err(|slices: Vec<Slice>| SlicingError::InvalidRank {
msg: format!("slice_assign rank ({R2}) does not match tensor rank ({rank})"),
shape: self.shape(),
slices,
})?;
let values: DynTensor = values.into_values(&self.device())?;
check_slices_bounds(&self.shape(), &slices)?;
if rank != values.rank() {
return Err(ConstraintError::new(
"DynTensor::slice_assign",
"values",
Rule::Relation {
lhs: ("values rank".into(), values.rank().to_string()),
op: "==",
rhs: ("tensor rank".into(), rank.to_string()),
},
)
.into());
}
let values = values.cast(self.dtype())?;
struct SliceAssignHandler<const R2: usize> {
this: DynTensor,
slices: [Slice; R2],
values: DynTensor,
}
impl<const R2: usize> RankHandler for SliceAssignHandler<R2> {
type Output = DynTensor;
fn call<const R: usize>(self) -> BunsenResult<Self::Output> {
Ok(match (self.this.kind, self.values.kind) {
(TensorKindDesc::Float, TensorKindDesc::Float) => {
let target = self.this.unwrap_clone::<R, Float>();
let source = self.values.unwrap_clone::<R, Float>();
let source = source.cast(target.dtype());
target.slice_assign(self.slices, source).into()
}
(TensorKindDesc::Int, TensorKindDesc::Int) => {
let target = self.this.unwrap_clone::<R, Int>();
let source = self.values.unwrap_clone::<R, Int>();
let source = source.cast(target.dtype());
target.slice_assign(self.slices, source).into()
}
(TensorKindDesc::Bool, TensorKindDesc::Bool) => {
let target = self.this.unwrap_clone::<R, Bool>();
let source = self.values.unwrap_clone::<R, Bool>();
target.slice_assign(self.slices, source).into()
}
_ => Err(BunsenError::internal(format!(
"target kind ({:?}) != value kind ({:?}) after the cast",
self.this.kind, self.values.kind
)))?,
})
}
}
SliceAssignHandler {
this: self.clone(),
slices,
values,
}
.dyn_call(rank)
}
pub fn slice_assign_dyn<V>(
self,
slices: &[Slice],
values: V,
) -> BunsenResult<Self>
where
V: ValuesArg,
{
struct SliceAssignDynHandler {
this: DynTensor,
slices: Vec<Slice>,
values: DynTensor,
}
impl RankHandler for SliceAssignDynHandler {
type Output = DynTensor;
fn call<const R: usize>(self) -> BunsenResult<Self::Output> {
self.this
.slice_assign::<R, _, _>(self.slices.as_slice(), self.values)
}
}
let rank = self.rank();
check_slices_bounds(&self.shape(), slices)?;
let mut slices = slices.to_vec();
slices.resize(rank, Slice::full());
let values = values.into_values(&self.device())?;
SliceAssignDynHandler {
this: self,
slices,
values,
}
.dyn_call(rank)
}
pub fn flatten(self) -> BunsenResult<Self> {
struct FlattenHandler {
tensor: DynTensor,
}
impl RankHandler for FlattenHandler {
type Output = DynTensor;
fn call<const R: usize>(self) -> BunsenResult<Self::Output> {
Ok(match self.tensor.kind {
TensorKindDesc::Float => self
.tensor
.unwrap_clone::<R, Float>()
.flatten::<1>(0, self.tensor.rank() - 1)
.into(),
TensorKindDesc::Int => self
.tensor
.unwrap_clone::<R, Int>()
.flatten::<1>(0, self.tensor.rank() - 1)
.into(),
TensorKindDesc::Bool => self
.tensor
.unwrap_clone::<R, Bool>()
.flatten::<1>(0, self.tensor.rank() - 1)
.into(),
})
}
}
let rank = self.rank();
FlattenHandler { tensor: self }.dyn_call(rank)
}
pub fn cast(
self,
dtype: DType,
) -> BunsenResult<Self> {
struct CastHandler {
this: DynTensor,
dtype: DType,
}
impl RankHandler for CastHandler {
type Output = DynTensor;
fn call<const R: usize>(self) -> BunsenResult<Self::Output> {
let target_kind: TensorKindDesc = self.dtype.into();
Ok(match self.this.kind {
TensorKindDesc::Float => {
let tensor: Tensor<R, Float> = self.this.unwrap_clone();
match target_kind {
TensorKindDesc::Float => tensor.cast(self.dtype).into(),
TensorKindDesc::Int => tensor.int().cast(self.dtype).into(),
TensorKindDesc::Bool => tensor.bool().into(),
}
}
TensorKindDesc::Int => {
let tensor: Tensor<R, Int> = self.this.unwrap_clone();
match target_kind {
TensorKindDesc::Float => tensor.float().cast(self.dtype).into(),
TensorKindDesc::Int => tensor.cast(self.dtype).into(),
TensorKindDesc::Bool => tensor.bool().into(),
}
}
TensorKindDesc::Bool => {
let tensor: Tensor<R, Bool> = self.this.unwrap_clone();
match target_kind {
TensorKindDesc::Float => tensor.float().cast(self.dtype).into(),
TensorKindDesc::Int => tensor.int().cast(self.dtype).into(),
TensorKindDesc::Bool => self.this,
}
}
})
}
}
let rank = self.rank();
CastHandler { this: self, dtype }.dyn_call(rank)
}
pub fn to_device(
self,
device: &Device,
) -> BunsenResult<Self> {
if &self.device() == device {
return Ok(self);
}
struct ToDeviceHandler<'a> {
this: DynTensor,
device: &'a Device,
}
impl<'a> RankHandler for ToDeviceHandler<'a> {
type Output = DynTensor;
fn call<const R: usize>(self) -> BunsenResult<Self::Output> {
Ok(match self.this.kind {
TensorKindDesc::Float => self
.this
.unwrap_clone::<R, Float>()
.to_device(self.device)
.into(),
TensorKindDesc::Int => self
.this
.unwrap_clone::<R, Int>()
.to_device(self.device)
.into(),
TensorKindDesc::Bool => self
.this
.unwrap_clone::<R, Bool>()
.to_device(self.device)
.into(),
})
}
}
let rank = self.rank();
ToDeviceHandler { this: self, device }.dyn_call(rank)
}
pub fn from_data(
data: TensorData,
device: &Device,
) -> BunsenResult<Self> {
struct FromDataHandler<'a> {
data: TensorData,
device: &'a Device,
}
impl<'a> RankHandler for FromDataHandler<'a> {
type Output = DynTensor;
fn call<const R: usize>(self) -> BunsenResult<Self::Output> {
let kind: TensorKindDesc = self.data.dtype().into();
Ok(match kind {
TensorKindDesc::Float => {
Tensor::<R, Float>::from_data(self.data, self.device).into()
}
TensorKindDesc::Int => {
Tensor::<R, Int>::from_data(self.data, self.device).into()
}
TensorKindDesc::Bool => {
Tensor::<R, Bool>::from_data(self.data, self.device).into()
}
})
}
}
let rank = data.rank();
FromDataHandler { data, device }.dyn_call(rank)
}
pub fn into_data(self) -> BunsenResult<TensorData> {
struct ToDataHandler {
this: DynTensor,
}
impl RankHandler for ToDataHandler {
type Output = TensorData;
fn call<const R: usize>(self) -> BunsenResult<Self::Output> {
Ok(match self.this.kind {
TensorKindDesc::Float => self.this.unwrap_clone::<R, Float>().into_data(),
TensorKindDesc::Int => self.this.unwrap_clone::<R, Int>().into_data(),
TensorKindDesc::Bool => self.this.unwrap_clone::<R, Bool>().into_data(),
})
}
}
let rank = self.rank();
ToDataHandler { this: self }.dyn_call(rank)
}
pub fn to_data(&self) -> BunsenResult<TensorData> {
self.clone().into_data()
}
}
#[cfg(test)]
mod tests {
use burn::{
prelude::{
Shape,
s,
},
tensor::{
Bool,
Device,
Distribution,
Float,
Int,
Slice,
Tensor,
TensorData,
},
};
use crate::{
burner::{
descriptors::{
TensorKindDesc,
TensorRankType,
},
tensor::dynamic::*,
},
errors::{
BunsenErrorKind,
ConstraintError,
SlicingError,
testing::{
ErrorMatcher,
predicate,
},
},
support::testing::{
DeviceMemoryGuard,
performance_device,
},
};
#[test]
fn test_is_send() {
fn assert_send<T: Send>() {}
assert_send::<DynTensor>();
}
#[test]
#[serial_test::serial]
fn test_stub_float() {
let device = performance_device();
let _memory = DeviceMemoryGuard::new(&device);
let source: Tensor<2> = Tensor::random([2, 3], Distribution::Default, &device);
let stub = DynTensor::new(source.clone());
assert_eq!(stub.rank(), 2);
assert_eq!(stub.shape(), source.shape());
assert_eq!(stub.num_elements(), 6);
assert_eq!(stub.dtype(), source.dtype());
assert_eq!(
stub.size_estimate(),
stub.num_elements() * source.dtype().size()
);
assert_eq!(stub.kind(), TensorKindDesc::Float);
assert_eq!(stub.device(), device);
assert!(stub.downcast_clone::<2, Int>().is_none());
assert!(stub.downcast_clone::<2, Bool>().is_none());
assert!(stub.downcast_clone::<3, Float>().is_none());
let clone = stub.downcast_clone::<2, Float>().unwrap();
clone.to_data().assert_eq(&source.clone().to_data(), true);
stub.clone()
.into_data()
.unwrap()
.assert_eq(&source.clone().to_data(), true);
let flatten = stub.clone().flatten().unwrap();
assert_eq!(flatten.shape(), [6].into());
flatten
.into_data()
.unwrap()
.assert_eq(&source.clone().flatten::<1>(0, 1).to_data(), true);
}
#[test]
#[serial_test::serial]
fn test_stub_int() {
let device = performance_device();
let _memory = DeviceMemoryGuard::new(&device);
let source: Tensor<2> = Tensor::random([2, 3], Distribution::Default, &device);
let source = source.int();
let stub = DynTensor::new(source.clone());
assert_eq!(stub.rank(), 2);
assert_eq!(stub.shape(), source.shape());
assert_eq!(stub.num_elements(), 6);
assert_eq!(stub.dtype(), source.dtype());
assert_eq!(
stub.size_estimate(),
stub.num_elements() * source.dtype().size()
);
assert_eq!(stub.kind(), TensorKindDesc::Int);
assert_eq!(stub.device(), device);
assert!(stub.downcast_clone::<2, Float>().is_none());
assert!(stub.downcast_clone::<2, Bool>().is_none());
assert!(stub.downcast_clone::<3, Int>().is_none());
let clone = stub.downcast_clone::<2, Int>().unwrap();
clone.to_data().assert_eq(&source.clone().to_data(), true);
stub.clone()
.into_data()
.unwrap()
.assert_eq(&source.clone().to_data(), true);
let flatten = stub.clone().flatten().unwrap();
assert_eq!(flatten.shape(), [6].into());
flatten
.into_data()
.unwrap()
.assert_eq(&source.clone().flatten::<1>(0, 1).to_data(), true);
}
#[test]
#[serial_test::serial]
fn test_stub_bool() {
let device = performance_device();
let _memory = DeviceMemoryGuard::new(&device);
let source: Tensor<2> = Tensor::random([2, 3], Distribution::Bernoulli(0.5), &device);
let source = source.bool();
let stub = DynTensor::new(source.clone());
assert_eq!(stub.rank(), 2);
assert_eq!(stub.shape(), source.shape());
assert_eq!(stub.num_elements(), 6);
assert_eq!(stub.dtype(), source.dtype());
assert_eq!(
stub.size_estimate(),
stub.num_elements() * source.dtype().size()
);
assert_eq!(stub.kind(), TensorKindDesc::Bool);
assert_eq!(stub.device(), device);
assert!(stub.downcast_clone::<2, Int>().is_none());
assert!(stub.downcast_clone::<2, Float>().is_none());
assert!(stub.downcast_clone::<3, Bool>().is_none());
let clone = stub.downcast_clone::<2, Bool>().unwrap();
clone.to_data().assert_eq(&source.clone().to_data(), true);
stub.clone()
.into_data()
.unwrap()
.assert_eq(&source.clone().to_data(), true);
let flatten = stub.clone().flatten().unwrap();
assert_eq!(flatten.shape(), [6].into());
flatten
.into_data()
.unwrap()
.assert_eq(&source.clone().flatten::<1>(0, 1).to_data(), true);
}
#[test]
#[serial_test::serial]
fn test_clone() {
let device = performance_device();
let _memory = DeviceMemoryGuard::new(&device);
let source: Tensor<2> = Tensor::random([2, 3], Distribution::Default, &device);
let stub = DynTensor::new(source.clone());
let stub_clone = stub.clone();
assert!(stub_clone.downcast_clone::<3, Float>().is_none());
assert!(stub_clone.downcast_clone::<2, Int>().is_none());
let clone = stub_clone.downcast_clone::<2, Float>().unwrap();
clone.to_data().assert_eq(&source.clone().to_data(), true);
}
#[test]
#[serial_test::serial]
fn test_slice() {
let device = performance_device();
let _memory = DeviceMemoryGuard::new(&device);
let source: Tensor<2> = Tensor::random([2, 3], Distribution::Default, &device);
let stub = DynTensor::new(source.clone());
let slice = stub.slice(s![.., 1..]).unwrap();
assert_eq!(slice.shape(), [2, 2].into());
slice
.downcast_clone::<2, Float>()
.unwrap()
.to_data()
.assert_eq(&source.clone().slice(s![.., 1..]).to_data(), true);
}
#[test]
#[serial_test::serial]
fn test_slice_dyn() {
let device = performance_device();
let _memory = DeviceMemoryGuard::new(&device);
let source: Tensor<2> = Tensor::random([2, 3], Distribution::Default, &device);
let stub = DynTensor::new(source.clone());
let slice = stub
.slice_dyn(&vec![Slice::new(0, None, 1), Slice::new(1, None, 1)])
.unwrap();
assert_eq!(slice.shape(), [2, 2].into());
slice
.downcast_clone::<2, Float>()
.unwrap()
.to_data()
.assert_eq(&source.clone().slice(s![.., 1..]).to_data(), true);
}
fn arange_2x3(device: &Device) -> DynTensor {
Tensor::arange(0..6, device).reshape([2, 3]).float().into()
}
#[test]
#[serial_test::serial]
fn test_slice_assign() {
let device = performance_device();
let _memory = DeviceMemoryGuard::new(&device);
let values: Tensor<2> = Tensor::zeros([2, 1], &device);
let result = arange_2x3(&device)
.slice_assign::<2, _, _>(s![.., 1..2], values)
.unwrap();
assert_eq!(result.shape(), [2, 3].into());
result.into_data().unwrap().assert_eq(
&TensorData::from([[0.0f32, 0.0, 2.0], [3.0, 0.0, 5.0]]),
true,
);
}
#[test]
#[serial_test::serial]
fn test_slice_assign_casts_values() {
let device = performance_device();
let _memory = DeviceMemoryGuard::new(&device);
let values: Tensor<2, Int> = Tensor::from_data([[9], [9]], &device);
let result = arange_2x3(&device)
.slice_assign::<2, _, _>(s![.., 0..1], values)
.unwrap();
assert_eq!(result.kind(), TensorKindDesc::Float);
result.into_data().unwrap().assert_eq(
&TensorData::from([[9.0f32, 1.0, 2.0], [9.0, 4.0, 5.0]]),
true,
);
}
#[test]
#[serial_test::serial]
fn test_slice_assign_tensor_data() {
let device = performance_device();
let _memory = DeviceMemoryGuard::new(&device);
let result: DynTensor = arange_2x3(&device)
.slice_assign::<2, _, _>(s![0..1, ..], TensorData::from([[7.0f32, 7.0, 7.0]]))
.unwrap();
result.into_data().unwrap().assert_eq(
&TensorData::from([[7.0f32, 7.0, 7.0], [3.0, 4.0, 5.0]]),
true,
);
}
#[test]
#[serial_test::serial]
fn test_slice_assign_int_and_bool() {
let device = performance_device();
let _memory = DeviceMemoryGuard::new(&device);
let source: Tensor<1, Int> = Tensor::arange(0..4, &device);
let values: Tensor<1, Int> = Tensor::from_data([8, 9], &device);
DynTensor::new(source)
.slice_assign::<1, _, _>(s![1..3], values)
.unwrap()
.into_data()
.unwrap()
.convert::<i64>()
.assert_eq(&TensorData::from([0i64, 8, 9, 3]), false);
let source: Tensor<1, Bool> = Tensor::from_data([false, false, false], &device);
let values: Tensor<1, Bool> = Tensor::from_data([true], &device);
DynTensor::new(source)
.slice_assign::<1, _, _>(s![2..3], values)
.unwrap()
.into_data()
.unwrap()
.assert_eq(&TensorData::from([false, false, true]), false);
}
#[test]
#[serial_test::serial]
fn test_slice_assign_rank_errors() {
let device = performance_device();
let _memory = DeviceMemoryGuard::new(&device);
let values: Tensor<1> = Tensor::zeros([3], &device);
ErrorMatcher::kind(BunsenErrorKind::Illegal)
.message_contains("values rank (1) must be == tensor rank (2)")
.has_cause::<ConstraintError>()
.assert_err(&arange_2x3(&device).slice_assign::<2, _, _>(s![0..1, ..], values));
let values: Tensor<2> = Tensor::zeros([1, 3], &device);
ErrorMatcher::kind(BunsenErrorKind::Illegal)
.cause(predicate("InvalidRank", |e: &SlicingError| {
matches!(e, SlicingError::InvalidRank { .. })
}))
.assert_err(&arange_2x3(&device).slice_assign::<1, _, _>(s![0..1], values));
}
#[test]
#[serial_test::serial]
fn test_slice_assign_out_of_bounds() {
let device = performance_device();
let _memory = DeviceMemoryGuard::new(&device);
let values: Tensor<2> = Tensor::zeros([1, 3], &device);
ErrorMatcher::kind(BunsenErrorKind::Illegal)
.cause(predicate("OutOfBounds", |e: &SlicingError| {
matches!(e, SlicingError::OutOfBounds { .. })
}))
.assert_err(&arange_2x3(&device).slice_assign::<2, _, _>(s![5..6, ..], values));
}
#[test]
#[serial_test::serial]
fn test_slice_assign_dyn() {
let device = performance_device();
let _memory = DeviceMemoryGuard::new(&device);
let values: Tensor<2> = Tensor::ones([1, 3], &device);
arange_2x3(&device)
.slice_assign_dyn(&[Slice::new(1, None, 1), Slice::full()], values)
.unwrap()
.into_data()
.unwrap()
.assert_eq(
&TensorData::from([[0.0f32, 1.0, 2.0], [1.0, 1.0, 1.0]]),
true,
);
}
#[test]
#[serial_test::serial]
fn test_slice_assign_dyn_partial_slices() {
let device = performance_device();
let _memory = DeviceMemoryGuard::new(&device);
let values: Tensor<2> = Tensor::ones([1, 3], &device);
arange_2x3(&device)
.slice_assign_dyn(&[Slice::new(0, Some(1), 1)], values)
.unwrap()
.into_data()
.unwrap()
.assert_eq(
&TensorData::from([[1.0f32, 1.0, 1.0], [3.0, 4.0, 5.0]]),
true,
);
}
#[test]
#[serial_test::serial]
fn test_slice_assign_dyn_too_many_slices() {
let device = performance_device();
let _memory = DeviceMemoryGuard::new(&device);
let values: Tensor<2> = Tensor::ones([2, 3], &device);
ErrorMatcher::kind(BunsenErrorKind::Illegal)
.cause(predicate("InvalidRank", |e: &SlicingError| {
matches!(e, SlicingError::InvalidRank { .. })
}))
.assert_err(
&arange_2x3(&device)
.slice_assign_dyn(&[Slice::full(), Slice::full(), Slice::full()], values),
);
}
#[test]
fn test_tensor_rank_desc() {
let device = performance_device();
let _memory = DeviceMemoryGuard::new(&device);
{
let tensor: Tensor<2> = Tensor::ones([2, 3], &device);
let dtensor = DynTensor::new(tensor);
let dtype = dtensor.dtype();
let rank_desc: TensorRankType = TensorRankType::from(&dtensor);
assert_eq!(rank_desc.kind(), TensorKindDesc::Float);
assert_eq!(rank_desc.dtype(), dtype);
assert_eq!(rank_desc.rank(), 2);
assert_eq!(rank_desc.size_estimate(6), dtype.size() * 2 * 3);
let desc = rank_desc.to_desc(Shape::new([2, 3]));
assert_eq!(desc.to_rank_type(), rank_desc);
assert_eq!(desc.kind(), TensorKindDesc::Float);
assert_eq!(desc.dtype(), dtype);
assert_eq!(desc.shape(), &Shape::new([2, 3]));
assert_eq!(desc.rank(), 2);
assert_eq!(desc.size_estimate(), dtype.size() * 2 * 3);
}
{
let tensor: Tensor<2, Int> = Tensor::ones([2, 3], &device);
let dtensor = DynTensor::new(tensor);
let dtype = dtensor.dtype();
let rank_desc: TensorRankType = TensorRankType::from(&dtensor);
assert_eq!(rank_desc.kind(), TensorKindDesc::Int);
assert_eq!(rank_desc.dtype(), dtype);
assert_eq!(rank_desc.rank(), 2);
assert_eq!(rank_desc.size_estimate(6), dtype.size() * 2 * 3);
let desc = rank_desc.to_desc(Shape::new([2, 3]));
assert_eq!(desc.to_rank_type(), rank_desc);
assert_eq!(desc.kind(), TensorKindDesc::Int);
assert_eq!(desc.dtype(), dtype);
assert_eq!(desc.shape(), &Shape::new([2, 3]));
assert_eq!(desc.rank(), 2);
assert_eq!(desc.size_estimate(), dtype.size() * 2 * 3);
}
{
let tensor: Tensor<2, Bool> = Tensor::zeros([2, 3], &device);
let dtensor = DynTensor::new(tensor);
let dtype = dtensor.dtype();
let rank_desc: TensorRankType = TensorRankType::from(&dtensor);
assert_eq!(rank_desc.kind(), TensorKindDesc::Bool);
assert_eq!(rank_desc.dtype(), dtype);
assert_eq!(rank_desc.rank(), 2);
assert_eq!(rank_desc.size_estimate(6), dtype.size() * 2 * 3);
let desc = rank_desc.to_desc(Shape::new([2, 3]));
assert_eq!(desc.to_rank_type(), rank_desc);
assert_eq!(desc.kind(), TensorKindDesc::Bool);
assert_eq!(desc.dtype(), dtype);
assert_eq!(desc.shape(), &Shape::new([2, 3]));
assert_eq!(desc.rank(), 2);
assert_eq!(desc.size_estimate(), dtype.size() * 2 * 3);
}
}
}