Skip to main content

onnx_ir/node/
random_like.rs

1//! # RandomLike Operations (RandomUniformLike, RandomNormalLike)
2//!
3//! Generates random tensors with the same shape as the input tensor, drawing values
4//! from either a uniform or normal distribution.
5//!
6//! **ONNX Specs**:
7//! - RandomUniformLike: <https://onnx.ai/onnx/operators/onnx__RandomUniformLike.html>
8//! - RandomNormalLike: <https://onnx.ai/onnx/operators/onnx__RandomNormalLike.html>
9//!
10//! ## Type Constraints
11//! - T1: Any tensor type
12//! - T2: float16, float32, or float64 tensor
13//!
14//! ## Opset Versions
15//! - Available since opset version 1
16//! - Current version: 22
17use onnx_ir_derive::NodeBuilder;
18
19use crate::ir::Argument;
20
21use crate::ir::{ArgType, DType, Node, RawNode, TensorType};
22use crate::processor::{
23    InputSpec, NodeProcessor, NodeSpec, OutputPreferences, OutputSpec, ProcessError,
24};
25use crate::protos::tensor_proto::DataType;
26use protobuf::Enum;
27
28/// Configuration for RandomNormalLike operation.
29#[derive(Debug, Clone)]
30pub struct RandomNormalLikeConfig {
31    pub mean: f64,
32    pub scale: f64,
33}
34
35/// Configuration for RandomUniformLike operation.
36#[derive(Debug, Clone)]
37pub struct RandomUniformLikeConfig {
38    pub low: f64,
39    pub high: f64,
40}
41
42/// Enum config that can hold either RandomNormalLike or RandomUniformLike config
43#[derive(Debug, Clone)]
44pub enum RandomLikeConfig {
45    Normal(RandomNormalLikeConfig),
46    Uniform(RandomUniformLikeConfig),
47}
48
49/// Node representation for RandomNormalLike operation
50#[derive(Debug, Clone, NodeBuilder)]
51pub struct RandomNormalLikeNode {
52    pub name: String,
53    pub inputs: Vec<Argument>,
54    pub outputs: Vec<Argument>,
55    pub config: RandomNormalLikeConfig,
56}
57
58/// Node representation for RandomUniformLike operation
59#[derive(Debug, Clone, NodeBuilder)]
60pub struct RandomUniformLikeNode {
61    pub name: String,
62    pub inputs: Vec<Argument>,
63    pub outputs: Vec<Argument>,
64    pub config: RandomUniformLikeConfig,
65}
66
67pub(crate) struct RandomLikeProcessor;
68
69impl NodeProcessor for RandomLikeProcessor {
70    type Config = RandomLikeConfig;
71
72    fn spec(&self) -> NodeSpec {
73        NodeSpec {
74            min_opset: 1,
75            max_opset: None,
76            inputs: InputSpec::Exact(1),
77            outputs: OutputSpec::Exact(1),
78        }
79    }
80
81    fn infer_types(
82        &self,
83        node: &mut RawNode,
84        _opset: usize,
85        _output_preferences: &OutputPreferences,
86    ) -> Result<(), ProcessError> {
87        // TODO: Spec mentions RandomNormalLike has mean/scale attributes, RandomUniformLike has high/low
88        // These attributes are documented but not validated or extracted into config
89        // TODO: Spec also mentions 'seed' attribute that is not validated
90
91        let dtype = node
92            .attrs
93            .get("dtype")
94            .map(|val| {
95                let code = val.clone().into_i32()?;
96                DataType::from_i32(code).ok_or_else(|| {
97                    ProcessError::Custom(format!("unknown dtype attribute value {code}"))
98                })
99            })
100            .transpose()?
101            .unwrap_or(DataType::FLOAT);
102
103        let elem_type = match dtype {
104            DataType::FLOAT => DType::F32,
105            DataType::FLOAT16 => DType::F16,
106            DataType::DOUBLE => DType::F64,
107            _ => {
108                return Err(ProcessError::InvalidAttribute {
109                    name: "dtype".to_string(),
110                    reason: format!("Tensor with type {dtype:?} not supported for random output"),
111                });
112            }
113        };
114
115        if let ArgType::Tensor(tensor) = &node.inputs[0].ty {
116            node.outputs[0].ty = ArgType::Tensor(TensorType {
117                dtype: elem_type,
118                rank: tensor.rank,
119                static_shape: tensor.static_shape.clone(),
120            });
121
122            Ok(())
123        } else {
124            Err(ProcessError::TypeMismatch {
125                expected: "Tensor".to_string(),
126                actual: "Only tensor input is valid".to_string(),
127            })
128        }
129    }
130
131    fn extract_config(&self, node: &RawNode, _opset: usize) -> Result<Self::Config, ProcessError> {
132        let config = match node.node_type {
133            crate::ir::NodeType::RandomNormalLike => {
134                let mean = node
135                    .attrs
136                    .get("mean")
137                    .map(|v| v.clone().into_f32().map(|x| x as f64))
138                    .transpose()?
139                    .unwrap_or(0.0);
140                let scale = node
141                    .attrs
142                    .get("scale")
143                    .map(|v| v.clone().into_f32().map(|x| x as f64))
144                    .transpose()?
145                    .unwrap_or(1.0);
146                RandomLikeConfig::Normal(RandomNormalLikeConfig { mean, scale })
147            }
148            crate::ir::NodeType::RandomUniformLike => {
149                let low = node
150                    .attrs
151                    .get("low")
152                    .map(|v| v.clone().into_f32().map(|x| x as f64))
153                    .transpose()?
154                    .unwrap_or(0.0);
155                let high = node
156                    .attrs
157                    .get("high")
158                    .map(|v| v.clone().into_f32().map(|x| x as f64))
159                    .transpose()?
160                    .unwrap_or(1.0);
161                RandomLikeConfig::Uniform(RandomUniformLikeConfig { low, high })
162            }
163            _ => {
164                return Err(ProcessError::Custom(format!(
165                    "RandomLikeProcessor does not support node type {:?}",
166                    node.node_type
167                )));
168            }
169        };
170
171        Ok(config)
172    }
173
174    fn build_node(&self, builder: RawNode, opset: usize) -> Result<Node, ProcessError> {
175        let config = self.extract_config(&builder, opset)?;
176
177        Ok(match config {
178            RandomLikeConfig::Normal(normal_like_config) => {
179                Node::RandomNormalLike(RandomNormalLikeNode {
180                    name: builder.name,
181                    inputs: builder.inputs,
182                    outputs: builder.outputs,
183                    config: normal_like_config,
184                })
185            }
186            RandomLikeConfig::Uniform(uniform_like_config) => {
187                Node::RandomUniformLike(RandomUniformLikeNode {
188                    name: builder.name,
189                    inputs: builder.inputs,
190                    outputs: builder.outputs,
191                    config: uniform_like_config,
192                })
193            }
194        })
195    }
196}
197
198#[cfg(test)]
199mod tests {
200    use super::*;
201    use crate::ir::NodeType;
202    use crate::node::test_utils::TestNodeBuilder;
203    use crate::protos::tensor_proto::DataType;
204
205    fn create_test_node(
206        dtype: i32,
207        input_rank: usize,
208        static_shape: Option<Vec<usize>>,
209    ) -> RawNode {
210        TestNodeBuilder::new(NodeType::RandomNormalLike, "test_random_like")
211            .input_tensor_f32("input", input_rank, static_shape)
212            .output_tensor_f32("output", 0, None) // Rank 0 will be updated
213            .attr_int("dtype", dtype as i64)
214            .build()
215    }
216
217    #[test]
218    fn test_random_like_float() {
219        let mut node = create_test_node(DataType::FLOAT.value(), 3, None);
220        let processor = RandomLikeProcessor;
221        let prefs = OutputPreferences::new();
222        processor.infer_types(&mut node, 16, &prefs).unwrap();
223
224        match &node.outputs[0].ty {
225            ArgType::Tensor(tensor) => {
226                assert_eq!(tensor.dtype, DType::F32);
227                assert_eq!(tensor.rank, 3);
228            }
229            _ => panic!("Expected tensor output"),
230        }
231    }
232
233    #[test]
234    fn test_random_like_double() {
235        let mut node = create_test_node(DataType::DOUBLE.value(), 2, Some(vec![5, 10]));
236        let processor = RandomLikeProcessor;
237        let prefs = OutputPreferences::new();
238        processor.infer_types(&mut node, 16, &prefs).unwrap();
239
240        match &node.outputs[0].ty {
241            ArgType::Tensor(tensor) => {
242                assert_eq!(tensor.dtype, DType::F64);
243                assert_eq!(tensor.rank, 2);
244                assert_eq!(tensor.static_shape, Some(vec![Some(5), Some(10)]));
245            }
246            _ => panic!("Expected tensor output"),
247        }
248    }
249
250    #[test]
251    fn test_random_like_invalid_input() {
252        let mut node = create_test_node(DataType::FLOAT.value(), 2, None);
253        node.inputs[0].ty = ArgType::ScalarNative(DType::F32);
254        let processor = RandomLikeProcessor;
255        let prefs = OutputPreferences::new();
256        let result = processor.infer_types(&mut node, 16, &prefs);
257        assert!(matches!(result, Err(ProcessError::TypeMismatch { .. })));
258    }
259
260    #[test]
261    fn test_random_like_unsupported_type() {
262        let mut node = create_test_node(DataType::INT32.value(), 2, None);
263        let processor = RandomLikeProcessor;
264        let prefs = OutputPreferences::new();
265        let result = processor.infer_types(&mut node, 16, &prefs);
266        assert!(matches!(result, Err(ProcessError::InvalidAttribute { .. })));
267    }
268}