torsh-backend 0.1.2

Backend abstraction layer for ToRSh
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
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
//! cuDNN descriptor management
//!
//! This module provides wrapper types for various cuDNN descriptors including
//! tensor, filter, convolution, activation, and pooling descriptors.

// Allow unused imports as they are used conditionally with the cudnn feature
#![allow(unused_imports)]

use super::types::{ActivationMode, ConvolutionMode, NanPropagation, PoolingMode};
use crate::cuda::error::{CudaError, CudaResult};
use torsh_core::DType;

#[cfg(feature = "cudnn")]
use cudnn_sys::*;

// Import compatibility layer for missing cudnn-sys functions
#[cfg(feature = "cudnn")]
use super::compat::{
    cudnnActivationDescriptor_t, cudnnCreateActivationDescriptor, cudnnDestroyActivationDescriptor,
    cudnnMathType_t, cudnnSetActivationDescriptor, cudnnSetConvolutionMathType,
};

/// Convert compat pooling mode to cudnn_sys pooling mode
#[cfg(feature = "cudnn")]
fn to_sys_pooling_mode(mode: super::compat::cudnnPoolingMode_t) -> cudnnPoolingMode_t {
    match mode {
        super::compat::cudnnPoolingMode_t::CUDNN_POOLING_MAX => {
            cudnnPoolingMode_t::CUDNN_POOLING_MAX
        }
        super::compat::cudnnPoolingMode_t::CUDNN_POOLING_AVERAGE_COUNT_INCLUDE_PADDING => {
            cudnnPoolingMode_t::CUDNN_POOLING_AVERAGE_COUNT_INCLUDE_PADDING
        }
        super::compat::cudnnPoolingMode_t::CUDNN_POOLING_AVERAGE_COUNT_EXCLUDE_PADDING => {
            cudnnPoolingMode_t::CUDNN_POOLING_AVERAGE_COUNT_EXCLUDE_PADDING
        }
        // Map deterministic to max (cudnn_sys 0.0.3 doesn't have deterministic variant)
        super::compat::cudnnPoolingMode_t::CUDNN_POOLING_MAX_DETERMINISTIC => {
            cudnnPoolingMode_t::CUDNN_POOLING_MAX
        }
    }
}

/// Tensor descriptor for cuDNN operations
///
/// Wraps cudnnTensorDescriptor_t to provide safe tensor description
/// for cuDNN operations with automatic resource management.
///
/// # Examples
///
/// ```rust,ignore
/// use torsh_backend::cuda::cudnn::TensorDescriptor;
/// use torsh_core::DType;
///
/// let mut desc = TensorDescriptor::new()?;
/// desc.set_4d(DType::F32, 1, 3, 224, 224)?;
/// ```
pub struct TensorDescriptor {
    #[cfg(feature = "cudnn")]
    desc: cudnnTensorDescriptor_t,
    #[cfg(not(feature = "cudnn"))]
    _phantom: std::marker::PhantomData<()>,
}

impl TensorDescriptor {
    /// Create new tensor descriptor
    ///
    /// # Returns
    ///
    /// A new `TensorDescriptor` instance on success, or an error if creation fails.
    ///
    /// # Errors
    ///
    /// Returns `CudaError::CudnnError` if descriptor creation fails.
    pub fn new() -> CudaResult<Self> {
        #[cfg(feature = "cudnn")]
        {
            let mut desc: cudnnTensorDescriptor_t = std::ptr::null_mut();
            let status = unsafe { cudnnCreateTensorDescriptor(&mut desc) };
            if status != cudnnStatus_t::CUDNN_STATUS_SUCCESS {
                return Err(CudaError::CudnnError(format!(
                    "Failed to create tensor descriptor: {:?}",
                    status
                )));
            }
            Ok(Self { desc })
        }
        #[cfg(not(feature = "cudnn"))]
        {
            Ok(Self {
                _phantom: std::marker::PhantomData,
            })
        }
    }

