Skip to main content

onnx_ir/node/
instance_norm.rs

1//! # InstanceNormalization
2//!
3//! Applies instance normalization to the input as described in
4//! <https://arxiv.org/abs/1607.08022>.
5//!
6//! The operation normalizes each channel in each data instance independently:
7//! `y = scale * (x - mean) / sqrt(variance + epsilon) + B`, where mean and
8//! variance are computed per instance per channel.
9//!
10//! **ONNX Spec**: <https://onnx.ai/onnx/operators/onnx__InstanceNormalization.html>
11//!
12//! ## Type Constraints
13//! - T: tensor(float16), tensor(float), tensor(double), tensor(bfloat16)
14//!
15//! ## Opset Versions
16//! - **Opset 1-5**: Earlier versions with different epsilon handling
17//! - **Opset 6+**: Current version with epsilon=1e-5 default and standardized behavior
18//!
19//! ## Missing Test Coverage
20//! - TODO: No test for custom epsilon values (e.g., epsilon=1e-3) - Only default epsilon tested
21//! - TODO: No test for edge cases: zero-mean inputs, constant inputs, single channel
22//! - TODO: No test validating behavior with different batch sizes or spatial dimensions
23use derive_new::new;
24use onnx_ir_derive::NodeBuilder;
25
26use crate::ir::{Argument, Node, RawNode};
27use crate::processor::{
28    InputSpec, NodeProcessor, NodeSpec, OutputPreferences, OutputSpec, ProcessError,
29    lift_all_or_none, validate_group_not_split,
30};
31
32/// Configuration for InstanceNorm operations
33#[derive(Debug, Clone, new)]
34pub struct InstanceNormConfig {
35    /// Small constant added for numerical stability
36    pub epsilon: f64,
37}
38
39/// Node representation for InstanceNormalization operation
40#[derive(Debug, Clone, NodeBuilder)]
41pub struct InstanceNormalizationNode {
42    pub name: String,
43    pub inputs: Vec<Argument>,
44    pub outputs: Vec<Argument>,
45    pub config: InstanceNormConfig,
46}
47
48pub(crate) struct InstanceNormProcessor;
49
50impl NodeProcessor for InstanceNormProcessor {
51    type Config = InstanceNormConfig;
52
53    fn spec(&self) -> NodeSpec {
54        NodeSpec {
55            min_opset: 1,
56            max_opset: None,
57            inputs: InputSpec::Exact(3),
58            outputs: OutputSpec::Exact(1),
59        }
60    }
61
62    fn lift_constants(&self, node: &mut RawNode, _opset: usize) -> Result<(), ProcessError> {
63        // Scale (input 1) and bias (input 2) are lifted together or not at all: codegen
64        // takes the static path only when both are static, and otherwise references both
65        // by name, which a lifted input no longer has.
66        lift_all_or_none(node, &[1, 2])
67    }
68
69    fn infer_types(
70        &self,
71        node: &mut RawNode,
72        _opset: usize,
73        _output_preferences: &OutputPreferences,
74    ) -> Result<(), ProcessError> {
75        validate_group_not_split(node, &[1, 2])?;
76
77        // TODO: Validate input tensor dtype is floating-point type - Type constraint T: tensor(float16), tensor(float), tensor(double), tensor(bfloat16) not enforced - burn/crates/onnx-ir/src/node/instance_norm.rs:88
78        // TODO: Validate that scale and bias tensors are 1D and have size C matching the channel dimension of input - Shape mismatch could cause runtime errors - burn/crates/onnx-ir/src/node/instance_norm.rs:88
79        // TODO: Validate that input tensor is at least 3D (N x C x D1 ...) - Spec requires minimum rank of 3 - burn/crates/onnx-ir/src/node/instance_norm.rs:88
80
81        // Validate attributes before extracting config
82        // Output type is same as input
83        crate::processor::same_as_input(node);
84
85        Ok(())
86    }
87
88    fn extract_config(&self, node: &RawNode, _opset: usize) -> Result<Self::Config, ProcessError> {
89        let mut epsilon = 1e-5;
90
91        for (key, value) in node.attrs.iter() {
92            if key.as_str() == "epsilon" {
93                // TODO: Validate epsilon > 0 for numerical stability
94                epsilon = value.clone().into_f32()?
95            }
96        }
97
98        let config = InstanceNormConfig::new(epsilon as f64);
99        Ok(config)
100    }
101
102    fn build_node(&self, builder: RawNode, opset: usize) -> Result<Node, ProcessError> {
103        let config = self.extract_config(&builder, opset)?;
104
105        Ok(Node::InstanceNormalization(InstanceNormalizationNode {
106            name: builder.name,
107            inputs: builder.inputs,
108            outputs: builder.outputs,
109            config,
110        }))
111    }
112}
113
114#[cfg(test)]
115mod tests {
116    use super::*;
117    use crate::ir::NodeType;
118    use crate::node::test_utils::TestNodeBuilder;
119
120    fn create_test_node(epsilon: f32, num_features: usize) -> TestNodeBuilder {
121        let weight_data = vec![1.0; num_features]; // Not important for the test
122        let bias_data = vec![0.0; num_features]; // Not important for the test
123
124        TestNodeBuilder::new(NodeType::InstanceNormalization, "test_instancenorm")
125            .input_tensor_f32("X", 3, None)
126            .input_tensor_f32_data("scale", weight_data, vec![num_features])
127            .input_tensor_f32_data("bias", bias_data, vec![num_features])
128            .output_tensor_f32("output", 3, None)
129            .attr_float("epsilon", epsilon)
130    }
131
132    #[test]
133    fn test_instance_norm_config_basic() {
134        let node = create_test_node(1e-5, 64).build_with_graph_data(16);
135        let mut node = node;
136        let processor = InstanceNormProcessor;
137        let prefs = OutputPreferences::new();
138        let config = processor.extract_config(&node, 16).unwrap();
139        processor.infer_types(&mut node, 16, &prefs).unwrap();
140
141        assert!(f64::abs(config.epsilon - 1e-5) < 1e-6);
142    }
143
144    #[test]
145    fn test_instance_norm_lifts_scale_and_bias_together() {
146        let mut node = create_test_node(1e-5, 4).build_with_graph_data(16);
147        InstanceNormProcessor.lift_constants(&mut node, 16).unwrap();
148        assert!(node.inputs[1].is_static() && node.inputs[2].is_static());
149    }
150
151    #[test]
152    fn test_instance_norm_mixed_scale_and_bias_not_lifted() {
153        // A constant scale next to a runtime bias must stay named: codegen references
154        // both by name unless both are static.
155        let mut node = TestNodeBuilder::new(NodeType::InstanceNormalization, "test_norm")
156            .input_tensor_f32("X", 3, None)
157            .input_tensor_f32_data("scale", vec![1.0; 4], vec![4])
158            .input_tensor_f32("bias", 1, None)
159            .output_tensor_f32("output", 3, None)
160            .build_with_graph_data(16);
161        InstanceNormProcessor.lift_constants(&mut node, 16).unwrap();
162        assert!(node.inputs[1].is_constant());
163        assert_eq!(node.inputs[1].name, "scale");
164        assert!(node.inputs[2].is_dynamic());
165    }
166
167    #[test]
168    fn test_lifted_scale_with_runtime_bias_rejected() {
169        // A subgraph capturing an already-lifted outer scale alongside a body-input bias:
170        // the scale has no runtime name for codegen to reference.
171        let mut node = TestNodeBuilder::new(NodeType::InstanceNormalization, "test_norm")
172            .input_tensor_f32("X", 3, None)
173            .input_tensor_f32_data("scale", vec![1.0; 4], vec![4])
174            .input_tensor_f32("bias", 1, None)
175            .output_tensor_f32("output", 3, None)
176            .build_with_graph_data(16);
177        node.inputs[1].to_static().unwrap();
178
179        let err = InstanceNormProcessor
180            .infer_types(&mut node, 16, &OutputPreferences::new())
181            .expect_err("a lifted scale with a runtime bias must be rejected");
182        assert!(err.to_string().contains("input #1 is a build-time value"));
183    }
184}