torsh-python 0.1.2

Python bindings for ToRSh - PyTorch-compatible deep learning in Rust
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
//! Input validation utilities for Python bindings

use crate::error::PyResult;
use pyo3::prelude::*;

/// Validate that a shape is valid (all dimensions > 0)
pub fn validate_shape(shape: &[usize]) -> PyResult<()> {
    for (i, &dim) in shape.iter().enumerate() {
        if dim == 0 {
            return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
                "Invalid shape: dimension {} cannot be zero",
                i
            )));
        }
    }
    Ok(())
}

/// Validate that an index is within bounds for a given dimension
pub fn validate_index(index: i64, dim_size: usize) -> PyResult<usize> {
    let positive_index = if index < 0 {
        let abs_index = (-index) as usize;
        if abs_index > dim_size {
            return Err(PyErr::new::<pyo3::exceptions::PyIndexError, _>(format!(
                "Index {} is out of bounds for dimension with size {}",
                index, dim_size
            )));
        }
        dim_size - abs_index
    } else {
        let pos_index = index as usize;
        if pos_index >= dim_size {
            return Err(PyErr::new::<pyo3::exceptions::PyIndexError, _>(format!(
                "Index {} is out of bounds for dimension with size {}",
                index, dim_size
            )));
        }
        pos_index
    };
    Ok(positive_index)
}

/// Validate that dimensions are compatible for broadcasting
pub fn validate_broadcast_shapes(shape1: &[usize], shape2: &[usize]) -> PyResult<Vec<usize>> {
    let mut result_shape = Vec::new();
    let max_dims = shape1.len().max(shape2.len());

    for i in 0..max_dims {
        let dim1 = if i < shape1.len() {
            shape1[shape1.len() - 1 - i]
        } else {
            1
        };
        let dim2 = if i < shape2.len() {
            shape2[shape2.len() - 1 - i]
        } else {
            1
        };

        if dim1 == dim2 || dim1 == 1 || dim2 == 1 {
            result_shape.push(dim1.max(dim2));
        } else {
            return Err(PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!(
                "Cannot broadcast shapes {:?} and {:?}",
                shape1, shape2
            )));
        }
    }

    result_shape.reverse();
    Ok(result_shape)
}

/// Validate that a learning rate is positive
pub fn validate_learning_rate(lr: f32) -> PyResult<()> {
    if lr <= 0.0 {
        return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(
            "Learning rate must be positive",
        ));
    }
    Ok(())
}

/// Validate that momentum is in valid range [0, 1]
pub fn validate_momentum(momentum: f32) -> PyResult<()> {
    if !(0.0..=1.0).contains(&momentum) {
        return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(
            "Momentum must be in range [0, 1]",
        ));
    }
    Ok(())
}

/// Validate that weight decay is non-negative
pub fn validate_weight_decay(weight_decay: f32) -> PyResult<()> {
    if weight_decay < 0.0 {
        return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(
            "Weight decay must be non-negative",
        ));
    }
    Ok(())
}

/// Validate that epsilon is positive
pub fn validate_epsilon(eps: f32) -> PyResult<()> {
    if eps <= 0.0 {
        return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(
            "Epsilon must be positive",
        ));
    }
    Ok(())
}

/// Validate beta parameters for Adam-like optimizers
pub fn validate_betas(betas: (f32, f32)) -> PyResult<()> {
    let (beta1, beta2) = betas;
    if !(0.0..1.0).contains(&beta1) {
        return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(
            "Beta1 must be in range [0, 1)",
        ));
    }
    if !(0.0..1.0).contains(&beta2) {
        return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(
            "Beta2 must be in range [0, 1)",
        ));
    }
    Ok(())
}

/// Validate that tensor dimensions match for operations
pub fn validate_tensor_shapes_match(shape1: &[usize], shape2: &[usize]) -> PyResult<()> {
    if shape1 != shape2 {
        return Err(PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!(
            "Tensor shapes do not match: {:?} vs {:?}",
            shape1, shape2
        )));
    }
    Ok(())
}

/// Validate that a dimension index is valid for a tensor
pub fn validate_dimension(dim: i32, ndim: usize) -> PyResult<usize> {
    let positive_dim = if dim < 0 {
        let abs_dim = (-dim) as usize;
        if abs_dim > ndim {
            return Err(PyErr::new::<pyo3::exceptions::PyIndexError, _>(format!(
                "Dimension {} is out of bounds for tensor with {} dimensions",
                dim, ndim
            )));
        }
        ndim - abs_dim
    } else {
        let pos_dim = dim as usize;
        if pos_dim >= ndim {
            return Err(PyErr::new::<pyo3::exceptions::PyIndexError, _>(format!(
                "Dimension {} is out of bounds for tensor with {} dimensions",
                dim, ndim
            )));
        }
        pos_dim
    };
    Ok(positive_dim)
}