    /// Set tensor descriptor with NCHW format
    ///
    /// Configures the tensor descriptor for 4D tensors in NCHW format.
    ///
    /// # Arguments
    ///
    /// * `dtype` - Data type of the tensor elements
    /// * `n` - Batch size
    /// * `c` - Number of channels
    /// * `h` - Height
    /// * `w` - Width
    ///
    /// # Returns
    ///
    /// `Ok(())` on success, or an error if configuration fails.
    pub fn set_4d(&mut self, dtype: DType, n: i32, c: i32, h: i32, w: i32) -> CudaResult<()> {
        #[cfg(feature = "cudnn")]
        {
            let cudnn_type = match dtype {
                DType::F32 => cudnnDataType_t::CUDNN_DATA_FLOAT,
                DType::F64 => cudnnDataType_t::CUDNN_DATA_DOUBLE,
                DType::F16 => cudnnDataType_t::CUDNN_DATA_HALF,
                _ => {
                    return Err(CudaError::CudnnError(format!(
                        "Unsupported dtype for cuDNN: {:?}",
                        dtype
                    )))
                }
            };

            let status = unsafe {
                cudnnSetTensor4dDescriptor(
                    self.desc,
                    cudnnTensorFormat_t::CUDNN_TENSOR_NCHW,
                    cudnn_type,
                    n,
                    c,
                    h,
                    w,
                )
            };

            if status != cudnnStatus_t::CUDNN_STATUS_SUCCESS {
                return Err(CudaError::CudnnError(format!(
                    "Failed to set tensor descriptor: {:?}",
                    status
                )));
            }
            Ok(())
        }
        #[cfg(not(feature = "cudnn"))]
        {
            let _ = (dtype, n, c, h, w);
            Err(CudaError::CudnnError(
                "cuDNN not available - feature not enabled".to_string(),
            ))
        }
    }

    /// Set tensor descriptor with NHWC format
    ///
    /// Configures the tensor descriptor for 4D tensors in NHWC format.
    ///
    /// # Arguments
    ///
    /// * `dtype` - Data type of the tensor elements
    /// * `n` - Batch size
    /// * `h` - Height
    /// * `w` - Width
    /// * `c` - Number of channels
    pub fn set_4d_nhwc(&mut self, dtype: DType, n: i32, h: i32, w: i32, c: i32) -> CudaResult<()> {
        #[cfg(feature = "cudnn")]
        {
            let cudnn_type = match dtype {
                DType::F32 => cudnnDataType_t::CUDNN_DATA_FLOAT,
                DType::F64 => cudnnDataType_t::CUDNN_DATA_DOUBLE,
                DType::F16 => cudnnDataType_t::CUDNN_DATA_HALF,
                _ => {
                    return Err(CudaError::CudnnError(format!(
                        "Unsupported dtype for cuDNN: {:?}",
                        dtype
                    )))
                }
            };

            let status = unsafe {
                cudnnSetTensor4dDescriptor(
                    self.desc,
                    cudnnTensorFormat_t::CUDNN_TENSOR_NHWC,
                    cudnn_type,
                    n,
                    c,
                    h,
                    w,
                )
            };

            if status != cudnnStatus_t::CUDNN_STATUS_SUCCESS {
                return Err(CudaError::CudnnError(format!(
                    "Failed to set tensor descriptor: {:?}",
                    status
                )));
            }
            Ok(())
        }
        #[cfg(not(feature = "cudnn"))]
        {
            let _ = (dtype, n, h, w, c);
            Err(CudaError::CudnnError(
                "cuDNN not available - feature not enabled".to_string(),
            ))
        }
    }

