burn-std 0.22.0

Core types and utilities shared across the Burn ecosystem.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
//! Configuration types for tensor operations.

use crate::ElementConversion;
use core::num::NonZeroUsize;

/// Check that the parameter value is non-zero.
// NOTE: for now we keep usize but we could refactor the parameters to hold `NonZeroUsize`.
pub(crate) fn check_nonzero(value: usize, msg: &str) -> usize {
    NonZeroUsize::new(value).expect(msg);
    value
}

/// Convolution options.
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct ConvOptions<const N: usize> {
    /// Stride (non-zero).
    pub stride: [usize; N],

    /// Padding as `(begin, end)` pairs for each spatial dimension.
    pub padding: [(usize, usize); N],

    /// Dilation (non-zero).
    pub dilation: [usize; N],

    /// Groups (non-zero).
    pub groups: usize,
}

impl<const N: usize> ConvOptions<N> {
    /// Constructs a new `ConvOptions`.
    pub fn new(
        stride: [usize; N],
        padding: [usize; N],
        dilation: [usize; N],
        groups: usize,
    ) -> Self {
        Self {
            stride: stride.map(|s| check_nonzero(s, "stride must be non-zero")),
            padding: padding.map(|padding| (padding, padding)),
            dilation: dilation.map(|d| check_nonzero(d, "dilation must be non-zero")),
            groups: check_nonzero(groups, "groups must be non-zero"),
        }
    }

    /// Constructs convolution options with explicit per-side padding.
    pub fn new_with_padding(
        stride: [usize; N],
        padding: [(usize, usize); N],
        dilation: [usize; N],
        groups: usize,
    ) -> Self {
        Self {
            stride: stride.map(|s| check_nonzero(s, "stride must be non-zero")),
            padding,
            dilation: dilation.map(|d| check_nonzero(d, "dilation must be non-zero")),
            groups: check_nonzero(groups, "groups must be non-zero"),
        }
    }

    /// Returns true if padding is asymmetric.
    pub fn is_asymmetric(&self) -> bool {
        self.padding.iter().any(|(begin, end)| begin != end)
    }

    /// Returns the padding at the beginning of every spatial dimension.
    pub fn padding_begin(&self) -> [usize; N] {
        self.padding.map(|(begin, _)| begin)
    }

    /// Returns the padding at the end of every spatial dimension.
    pub fn padding_end(&self) -> [usize; N] {
        self.padding.map(|(_, after)| after)
    }

    /// Returns symmetric padding values.
    ///
    /// # Panics
    /// Panics when any spatial dimension has asymmetric padding.
    pub fn symmetric_padding(&self) -> [usize; N] {
        assert!(
            !self.is_asymmetric(),
            "expected symmetric convolution padding"
        );
        self.padding_begin()
    }
}

/// Convolution options with optional asymmetric end padding.
///
/// Deprecated compatibility wrapper for the convolution options API shipped in
/// Burn 0.22. Use [`ConvOptions::new_with_padding`] instead.
#[deprecated(since = "0.22.0", note = "Use `ConvOptions::new_with_padding` instead")]
#[derive(Debug, Clone)]
pub struct PaddedConvOptions<const N: usize> {
    /// The underlying convolution options.
    pub options: ConvOptions<N>,
    /// Padding at the end of each spatial dimension.
    ///
    /// When `None`, the padding stored in [`Self::options`] is used unchanged.
    pub padding_end: Option<[usize; N]>,
}

#[allow(deprecated)]
impl<const N: usize> PaddedConvOptions<N> {
    /// Creates options with explicit begin and end padding.
    pub fn asymmetric(
        stride: [usize; N],
        padding_begin: [usize; N],
        padding_end: [usize; N],
        dilation: [usize; N],
        groups: usize,
    ) -> Self {
        let options = ConvOptions::new(stride, padding_begin, dilation, groups);
        let padding_end = (padding_begin != padding_end).then_some(padding_end);
        Self {
            options,
            padding_end,
        }
    }