/// Validate that parameters list is not empty
pub fn validate_parameters_not_empty<T>(params: &[T]) -> PyResult<()> {
    if params.is_empty() {
        return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(
            "Parameters list cannot be empty",
        ));
    }
    Ok(())
}

/// Validate dropout probability is in valid range [0, 1]
pub fn validate_dropout_probability(p: f32) -> PyResult<()> {
    if !(0.0..=1.0).contains(&p) {
        return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
            "Dropout probability must be in range [0, 1], got {}",
            p
        )));
    }
    Ok(())
}

/// Validate kernel size is positive
pub fn validate_kernel_size(kernel_size: usize, name: &str) -> PyResult<()> {
    if kernel_size == 0 {
        return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
            "{} must be positive, got 0",
            name
        )));
    }
    Ok(())
}

/// Validate stride is positive
pub fn validate_stride(stride: usize, name: &str) -> PyResult<()> {
    if stride == 0 {
        return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
            "{} must be positive, got 0",
            name
        )));
    }
    Ok(())
}

/// Validate that input tensor has expected number of dimensions
pub fn validate_tensor_ndim(
    actual_ndim: usize,
    expected_ndim: usize,
    op_name: &str,
) -> PyResult<()> {
    if actual_ndim != expected_ndim {
        return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
            "{} expects {}D input, got {}D",
            op_name, expected_ndim, actual_ndim
        )));
    }
    Ok(())
}

/// Validate that input tensor has at least minimum number of dimensions
pub fn validate_tensor_min_ndim(
    actual_ndim: usize,
    min_ndim: usize,
    op_name: &str,
) -> PyResult<()> {
    if actual_ndim < min_ndim {
        return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
            "{} expects at least {}D input, got {}D",
            op_name, min_ndim, actual_ndim
        )));
    }
    Ok(())
}

/// Validate that number of features matches expected value
pub fn validate_num_features(
    actual_features: usize,
    expected_features: usize,
    layer_name: &str,
) -> PyResult<()> {
    if actual_features != expected_features {
        return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
            "{} expected {} features, got {}",
            layer_name, expected_features, actual_features
        )));
    }
    Ok(())
}

/// Validate that a value is finite (not NaN or infinity)
pub fn validate_finite(value: f32, name: &str) -> PyResult<()> {
    if !value.is_finite() {
        return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
            "{} must be finite, got {}",
            name, value
        )));
    }
    Ok(())
}

/// Validate that a range is valid (start < end)
pub fn validate_range(start: usize, end: usize, name: &str) -> PyResult<()> {
    if start >= end {
        return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
            "Invalid range for {}: start ({}) must be less than end ({})",
            name, start, end
        )));
    }
    Ok(())
}

/// Validate pooling output size calculation
pub fn validate_pooling_output_size(
    input_size: usize,
    kernel_size: usize,
    stride: usize,
    padding: usize,
    dilation: usize,
) -> PyResult<usize> {
    if kernel_size == 0 || stride == 0 {
        return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(
            "Kernel size and stride must be positive",
        ));
    }

    let effective_kernel = dilation * (kernel_size - 1) + 1;
    if input_size + 2 * padding < effective_kernel {
        return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
            "Input size {} (with padding {}) is too small for kernel size {} (with dilation {})",
            input_size, padding, kernel_size, dilation
        )));
    }

    let output_size = (input_size + 2 * padding - effective_kernel) / stride + 1;
    Ok(output_size)
}

