Skip to main content

onnx_ir/node/
lp_normalization.rs

1//! # LpNormalization
2//!
3//! For each 1-D slice along `axis`, divides the slice by its Lp-norm:
4//! `Y = X / ||X||_p`. The norm is computed per-slice (reducing `axis` to
5//! size 1) so the division broadcasts against the original shape. A slice of
6//! all zeros yields NaN/Inf, matching ONNX Runtime (the ONNX reference
7//! evaluator adds a `where(norm == 0, 0, ...)` guard that the spec does not
8//! require).
9//!
10//! **ONNX Spec**: <https://onnx.ai/onnx/operators/onnx__LpNormalization.html>
11//!
12//! ## Type Constraints
13//! - T: tensor(bfloat16), tensor(double), tensor(float), tensor(float16)
14//!
15//! ## Opset Versions
16//! - **Opset 1**: Initial version (types: float16, float, double)
17//! - **Opset 22**: Added bfloat16 type support
18use crate::ir::{ArgType, Argument, Node, RawNode};
19use crate::processor::{
20    InputSpec, NodeProcessor, NodeSpec, OutputPreferences, OutputSpec, ProcessError,
21};
22use burn_tensor::DType;
23use derive_new::new;
24use onnx_ir_derive::NodeBuilder;
25
26/// Configuration for LpNormalization.
27#[derive(Debug, Clone, new)]
28pub struct LpNormalizationConfig {
29    /// Axis along which to compute the p-norm. Resolved to a positive index.
30    /// Defaults to the last axis (`rank - 1`) per the ONNX spec.
31    pub axis: usize,
32    /// Order of the norm. ONNX restricts this to 1 (L1) or 2 (L2).
33    pub p: i64,
34}
35
36/// Node representation for the LpNormalization operation.
37#[derive(Debug, Clone, NodeBuilder)]
38pub struct LpNormalizationNode {
39    pub name: String,
40    pub inputs: Vec<Argument>,
41    pub outputs: Vec<Argument>,
42    pub config: LpNormalizationConfig,
43}
44
45pub(crate) struct LpNormalizationProcessor;
46
47impl NodeProcessor for LpNormalizationProcessor {
48    type Config = LpNormalizationConfig;
49
50    fn spec(&self) -> NodeSpec {
51        NodeSpec {
52            min_opset: 1,
53            max_opset: None,
54            inputs: InputSpec::Exact(1),
55            outputs: OutputSpec::Exact(1),
56        }
57    }
58
59    fn infer_types(
60        &self,
61        node: &mut RawNode,
62        opset: usize,
63        _output_preferences: &OutputPreferences,
64    ) -> Result<(), ProcessError> {
65        let arg = node
66            .inputs
67            .first()
68            .ok_or_else(|| ProcessError::MissingInput("input".to_string()))?;
69        let ArgType::Tensor(ref tensor_ty) = arg.ty else {
70            return Err(ProcessError::TypeMismatch {
71                expected: "Input should be a tensor".to_string(),
72                actual: format!("{:?}", arg.ty),
73            });
74        };
75
76        let allowed = if opset >= 22 {
77            matches!(
78                tensor_ty.dtype,
79                DType::BF16 | DType::F16 | DType::F32 | DType::F64
80            )
81        } else {
82            matches!(tensor_ty.dtype, DType::F16 | DType::F32 | DType::F64)
83        };
84        if !allowed {
85            return Err(ProcessError::TypeMismatch {
86                expected: "Floating-point tensor dtype".to_string(),
87                actual: format!("{:?}", tensor_ty.dtype),
88            });
89        }
90
91        // Validate here so malformed graphs fail before codegen.
92        let rank = tensor_ty.rank;
93        extract_axis(node, rank)?;
94        extract_p(node)?;
95
96        crate::processor::same_as_input(node);
97
98        Ok(())
99    }
100
101    fn extract_config(&self, node: &RawNode, _opset: usize) -> Result<Self::Config, ProcessError> {
102        let rank = match &node.inputs[0].ty {
103            ArgType::Tensor(tensor) => tensor.rank,
104            other => {
105                return Err(ProcessError::TypeMismatch {
106                    expected: "Tensor".to_string(),
107                    actual: format!("{:?}", other),
108                });
109            }
110        };
111
112        let axis = extract_axis(node, rank)?;
113        let p = extract_p(node)?;
114        Ok(LpNormalizationConfig::new(axis, p))
115    }
116
117    fn build_node(&self, builder: RawNode, opset: usize) -> Result<Node, ProcessError> {
118        let config = self.extract_config(&builder, opset)?;
119
120        Ok(Node::LpNormalization(LpNormalizationNode {
121            name: builder.name,
122            inputs: builder.inputs,
123            outputs: builder.outputs,
124            config,
125        }))
126    }
127}
128
129/// Parse `axis`, resolving negative values against `rank`. Defaults to `-1`
130/// (last axis) per the ONNX spec.
131fn extract_axis(node: &RawNode, rank: usize) -> Result<usize, ProcessError> {
132    let raw = node
133        .attrs
134        .get("axis")
135        .map(|v| v.clone().into_i64())
136        .transpose()?
137        .unwrap_or(-1);
138
139    let rank_i64 = rank as i64;
140    let resolved = if raw < 0 { raw + rank_i64 } else { raw };
141    if resolved < 0 || resolved >= rank_i64 {
142        return Err(ProcessError::InvalidAttribute {
143            name: "axis".to_string(),
144            reason: format!("axis {raw} is out of range for tensor of rank {rank}"),
145        });
146    }
147    Ok(resolved as usize)
148}
149
150/// Parse `p`, which ONNX restricts to 1 or 2. Defaults to 2 per the ONNX spec.
151fn extract_p(node: &RawNode) -> Result<i64, ProcessError> {
152    let p = node
153        .attrs
154        .get("p")
155        .map(|v| v.clone().into_i64())
156        .transpose()?
157        .unwrap_or(2);
158
159    if p != 1 && p != 2 {
160        return Err(ProcessError::InvalidAttribute {
161            name: "p".to_string(),
162            reason: format!("only p=1 or p=2 are supported by ONNX, got {p}"),
163        });
164    }
165    Ok(p)
166}
167
168#[cfg(test)]
169mod tests {
170    use super::*;
171    use crate::ir::NodeType;
172    use crate::node::test_utils::TestNodeBuilder;
173
174    fn build_node(rank: usize, axis: Option<i64>, p: Option<i64>) -> RawNode {
175        let mut builder = TestNodeBuilder::new(NodeType::LpNormalization, "lpnorm")
176            .input_tensor_f32("X", rank, None)
177            .output_tensor_f32("Y", rank, None);
178        if let Some(axis) = axis {
179            builder = builder.attr_int("axis", axis);
180        }
181        if let Some(p) = p {
182            builder = builder.attr_int("p", p);
183        }
184        builder.build()
185    }
186
187    #[test]
188    fn default_axis_and_p() {
189        let node = build_node(3, None, None);
190        let config = LpNormalizationProcessor.extract_config(&node, 1).unwrap();
191        assert_eq!(config.axis, 2);
192        assert_eq!(config.p, 2);
193    }
194
195    #[test]
196    fn l1_norm_along_axis_0() {
197        let node = build_node(4, Some(0), Some(1));
198        let config = LpNormalizationProcessor.extract_config(&node, 1).unwrap();
199        assert_eq!(config.axis, 0);
200        assert_eq!(config.p, 1);
201    }
202
203    #[test]
204    fn negative_axis_resolved() {
205        let node = build_node(4, Some(-2), None);
206        let config = LpNormalizationProcessor.extract_config(&node, 1).unwrap();
207        assert_eq!(config.axis, 2);
208    }
209
210    #[test]
211    fn negative_axis_boundary() {
212        // axis=-rank resolves to 0; axis=-rank-1 is out of range.
213        let node = build_node(3, Some(-3), None);
214        let config = LpNormalizationProcessor.extract_config(&node, 1).unwrap();
215        assert_eq!(config.axis, 0);
216
217        let node = build_node(3, Some(-4), None);
218        let err = LpNormalizationProcessor
219            .extract_config(&node, 1)
220            .unwrap_err();
221        assert!(matches!(
222            err,
223            ProcessError::InvalidAttribute { ref name, .. } if name == "axis"
224        ));
225    }
226
227    #[test]
228    fn out_of_range_axis_errors() {
229        let node = build_node(3, Some(5), None);
230        let err = LpNormalizationProcessor
231            .extract_config(&node, 1)
232            .unwrap_err();
233        assert!(matches!(
234            err,
235            ProcessError::InvalidAttribute { ref name, .. } if name == "axis"
236        ));
237    }
238
239    #[test]
240    fn invalid_p_errors() {
241        let node = build_node(3, None, Some(3));
242        let err = LpNormalizationProcessor
243            .extract_config(&node, 1)
244            .unwrap_err();
245        assert!(matches!(
246            err,
247            ProcessError::InvalidAttribute { ref name, .. } if name == "p"
248        ));
249    }
250
251    #[test]
252    fn infer_preserves_shape_and_dtype() {
253        let mut node = TestNodeBuilder::new(NodeType::LpNormalization, "lpnorm")
254            .input_tensor_f32("X", 3, Some(vec![2, 4, 5]))
255            .output_tensor_f32("Y", 3, None)
256            .build();
257        let prefs = OutputPreferences::new();
258        LpNormalizationProcessor
259            .infer_types(&mut node, 1, &prefs)
260            .unwrap();
261        match &node.outputs[0].ty {
262            ArgType::Tensor(t) => {
263                assert_eq!(t.dtype, DType::F32);
264                assert_eq!(t.rank, 3);
265                assert_eq!(t.static_shape, Some(vec![Some(2), Some(4), Some(5)]));
266            }
267            _ => panic!("expected tensor output"),
268        }
269    }
270
271    #[test]
272    fn rejects_non_float_dtype() {
273        let mut node = TestNodeBuilder::new(NodeType::LpNormalization, "lpnorm")
274            .input_tensor_i32("X", 3, None)
275            .output_tensor_f32("Y", 3, None)
276            .build();
277        let prefs = OutputPreferences::new();
278        let err = LpNormalizationProcessor
279            .infer_types(&mut node, 1, &prefs)
280            .unwrap_err();
281        assert!(matches!(err, ProcessError::TypeMismatch { .. }));
282    }
283
284    #[test]
285    fn rejects_bfloat16_before_opset_22() {
286        let mut node = TestNodeBuilder::new(NodeType::LpNormalization, "lpnorm")
287            .input_tensor_bf16("X", 3, None)
288            .output_tensor_f32("Y", 3, None)
289            .build();
290        let prefs = OutputPreferences::new();
291        let err = LpNormalizationProcessor
292            .infer_types(&mut node, 1, &prefs)
293            .unwrap_err();
294        assert!(matches!(err, ProcessError::TypeMismatch { .. }));
295    }
296
297    #[test]
298    fn accepts_bfloat16_at_opset_22() {
299        let mut node = TestNodeBuilder::new(NodeType::LpNormalization, "lpnorm")
300            .input_tensor_bf16("X", 3, None)
301            .output_tensor_f32("Y", 3, None)
302            .build();
303        let prefs = OutputPreferences::new();
304        LpNormalizationProcessor
305            .infer_types(&mut node, 22, &prefs)
306            .unwrap();
307    }
308}