1use 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#[derive(Debug, Clone, new)]
27pub struct LayerNormConfig {
28 pub epsilon: f64,
30 pub full_precision: bool,
32 #[new(value = "-1")]
34 pub axis: i64,
35}
36
37impl LayerNormConfig {
38 pub fn with_epsilon(mut self, epsilon: f64) -> Self {
40 self.epsilon = epsilon;
41 self
42 }
43
44 pub fn with_full_precision(mut self, full_precision: bool) -> Self {
46 self.full_precision = full_precision;
47 self
48 }
49
50 pub fn with_axis(mut self, axis: i64) -> Self {
52 self.axis = axis;
53 self
54 }
55}
56
57#[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
68fn 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 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 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 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 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; 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 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]; let bias_data = vec![0.0; num_features]; 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); }
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); }
253
254 #[test]
255 fn test_layer_norm_rejects_scale_above_normalized_rank() {
256 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}