    /// Returns true if explicit asymmetric end padding is present.
    pub fn is_asymmetric(&self) -> bool {
        self.padding_end.is_some()
    }
}

#[allow(deprecated)]
impl<const N: usize> From<PaddedConvOptions<N>> for ConvOptions<N> {
    fn from(value: PaddedConvOptions<N>) -> Self {
        let Some(padding_end) = value.padding_end else {
            return value.options;
        };
        let padding_begin = value.options.padding_begin();
        let padding = core::array::from_fn(|i| (padding_begin[i], padding_end[i]));

        ConvOptions::new_with_padding(
            value.options.stride,
            padding,
            value.options.dilation,
            value.options.groups,
        )
    }
}

#[allow(deprecated)]
impl<const N: usize> From<ConvOptions<N>> for PaddedConvOptions<N> {
    fn from(options: ConvOptions<N>) -> Self {
        if options.is_asymmetric() {
            let padding_begin = options.padding_begin();
            let padding_end = options.padding_end();
            Self {
                options: ConvOptions::new(
                    options.stride,
                    padding_begin,
                    options.dilation,
                    options.groups,
                ),
                padding_end: Some(padding_end),
            }
        } else {
            Self {
                options,
                padding_end: None,
            }
        }
    }
}

/// Max pooling options.
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct MaxPoolOptions<const N: usize> {
    /// Kernel size (non-zero).
    pub kernel_size: [usize; N],

    /// Stride (non-zero).
    pub stride: [usize; N],

    /// Padding as `(begin, end)` pairs for each spatial dimension.
    pub padding: [(usize, usize); N],

    /// Dilation (non-zero).
    pub dilation: [usize; N],

    /// If true, use ceiling instead of floor for output size calculation.
    pub ceil_mode: bool,
}

impl<const N: usize> MaxPoolOptions<N> {
    /// Constructs max pooling options with the given kernel size.
    ///
    /// Defaults to a stride equal to the kernel size, no padding, a dilation
    /// of 1 and floor mode.
    pub fn new(kernel_size: [usize; N]) -> Self {
        let kernel_size = kernel_size.map(|k| check_nonzero(k, "kernel size must be non-zero"));
        Self {
            kernel_size,
            stride: kernel_size,
            padding: [(0, 0); N],
            dilation: [1; N],
            ceil_mode: false,
        }
    }

    /// Sets the stride.
    pub fn with_stride(mut self, stride: [usize; N]) -> Self {
        self.stride = stride.map(|s| check_nonzero(s, "stride must be non-zero"));
        self
    }

    /// Sets symmetric padding for every spatial dimension.
    pub fn with_padding(mut self, padding: [usize; N]) -> Self {
        self.padding = padding.map(|padding| (padding, padding));
        self
    }

    /// Sets explicit `(begin, end)` padding for every spatial dimension.
    pub fn with_padding_pairs(mut self, padding: [(usize, usize); N]) -> Self {
        self.padding = padding;
        self
    }

    /// Sets the dilation.
    pub fn with_dilation(mut self, dilation: [usize; N]) -> Self {
        self.dilation = dilation.map(|d| check_nonzero(d, "dilation must be non-zero"));
        self
    }

    /// Sets whether to use ceiling instead of floor for output size calculation.
    pub fn with_ceil_mode(mut self, ceil_mode: bool) -> Self {
        self.ceil_mode = ceil_mode;
        self
    }

    /// Returns true if padding is asymmetric.
    pub fn is_asymmetric(&self) -> bool {
        self.padding.iter().any(|(begin, end)| begin != end)
    }
}

