1use std::fmt;
15
16use crate::ir::{ArgType, AttributeValue, RawNode};
17use crate::processor::ProcessError;
18
19#[derive(Debug, Clone, PartialEq, Eq, Default)]
24pub enum AutoPad {
25 #[default]
27 NotSet,
28 SameUpper,
30 SameLower,
32 Valid,
34}
35
36impl AutoPad {
37 pub fn parse(s: &str) -> Result<Self, ProcessError> {
39 match s {
40 "NOTSET" => Ok(AutoPad::NotSet),
41 "SAME_UPPER" => Ok(AutoPad::SameUpper),
42 "SAME_LOWER" => Ok(AutoPad::SameLower),
43 "VALID" => Ok(AutoPad::Valid),
44 _ => Err(ProcessError::InvalidAttribute {
45 name: "auto_pad".to_string(),
46 reason: format!("Unknown auto_pad value: {s}"),
47 }),
48 }
49 }
50}
51
52impl fmt::Display for AutoPad {
53 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54 match self {
55 AutoPad::NotSet => write!(f, "NOTSET"),
56 AutoPad::SameUpper => write!(f, "SAME_UPPER"),
57 AutoPad::SameLower => write!(f, "SAME_LOWER"),
58 AutoPad::Valid => write!(f, "VALID"),
59 }
60 }
61}
62
63pub fn static_spatial_dims(ty: &ArgType) -> Option<Vec<usize>> {
68 ty.static_shape()?.get(2..)?.iter().copied().collect()
69}
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub enum SameBlocker {
77 SameLower,
79 Dilated,
81 ThreeSpatialDims,
83}
84
85impl fmt::Display for SameBlocker {
86 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87 match self {
88 SameBlocker::SameLower => write!(
89 f,
90 "SAME_LOWER puts the extra pad at the start of the dimension, while padding \
91 computed at forward time puts it at the end"
92 ),
93 SameBlocker::Dilated => {
94 write!(
95 f,
96 "padding computed at forward time does not account for dilation"
97 )
98 }
99 SameBlocker::ThreeSpatialDims => write!(
100 f,
101 "padding computed at forward time is symmetric-only over 3 spatial dimensions"
102 ),
103 }
104 }
105}
106
107pub fn forward_time_same_blocker(
126 auto_pad: &AutoPad,
127 dilated: bool,
128 spatial_rank: usize,
129) -> Option<SameBlocker> {
130 if *auto_pad == AutoPad::SameLower {
131 Some(SameBlocker::SameLower)
132 } else if dilated {
133 Some(SameBlocker::Dilated)
134 } else if spatial_rank > 2 {
135 Some(SameBlocker::ThreeSpatialDims)
136 } else {
137 None
138 }
139}
140
141pub(crate) fn validate_auto_pad(node: &RawNode) -> Result<(), ProcessError> {
148 let auto_pad = match node.attrs.get("auto_pad") {
149 None => return Ok(()),
150 Some(AttributeValue::String(value)) => AutoPad::parse(value)?,
151 Some(other) => {
152 return Err(ProcessError::InvalidAttribute {
153 name: "auto_pad".to_string(),
154 reason: format!("expected a string, got {other:?}"),
155 });
156 }
157 };
158
159 let input = &node.inputs[0].ty;
160 if !matches!(auto_pad, AutoPad::SameUpper | AutoPad::SameLower)
161 || static_spatial_dims(input).is_some()
162 {
163 return Ok(());
164 }
165
166 let dilated = match node.attrs.get("dilations") {
167 None => false,
168 Some(AttributeValue::Int64s(dilations)) => dilations.iter().any(|&d| d != 1),
169 Some(other) => {
170 return Err(ProcessError::InvalidAttribute {
171 name: "dilations".to_string(),
172 reason: format!("expected a list of ints, got {other:?}"),
173 });
174 }
175 };
176
177 match forward_time_same_blocker(&auto_pad, dilated, input.rank().saturating_sub(2)) {
178 None => Ok(()),
179 Some(blocker) => Err(ProcessError::InvalidAttribute {
180 name: "auto_pad".to_string(),
181 reason: format!(
182 "{auto_pad} needs the input spatial dimensions, but they are dynamic, and the \
183 padding cannot be deferred to forward time either: {blocker}. Re-export the \
184 model with a static input shape, or with explicit pads."
185 ),
186 }),
187 }
188}
189
190pub(crate) fn conv_transpose_ints(
192 name: &str,
193 values: &[i64],
194 min: i64,
195) -> Result<Vec<usize>, ProcessError> {
196 if values.iter().any(|&value| value < min) {
197 return Err(ProcessError::InvalidAttribute {
198 name: name.to_string(),
199 reason: format!("values must be at least {min}, got {values:?}"),
200 });
201 }
202 Ok(values.iter().map(|&value| value as usize).collect())
203}
204
205pub(crate) fn conv_transpose_output_shape(
207 output_shape: &[i64],
208 spatial_rank: usize,
209) -> Result<Vec<usize>, ProcessError> {
210 if output_shape.len() != spatial_rank {
211 return Err(ProcessError::InvalidAttribute {
212 name: "output_shape".to_string(),
213 reason: format!("expected {spatial_rank} spatial dimensions, got {output_shape:?}"),
214 });
215 }
216 conv_transpose_ints("output_shape", output_shape, 0)
217}
218
219pub(crate) fn validate_conv_transpose_pads(
225 node: &RawNode,
226 auto_pad: &AutoPad,
227 has_output_shape: bool,
228) -> Result<(), ProcessError> {
229 let derived = matches!(auto_pad, AutoPad::SameUpper | AutoPad::SameLower);
230 if !derived && !has_output_shape {
231 return Ok(());
232 }
233 let source = if has_output_shape {
234 "output_shape".to_string()
235 } else {
236 format!("auto_pad {auto_pad}")
237 };
238 match static_spatial_dims(&node.inputs[0].ty) {
239 Some(dims) if !dims.contains(&0) => Ok(()),
240 Some(dims) => Err(ProcessError::Custom(format!(
241 "ConvTranspose pads from {source} need non-empty input spatial dimensions, got {dims:?}"
242 ))),
243 None => Err(ProcessError::Custom(format!(
244 "ConvTranspose pads from {source} need the input spatial dimensions, but they are \
245 dynamic. Re-export the model with a static input shape, or with explicit pads."
246 ))),
247 }
248}
249
250pub(crate) fn pool_output_type(node: &mut RawNode) -> Result<(), ProcessError> {
258 let tensor = match &node.inputs[0].ty {
259 ArgType::Tensor(tensor) => tensor.clone(),
260 other => {
261 return Err(ProcessError::TypeMismatch {
262 expected: "Tensor".to_string(),
263 actual: format!("{other:?}"),
264 });
265 }
266 };
267 let ints = |name: &str| match node.attrs.get(name) {
268 Some(AttributeValue::Int64s(values)) => Some(values.clone()),
269 _ => None,
270 };
271 let kernel = ints("kernel_shape");
272 let strides = ints("strides");
273 let pads = ints("pads");
274 let dilations = ints("dilations");
275 let ceil_mode = match node.attrs.get("ceil_mode") {
277 None | Some(AttributeValue::Int64(0)) => Some(false),
278 Some(AttributeValue::Int64(1)) => Some(true),
279 _ => None,
280 };
281 let auto_pad = match node.attrs.get("auto_pad") {
282 Some(AttributeValue::String(value)) => AutoPad::parse(value)?,
283 _ => AutoPad::NotSet,
284 };
285
286 let spatial_rank = tensor.rank.saturating_sub(2);
287 let spatial_size = |axis: usize, input: usize| -> Option<usize> {
288 let at = |values: &Option<Vec<i64>>, index: usize, default: i64| match values {
289 Some(values) => values.get(index).copied(),
290 None => Some(default),
291 };
292 let input = input as i64;
293 let kernel = kernel.as_ref()?.get(axis).copied()?;
294 let stride = at(&strides, axis, 1)?;
295 let dilation = at(&dilations, axis, 1)?;
296 if kernel < 1 || stride < 1 || dilation < 1 {
297 return None;
298 }
299 if matches!(auto_pad, AutoPad::SameUpper | AutoPad::SameLower) {
302 return usize::try_from((input + stride - 1) / stride).ok();
303 }
304 let (pad_begin, pad_end) = match auto_pad {
305 AutoPad::Valid => (0, 0),
306 _ => (at(&pads, axis, 0)?, at(&pads, axis + spatial_rank, 0)?),
307 };
308 let span = input + pad_begin + pad_end - ((kernel - 1) * dilation + 1);
309 let size = if ceil_mode? {
310 let size = (span + stride - 1).div_euclid(stride) + 1;
311 if (size - 1) * stride >= input + pad_begin {
312 size - 1
313 } else {
314 size
315 }
316 } else {
317 span.div_euclid(stride) + 1
318 };
319 usize::try_from(size).ok().filter(|&size| size > 0)
320 };
321
322 let static_shape = tensor.static_shape.as_ref().map(|shape| {
323 shape
324 .iter()
325 .enumerate()
326 .map(|(axis, &dim)| match axis {
327 0 | 1 => dim,
328 _ => dim.and_then(|input| spatial_size(axis - 2, input)),
329 })
330 .collect()
331 });
332
333 node.outputs[0].ty = ArgType::Tensor(crate::ir::TensorType {
334 dtype: tensor.dtype,
335 rank: tensor.rank,
336 static_shape,
337 });
338 Ok(())
339}
340
341pub(crate) struct ConvTransposeDims<'a> {
343 pub kernel: &'a [usize],
344 pub stride: &'a [usize],
345 pub dilation: &'a [usize],
346 pub padding: &'a [usize],
348 pub output_padding: &'a [usize],
349 pub groups: usize,
350 pub auto_pad: &'a AutoPad,
351 pub output_shape: Option<&'a [usize]>,
352}
353
354pub(crate) fn conv_transpose_output_type(
361 node: &mut RawNode,
362 dims: ConvTransposeDims<'_>,
363) -> Result<(), ProcessError> {
364 let tensor = match &node.inputs[0].ty {
365 ArgType::Tensor(tensor) => tensor.clone(),
366 other => {
367 return Err(ProcessError::TypeMismatch {
368 expected: "Tensor".to_string(),
369 actual: format!("{other:?}"),
370 });
371 }
372 };
373 let input_dim = |axis: usize| {
374 tensor
375 .static_shape
376 .as_ref()
377 .and_then(|shape| shape.get(axis).copied().flatten())
378 };
379 let out_channels = known_weight_shape(&node.inputs[1])
380 .and_then(|shape| shape.get(1).map(|per_group| per_group * dims.groups));
381
382 let mut static_shape = vec![input_dim(0), out_channels];
383 for axis in 0..dims.kernel.len() {
384 let size = match dims.output_shape {
385 Some(shape) => Some(shape[axis]),
386 None => input_dim(axis + 2).map(|input| match dims.auto_pad {
387 AutoPad::SameUpper | AutoPad::SameLower => input * dims.stride[axis],
388 _ => {
389 let pads = match dims.auto_pad {
390 AutoPad::Valid => 0,
391 _ => 2 * dims.padding[axis],
392 };
393 (dims.stride[axis] * input.saturating_sub(1)
394 + dims.output_padding[axis]
395 + (dims.kernel[axis] - 1) * dims.dilation[axis]
396 + 1)
397 .saturating_sub(pads)
398 }
399 }),
400 };
401 static_shape.push(size);
402 }
403
404 node.outputs[0].ty = ArgType::Tensor(crate::ir::TensorType {
405 dtype: tensor.dtype,
406 rank: tensor.rank,
407 static_shape: Some(static_shape),
408 });
409 Ok(())
410}
411
412#[derive(Debug, Clone, PartialEq, Eq, Default)]
414pub enum PaddingConfig1d {
415 #[default]
417 Valid,
418 Explicit(usize, usize),
422}
423
424impl fmt::Display for PaddingConfig1d {
425 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
426 match self {
427 PaddingConfig1d::Valid => write!(f, "Valid"),
428 PaddingConfig1d::Explicit(left, right) => write!(f, "Explicit({left}, {right})"),
429 }
430 }
431}
432
433impl PaddingConfig1d {
434 pub fn is_asymmetric(&self) -> bool {
436 match self {
437 PaddingConfig1d::Explicit(left, right) => left != right,
438 _ => false,
439 }
440 }
441
442 pub fn as_tuple(&self) -> (usize, usize) {
444 match self {
445 PaddingConfig1d::Valid => (0, 0),
446 PaddingConfig1d::Explicit(left, right) => (*left, *right),
447 }
448 }
449}
450pub(crate) fn check_attr_len<T>(
453 name: &str,
454 values: &[T],
455 expected: usize,
456) -> Result<(), ProcessError> {
457 if values.len() < expected {
458 return Err(ProcessError::InvalidAttribute {
459 name: name.to_string(),
460 reason: format!("expected {expected} values, got {}", values.len()),
461 });
462 }
463 Ok(())
464}
465
466pub(crate) fn padding_config_1d(pads: &[i64]) -> Result<PaddingConfig1d, ProcessError> {
485 check_attr_len("pads", pads, 2)?;
486 let [left, right] = [pads[0], pads[1]];
487
488 if left < 0 || right < 0 {
489 Err(ProcessError::InvalidAttribute {
490 name: "pads".to_string(),
491 reason: format!("negative pad values are not supported: {pads:?}"),
492 })
493 } else if left == 0 && right == 0 {
494 Ok(PaddingConfig1d::Valid)
495 } else {
496 Ok(PaddingConfig1d::Explicit(left as usize, right as usize))
497 }
498}
499
500#[derive(Debug, Clone, PartialEq, Eq, Default)]
502pub enum PaddingConfig2d {
503 #[default]
505 Valid,
506 Explicit(usize, usize, usize, usize),
510}
511
512impl fmt::Display for PaddingConfig2d {
513 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
514 match self {
515 PaddingConfig2d::Valid => write!(f, "Valid"),
516 PaddingConfig2d::Explicit(top, left, bottom, right) => {
517 write!(f, "Explicit({top}, {left}, {bottom}, {right})")
518 }
519 }
520 }
521}
522
523impl PaddingConfig2d {
524 pub fn is_asymmetric(&self) -> bool {
526 match self {
527 PaddingConfig2d::Explicit(top, left, bottom, right) => top != bottom || left != right,
528 _ => false,
529 }
530 }
531
532 pub fn as_tuple(&self) -> (usize, usize, usize, usize) {
534 match self {
535 PaddingConfig2d::Valid => (0, 0, 0, 0),
536 PaddingConfig2d::Explicit(top, left, bottom, right) => (*top, *left, *bottom, *right),
537 }
538 }
539}
540
541pub(crate) fn padding_config_2d(pads: &[i64]) -> Result<PaddingConfig2d, ProcessError> {
560 check_attr_len("pads", pads, 4)?;
561 let [top, left, bottom, right] = [pads[0], pads[1], pads[2], pads[3]];
562
563 if left < 0 || right < 0 || top < 0 || bottom < 0 {
564 Err(ProcessError::InvalidAttribute {
565 name: "pads".to_string(),
566 reason: format!("negative pad values are not supported: {pads:?}"),
567 })
568 } else if left == 0 && right == 0 && top == 0 && bottom == 0 {
569 Ok(PaddingConfig2d::Valid)
570 } else {
571 Ok(PaddingConfig2d::Explicit(
572 top as usize,
573 left as usize,
574 bottom as usize,
575 right as usize,
576 ))
577 }
578}
579
580#[derive(Debug, Clone, PartialEq, Eq, Default)]
582pub enum PaddingConfig3d {
583 #[default]
585 Valid,
586 Explicit(usize, usize, usize, usize, usize, usize),
590}
591
592impl fmt::Display for PaddingConfig3d {
593 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
594 match self {
595 PaddingConfig3d::Valid => write!(f, "Valid"),
596 PaddingConfig3d::Explicit(front, top, left, back, bottom, right) => {
597 write!(
598 f,
599 "Explicit({front}, {top}, {left}, {back}, {bottom}, {right})"
600 )
601 }
602 }
603 }
604}
605
606impl PaddingConfig3d {
607 pub fn is_asymmetric(&self) -> bool {
609 match self {
610 PaddingConfig3d::Explicit(front, top, left, back, bottom, right) => {
611 front != back || top != bottom || left != right
612 }
613 _ => false,
614 }
615 }
616
617 pub fn as_tuple(&self) -> (usize, usize, usize, usize, usize, usize) {
619 match self {
620 PaddingConfig3d::Valid => (0, 0, 0, 0, 0, 0),
621 PaddingConfig3d::Explicit(front, top, left, back, bottom, right) => {
622 (*front, *top, *left, *back, *bottom, *right)
623 }
624 }
625 }
626}
627
628pub(crate) fn padding_config_3d(pads: &[i64]) -> Result<PaddingConfig3d, ProcessError> {
647 check_attr_len("pads", pads, 6)?;
648 let [front, top, left, back, bottom, right] =
649 [pads[0], pads[1], pads[2], pads[3], pads[4], pads[5]];
650
651 if left < 0 || right < 0 || top < 0 || bottom < 0 || front < 0 || back < 0 {
652 Err(ProcessError::InvalidAttribute {
653 name: "pads".to_string(),
654 reason: format!("negative pad values are not supported: {pads:?}"),
655 })
656 } else if left == 0 && right == 0 && top == 0 && bottom == 0 && front == 0 && back == 0 {
657 Ok(PaddingConfig3d::Valid)
658 } else {
659 Ok(PaddingConfig3d::Explicit(
660 front as usize,
661 top as usize,
662 left as usize,
663 back as usize,
664 bottom as usize,
665 right as usize,
666 ))
667 }
668}
669
670pub(crate) fn known_weight_shape(weight: &crate::ir::Argument) -> Option<Vec<usize>> {
673 weight
674 .ty
675 .static_shape_known()
676 .or_else(|| weight.value().map(|data| data.shape().to_vec()))
677}
678
679#[cfg(test)]
680mod tests {
681 use super::*;
682 use crate::ir::{DType, NodeType, TensorType};
683 use crate::node::test_utils::TestNodeBuilder;
684
685 fn conv_node(auto_pad: &str, spatial: &[Option<usize>], dilations: Vec<i64>) -> RawNode {
689 let mut static_shape = vec![None, Some(3)];
690 static_shape.extend_from_slice(spatial);
691 let rank = static_shape.len();
692 TestNodeBuilder::new(NodeType::Conv2d, "test_conv")
693 .add_input(
694 "data",
695 ArgType::Tensor(TensorType {
696 dtype: DType::F32,
697 rank,
698 static_shape: Some(static_shape),
699 }),
700 )
701 .output_tensor_f32("output", rank, None)
702 .attr_string("auto_pad", auto_pad)
703 .attr_ints("dilations", dilations)
704 .build()
705 }
706
707 #[test]
708 fn test_static_spatial_dims_ignores_dynamic_batch() {
709 let node = conv_node("SAME_UPPER", &[Some(7), Some(9)], vec![1, 1]);
710 assert_eq!(static_spatial_dims(&node.inputs[0].ty), Some(vec![7, 9]));
711 }
712
713 #[test]
714 fn test_static_spatial_dims_dynamic() {
715 let node = conv_node("SAME_UPPER", &[None, None], vec![1, 1]);
716 assert_eq!(static_spatial_dims(&node.inputs[0].ty), None);
717 }
718
719 #[test]
720 fn test_validate_auto_pad_accepts_static_spatial() {
721 for auto_pad in ["SAME_UPPER", "SAME_LOWER"] {
724 let node = conv_node(auto_pad, &[Some(7), Some(7)], vec![2, 2]);
725 assert!(validate_auto_pad(&node).is_ok());
726 }
727 }
728
729 #[test]
730 fn test_validate_auto_pad_accepts_same_upper_dynamic() {
731 let node = conv_node("SAME_UPPER", &[None, None], vec![1, 1]);
732 assert!(validate_auto_pad(&node).is_ok());
733 }
734
735 #[test]
736 fn test_validate_auto_pad_rejects_same_lower_dynamic() {
737 let node = conv_node("SAME_LOWER", &[None, None], vec![1, 1]);
738 let err = validate_auto_pad(&node).unwrap_err().to_string();
739 assert!(err.contains(&SameBlocker::SameLower.to_string()), "{err}");
740 }
741
742 #[test]
743 fn test_validate_auto_pad_rejects_dilation_dynamic() {
744 let node = conv_node("SAME_UPPER", &[None, None], vec![2, 2]);
745 let err = validate_auto_pad(&node).unwrap_err().to_string();
746 assert!(err.contains(&SameBlocker::Dilated.to_string()), "{err}");
747 }
748
749 #[test]
750 fn test_validate_auto_pad_rejects_3d_dynamic() {
751 let node = conv_node("SAME_UPPER", &[None, None, None], vec![1, 1, 1]);
752 let err = validate_auto_pad(&node).unwrap_err().to_string();
753 assert!(
754 err.contains(&SameBlocker::ThreeSpatialDims.to_string()),
755 "{err}"
756 );
757 }
758
759 #[test]
760 fn test_forward_time_same_blocker_precedence() {
761 assert_eq!(
764 forward_time_same_blocker(&AutoPad::SameLower, true, 3),
765 Some(SameBlocker::SameLower)
766 );
767 assert_eq!(
768 forward_time_same_blocker(&AutoPad::SameUpper, true, 3),
769 Some(SameBlocker::Dilated)
770 );
771 assert_eq!(
772 forward_time_same_blocker(&AutoPad::SameUpper, false, 3),
773 Some(SameBlocker::ThreeSpatialDims)
774 );
775 assert_eq!(
776 forward_time_same_blocker(&AutoPad::SameUpper, false, 2),
777 None
778 );
779 }
780
781 #[test]
782 fn test_validate_auto_pad_rejects_wrong_attribute_types() {
783 let mut node = conv_node("SAME_UPPER", &[None, None], vec![1, 1]);
784 node.attrs
785 .insert("auto_pad".to_string(), AttributeValue::Int64(1));
786 let err = validate_auto_pad(&node).unwrap_err().to_string();
787 assert!(err.contains("expected a string"), "{err}");
788
789 let mut node = conv_node("SAME_UPPER", &[None, None], vec![1, 1]);
790 node.attrs
791 .insert("dilations".to_string(), AttributeValue::Int64(1));
792 let err = validate_auto_pad(&node).unwrap_err().to_string();
793 assert!(err.contains("expected a list of ints"), "{err}");
794 }
795
796 #[test]
797 fn test_validate_auto_pad_ignores_other_modes() {
798 for auto_pad in ["NOTSET", "VALID"] {
799 let node = conv_node(auto_pad, &[None, None], vec![1, 1]);
800 assert!(validate_auto_pad(&node).is_ok());
801 }
802 }
803
804 #[test]
806 fn test_auto_pad_parse() {
807 assert_eq!(AutoPad::parse("NOTSET").unwrap(), AutoPad::NotSet);
808 assert_eq!(AutoPad::parse("SAME_UPPER").unwrap(), AutoPad::SameUpper);
809 assert_eq!(AutoPad::parse("SAME_LOWER").unwrap(), AutoPad::SameLower);
810 assert_eq!(AutoPad::parse("VALID").unwrap(), AutoPad::Valid);
811 assert!(AutoPad::parse("INVALID").is_err());
812 }
813
814 #[test]
815 fn test_auto_pad_display() {
816 assert_eq!(AutoPad::NotSet.to_string(), "NOTSET");
817 assert_eq!(AutoPad::SameUpper.to_string(), "SAME_UPPER");
818 assert_eq!(AutoPad::SameLower.to_string(), "SAME_LOWER");
819 assert_eq!(AutoPad::Valid.to_string(), "VALID");
820 }
821
822 #[test]
824 fn test_padding_config_1d_valid() {
825 let pads = vec![0, 0];
826 let config = padding_config_1d(&pads).unwrap();
827 assert!(matches!(config, PaddingConfig1d::Valid));
828 }
829
830 #[test]
831 fn test_padding_config_1d_explicit_symmetric() {
832 let pads = vec![2, 2];
833 let config = padding_config_1d(&pads).unwrap();
834 assert!(matches!(config, PaddingConfig1d::Explicit(2, 2)));
835 assert!(!config.is_asymmetric());
836 assert_eq!(config.as_tuple(), (2, 2));
837 }
838
839 #[test]
840 fn test_padding_config_1d_explicit_asymmetric() {
841 let pads = vec![1, 2];
842 let config = padding_config_1d(&pads).unwrap();
843 assert!(matches!(config, PaddingConfig1d::Explicit(1, 2)));
844 assert!(config.is_asymmetric());
845 assert_eq!(config.as_tuple(), (1, 2));
846 }
847
848 #[test]
849 fn test_padding_config_1d_negative() {
850 let pads = vec![-1, -1];
851 let err = padding_config_1d(&pads).unwrap_err();
852 assert!(err.to_string().contains("negative pad values"), "{err}");
853 }
854
855 #[test]
857 fn test_padding_config_2d_valid() {
858 let pads = vec![0, 0, 0, 0];
859 let config = padding_config_2d(&pads).unwrap();
860 assert!(matches!(config, PaddingConfig2d::Valid));
861 assert!(!config.is_asymmetric());
862 }
863
864 #[test]
865 fn test_padding_config_2d_explicit_symmetric() {
866 let pads = vec![2, 2, 2, 2];
867 let config = padding_config_2d(&pads).unwrap();
868 assert!(matches!(config, PaddingConfig2d::Explicit(2, 2, 2, 2)));
869 assert!(!config.is_asymmetric());
870 assert_eq!(config.as_tuple(), (2, 2, 2, 2));
871 }
872
873 #[test]
874 fn test_padding_config_2d_explicit_asymmetric() {
875 let pads = vec![1, 2, 3, 4];
877 let config = padding_config_2d(&pads).unwrap();
878 assert!(matches!(config, PaddingConfig2d::Explicit(1, 2, 3, 4)));
879 assert!(config.is_asymmetric());
880 assert_eq!(config.as_tuple(), (1, 2, 3, 4));
881 }
882
883 #[test]
884 fn test_padding_config_2d_explicit_asymmetric_top_bottom() {
885 let pads = vec![1, 2, 3, 2];
887 let config = padding_config_2d(&pads).unwrap();
888 assert!(matches!(config, PaddingConfig2d::Explicit(1, 2, 3, 2)));
889 assert!(config.is_asymmetric());
890 }
891
892 #[test]
893 fn test_padding_config_2d_explicit_asymmetric_left_right() {
894 let pads = vec![2, 1, 2, 3];
896 let config = padding_config_2d(&pads).unwrap();
897 assert!(matches!(config, PaddingConfig2d::Explicit(2, 1, 2, 3)));
898 assert!(config.is_asymmetric());
899 }
900
901 #[test]
902 fn test_padding_config_2d_negative() {
903 let pads = vec![-1, -1, -1, -1];
904 let err = padding_config_2d(&pads).unwrap_err();
905 assert!(err.to_string().contains("negative pad values"), "{err}");
906 }
907
908 #[test]
910 fn test_padding_config_3d_valid() {
911 let pads = vec![0, 0, 0, 0, 0, 0];
912 let config = padding_config_3d(&pads).unwrap();
913 assert!(matches!(config, PaddingConfig3d::Valid));
914 assert!(!config.is_asymmetric());
915 }
916
917 #[test]
918 fn test_padding_config_3d_explicit_symmetric() {
919 let pads = vec![2, 3, 1, 2, 3, 1];
920 let config = padding_config_3d(&pads).unwrap();
921 assert!(matches!(
922 config,
923 PaddingConfig3d::Explicit(2, 3, 1, 2, 3, 1)
924 ));
925 assert!(!config.is_asymmetric());
926 assert_eq!(config.as_tuple(), (2, 3, 1, 2, 3, 1));
927 }
928
929 #[test]
930 fn test_padding_config_3d_explicit_asymmetric() {
931 let pads = vec![1, 2, 3, 4, 5, 6];
933 let config = padding_config_3d(&pads).unwrap();
934 assert!(matches!(
935 config,
936 PaddingConfig3d::Explicit(1, 2, 3, 4, 5, 6)
937 ));
938 assert!(config.is_asymmetric());
939 assert_eq!(config.as_tuple(), (1, 2, 3, 4, 5, 6));
940 }
941
942 #[test]
943 fn test_padding_config_3d_explicit_asymmetric_partial() {
944 let pads = vec![1, 3, 1, 2, 3, 1];
946 let config = padding_config_3d(&pads).unwrap();
947 assert!(matches!(
948 config,
949 PaddingConfig3d::Explicit(1, 3, 1, 2, 3, 1)
950 ));
951 assert!(config.is_asymmetric());
952 }
953
954 #[test]
955 fn test_padding_config_3d_negative() {
956 let pads = vec![-1, -1, -1, -1, -1, -1];
957 let err = padding_config_3d(&pads).unwrap_err();
958 assert!(err.to_string().contains("negative pad values"), "{err}");
959 }
960
961 fn pool_shape(
964 spatial: &[Option<usize>],
965 attrs: impl FnOnce(TestNodeBuilder) -> TestNodeBuilder,
966 ) -> Vec<Option<usize>> {
967 let mut static_shape = vec![None, Some(3)];
968 static_shape.extend_from_slice(spatial);
969 let rank = static_shape.len();
970 let builder = TestNodeBuilder::new(NodeType::MaxPool2d, "test_pool")
971 .add_input(
972 "data",
973 ArgType::Tensor(TensorType {
974 dtype: DType::F32,
975 rank,
976 static_shape: Some(static_shape),
977 }),
978 )
979 .output_tensor_f32("output", rank, None);
980 let mut node = attrs(builder).build();
981 pool_output_type(&mut node).unwrap();
982 node.outputs[0].ty.static_shape().unwrap().clone()
983 }
984
985 #[test]
986 fn test_pool_output_type_asymmetric_pads_and_dilation() {
987 let shape = pool_shape(&[Some(10), Some(10)], |node| {
989 node.attr_ints("kernel_shape", vec![3, 3])
990 .attr_ints("strides", vec![2, 1])
991 .attr_ints("pads", vec![1, 0, 2, 0])
992 .attr_ints("dilations", vec![2, 1])
993 });
994 assert_eq!(shape, vec![None, Some(3), Some(5), Some(8)]);
995 }
996
997 #[test]
998 fn test_pool_output_type_ceil_mode_asymmetric_pads_drops_window() {
999 let shape = pool_shape(&[Some(5)], |node| {
1001 node.attr_ints("kernel_shape", vec![3])
1002 .attr_ints("strides", vec![3])
1003 .attr_ints("pads", vec![0, 2])
1004 .attr_int("ceil_mode", 1)
1005 });
1006 assert_eq!(shape, vec![None, Some(3), Some(2)]);
1007 }
1008
1009 #[test]
1010 fn test_pool_output_type_valid_ignores_pads() {
1011 let shape = pool_shape(&[Some(6), Some(6), Some(6)], |node| {
1012 node.attr_ints("kernel_shape", vec![2, 2, 2])
1013 .attr_ints("pads", vec![1, 1, 1, 1, 1, 1])
1014 .attr_string("auto_pad", "VALID")
1015 });
1016 assert_eq!(shape, vec![None, Some(3), Some(5), Some(5), Some(5)]);
1017 }
1018
1019 #[test]
1020 fn test_pool_output_type_unknown_spatial_dims() {
1021 let shape = pool_shape(&[None, Some(2)], |node| {
1023 node.attr_ints("kernel_shape", vec![3, 3])
1024 });
1025 assert_eq!(shape, vec![None, Some(3), None, None]);
1026 }
1027
1028 #[test]
1029 fn test_pool_output_type_unrecognized_ceil_mode() {
1030 let shape = pool_shape(&[Some(7)], |node| {
1031 node.attr_ints("kernel_shape", vec![2])
1032 .attr_ints("strides", vec![2])
1033 .attr_int("ceil_mode", 2)
1034 });
1035 assert_eq!(shape, vec![None, Some(3), None]);
1036 }
1037}