    /// Set tensor descriptor with arbitrary dimensions
    ///
    /// Configures the tensor descriptor for tensors with arbitrary dimensions.
    ///
    /// # Arguments
    ///
    /// * `dtype` - Data type of the tensor elements
    /// * `dims` - Dimension sizes
    /// * `strides` - Stride values
    pub fn set_nd(&mut self, dtype: DType, dims: &[i32], strides: &[i32]) -> CudaResult<()> {
        #[cfg(feature = "cudnn")]
        {
            if dims.len() != strides.len() {
                return Err(CudaError::CudnnError(
                    "Dimensions and strides must have the same length".to_string(),
                ));
            }

            let cudnn_type = match dtype {
                DType::F32 => cudnnDataType_t::CUDNN_DATA_FLOAT,
                DType::F64 => cudnnDataType_t::CUDNN_DATA_DOUBLE,
                DType::F16 => cudnnDataType_t::CUDNN_DATA_HALF,
                _ => {
                    return Err(CudaError::CudnnError(format!(
                        "Unsupported dtype for cuDNN: {:?}",
                        dtype
                    )))
                }
            };

            let status = unsafe {
                cudnnSetTensorNdDescriptor(
                    self.desc,
                    cudnn_type,
                    dims.len() as i32,
                    dims.as_ptr(),
                    strides.as_ptr(),
                )
            };

            if status != cudnnStatus_t::CUDNN_STATUS_SUCCESS {
                return Err(CudaError::CudnnError(format!(
                    "Failed to set tensor descriptor: {:?}",
                    status
                )));
            }
            Ok(())
        }
        #[cfg(not(feature = "cudnn"))]
        {
            let _ = (dtype, dims, strides);
            Err(CudaError::CudnnError(
                "cuDNN not available - feature not enabled".to_string(),
            ))
        }
    }

    /// Get the raw cuDNN tensor descriptor
    #[cfg(feature = "cudnn")]
    pub fn raw(&self) -> cudnnTensorDescriptor_t {
        self.desc
    }
}

impl Drop for TensorDescriptor {
    fn drop(&mut self) {
        #[cfg(feature = "cudnn")]
        {
            if !self.desc.is_null() {
                unsafe {
                    let _status = cudnnDestroyTensorDescriptor(self.desc);
                }
            }
        }
    }
}

/// Filter (kernel) descriptor for convolution operations
///
/// Wraps cudnnFilterDescriptor_t to provide safe filter description
/// for convolution operations with automatic resource management.
pub struct FilterDescriptor {
    #[cfg(feature = "cudnn")]
    desc: cudnnFilterDescriptor_t,
    #[cfg(not(feature = "cudnn"))]
    _phantom: std::marker::PhantomData<()>,
}

impl FilterDescriptor {
    /// Create new filter descriptor
    pub fn new() -> CudaResult<Self> {
        #[cfg(feature = "cudnn")]
        {
            let mut desc: cudnnFilterDescriptor_t = std::ptr::null_mut();
            let status = unsafe { cudnnCreateFilterDescriptor(&mut desc) };
            if status != cudnnStatus_t::CUDNN_STATUS_SUCCESS {
                return Err(CudaError::CudnnError(format!(
                    "Failed to create filter descriptor: {:?}",
                    status
                )));
            }
            Ok(Self { desc })
        }
        #[cfg(not(feature = "cudnn"))]
        {
            Ok(Self {
                _phantom: std::marker::PhantomData,
            })
        }
    }

    /// Set filter descriptor for 2D convolution
    ///
    /// # Arguments
    ///
    /// * `dtype` - Data type of the filter elements
    /// * `k` - Number of output feature maps
    /// * `c` - Number of input feature maps
    /// * `h` - Filter height
    /// * `w` - Filter width
    pub fn set_4d(&mut self, dtype: DType, k: i32, c: i32, h: i32, w: i32) -> CudaResult<()> {
        #[cfg(feature = "cudnn")]
        {
            let cudnn_type = match dtype {
                DType::F32 => cudnnDataType_t::CUDNN_DATA_FLOAT,
                DType::F64 => cudnnDataType_t::CUDNN_DATA_DOUBLE,
                DType::F16 => cudnnDataType_t::CUDNN_DATA_HALF,
                _ => {
                    return Err(CudaError::CudnnError(format!(
                        "Unsupported dtype for cuDNN: {:?}",
                        dtype
                    )))
                }
            };

            let status = unsafe {
                // cudnn-sys 0.0.3 doesn't take tensor format for Filter4dDescriptor
                cudnnSetFilter4dDescriptor(self.desc, cudnn_type, k, c, h, w)
            };

            if status != cudnnStatus_t::CUDNN_STATUS_SUCCESS {
                return Err(CudaError::CudnnError(format!(
                    "Failed to set filter descriptor: {:?}",
                    status
                )));
            }
            Ok(())
        }
        #[cfg(not(feature = "cudnn"))]
        {
            let _ = (dtype, k, c, h, w);
            Err(CudaError::CudnnError(
                "cuDNN not available - feature not enabled".to_string(),
            ))
        }
    }

