Skip to main content

onnx_ir/node/
mean_variance_normalization.rs

1//! # MeanVarianceNormalization
2//!
3//! Performs mean-variance normalization on the input tensor using the formula
4//! `Y = (X - E[X]) / sqrt(E[(X - E[X])^2])`, where the mean and variance are
5//! reduced along the axes specified by the `axes` attribute (default `[0, 2, 3]`
6//! i.e. normalize across batch and spatial dims, per-channel).
7//!
8//! **ONNX Spec**: <https://onnx.ai/onnx/operators/onnx__MeanVarianceNormalization.html>
9//!
10//! ## Type Constraints
11//! - T: tensor(bfloat16), tensor(double), tensor(float), tensor(float16)
12//!
13//! ## Opset Versions
14//! - **Opset 9**: Initial version (types: float16, float, double)
15//! - **Opset 13**: Added bfloat16 type support
16use crate::ir::{ArgType, Argument, Node, RawNode};
17use crate::processor::{
18    InputSpec, NodeProcessor, NodeSpec, OutputPreferences, OutputSpec, ProcessError,
19};
20use burn_tensor::DType;
21use derive_new::new;
22use onnx_ir_derive::NodeBuilder;
23
24/// Configuration for MeanVarianceNormalization.
25#[derive(Debug, Clone, new)]
26pub struct MeanVarianceNormalizationConfig {
27    /// Axes along which mean and variance are computed. Resolved to positive
28    /// indices, sorted ascending, and deduplicated. Defaults to `[0, 2, 3]`
29    /// per the ONNX spec.
30    pub axes: Vec<usize>,
31}
32
33/// Node representation for the MeanVarianceNormalization operation.
34#[derive(Debug, Clone, NodeBuilder)]
35pub struct MeanVarianceNormalizationNode {
36    pub name: String,
37    pub inputs: Vec<Argument>,
38    pub outputs: Vec<Argument>,
39    pub config: MeanVarianceNormalizationConfig,
40}
41
42pub(crate) struct MeanVarianceNormalizationProcessor;
43
44impl NodeProcessor for MeanVarianceNormalizationProcessor {
45    type Config = MeanVarianceNormalizationConfig;
46
47    fn spec(&self) -> NodeSpec {
48        NodeSpec {
49            min_opset: 9,
50            max_opset: None,
51            inputs: InputSpec::Exact(1),
52            outputs: OutputSpec::Exact(1),
53        }
54    }
55
56    fn infer_types(
57        &self,
58        node: &mut RawNode,
59        opset: usize,
60        _output_preferences: &OutputPreferences,
61    ) -> Result<(), ProcessError> {
62        let arg = node
63            .inputs
64            .first()
65            .ok_or_else(|| ProcessError::MissingInput("Missing input X".to_string()))?;
66        let ArgType::Tensor(ref tensor_ty) = arg.ty else {
67            return Err(ProcessError::TypeMismatch {
68                expected: "Input should be a tensor".to_string(),
69                actual: format!("{:?}", arg.ty),
70            });
71        };
72
73        let allowed = if opset >= 13 {
74            matches!(
75                tensor_ty.dtype,
76                DType::BF16 | DType::F16 | DType::F32 | DType::F64
77            )
78        } else {
79            matches!(tensor_ty.dtype, DType::F16 | DType::F32 | DType::F64)
80        };
81        if !allowed {
82            return Err(ProcessError::TypeMismatch {
83                expected: "Floating-point tensor dtype".to_string(),
84                actual: format!("{:?}", tensor_ty.dtype),
85            });
86        }
87
88        // Run axes validation for its side effect of surfacing out-of-range
89        // errors during type inference. The resolved axes are rebuilt later in
90        // `extract_config`; we discard the value here rather than caching it.
91        let rank = tensor_ty.rank;
92        extract_axes(node, rank)?;
93
94        crate::processor::same_as_input(node);
95
96        Ok(())
97    }
98
99    fn extract_config(&self, node: &RawNode, _opset: usize) -> Result<Self::Config, ProcessError> {
100        let rank = match &node.inputs[0].ty {
101            ArgType::Tensor(tensor) => tensor.rank,
102            other => {
103                return Err(ProcessError::TypeMismatch {
104                    expected: "Tensor".to_string(),
105                    actual: format!("{:?}", other),
106                });
107            }
108        };
109
110        let axes = extract_axes(node, rank)?;
111        Ok(MeanVarianceNormalizationConfig::new(axes))
112    }
113
114    fn build_node(&self, builder: RawNode, opset: usize) -> Result<Node, ProcessError> {
115        let config = self.extract_config(&builder, opset)?;
116
117        Ok(Node::MeanVarianceNormalization(
118            MeanVarianceNormalizationNode {
119                name: builder.name,
120                inputs: builder.inputs,
121                outputs: builder.outputs,
122                config,
123            },
124        ))
125    }
126}
127
128/// Parse the `axes` attribute, resolve negative indices against `rank`, sort, and
129/// deduplicate. Falls back to `[0, 2, 3]` per the ONNX default.
130fn extract_axes(node: &RawNode, rank: usize) -> Result<Vec<usize>, ProcessError> {
131    let (raw_axes, from_default): (Vec<i64>, bool) = match node.attrs.get("axes") {
132        Some(value) => (value.clone().into_i64s()?, false),
133        None => (vec![0, 2, 3], true),
134    };
135
136    let rank_i64 = rank as i64;
137    let mut axes: Vec<usize> = Vec::with_capacity(raw_axes.len());
138    for axis in raw_axes {
139        let resolved = if axis < 0 { axis + rank_i64 } else { axis };
140        if resolved < 0 || resolved >= rank_i64 {
141            let hint = if from_default {
142                " (default axes [0, 2, 3] assume a rank-4 NCHW input; specify `axes` explicitly for other ranks)"
143            } else {
144                ""
145            };
146            return Err(ProcessError::InvalidAttribute {
147                name: "axes".to_string(),
148                reason: format!("axis {axis} is out of range for tensor of rank {rank}{hint}"),
149            });
150        }
151        axes.push(resolved as usize);
152    }
153
154    axes.sort();
155    axes.dedup();
156
157    Ok(axes)
158}
159
160#[cfg(test)]
161mod tests {
162    use super::*;
163    use crate::ir::NodeType;
164    use crate::node::test_utils::TestNodeBuilder;
165
166    fn build_node(rank: usize, axes: Option<Vec<i64>>) -> RawNode {
167        let mut builder = TestNodeBuilder::new(NodeType::MeanVarianceNormalization, "mvn")
168            .input_tensor_f32("X", rank, None)
169            .output_tensor_f32("Y", rank, None);
170        if let Some(axes) = axes {
171            builder = builder.attr_ints("axes", axes);
172        }
173        builder.build()
174    }
175
176    #[test]
177    fn default_axes() {
178        let node = build_node(4, None);
179        let config = MeanVarianceNormalizationProcessor
180            .extract_config(&node, 13)
181            .unwrap();
182        assert_eq!(config.axes, vec![0, 2, 3]);
183    }
184
185    #[test]
186    fn custom_axes_sorted_and_dedup() {
187        let node = build_node(4, Some(vec![3, 0, 2, 0]));
188        let config = MeanVarianceNormalizationProcessor
189            .extract_config(&node, 13)
190            .unwrap();
191        assert_eq!(config.axes, vec![0, 2, 3]);
192    }
193
194    #[test]
195    fn negative_axes_resolved() {
196        let node = build_node(4, Some(vec![-4, -2, -1]));
197        let config = MeanVarianceNormalizationProcessor
198            .extract_config(&node, 13)
199            .unwrap();
200        assert_eq!(config.axes, vec![0, 2, 3]);
201    }
202
203    #[test]
204    fn out_of_range_axis_errors() {
205        let node = build_node(4, Some(vec![4]));
206        let err = MeanVarianceNormalizationProcessor
207            .extract_config(&node, 13)
208            .unwrap_err();
209        assert!(matches!(
210            err,
211            ProcessError::InvalidAttribute { ref name, .. } if name == "axes"
212        ));
213    }
214
215    #[test]
216    fn infer_preserves_shape_and_dtype() {
217        let mut node = TestNodeBuilder::new(NodeType::MeanVarianceNormalization, "mvn")
218            .input_tensor_f32("X", 4, Some(vec![2, 3, 5, 7]))
219            .output_tensor_f32("Y", 4, None)
220            .build();
221        let prefs = OutputPreferences::new();
222        MeanVarianceNormalizationProcessor
223            .infer_types(&mut node, 13, &prefs)
224            .unwrap();
225        match &node.outputs[0].ty {
226            ArgType::Tensor(t) => {
227                assert_eq!(t.dtype, DType::F32);
228                assert_eq!(t.rank, 4);
229                assert_eq!(
230                    t.static_shape,
231                    Some(vec![Some(2), Some(3), Some(5), Some(7)])
232                );
233            }
234            _ => panic!("expected tensor output"),
235        }
236    }
237
238    #[test]
239    fn rejects_non_float_dtype() {
240        let mut node = TestNodeBuilder::new(NodeType::MeanVarianceNormalization, "mvn")
241            .input_tensor_i32("X", 4, None)
242            .output_tensor_f32("Y", 4, None)
243            .build();
244        let prefs = OutputPreferences::new();
245        let err = MeanVarianceNormalizationProcessor
246            .infer_types(&mut node, 13, &prefs)
247            .unwrap_err();
248        assert!(matches!(err, ProcessError::TypeMismatch { .. }));
249    }
250
251    #[test]
252    fn rejects_bfloat16_before_opset_13() {
253        let mut node = TestNodeBuilder::new(NodeType::MeanVarianceNormalization, "mvn")
254            .input_tensor_bf16("X", 4, None)
255            .output_tensor_f32("Y", 4, None)
256            .build();
257        let prefs = OutputPreferences::new();
258        let err = MeanVarianceNormalizationProcessor
259            .infer_types(&mut node, 9, &prefs)
260            .unwrap_err();
261        assert!(matches!(err, ProcessError::TypeMismatch { .. }));
262    }
263}