/// Average pooling options.
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct AvgPoolOptions<const N: usize> {
    /// Kernel size (non-zero).
    pub kernel_size: [usize; N],

    /// Stride (non-zero).
    pub stride: [usize; N],

    /// Padding as `(begin, end)` pairs for each spatial dimension.
    pub padding: [(usize, usize); N],

    /// If true, padded values are counted in the denominator of the average.
    pub count_include_pad: bool,

    /// If true, use ceiling instead of floor for output size calculation.
    pub ceil_mode: bool,
}

impl<const N: usize> AvgPoolOptions<N> {
    /// Constructs average pooling options with the given kernel size.
    ///
    /// Defaults to a stride equal to the kernel size, no padding, counting
    /// padded values in the average and floor mode.
    pub fn new(kernel_size: [usize; N]) -> Self {
        let kernel_size = kernel_size.map(|k| check_nonzero(k, "kernel size must be non-zero"));
        Self {
            kernel_size,
            stride: kernel_size,
            padding: [(0, 0); N],
            count_include_pad: true,
            ceil_mode: false,
        }
    }

    /// Sets the stride.
    pub fn with_stride(mut self, stride: [usize; N]) -> Self {
        self.stride = stride.map(|s| check_nonzero(s, "stride must be non-zero"));
        self
    }

    /// Sets symmetric padding for every spatial dimension.
    pub fn with_padding(mut self, padding: [usize; N]) -> Self {
        self.padding = padding.map(|padding| (padding, padding));
        self
    }

    /// Sets explicit `(begin, end)` padding for every spatial dimension.
    pub fn with_padding_pairs(mut self, padding: [(usize, usize); N]) -> Self {
        self.padding = padding;
        self
    }

    /// Sets whether padded values are counted in the denominator of the average.
    pub fn with_count_include_pad(mut self, count_include_pad: bool) -> Self {
        self.count_include_pad = count_include_pad;
        self
    }

    /// Sets whether to use ceiling instead of floor for output size calculation.
    pub fn with_ceil_mode(mut self, ceil_mode: bool) -> Self {
        self.ceil_mode = ceil_mode;
        self
    }

    /// Returns true if padding is asymmetric.
    pub fn is_asymmetric(&self) -> bool {
        self.padding.iter().any(|(begin, end)| begin != end)
    }
}

/// Deformable convolution options.
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct DeformConvOptions<const N: usize> {
    /// Stride (non-zero).
    pub stride: [usize; N],

    /// Padding.
    pub padding: [usize; N],

    /// Dilation (non-zero).
    pub dilation: [usize; N],

    /// Weight Groups (non-zero).
    pub weight_groups: usize,

    /// Offset Groups (non-zero).
    pub offset_groups: usize,
}

impl<const N: usize> DeformConvOptions<N> {
    /// Constructs a new `DeformConvOptions`.
    pub fn new(
        stride: [usize; N],
        padding: [usize; N],
        dilation: [usize; N],
        weight_groups: usize,
        offset_groups: usize,
    ) -> Self {
        Self {
            stride: stride.map(|s| check_nonzero(s, "stride must be non-zero")),
            padding,
            dilation: dilation.map(|d| check_nonzero(d, "dilation must be non-zero")),
            weight_groups: check_nonzero(weight_groups, "weight groups must be non-zero"),
            offset_groups: check_nonzero(offset_groups, "offset groups must be non-zero"),
        }
    }
}

/// Transposed convolution options.
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct ConvTransposeOptions<const N: usize> {
    /// Stride (non-zero).
    pub stride: [usize; N],

    /// Padding.
    pub padding: [usize; N],

    /// Padding out.
    pub padding_out: [usize; N],

    /// Dilation (non-zero).
    pub dilation: [usize; N],

    /// Groups (non-zero).
    pub groups: usize,
}

