Skip to main content

onnx_ir/node/
random.rs

1//! # Random Tensor Generation (RandomNormal, RandomUniform)
2//!
3//! This module implements processors for ONNX random tensor generation operations that create
4//! tensors with random values sampled from specified distributions.
5//!
6//! **ONNX Specs**:
7//! - RandomNormal: <https://onnx.ai/onnx/operators/onnx__RandomNormal.html>
8//! - RandomUniform: <https://onnx.ai/onnx/operators/onnx__RandomUniform.html>
9//!
10//! ## Supported Operations
11//!
12//! - **RandomNormal**: Generates a tensor with values drawn from a normal distribution
13//! - **RandomUniform**: Generates a tensor with values drawn from a uniform distribution
14//!
15//! Both operations require a `shape` attribute and support an optional `dtype` attribute
16//! (defaults to FLOAT if not specified).
17//!
18//! ## Opset Versions
19//!
20//! ### RandomNormal
21//! - **Opset 1**: Initial version with shape, dtype, mean, scale, and seed attributes.
22//!
23//! ### RandomUniform
24//! - **Opset 1**: Initial version with shape, dtype, high, low, and seed attributes.
25use onnx_ir_derive::NodeBuilder;
26
27use crate::ir::Argument;
28
29use crate::ir::{ArgType, DType, Node, RawNode, TensorType};
30use crate::processor::{
31    InputSpec, NodeProcessor, NodeSpec, OutputPreferences, OutputSpec, ProcessError,
32};
33use crate::protos::tensor_proto::DataType;
34use protobuf::Enum;
35
36/// Configuration for RandomNormal operation.
37#[derive(Debug, Clone)]
38pub struct RandomNormalConfig {
39    pub mean: f64,
40    pub scale: f64,
41    pub shape: Vec<usize>,
42}
43
44/// Configuration for RandomUniform operation.
45#[derive(Debug, Clone)]
46pub struct RandomUniformConfig {
47    pub low: f64,
48    pub high: f64,
49    pub shape: Vec<usize>,
50}
51
52/// Enum config that can hold either RandomNormal or RandomUniform config
53#[derive(Debug, Clone)]
54pub enum RandomConfig {
55    Normal(RandomNormalConfig),
56    Uniform(RandomUniformConfig),
57}
58
59/// Node representation for RandomNormal operation
60#[derive(Debug, Clone, NodeBuilder)]
61pub struct RandomNormalNode {
62    pub name: String,
63    pub inputs: Vec<Argument>,
64    pub outputs: Vec<Argument>,
65    pub config: RandomNormalConfig,
66}
67
68/// Node representation for RandomUniform operation
69#[derive(Debug, Clone, NodeBuilder)]
70pub struct RandomUniformNode {
71    pub name: String,
72    pub inputs: Vec<Argument>,
73    pub outputs: Vec<Argument>,
74    pub config: RandomUniformConfig,
75}
76
77pub(crate) struct RandomProcessor;
78
79impl NodeProcessor for RandomProcessor {
80    type Config = RandomConfig;
81
82    fn spec(&self) -> NodeSpec {
83        NodeSpec {
84            min_opset: 1,
85            max_opset: None,
86            inputs: InputSpec::Exact(0),
87            outputs: OutputSpec::Exact(1),
88        }
89    }
90
91    fn infer_types(
92        &self,
93        node: &mut RawNode,
94        _opset: usize,
95        _output_preferences: &OutputPreferences,
96    ) -> Result<(), ProcessError> {
97        // TODO: Validate that this node has zero inputs (Random operations don't take inputs)
98        // Random operators should have no inputs, but this isn't validated.
99        // Should add: validate_input_count(node, 0) or validate_max_inputs(node, 0)
100        // Location: After validate_output_count
101
102        // TODO: RandomNormal mean and scale attributes not validated or extracted
103        // ONNX spec defines:
104        // - mean (float, default=0.0): Mean of the normal distribution
105        // - scale (float, default=1.0): Standard deviation of the normal distribution
106        // - seed (float, optional): Random seed for reproducibility
107        // These attributes exist in spec but are completely ignored by implementation.
108        // Should extract into config and validate ranges (scale > 0).
109        // Location: extract_config method
110
111        // TODO: RandomUniform high/low attributes not validated or extracted
112        // ONNX spec defines:
113        // - high (float, default=1.0): Upper boundary of uniform distribution (exclusive)
114        // - low (float, default=0.0): Lower boundary of uniform distribution (inclusive)
115        // - seed (float, optional): Random seed for reproducibility
116        // These attributes are ignored. Should extract into config and validate low < high.
117        // Location: extract_config method
118
119        // TODO: Missing test coverage for non-default distribution parameters
120        // Tests only validate basic shape output, not distribution parameters (mean, scale, high, low).
121        // Add tests: random_normal_custom_mean_scale, random_uniform_custom_range
122        // Note: Testing actual distribution properties is hard, but should at least extract attrs.
123
124        // TODO: Missing validation for seed attribute
125        // Spec mentions seed attribute for reproducibility but it's not extracted or validated.
126        // Add tests: random_normal_with_seed, random_uniform_with_seed
127
128        let dtype = node
129            .attrs
130            .get("dtype")
131            .map(|val| {
132                let code = val.clone().into_i32()?;
133                DataType::from_i32(code).ok_or_else(|| {
134                    ProcessError::Custom(format!("unknown dtype attribute value {code}"))
135                })
136            })
137            .transpose()?
138            .unwrap_or(DataType::FLOAT);
139
140        let shape = node
141            .attrs
142            .get("shape")
143            .ok_or_else(|| ProcessError::Custom("required shape attribute missing".to_string()))?
144            .clone()
145            .into_i64s()?;
146
147        let elem_type = match dtype {
148            DataType::FLOAT => DType::F32,
149            DataType::DOUBLE => DType::F64,
150            _ => {
151                return Err(ProcessError::InvalidAttribute {
152                    name: "dtype".to_string(),
153                    reason: format!("tensor with type {dtype:?} not supported for random output"),
154                });
155            }
156        };
157
158        let rank = shape.len();
159
160        node.outputs[0].ty = ArgType::Tensor(TensorType {
161            dtype: elem_type,
162            rank,
163            static_shape: None,
164        });
165
166        Ok(())
167    }
168
169    fn extract_config(&self, node: &RawNode, _opset: usize) -> Result<Self::Config, ProcessError> {
170        let shape = node
171            .attrs
172            .get("shape")
173            .ok_or_else(|| ProcessError::Custom("required shape attribute missing".to_string()))?
174            .clone()
175            .into_i64s()?;
176        let shape: Vec<usize> = shape.into_iter().map(|i| i as usize).collect();
177
178        let config = match node.node_type {
179            crate::ir::NodeType::RandomNormal => {
180                let mean = node
181                    .attrs
182                    .get("mean")
183                    .map(|v| v.clone().into_f32().map(|x| x as f64))
184                    .transpose()?
185                    .unwrap_or(0.0);
186                let scale = node
187                    .attrs
188                    .get("scale")
189                    .map(|v| v.clone().into_f32().map(|x| x as f64))
190                    .transpose()?
191                    .unwrap_or(1.0);
192                RandomConfig::Normal(RandomNormalConfig { mean, scale, shape })
193            }
194            crate::ir::NodeType::RandomUniform => {
195                let low = node
196                    .attrs
197                    .get("low")
198                    .map(|v| v.clone().into_f32().map(|x| x as f64))
199                    .transpose()?
200                    .unwrap_or(0.0);
201                let high = node
202                    .attrs
203                    .get("high")
204                    .map(|v| v.clone().into_f32().map(|x| x as f64))
205                    .transpose()?
206                    .unwrap_or(1.0);
207                RandomConfig::Uniform(RandomUniformConfig { low, high, shape })
208            }
209            _ => {
210                return Err(ProcessError::Custom(format!(
211                    "RandomProcessor does not support node type {:?}",
212                    node.node_type
213                )));
214            }
215        };
216
217        Ok(config)
218    }
219
220    fn build_node(&self, builder: RawNode, opset: usize) -> Result<Node, ProcessError> {
221        let config = self.extract_config(&builder, opset)?;
222
223        Ok(match config {
224            RandomConfig::Normal(normal_config) => Node::RandomNormal(RandomNormalNode {
225                name: builder.name,
226                inputs: builder.inputs,
227                outputs: builder.outputs,
228                config: normal_config,
229            }),
230            RandomConfig::Uniform(uniform_config) => Node::RandomUniform(RandomUniformNode {
231                name: builder.name,
232                inputs: builder.inputs,
233                outputs: builder.outputs,
234                config: uniform_config,
235            }),
236        })
237    }
238}
239
240#[cfg(test)]
241mod tests {
242    use super::*;
243    use crate::ir::NodeType;
244    use crate::node::test_utils::TestNodeBuilder;
245    use crate::protos::tensor_proto::DataType;
246
247    fn create_test_node(dtype: i32, shape: Vec<i64>) -> RawNode {
248        TestNodeBuilder::new(NodeType::RandomNormal, "test_random")
249            .output_tensor_f32("output", 0, None) // Rank 0 will be updated
250            .attr_int("dtype", dtype as i64)
251            .attr_ints("shape", shape)
252            .build()
253    }
254
255    #[test]
256    fn test_random_normal_float() {
257        let mut node = create_test_node(DataType::FLOAT.value(), vec![2, 3, 4]);
258        let processor = RandomProcessor;
259        let prefs = OutputPreferences::new();
260        processor.infer_types(&mut node, 16, &prefs).unwrap();
261
262        match &node.outputs[0].ty {
263            ArgType::Tensor(tensor) => {
264                assert_eq!(tensor.dtype, DType::F32);
265                assert_eq!(tensor.rank, 3);
266            }
267            _ => panic!("Expected tensor output"),
268        }
269    }
270
271    #[test]
272    fn test_random_normal_double() {
273        let mut node = create_test_node(DataType::DOUBLE.value(), vec![5]);
274        let processor = RandomProcessor;
275        let prefs = OutputPreferences::new();
276        processor.infer_types(&mut node, 16, &prefs).unwrap();
277
278        match &node.outputs[0].ty {
279            ArgType::Tensor(tensor) => {
280                assert_eq!(tensor.dtype, DType::F64);
281                assert_eq!(tensor.rank, 1);
282            }
283            _ => panic!("Expected tensor output"),
284        }
285    }
286
287    #[test]
288    fn test_random_normal_missing_shape() {
289        // Create node and then manually remove the shape attribute
290        let mut node = create_test_node(DataType::FLOAT.value(), vec![2, 3]);
291        node.attrs.remove("shape");
292        let processor = RandomProcessor;
293        let prefs = OutputPreferences::new();
294        let result = processor.infer_types(&mut node, 16, &prefs);
295        assert!(matches!(result, Err(ProcessError::Custom(_))));
296    }
297
298    #[test]
299    fn test_random_normal_unsupported_type() {
300        let mut node = create_test_node(DataType::INT32.value(), vec![2, 3]);
301        let processor = RandomProcessor;
302        let prefs = OutputPreferences::new();
303        let result = processor.infer_types(&mut node, 16, &prefs);
304        assert!(matches!(result, Err(ProcessError::InvalidAttribute { .. })));
305    }
306}