Skip to content
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 cumulative sum tensor operation #1722

Closed
wants to merge 11 commits into from
13 changes: 12 additions & 1 deletion crates/burn-ndarray/src/ops/int_tensor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use burn_tensor::{Distribution, Reader};

use burn_tensor::ElementConversion;
use core::ops::Range;
use ndarray::IntoDimension;
use ndarray::{Axis, IntoDimension};

// Current crate
use crate::element::ExpElement;
Expand Down Expand Up @@ -286,6 +286,17 @@ impl<E: FloatNdArrayElement> IntTensorOps<Self> for NdArray<E> {
NdArrayMathOps::sum_dim(tensor, dim)
}

fn int_cumsum_dim<const D: usize>(
tensor: NdArrayTensor<i64, D>,
dim: usize,
) -> NdArrayTensor<i64, D> {
let mut array = tensor.array.clone().into_owned();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See comment for float_cumsum


array.accumulate_axis_inplace(Axis(dim), |&prev, curr| *curr += prev);

NdArrayTensor::new(array.to_shared())
}

fn int_prod<const D: usize>(tensor: NdArrayTensor<i64, D>) -> NdArrayTensor<i64, 1> {
NdArrayMathOps::prod(tensor)
}
Expand Down
13 changes: 12 additions & 1 deletion crates/burn-ndarray/src/ops/tensor.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Language
use alloc::vec::Vec;
use core::ops::Range;
use ndarray::IntoDimension;
use ndarray::{Axis, IntoDimension};

// Current crate
use super::{matmul::matmul, NdArrayMathOps, NdArrayOps};
Expand Down Expand Up @@ -338,6 +338,17 @@ impl<E: FloatNdArrayElement> FloatTensorOps<Self> for NdArray<E> {
NdArrayMathOps::sum_dim(tensor, dim)
}

fn float_cumsum_dim<const D: usize>(
tensor: NdArrayTensor<E, D>,
dim: usize,
) -> NdArrayTensor<E, D> {
let mut array = tensor.array.clone().into_owned();
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe the underlying array struct of tensor needs to be cloned, since NdArray's method for accumulating elements along an axis modifies an array's data inplace. Referring to this method

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well float_cumsum takes ownership of the tensor, so I don't think the clone is required here.


array.accumulate_axis_inplace(Axis(dim), |&prev, curr| *curr += prev);

NdArrayTensor::new(array.to_shared())
}

fn float_argmax<const D: usize>(
tensor: NdArrayTensor<E, D>,
dim: usize,
Expand Down