-
Notifications
You must be signed in to change notification settings - Fork 435
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add ONNX op Random Normal Like (#2441)
* add random normal like python code to generate onnx model * add random normal like node * modify onnx burn to add new op * add test on test onnx * revert commentouts * fix review points to respond to dynamically shape
- Loading branch information
Showing
10 changed files
with
243 additions
and
6 deletions.
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
15 changes: 15 additions & 0 deletions
15
crates/burn-import/onnx-tests/tests/random_normal_like/random_normal_like.onnx
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,15 @@ | ||
pytorch2.2.0:� | ||
P | ||
onnx::RandomNormalLike_01/RandomNormalLike"RandomNormalLike* | ||
dtype� | ||
main_graphZ. | ||
onnx::RandomNormalLike_0 | ||
b | ||
1 | ||
B |
49 changes: 49 additions & 0 deletions
49
crates/burn-import/onnx-tests/tests/random_normal_like/random_normal_like.py
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,49 @@ | ||
#!/usr/bin/env python3 | ||
|
||
# used to generate model: random_normal_like.onnx | ||
|
||
import torch | ||
import torch.nn as nn | ||
|
||
|
||
class RandomNormalLikeModel(nn.Module): | ||
def __init__(self): | ||
super(RandomNormalLikeModel, self).__init__() | ||
|
||
def forward(self, x): | ||
return torch.randn_like(x) | ||
|
||
|
||
def main(): | ||
# Set seed for reproducibility | ||
torch.manual_seed(42) | ||
|
||
# Set print options for better precision output | ||
torch.set_printoptions(precision=8) | ||
|
||
# Export Random NormalLike Model | ||
model = RandomNormalLikeModel() | ||
model.eval() | ||
device = torch.device("cpu") | ||
|
||
# Generate test input: a 2D matrix or batch of 2D matrices | ||
file_name = "random_normal_like.onnx" | ||
test_input = torch.randn(2, 4, 4, device=device) # 2 batches of 4x4 matrices | ||
torch.onnx.export(model, | ||
test_input, | ||
file_name, | ||
verbose=False, | ||
opset_version=16) | ||
|
||
print("Finished exporting model to {}".format(file_name)) | ||
|
||
# Output some test data for use in the test | ||
print("Test input data: {}".format(test_input)) | ||
print("Test input data shape: {}".format(test_input.shape)) | ||
output = model.forward(test_input) | ||
print("Test output data shape: {}".format(output.shape)) | ||
print("Test output: {}".format(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 |
---|---|---|
@@ -0,0 +1,101 @@ | ||
use super::{Node, NodeCodegen}; | ||
use crate::burn::{Scope, TensorType, Type}; | ||
use burn::record::PrecisionSettings; | ||
use proc_macro2::TokenStream; | ||
use quote::quote; | ||
|
||
#[derive(Debug, Clone, new)] | ||
pub struct RandomNormalLikeNode { | ||
pub mean: f64, | ||
pub scale: f64, | ||
pub input: TensorType, | ||
pub output: TensorType, | ||
} | ||
|
||
impl RandomNormalLikeNode { | ||
// Set distribution parameters based on mean and scale | ||
fn get_distribution(&self) -> TokenStream { | ||
let mean = self.mean; | ||
let std_deviation = self.scale; | ||
quote! { Distribution::Normal(#mean, #std_deviation) } | ||
} | ||
} | ||
|
||
impl<PS: PrecisionSettings> NodeCodegen<PS> for RandomNormalLikeNode { | ||
fn input_types(&self) -> Vec<Type> { | ||
vec![Type::Tensor(self.input.clone())] | ||
} | ||
|
||
fn output_types(&self) -> Vec<Type> { | ||
vec![Type::Tensor(self.output.clone())] | ||
} | ||
|
||
fn forward(&self, _scope: &mut Scope, _node_position: usize) -> TokenStream { | ||
let output = &self.output.name; | ||
let input = &self.input.name; | ||
let dist = self.get_distribution(); | ||
quote! { | ||
let #output = #input.random_like(#dist); | ||
} | ||
} | ||
|
||
fn into_node(self) -> Node<PS> { | ||
Node::RandomNormalLike(self) | ||
} | ||
|
||
fn register_imports(&self, imports: &mut crate::burn::BurnImports) { | ||
imports.register("burn::tensor::Distribution"); | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
use crate::burn::{graph::BurnGraph, node::test::assert_tokens, TensorKind, TensorType}; | ||
use burn::record::FullPrecisionSettings; | ||
|
||
#[test] | ||
fn test_random_normal_like_codegen() { | ||
let mut graph = BurnGraph::<FullPrecisionSettings>::default(); | ||
|
||
graph.register(RandomNormalLikeNode::new( | ||
0.0f64, | ||
1.0f64, | ||
TensorType::new("input", 2, TensorKind::Float, Some(vec![2, 3])), | ||
TensorType::new("output", 2, TensorKind::Float, Some(vec![2, 3])), | ||
)); | ||
|
||
graph.register_input_output(vec!["input".to_string()], vec!["output".to_string()]); | ||
|
||
let expected = quote! { | ||
use burn::tensor::Distribution; | ||
use burn::{ | ||
module::Module, | ||
tensor::{backend::Backend, Tensor}, | ||
}; | ||
|
||
#[derive(Module, Debug)] | ||
pub struct Model<B: Backend> { | ||
phantom: core::marker::PhantomData<B>, | ||
device: burn::module::Ignored<B::Device>, | ||
} | ||
|
||
impl<B: Backend> Model<B> { | ||
#[allow(unused_variables)] | ||
pub fn new(device: &B::Device) -> Self { | ||
Self { | ||
phantom: core::marker::PhantomData, | ||
device: burn::module::Ignored(device.clone()), | ||
} | ||
} | ||
#[allow(clippy::let_and_return, clippy::approx_constant)] | ||
pub fn forward(&self, input: Tensor<B, 2>) -> Tensor<B, 2> { | ||
let output = input.random_like(Distribution::Normal(0f64, 1f64)); | ||
output | ||
} | ||
} | ||
}; | ||
|
||
assert_tokens(graph.codegen(), expected); | ||
} | ||
} |
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