1use derive_new::new;
20use onnx_ir_derive::NodeBuilder;
21
22use crate::ir::{ArgType, Argument, Node, RawNode, RuntimeInputRef, TensorDataExt};
23use crate::processor::{
24 InputSpec, NodeProcessor, NodeSpec, OutputPreferences, OutputSpec, ProcessError,
25};
26
27#[derive(Debug, Clone, new)]
29pub struct SliceConfig {
30 pub starts: SliceInput,
31 pub ends: SliceInput,
32 pub axes: Option<SliceInput>,
33 pub steps: Option<SliceInput>,
34}
35
36#[derive(Debug, Clone, NodeBuilder)]
38pub struct SliceNode {
39 pub name: String,
40 pub inputs: Vec<Argument>,
41 pub outputs: Vec<Argument>,
42 pub config: SliceConfig,
43}
44
45#[derive(Debug, Clone)]
47pub enum SliceInput {
48 Static(Vec<i64>),
50 Runtime(RuntimeInputRef),
52}
53
54impl Default for SliceInput {
55 fn default() -> Self {
56 Self::Static(Vec::new())
57 }
58}
59
60fn normalize_axes(axes: &mut [i64], rank: usize, _node_name: &str) {
62 for axis in axes.iter_mut() {
63 if *axis < 0 {
64 *axis += rank as i64;
65 }
66 }
67}
68
69fn calculate_dim_slice_output_len(start: i64, end: i64, step: i64, dim_size: usize) -> usize {
77 if dim_size == 0 {
78 return 0;
79 }
80 let dim_len = dim_size as i64;
81
82 fn normalize_index(idx: i64, lo: i64, hi: i64, n: i64) -> i64 {
85 let abs = if idx < 0 { idx + n } else { idx };
86 abs.clamp(lo, hi)
87 }
88
89 let (norm_start, norm_end) = if step > 0 {
96 (
97 normalize_index(start, 0, dim_len, dim_len),
98 normalize_index(end, 0, dim_len, dim_len),
99 )
100 } else {
101 (
102 normalize_index(start, -1, dim_len - 1, dim_len),
103 normalize_index(end, -1, dim_len - 1, dim_len),
104 )
105 };
106
107 let range_len = (norm_end - norm_start) * step.signum();
108 if range_len <= 0 {
109 0
110 } else {
111 (range_len as u64).div_ceil(step.unsigned_abs()) as usize
114 }
115}
116
117pub(crate) struct SliceProcessor;
118
119impl NodeProcessor for SliceProcessor {
120 type Config = SliceConfig;
121
122 fn spec(&self) -> NodeSpec {
123 NodeSpec {
124 min_opset: 1,
125 max_opset: None,
126 inputs: InputSpec::AtLeast(1),
127 outputs: OutputSpec::Exact(1),
128 }
129 }
130
131 fn input_preferences(
132 &self,
133 node: &RawNode,
134 _opset: usize,
135 ) -> Result<Option<crate::processor::InputPreferences>, ProcessError> {
136 use crate::processor::{ArgPreference, InputPreferences};
137
138 let mut prefs = InputPreferences::new();
139 for input in node.inputs.iter().skip(1) {
140 prefs = prefs.add(&input.name, ArgPreference::Shape);
142 if input.ty.is_scalar() {
143 prefs = prefs.add(&input.name, ArgPreference::ScalarNative);
144 }
145 }
146
147 Ok(Some(prefs))
148 }
149
150 fn lift_constants(&self, node: &mut RawNode, _opset: usize) -> Result<(), ProcessError> {
151 if node.inputs.len() > 1 && node.inputs[1].is_constant() {
153 node.inputs[1].to_static()?;
154 }
155
156 if node.inputs.len() > 2 && node.inputs[2].is_constant() {
158 node.inputs[2].to_static()?;
159 }
160
161 if node.inputs.len() > 3 && node.inputs[3].is_constant() {
163 node.inputs[3].to_static()?;
164 }
165
166 if node.inputs.len() > 4 && node.inputs[4].is_constant() {
168 node.inputs[4].to_static()?;
169 }
170
171 Ok(())
172 }
173
174 fn infer_types(
175 &self,
176 node: &mut RawNode,
177 opset: usize,
178 _output_preferences: &OutputPreferences,
179 ) -> Result<(), ProcessError> {
180 let config = self.extract_config(node, opset)?;
182
183 let input_ty = node.inputs[0].ty.clone();
185
186 match input_ty {
187 ArgType::Tensor(tensor_type) => {
188 let runtime_bounds = matches!(config.starts, SliceInput::Runtime(_))
199 || matches!(config.ends, SliceInput::Runtime(_));
200 match &config.steps {
201 Some(SliceInput::Runtime(_)) if !runtime_bounds => {
202 return Err(ProcessError::Custom(format!(
203 "Slice with static bounds needs static steps; node {} has a runtime steps input",
204 node.name
205 )));
206 }
207 Some(SliceInput::Static(steps))
208 if runtime_bounds && steps.iter().any(|&s| s != 1) =>
209 {
210 return Err(ProcessError::Custom(format!(
211 "Slice with runtime bounds only supports step=1; node {} has steps={:?}",
212 node.name, steps
213 )));
214 }
215 _ => {}
216 }
217
218 let mut static_shape = tensor_type
221 .static_shape
222 .clone()
223 .unwrap_or_else(|| vec![None; tensor_type.rank]);
224
225 if let (
226 SliceInput::Static(starts),
227 SliceInput::Static(ends),
228 Some(SliceInput::Static(axes)),
229 Some(SliceInput::Static(steps)),
230 ) = (&config.starts, &config.ends, &config.axes, &config.steps)
231 {
232 for (i, &axis) in axes.iter().enumerate() {
233 let axis = axis as usize;
234 if let Some(Some(dim_size)) =
235 tensor_type.static_shape.as_ref().and_then(|s| s.get(axis))
236 {
237 let out_dim = calculate_dim_slice_output_len(
238 starts[i], ends[i], steps[i], *dim_size,
239 );
240 static_shape[axis] = Some(out_dim);
241 }
242 }
243 }
244
245 node.outputs[0].ty = ArgType::Tensor(crate::ir::TensorType {
246 dtype: tensor_type.dtype,
247 rank: tensor_type.rank,
248 static_shape: Some(static_shape),
249 });
250 }
251 ArgType::Shape(shape_rank) => {
252 let static_bounds = match (&config.starts, &config.ends, &config.steps) {
255 (SliceInput::Static(s), SliceInput::Static(e), steps_opt) => {
256 let steps = match steps_opt {
257 Some(SliceInput::Static(st)) => st.clone(),
258 Some(SliceInput::Runtime(_)) => vec![],
259 None => vec![1],
260 };
261 if steps.is_empty() {
262 None
263 } else {
264 Some((s, e, steps))
265 }
266 }
267 _ => None,
268 };
269
270 if let Some((starts, ends, steps)) = static_bounds {
271 if starts.len() != 1 || ends.len() != 1 {
272 return Err(ProcessError::Custom(format!(
273 "Slice on Shape input requires exactly one dimension slice config for node {}",
274 node.name
275 )));
276 }
277
278 let step = if steps.is_empty() { 1 } else { steps[0] };
279 let output_len =
280 calculate_dim_slice_output_len(starts[0], ends[0], step, shape_rank);
281 node.outputs[0].ty = ArgType::Shape(output_len);
282 } else {
283 let len_of = |input: &SliceInput| -> Option<usize> {
286 match input {
287 SliceInput::Static(v) => Some(v.len()),
288 SliceInput::Runtime(r) => {
289 let ty = &node.inputs[r.input_index].ty;
290 match ty {
291 ArgType::ScalarNative(_) | ArgType::ScalarTensor(_) => Some(1),
292 _ => ty.first_dim_static_len(),
293 }
294 }
295 }
296 };
297 let mut any_unknown_len = false;
298 for (which, input) in [("starts", &config.starts), ("ends", &config.ends)] {
299 match len_of(input) {
300 Some(n) if n != 1 => {
301 return Err(ProcessError::Custom(format!(
302 "Slice on Shape input requires single-axis slicing; node {} has {} of length {}",
303 node.name, which, n
304 )));
305 }
306 None => any_unknown_len = true,
307 _ => {}
308 }
309 }
310 if any_unknown_len {
311 log::debug!(
312 "Slice node {}: runtime bound length not statically known; \
313 codegen will assert exactly one element at inference time",
314 node.name
315 );
316 }
317 match &config.steps {
318 Some(SliceInput::Static(steps)) if steps.iter().any(|&s| s != 1) => {
319 return Err(ProcessError::Custom(format!(
320 "Slice on Shape input with runtime bounds only supports step=1; node {} has steps={:?}",
321 node.name, steps
322 )));
323 }
324 Some(SliceInput::Runtime(_)) => {
325 return Err(ProcessError::Custom(format!(
326 "Slice on Shape input with runtime steps is not supported (node {})",
327 node.name
328 )));
329 }
330 _ => {}
331 }
332 node.outputs[0].ty = ArgType::Tensor(crate::ir::TensorType {
333 dtype: crate::ir::DType::I64,
334 rank: 1,
335 static_shape: None,
336 });
337 }
338 }
339 ArgType::ScalarTensor(dtype) => {
340 node.outputs[0].ty = ArgType::Tensor(crate::ir::TensorType {
342 dtype,
343 rank: 1,
344 static_shape: None,
345 });
346 }
347 unsupported_type => {
348 return Err(ProcessError::TypeMismatch {
349 expected: "Tensor, Shape, or ScalarTensor".to_string(),
350 actual: format!("{:?}", unsupported_type),
351 });
352 }
353 }
354
355 Ok(())
356 }
357
358 fn extract_config(&self, node: &RawNode, _opset: usize) -> Result<Self::Config, ProcessError> {
359 if node.inputs.len() < 2 {
361 let starts = node
362 .attrs
363 .get("starts")
364 .map(|v| v.clone().into_i64s().map(SliceInput::Static))
365 .transpose()?
366 .ok_or_else(|| ProcessError::MissingAttribute("starts".to_string()))?;
367 let ends = node
368 .attrs
369 .get("ends")
370 .map(|v| v.clone().into_i64s().map(SliceInput::Static))
371 .transpose()?
372 .ok_or_else(|| ProcessError::MissingAttribute("ends".to_string()))?;
373 let mut axes = node
374 .attrs
375 .get("axes")
376 .map(|v| v.clone().into_i64s().map(SliceInput::Static))
377 .transpose()?;
378
379 if axes.is_none()
381 && let SliceInput::Static(ref starts_vec) = starts
382 {
383 axes = Some(SliceInput::Static((0..starts_vec.len() as i64).collect()));
384 }
385
386 if let Some(SliceInput::Static(ref mut axes_values)) = axes
388 && let ArgType::Tensor(ref tensor_type) = node.inputs[0].ty
389 {
390 normalize_axes(axes_values, tensor_type.rank, &node.name);
391 }
392
393 let steps = if let SliceInput::Static(ref starts_vec) = starts {
395 Some(SliceInput::Static(vec![1; starts_vec.len()]))
396 } else {
397 None
398 };
399
400 return Ok(SliceConfig {
401 starts,
402 ends,
403 axes,
404 steps,
405 });
406 }
407
408 fn get_slice_input(
410 node: &RawNode,
411 index: usize,
412 ) -> Result<Option<SliceInput>, ProcessError> {
413 let input = match node.inputs.get(index) {
414 Some(i) => i,
415 None => return Ok(None),
416 };
417
418 if matches!(input.ty, ArgType::Shape(_)) {
420 match input.value() {
422 Some(tensor_data) => match tensor_data.to_i64_vec() {
423 Ok(vec) => return Ok(Some(SliceInput::Static(vec))),
424 Err(_) => {
425 return Err(ProcessError::Custom(format!(
426 "Slice Shape input at index {} must be int32 or int64",
427 index
428 )));
429 }
430 },
431 None => {
432 return Ok(Some(SliceInput::Runtime(RuntimeInputRef::new(
435 input.name.clone(),
436 index,
437 ))));
438 }
439 }
440 }
441
442 match input.value() {
444 None => {
445 Ok(Some(SliceInput::Runtime(RuntimeInputRef::new(
447 input.name.clone(),
448 index,
449 ))))
450 }
451 Some(tensor_data) => match tensor_data.to_i64_vec() {
452 Ok(vec) => Ok(Some(SliceInput::Static(vec))),
453 Err(_) => Err(ProcessError::Custom(format!(
454 "Slice input at index {} must be int32 or int64",
455 index
456 ))),
457 },
458 }
459 }
460
461 let starts = get_slice_input(node, 1)?
462 .ok_or_else(|| ProcessError::MissingInput("starts".to_string()))?;
463
464 let ends = get_slice_input(node, 2)?
465 .ok_or_else(|| ProcessError::MissingInput("ends".to_string()))?;
466
467 let axes = get_slice_input(node, 3)?;
468 let steps = get_slice_input(node, 4)?;
469
470 let num_slices: Option<usize> = match &starts {
480 SliceInput::Static(v) => Some(v.len()),
481 SliceInput::Runtime(r) => node.inputs[r.input_index].ty.first_dim_static_len(),
482 };
483
484 let (mut axes, steps) = if let Some(n) = num_slices.filter(|n| *n > 0) {
485 let steps = if steps.is_none() {
487 Some(SliceInput::Static(vec![1; n]))
488 } else {
489 steps
490 };
491
492 let axes = if axes.is_none() {
494 Some(SliceInput::Static((0..n as i64).collect()))
495 } else {
496 axes
497 };
498
499 (axes, steps)
500 } else {
501 (axes, steps)
505 };
506
507 if let Some(SliceInput::Static(ref step_values)) = steps
509 && step_values.contains(&0)
510 {
511 return Err(ProcessError::Custom(
512 "Slice: step values cannot be zero".to_string(),
513 ));
514 }
515
516 if let Some(SliceInput::Static(ref mut axes_values)) = axes
525 && let ArgType::Tensor(ref tensor_type) = node.inputs[0].ty
526 {
527 normalize_axes(axes_values, tensor_type.rank, &node.name);
528 }
529
530 let config = SliceConfig {
531 starts,
532 ends,
533 axes,
534 steps,
535 };
536 Ok(config)
537 }
538
539 fn build_node(&self, builder: RawNode, opset: usize) -> Result<Node, ProcessError> {
540 let config = self.extract_config(&builder, opset)?;
541
542 Ok(Node::Slice(SliceNode {
543 name: builder.name,
544 inputs: builder.inputs,
545 outputs: builder.outputs,
546 config,
547 }))
548 }
549}
550
551#[cfg(test)]
552mod tests {
553 use crate::ir::{DType, NodeType};
554 use crate::node::test_utils::TestNodeBuilder;
555
556 use super::*;
557
558 fn create_test_node(
559 starts: Vec<i64>,
560 ends: Vec<i64>,
561 axes: Option<Vec<i64>>,
562 ) -> TestNodeBuilder {
563 let mut builder = TestNodeBuilder::new(NodeType::Slice, "test_slice")
564 .input_tensor_f32("data", 3, None)
565 .output_default("output");
566
567 builder = builder.input_tensor_i64_data("starts", starts.clone(), vec![starts.len()]);
569 builder = builder.input_tensor_i64_data("ends", ends.clone(), vec![ends.len()]);
570
571 if let Some(axes_vec) = axes.clone() {
572 builder = builder.input_tensor_i64_data("axes", axes_vec.clone(), vec![axes_vec.len()]);
573 }
574
575 builder
576 }
577
578 fn create_static_shape_slice_node(
579 static_shape: Vec<Option<usize>>,
580 starts: Vec<i64>,
581 ends: Vec<i64>,
582 axes: Vec<i64>,
583 steps: Vec<i64>,
584 ) -> TestNodeBuilder {
585 TestNodeBuilder::new(NodeType::Slice, "test_tensor_slice")
586 .add_input(
587 "data",
588 ArgType::Tensor(crate::ir::TensorType {
589 dtype: crate::ir::DType::F32,
590 rank: static_shape.len(),
591 static_shape: Some(static_shape),
592 }),
593 )
594 .input_tensor_i64_data("starts", starts.clone(), vec![starts.len()])
595 .input_tensor_i64_data("ends", ends.clone(), vec![ends.len()])
596 .input_tensor_i64_data("axes", axes.clone(), vec![axes.len()])
597 .input_tensor_i64_data("steps", steps.clone(), vec![steps.len()])
598 .output_default("output")
599 }
600
601 fn create_shape_input_node(start: i64, end: i64) -> TestNodeBuilder {
602 TestNodeBuilder::new(NodeType::Slice, "test_slice_shape")
603 .input_shape("data", 5)
604 .input_tensor_i64_data("starts", vec![start], vec![1])
605 .input_tensor_i64_data("ends", vec![end], vec![1])
606 .input_tensor_i64_data("axes", vec![0], vec![1])
607 .output_default("output")
608 }
609
610 fn create_runtime_slice_node() -> TestNodeBuilder {
611 TestNodeBuilder::new(NodeType::Slice, "test_runtime_slice")
612 .input_tensor_f32("data", 2, None)
613 .input_tensor_i64("starts", 0, None) .input_tensor_i64("ends", 0, None) .input_tensor_i64_data("axes", vec![0], vec![1])
616 .input_tensor_i64_data("steps", vec![1], vec![1])
617 .output_default("output")
618 }
619
620 fn create_mixed_slice_node_runtime_start() -> TestNodeBuilder {
621 TestNodeBuilder::new(NodeType::Slice, "test_mixed_slice")
622 .input_tensor_f32("data", 2, None)
623 .input_tensor_i64("starts", 0, None) .input_tensor_i64_data("ends", vec![3], vec![1]) .input_tensor_i64_data("axes", vec![0], vec![1])
626 .input_tensor_i64_data("steps", vec![1], vec![1])
627 .output_default("output")
628 }
629
630 fn create_mixed_slice_node_runtime_end() -> TestNodeBuilder {
631 TestNodeBuilder::new(NodeType::Slice, "test_mixed_slice")
632 .input_tensor_f32("data", 2, None)
633 .input_tensor_i64_data("starts", vec![1], vec![1]) .input_tensor_i64("ends", 0, None) .input_tensor_i64_data("axes", vec![0], vec![1])
636 .input_tensor_i64_data("steps", vec![1], vec![1])
637 .output_default("output")
638 }
639
640 #[test]
641 fn test_slice_config_basic() {
642 let node =
644 create_test_node(vec![1, 0], vec![3, 2], Some(vec![0, 2])).build_with_graph_data(16);
645
646 let mut node = node;
647
648 let processor = SliceProcessor;
649
650 let prefs = OutputPreferences::new();
651 processor.infer_types(&mut node, 16, &prefs).unwrap();
652
653 let result = processor.extract_config(&node, 16).unwrap();
654
655 match (&result.starts, &result.ends) {
657 (SliceInput::Static(starts), SliceInput::Static(ends)) => {
658 assert_eq!(starts, &vec![1, 0]);
659 assert_eq!(ends, &vec![3, 2]);
660 if let Some(SliceInput::Static(axes)) = &result.axes {
662 assert_eq!(axes, &vec![0, 2]);
663 }
664 if let Some(SliceInput::Static(steps)) = &result.steps {
666 assert_eq!(steps, &vec![1, 1]);
667 } else {
668 panic!("Expected steps to have ONNX spec default");
669 }
670 }
671 _ => panic!("Expected static config"),
672 }
673 }
674
675 #[test]
676 fn test_slice_config_negative_axes() {
677 let node = create_test_node(vec![1], vec![3], Some(vec![-3])).build_with_graph_data(16);
679
680 let mut node = node;
681
682 let processor = SliceProcessor;
683
684 let prefs = OutputPreferences::new();
685 processor.infer_types(&mut node, 16, &prefs).unwrap();
686
687 let result = processor.extract_config(&node, 16).unwrap();
688
689 match (&result.starts, &result.ends) {
691 (SliceInput::Static(starts), SliceInput::Static(ends)) => {
692 assert_eq!(starts, &vec![1]);
693 assert_eq!(ends, &vec![3]);
694 if let Some(SliceInput::Static(axes)) = &result.axes {
696 assert_eq!(axes, &vec![0]); }
698 }
699 _ => panic!("Expected static config"),
700 }
701 }
702
703 #[test]
704 fn test_slice_config_default_axes() {
705 let node = create_test_node(vec![1, 2], vec![3, 4], None).build_with_graph_data(16);
707
708 let mut node = node;
709
710 let processor = SliceProcessor;
711
712 let prefs = OutputPreferences::new();
713 processor.infer_types(&mut node, 16, &prefs).unwrap();
714
715 let result = processor.extract_config(&node, 16).unwrap();
716
717 match (&result.starts, &result.ends) {
719 (SliceInput::Static(starts), SliceInput::Static(ends)) => {
720 assert_eq!(starts, &vec![1, 2]);
721 assert_eq!(ends, &vec![3, 4]);
722 if let Some(SliceInput::Static(axes)) = &result.axes {
724 assert_eq!(axes, &vec![0, 1]);
725 } else {
726 panic!("Expected axes to have ONNX spec default");
727 }
728 }
729 _ => panic!("Expected static config"),
730 }
731 }
732
733 #[test]
734 fn test_slice_config_runtime() {
735 let mut node = create_runtime_slice_node().build_with_graph_data(16);
737
738 let processor = SliceProcessor;
739
740 let prefs = OutputPreferences::new();
741 processor.infer_types(&mut node, 16, &prefs).unwrap();
742
743 let result = processor.extract_config(&node, 16).unwrap();
744
745 match (&result.starts, &result.ends) {
747 (SliceInput::Runtime(starts), SliceInput::Runtime(ends)) => {
748 assert_eq!(starts.name, "starts");
749 assert_eq!(ends.name, "ends");
750 assert!(
752 matches!(&result.axes, Some(SliceInput::Static(axes)) if axes == &vec![0]),
753 "expected static axes, got {:?}",
754 result.axes
755 );
756 assert!(
757 matches!(&result.steps, Some(SliceInput::Static(steps)) if steps == &vec![1]),
758 "expected static steps, got {:?}",
759 result.steps
760 );
761 }
762 _ => panic!("Expected runtime config"),
763 }
764 }
765
766 #[test]
767 fn test_slice_update_output_rank_tensor_input() {
768 let mut node = create_test_node(vec![1, 2], vec![3, 4], None).build_with_graph_data(16);
770
771 assert!(matches!(node.inputs[0].ty, ArgType::Tensor(_)));
773 assert!(matches!(node.outputs[0].ty, ArgType::Tensor(_)));
774
775 let processor = SliceProcessor;
776 let prefs = OutputPreferences::new();
777 processor.infer_types(&mut node, 16, &prefs).unwrap();
778
779 assert!(
781 matches!(&node.outputs[0].ty, ArgType::Tensor(tensor_type) if tensor_type.dtype == DType::F32 && tensor_type.rank == 3)
782 );
783 }
784
785 #[test]
786 fn test_slice_update_output_rank_shape_input() {
787 let mut node = create_shape_input_node(1, 3).build_with_graph_data(16);
789
790 assert!(matches!(node.inputs[0].ty, ArgType::Shape(5)));
792 assert!(matches!(node.outputs[0].ty, ArgType::Tensor(ref t) if t.rank == 0));
794
795 let processor = SliceProcessor;
796 let prefs = OutputPreferences::new();
797 processor.infer_types(&mut node, 16, &prefs).unwrap();
798
799 assert!(matches!(&node.outputs[0].ty, ArgType::Shape(2)));
802 }
803
804 #[test]
805 fn test_slice_shape_input_runtime_bounds_degrades_to_tensor() {
806 let mut node = TestNodeBuilder::new(NodeType::Slice, "test_slice_shape_runtime")
809 .input_shape("data", 5)
810 .input_tensor_i64("starts", 1, None)
811 .input_tensor_i64("ends", 1, None)
812 .output_default("output")
813 .build_with_graph_data(16);
814
815 let processor = SliceProcessor;
816 let prefs = OutputPreferences::new();
817 processor.infer_types(&mut node, 16, &prefs).unwrap();
818
819 match &node.outputs[0].ty {
820 ArgType::Tensor(t) => {
821 assert_eq!(t.dtype, DType::I64);
822 assert_eq!(t.rank, 1);
823 assert!(t.static_shape.is_none());
824 }
825 other => panic!("Expected Tensor output, got {:?}", other),
826 }
827 }
828
829 #[test]
830 fn test_slice_shape_input_runtime_bounds_length_gt_1_rejected() {
831 let mut node = TestNodeBuilder::new(NodeType::Slice, "shape_runtime_len2")
835 .input_shape("data", 5)
836 .input_tensor_i64("starts", 1, Some(vec![2]))
837 .input_tensor_i64("ends", 1, Some(vec![2]))
838 .output_default("output")
839 .build_with_graph_data(16);
840
841 let processor = SliceProcessor;
842 let prefs = OutputPreferences::new();
843 let result = processor.infer_types(&mut node, 16, &prefs);
844 assert!(matches!(result, Err(ProcessError::Custom(ref m)) if m.contains("single-axis")));
845 }
846
847 #[test]
848 fn test_slice_tensor_runtime_bounds_non_unit_step_rejected() {
849 for step in [-1, 2] {
853 let mut node = TestNodeBuilder::new(NodeType::Slice, "tensor_runtime_step")
854 .input_tensor_f32("data", 2, None)
855 .input_tensor_i64("starts", 1, None)
856 .input_tensor_i64("ends", 1, None)
857 .input_tensor_i64_data("axes", vec![0], vec![1])
858 .input_tensor_i64_data("steps", vec![step], vec![1])
859 .output_default("output")
860 .build_with_graph_data(16);
861
862 let processor = SliceProcessor;
863 let result = processor.infer_types(&mut node, 16, &OutputPreferences::new());
864 assert!(
865 matches!(result, Err(ProcessError::Custom(ref m)) if m.contains("step=1")),
866 "step {step} should be rejected, got {result:?}"
867 );
868 }
869 }
870
871 #[test]
872 fn test_slice_tensor_runtime_steps_with_static_bounds_rejected() {
873 let mut node = TestNodeBuilder::new(NodeType::Slice, "tensor_runtime_steps")
876 .input_tensor_f32("data", 2, None)
877 .input_tensor_i64_data("starts", vec![0], vec![1])
878 .input_tensor_i64_data("ends", vec![2], vec![1])
879 .input_tensor_i64_data("axes", vec![0], vec![1])
880 .input_tensor_i64("steps", 1, None)
881 .output_default("output")
882 .build_with_graph_data(16);
883
884 let processor = SliceProcessor;
885 let result = processor.infer_types(&mut node, 16, &OutputPreferences::new());
886 assert!(
887 matches!(result, Err(ProcessError::Custom(ref m)) if m.contains("static steps")),
888 "runtime steps with static bounds should be rejected, got {result:?}"
889 );
890 }
891
892 #[test]
893 fn test_slice_tensor_all_runtime_allowed() {
894 let mut node = TestNodeBuilder::new(NodeType::Slice, "tensor_all_runtime")
898 .input_tensor_f32("data", 2, None)
899 .input_tensor_i64("starts", 1, None)
900 .input_tensor_i64("ends", 1, None)
901 .input_tensor_i64("axes", 1, None)
902 .input_tensor_i64("steps", 1, None)
903 .output_default("output")
904 .build_with_graph_data(16);
905
906 let processor = SliceProcessor;
907 processor
908 .infer_types(&mut node, 16, &OutputPreferences::new())
909 .expect("fully runtime Slice params must still import");
910 }
911
912 #[test]
913 fn test_slice_tensor_runtime_bounds_unit_step_allowed() {
914 let mut node = TestNodeBuilder::new(NodeType::Slice, "tensor_runtime_step1")
916 .input_tensor_f32("data", 2, None)
917 .input_tensor_i64("starts", 1, None)
918 .input_tensor_i64("ends", 1, None)
919 .input_tensor_i64_data("axes", vec![0], vec![1])
920 .input_tensor_i64_data("steps", vec![1], vec![1])
921 .output_default("output")
922 .build_with_graph_data(16);
923
924 let processor = SliceProcessor;
925 processor
926 .infer_types(&mut node, 16, &OutputPreferences::new())
927 .expect("runtime bounds with step=1 are supported");
928 }
929
930 #[test]
931 fn test_slice_shape_input_runtime_bounds_step_2_rejected() {
932 let mut node = TestNodeBuilder::new(NodeType::Slice, "shape_runtime_step2")
935 .input_shape("data", 5)
936 .input_tensor_i64("starts", 1, None)
937 .input_tensor_i64("ends", 1, None)
938 .input_tensor_i64_data("axes", vec![0], vec![1])
939 .input_tensor_i64_data("steps", vec![2], vec![1])
940 .output_default("output")
941 .build_with_graph_data(16);
942
943 let processor = SliceProcessor;
944 let prefs = OutputPreferences::new();
945 let result = processor.infer_types(&mut node, 16, &prefs);
946 assert!(matches!(result, Err(ProcessError::Custom(ref m)) if m.contains("step=1")));
947 }
948
949 #[test]
950 fn test_slice_config_mixed_runtime_start() {
951 let node = create_mixed_slice_node_runtime_start().build_with_graph_data(16);
953
954 let mut node = node;
955
956 let processor = SliceProcessor;
957
958 let prefs = OutputPreferences::new();
959 processor.infer_types(&mut node, 16, &prefs).unwrap();
960
961 let result = processor.extract_config(&node, 16).unwrap();
962
963 match (&result.starts, &result.ends) {
965 (SliceInput::Runtime(starts), SliceInput::Static(ends)) => {
966 assert_eq!(starts.name, "starts");
967 assert_eq!(ends, &vec![3]);
968 }
969 _ => panic!("Expected mixed config with runtime start and static end"),
970 }
971 }
972
973 #[test]
974 fn test_slice_config_mixed_runtime_end() {
975 let node = create_mixed_slice_node_runtime_end().build_with_graph_data(16);
977
978 let mut node = node;
979
980 let processor = SliceProcessor;
981
982 let prefs = OutputPreferences::new();
983 processor.infer_types(&mut node, 16, &prefs).unwrap();
984
985 let result = processor.extract_config(&node, 16).unwrap();
986
987 match (&result.starts, &result.ends) {
989 (SliceInput::Static(starts), SliceInput::Runtime(ends)) => {
990 assert_eq!(starts, &vec![1]);
991 assert_eq!(ends.name, "ends");
992 }
993 _ => panic!("Expected mixed config with static start and runtime end"),
994 }
995 }
996
997 #[test]
998 fn test_slice_config_with_steps() {
999 let builder = TestNodeBuilder::new(NodeType::Slice, "test_slice_with_steps")
1001 .input_tensor_f32("data", 3, None)
1002 .input_tensor_i64_data("starts", vec![0, 0], vec![2])
1003 .input_tensor_i64_data("ends", vec![10, 10], vec![2])
1004 .input_tensor_i64_data("axes", vec![0, 1], vec![2])
1005 .input_tensor_i64_data("steps", vec![2, 3], vec![2])
1006 .output_default("output");
1007
1008 let node = builder.build_with_graph_data(16);
1009 let mut node = node;
1010
1011 let processor = SliceProcessor;
1012
1013 let prefs = OutputPreferences::new();
1014 processor.infer_types(&mut node, 16, &prefs).unwrap();
1015
1016 let result = processor.extract_config(&node, 16).unwrap();
1017
1018 match (&result.starts, &result.ends, &result.steps) {
1020 (
1021 SliceInput::Static(starts),
1022 SliceInput::Static(ends),
1023 Some(SliceInput::Static(steps)),
1024 ) => {
1025 assert_eq!(starts, &vec![0, 0]);
1026 assert_eq!(ends, &vec![10, 10]);
1027 assert_eq!(steps, &vec![2, 3]);
1028 }
1029 _ => panic!("Expected static config with steps"),
1030 }
1031 }
1032
1033 #[test]
1034 fn test_slice_config_zero_step() {
1035 let builder = TestNodeBuilder::new(NodeType::Slice, "test_zero_step")
1037 .input_tensor_f32("data", 2, None)
1038 .input_tensor_i64_data("starts", vec![0], vec![1])
1039 .input_tensor_i64_data("ends", vec![10], vec![1])
1040 .input_tensor_i64_data("axes", vec![0], vec![1])
1041 .input_tensor_i64_data("steps", vec![0], vec![1])
1042 .output_default("output");
1043
1044 let node = builder.build_with_graph_data(16);
1045 let node = node;
1046
1047 let processor = SliceProcessor;
1048
1049 let result = processor.extract_config(&node, 16);
1050 assert!(matches!(result, Err(ProcessError::Custom(_))));
1051 }
1052
1053 #[test]
1054 fn test_slice_config_negative_steps() {
1055 let builder = TestNodeBuilder::new(NodeType::Slice, "test_negative_steps")
1057 .input_tensor_f32("data", 2, None)
1058 .input_tensor_i64_data("starts", vec![0, 2], vec![2])
1059 .input_tensor_i64_data("ends", vec![10, 8], vec![2])
1060 .input_tensor_i64_data("axes", vec![0, 1], vec![2])
1061 .input_tensor_i64_data("steps", vec![-1, -2], vec![2])
1062 .output_default("output");
1063
1064 let node = builder.build_with_graph_data(16);
1065 let mut node = node;
1066
1067 let processor = SliceProcessor;
1068
1069 let prefs = OutputPreferences::new();
1070 processor.infer_types(&mut node, 16, &prefs).unwrap();
1071
1072 let result = processor.extract_config(&node, 16).unwrap();
1073
1074 match &result.steps {
1076 Some(SliceInput::Static(steps)) => {
1077 assert_eq!(steps, &vec![-1, -2]);
1078 }
1079 _ => panic!("Expected static steps with negative values"),
1080 }
1081 }
1082
1083 #[test]
1084 fn test_tensor_static_shape_known_dim_filled() {
1085 let mut node = create_static_shape_slice_node(
1087 vec![Some(10), Some(20)],
1088 vec![2],
1089 vec![7],
1090 vec![0],
1091 vec![1],
1092 )
1093 .build_with_graph_data(16);
1094
1095 let processor = SliceProcessor;
1096 processor
1097 .infer_types(&mut node, 16, &OutputPreferences::new())
1098 .unwrap();
1099
1100 match &node.outputs[0].ty {
1101 ArgType::Tensor(tensor_type) => {
1102 let shape = tensor_type.static_shape.as_ref().unwrap();
1103 assert_eq!(shape[0], Some(5));
1104 assert_eq!(shape[1], Some(20));
1105 }
1106 other => panic!("Expected tensor, got {:?}", other),
1107 }
1108 }
1109
1110 #[test]
1111 fn test_tensor_static_shape_multi_axis_partial_known() {
1112 let mut node = create_static_shape_slice_node(
1115 vec![Some(10), Some(5), Some(12)],
1116 vec![1, 0],
1117 vec![6, 12],
1118 vec![0, 2],
1119 vec![1, 2],
1120 )
1121 .build_with_graph_data(16);
1122
1123 let processor = SliceProcessor;
1124 processor
1125 .infer_types(&mut node, 16, &OutputPreferences::new())
1126 .unwrap();
1127
1128 match &node.outputs[0].ty {
1129 ArgType::Tensor(tensor_type) => {
1130 let shape = tensor_type.static_shape.as_ref().unwrap();
1131 assert_eq!(shape[0], Some(5));
1132 assert_eq!(shape[1], Some(5));
1133 assert_eq!(shape[2], Some(6));
1134 }
1135 other => panic!("Expected tensor, got {:?}", other),
1136 }
1137 }
1138
1139 #[test]
1140 fn test_tensor_static_shape_runtime_inputs_all_none() {
1141 let mut node = create_runtime_slice_node().build_with_graph_data(16);
1143
1144 let processor = SliceProcessor;
1145 processor
1146 .infer_types(&mut node, 16, &OutputPreferences::new())
1147 .unwrap();
1148
1149 match &node.outputs[0].ty {
1150 ArgType::Tensor(tensor_type) => match &tensor_type.static_shape {
1151 Some(shape) => {
1152 assert_eq!(shape.len(), 2);
1153 assert!(shape.iter().all(|d| d.is_none()));
1154 }
1155 None => panic!("Expect tensor static shape"),
1156 },
1157 other => panic!("Expected tensor, got {:?}", other),
1158 }
1159 }
1160
1161 #[test]
1162 fn test_dim_slice_output_len_sentinels_and_extreme_steps() {
1163 assert_eq!(calculate_dim_slice_output_len(7, i64::MIN, -1, 8), 8);
1167 assert_eq!(calculate_dim_slice_output_len(-1, i64::MIN, -1, 8), 8);
1168 assert_eq!(calculate_dim_slice_output_len(7, i64::MIN, -3, 8), 3);
1169
1170 assert_eq!(calculate_dim_slice_output_len(3, i64::MAX, 1, 8), 5);
1172
1173 assert_eq!(calculate_dim_slice_output_len(3, i64::MIN, 1, 8), 0);
1175 assert_eq!(calculate_dim_slice_output_len(3, i64::MAX, -1, 8), 0);
1176
1177 assert_eq!(calculate_dim_slice_output_len(-100, i64::MIN, -1, 5), 0);
1181 assert_eq!(calculate_dim_slice_output_len(-6, i64::MIN, -1, 5), 0);
1182 assert_eq!(calculate_dim_slice_output_len(-5, i64::MIN, -1, 5), 1);
1183 assert_eq!(calculate_dim_slice_output_len(99, i64::MIN, -1, 5), 5);
1184
1185 assert_eq!(calculate_dim_slice_output_len(0, 10, i64::MAX, 10), 1);
1188 assert_eq!(calculate_dim_slice_output_len(9, 0, i64::MIN, 10), 1);
1189 }
1190
1191 #[test]
1192 fn test_tensor_static_shape_end_i64_max_slices_to_end() {
1193 let mut node = create_static_shape_slice_node(
1195 vec![Some(8)],
1196 vec![3],
1197 vec![i64::MAX],
1198 vec![0],
1199 vec![1],
1200 )
1201 .build_with_graph_data(16);
1202
1203 let processor = SliceProcessor;
1204 processor
1205 .infer_types(&mut node, 16, &OutputPreferences::new())
1206 .unwrap();
1207
1208 match &node.outputs[0].ty {
1209 ArgType::Tensor(t) => {
1210 let shape = t.static_shape.as_ref().unwrap();
1211 assert_eq!(shape[0], Some(5));
1212 }
1213 other => panic!("Expected tensor, got {:?}", other),
1214 }
1215 }
1216
1217 #[test]
1218 fn test_tensor_static_shape_end_i64_min_slices_to_start() {
1219 let mut node = create_static_shape_slice_node(
1221 vec![Some(8)],
1222 vec![7],
1223 vec![i64::MIN],
1224 vec![0],
1225 vec![-1],
1226 )
1227 .build_with_graph_data(16);
1228
1229 let processor = SliceProcessor;
1230 processor
1231 .infer_types(&mut node, 16, &OutputPreferences::new())
1232 .unwrap();
1233
1234 match &node.outputs[0].ty {
1235 ArgType::Tensor(t) => {
1236 let shape = t.static_shape.as_ref().unwrap();
1237 assert_eq!(shape[0], Some(8));
1238 }
1239 other => panic!("Expected tensor, got {:?}", other),
1240 }
1241 }
1242
1243 #[test]
1244 fn test_tensor_static_shape_negative_step_typical() {
1245 let mut node =
1247 create_static_shape_slice_node(vec![Some(10)], vec![7], vec![2], vec![0], vec![-1])
1248 .build_with_graph_data(16);
1249
1250 let processor = SliceProcessor;
1251 processor
1252 .infer_types(&mut node, 16, &OutputPreferences::new())
1253 .unwrap();
1254
1255 match &node.outputs[0].ty {
1256 ArgType::Tensor(t) => assert_eq!(t.static_shape.as_ref().unwrap()[0], Some(5)),
1257 other => panic!("Expected tensor, got {:?}", other),
1258 }
1259 }
1260
1261 #[test]
1262 fn test_tensor_static_shape_negative_indices() {
1263 let mut node =
1265 create_static_shape_slice_node(vec![Some(10)], vec![-3], vec![-1], vec![0], vec![1])
1266 .build_with_graph_data(16);
1267
1268 let processor = SliceProcessor;
1269 processor
1270 .infer_types(&mut node, 16, &OutputPreferences::new())
1271 .unwrap();
1272
1273 match &node.outputs[0].ty {
1274 ArgType::Tensor(t) => assert_eq!(t.static_shape.as_ref().unwrap()[0], Some(2)),
1275 other => panic!("Expected tensor, got {:?}", other),
1276 }
1277 }
1278
1279 #[test]
1280 fn test_tensor_static_shape_empty_slice() {
1281 let mut node =
1283 create_static_shape_slice_node(vec![Some(10)], vec![5], vec![5], vec![0], vec![1])
1284 .build_with_graph_data(16);
1285
1286 let processor = SliceProcessor;
1287 processor
1288 .infer_types(&mut node, 16, &OutputPreferences::new())
1289 .unwrap();
1290
1291 match &node.outputs[0].ty {
1292 ArgType::Tensor(t) => assert_eq!(t.static_shape.as_ref().unwrap()[0], Some(0)),
1293 other => panic!("Expected tensor, got {:?}", other),
1294 }
1295 }
1296
1297 #[test]
1298 fn test_tensor_static_shape_partial_known_preserves_none() {
1299 let mut node = create_static_shape_slice_node(
1301 vec![Some(10), None, Some(8)],
1302 vec![1],
1303 vec![6],
1304 vec![0],
1305 vec![1],
1306 )
1307 .build_with_graph_data(16);
1308
1309 let processor = SliceProcessor;
1310 processor
1311 .infer_types(&mut node, 16, &OutputPreferences::new())
1312 .unwrap();
1313
1314 match &node.outputs[0].ty {
1315 ArgType::Tensor(t) => {
1316 let shape = t.static_shape.as_ref().unwrap();
1317 assert_eq!(shape, &vec![Some(5), None, Some(8)]);
1318 }
1319 other => panic!("Expected tensor, got {:?}", other),
1320 }
1321 }
1322
1323 #[test]
1324 fn test_tensor_no_static_shape_yields_all_none() {
1325 let mut node = create_test_node(vec![1], vec![5], Some(vec![0])).build_with_graph_data(16);
1327
1328 let processor = SliceProcessor;
1329 processor
1330 .infer_types(&mut node, 16, &OutputPreferences::new())
1331 .unwrap();
1332
1333 match &node.outputs[0].ty {
1334 ArgType::Tensor(t) => {
1335 let shape = t.static_shape.as_ref().unwrap();
1336 assert_eq!(shape, &vec![None, None, None]);
1337 }
1338 other => panic!("Expected tensor, got {:?}", other),
1339 }
1340 }
1341
1342 #[test]
1343 fn test_shape_input_negative_step() {
1344 let mut node = TestNodeBuilder::new(NodeType::Slice, "test_shape_neg_step")
1347 .input_shape("data", 5)
1348 .input_tensor_i64_data("starts", vec![4], vec![1])
1349 .input_tensor_i64_data("ends", vec![1], vec![1])
1350 .input_tensor_i64_data("axes", vec![0], vec![1])
1351 .input_tensor_i64_data("steps", vec![-1], vec![1])
1352 .output_default("output")
1353 .build_with_graph_data(16);
1354
1355 let processor = SliceProcessor;
1356 processor
1357 .infer_types(&mut node, 16, &OutputPreferences::new())
1358 .unwrap();
1359
1360 assert!(matches!(&node.outputs[0].ty, ArgType::Shape(3)));
1361 }
1362
1363 #[test]
1373 fn test_slice_scalar_tensor_input() {
1374 let mut node = TestNodeBuilder::new(NodeType::Slice, "test_slice")
1376 .add_input("data", ArgType::ScalarTensor(DType::I64))
1377 .input_tensor_i64_data("starts", vec![0], vec![1])
1378 .input_tensor_i64_data("ends", vec![1], vec![1])
1379 .output_default("output")
1380 .build_with_graph_data(16);
1381
1382 let processor = SliceProcessor;
1383 let prefs = OutputPreferences::new();
1384 processor.infer_types(&mut node, 16, &prefs).unwrap();
1385
1386 match &node.outputs[0].ty {
1387 ArgType::Tensor(t) => {
1388 assert_eq!(t.dtype, DType::I64);
1389 assert_eq!(t.rank, 1);
1390 }
1391 other => panic!("Expected Tensor, got {:?}", other),
1392 }
1393 }
1394}