    /// Set filter descriptor with arbitrary dimensions
    ///
    /// # Arguments
    ///
    /// * `dtype` - Data type of the filter elements
    /// * `dims` - Filter dimensions
    pub fn set_nd(&mut self, dtype: DType, dims: &[i32]) -> CudaResult<()> {
        #[cfg(feature = "cudnn")]
        {
            let cudnn_type = match dtype {
                DType::F32 => cudnnDataType_t::CUDNN_DATA_FLOAT,
                DType::F64 => cudnnDataType_t::CUDNN_DATA_DOUBLE,
                DType::F16 => cudnnDataType_t::CUDNN_DATA_HALF,
                _ => {
                    return Err(CudaError::CudnnError(format!(
                        "Unsupported dtype for cuDNN: {:?}",
                        dtype
                    )))
                }
            };

            let status = unsafe {
                // cudnn-sys 0.0.3 doesn't take tensor format for FilterNdDescriptor
                cudnnSetFilterNdDescriptor(self.desc, cudnn_type, dims.len() as i32, dims.as_ptr())
            };

            if status != cudnnStatus_t::CUDNN_STATUS_SUCCESS {
                return Err(CudaError::CudnnError(format!(
                    "Failed to set filter descriptor: {:?}",
                    status
                )));
            }
            Ok(())
        }
        #[cfg(not(feature = "cudnn"))]
        {
            let _ = (dtype, dims);
            Err(CudaError::CudnnError(
                "cuDNN not available - feature not enabled".to_string(),
            ))
        }
    }

    /// Get the raw cuDNN filter descriptor
    #[cfg(feature = "cudnn")]
    pub fn raw(&self) -> cudnnFilterDescriptor_t {
        self.desc
    }
}

impl Drop for FilterDescriptor {
    fn drop(&mut self) {
        #[cfg(feature = "cudnn")]
        {
            if !self.desc.is_null() {
                unsafe {
                    let _status = cudnnDestroyFilterDescriptor(self.desc);
                }
            }
        }
    }
}

/// Convolution descriptor
///
/// Wraps cudnnConvolutionDescriptor_t to provide safe convolution description
/// for convolution operations with automatic resource management.
pub struct ConvolutionDescriptor {
    #[cfg(feature = "cudnn")]
    desc: cudnnConvolutionDescriptor_t,
    #[cfg(not(feature = "cudnn"))]
    _phantom: std::marker::PhantomData<()>,
}

impl ConvolutionDescriptor {
    /// Create new convolution descriptor
    pub fn new() -> CudaResult<Self> {
        #[cfg(feature = "cudnn")]
        {
            let mut desc: cudnnConvolutionDescriptor_t = std::ptr::null_mut();
            let status = unsafe { cudnnCreateConvolutionDescriptor(&mut desc) };
            if status != cudnnStatus_t::CUDNN_STATUS_SUCCESS {
                return Err(CudaError::CudnnError(format!(
                    "Failed to create convolution descriptor: {:?}",
                    status
                )));
            }
            Ok(Self { desc })
        }
        #[cfg(not(feature = "cudnn"))]
        {
            Ok(Self {
                _phantom: std::marker::PhantomData,
            })
        }
    }

