Skip to main content

onnx_ir/node/
layer_norm.rs

1//! # LayerNormalization
2//!
3//! Layer normalization operation.
4//!
5//! **ONNX Spec**: <https://onnx.ai/onnx/operators/onnx__LayerNormalization.html>
6//!
7//! ## Opset Versions
8//! - **Opset 17**: Initial version introducing LayerNormalization operator. Supports `axis`,
9//!   `epsilon`, and `stash_type` attributes. Includes support for optional Mean and InvStdDev outputs.
10//!
11//! **Implementation Note**: Requires at least 2 inputs (X and Scale; Bias is optional).
12//! Accepts 1-3 outputs (Y required, optional Mean and InvStdDev). Scale and Bias are
13//! lifted into a module only when Scale is a 1-D constant, `axis` is the last axis, Bias
14//! is absent or constant, and neither optional output is used; otherwise both stay
15//! graph values.
16
17use derive_new::new;
18use onnx_ir_derive::NodeBuilder;
19
20use crate::ir::{ArgType, Argument, DType, Node, RawNode, TensorType};
21use crate::processor::{
22    InputSpec, NodeProcessor, NodeSpec, OutputPreferences, OutputSpec, ProcessError,
23};
24
25/// Configuration for LayerNorm operations
26#[derive(Debug, Clone, new)]
27pub struct LayerNormConfig {
28    /// Small constant added for numerical stability
29    pub epsilon: f64,
30    /// Whether to use full precision for intermediate calculations (stash_type == 1)
31    pub full_precision: bool,
32    /// First normalized axis, as given in the model (negative counts from the end).
33    #[new(value = "-1")]
34    pub axis: i64,
35}
36
37impl LayerNormConfig {
38    /// Set the epsilon value
39    pub fn with_epsilon(mut self, epsilon: f64) -> Self {
40        self.epsilon = epsilon;
41        self
42    }
43
44    /// Set the full_precision value
45    pub fn with_full_precision(mut self, full_precision: bool) -> Self {
46        self.full_precision = full_precision;
47        self
48    }
49
50    /// Set the axis value
51    pub fn with_axis(mut self, axis: i64) -> Self {
52        self.axis = axis;
53        self
54    }
55}
56
57/// Node representation for LayerNormalization operation
58#[derive(Debug, Clone, NodeBuilder)]
59pub struct LayerNormalizationNode {
60    pub name: String,
61    pub inputs: Vec<Argument>,
62    pub outputs: Vec<Argument>,
63    pub config: LayerNormConfig,
64}
65
66pub(crate) struct LayerNormProcessor;
67
68/// Whether the optional Mean or InvStdDev output is used.
69fn uses_statistics(node: &RawNode) -> bool {
70    node.outputs.iter().skip(1).any(|arg| !arg.is_optional())
71}
72
73impl NodeProcessor for LayerNormProcessor {
74    type Config = LayerNormConfig;
75
76    fn spec(&self) -> NodeSpec {
77        NodeSpec {
78            min_opset: 17,
79            max_opset: None,
80            inputs: InputSpec::AtLeast(2),
81            outputs: OutputSpec::Range(1, 3),
82        }
83    }
84
85    fn lift_constants(&self, node: &mut RawNode, opset: usize) -> Result<(), ProcessError> {
86        // A module holds a single [features] scale over the last axis. Anything else
87        // (a multi-axis scale, or the statistics outputs) goes through the functional
88        // op, which takes scale and bias as graph values.
89        let rank = node.inputs[0].ty.rank() as i64;
90        let axis = self.extract_config(node, opset)?.axis;
91        let axis_is_last = rank > 0 && axis.rem_euclid(rank) == rank - 1;
92        if node.inputs[1].ty.rank() != 1 || !axis_is_last || uses_statistics(node) {
93            return Ok(());
94        }
95        crate::processor::lift_all_or_none(node, &[1, 2])
96    }
97
98    fn infer_types(
99        &self,
100        node: &mut RawNode,
101        opset: usize,
102        _output_preferences: &OutputPreferences,
103    ) -> Result<(), ProcessError> {
104        for key in node.attrs.keys() {
105            match key.as_str() {
106                "axis" | "epsilon" | "stash_type" => {}
107                _ => {}
108            }
109        }
110
111        // TODO: Validate input tensor dtype is floating-point type - Type constraint T not enforced
112        let input = match &node.inputs[0].ty {
113            ArgType::Tensor(tensor) => tensor.clone(),
114            other => {
115                return Err(ProcessError::TypeMismatch {
116                    expected: "Tensor".to_string(),
117                    actual: format!("{other:?}"),
118                });
119            }
120        };
121
122        let config = self.extract_config(node, opset)?;
123        let rank = input.rank as i64;
124        if config.axis < -rank || config.axis >= rank {
125            return Err(ProcessError::Custom(format!(
126                "LayerNorm: axis {} is out of range for rank {rank}",
127                config.axis
128            )));
129        }
130        let axis = config.axis.rem_euclid(rank) as usize;
131
132        // Scale (and Bias) broadcast against the normalized axes X.shape[axis..].
133        let normalized_rank = input.rank - axis;
134        for (index, name) in [(1, "scale"), (2, "bias")] {
135            if let Some(arg) = node.get_input(index)
136                && arg.ty.rank() > normalized_rank
137            {
138                return Err(ProcessError::Custom(format!(
139                    "LayerNorm: {name} must have at most rank {normalized_rank} for axis {}, got rank {}",
140                    config.axis,
141                    arg.ty.rank()
142                )));
143            }
144        }
145
146        crate::processor::same_as_input(node);
147
148        // Mean and InvStdDev keep X's rank with the normalized axes reduced to 1. They
149        // are float32 under stash_type=1, as the computation is.
150        let stat_dtype = if config.full_precision {
151            DType::F32
152        } else {
153            input.dtype
154        };
155        let stat_shape = input.static_shape.as_ref().map(|shape| {
156            shape
157                .iter()
158                .enumerate()
159                .map(|(i, dim)| if i < axis { *dim } else { Some(1) })
160                .collect()
161        });
162        for output in node.outputs.iter_mut().skip(1) {
163            output.ty = ArgType::Tensor(TensorType {
164                dtype: stat_dtype,
165                rank: input.rank,
166                static_shape: stat_shape.clone(),
167            });
168        }
169
170        Ok(())
171    }
172
173    fn extract_config(&self, node: &RawNode, _opset: usize) -> Result<Self::Config, ProcessError> {
174        let mut epsilon = 1e-5;
175        let mut stash_type = 1; // Default value is 1 (full precision)
176        let mut axis = -1;
177
178        for (key, value) in node.attrs.iter() {
179            match key.as_str() {
180                "axis" => axis = value.clone().into_i64()?,
181                "epsilon" => epsilon = value.clone().into_f32()?,
182                "stash_type" => stash_type = value.clone().into_i64()?,
183                _ => {}
184            }
185        }
186
187        // TODO: Validate epsilon > 0 for numerical stability - Negative or zero epsilon could cause issues
188        // TODO: Validate stash_type is 1 or unspecified - Spec only defines stash_type=1 (float), other values undefined
189        let full_precision = stash_type == 1;
190        let config = LayerNormConfig::new(epsilon as f64, full_precision).with_axis(axis);
191        Ok(config)
192    }
193
194    fn build_node(&self, builder: RawNode, opset: usize) -> Result<Node, ProcessError> {
195        let config = self.extract_config(&builder, opset)?;
196
197        Ok(Node::LayerNormalization(LayerNormalizationNode {
198            name: builder.name,
199            inputs: builder.inputs,
200            outputs: builder.outputs,
201            config,
202        }))
203    }
204}
205
206#[cfg(test)]
207mod tests {
208    use super::*;
209    use crate::ir::NodeType;
210    use crate::node::test_utils::TestNodeBuilder;
211
212    fn create_test_node(
213        epsilon: f32,
214        axis: i64,
215        stash_type: i64,
216        num_features: usize,
217    ) -> TestNodeBuilder {
218        let weight_data = vec![1.0; num_features]; // Not important for the test
219        let bias_data = vec![0.0; num_features]; // Not important for the test
220
221        TestNodeBuilder::new(NodeType::LayerNormalization, "test_layernorm")
222            .input_tensor_f32("X", 3, None)
223            .input_tensor_f32_data("scale", weight_data, vec![num_features])
224            .input_tensor_f32_data("bias", bias_data, vec![num_features])
225            .output_tensor_f32("output", 3, None)
226            .attr_float("epsilon", epsilon)
227            .attr_int("axis", axis)
228            .attr_int("stash_type", stash_type)
229    }
230
231    #[test]
232    fn test_layer_norm_config_basic() {
233        let mut node = create_test_node(1e-5, -1, 1, 64).build_with_graph_data(17);
234        let processor = LayerNormProcessor;
235        let prefs = OutputPreferences::new();
236        let config = processor.extract_config(&node, 17).unwrap();
237        processor.infer_types(&mut node, 17, &prefs).unwrap();
238
239        assert!(f64::abs(config.epsilon - 1e-5) < 1e-6);
240        assert!(config.full_precision); // stash_type == 1
241    }
242
243    #[test]
244    fn test_layer_norm_config_no_stash_type() {
245        let mut node = create_test_node(1e-5, -1, 0, 32).build_with_graph_data(17);
246        let processor = LayerNormProcessor;
247        let prefs = OutputPreferences::new();
248        let config = processor.extract_config(&node, 17).unwrap();
249        processor.infer_types(&mut node, 17, &prefs).unwrap();
250
251        assert!(!config.full_precision); // stash_type == 0
252    }
253
254    #[test]
255    fn test_layer_norm_rejects_scale_above_normalized_rank() {
256        // axis=-1 normalizes a single axis, so a rank-2 scale cannot broadcast to it.
257        let node = TestNodeBuilder::new(NodeType::LayerNormalization, "test_layernorm_invalid")
258            .input_tensor_f32("X", 3, None)
259            .input_tensor_f32_data("scale", vec![1.0; 32 * 64], vec![32, 64])
260            .input_tensor_f32_data("bias", vec![0.0; 32 * 64], vec![32, 64])
261            .output_tensor_f32("output", 3, None)
262            .attr_float("epsilon", 1e-5)
263            .attr_int("axis", -1)
264            .attr_int("stash_type", 1)
265            .build_with_graph_data(17);
266
267        let mut node = node;
268        let result = LayerNormProcessor.infer_types(&mut node, 17, &OutputPreferences::new());
269        assert!(matches!(result, Err(ProcessError::Custom(_))));
270    }
271}