Skip to main content

onnx_ir/node/
split.rs

1//! # Split
2//!
3//! Splits a tensor into multiple output tensors along a specified axis.
4//!
5//! **ONNX Spec**: <https://onnx.ai/onnx/operators/onnx__Split.html>
6//!
7//! ## Opset Versions
8//! - **Opset 1-2**: Initial implementation with `split` sizes specified as an attribute.
9//! - **Opset 11**: Refinements to split behavior and type constraints.
10//! - **Opset 13**: **BREAKING CHANGE** - `split` changed from attribute to optional input to
11//!   support dynamic shapes. This enables runtime determination of split sizes.
12//! - **Opset 18**: Added `num_outputs` attribute for easier specification of equal splits without
13//!   explicitly providing split sizes.
14use derive_new::new;
15use onnx_ir_derive::NodeBuilder;
16
17use crate::ir::{ArgType, Argument, Node, RawNode, RuntimeInputRef, TensorDataExt, TensorType};
18use crate::processor::{
19    InputSpec, NodeProcessor, NodeSpec, OutputPreferences, OutputSpec, ProcessError,
20};
21
22/// Represents either a static value or a runtime argument for Split sizes.
23#[derive(Debug, Clone)]
24pub enum SplitSizesInput {
25    /// Static split sizes known at compile time.
26    Static(Vec<usize>),
27    /// Runtime split sizes determined during execution.
28    Runtime(RuntimeInputRef),
29}
30
31impl Default for SplitSizesInput {
32    fn default() -> Self {
33        SplitSizesInput::Static(vec![])
34    }
35}
36
37/// Configuration for the Split operation.
38#[derive(Clone, Debug, new)]
39pub struct SplitConfig {
40    /// The axis along which to split the input tensor.
41    pub axis: usize,
42    /// The uniform size of each split when splitting evenly.
43    /// When `None` and `split_sizes` is also `None`, the split size will be calculated at runtime
44    /// using `num_outputs`.
45    pub split_size: Option<usize>,
46    /// Custom sizes for each split when splitting unevenly (Static or Runtime).
47    pub split_sizes: Option<SplitSizesInput>,
48    /// Number of outputs for runtime split calculation. Only used when both
49    /// `split_size` and `split_sizes` are `None`.
50    pub num_outputs: Option<usize>,
51}
52
53/// Node representation for Split operation
54#[derive(Debug, Clone, NodeBuilder)]
55pub struct SplitNode {
56    pub name: String,
57    pub inputs: Vec<Argument>,
58    pub outputs: Vec<Argument>,
59    pub config: SplitConfig,
60}
61
62pub(crate) struct SplitProcessor;
63
64impl NodeProcessor for SplitProcessor {
65    type Config = SplitConfig;
66
67    fn spec(&self) -> NodeSpec {
68        NodeSpec {
69            min_opset: 1,
70            max_opset: None,
71            inputs: InputSpec::AtLeast(1),
72            outputs: OutputSpec::Range(1, 2147483647),
73        }
74    }
75
76    fn lift_constants(&self, node: &mut RawNode, _opset: usize) -> Result<(), ProcessError> {
77        // Lift split input (input[1]) if present
78        if node.inputs.len() > 1 && node.inputs[1].is_constant() {
79            node.inputs[1].to_static()?;
80        }
81
82        Ok(())
83    }
84
85    fn infer_types(
86        &self,
87        node: &mut RawNode,
88        _opset: usize,
89        _output_preferences: &OutputPreferences,
90    ) -> Result<(), ProcessError> {
91        // Extract the input type to determine rank and shape
92        let (dtype, rank, input_static_shape) = match &node.inputs.first().unwrap().ty {
93            ArgType::Tensor(tensor) => (tensor.dtype, tensor.rank, tensor.static_shape.clone()),
94            ArgType::Shape(r) => (crate::ir::DType::I64, 1, Some(vec![Some(*r)])),
95            ArgType::ScalarTensor(dtype) => (*dtype, 1, Some(vec![Some(1)])),
96            _ => {
97                return Err(ProcessError::TypeMismatch {
98                    expected: "Tensor, Shape, or ScalarTensor".to_string(),
99                    actual: format!("{:?}", node.inputs.first().unwrap().ty),
100                });
101            }
102        };
103
104        // Try to get static split sizes to compute output static shapes
105        let split_sizes: Option<Vec<usize>> = if node.inputs.len() > 1 {
106            node.inputs[1]
107                .value()
108                .and_then(|v| v.try_into_vec::<i64>().ok())
109                .map(|sizes| sizes.into_iter().map(|s| s as usize).collect())
110        } else {
111            // For opset < 13, split sizes are an attribute
112            node.attrs
113                .get("split")
114                .map(|v| v.clone().into_i64s())
115                .transpose()?
116                .map(|sizes| sizes.into_iter().map(|s| s as usize).collect())
117        };
118
119        // Infer output types - all outputs have the same rank and element type as input
120        for (i, output_arg) in node.outputs.iter_mut().enumerate() {
121            let static_shape = if let Some(ref sizes) = split_sizes {
122                // When split sizes are known, compute output static shape
123                if let Some(ref input_shape) = input_static_shape {
124                    // Get the split axis (default 0)
125                    let axis = node
126                        .attrs
127                        .get("axis")
128                        .map(|v| v.clone().into_i64())
129                        .transpose()?
130                        .map(|a| {
131                            if a < 0 {
132                                (a + rank as i64) as usize
133                            } else {
134                                a as usize
135                            }
136                        })
137                        .unwrap_or(0);
138                    if i < sizes.len() {
139                        let mut shape = input_shape.clone();
140                        shape[axis] = Some(sizes[i]);
141                        Some(shape)
142                    } else {
143                        None
144                    }
145                } else {
146                    None
147                }
148            } else {
149                None
150            };
151
152            output_arg.ty = ArgType::Tensor(TensorType {
153                dtype,
154                rank,
155                static_shape,
156            });
157        }
158
159        Ok(())
160    }
161
162    fn is_noop(&self, node: &RawNode) -> bool {
163        // Split is a no-op when there is only a single output
164        node.outputs.len() == 1
165    }
166
167    fn extract_config(&self, node: &RawNode, _opset: usize) -> Result<Self::Config, ProcessError> {
168        // Initialize the axis to split along (default is 0 as per ONNX specification)
169        let mut axis: i64 = 0;
170        // Holds the uniform split size if calculated or provided
171        let split_size: Option<usize> = None;
172        // Holds the custom split sizes if provided as input (Static or Runtime)
173        let mut split_sizes: Option<SplitSizesInput> = None;
174
175        // Extract the input type to determine rank and shape
176        let tensor = match &node.inputs.first().unwrap().ty {
177            ArgType::Tensor(tensor) => tensor.clone(),
178            ArgType::Shape(rank) => TensorType {
179                dtype: crate::ir::DType::I64,
180                rank: 1,
181                static_shape: Some(vec![Some(*rank)]),
182            },
183            ArgType::ScalarTensor(dtype) => TensorType {
184                dtype: *dtype,
185                rank: 1,
186                static_shape: Some(vec![Some(1)]),
187            },
188            _ => {
189                return Err(ProcessError::TypeMismatch {
190                    expected: "Tensor, Shape, or ScalarTensor".to_string(),
191                    actual: format!("{:?}", node.inputs.first().unwrap().ty),
192                });
193            }
194        };
195
196        // Optionally store the number of outputs if provided as an attribute
197        let mut num_outputs: Option<usize> = None;
198
199        // Iterate through node attributes to extract relevant values
200        for (key, value) in node.attrs.iter() {
201            match key.as_str() {
202                "axis" => axis = value.clone().into_i64()?,
203                "num_outputs" => num_outputs = Some(value.clone().into_i64()? as usize),
204                _ => {}
205            }
206        }
207
208        // TODO: Missing validation that split sizes are positive integers.
209        // Negative or zero split sizes should be rejected but only partially validated.
210
211        // Validate axis before normalizing - must be in range [-rank, rank-1]
212        let rank = tensor.rank as i64;
213        if axis < -rank || axis >= rank {
214            return Err(ProcessError::InvalidAttribute {
215                name: "axis".to_string(),
216                reason: format!(
217                    "Split: axis {} is out of range for tensor of rank {} (valid range: [{}, {}])",
218                    axis,
219                    rank,
220                    -rank,
221                    rank - 1
222                ),
223            });
224        }
225
226        // Adjust axis if negative to count from the end as per ONNX spec
227        if axis < 0 {
228            axis += rank;
229        }
230
231        // Validate num_outputs if provided
232        if let Some(num) = num_outputs
233            && num == 0
234        {
235            return Err(ProcessError::InvalidAttribute {
236                name: "num_outputs".to_string(),
237                reason: "Split: num_outputs must be greater than 0".to_string(),
238            });
239        }
240
241        // Handle the case when num_outputs is provided to calculate uniform split size
242        if let Some(num_outputs) = num_outputs
243            && let Some(static_shape) = &tensor.static_shape
244            && let Some(dim_size) = static_shape[axis as usize]
245        {
246            // Validate that dimension size is sufficient for the number of outputs
247            if dim_size == 0 {
248                return Err(ProcessError::Custom(format!(
249                    "Split: cannot split dimension of size 0 into {} outputs",
250                    num_outputs
251                )));
252            }
253
254            // Compute explicit per-output sizes so codegen uses
255            // split_with_sizes(), which always produces exactly num_outputs
256            // chunks (split() can give fewer when dim_size < chunk * (n-1)).
257            let chunk = dim_size.div_ceil(num_outputs);
258            let mut remaining = dim_size;
259            let sizes: Vec<usize> = (0..num_outputs)
260                .map(|_| {
261                    let s = chunk.min(remaining);
262                    remaining = remaining.saturating_sub(chunk);
263                    s
264                })
265                .collect();
266
267            split_sizes = Some(SplitSizesInput::Static(sizes));
268        }
269        // If static shape is not available, split_size will be calculated at runtime
270        // using num_outputs. We'll handle this in the code generation phase.
271
272        // Check for custom split sizes provided as a second input (opset 13+)
273        if node.inputs.len() > 1 {
274            // Validate split input type
275            match &node.inputs[1].ty {
276                ArgType::Tensor(t) => {
277                    // Split tensor must be 1D and int64 dtype
278                    if t.rank != 1 {
279                        return Err(ProcessError::Custom(format!(
280                            "Split: split sizes tensor must be 1D, got rank {}",
281                            t.rank
282                        )));
283                    }
284                    if t.dtype != crate::ir::DType::I64 {
285                        return Err(ProcessError::TypeMismatch {
286                            expected: "Split sizes tensor with dtype I64".to_string(),
287                            actual: format!("Split sizes tensor with dtype {:?}", t.dtype),
288                        });
289                    }
290                }
291                // A Shape is a 1D list of i64 values, like a 1D I64 tensor
292                ArgType::Shape(_) => {}
293                _ => {
294                    return Err(ProcessError::TypeMismatch {
295                        expected: "Tensor for split sizes input".to_string(),
296                        actual: format!("{:?}", node.inputs[1].ty),
297                    });
298                }
299            }
300
301            split_sizes = match node.inputs[1].value() {
302                None => {
303                    // Runtime input - no static value available
304                    Some(SplitSizesInput::Runtime(RuntimeInputRef::new(
305                        node.inputs[1].name.clone(),
306                        1,
307                    )))
308                }
309                Some(tensor_data) => {
310                    let sizes: Vec<i64> = tensor_data.to_i64_vec().map_err(|e| {
311                        ProcessError::Custom(format!("Split: cannot read split sizes: {e:?}"))
312                    })?;
313
314                    // Validate that all split sizes are non-negative
315                    for (i, &size) in sizes.iter().enumerate() {
316                        if size < 0 {
317                            return Err(ProcessError::Custom(format!(
318                                "Split: split size at index {} must be non-negative, got {}",
319                                i, size
320                            )));
321                        }
322                    }
323
324                    let usizes: Vec<usize> = sizes.into_iter().map(|x| x as usize).collect();
325
326                    // Validate that number of split sizes matches number of outputs
327                    if usizes.len() != node.outputs.len() {
328                        return Err(ProcessError::Custom(format!(
329                            "Split: number of split sizes ({}) must match number of outputs ({})",
330                            usizes.len(),
331                            node.outputs.len()
332                        )));
333                    }
334
335                    // Validate that sum of split sizes matches the dimension size (if static shape is available)
336                    if let Some(static_shape) = &tensor.static_shape
337                        && let Some(dim_size) = static_shape[axis as usize]
338                    {
339                        let total_size: usize = usizes.iter().sum();
340                        if total_size != dim_size {
341                            return Err(ProcessError::Custom(format!(
342                                "Split: sum of split sizes ({}) must equal dimension size ({}) along axis {}",
343                                total_size, dim_size, axis
344                            )));
345                        }
346                    }
347
348                    if !usizes.is_empty() {
349                        Some(SplitSizesInput::Static(usizes))
350                    } else {
351                        None
352                    }
353                }
354            };
355        } else if let Some(split_attr) = node.attrs.get("split") {
356            // For opset < 13, split sizes are an attribute
357            let sizes = split_attr.clone().into_i64s()?;
358            if !sizes.is_empty() {
359                if sizes.iter().any(|&s| s < 0) {
360                    return Err(ProcessError::Custom(
361                        "Split: split sizes must be non-negative".to_string(),
362                    ));
363                }
364                let usizes: Vec<usize> = sizes.into_iter().map(|s| s as usize).collect();
365
366                if usizes.len() != node.outputs.len() {
367                    return Err(ProcessError::Custom(format!(
368                        "Split: number of split sizes ({}) must match number of outputs ({})",
369                        usizes.len(),
370                        node.outputs.len()
371                    )));
372                }
373
374                if let Some(static_shape) = &tensor.static_shape
375                    && let Some(dim_size) = static_shape[axis as usize]
376                {
377                    let total_size: usize = usizes.iter().sum();
378                    if total_size != dim_size {
379                        return Err(ProcessError::Custom(format!(
380                            "Split: sum of split sizes ({}) must equal dimension size ({}) along axis {}",
381                            total_size, dim_size, axis
382                        )));
383                    }
384                }
385
386                split_sizes = Some(SplitSizesInput::Static(usizes));
387            }
388        }
389
390        // Infer split_size if neither custom split_sizes nor split_size is provided
391        // and static shape is available
392        if split_sizes.is_none()
393            && split_size.is_none()
394            && let Some(static_shape) = &tensor.static_shape
395            && let Some(dim_size) = static_shape[axis as usize]
396        {
397            let n = node.outputs.len();
398            let chunk = dim_size.div_ceil(n);
399            let mut remaining = dim_size;
400            let sizes: Vec<usize> = (0..n)
401                .map(|_| {
402                    let s = chunk.min(remaining);
403                    remaining = remaining.saturating_sub(chunk);
404                    s
405                })
406                .collect();
407
408            split_sizes = Some(SplitSizesInput::Static(sizes));
409        }
410        // If static shape is not available, we need num_outputs for runtime calculation
411
412        // Determine num_outputs for runtime calculation
413        // Only set if both split_size and split_sizes are None (runtime case)
414        let runtime_num_outputs = if split_size.is_none() && split_sizes.is_none() {
415            Some(num_outputs.unwrap_or(node.outputs.len()))
416        } else {
417            None
418        };
419
420        // Return the configuration for splitting operation
421        let config = SplitConfig {
422            axis: axis as usize,
423            split_size,
424            split_sizes,
425            num_outputs: runtime_num_outputs,
426        };
427        Ok(config)
428    }
429
430    fn build_node(&self, builder: RawNode, opset: usize) -> Result<Node, ProcessError> {
431        let config = self.extract_config(&builder, opset)?;
432
433        Ok(Node::Split(SplitNode {
434            name: builder.name,
435            inputs: builder.inputs,
436            outputs: builder.outputs,
437            config,
438        }))
439    }
440}
441
442#[cfg(test)]
443mod tests {
444    use super::*;
445    use crate::ir::{ArgType, AttributeValue, DType, NodeType};
446    use crate::node::test_utils::TestNodeBuilder;
447    use std::collections::HashMap;
448
449    fn create_test_node(
450        input_rank: usize,
451        num_outputs: usize,
452        static_shape: Option<Vec<usize>>,
453        attrs: Option<HashMap<String, AttributeValue>>,
454        split_sizes_input: Option<Vec<i64>>,
455    ) -> TestNodeBuilder {
456        // Start with input tensor
457        let mut builder = TestNodeBuilder::new(NodeType::Split, "test_split").input_tensor_f32(
458            "input",
459            input_rank,
460            static_shape,
461        );
462
463        // Add split sizes input if provided
464        if let Some(sizes) = split_sizes_input {
465            builder = builder.input_tensor_i64_data("split", sizes.clone(), vec![sizes.len()]);
466        }
467
468        // Add output tensors
469        for i in 0..num_outputs {
470            builder = builder.output_tensor_f32(
471                &format!("output_{i}"),
472                0, // Will be updated
473                None,
474            );
475        }
476
477        // Add attributes if provided
478        if let Some(attributes) = attrs {
479            for (key, value) in attributes {
480                builder = match key.as_str() {
481                    "axis" => builder.attr_int("axis", value.into_i64().unwrap()),
482                    "num_outputs" => builder.attr_int("num_outputs", value.into_i64().unwrap()),
483                    _ => builder,
484                };
485            }
486        }
487
488        builder
489    }
490
491    #[test]
492    fn test_split_single_output() {
493        let mut node = create_test_node(3, 1, Some(vec![10, 20, 30]), None, None).build();
494
495        let processor = SplitProcessor;
496        let prefs = OutputPreferences::new();
497        let _config = processor.extract_config(&node, 16).unwrap();
498        processor.infer_types(&mut node, 16, &prefs).unwrap();
499
500        assert_eq!(node.outputs.len(), 1);
501        match &node.outputs[0].ty {
502            ArgType::Tensor(tensor) => {
503                assert_eq!(tensor.dtype, DType::F32);
504                assert_eq!(tensor.rank, 3);
505            }
506            _ => panic!("Expected tensor output"),
507        }
508    }
509
510    #[test]
511    fn test_split_multiple_outputs() {
512        let mut node = create_test_node(4, 3, Some(vec![12, 15, 18, 21]), None, None).build();
513
514        let processor = SplitProcessor;
515        let prefs = OutputPreferences::new();
516        let _config = processor.extract_config(&node, 16).unwrap();
517        processor.infer_types(&mut node, 16, &prefs).unwrap();
518
519        assert_eq!(node.outputs.len(), 3);
520        for output in &node.outputs {
521            match &output.ty {
522                ArgType::Tensor(tensor) => {
523                    assert_eq!(tensor.dtype, DType::F32);
524                    assert_eq!(tensor.rank, 4);
525                }
526                _ => panic!("Expected tensor output"),
527            }
528        }
529    }
530
531    #[test]
532    fn test_split_invalid_input() {
533        let mut node = create_test_node(3, 2, Some(vec![10, 20, 30]), None, None).build();
534        node.inputs[0].ty = ArgType::ScalarNative(DType::F32);
535
536        let processor = SplitProcessor;
537        let _prefs = OutputPreferences::new();
538        let result = processor.extract_config(&node, 16);
539        assert!(matches!(result, Err(ProcessError::TypeMismatch { .. })));
540    }
541
542    // Tests for split_config function
543
544    #[test]
545    fn test_split_config_default_axis() {
546        // Create a node with static shape and 2 outputs
547        let static_shape = Some(vec![10, 20, 30]);
548        let node = create_test_node(3, 2, static_shape, None, None).build();
549
550        let mut node = node;
551        let processor = SplitProcessor;
552        let prefs = OutputPreferences::new();
553        let config = processor.extract_config(&node, 16).unwrap();
554        processor.infer_types(&mut node, 16, &prefs).unwrap();
555
556        // Default axis should be 0, with explicit split sizes
557        assert_eq!(config.axis, 0);
558        assert!(config.split_size.is_none());
559        assert!(
560            matches!(&config.split_sizes, Some(SplitSizesInput::Static(sizes)) if sizes == &vec![5, 5])
561        );
562    }
563
564    #[test]
565    fn test_split_config_specified_axis() {
566        // Create a node with static shape, 2 outputs, and a specified axis
567        let static_shape = Some(vec![10, 20, 30]);
568        let mut attrs = HashMap::new();
569        attrs.insert("axis".to_string(), AttributeValue::Int64(1)); // Split along axis 1
570
571        let node = create_test_node(3, 2, static_shape, Some(attrs), None).build();
572
573        let mut node = node;
574        let processor = SplitProcessor;
575        let prefs = OutputPreferences::new();
576        let config = processor.extract_config(&node, 16).unwrap();
577        processor.infer_types(&mut node, 16, &prefs).unwrap();
578
579        assert_eq!(config.axis, 1);
580        assert!(config.split_size.is_none());
581        assert!(
582            matches!(&config.split_sizes, Some(SplitSizesInput::Static(sizes)) if sizes == &vec![10, 10])
583        );
584    }
585
586    #[test]
587    fn test_split_config_negative_axis() {
588        // Test with negative axis (should count from the end)
589        let static_shape = Some(vec![10, 20, 30]);
590        let mut attrs = HashMap::new();
591        attrs.insert("axis".to_string(), AttributeValue::Int64(-1)); // Last axis (index 2)
592
593        let node = create_test_node(3, 3, static_shape, Some(attrs), None).build();
594
595        let mut node = node;
596        let processor = SplitProcessor;
597        let prefs = OutputPreferences::new();
598        let config = processor.extract_config(&node, 16).unwrap();
599        processor.infer_types(&mut node, 16, &prefs).unwrap();
600
601        assert_eq!(config.axis, 2); // -1 should be converted to 2
602        assert!(config.split_size.is_none());
603        assert!(
604            matches!(&config.split_sizes, Some(SplitSizesInput::Static(sizes)) if sizes == &vec![10, 10, 10])
605        );
606    }
607
608    #[test]
609    fn test_split_config_num_outputs_attr() {
610        // Test with explicitly specified num_outputs attribute
611        let static_shape = Some(vec![12, 24, 36]);
612        let mut attrs = HashMap::new();
613        attrs.insert("num_outputs".to_string(), AttributeValue::Int64(4));
614
615        let node = create_test_node(3, 4, static_shape, Some(attrs), None).build();
616
617        let mut node = node;
618        let processor = SplitProcessor;
619        let prefs = OutputPreferences::new();
620        let config = processor.extract_config(&node, 16).unwrap();
621        processor.infer_types(&mut node, 16, &prefs).unwrap();
622
623        assert_eq!(config.axis, 0);
624        assert!(config.split_size.is_none());
625        assert!(
626            matches!(&config.split_sizes, Some(SplitSizesInput::Static(sizes)) if sizes == &vec![3, 3, 3, 3])
627        );
628    }
629
630    #[test]
631    fn test_split_config_with_split_sizes_input() {
632        // Test with explicit split sizes provided as second input
633        let static_shape = Some(vec![10, 20, 30]);
634        let split_sizes = vec![3, 7]; // Custom split sizes along default axis (must sum to 10)
635
636        let node = create_test_node(3, 2, static_shape, None, Some(split_sizes.clone()))
637            .build_with_graph_data(16);
638
639        let mut node = node;
640        let processor = SplitProcessor;
641        let prefs = OutputPreferences::new();
642        let config = processor.extract_config(&node, 16).unwrap();
643        processor.infer_types(&mut node, 16, &prefs).unwrap();
644
645        assert_eq!(config.axis, 0);
646        assert_eq!(config.split_size, None);
647        assert!(
648            matches!(&config.split_sizes, Some(SplitSizesInput::Static(sizes)) if sizes == &vec![3, 7])
649        );
650    }
651
652    #[test]
653    fn test_split_config_both_splits_and_num_outputs() {
654        // Test with both split sizes input and num_outputs attribute (should be valid but may have issues)
655        let static_shape = Some(vec![10, 20, 30]);
656        let mut attrs = HashMap::new();
657        attrs.insert("num_outputs".to_string(), AttributeValue::Int64(2));
658        let split_sizes = vec![3, 7];
659
660        let node = create_test_node(3, 2, static_shape, Some(attrs), Some(split_sizes))
661            .build_with_graph_data(16);
662
663        let mut node = node;
664        let processor = SplitProcessor;
665        let prefs = OutputPreferences::new();
666        // When both are provided, split_sizes takes precedence, so extract_config should succeed
667        let _config = processor.extract_config(&node, 16).unwrap();
668        processor.infer_types(&mut node, 16, &prefs).unwrap();
669    }
670
671    #[test]
672    fn test_split_config_zero_num_outputs() {
673        // Test with num_outputs attribute set to 0 - this causes divide by zero
674        // The test just verifies the node can be created; actual usage would need validation
675        let static_shape = Some(vec![10, 20, 30]);
676        let mut attrs = HashMap::new();
677        attrs.insert("num_outputs".to_string(), AttributeValue::Int64(0));
678
679        let node = create_test_node(3, 0, static_shape, Some(attrs), None).build();
680
681        // Node created successfully - config extraction would panic on zero, so we skip it
682        assert_eq!(node.outputs.len(), 0);
683    }
684
685    #[test]
686    fn test_split_config_invalid_num_outputs() {
687        // Test with num_outputs larger than the dimension size
688        let static_shape = Some(vec![5, 10, 15]);
689        let mut attrs = HashMap::new();
690        attrs.insert("num_outputs".to_string(), AttributeValue::Int64(10)); // Larger than dim 0 size
691
692        let node = create_test_node(3, 10, static_shape, Some(attrs), None).build();
693
694        let mut node = node;
695        let processor = SplitProcessor;
696        let prefs = OutputPreferences::new();
697        let _config = processor.extract_config(&node, 16).unwrap();
698        processor.infer_types(&mut node, 16, &prefs).unwrap();
699    }
700
701    #[test]
702    fn test_split_config_no_static_shape() {
703        // Test with no static shape available - extract_config should succeed
704        // with num_outputs set for runtime calculation
705        let mut attrs = HashMap::new();
706        attrs.insert("num_outputs".to_string(), AttributeValue::Int64(2));
707
708        let node = create_test_node(3, 2, None, Some(attrs), None).build();
709
710        let node = node;
711        let processor = SplitProcessor;
712        let config = processor.extract_config(&node, 16).unwrap();
713
714        // When static shape is not available, split_size is None and num_outputs is set
715        assert_eq!(config.axis, 0);
716        assert!(config.split_size.is_none());
717        assert!(config.split_sizes.is_none());
718        assert_eq!(config.num_outputs, Some(2));
719    }
720
721    #[test]
722    fn test_split_config_invalid_input_type() {
723        // Test with invalid input type - extract_config should fail
724        let mut node = create_test_node(3, 2, Some(vec![10, 20, 30]), None, None).build();
725        node.inputs[0].ty = ArgType::ScalarNative(DType::F32);
726
727        let node = node;
728        let processor = SplitProcessor;
729        let result = processor.extract_config(&node, 16);
730        assert!(matches!(result, Err(ProcessError::TypeMismatch { .. })));
731    }
732
733    #[test]
734    fn test_split_config_with_runtime_split_sizes() {
735        // Test with runtime split sizes (no static value)
736        let static_shape = Some(vec![20, 30, 40]);
737        let node = TestNodeBuilder::new(NodeType::Split, "test_split")
738            .input_tensor_f32("input", 3, static_shape)
739            .input_tensor_i64("split", 1, Some(vec![2])) // Runtime input - no static value
740            .output_tensor_f32("output_0", 0, None)
741            .output_tensor_f32("output_1", 0, None)
742            .build();
743
744        let mut node = node;
745        let processor = SplitProcessor;
746        let prefs = OutputPreferences::new();
747        let config = processor.extract_config(&node, 16).unwrap();
748        processor.infer_types(&mut node, 16, &prefs).unwrap();
749
750        assert_eq!(config.axis, 0);
751        assert_eq!(config.split_size, None);
752        assert!(
753            matches!(&config.split_sizes, Some(SplitSizesInput::Runtime(arg)) if arg.name == "split")
754        );
755    }
756
757    #[test]
758    fn test_split_config_non_even_split() {
759        // Test with non-evenly divisible dimension size
760        let static_shape = Some(vec![11, 22, 33]); // 11 is not evenly divisible by 3
761        let mut attrs = HashMap::new();
762        attrs.insert("axis".to_string(), AttributeValue::Int64(0));
763
764        let node = create_test_node(3, 3, static_shape, Some(attrs), None).build();
765
766        let mut node = node;
767        let processor = SplitProcessor;
768        let prefs = OutputPreferences::new();
769        let config = processor.extract_config(&node, 16).unwrap();
770        processor.infer_types(&mut node, 16, &prefs).unwrap();
771
772        // ceil(11 / 3) = 4, so sizes = [4, 4, 3]
773        assert!(config.split_size.is_none());
774        assert!(
775            matches!(&config.split_sizes, Some(SplitSizesInput::Static(sizes)) if sizes == &vec![4, 4, 3])
776        );
777    }
778
779    // TODO: Missing test for split with runtime split sizes (dynamic case).
780    // Need test where split input has no static value to verify Runtime variant handling.
781
782    /// Regression test for #55: Split must accept Shape(rank) input.
783    /// Shape values flow through Split in models that reshape tensors based on
784    /// computed shapes (e.g., split a shape, replace one dimension, concat back).
785    #[test]
786    fn test_split_shape_input() {
787        // Shape(3) = a 3-element shape, like the output of Shape(rank-3 tensor)
788        // Split it with sizes [1, 1, 1] into 3 scalar-like outputs
789        let node = TestNodeBuilder::new(NodeType::Split, "test_split")
790            .input_shape("shape_input", 3)
791            .input_tensor_i64_data("split_sizes", vec![1, 1, 1], vec![3])
792            .output_tensor_i64("output_0", 0, None)
793            .output_tensor_i64("output_1", 0, None)
794            .output_tensor_i64("output_2", 0, None)
795            .build_with_graph_data(16);
796
797        let mut node = node;
798        let processor = SplitProcessor;
799        let prefs = OutputPreferences::new();
800        processor.infer_types(&mut node, 16, &prefs).unwrap();
801
802        // All outputs should be rank-1 I64 tensors with static_shape [1]
803        for output in &node.outputs {
804            match &output.ty {
805                ArgType::Tensor(t) => {
806                    assert_eq!(t.dtype, DType::I64);
807                    assert_eq!(t.rank, 1);
808                    assert_eq!(t.static_shape, Some(vec![Some(1)]));
809                }
810                other => panic!("Expected Tensor, got {:?}", other),
811            }
812        }
813    }
814
815    /// Regression test for #55: Split with zero-sized split parts is valid per ONNX spec.
816    /// Models use [0, N, 0] splits to extract the middle element of a shape.
817    #[test]
818    fn test_split_zero_sized_parts() {
819        let node = TestNodeBuilder::new(NodeType::Split, "test_split")
820            .input_shape("shape_input", 1)
821            .input_tensor_i64_data("split_sizes", vec![0, 1, 0], vec![3])
822            .output_tensor_i64("output_0", 0, None)
823            .output_tensor_i64("output_1", 0, None)
824            .output_tensor_i64("output_2", 0, None)
825            .build_with_graph_data(16);
826
827        let mut node = node;
828        let processor = SplitProcessor;
829        let prefs = OutputPreferences::new();
830        processor.infer_types(&mut node, 16, &prefs).unwrap();
831
832        // Check static shapes: [0], [1], [0]
833        let shapes: Vec<_> = node
834            .outputs
835            .iter()
836            .map(|o| match &o.ty {
837                ArgType::Tensor(t) => t.static_shape.clone(),
838                _ => panic!("Expected Tensor"),
839            })
840            .collect();
841        assert_eq!(
842            shapes,
843            vec![
844                Some(vec![Some(0)]),
845                Some(vec![Some(1)]),
846                Some(vec![Some(0)])
847            ]
848        );
849
850        // extract_config should also succeed (no rejection of size 0)
851        let config = processor.extract_config(&node, 16).unwrap();
852        assert!(matches!(
853            &config.split_sizes,
854            Some(SplitSizesInput::Static(sizes)) if sizes == &vec![0, 1, 0]
855        ));
856    }
857
858    #[test]
859    fn test_split_single_output_is_noop() {
860        let node = create_test_node(3, 1, Some(vec![2, 3, 4]), None, None).build();
861        assert!(SplitProcessor.is_noop(&node));
862    }
863
864    #[test]
865    fn test_split_multiple_outputs_is_not_noop() {
866        let node = create_test_node(3, 2, Some(vec![2, 3, 4]), None, None).build();
867        assert!(!SplitProcessor.is_noop(&node));
868    }
869
870    // TODO: Missing test for split_sizes that don't sum to dimension size.
871    // E.g., shape=[10, 20], axis=0, split=[3, 4] (sum=7) should fail as it doesn't match dim size 10.
872
873    // TODO: Missing test for empty splits - split_sizes=[] or num_outputs=0.
874    // Should be rejected as invalid configuration.
875
876    // TODO: Missing test for single output split - num_outputs=1 or split=[10].
877    // This is valid but not explicitly tested.
878
879    // TODO: Missing test for very uneven splits - e.g., split=[1, 1, 1, 97] for dim size 100.
880    // Verify this edge case works correctly.
881
882    // TODO: Missing test for opset < 13 behavior - split as attribute vs input.
883    // Implementation requires opset 11+ but attribute-based split (opset < 13) might not work.
884
885    #[test]
886    fn test_split_scalar_tensor_input() {
887        // ScalarTensor(F32) as primary input: treated as rank-1 tensor with 1 element
888        let mut node = TestNodeBuilder::new(NodeType::Split, "test_split")
889            .add_input("data", ArgType::ScalarTensor(DType::F32))
890            .output_default("output_0")
891            .build();
892
893        let processor = SplitProcessor;
894        let prefs = OutputPreferences::new();
895        processor.infer_types(&mut node, 16, &prefs).unwrap();
896
897        match &node.outputs[0].ty {
898            ArgType::Tensor(t) => {
899                assert_eq!(t.dtype, DType::F32);
900                assert_eq!(t.rank, 1);
901            }
902            other => panic!("Expected Tensor, got {:?}", other),
903        }
904    }
905
906    /// Regression test for #344: split sizes given as a Shape input.
907    #[test]
908    fn test_split_sizes_as_shape_input() {
909        let node = TestNodeBuilder::new(NodeType::Split, "test_split")
910            .input_tensor_f32("input", 3, Some(vec![10, 20, 30]))
911            .input_shape_with_data("split", vec![3, 7])
912            .output_tensor_f32("output_0", 0, None)
913            .output_tensor_f32("output_1", 0, None)
914            .build_with_graph_data(16);
915
916        let processor = SplitProcessor;
917        let config = processor.extract_config(&node, 16).unwrap();
918
919        assert!(matches!(
920            &config.split_sizes,
921            Some(SplitSizesInput::Static(sizes)) if sizes == &vec![3, 7]
922        ));
923    }
924}