-
Notifications
You must be signed in to change notification settings - Fork 482
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
Closed
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
b7188aa
Begin draft of cumulative sum: interfaces
allenqm c51d7be
format
allenqm 729778e
add torch implementation
allenqm ed7681e
add candle implementation
allenqm 9175f92
add ndarray implementation
allenqm 3a477a2
add autodiff implementation
allenqm 46cc2c8
add tensor tests
allenqm 91c27b4
remove int overflow test
allenqm fdc5c95
add cumsum source to burn-import. tests/ in subsequent commits.
allenqm 8b9b39e
add burn import tests
allenqm dab2905
rename cumsum_dim to cumsum
allenqm 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,25 @@ | ||
#[burn_tensor_testgen::testgen(ad_cumsum)] | ||
mod tests { | ||
use super::*; | ||
use burn_tensor::Data; | ||
|
||
#[test] | ||
fn should_diff_cumsum() { | ||
let device = Default::default(); | ||
let data = Data::from([[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]); | ||
// Original Tensor | ||
let tensor_0 = TestAutodiffTensor::from_data(data, &device).require_grad(); | ||
// Cumsum Tensor | ||
let dim = 1; | ||
let tensor_1 = tensor_0.clone().cumsum(dim); | ||
// Fake loss | ||
let loss = tensor_1.clone().sum(); | ||
// Gradients with respect to the original tensor | ||
let grads = loss.backward(); | ||
// let grads = tensor_1.backward(); | ||
let grad_0 = tensor_0.grad(&grads).unwrap(); | ||
// Gradient is correct | ||
let grad_0_expected = Data::from([[3., 2., 1.], [3., 2., 1.], [3., 2., 1.]]); | ||
grad_0.into_data().assert_approx_eq(&grad_0_expected, 2); | ||
} | ||
} |
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
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,47 @@ | ||
#!/usr/bin/env python3 | ||
|
||
# used to generate model: onnx-tests/tests/cumsum/cumsum.onnx | ||
|
||
import torch | ||
import torch.nn as nn | ||
|
||
|
||
class Model(nn.Module): | ||
def __init__(self): | ||
super(Model, self).__init__() | ||
# self.b = 5.0 | ||
|
||
def forward(self, x, d): | ||
# cumulative sum of a tensor along dimension d | ||
x = x.cumsum(d) | ||
|
||
return x | ||
|
||
|
||
def main(): | ||
# Export to onnx | ||
model = Model() | ||
model.eval() | ||
device = torch.device("cpu") | ||
onnx_name = "cumsum.onnx" | ||
dummy_input = torch.tensor([[0,1,2], [3,4,5], [6, 7, 8]], dtype=torch.float32, device=device) | ||
|
||
dim= 1 | ||
|
||
torch.onnx.export( | ||
model, (dummy_input, dim), onnx_name, verbose=False, opset_version=16 | ||
) | ||
|
||
print(f"Finished exporting model to {onnx_name}") | ||
|
||
# Output some test data for use in the test | ||
test_input = torch.tensor([[0,1,2], [3,4,5], [6, 7, 8]], dtype=torch.float32, device=device) | ||
|
||
print(f"Test input data: {test_input}, {dim}") | ||
output = model.forward(test_input, dim) | ||
print(f"Test output data: {output}") | ||
|
||
|
||
|
||
if __name__ == "__main__": | ||
main() |
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,45 @@ | ||
#!/usr/bin/env python3 | ||
|
||
# used to generate model: onnx-tests/tests/cumsum/cumsum.onnx | ||
|
||
import torch | ||
import torch.nn as nn | ||
|
||
|
||
class Model(nn.Module): | ||
def __init__(self): | ||
super(Model, self).__init__() | ||
# self.b = 5.0 | ||
|
||
def forward(self, x, d): | ||
# cumulative sum of a tensor along dimension d | ||
x = x.cumsum(d) | ||
|
||
return x | ||
|
||
|
||
def main(): | ||
# Export to onnx | ||
model = Model() | ||
model.eval() | ||
device = torch.device("cpu") | ||
onnx_name = "cumsum.onnx" | ||
test_input = torch.tensor([[0,1,2], [3,4,5], [6, 7, 8]], dtype=torch.int32, device=device) | ||
|
||
dim= 1 | ||
|
||
torch.onnx.export( | ||
model, (test_input, dim), onnx_name, verbose=False, opset_version=16 | ||
) | ||
|
||
print(f"Finished exporting model to {onnx_name}") | ||
|
||
|
||
print(f"Test input data: {test_input}, {dim}") | ||
output = model.forward(test_input, dim) | ||
print(f"Test output data: {output}") | ||
|
||
|
||
|
||
if __name__ == "__main__": | ||
main() |
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
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 |
---|---|---|
|
@@ -278,6 +278,7 @@ impl OnnxGraph { | |
graph.register(Self::conv_transpose2d_conversion(node)) | ||
} | ||
NodeType::Pow => graph.register(Self::pow_conversion(node)), | ||
NodeType::CumSum => graph.register(Self::cumsum_conversion(node)), | ||
NodeType::Unsqueeze => graph.register(Self::unsqueeze_conversion(node)), | ||
NodeType::Where => graph.register(Self::where_conversion(node)), | ||
NodeType::Sign => graph.register(Self::sign_conversion(node)), | ||
|
@@ -779,6 +780,19 @@ impl OnnxGraph { | |
_ => panic!("pow function only supports RHS scalar or tensor types"), | ||
} | ||
} | ||
fn cumsum_conversion(node: Node) -> BinaryNode { | ||
let lhs = node.inputs.first().unwrap().to_type(); | ||
let rhs = node.inputs.get(1).unwrap().to_type(); | ||
let output = node.outputs.first().unwrap().to_type(); | ||
match &lhs { | ||
Type::Tensor(x) => match x.kind { | ||
TensorKind::Int => BinaryNode::int_cumsum(lhs, rhs, output), | ||
TensorKind::Float => BinaryNode::float_cumsum(lhs, rhs, output), | ||
_ => panic!("cumsum function requires LHS to be int or float type"), | ||
}, | ||
_ => panic!("cumsum function only supports LHS tensor type"), | ||
} | ||
} | ||
Comment on lines
+787
to
+795
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. By making cumsum a single node it should simplify this block |
||
|
||
fn sign_conversion(node: Node) -> UnaryNode { | ||
let input = node.inputs.first().unwrap().to_type(); | ||
|
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 |
---|---|---|
|
@@ -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; | ||
|
@@ -286,6 +286,17 @@ impl<E: FloatNdArrayElement> IntTensorOps<Self> for NdArray<E> { | |
NdArrayMathOps::sum_dim(tensor, dim) | ||
} | ||
|
||
fn int_cumsum<const D: usize>( | ||
tensor: NdArrayTensor<i64, D>, | ||
dim: usize, | ||
) -> NdArrayTensor<i64, D> { | ||
let mut array = tensor.array.clone().into_owned(); | ||
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. See comment for |
||
|
||
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) | ||
} | ||
|
Oops, something went wrong.
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.
CumSum
is a single operator, the same for int and float.So we should also only have one node type,
BinaryType::Cumsum
. See for exampleBinaryType::Sub
, which does split the int and float tests for the generated onnx files but it's still a single operation/node.