Skip to main content

onnx_ir/node/
linear.rs

1//! # Linear
2//!
3//! Linear transformation: Y = X * W^T + b
4//!
5//! **Note**: This is a Burn-specific node type created by fusing ONNX Gemm or MatMul+Add operations.
6//! See the node_conversion phase where Gemm (with alpha=1, beta=1, transB=1) is converted to Linear,
7//! and MatMul followed by Add is fused into Linear.
8//!
9//! **Weight Layout**: The weight tensor layout depends on the source operation:
10//! - **Gemm-sourced** (transB=1): Weight is in `[out_features, in_features]` format.
11//!   The `transpose_weight` config flag is set to `true`.
12//! - **MatMul-sourced**: Weight is already in `[in_features, out_features]` format.
13//!   The `transpose_weight` config flag is set to `false`.
14//!
15//! The burn-onnx layer reads the `transpose_weight` flag and transposes the weight
16//! tensor only when needed during code generation.
17//!
18//! **Related ONNX Specs**:
19//! - Gemm: <https://onnx.ai/onnx/operators/onnx__Gemm.html>
20//! - MatMul: <https://onnx.ai/onnx/operators/onnx__MatMul.html>
21//!
22//! ## Missing Test Coverage
23//! - TODO: No test for Linear without bias (2 inputs only) - Optional bias not tested
24//! - TODO: No test for input rank validation - Spec requires specific input dimensions for matrix multiplication
25//! - TODO: No test for dtype mismatch between inputs - All inputs should have same dtype
26//! - TODO: No test for zero-size dimensions - Edge case for empty matrices
27//! - TODO: Test uses sum verification instead of exact values - Could miss subtle bugs in weight application
28
29use derive_new::new;
30use onnx_ir_derive::NodeBuilder;
31
32use crate::ir::{ArgType, Argument, AttributeValue, Node, RawNode, TensorType};
33use crate::processor::{
34    InputSpec, NodeProcessor, NodeSpec, OutputPreferences, OutputSpec, ProcessError,
35};
36
37/// Configuration for Linear operations
38#[derive(Debug, Clone, new)]
39pub struct LinearConfig {
40    /// Whether weight needs transposition for Burn's expected layout.
41    /// - true: Weight is in ONNX Gemm layout [out_features, in_features] (from Gemm with transB=1)
42    /// - false: Weight is already in [in_features, out_features] format (from MatMul)
43    pub transpose_weight: bool,
44}
45
46/// Node representation for Linear operation
47#[derive(Debug, Clone, NodeBuilder)]
48pub struct LinearNode {
49    pub name: String,
50    pub inputs: Vec<Argument>,
51    pub outputs: Vec<Argument>,
52    pub config: LinearConfig,
53}
54
55pub(crate) struct LinearProcessor;
56
57impl NodeProcessor for LinearProcessor {
58    type Config = LinearConfig;
59
60    fn spec(&self) -> NodeSpec {
61        NodeSpec {
62            min_opset: 1,
63            max_opset: None,
64            inputs: InputSpec::AtLeast(2),
65            outputs: OutputSpec::Exact(1),
66        }
67    }
68
69    fn lift_constants(&self, node: &mut RawNode, _opset: usize) -> Result<(), ProcessError> {
70        // Lift weight (input 1) and bias (input 2) if present
71        if node.inputs.len() > 1 && node.inputs[1].is_constant() {
72            node.inputs[1].to_static()?;
73        }
74        if node.inputs.len() > 2 && node.inputs[2].is_constant() {
75            node.inputs[2].to_static()?;
76        }
77
78        Ok(())
79    }
80
81    fn infer_types(
82        &self,
83        node: &mut RawNode,
84        _opset: usize,
85        _output_preferences: &OutputPreferences,
86    ) -> Result<(), ProcessError> {
87        // TODO: Validate all inputs have compatible dtypes - Type mismatch would cause runtime errors - burn/crates/onnx-ir/src/node/linear.rs:86
88        // TODO: Validate input rank is compatible for matrix multiplication - At least 2D required - burn/crates/onnx-ir/src/node/linear.rs:86
89
90        // Validate that only expected attributes are present
91        // Linear accepts only transpose_weight (internal attribute set by node_conversion)
92        for key in node.attrs.keys() {
93            if key != "transpose_weight" {
94                return Err(ProcessError::InvalidAttribute {
95                    name: key.clone(),
96                    reason: format!(
97                        "Linear only accepts 'transpose_weight' attribute, found: {}",
98                        key
99                    ),
100                });
101            }
102        }
103
104        // Gemm's B is 2D by spec, but the Gemm fusion does not check it (MatMul fusion does)
105        let weight_rank = node.inputs[1].ty.rank();
106        if weight_rank != 2 {
107            return Err(ProcessError::Custom(format!(
108                "Linear expects weight tensor of rank 2, got rank {weight_rank}"
109            )));
110        }
111
112        let tensor = match &node.inputs[0].ty {
113            ArgType::Tensor(tensor) => tensor,
114            _ => {
115                return Err(ProcessError::TypeMismatch {
116                    expected: "Tensor".to_string(),
117                    actual: format!("{:?}", node.inputs[0].ty),
118                });
119            }
120        };
121
122        // Compute output static_shape: same as input but last dim = out_features
123        let static_shape = {
124            let transpose_weight = node
125                .attrs
126                .get("transpose_weight")
127                .map(|v| matches!(v, AttributeValue::Int64(1)))
128                .unwrap_or(false);
129            let out_features = node.inputs[1]
130                .value()
131                .and_then(|data| {
132                    let idx = if transpose_weight { 0 } else { 1 };
133                    data.shape().get(idx).copied()
134                })
135                .or_else(|| match &node.inputs[1].ty {
136                    ArgType::Tensor(weight) => weight.static_shape.as_ref().and_then(|ws| {
137                        let idx = if transpose_weight { 0 } else { 1 };
138                        ws.get(idx).copied().flatten()
139                    }),
140                    _ => None,
141                });
142            let mut shape: Vec<Option<usize>> = tensor
143                .static_shape
144                .clone()
145                .unwrap_or_else(|| vec![None; tensor.rank]);
146            if let Some(last) = shape.last_mut() {
147                *last = out_features;
148            }
149            Some(shape)
150        };
151
152        node.outputs[0].ty = ArgType::Tensor(TensorType {
153            dtype: tensor.dtype,
154            rank: tensor.rank,
155            static_shape,
156        });
157
158        Ok(())
159    }
160
161    fn extract_config(&self, node: &RawNode, _opset: usize) -> Result<Self::Config, ProcessError> {
162        use crate::ir::AttributeValue;
163
164        // Check if weight needs transposition (set by node_conversion phase)
165        // - Gemm with transB=1 → transpose_weight=true (weight is [out, in])
166        // - MatMul → transpose_weight=false (weight is [in, out])
167        let transpose_weight = node
168            .attrs
169            .get("transpose_weight")
170            .map(|v| matches!(v, AttributeValue::Int64(1)))
171            .unwrap_or(false);
172
173        Ok(LinearConfig::new(transpose_weight))
174    }
175
176    fn build_node(&self, builder: RawNode, opset: usize) -> Result<Node, ProcessError> {
177        let config = self.extract_config(&builder, opset)?;
178
179        Ok(Node::Linear(LinearNode {
180            name: builder.name,
181            inputs: builder.inputs,
182            outputs: builder.outputs,
183            config,
184        }))
185    }
186}
187
188#[cfg(test)]
189mod tests {
190    use super::*;
191    use crate::ir::NodeType;
192    use crate::node::test_utils::TestNodeBuilder;
193
194    /// Create a test node simulating Gemm->Linear conversion
195    /// Weight is in ONNX Gemm layout [out_features, in_features] with transpose_weight=true
196    fn create_gemm_linear_node(has_bias: bool, weight_dims: Vec<usize>) -> TestNodeBuilder {
197        // Create weight tensor data
198        let weight_data = vec![0.0; weight_dims.iter().product()]; // Not important for the test
199
200        // Start building the node with input and weight
201        // weight_dims is in Gemm format: [out_features, in_features]
202        let mut builder = TestNodeBuilder::new(NodeType::Linear, "test_linear")
203            .input_tensor_f32("input", 2, None)
204            .input_tensor_f32_data("weight", weight_data, weight_dims.clone())
205            .output_tensor_f32("output", 2, None)
206            .attr_int("transpose_weight", 1); // Gemm-sourced
207
208        // Add bias if needed - bias size equals out_features (weight_dims[0])
209        if has_bias {
210            let bias_data = vec![0.0; weight_dims[0]];
211            builder = builder.input_tensor_f32_data("bias", bias_data, vec![weight_dims[0]]);
212        }
213
214        builder
215    }
216
217    /// Create a test node simulating MatMul->Linear conversion
218    /// Weight is in MatMul layout [in_features, out_features] with transpose_weight=false
219    fn create_matmul_linear_node(has_bias: bool, weight_dims: Vec<usize>) -> TestNodeBuilder {
220        // Create weight tensor data
221        let weight_data = vec![0.0; weight_dims.iter().product()]; // Not important for the test
222
223        // Start building the node with input and weight
224        // weight_dims is in MatMul format: [in_features, out_features]
225        let mut builder = TestNodeBuilder::new(NodeType::Linear, "test_linear")
226            .input_tensor_f32("input", 2, None)
227            .input_tensor_f32_data("weight", weight_data, weight_dims.clone())
228            .output_tensor_f32("output", 2, None);
229        // No transpose_weight attribute means MatMul-sourced (transpose_weight=false)
230
231        // Add bias if needed - bias size equals out_features (weight_dims[1] for MatMul)
232        if has_bias {
233            let bias_data = vec![0.0; weight_dims[1]];
234            builder = builder.input_tensor_f32_data("bias", bias_data, vec![weight_dims[1]]);
235        }
236
237        builder
238    }
239
240    #[test]
241    fn test_linear_config_gemm_source() {
242        // Gemm layout: weight shape [10, 5] means [out_features=10, in_features=5]
243        let node = create_gemm_linear_node(false, vec![10, 5]).process(LinearProcessor, 16);
244        let processor = LinearProcessor;
245        let config = processor.extract_config(&node, 16).unwrap();
246
247        assert!(config.transpose_weight);
248    }
249
250    #[test]
251    fn test_linear_config_matmul_source() {
252        // MatMul layout: weight shape [5, 10] means [in_features=5, out_features=10]
253        let node = create_matmul_linear_node(false, vec![5, 10]).process(LinearProcessor, 16);
254        let processor = LinearProcessor;
255        let config = processor.extract_config(&node, 16).unwrap();
256
257        assert!(!config.transpose_weight);
258    }
259
260    #[test]
261    fn test_linear_config_missing_weight() {
262        let mut node = create_matmul_linear_node(false, vec![10, 5]).build_with_graph_data(16);
263        node.inputs.remove(1);
264
265        let processor = LinearProcessor;
266        let spec = processor.spec();
267        let result = crate::processor::validate_node_spec(&node, 16, &spec);
268        assert!(matches!(
269            result,
270            Err(ProcessError::InvalidInputCount { .. })
271        ));
272    }
273
274    #[test]
275    fn test_linear_rejects_non_2d_weight() {
276        let mut node = TestNodeBuilder::new(NodeType::Linear, "test_linear")
277            .input_tensor_f32("input", 2, None)
278            .input_tensor_f32_data("weight", vec![0.0; 60], vec![2, 10, 3])
279            .output_tensor_f32("output", 2, None)
280            .attr_int("transpose_weight", 1)
281            .build_with_graph_data(16);
282
283        let processor = LinearProcessor;
284        let prefs = OutputPreferences::new();
285        let result = processor.infer_types(&mut node, 16, &prefs);
286        assert!(matches!(result, Err(ProcessError::Custom(msg)) if msg.contains("rank 3")));
287    }
288
289    #[test]
290    fn test_linear_static_shape_gemm() {
291        // Gemm: weight [out=10, in=5], input has static shape [batch=2, in=5]
292        let mut node = TestNodeBuilder::new(NodeType::Linear, "test_linear")
293            .input_tensor_f32("input", 2, Some(vec![2, 5]))
294            .input_tensor_f32_data("weight", vec![0.0; 50], vec![10, 5])
295            .output_tensor_f32("output", 2, None)
296            .attr_int("transpose_weight", 1)
297            .build_with_graph_data(16);
298
299        let processor = LinearProcessor;
300        let prefs = OutputPreferences::new();
301        processor.infer_types(&mut node, 16, &prefs).unwrap();
302
303        match &node.outputs[0].ty {
304            ArgType::Tensor(t) => {
305                assert_eq!(t.static_shape, Some(vec![Some(2), Some(10)]));
306            }
307            _ => panic!("Expected tensor output"),
308        }
309    }
310
311    #[test]
312    fn test_linear_static_shape_matmul() {
313        // MatMul: weight [in=5, out=10], input has static shape [batch=2, in=5]
314        let mut node = TestNodeBuilder::new(NodeType::Linear, "test_linear")
315            .input_tensor_f32("input", 2, Some(vec![2, 5]))
316            .input_tensor_f32_data("weight", vec![0.0; 50], vec![5, 10])
317            .output_tensor_f32("output", 2, None)
318            .build_with_graph_data(16);
319
320        let processor = LinearProcessor;
321        let prefs = OutputPreferences::new();
322        processor.infer_types(&mut node, 16, &prefs).unwrap();
323
324        match &node.outputs[0].ty {
325            ArgType::Tensor(t) => {
326                assert_eq!(t.static_shape, Some(vec![Some(2), Some(10)]));
327            }
328            _ => panic!("Expected tensor output"),
329        }
330    }
331
332    #[test]
333    fn test_linear_no_input_static_shape_still_infers_out_features() {
334        // No input static shape -> output still has out_features from weight
335        let node = create_gemm_linear_node(false, vec![10, 5]).process(LinearProcessor, 16);
336
337        match &node.outputs[0].ty {
338            ArgType::Tensor(t) => {
339                assert_eq!(t.static_shape, Some(vec![None, Some(10)]));
340            }
341            _ => panic!("Expected tensor output"),
342        }
343    }
344
345    #[test]
346    fn test_linear_partial_static_shape() {
347        // Input has partial static shape (batch unknown)
348        let mut node = TestNodeBuilder::new(NodeType::Linear, "test_linear")
349            .add_input(
350                "input",
351                ArgType::Tensor(TensorType {
352                    dtype: crate::ir::DType::F32,
353                    rank: 2,
354                    static_shape: Some(vec![None, Some(5)]),
355                }),
356            )
357            .input_tensor_f32_data("weight", vec![0.0; 50], vec![10, 5])
358            .output_tensor_f32("output", 2, None)
359            .attr_int("transpose_weight", 1)
360            .build_with_graph_data(16);
361
362        let processor = LinearProcessor;
363        let prefs = OutputPreferences::new();
364        processor.infer_types(&mut node, 16, &prefs).unwrap();
365
366        match &node.outputs[0].ty {
367            ArgType::Tensor(t) => {
368                assert_eq!(t.static_shape, Some(vec![None, Some(10)]));
369            }
370            _ => panic!("Expected tensor output"),
371        }
372    }
373}