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 MatmulNode {
pub lhs: TensorType,
pub rhs: TensorType,
pub output: TensorType,
}
impl<PS: PrecisionSettings> NodeCodegen<PS> for MatmulNode {
fn output_types(&self) -> Vec<Type> {
vec![Type::Tensor(self.output.clone())]
}
fn input_types(&self) -> Vec<Type> {
vec![
Type::Tensor(self.lhs.clone()),
Type::Tensor(self.rhs.clone()),
]
}
fn forward(&self, scope: &mut Scope, node_position: usize) -> TokenStream {
let lhs = scope.tensor_use_owned(&self.lhs, node_position);
let rhs = scope.tensor_use_owned(&self.rhs, node_position);
let output = &self.output.name;
quote! {
let #output = #lhs.matmul(#rhs);
}
}
fn into_node(self) -> Node<PS> {
Node::Matmul(self)
}
}
#[cfg(test)]
mod tests {
use burn::record::FullPrecisionSettings;
use super::*;
use crate::burn::{
graph::BurnGraph,
node::{matmul::MatmulNode, test::assert_tokens},
TensorType,
};
#[test]
fn test_codegen_two_nodes() {
let mut graph = BurnGraph::<FullPrecisionSettings>::default();
graph.register(MatmulNode::new(
TensorType::new_float("tensor1", 4),
TensorType::new_float("tensor2", 4),
TensorType::new_float("tensor3", 4),
));
graph.register_input_output(
vec!["tensor1".to_string(), "tensor2".to_string()],
vec!["tensor3".to_string()],
);
let expected = quote! {
use burn::{
module::Module,
tensor::{backend::Backend, Tensor},
};
#[derive(Module, Debug)]
pub struct Model<B: Backend> {
phantom: core::marker::PhantomData<B>,
}
impl<B: Backend> Model <B> {
#[allow(unused_variables)]
pub fn new_with(record: ModelRecord<B>) -> Self {
Self {
phantom: core::marker::PhantomData,
}
}
#[allow(clippy::let_and_return, clippy::approx_constant)]
pub fn forward(
&self,
tensor1: Tensor<B, 4>,
tensor2: Tensor<B, 4>
) -> Tensor<B, 4> {
let tensor3 = tensor1.matmul(tensor2);
tensor3
}
}
};
assert_tokens(graph.codegen(), expected);
}
}