Skip to main content

onnx_ir/node/
grid_sample.rs

1//! # GridSample
2//!
3//! Performs spatial sampling using normalized grid coordinates.
4//!
5//! **ONNX Spec**: <https://onnx.ai/onnx/operators/onnx__GridSample.html>
6//!
7//! ## Opset Versions
8//! - **Opset 16**: Initial version with 4D spatial inputs only (N, C, H, W).
9//! - **Opset 20**: Extended to N-dimensional spatial inputs.
10//! - **Opset 22**: Added bfloat16 support for grid.
11
12use derive_new::new;
13use onnx_ir_derive::NodeBuilder;
14use std::str::FromStr;
15
16use crate::ir::{ArgType, Argument, Node, RawNode, TensorType};
17use crate::processor::{
18    InputSpec, NodeProcessor, NodeSpec, OutputPreferences, OutputSpec, ProcessError,
19};
20
21/// Interpolation mode for grid sampling
22#[derive(Debug, Clone, PartialEq, Default)]
23pub enum GridSampleMode {
24    /// Bilinear interpolation (default)
25    #[default]
26    Bilinear,
27    /// Nearest neighbor interpolation
28    Nearest,
29    /// Bicubic interpolation
30    Bicubic,
31}
32
33impl FromStr for GridSampleMode {
34    type Err = String;
35
36    fn from_str(s: &str) -> Result<Self, Self::Err> {
37        match s.to_lowercase().as_str() {
38            "bilinear" | "linear" => Ok(GridSampleMode::Bilinear),
39            "nearest" => Ok(GridSampleMode::Nearest),
40            "bicubic" | "cubic" => Ok(GridSampleMode::Bicubic),
41            _ => Err(format!("Unsupported grid sample mode: {}", s)),
42        }
43    }
44}
45
46/// Padding mode for out-of-bounds grid values
47#[derive(Debug, Clone, PartialEq, Default)]
48pub enum GridSamplePaddingMode {
49    /// Fill with zeros (default)
50    #[default]
51    Zeros,
52    /// Use border values
53    Border,
54    /// Reflect at boundaries
55    Reflection,
56}
57
58impl FromStr for GridSamplePaddingMode {
59    type Err = String;
60
61    fn from_str(s: &str) -> Result<Self, Self::Err> {
62        match s.to_lowercase().as_str() {
63            "zeros" => Ok(GridSamplePaddingMode::Zeros),
64            "border" => Ok(GridSamplePaddingMode::Border),
65            "reflection" => Ok(GridSamplePaddingMode::Reflection),
66            _ => Err(format!("Unsupported grid sample padding mode: {}", s)),
67        }
68    }
69}
70
71/// Configuration for the GridSample operation.
72#[derive(Debug, Clone, new)]
73pub struct GridSampleConfig {
74    /// Interpolation mode (default: bilinear)
75    pub mode: GridSampleMode,
76    /// Padding mode for out-of-bounds values (default: zeros)
77    pub padding_mode: GridSamplePaddingMode,
78    /// Whether grid extrema (-1, 1) refer to corner centers (1) or corner points (0)
79    /// Default: 0 (corner points)
80    pub align_corners: bool,
81}
82
83impl Default for GridSampleConfig {
84    fn default() -> Self {
85        Self {
86            mode: GridSampleMode::Bilinear,
87            padding_mode: GridSamplePaddingMode::Zeros,
88            align_corners: false,
89        }
90    }
91}
92
93/// Node representation for GridSample operation
94#[derive(Debug, Clone, NodeBuilder)]
95pub struct GridSampleNode {
96    pub name: String,
97    pub inputs: Vec<Argument>,
98    pub outputs: Vec<Argument>,
99    pub config: GridSampleConfig,
100}
101
102pub(crate) struct GridSampleProcessor;
103
104impl NodeProcessor for GridSampleProcessor {
105    type Config = GridSampleConfig;
106
107    fn spec(&self) -> NodeSpec {
108        NodeSpec {
109            min_opset: 16,
110            max_opset: None,
111            inputs: InputSpec::Exact(2), // X and grid
112            outputs: OutputSpec::Exact(1),
113        }
114    }
115
116    fn infer_types(
117        &self,
118        node: &mut RawNode,
119        opset: usize,
120        _output_preferences: &OutputPreferences,
121    ) -> Result<(), ProcessError> {
122        // Get input tensor type
123        let input_tensor = match &node.inputs[0].ty {
124            ArgType::Tensor(tensor) => tensor.clone(),
125            _ => {
126                return Err(ProcessError::TypeMismatch {
127                    expected: "Tensor".to_string(),
128                    actual: format!("{:?}", node.inputs[0].ty),
129                });
130            }
131        };
132
133        // Get grid tensor type
134        let grid_tensor = match &node.inputs[1].ty {
135            ArgType::Tensor(tensor) => tensor.clone(),
136            _ => {
137                return Err(ProcessError::TypeMismatch {
138                    expected: "Tensor".to_string(),
139                    actual: format!("{:?}", node.inputs[1].ty),
140                });
141            }
142        };
143
144        // For opset 16, input must be 4D (N, C, H, W)
145        if opset < 20 && input_tensor.rank != 4 {
146            return Err(ProcessError::Custom(format!(
147                "GridSample: For opset {}, input must be 4D (N, C, H, W), got rank {}",
148                opset, input_tensor.rank
149            )));
150        }
151
152        // Grid should have rank = input_rank - 1 + 1 = input_rank
153        // For 4D input (N, C, H, W), grid is (N, H_out, W_out, 2)
154        let expected_grid_rank = input_tensor.rank;
155        if grid_tensor.rank != expected_grid_rank {
156            return Err(ProcessError::Custom(format!(
157                "GridSample: Grid rank should be {}, got {}",
158                expected_grid_rank, grid_tensor.rank
159            )));
160        }
161
162        // Extract and validate config
163        let config = self.extract_config(node, opset)?;
164
165        // Validate bicubic is only for 4D
166        if config.mode == GridSampleMode::Bicubic && input_tensor.rank != 4 {
167            return Err(ProcessError::Custom(
168                "GridSample: Bicubic mode only supports 4D input".to_string(),
169            ));
170        }
171
172        // Output has same dtype as input, same rank
173        // Shape is (N, C, D1_out, D2_out, ...) based on grid dimensions
174        node.outputs[0].ty = ArgType::Tensor(TensorType {
175            dtype: input_tensor.dtype,
176            rank: input_tensor.rank,
177            static_shape: None, // Output shape depends on grid dimensions
178        });
179
180        Ok(())
181    }
182
183    fn extract_config(&self, node: &RawNode, _opset: usize) -> Result<Self::Config, ProcessError> {
184        let mut mode = GridSampleMode::default();
185        let mut padding_mode = GridSamplePaddingMode::default();
186        let mut align_corners = false;
187
188        for (key, value) in node.attrs.iter() {
189            match key.as_str() {
190                "mode" => {
191                    mode = value
192                        .clone()
193                        .into_string()?
194                        .parse::<GridSampleMode>()
195                        .map_err(|e| ProcessError::InvalidAttribute {
196                            name: "mode".to_string(),
197                            reason: e,
198                        })?;
199                }
200                "padding_mode" => {
201                    padding_mode = value
202                        .clone()
203                        .into_string()?
204                        .parse::<GridSamplePaddingMode>()
205                        .map_err(|e| ProcessError::InvalidAttribute {
206                            name: "padding_mode".to_string(),
207                            reason: e,
208                        })?;
209                }
210                "align_corners" => {
211                    align_corners = value.clone().into_i32()? != 0;
212                }
213                _ => {}
214            }
215        }
216
217        Ok(GridSampleConfig {
218            mode,
219            padding_mode,
220            align_corners,
221        })
222    }
223
224    fn build_node(&self, builder: RawNode, opset: usize) -> Result<Node, ProcessError> {
225        let config = self.extract_config(&builder, opset)?;
226
227        Ok(Node::GridSample(GridSampleNode {
228            name: builder.name,
229            inputs: builder.inputs,
230            outputs: builder.outputs,
231            config,
232        }))
233    }
234}
235
236#[cfg(test)]
237mod tests {
238    use super::*;
239    use crate::ir::{DType, NodeType};
240    use crate::node::test_utils::TestNodeBuilder;
241
242    fn create_test_node() -> TestNodeBuilder {
243        TestNodeBuilder::new(NodeType::GridSample, "test_grid_sample")
244            .input_tensor_f32("X", 4, None) // N, C, H, W
245            .input_tensor_f32("grid", 4, None) // N, H_out, W_out, 2
246            .output_tensor_f32("Y", 4, None)
247    }
248
249    #[test]
250    fn test_grid_sample_default_config() {
251        let node = create_test_node().build();
252        let processor = GridSampleProcessor;
253        let config = processor.extract_config(&node, 16).unwrap();
254
255        assert_eq!(config.mode, GridSampleMode::Bilinear);
256        assert_eq!(config.padding_mode, GridSamplePaddingMode::Zeros);
257        assert!(!config.align_corners);
258    }
259
260    #[test]
261    fn test_grid_sample_custom_config() {
262        let node = create_test_node()
263            .attr_string("mode", "nearest")
264            .attr_string("padding_mode", "border")
265            .attr_int("align_corners", 1)
266            .build();
267        let processor = GridSampleProcessor;
268        let config = processor.extract_config(&node, 16).unwrap();
269
270        assert_eq!(config.mode, GridSampleMode::Nearest);
271        assert_eq!(config.padding_mode, GridSamplePaddingMode::Border);
272        assert!(config.align_corners);
273    }
274
275    #[test]
276    fn test_grid_sample_bicubic_mode() {
277        let node = create_test_node().attr_string("mode", "bicubic").build();
278        let processor = GridSampleProcessor;
279        let config = processor.extract_config(&node, 16).unwrap();
280
281        assert_eq!(config.mode, GridSampleMode::Bicubic);
282    }
283
284    #[test]
285    fn test_grid_sample_type_inference() {
286        let mut node = create_test_node().build();
287        let processor = GridSampleProcessor;
288        let prefs = OutputPreferences::new();
289        processor.infer_types(&mut node, 16, &prefs).unwrap();
290
291        match &node.outputs[0].ty {
292            ArgType::Tensor(tensor) => {
293                assert_eq!(tensor.dtype, DType::F32);
294                assert_eq!(tensor.rank, 4);
295            }
296            _ => panic!("Expected tensor output"),
297        }
298    }
299
300    #[test]
301    fn test_grid_sample_invalid_input_rank() {
302        let mut node = TestNodeBuilder::new(NodeType::GridSample, "test_grid_sample")
303            .input_tensor_f32("X", 3, None) // Wrong rank for opset 16
304            .input_tensor_f32("grid", 3, None)
305            .output_tensor_f32("Y", 3, None)
306            .build();
307        let processor = GridSampleProcessor;
308        let prefs = OutputPreferences::new();
309        let result = processor.infer_types(&mut node, 16, &prefs);
310
311        assert!(matches!(result, Err(ProcessError::Custom(_))));
312    }
313
314    #[test]
315    fn test_grid_sample_linear_mode_alias() {
316        // Opset 20+ uses "linear" instead of "bilinear"
317        let node = create_test_node().attr_string("mode", "linear").build();
318        let processor = GridSampleProcessor;
319        let config = processor.extract_config(&node, 20).unwrap();
320
321        // "linear" should map to Bilinear
322        assert_eq!(config.mode, GridSampleMode::Bilinear);
323    }
324
325    #[test]
326    fn test_grid_sample_cubic_mode_alias() {
327        // "cubic" is an alias for "bicubic"
328        let node = create_test_node().attr_string("mode", "cubic").build();
329        let processor = GridSampleProcessor;
330        let config = processor.extract_config(&node, 16).unwrap();
331
332        assert_eq!(config.mode, GridSampleMode::Bicubic);
333    }
334
335    #[test]
336    fn test_grid_sample_reflection_padding() {
337        let node = create_test_node()
338            .attr_string("padding_mode", "reflection")
339            .build();
340        let processor = GridSampleProcessor;
341        let config = processor.extract_config(&node, 16).unwrap();
342
343        assert_eq!(config.padding_mode, GridSamplePaddingMode::Reflection);
344    }
345}