/// Validate convolution parameters
pub fn validate_conv_params(
    in_channels: usize,
    out_channels: usize,
    kernel_size: usize,
) -> PyResult<()> {
    if in_channels == 0 {
        return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(
            "in_channels must be positive",
        ));
    }
    if out_channels == 0 {
        return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(
            "out_channels must be positive",
        ));
    }
    if kernel_size == 0 {
        return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(
            "kernel_size must be positive",
        ));
    }
    Ok(())
}

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

    // =============================================================================
    // Shape Validation Tests
    // =============================================================================

    #[test]
    fn test_validate_shape_valid() {
        assert!(validate_shape(&[1, 2, 3]).is_ok());
        assert!(validate_shape(&[10, 20, 30, 40]).is_ok());
    }

    #[test]
    fn test_validate_shape_with_zero() {
        assert!(validate_shape(&[1, 0, 3]).is_err());
        assert!(validate_shape(&[0]).is_err());
    }

    #[test]
    fn test_validate_shape_empty() {
        // Empty shape (scalar) should be valid
        assert!(validate_shape(&[]).is_ok());
    }

    // =============================================================================
    // Index Validation Tests
    // =============================================================================

    #[test]
    fn test_validate_index_positive() {
        assert_eq!(
            validate_index(0, 10).expect("validate index should succeed"),
            0
        );
        assert_eq!(
            validate_index(5, 10).expect("validate index should succeed"),
            5
        );
        assert_eq!(
            validate_index(9, 10).expect("validate index should succeed"),
            9
        );
    }

    #[test]
    fn test_validate_index_negative() {
        assert_eq!(
            validate_index(-1, 10).expect("validate index should succeed"),
            9
        );
        assert_eq!(
            validate_index(-5, 10).expect("validate index should succeed"),
            5
        );
        assert_eq!(
            validate_index(-10, 10).expect("validate index should succeed"),
            0
        );
    }

    #[test]
    fn test_validate_index_out_of_bounds_positive() {
        assert!(validate_index(10, 10).is_err());
        assert!(validate_index(100, 10).is_err());
    }

    #[test]
    fn test_validate_index_out_of_bounds_negative() {
        assert!(validate_index(-11, 10).is_err());
        assert!(validate_index(-100, 10).is_err());
    }

    // =============================================================================
    // Broadcasting Tests
    // =============================================================================

    #[test]
    fn test_validate_broadcast_shapes_compatible() {
        assert_eq!(
            validate_broadcast_shapes(&[3, 4], &[3, 4])
                .expect("validate broadcast shapes should succeed"),
            vec![3, 4]
        );
        assert_eq!(
            validate_broadcast_shapes(&[3, 1], &[3, 4])
                .expect("validate broadcast shapes should succeed"),
            vec![3, 4]
        );
        assert_eq!(
            validate_broadcast_shapes(&[1, 4], &[3, 4])
                .expect("validate broadcast shapes should succeed"),
            vec![3, 4]
        );
        assert_eq!(
            validate_broadcast_shapes(&[3, 4], &[4])
                .expect("validate broadcast shapes should succeed"),
            vec![3, 4]
        );
    }

    #[test]
    fn test_validate_broadcast_shapes_incompatible() {
        assert!(validate_broadcast_shapes(&[3, 4], &[3, 5]).is_err());
        assert!(validate_broadcast_shapes(&[2, 3], &[3, 4]).is_err());
    }

    // =============================================================================
    // Learning Rate Validation Tests
    // =============================================================================

    #[test]
    fn test_validate_learning_rate_valid() {
        assert!(validate_learning_rate(0.001).is_ok());
        assert!(validate_learning_rate(0.1).is_ok());
        assert!(validate_learning_rate(1.0).is_ok());
        assert!(validate_learning_rate(10.0).is_ok());
    }

    #[test]
    fn test_validate_learning_rate_invalid() {
        assert!(validate_learning_rate(0.0).is_err());
        assert!(validate_learning_rate(-0.1).is_err());
    }

    // =============================================================================
    // Momentum Validation Tests
    // =============================================================================

    #[test]
    fn test_validate_momentum_valid() {
        assert!(validate_momentum(0.0).is_ok());
        assert!(validate_momentum(0.5).is_ok());
        assert!(validate_momentum(0.9).is_ok());
        assert!(validate_momentum(1.0).is_ok());
    }

    #[test]
    fn test_validate_momentum_invalid() {
        assert!(validate_momentum(-0.1).is_err());
        assert!(validate_momentum(1.1).is_err());
    }

    // =============================================================================
    // Weight Decay Validation Tests
    // =============================================================================

    #[test]
    fn test_validate_weight_decay_valid() {
        assert!(validate_weight_decay(0.0).is_ok());
        assert!(validate_weight_decay(0.01).is_ok());
        assert!(validate_weight_decay(1.0).is_ok());
    }

    #[test]
    fn test_validate_weight_decay_invalid() {
        assert!(validate_weight_decay(-0.1).is_err());
    }

    // =============================================================================
    // Epsilon Validation Tests
    // =============================================================================

    #[test]
    fn test_validate_epsilon_valid() {
        assert!(validate_epsilon(1e-8).is_ok());
        assert!(validate_epsilon(1e-5).is_ok());
        assert!(validate_epsilon(0.1).is_ok());
    }

    #[test]
    fn test_validate_epsilon_invalid() {
        assert!(validate_epsilon(0.0).is_err());
        assert!(validate_epsilon(-1e-8).is_err());
    }

    // =============================================================================
    // Beta Parameters Validation Tests
    // =============================================================================

    #[test]
    fn test_validate_betas_valid() {
        assert!(validate_betas((0.0, 0.0)).is_ok());
        assert!(validate_betas((0.9, 0.999)).is_ok());
        assert!(validate_betas((0.5, 0.5)).is_ok());
    }

    #[test]
    fn test_validate_betas_invalid() {
        assert!(validate_betas((-0.1, 0.5)).is_err());
        assert!(validate_betas((0.5, 1.0)).is_err());
        assert!(validate_betas((1.0, 0.5)).is_err());
        assert!(validate_betas((1.1, 0.5)).is_err());
    }

    // =============================================================================
    // Tensor Shape Matching Tests
    // =============================================================================

    #[test]
    fn test_validate_tensor_shapes_match_valid() {
        assert!(validate_tensor_shapes_match(&[3, 4], &[3, 4]).is_ok());
        assert!(validate_tensor_shapes_match(&[], &[]).is_ok());
    }

    #[test]
    fn test_validate_tensor_shapes_match_invalid() {
        assert!(validate_tensor_shapes_match(&[3, 4], &[3, 5]).is_err());
        assert!(validate_tensor_shapes_match(&[3, 4], &[4, 3]).is_err());
    }

    // =============================================================================
    // Dimension Validation Tests
    // =============================================================================

    #[test]
    fn test_validate_dimension_positive() {
        assert_eq!(
            validate_dimension(0, 4).expect("validate dimension should succeed"),
            0
        );
        assert_eq!(
            validate_dimension(2, 4).expect("validate dimension should succeed"),
            2
        );
        assert_eq!(
            validate_dimension(3, 4).expect("validate dimension should succeed"),
            3
        );
    }

    #[test]
    fn test_validate_dimension_negative() {
        assert_eq!(
            validate_dimension(-1, 4).expect("validate dimension should succeed"),
            3
        );
        assert_eq!(
            validate_dimension(-2, 4).expect("validate dimension should succeed"),
            2
        );
        assert_eq!(
            validate_dimension(-4, 4).expect("validate dimension should succeed"),
            0
        );
    }

    #[test]
    fn test_validate_dimension_out_of_bounds() {
        assert!(validate_dimension(4, 4).is_err());
        assert!(validate_dimension(-5, 4).is_err());
    }

    // =============================================================================
    // Parameters Validation Tests
    // =============================================================================

    #[test]
    fn test_validate_parameters_not_empty_valid() {
        assert!(validate_parameters_not_empty(&[1, 2, 3]).is_ok());
    }

    #[test]
    fn test_validate_parameters_not_empty_invalid() {
        let empty: &[i32] = &[];
        assert!(validate_parameters_not_empty(empty).is_err());
    }

    // =============================================================================
    // Dropout Probability Validation Tests
    // =============================================================================

    #[test]
    fn test_validate_dropout_probability_valid() {
        assert!(validate_dropout_probability(0.0).is_ok());
        assert!(validate_dropout_probability(0.5).is_ok());
        assert!(validate_dropout_probability(1.0).is_ok());
    }

    #[test]
    fn test_validate_dropout_probability_invalid() {
        assert!(validate_dropout_probability(-0.1).is_err());
        assert!(validate_dropout_probability(1.1).is_err());
    }

    // =============================================================================
    // Kernel Size Validation Tests
    // =============================================================================

    #[test]
    fn test_validate_kernel_size_valid() {
        assert!(validate_kernel_size(1, "kernel").is_ok());
        assert!(validate_kernel_size(3, "kernel").is_ok());
        assert!(validate_kernel_size(5, "kernel").is_ok());
    }

    #[test]
    fn test_validate_kernel_size_invalid() {
        assert!(validate_kernel_size(0, "kernel").is_err());
    }

    // =============================================================================
    // Stride Validation Tests
    // =============================================================================

    #[test]
    fn test_validate_stride_valid() {
        assert!(validate_stride(1, "stride").is_ok());
        assert!(validate_stride(2, "stride").is_ok());
    }

    #[test]
    fn test_validate_stride_invalid() {
        assert!(validate_stride(0, "stride").is_err());
    }

    // =============================================================================
    // Tensor NDim Validation Tests
    // =============================================================================

    #[test]
    fn test_validate_tensor_ndim_valid() {
        assert!(validate_tensor_ndim(4, 4, "conv2d").is_ok());
        assert!(validate_tensor_ndim(2, 2, "linear").is_ok());
    }

    #[test]
    fn test_validate_tensor_ndim_invalid() {
        assert!(validate_tensor_ndim(3, 4, "conv2d").is_err());
        assert!(validate_tensor_ndim(5, 4, "conv2d").is_err());
    }

    // =============================================================================
    // Tensor Min NDim Validation Tests
    // =============================================================================

    #[test]
    fn test_validate_tensor_min_ndim_valid() {
        assert!(validate_tensor_min_ndim(4, 2, "operation").is_ok());
        assert!(validate_tensor_min_ndim(2, 2, "operation").is_ok());
    }

    #[test]
    fn test_validate_tensor_min_ndim_invalid() {
        assert!(validate_tensor_min_ndim(1, 2, "operation").is_err());
    }

    // =============================================================================
    // Number of Features Validation Tests
    // =============================================================================

    #[test]
    fn test_validate_num_features_valid() {
        assert!(validate_num_features(64, 64, "BatchNorm").is_ok());
    }

    #[test]
    fn test_validate_num_features_invalid() {
        assert!(validate_num_features(32, 64, "BatchNorm").is_err());
    }

    // =============================================================================
    // Finite Value Validation Tests
    // =============================================================================

    #[test]
    fn test_validate_finite_valid() {
        assert!(validate_finite(0.0, "value").is_ok());
        assert!(validate_finite(1.0, "value").is_ok());
        assert!(validate_finite(-1.0, "value").is_ok());
    }

    #[test]
    fn test_validate_finite_invalid() {
        assert!(validate_finite(f32::NAN, "value").is_err());
        assert!(validate_finite(f32::INFINITY, "value").is_err());
        assert!(validate_finite(f32::NEG_INFINITY, "value").is_err());
    }

    // =============================================================================
    // Range Validation Tests
    // =============================================================================

    #[test]
    fn test_validate_range_valid() {
        assert!(validate_range(0, 10, "range").is_ok());
        assert!(validate_range(5, 10, "range").is_ok());
    }

    #[test]
    fn test_validate_range_invalid() {
        assert!(validate_range(10, 10, "range").is_err());
        assert!(validate_range(10, 5, "range").is_err());
    }

    // =============================================================================
    // Pooling Output Size Validation Tests
    // =============================================================================

    #[test]
    fn test_validate_pooling_output_size_valid() {
        // Input: 28, Kernel: 2, Stride: 2, Padding: 0, Dilation: 1
        // Output: (28 + 0 - 2) / 2 + 1 = 14
        assert_eq!(
            validate_pooling_output_size(28, 2, 2, 0, 1)
                .expect("validate pooling output size should succeed"),
            14
        );

        // Input: 32, Kernel: 3, Stride: 1, Padding: 1, Dilation: 1
        // Output: (32 + 2 - 3) / 1 + 1 = 32
        assert_eq!(
            validate_pooling_output_size(32, 3, 1, 1, 1)
                .expect("validate pooling output size should succeed"),
            32
        );
    }

    #[test]
    fn test_validate_pooling_output_size_invalid_zero_kernel() {
        assert!(validate_pooling_output_size(28, 0, 2, 0, 1).is_err());
    }

    #[test]
    fn test_validate_pooling_output_size_invalid_zero_stride() {
        assert!(validate_pooling_output_size(28, 2, 0, 0, 1).is_err());
    }

    #[test]
    fn test_validate_pooling_output_size_invalid_too_small() {
        // Input: 2, Kernel: 5, Stride: 1, Padding: 0, Dilation: 1
        // Input too small for kernel
        assert!(validate_pooling_output_size(2, 5, 1, 0, 1).is_err());
    }

    // =============================================================================
    // Convolution Parameters Validation Tests
    // =============================================================================

    #[test]
    fn test_validate_conv_params_valid() {
        assert!(validate_conv_params(3, 64, 3).is_ok());
        assert!(validate_conv_params(64, 128, 5).is_ok());
    }

    #[test]
    fn test_validate_conv_params_invalid_in_channels() {
        assert!(validate_conv_params(0, 64, 3).is_err());
    }

    #[test]
    fn test_validate_conv_params_invalid_out_channels() {
        assert!(validate_conv_params(3, 0, 3).is_err());
    }

    #[test]
    fn test_validate_conv_params_invalid_kernel_size() {
        assert!(validate_conv_params(3, 64, 0).is_err());
    }
}