impl<const N: usize> ConvTransposeOptions<N> {
    /// Constructs a new `ConvTransposeOptions`.
    pub fn new(
        stride: [usize; N],
        padding: [usize; N],
        padding_out: [usize; N],
        dilation: [usize; N],
        groups: usize,
    ) -> Self {
        Self {
            stride: stride.map(|s| check_nonzero(s, "stride must be non-zero")),
            padding,
            padding_out,
            dilation: dilation.map(|d| check_nonzero(d, "dilation must be non-zero")),
            groups: check_nonzero(groups, "groups must be non-zero"),
        }
    }
}

/// Unfold operation options.
#[derive(Debug, Clone)]
pub struct UnfoldOptions {
    /// The number of positions to slide over the input tensor in each dimension.
    /// A stride of `[1, 1]` will slide the kernel one pixel at a time.
    pub stride: [usize; 2],

    /// The number of zero-padding pixels added to each side of the input tensor in each dimension.
    pub padding: [usize; 2],

    /// The spacing between the blocks (patches) in the original input tensor.
    pub dilation: [usize; 2],
}

impl UnfoldOptions {
    /// Constructs a new `UnfoldOptions`.
    pub fn new(stride: [usize; 2], padding: [usize; 2], dilation: [usize; 2]) -> Self {
        Self {
            stride: stride.map(|s| check_nonzero(s, "stride must be non-zero")),
            padding,
            dilation: dilation.map(|d| check_nonzero(d, "dilation must be non-zero")),
        }
    }
}

/// Algorithm used.
#[derive(new, Debug, Clone, serde::Deserialize, serde::Serialize)]
pub enum InterpolateMode {
    /// Nearest-neighbor floor interpolation.
    /// Matches the legacy behavior of OpenCV’s INTER_NEAREST. It results in a bottom-right shift when resizing.
    /// <https://en.wikipedia.org/wiki/Nearest-neighbor_interpolation>
    Nearest,

    /// Nearest-neighbor exact interpolation.
    /// <https://en.wikipedia.org/wiki/Nearest-neighbor_interpolation>
    NearestExact,

    /// Bilinear interpolation.
    /// <https://en.wikipedia.org/wiki/Bilinear_interpolation>
    Bilinear,

    /// Bicubic interpolation.
    /// <https://en.wikipedia.org/wiki/Bicubic_interpolation>
    Bicubic,

    /// Lanczos3 interpolation (6-tap sinc-based filter).
    /// <https://en.wikipedia.org/wiki/Lanczos_resampling>
    Lanczos3,
}

/// Interpolation options.
#[derive(Debug, Clone)]
pub struct InterpolateOptions {
    /// Algorithm used.
    pub mode: InterpolateMode,
    /// If `true`, the input and output tensors are aligned by their corner pixels.
    /// If `false`, half-pixel coordinate mapping is used instead.
    pub align_corners: bool,
    /// Output spatial size `[height, width]`.
    ///
    /// Exactly one of `output_size` or `scale_factor` must be set when calling
    /// `burn_tensor::module::interpolate`. Backends receive the resolved size as a
    /// separate argument and ignore this field.
    pub output_size: Option<[usize; 2]>,
    /// Scale factor `[scale_height, scale_width]` applied to the input spatial size.
    /// The output size is `floor(input_size * scale_factor)`.
    ///
    /// Exactly one of `output_size` or `scale_factor` must be set when calling
    /// `burn_tensor::module::interpolate`. Backends ignore this field.
    pub scale_factor: Option<[f32; 2]>,
}

impl InterpolateOptions {
    /// Create new interpolate options with the given mode.
    /// Defaults to `align_corners = true` and no output size or scale factor.
    pub fn new(mode: InterpolateMode) -> Self {
        Self {
            mode,
            align_corners: true,
            output_size: None,
            scale_factor: None,
        }
    }

    /// Set align_corners.
    pub fn with_align_corners(mut self, align_corners: bool) -> Self {
        self.align_corners = align_corners;
        self
    }

    /// Set the output size `[height, width]`, clearing any scale factor.
    pub fn with_output_size(mut self, output_size: [usize; 2]) -> Self {
        self.output_size = Some(output_size);
        self.scale_factor = None;
        self
    }