    /// Set 2D convolution descriptor
    ///
    /// # Arguments
    ///
    /// * `pad_h` - Zero-padding height
    /// * `pad_w` - Zero-padding width
    /// * `stride_h` - Vertical stride
    /// * `stride_w` - Horizontal stride
    /// * `dilation_h` - Vertical dilation
    /// * `dilation_w` - Horizontal dilation
    /// * `mode` - Convolution mode
    pub fn set_2d(
        &mut self,
        pad_h: i32,
        pad_w: i32,
        stride_h: i32,
        stride_w: i32,
        dilation_h: i32,
        dilation_w: i32,
        mode: ConvolutionMode,
    ) -> CudaResult<()> {
        #[cfg(feature = "cudnn")]
        {
            let cudnn_mode = mode.to_cudnn();

            // Convert to cudnn_sys type directly
            let mode_value = match cudnn_mode {
                crate::cuda::cudnn::compat::cudnnConvolutionMode_t::CUDNN_CONVOLUTION => {
                    cudnn_sys::cudnnConvolutionMode_t::CUDNN_CONVOLUTION
                }
                crate::cuda::cudnn::compat::cudnnConvolutionMode_t::CUDNN_CROSS_CORRELATION => {
                    cudnn_sys::cudnnConvolutionMode_t::CUDNN_CROSS_CORRELATION
                }
            };

            let status = unsafe {
                // cudnn-sys 0.0.3 doesn't take data type argument
                cudnnSetConvolution2dDescriptor(
                    self.desc, pad_h, pad_w, stride_h, stride_w, dilation_h, dilation_w, mode_value,
                )
            };

            if status != cudnnStatus_t::CUDNN_STATUS_SUCCESS {
                return Err(CudaError::CudnnError(format!(
                    "Failed to set convolution descriptor: {:?}",
                    status
                )));
            }
            Ok(())
        }
        #[cfg(not(feature = "cudnn"))]
        {
            let _ = (
                pad_h, pad_w, stride_h, stride_w, dilation_h, dilation_w, mode,
            );
            Err(CudaError::CudnnError(
                "cuDNN not available - feature not enabled".to_string(),
            ))
        }
    }

    /// Set convolution math type
    ///
    /// # Arguments
    ///
    /// * `math_type` - Math type for the convolution
    #[cfg(feature = "cudnn")]
    pub fn set_math_type(&mut self, math_type: cudnnMathType_t) -> CudaResult<()> {
        let status = unsafe { cudnnSetConvolutionMathType(self.desc, math_type) };
        if status != cudnnStatus_t::CUDNN_STATUS_SUCCESS {
            return Err(CudaError::CudnnError(format!(
                "Failed to set convolution math type: {:?}",
                status
            )));
        }
        Ok(())
    }

    /// Get the raw cuDNN convolution descriptor
    #[cfg(feature = "cudnn")]
    pub fn raw(&self) -> cudnnConvolutionDescriptor_t {
        self.desc
    }
}

impl Drop for ConvolutionDescriptor {
    fn drop(&mut self) {
        #[cfg(feature = "cudnn")]
        {
            if !self.desc.is_null() {
                unsafe {
                    let _status = cudnnDestroyConvolutionDescriptor(self.desc);
                }
            }
        }
    }
}

/// Activation descriptor for activation functions
///
/// Wraps cudnnActivationDescriptor_t to provide safe activation description
/// for activation operations with automatic resource management.
pub struct ActivationDescriptor {
    #[cfg(feature = "cudnn")]
    desc: cudnnActivationDescriptor_t,
    #[cfg(not(feature = "cudnn"))]
    _phantom: std::marker::PhantomData<()>,
}

impl ActivationDescriptor {
    /// Create new activation descriptor
    pub fn new() -> CudaResult<Self> {
        #[cfg(feature = "cudnn")]
        {
            let mut desc: cudnnActivationDescriptor_t = std::ptr::null_mut();
            let status = unsafe { cudnnCreateActivationDescriptor(&mut desc) };
            if status != cudnnStatus_t::CUDNN_STATUS_SUCCESS {
                return Err(CudaError::CudnnError(format!(
                    "Failed to create activation descriptor: {:?}",
                    status
                )));
            }
            Ok(Self { desc })
        }
        #[cfg(not(feature = "cudnn"))]
        {
            Ok(Self {
                _phantom: std::marker::PhantomData,
            })
        }
    }

