1use derive_new::new;
14use onnx_ir_derive::NodeBuilder;
15
16use crate::ir::Argument;
17
18use crate::ir::{ArgType, Node, RawNode, TensorType};
19use crate::processor::{
20 InputSpec, NodeProcessor, NodeSpec, OutputPreferences, OutputSpec, ProcessError,
21};
22
23#[derive(Debug, Clone)]
30pub enum BatchNormConfig {
31 Static(BatchNormStaticConfig),
33 Runtime(BatchNormRuntimeConfig),
35}
36
37#[derive(Debug, Clone, new)]
39pub struct BatchNormStaticConfig {
40 pub epsilon: f64,
42 pub momentum: f64,
44}
45
46#[derive(Debug, Clone, new)]
48pub struct BatchNormRuntimeConfig {
49 pub epsilon: f64,
51 pub momentum: f64,
53}
54
55#[derive(Debug, Clone, NodeBuilder)]
57pub struct BatchNormalizationNode {
58 pub name: String,
59 pub inputs: Vec<Argument>,
60 pub outputs: Vec<Argument>,
61 pub config: BatchNormConfig,
62}
63
64pub(crate) struct BatchNormProcessor;
65
66impl NodeProcessor for BatchNormProcessor {
67 type Config = BatchNormConfig;
68
69 fn spec(&self) -> NodeSpec {
70 NodeSpec {
71 min_opset: 1,
72 max_opset: None,
73 inputs: InputSpec::Exact(5),
74 outputs: OutputSpec::Range(1, 5),
78 }
79 }
80
81 fn lift_constants(&self, node: &mut RawNode, _opset: usize) -> Result<(), ProcessError> {
82 let all_constant = (1..=4).all(|i| node.inputs.len() > i && node.inputs[i].is_constant());
86
87 if all_constant {
88 for i in 1..=4 {
89 node.inputs[i].to_static()?;
90 }
91 }
92
93 Ok(())
94 }
95
96 fn infer_types(
97 &self,
98 node: &mut RawNode,
99 _opset: usize,
100 _output_preferences: &OutputPreferences,
101 ) -> Result<(), ProcessError> {
102 if let Some(training_mode) = node.attrs.get("training_mode")
104 && training_mode.clone().into_i64()? != 0
105 {
106 return Err(ProcessError::Custom(
107 "BatchNorm: training_mode=1 is not supported (only inference mode)".to_string(),
108 ));
109 }
110
111 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 = {
125 let mut shape = tensor
126 .static_shape
127 .clone()
128 .unwrap_or_else(|| vec![None; tensor.rank]);
129 if shape.len() > 1 && shape[1].is_none() {
131 let channels = node.inputs[1]
132 .value()
133 .and_then(|data| data.shape().first().copied())
134 .or_else(|| match &node.inputs[1].ty {
135 ArgType::Tensor(t) => t
136 .static_shape
137 .as_ref()
138 .and_then(|s| s.first().copied().flatten()),
139 _ => None,
140 });
141 shape[1] = channels;
142 }
143 Some(shape)
144 };
145
146 let channels = static_shape
149 .as_ref()
150 .and_then(|s| s.get(1).copied().flatten());
151 let stats_ty = ArgType::Tensor(TensorType {
152 dtype: tensor.dtype,
153 rank: 1,
154 static_shape: Some(vec![channels]),
155 });
156
157 node.outputs[0].ty = ArgType::Tensor(TensorType {
158 dtype: tensor.dtype,
159 rank: tensor.rank,
160 static_shape,
161 });
162 for output in node.outputs.iter_mut().skip(1) {
163 output.ty = stats_ty.clone();
164 }
165
166 Ok(())
167 }
168
169 fn extract_config(&self, node: &RawNode, _opset: usize) -> Result<Self::Config, ProcessError> {
170 let mut epsilon = 0f32;
171 let mut momentum = 0f32;
172
173 for (key, value) in node.attrs.iter() {
174 match key.as_str() {
175 "momentum" => momentum = value.clone().into_f32()?,
176 "epsilon" => epsilon = value.clone().into_f32()?,
177 "spatial" | "consumed_inputs" | "is_test" | "training_mode" => {}
179 _ => {}
180 }
181 }
182
183 let all_static = (1..=4).all(|i| node.inputs[i].value().is_some());
185
186 if all_static {
187 Ok(BatchNormConfig::Static(BatchNormStaticConfig::new(
188 epsilon as f64,
189 momentum as f64,
190 )))
191 } else {
192 Ok(BatchNormConfig::Runtime(BatchNormRuntimeConfig::new(
193 epsilon as f64,
194 momentum as f64,
195 )))
196 }
197 }
198
199 fn build_node(&self, builder: RawNode, opset: usize) -> Result<Node, ProcessError> {
200 let config = self.extract_config(&builder, opset)?;
201
202 Ok(Node::BatchNormalization(BatchNormalizationNode {
203 name: builder.name,
204 inputs: builder.inputs,
205 outputs: builder.outputs,
206 config,
207 }))
208 }
209}
210
211#[cfg(test)]
212mod tests {
213 use super::*;
214 use crate::ir::NodeType;
215 use crate::node::test_utils::TestNodeBuilder;
216
217 fn create_test_node(epsilon: f32, momentum: f32, num_features: usize) -> TestNodeBuilder {
218 let ones = vec![1.0; num_features];
219 let zeros = vec![0.0; num_features];
220
221 TestNodeBuilder::new(NodeType::BatchNormalization, "test_batchnorm")
222 .input_tensor_f32("X", 4, None) .input_tensor_f32_data("scale", ones.clone(), vec![num_features])
224 .input_tensor_f32_data("bias", zeros.clone(), vec![num_features])
225 .input_tensor_f32_data("mean", zeros.clone(), vec![num_features])
226 .input_tensor_f32_data("var", ones.clone(), vec![num_features])
227 .output_tensor_f32("output", 4, None)
228 .attr_float("epsilon", epsilon)
229 .attr_float("momentum", momentum)
230 }
231
232 fn create_runtime_test_node(epsilon: f32, momentum: f32) -> TestNodeBuilder {
233 TestNodeBuilder::new(NodeType::BatchNormalization, "test_batchnorm")
234 .input_tensor_f32("X", 4, None)
235 .input_tensor_f32("scale", 1, None)
236 .input_tensor_f32("bias", 1, None)
237 .input_tensor_f32("mean", 1, None)
238 .input_tensor_f32("var", 1, None)
239 .output_tensor_f32("output", 4, None)
240 .attr_float("epsilon", epsilon)
241 .attr_float("momentum", momentum)
242 }
243
244 #[test]
245 fn test_batch_norm_config_basic() {
246 let node = create_test_node(1e-5, 0.9, 64).build_with_graph_data(16);
247 let mut node = node;
248 let processor = BatchNormProcessor;
249 let prefs = OutputPreferences::new();
250 let config = processor.extract_config(&node, 16).unwrap();
251 processor.infer_types(&mut node, 16, &prefs).unwrap();
252
253 match config {
254 BatchNormConfig::Static(c) => {
255 assert!(f64::abs(c.epsilon - 1e-5) < 1e-6);
256 assert!(f64::abs(c.momentum - 0.9) < 1e-6);
257 }
258 _ => panic!("Expected Static config"),
259 }
260 }
261
262 #[test]
263 fn test_batch_norm_config_default_values() {
264 let node = create_test_node(0.0, 0.0, 32).build_with_graph_data(16);
265 let mut node = node;
266 let processor = BatchNormProcessor;
267 let prefs = OutputPreferences::new();
268 let config = processor.extract_config(&node, 16).unwrap();
269 processor.infer_types(&mut node, 16, &prefs).unwrap();
270
271 match config {
272 BatchNormConfig::Static(c) => {
273 assert!(f64::abs(c.epsilon - 0.0) < 1e-6);
274 assert!(f64::abs(c.momentum - 0.0) < 1e-6);
275 }
276 _ => panic!("Expected Static config"),
277 }
278 }
279
280 #[test]
281 fn test_batch_norm_config_runtime() {
282 let node = create_runtime_test_node(1e-5, 0.9).build_with_graph_data(16);
283 let processor = BatchNormProcessor;
284 let config = processor.extract_config(&node, 16).unwrap();
285
286 match config {
287 BatchNormConfig::Runtime(c) => {
288 assert!(f64::abs(c.epsilon - 1e-5) < 1e-6);
289 assert!(f64::abs(c.momentum - 0.9) < 1e-6);
290 }
291 _ => panic!("Expected Runtime config"),
292 }
293 }
294
295 #[test]
296 fn test_batch_norm_propagates_static_shape() {
297 let mut node = TestNodeBuilder::new(NodeType::BatchNormalization, "test")
298 .input_tensor_f32("X", 4, Some(vec![1, 64, 32, 32]))
299 .input_tensor_f32_data("scale", vec![1.0; 64], vec![64])
300 .input_tensor_f32_data("bias", vec![0.0; 64], vec![64])
301 .input_tensor_f32_data("mean", vec![0.0; 64], vec![64])
302 .input_tensor_f32_data("var", vec![1.0; 64], vec![64])
303 .output_tensor_f32("output", 4, None)
304 .attr_float("epsilon", 1e-5)
305 .attr_float("momentum", 0.9)
306 .build_with_graph_data(16);
307
308 let processor = BatchNormProcessor;
309 let prefs = OutputPreferences::new();
310 processor.infer_types(&mut node, 16, &prefs).unwrap();
311
312 match &node.outputs[0].ty {
313 ArgType::Tensor(t) => {
314 assert_eq!(
315 t.static_shape,
316 Some(vec![Some(1), Some(64), Some(32), Some(32)])
317 );
318 }
319 _ => panic!("Expected tensor output"),
320 }
321 }
322
323 #[test]
324 fn test_batch_norm_no_input_static_shape_infers_channels() {
325 let mut node = create_test_node(1e-5, 0.9, 64).build_with_graph_data(16);
327 let processor = BatchNormProcessor;
328 let prefs = OutputPreferences::new();
329 processor.infer_types(&mut node, 16, &prefs).unwrap();
330
331 match &node.outputs[0].ty {
332 ArgType::Tensor(t) => {
333 assert_eq!(t.static_shape, Some(vec![None, Some(64), None, None]));
335 }
336 _ => panic!("Expected tensor output"),
337 }
338 }
339
340 #[test]
341 fn test_batch_norm_training_mode_rejected() {
342 let mut node = create_test_node(1e-5, 0.9, 64)
343 .attr_int("training_mode", 1)
344 .build_with_graph_data(16);
345
346 let processor = BatchNormProcessor;
347 let prefs = OutputPreferences::new();
348 let result = processor.infer_types(&mut node, 16, &prefs);
349 assert!(
350 matches!(result, Err(ProcessError::Custom(ref msg)) if msg.contains("training_mode"))
351 );
352 }
353
354 #[test]
355 fn test_batch_norm_runtime_no_static_shape() {
356 let mut node = create_runtime_test_node(1e-5, 0.9).build_with_graph_data(16);
358 let processor = BatchNormProcessor;
359 let prefs = OutputPreferences::new();
360 processor.infer_types(&mut node, 16, &prefs).unwrap();
361
362 match &node.outputs[0].ty {
363 ArgType::Tensor(t) => {
364 assert_eq!(t.static_shape, Some(vec![None, None, None, None]));
365 }
366 _ => panic!("Expected tensor output"),
367 }
368 }
369}