    /// Set the scale factor `[scale_height, scale_width]`, clearing any output size.
    pub fn with_scale_factor(mut self, scale_factor: [f32; 2]) -> Self {
        self.scale_factor = Some(scale_factor);
        self.output_size = None;
        self
    }
}

/// Padding mode for grid sampling when coordinates are out of bounds.
///
/// Matches PyTorch's `padding_mode` parameter in `grid_sample`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Deserialize, serde::Serialize)]
pub enum GridSamplePaddingMode {
    /// Fill with zeros for out-of-bounds coordinates.
    #[default]
    Zeros,
    /// Clamp coordinates to the border (use nearest edge value).
    Border,
    /// Reflect coordinates at the boundary.
    Reflection,
}

/// Options for grid sampling operations.
#[derive(Debug, Clone)]
pub struct GridSampleOptions {
    /// Interpolation mode (bilinear, nearest, or bicubic).
    pub mode: InterpolateMode,
    /// Padding mode for out-of-bounds coordinates.
    pub padding_mode: GridSamplePaddingMode,
    /// If `true`, grid values of -1 and 1 correspond to the corner pixels.
    /// If `false`, they correspond to the corner points of the corner pixels
    /// (i.e., -1 maps to -0.5 and 1 maps to size - 0.5 in pixel coordinates).
    pub align_corners: bool,
}

impl Default for GridSampleOptions {
    fn default() -> Self {
        Self {
            mode: InterpolateMode::Bilinear,
            padding_mode: GridSamplePaddingMode::Zeros,
            align_corners: false,
        }
    }
}

impl From<InterpolateMode> for GridSampleOptions {
    fn from(value: InterpolateMode) -> Self {
        GridSampleOptions::new(value)
    }
}

impl GridSampleOptions {
    /// Create new grid sample options with the given interpolation mode.
    ///
    /// Uses default values for padding_mode (Zeros) and align_corners (false).
    pub fn new(mode: InterpolateMode) -> Self {
        Self {
            mode,
            ..Default::default()
        }
    }

    /// Set the padding mode.
    pub fn with_padding_mode(mut self, padding_mode: GridSamplePaddingMode) -> Self {
        self.padding_mode = padding_mode;
        self
    }

    /// Set align_corners.
    pub fn with_align_corners(mut self, align_corners: bool) -> Self {
        self.align_corners = align_corners;
        self
    }
}

/// Padding mode for tensor pad operations.
///
/// Defines how values are filled when padding a tensor beyond its original boundaries.
/// Padding can be applied to any dimension of a tensor.
///
/// # Modes
///
/// - [`Constant`](PadMode::Constant): Fill with a specified value (default: 0.0)
/// - [`Reflect`](PadMode::Reflect): Mirror values at boundary, excluding edge (requires padding < dim_size)
/// - [`Edge`](PadMode::Edge): Replicate boundary values
#[derive(Debug, Clone, Copy, PartialEq, serde::Deserialize, serde::Serialize)]
pub enum PadMode {
    /// Fill padded regions with a constant value.
    ///
    /// # Example
    /// For tensor `[1, 2, 3]` with padding 2 on the left and value 0:
    /// Result: `[0, 0, 1, 2, 3]`
    Constant(f32),

    /// Reflect values at the boundary, excluding the edge value.
    ///
    /// Padding must be less than the dimension size (i.e., `padding < dim_size`).
    ///
    /// # Example
    /// For tensor `[1, 2, 3, 4]` with padding 2 on the left:
    /// Result: `[3, 2, 1, 2, 3, 4]` (reflects from index 1, not 0)
    Reflect,

    /// Replicate the edge values.
    ///
    /// # Example
    /// For tensor `[1, 2, 3, 4]` with padding 2 on the left:
    /// Result: `[1, 1, 1, 2, 3, 4]`
    Edge,
}