    /// Set activation descriptor
    ///
    /// # Arguments
    ///
    /// * `mode` - Activation function mode
    /// * `nan_opt` - NaN propagation mode
    /// * `coef` - Coefficient for certain activation functions
    pub fn set(
        &mut self,
        mode: ActivationMode,
        nan_opt: NanPropagation,
        coef: f64,
    ) -> CudaResult<()> {
        #[cfg(feature = "cudnn")]
        {
            let cudnn_mode = mode.to_cudnn();
            let cudnn_nan = nan_opt.to_cudnn();

            let status =
                unsafe { cudnnSetActivationDescriptor(self.desc, cudnn_mode, cudnn_nan, coef) };

            if status != cudnnStatus_t::CUDNN_STATUS_SUCCESS {
                return Err(CudaError::CudnnError(format!(
                    "Failed to set activation descriptor: {:?}",
                    status
                )));
            }
            Ok(())
        }
        #[cfg(not(feature = "cudnn"))]
        {
            let _ = (mode, nan_opt, coef);
            Err(CudaError::CudnnError(
                "cuDNN not available - feature not enabled".to_string(),
            ))
        }
    }

    /// Get the raw cuDNN activation descriptor
    #[cfg(feature = "cudnn")]
    pub fn raw(&self) -> cudnnActivationDescriptor_t {
        self.desc
    }
}

impl Drop for ActivationDescriptor {
    fn drop(&mut self) {
        #[cfg(feature = "cudnn")]
        {
            if !self.desc.is_null() {
                unsafe {
                    let _status = cudnnDestroyActivationDescriptor(self.desc);
                }
            }
        }
    }
}

/// Pooling descriptor for pooling operations
///
/// Wraps cudnnPoolingDescriptor_t to provide safe pooling description
/// for pooling operations with automatic resource management.
pub struct PoolingDescriptor {
    #[cfg(feature = "cudnn")]
    desc: cudnnPoolingDescriptor_t,
    #[cfg(not(feature = "cudnn"))]
    _phantom: std::marker::PhantomData<()>,
}

impl PoolingDescriptor {
    /// Create new pooling descriptor
    pub fn new() -> CudaResult<Self> {
        #[cfg(feature = "cudnn")]
        {
            let mut desc: cudnnPoolingDescriptor_t = std::ptr::null_mut();
            let status = unsafe { cudnnCreatePoolingDescriptor(&mut desc) };
            if status != cudnnStatus_t::CUDNN_STATUS_SUCCESS {
                return Err(CudaError::CudnnError(format!(
                    "Failed to create pooling descriptor: {:?}",
                    status
                )));
            }
            Ok(Self { desc })
        }
        #[cfg(not(feature = "cudnn"))]
        {
            Ok(Self {
                _phantom: std::marker::PhantomData,
            })
        }
    }

    /// Set 2D pooling descriptor
    ///
    /// # Arguments
    ///
    /// * `mode` - Pooling mode
    /// * `nan_opt` - NaN propagation mode
    /// * `window_h` - Pooling window height
    /// * `window_w` - Pooling window width
    /// * `pad_h` - Zero-padding height
    /// * `pad_w` - Zero-padding width
    /// * `stride_h` - Vertical stride
    /// * `stride_w` - Horizontal stride
    pub fn set_2d(
        &mut self,
        mode: PoolingMode,
        nan_opt: NanPropagation,
        window_h: i32,
        window_w: i32,
        pad_h: i32,
        pad_w: i32,
        stride_h: i32,
        stride_w: i32,
    ) -> CudaResult<()> {
        #[cfg(feature = "cudnn")]
        {
            let compat_mode = mode.to_cudnn();
            let cudnn_mode = to_sys_pooling_mode(compat_mode);
            let _ = nan_opt; // cudnn-sys 0.0.3 doesn't support nan propagation option

            let status = unsafe {
                // cudnn-sys 0.0.3 doesn't take nan propagation argument
                cudnnSetPooling2dDescriptor(
                    self.desc, cudnn_mode, window_h, window_w, pad_h, pad_w, stride_h, stride_w,
                )
            };

            if status != cudnnStatus_t::CUDNN_STATUS_SUCCESS {
                return Err(CudaError::CudnnError(format!(
                    "Failed to set pooling descriptor: {:?}",
                    status
                )));
            }
            Ok(())
        }
        #[cfg(not(feature = "cudnn"))]
        {
            let _ = (
                mode, nan_opt, window_h, window_w, pad_h, pad_w, stride_h, stride_w,
            );
            Err(CudaError::CudnnError(
                "cuDNN not available - feature not enabled".to_string(),
            ))
        }
    }

