-
Notifications
You must be signed in to change notification settings - Fork 446
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
Onnx op topk #2305
Open
oojo12
wants to merge
14
commits into
tracel-ai:main
Choose a base branch
from
oojo12:onnx-op-topk
base: main
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.
Open
Onnx op topk #2305
Changes from 8 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
da34ba5
feat: add topk operation
oojo12 2973945
fix test
oojo12 578c346
fix: update IOEntry::Node j in the input_name map
oojo12 17dce60
fix: only run on macos
oojo12 ce1aa89
chore: clean up
oojo12 5783f76
chore: updated supported ops
oojo12 16ce366
cleanup
oojo12 4ca56c6
cleanup
oojo12 49a6a73
address feedback
oojo12 f293ad3
usize cast in config and add topk_smallest
oojo12 449f519
EOD
oojo12 249d60c
EOD cleanup
oojo12 07f79ab
minor update
oojo12 7e221c9
run checks and other fixes
oojo12 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
Binary file not shown.
oojo12 marked this conversation as resolved.
Show resolved
Hide resolved
|
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,57 @@ | ||
import numpy as np | ||
import onnx | ||
from onnx import helper, TensorProto | ||
|
||
# Define the input tensor | ||
X = np.array([[0, 1, 2, 3], | ||
[4, 5, 6, 7], | ||
[8, 9, 10, 11]], dtype=np.float32) | ||
|
||
# Define the value of K | ||
k = 3 | ||
K = np.array([k], dtype=np.int64) | ||
axis = 1 | ||
new_dims = [X.shape[0], k] | ||
|
||
input_tensors = [ | ||
helper.make_tensor_value_info('X', TensorProto.FLOAT, X.shape), | ||
#helper.make_tensor_value_info('K', TensorProto.INT32, K.shape) | ||
] | ||
|
||
output_tensors = [ | ||
helper.make_tensor_value_info('Values', TensorProto.FLOAT, new_dims), | ||
helper.make_tensor_value_info('Indices', TensorProto.INT32, new_dims) | ||
] | ||
|
||
# Create the TopK node | ||
node = helper.make_node( | ||
'TopK', | ||
inputs=['X'],# 'K'], | ||
outputs=['Values', 'Indices'], | ||
axis=axis, # Axis along which to find the top K elements | ||
#largest=-1, | ||
k=k | ||
) | ||
|
||
# Create the graph | ||
graph = helper.make_graph( | ||
nodes = [node], | ||
name = 'TopKGraph', | ||
inputs = input_tensors, | ||
outputs = output_tensors | ||
) | ||
|
||
# Create the model | ||
model = helper.make_model( | ||
graph, | ||
ir_version=8, | ||
opset_imports=[onnx.helper.make_operatorsetid("", 1)] | ||
) | ||
|
||
# Check the model | ||
onnx.checker.check_model(model) | ||
|
||
# Save the model to a file | ||
onnx.save(model, 'top_k.onnx') | ||
|
||
print("Model saved to topk_model.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
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,112 @@ | ||
use super::{Node, NodeCodegen}; | ||
use crate::burn::{Scope, TensorType, Type}; | ||
use burn::config::Config; | ||
use burn::record::PrecisionSettings; | ||
use proc_macro2::TokenStream; | ||
use quote::{quote, ToTokens}; | ||
|
||
#[derive(Config, Debug)] | ||
pub struct TopKConfig { | ||
pub axis: i64, | ||
pub k: i64, | ||
} | ||
|
||
#[derive(Debug, Clone, new)] | ||
pub struct TopKNode { | ||
pub input: TensorType, | ||
pub outputs: Vec<TensorType>, | ||
pub config: TopKConfig, | ||
} | ||
|
||
impl<PS: PrecisionSettings> NodeCodegen<PS> for TopKNode { | ||
fn output_types(&self) -> Vec<Type> { | ||
self.outputs | ||
.iter() | ||
.map(|t| Type::Tensor(t.clone())) | ||
.collect() | ||
} | ||
|
||
fn input_types(&self) -> Vec<Type> { | ||
vec![Type::Tensor(self.input.clone())] | ||
} | ||
|
||
fn forward(&self, scope: &mut Scope, node_position: usize) -> TokenStream { | ||
let axis = self.config.axis.to_token_stream(); | ||
let k = self.config.k.to_token_stream(); | ||
|
||
let input = scope.tensor_use_owned(&self.input, node_position); | ||
let values_output = &self.outputs[0].name; | ||
let indices_output = &self.outputs[1].name; | ||
|
||
quote! { | ||
let (#values_output, #indices_output) = #input.topk_with_indices(#k as usize, #axis as usize); | ||
} | ||
} | ||
|
||
fn into_node(self) -> Node<PS> { | ||
Node::TopK(self) | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use burn::record::FullPrecisionSettings; | ||
|
||
use super::*; | ||
use crate::burn::{ | ||
graph::BurnGraph, | ||
node::{test::assert_tokens, top_k::TopKNode}, | ||
TensorType, | ||
}; | ||
|
||
#[test] | ||
fn test_codegen_nodes() { | ||
let mut graph = BurnGraph::<FullPrecisionSettings>::default(); | ||
let config = TopKConfig::new(-1, 3); | ||
|
||
graph.register(TopKNode::new( | ||
TensorType::new_float("input_tensor", 4), | ||
vec![ | ||
TensorType::new_float("values_tensor", 4), | ||
TensorType::new_int("indices_tensor", 4), | ||
], | ||
config, | ||
)); | ||
|
||
graph.register_input_output( | ||
vec!["input_tensor".to_string()], | ||
vec!["values_tensor".to_string(), "indices_tensor".to_string()], | ||
); | ||
|
||
let expected = quote! { | ||
use burn::tensor::Int; | ||
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: Tensor<B, 4>) -> (Tensor<B, 4>, Tensor<B, 4, Int>) { | ||
let (values_tensor, indices_tensor) = input_tensor.topk_with_indices(3i64 as usize, -1i64 as usize); | ||
oojo12 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
(values_tensor, indices_tensor) | ||
} | ||
} | ||
}; | ||
|
||
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
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
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.
Looks the CI caught something I missed! This file doesn't exist anymore with your changes :)