impl Default for PadMode {
    fn default() -> Self {
        PadMode::Constant(0.0)
    }
}

impl<E: ElementConversion> From<E> for PadMode {
    fn from(value: E) -> Self {
        PadMode::Constant(value.elem())
    }
}

/// Options for the attention module.
#[derive(Debug, Clone, Copy, Default, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct AttentionModuleOptions {
    /// Custom scale factor applied to QK^T. When `None`, defaults to `1/sqrt(head_dim)`.
    pub scale: Option<f64>,

    /// Soft capping applied before softmax: `softcap * tanh(scores / softcap)`.
    /// Used by Gemma-2 and similar models. Must be positive when set.
    pub softcap: Option<f64>,

    /// When `true`, applies causal (autoregressive) masking so that each query position
    /// can only attend to key positions at or before it. This is more efficient than
    /// passing an explicit lower-triangular bool mask because backends can use optimized
    /// kernel paths (e.g. flash attention with causal mode).
    pub is_causal: bool,
}

/// Computation to be used to update the existing values in indexed assignment operations (scatter/select).
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum IndexingUpdateOp {
    /// Overwrite existing values.
    Assign,
    /// Performs an addition.
    Add,
    /// Multiply existing values.
    Mul,
    /// Take element-wise minimum.
    Min,
    /// Take element-wise maximum.
    Max,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn conv_options_symmetric_constructor() {
        let options = ConvOptions::new([1, 2], [3, 4], [5, 6], 7);

        assert_eq!(options.padding, [(3, 3), (4, 4)]);
        assert_eq!(options.padding_begin(), [3, 4]);
        assert_eq!(options.padding_end(), [3, 4]);
        assert_eq!(options.symmetric_padding(), [3, 4]);
        assert!(!options.is_asymmetric());
    }

    #[test]
    fn conv_options_explicit_padding_constructor() {
        let options = ConvOptions::new_with_padding([1, 2], [(3, 4), (5, 6)], [7, 8], 9);

        assert_eq!(options.padding, [(3, 4), (5, 6)]);
        assert_eq!(options.padding_begin(), [3, 5]);
        assert_eq!(options.padding_end(), [4, 6]);
        assert!(options.is_asymmetric());
    }

    #[test]
    #[allow(deprecated)]
    fn padded_conv_options_convert_to_conv_options() {
        let options: ConvOptions<2> =
            PaddedConvOptions::asymmetric([1, 2], [3, 5], [4, 6], [7, 8], 9).into();

        assert_eq!(options.padding, [(3, 4), (5, 6)]);
        assert_eq!(options.stride, [1, 2]);
        assert_eq!(options.dilation, [7, 8]);
        assert_eq!(options.groups, 9);
    }

    #[test]
    #[allow(deprecated)]
    fn asymmetric_conv_options_roundtrip_through_padded_options() {
        let expected = ConvOptions::new_with_padding([1, 2], [(3, 4), (5, 6)], [7, 8], 9);
        let padded: PaddedConvOptions<2> = expected.clone().into();
        let actual: ConvOptions<2> = padded.into();

        assert_eq!(actual, expected);
    }

    #[test]
    #[should_panic = "expected symmetric convolution padding"]
    fn conv_options_symmetric_padding_with_asymmetric_options() {
        let options = ConvOptions::new_with_padding([1], [(1, 2)], [1], 1);
        let _ = options.symmetric_padding();
    }

    #[test]
    #[should_panic = "stride must be non-zero"]
    fn conv_options_stride_zero() {
        let _opt = ConvOptions::new([0, 1], [0, 0], [1, 1], 1);
    }

    #[test]
    #[should_panic = "dilation must be non-zero"]
    fn conv_options_dilation_zero() {
        let _opt = ConvOptions::new([1, 1], [0, 0], [0, 0], 1);
    }

    #[test]
    #[should_panic = "groups must be non-zero"]
    fn conv_options_groups_zero() {
        let _opt = ConvOptions::new([1, 1], [0, 0], [1, 1], 0);
    }

    #[test]
    fn pool_options_defaults() {
        let max = MaxPoolOptions::new([2, 3]);
        let avg = AvgPoolOptions::new([2, 3]);

        assert_eq!(max.stride, [2, 3]);
        assert_eq!(max.padding, [(0, 0), (0, 0)]);
        assert_eq!(max.dilation, [1, 1]);
        assert!(!max.ceil_mode);
        assert_eq!(avg.stride, [2, 3]);
        assert_eq!(avg.padding, [(0, 0), (0, 0)]);
        assert!(avg.count_include_pad);
        assert!(!avg.ceil_mode);
    }

    #[test]
    fn pool_options_padding() {
        let symmetric = MaxPoolOptions::new([2, 2]).with_padding([0, 1]);
        let asymmetric = AvgPoolOptions::new([2]).with_padding_pairs([(0, 1)]);

        assert_eq!(symmetric.padding, [(0, 0), (1, 1)]);
        assert!(!symmetric.is_asymmetric());
        assert!(asymmetric.is_asymmetric());
    }

    #[test]
    #[should_panic = "kernel size must be non-zero"]
    fn max_pool_options_kernel_size_zero() {
        let _opt = MaxPoolOptions::new([0, 1]);
    }

    #[test]
    #[should_panic = "dilation must be non-zero"]
    fn max_pool_options_dilation_zero() {
        let _opt = MaxPoolOptions::new([1, 1]).with_dilation([0, 1]);
    }

    #[test]
    #[should_panic = "stride must be non-zero"]
    fn avg_pool_options_stride_zero() {
        let _opt = AvgPoolOptions::new([1, 1]).with_stride([0, 1]);
    }

    #[test]
    #[should_panic = "stride must be non-zero"]
    fn conv_transpose_options_stride_zero() {
        let _opt = ConvTransposeOptions::new([0, 1], [0, 0], [0, 0], [1, 1], 1);
    }

    #[test]
    #[should_panic = "dilation must be non-zero"]
    fn conv_transpose_options_dilation_zero() {
        let _opt = ConvTransposeOptions::new([1, 1], [0, 0], [0, 0], [0, 0], 1);
    }

    #[test]
    #[should_panic = "groups must be non-zero"]
    fn conv_transpose_options_groups_zero() {
        let _opt = ConvTransposeOptions::new([1, 1], [0, 0], [0, 0], [1, 1], 0);
    }

    #[test]
    #[should_panic = "stride must be non-zero"]
    fn deform_conv_options_stride_zero() {
        let _opt = DeformConvOptions::new([0, 1], [0, 0], [1, 1], 1, 1);
    }

    #[test]
    #[should_panic = "dilation must be non-zero"]
    fn deform_conv_options_dilation_zero() {
        let _opt = DeformConvOptions::new([1, 1], [0, 0], [0, 0], 1, 1);
    }

    #[test]
    #[should_panic = "weight groups must be non-zero"]
    fn deform_conv_options_weights_groups_zero() {
        let _opt = DeformConvOptions::new([1, 1], [0, 0], [1, 1], 0, 1);
    }

    #[test]
    #[should_panic = "offset groups must be non-zero"]
    fn deform_conv_options_offset_groups_zero() {
        let _opt = DeformConvOptions::new([1, 1], [0, 0], [1, 1], 1, 0);
    }

    #[test]
    #[should_panic = "stride must be non-zero"]
    fn unfold_options_stride_zero() {
        let _opt = UnfoldOptions::new([0, 1], [0, 0], [1, 1]);
    }

    #[test]
    #[should_panic = "dilation must be non-zero"]
    fn unfold_options_dilation_zero() {
        let _opt = UnfoldOptions::new([1, 1], [0, 0], [0, 0]);
    }
}