    /// Get the raw cuDNN pooling descriptor
    #[cfg(feature = "cudnn")]
    pub fn raw(&self) -> cudnnPoolingDescriptor_t {
        self.desc
    }
}

impl Drop for PoolingDescriptor {
    fn drop(&mut self) {
        #[cfg(feature = "cudnn")]
        {
            if !self.desc.is_null() {
                unsafe {
                    let _status = cudnnDestroyPoolingDescriptor(self.desc);
                }
            }
        }
    }
}

// Default implementations for all descriptors
impl Default for TensorDescriptor {
    fn default() -> Self {
        Self::new().expect("Failed to create default tensor descriptor")
    }
}

impl Default for FilterDescriptor {
    fn default() -> Self {
        Self::new().expect("Failed to create default filter descriptor")
    }
}

impl Default for ConvolutionDescriptor {
    fn default() -> Self {
        Self::new().expect("Failed to create default convolution descriptor")
    }
}

impl Default for ActivationDescriptor {
    fn default() -> Self {
        Self::new().expect("Failed to create default activation descriptor")
    }
}

impl Default for PoolingDescriptor {
    fn default() -> Self {
        Self::new().expect("Failed to create default pooling descriptor")
    }
}

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

    #[test]
    fn test_tensor_descriptor_creation() {
        match TensorDescriptor::new() {
            Ok(_desc) => {
                // Descriptor created successfully
            }
            Err(_) => {
                // cuDNN might not be available in test environment
            }
        }
    }

    #[test]
    fn test_filter_descriptor_creation() {
        match FilterDescriptor::new() {
            Ok(_desc) => {
                // Descriptor created successfully
            }
            Err(_) => {
                // cuDNN might not be available in test environment
            }
        }
    }

    #[test]
    fn test_convolution_descriptor_creation() {
        match ConvolutionDescriptor::new() {
            Ok(_desc) => {
                // Descriptor created successfully
            }
            Err(_) => {
                // cuDNN might not be available in test environment
            }
        }
    }

    #[test]
    fn test_activation_descriptor_creation() {
        match ActivationDescriptor::new() {
            Ok(_desc) => {
                // Descriptor created successfully
            }
            Err(_) => {
                // cuDNN might not be available in test environment
            }
        }
    }

    #[test]
    fn test_pooling_descriptor_creation() {
        match PoolingDescriptor::new() {
            Ok(_desc) => {
                // Descriptor created successfully
            }
            Err(_) => {
                // cuDNN might not be available in test environment
            }
        }
    }

    #[test]
    fn test_tensor_descriptor_4d() {
        if let Ok(mut desc) = TensorDescriptor::new() {
            let result = desc.set_4d(DType::F32, 1, 3, 224, 224);
            // Result may fail if cuDNN is not available, which is acceptable in tests
            match result {
                Ok(_) => {
                    // Successfully set descriptor
                }
                Err(_) => {
                    // cuDNN might not be available
                }
            }
        }
    }

    #[test]
    fn test_default_implementations() {
        // Test that default implementations don't panic when cuDNN is available
        // When cuDNN is not available, these will panic by design
        #[cfg(feature = "cudnn")]
        {
            // Only test defaults when cuDNN feature is enabled
            // In practice, these might still fail if cuDNN runtime is not available
        }
    }
}