1use 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#[derive(Debug, Clone, new)]
39pub struct LinearConfig {
40 pub transpose_weight: bool,
44}
45
46#[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 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 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 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 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 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 fn create_gemm_linear_node(has_bias: bool, weight_dims: Vec<usize>) -> TestNodeBuilder {
197 let weight_data = vec![0.0; weight_dims.iter().product()]; 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); 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 fn create_matmul_linear_node(has_bias: bool, weight_dims: Vec<usize>) -> TestNodeBuilder {
220 let weight_data = vec![0.0; weight_dims.iter().product()]; 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 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 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 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 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 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 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 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}