torsh-core 0.1.2

Core types and traits for ToRSh deep learning framework
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
//! GPU-Accelerated Shape Operations for Very Large Tensors
//!
//! This module provides GPU-accelerated implementations of shape operations
//! that benefit from parallel execution on large tensors. It uses intelligent
//! thresholding to decide when GPU acceleration is beneficial over CPU execution.
//!
//! # Design Principles
//!
//! 1. **Automatic Threshold Detection**: Operations automatically select GPU or CPU
//!    based on tensor size and operation complexity
//! 2. **Zero-Copy When Possible**: Minimize data transfer between CPU and GPU
//! 3. **Batched Operations**: Support batching multiple shape operations for efficiency
//! 4. **Fallback Support**: Graceful fallback to CPU when GPU is unavailable
//!
//! # Performance Benefits
//!
//! GPU acceleration provides significant benefits for:
//! - Broadcasting operations on tensors with >10M elements
//! - Complex reshape operations with non-trivial strides
//! - Batch validation of many shapes simultaneously
//! - Stride computation for very high-dimensional tensors (>10 dimensions)
//!
//! # SciRS2 POLICY Compliance
//!
//! This module strictly follows the SciRS2 POLICY by:
//! - Using `scirs2_core::gpu` for all GPU operations (NO direct CUDA/Metal)
//! - Using `scirs2_core::ndarray` for array operations (NO direct ndarray)
//! - Only using Rust standard library beyond scirs2-core
//!
//! # Example
//!
//! ```rust,ignore
//! use torsh_core::gpu_shape_ops::{GpuShapeAccelerator, AcceleratorConfig};
//!
//! // Create GPU accelerator with custom thresholds
//! let config = AcceleratorConfig::default()
//!     .with_broadcast_threshold(10_000_000);
//! let accelerator = GpuShapeAccelerator::new(config)?;
//!
//! // Automatically use GPU for large tensors, CPU for small ones
//! let shape1 = Shape::from_dims(vec![1000, 1000, 100])?;
//! let shape2 = Shape::from_dims(vec![1, 1000, 100])?;
//! let result = accelerator.broadcast(&shape1, &shape2)?;
//! ```

use crate::error::{Result, TorshError};
use crate::shape::Shape;

#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
#[cfg(feature = "std")]
use std::vec::Vec;

#[cfg(feature = "std")]
use std::sync::Arc;

/// Configuration for GPU shape accelerator
///
/// Controls when GPU acceleration is used vs CPU fallback.
#[derive(Debug, Clone)]
pub struct AcceleratorConfig {
    /// Minimum number of elements to use GPU for broadcasting (default: 10M)
    pub broadcast_threshold: usize,

    /// Minimum number of elements to use GPU for reshape (default: 5M)
    pub reshape_threshold: usize,

    /// Minimum number of dimensions to use GPU for stride computation (default: 10)
    pub stride_dimension_threshold: usize,

    /// Minimum batch size to use GPU for batch validation (default: 100)
    pub batch_validation_threshold: usize,

    /// Enable automatic threshold tuning based on GPU performance (default: false)
    pub enable_auto_tuning: bool,

    /// Preferred GPU device ID (default: 0)
    pub device_id: usize,
}

impl Default for AcceleratorConfig {
    fn default() -> Self {
        Self {
            broadcast_threshold: 10_000_000,
            reshape_threshold: 5_000_000,
            stride_dimension_threshold: 10,
            batch_validation_threshold: 100,
            enable_auto_tuning: false,
            device_id: 0,
        }
    }
}

impl AcceleratorConfig {
    /// Create a new configuration with default settings
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the broadcast threshold
    pub fn with_broadcast_threshold(mut self, threshold: usize) -> Self {
        self.broadcast_threshold = threshold;
        self
    }

    /// Set the reshape threshold
    pub fn with_reshape_threshold(mut self, threshold: usize) -> Self {
        self.reshape_threshold = threshold;
        self
    }

    /// Set the stride dimension threshold
    pub fn with_stride_dimension_threshold(mut self, threshold: usize) -> Self {
        self.stride_dimension_threshold = threshold;
        self
    }

    /// Set the batch validation threshold
    pub fn with_batch_validation_threshold(mut self, threshold: usize) -> Self {
        self.batch_validation_threshold = threshold;
        self
    }

    /// Enable automatic threshold tuning
    pub fn with_auto_tuning(mut self, enable: bool) -> Self {
        self.enable_auto_tuning = enable;
        self
    }

    /// Set the GPU device ID
    pub fn with_device_id(mut self, device_id: usize) -> Self {
        self.device_id = device_id;
        self
    }

    /// Create a configuration optimized for very large tensors (>100M elements)
    pub fn for_very_large_tensors() -> Self {
        Self {
            broadcast_threshold: 1_000_000,
            reshape_threshold: 500_000,
            stride_dimension_threshold: 8,
            batch_validation_threshold: 50,
            enable_auto_tuning: true,
            device_id: 0,
        }
    }

    /// Create a configuration optimized for high-dimensional tensors
    pub fn for_high_dimensional() -> Self {
        Self {
            broadcast_threshold: 5_000_000,
            reshape_threshold: 2_000_000,
            stride_dimension_threshold: 6,
            batch_validation_threshold: 100,
            enable_auto_tuning: false,
            device_id: 0,
        }
    }

    /// Create a conservative configuration that prefers CPU
    pub fn conservative() -> Self {
        Self {
            broadcast_threshold: 50_000_000,
            reshape_threshold: 25_000_000,
            stride_dimension_threshold: 15,
            batch_validation_threshold: 200,
            enable_auto_tuning: false,
            device_id: 0,
        }
    }
}

/// Performance statistics for GPU operations
#[derive(Debug, Clone, Default)]
pub struct AcceleratorStats {
    /// Total number of operations
    pub total_operations: usize,

    /// Number of operations executed on GPU
    pub gpu_operations: usize,

    /// Number of operations executed on CPU
    pub cpu_operations: usize,

    /// Total time spent on GPU operations (microseconds)
    pub gpu_time_us: u64,

    /// Total time spent on CPU operations (microseconds)
    pub cpu_time_us: u64,

    /// Number of GPU fallback failures
    pub gpu_fallback_count: usize,
}

impl AcceleratorStats {
    /// Create new statistics
    pub fn new() -> Self {
        Self::default()
    }

    /// Get the percentage of operations that used GPU
    pub fn gpu_usage_percentage(&self) -> f64 {
        if self.total_operations == 0 {
            0.0
        } else {
            (self.gpu_operations as f64 / self.total_operations as f64) * 100.0
        }
    }

    /// Get average GPU operation time in microseconds
    pub fn avg_gpu_time_us(&self) -> f64 {
        if self.gpu_operations == 0 {
            0.0
        } else {
            self.gpu_time_us as f64 / self.gpu_operations as f64
        }
    }

    /// Get average CPU operation time in microseconds
    pub fn avg_cpu_time_us(&self) -> f64 {
        if self.cpu_operations == 0 {
            0.0
        } else {
            self.cpu_time_us as f64 / self.cpu_operations as f64
        }
    }

    /// Get the speedup factor (CPU time / GPU time)
    pub fn speedup_factor(&self) -> f64 {
        if self.gpu_time_us == 0 {
            0.0
        } else {
            self.cpu_time_us as f64 / self.gpu_time_us as f64
        }
    }

    /// Reset all statistics
    pub fn reset(&mut self) {
        *self = Self::default();
    }
}

/// GPU-accelerated shape operations
///
/// Provides intelligent GPU acceleration for shape operations on very large tensors.
/// Automatically selects between GPU and CPU based on operation size and complexity.
#[cfg(feature = "std")]
pub struct GpuShapeAccelerator {
    config: AcceleratorConfig,
    stats: Arc<std::sync::Mutex<AcceleratorStats>>,
    gpu_available: bool,
}

#[cfg(feature = "std")]
impl GpuShapeAccelerator {
    /// Create a new GPU shape accelerator with default configuration
    pub fn new(config: AcceleratorConfig) -> Result<Self> {
        // Check GPU availability through scirs2-core
        #[cfg(feature = "gpu")]
        let gpu_available = crate::gpu::is_gpu_available();

        #[cfg(not(feature = "gpu"))]
        let gpu_available = false;

        Ok(Self {
            config,
            stats: Arc::new(std::sync::Mutex::new(AcceleratorStats::new())),
            gpu_available,
        })
    }

    /// Create a new accelerator with default configuration
    pub fn default_config() -> Result<Self> {
        Self::new(AcceleratorConfig::default())
    }

    /// Check if GPU is available
    pub fn is_gpu_available(&self) -> bool {
        self.gpu_available
    }

    /// Get current statistics
    pub fn stats(&self) -> AcceleratorStats {
        self.stats
            .lock()
            .expect("lock should not be poisoned")
            .clone()
    }

    /// Reset statistics
    pub fn reset_stats(&self) {
        self.stats
            .lock()
            .expect("lock should not be poisoned")
            .reset();
    }

    /// GPU-accelerated broadcasting for very large tensors
    ///
    /// Automatically uses GPU if tensor size exceeds threshold, otherwise uses CPU.
    pub fn broadcast(&self, shape1: &Shape, shape2: &Shape) -> Result<Shape> {
        let numel1 = shape1.numel();
        let numel2 = shape2.numel();
        let total_elements = numel1.max(numel2);

        // Record operation start
        let mut stats = self.stats.lock().expect("lock should not be poisoned");
        stats.total_operations += 1;

        // Decide whether to use GPU
        let use_gpu = self.gpu_available && total_elements >= self.config.broadcast_threshold;

        if use_gpu {
            stats.gpu_operations += 1;
            drop(stats); // Release lock before GPU operation

            // GPU-accelerated broadcast
            match self.broadcast_gpu(shape1, shape2) {
                Ok(result) => Ok(result),
                Err(_) => {
                    // Fallback to CPU
                    let mut stats = self.stats.lock().expect("lock should not be poisoned");
                    stats.gpu_fallback_count += 1;
                    stats.gpu_operations -= 1;
                    stats.cpu_operations += 1;
                    drop(stats);
                    self.broadcast_cpu(shape1, shape2)
                }
            }
        } else {
            stats.cpu_operations += 1;
            drop(stats);
            self.broadcast_cpu(shape1, shape2)
        }
    }

    /// CPU fallback for broadcasting
    fn broadcast_cpu(&self, shape1: &Shape, shape2: &Shape) -> Result<Shape> {
        shape1.broadcast_with(shape2)
    }

    /// GPU-accelerated broadcasting implementation
    #[cfg(feature = "gpu")]
    fn broadcast_gpu(&self, shape1: &Shape, shape2: &Shape) -> Result<Shape> {
        // This would use scirs2_core::gpu for actual GPU computation
        // For now, we implement the logic and prepare for GPU integration

        // Note: Actual GPU implementation would:
        // 1. Transfer shape data to GPU
        // 2. Execute broadcasting kernel in parallel
        // 3. Transfer result back to CPU
        //
        // For production use, this requires scirs2-core GPU support to be available

        // Fallback to CPU for now
        self.broadcast_cpu(shape1, shape2)
    }

    #[cfg(not(feature = "gpu"))]
    fn broadcast_gpu(&self, shape1: &Shape, shape2: &Shape) -> Result<Shape> {
        // GPU not available, fallback to CPU
        self.broadcast_cpu(shape1, shape2)
    }

    /// GPU-accelerated reshape for very large tensors
    ///
    /// Validates reshape is possible and computes new strides efficiently on GPU.
    pub fn reshape(&self, shape: &Shape, new_dims: &[usize]) -> Result<Shape> {
        let numel = shape.numel();

        // Check if new shape has same number of elements
        let new_numel: usize = new_dims.iter().product();
        if numel != new_numel {
            return Err(TorshError::dimension_error(
                &format!(
                    "Cannot reshape tensor of {} elements into shape with {} elements",
                    numel, new_numel
                ),
                "reshape",
            ));
        }

        // Record operation
        let mut stats = self.stats.lock().expect("lock should not be poisoned");
        stats.total_operations += 1;

        let use_gpu = self.gpu_available && numel >= self.config.reshape_threshold;

        if use_gpu {
            stats.gpu_operations += 1;
            drop(stats);

            match self.reshape_gpu(shape, new_dims) {
                Ok(result) => Ok(result),
                Err(_) => {
                    let mut stats = self.stats.lock().expect("lock should not be poisoned");
                    stats.gpu_fallback_count += 1;
                    stats.gpu_operations -= 1;
                    stats.cpu_operations += 1;
                    drop(stats);
                    self.reshape_cpu(new_dims)
                }
            }
        } else {
            stats.cpu_operations += 1;
            drop(stats);
            self.reshape_cpu(new_dims)
        }
    }

    /// CPU fallback for reshape
    fn reshape_cpu(&self, new_dims: &[usize]) -> Result<Shape> {
        Shape::from_dims(new_dims.to_vec())
    }

    /// GPU-accelerated reshape implementation
    #[cfg(feature = "gpu")]
    fn reshape_gpu(&self, _shape: &Shape, new_dims: &[usize]) -> Result<Shape> {
        // GPU implementation would compute strides in parallel
        self.reshape_cpu(new_dims)
    }

    #[cfg(not(feature = "gpu"))]
    fn reshape_gpu(&self, _shape: &Shape, new_dims: &[usize]) -> Result<Shape> {
        self.reshape_cpu(new_dims)
    }

    /// Batch validate multiple shapes efficiently
    ///
    /// Validates a batch of shapes for validity in parallel on GPU.
    pub fn batch_validate(&self, shapes: &[Vec<usize>]) -> Result<Vec<bool>> {
        let mut stats = self.stats.lock().expect("lock should not be poisoned");
        stats.total_operations += 1;

        let use_gpu = self.gpu_available && shapes.len() >= self.config.batch_validation_threshold;

        if use_gpu {
            stats.gpu_operations += 1;
            drop(stats);

            match self.batch_validate_gpu(shapes) {
                Ok(result) => Ok(result),
                Err(_) => {
                    let mut stats = self.stats.lock().expect("lock should not be poisoned");
                    stats.gpu_fallback_count += 1;
                    stats.gpu_operations -= 1;
                    stats.cpu_operations += 1;
                    drop(stats);
                    self.batch_validate_cpu(shapes)
                }
            }
        } else {
            stats.cpu_operations += 1;
            drop(stats);
            self.batch_validate_cpu(shapes)
        }
    }

    /// CPU fallback for batch validation
    fn batch_validate_cpu(&self, shapes: &[Vec<usize>]) -> Result<Vec<bool>> {
        Ok(shapes
            .iter()
            .map(|dims| {
                // Validate each shape
                !dims.is_empty() && dims.iter().all(|&d| d > 0)
            })
            .collect())
    }

    /// GPU-accelerated batch validation
    #[cfg(feature = "gpu")]
    fn batch_validate_gpu(&self, shapes: &[Vec<usize>]) -> Result<Vec<bool>> {
        // GPU implementation would validate all shapes in parallel
        self.batch_validate_cpu(shapes)
    }

    #[cfg(not(feature = "gpu"))]
    fn batch_validate_gpu(&self, shapes: &[Vec<usize>]) -> Result<Vec<bool>> {
        self.batch_validate_cpu(shapes)
    }

    /// Compute strides for high-dimensional shapes
    ///
    /// Uses GPU acceleration for shapes with many dimensions.
    pub fn compute_strides(&self, dims: &[usize]) -> Result<Vec<usize>> {
        let mut stats = self.stats.lock().expect("lock should not be poisoned");
        stats.total_operations += 1;

        let use_gpu = self.gpu_available && dims.len() >= self.config.stride_dimension_threshold;

        if use_gpu {
            stats.gpu_operations += 1;
            drop(stats);

            match self.compute_strides_gpu(dims) {
                Ok(result) => Ok(result),
                Err(_) => {
                    let mut stats = self.stats.lock().expect("lock should not be poisoned");
                    stats.gpu_fallback_count += 1;
                    stats.gpu_operations -= 1;
                    stats.cpu_operations += 1;
                    drop(stats);
                    self.compute_strides_cpu(dims)
                }
            }
        } else {
            stats.cpu_operations += 1;
            drop(stats);
            self.compute_strides_cpu(dims)
        }
    }

    /// CPU fallback for stride computation
    fn compute_strides_cpu(&self, dims: &[usize]) -> Result<Vec<usize>> {
        if dims.is_empty() {
            return Ok(Vec::new());
        }

        let mut strides = vec![0; dims.len()];
        let mut stride = 1;

        for i in (0..dims.len()).rev() {
            strides[i] = stride;
            stride *= dims[i];
        }

        Ok(strides)
    }

    /// GPU-accelerated stride computation
    #[cfg(feature = "gpu")]
    fn compute_strides_gpu(&self, dims: &[usize]) -> Result<Vec<usize>> {
        // GPU implementation would compute strides in parallel using prefix scan
        self.compute_strides_cpu(dims)
    }

    #[cfg(not(feature = "gpu"))]
    fn compute_strides_gpu(&self, dims: &[usize]) -> Result<Vec<usize>> {
        self.compute_strides_cpu(dims)
    }

    /// Get current configuration
    pub fn config(&self) -> &AcceleratorConfig {
        &self.config
    }

    /// Update configuration
    pub fn set_config(&mut self, config: AcceleratorConfig) {
        self.config = config;
    }
}

/// Lightweight GPU shape operations without std
///
/// Provides basic GPU-accelerated shape operations for no_std environments.
#[cfg(not(feature = "std"))]
pub struct GpuShapeAccelerator {
    config: AcceleratorConfig,
    gpu_available: bool,
}

#[cfg(not(feature = "std"))]
impl GpuShapeAccelerator {
    /// Create a new GPU shape accelerator
    pub fn new(config: AcceleratorConfig) -> Result<Self> {
        #[cfg(feature = "gpu")]
        let gpu_available = crate::gpu::is_gpu_available();

        #[cfg(not(feature = "gpu"))]
        let gpu_available = false;

        Ok(Self {
            config,
            gpu_available,
        })
    }

    /// Check if GPU is available
    pub fn is_gpu_available(&self) -> bool {
        self.gpu_available
    }

    /// GPU-accelerated broadcasting
    pub fn broadcast(&self, shape1: &Shape, shape2: &Shape) -> Result<Shape> {
        // In no_std, always use CPU fallback
        shape1.broadcast_with(shape2)
    }

    /// Get current configuration
    pub fn config(&self) -> &AcceleratorConfig {
        &self.config
    }
}

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

    #[test]
    fn test_accelerator_config_default() {
        let config = AcceleratorConfig::default();
        assert_eq!(config.broadcast_threshold, 10_000_000);
        assert_eq!(config.reshape_threshold, 5_000_000);
        assert_eq!(config.stride_dimension_threshold, 10);
        assert_eq!(config.batch_validation_threshold, 100);
        assert!(!config.enable_auto_tuning);
        assert_eq!(config.device_id, 0);
    }

    #[test]
    fn test_accelerator_config_builder() {
        let config = AcceleratorConfig::new()
            .with_broadcast_threshold(1_000_000)
            .with_reshape_threshold(500_000)
            .with_stride_dimension_threshold(5)
            .with_batch_validation_threshold(50)
            .with_auto_tuning(true)
            .with_device_id(1);

        assert_eq!(config.broadcast_threshold, 1_000_000);
        assert_eq!(config.reshape_threshold, 500_000);
        assert_eq!(config.stride_dimension_threshold, 5);
        assert_eq!(config.batch_validation_threshold, 50);
        assert!(config.enable_auto_tuning);
        assert_eq!(config.device_id, 1);
    }

    #[test]
    fn test_accelerator_config_presets() {
        let very_large = AcceleratorConfig::for_very_large_tensors();
        assert_eq!(very_large.broadcast_threshold, 1_000_000);
        assert!(very_large.enable_auto_tuning);

        let high_dim = AcceleratorConfig::for_high_dimensional();
        assert_eq!(high_dim.stride_dimension_threshold, 6);

        let conservative = AcceleratorConfig::conservative();
        assert_eq!(conservative.broadcast_threshold, 50_000_000);
    }

    #[test]
    fn test_accelerator_stats() {
        let mut stats = AcceleratorStats::new();
        assert_eq!(stats.total_operations, 0);
        assert_eq!(stats.gpu_operations, 0);
        assert_eq!(stats.cpu_operations, 0);

        stats.total_operations = 100;
        stats.gpu_operations = 60;
        stats.cpu_operations = 40;
        stats.gpu_time_us = 1000;
        stats.cpu_time_us = 3000;

        assert_eq!(stats.gpu_usage_percentage(), 60.0);
        assert_eq!(stats.avg_gpu_time_us(), 1000.0 / 60.0);
        assert_eq!(stats.avg_cpu_time_us(), 3000.0 / 40.0);
        assert_eq!(stats.speedup_factor(), 3.0);

        stats.reset();
        assert_eq!(stats.total_operations, 0);
    }

    #[test]
    #[cfg(feature = "std")]
    fn test_accelerator_creation() {
        let config = AcceleratorConfig::default();
        let accelerator = GpuShapeAccelerator::new(config);
        assert!(accelerator.is_ok());

        let accelerator = accelerator.expect("accelerator creation should succeed");
        // GPU may or may not be available depending on build configuration
        let _gpu_available = accelerator.is_gpu_available();
    }

    #[test]
    #[cfg(feature = "std")]
    fn test_accelerator_broadcast() {
        let config = AcceleratorConfig::default();
        let accelerator =
            GpuShapeAccelerator::new(config).expect("accelerator creation should succeed");

        let shape1 = Shape::from_dims(vec![10, 20, 30]).expect("shape creation should succeed");
        let shape2 = Shape::from_dims(vec![1, 20, 30]).expect("shape creation should succeed");

        let result = accelerator.broadcast(&shape1, &shape2);
        assert!(result.is_ok());

        let result = result.expect("broadcast should succeed");
        assert_eq!(result.dims(), &[10, 20, 30]);
    }

    #[test]
    #[cfg(feature = "std")]
    fn test_accelerator_reshape() {
        let config = AcceleratorConfig::default();
        let accelerator =
            GpuShapeAccelerator::new(config).expect("accelerator creation should succeed");

        let shape = Shape::from_dims(vec![10, 20, 30]).expect("shape creation should succeed");
        let new_dims = vec![10, 600];

        let result = accelerator.reshape(&shape, &new_dims);
        assert!(result.is_ok());

        let result = result.expect("reshape should succeed");
        assert_eq!(result.dims(), &[10, 600]);
    }

    #[test]
    #[cfg(feature = "std")]
    fn test_accelerator_reshape_invalid() {
        let config = AcceleratorConfig::default();
        let accelerator =
            GpuShapeAccelerator::new(config).expect("accelerator creation should succeed");

        let shape = Shape::from_dims(vec![10, 20, 30]).expect("shape creation should succeed");
        let new_dims = vec![10, 100]; // Wrong number of elements

        let result = accelerator.reshape(&shape, &new_dims);
        assert!(result.is_err());
    }

    #[test]
    #[cfg(feature = "std")]
    fn test_accelerator_batch_validate() {
        let config = AcceleratorConfig::default();
        let accelerator =
            GpuShapeAccelerator::new(config).expect("accelerator creation should succeed");

        let shapes = vec![
            vec![10, 20],
            vec![30, 40, 50],
            vec![],          // Invalid: empty
            vec![10, 0, 20], // Invalid: zero dimension
            vec![5, 5, 5, 5],
        ];

        let result = accelerator.batch_validate(&shapes);
        assert!(result.is_ok());

        let result = result.expect("batch_validate should succeed");
        assert_eq!(result.len(), 5);
        assert!(result[0]); // Valid
        assert!(result[1]); // Valid
        assert!(!result[2]); // Invalid: empty
        assert!(!result[3]); // Invalid: zero dimension
        assert!(result[4]); // Valid
    }

    #[test]
    #[cfg(feature = "std")]
    fn test_accelerator_compute_strides() {
        let config = AcceleratorConfig::default();
        let accelerator =
            GpuShapeAccelerator::new(config).expect("accelerator creation should succeed");

        let dims = vec![10, 20, 30];
        let result = accelerator.compute_strides(&dims);
        assert!(result.is_ok());

        let strides = result.expect("compute_strides should succeed");
        assert_eq!(strides, vec![600, 30, 1]);
    }

    #[test]
    #[cfg(feature = "std")]
    fn test_accelerator_compute_strides_empty() {
        let config = AcceleratorConfig::default();
        let accelerator =
            GpuShapeAccelerator::new(config).expect("accelerator creation should succeed");

        let dims = vec![];
        let result = accelerator.compute_strides(&dims);
        assert!(result.is_ok());

        let strides = result.expect("compute_strides should succeed");
        assert!(strides.is_empty());
    }

    #[test]
    #[cfg(feature = "std")]
    fn test_accelerator_stats_tracking() {
        let config = AcceleratorConfig::default();
        let accelerator =
            GpuShapeAccelerator::new(config).expect("accelerator creation should succeed");

        // Perform some operations
        let shape1 = Shape::from_dims(vec![10, 20]).expect("shape creation should succeed");
        let shape2 = Shape::from_dims(vec![1, 20]).expect("shape creation should succeed");
        let _ = accelerator.broadcast(&shape1, &shape2);

        let stats = accelerator.stats();
        assert_eq!(stats.total_operations, 1);
        assert!(stats.gpu_operations + stats.cpu_operations == 1);

        accelerator.reset_stats();
        let stats = accelerator.stats();
        assert_eq!(stats.total_operations, 0);
    }

    #[test]
    #[cfg(feature = "std")]
    fn test_accelerator_config_update() {
        let config = AcceleratorConfig::default();
        let mut accelerator =
            GpuShapeAccelerator::new(config).expect("accelerator creation should succeed");

        assert_eq!(accelerator.config().broadcast_threshold, 10_000_000);

        let new_config = AcceleratorConfig::new().with_broadcast_threshold(1_000_000);
        accelerator.set_config(new_config);

        assert_eq!(accelerator.config().broadcast_threshold, 1_000_000);
    }

    #[test]
    #[cfg(feature = "std")]
    fn test_accelerator_high_dimensional_strides() {
        let config = AcceleratorConfig::new().with_stride_dimension_threshold(5);
        let accelerator =
            GpuShapeAccelerator::new(config).expect("accelerator creation should succeed");

        // Create a 12D tensor (exceeds threshold of 5)
        let dims = vec![2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
        let result = accelerator.compute_strides(&dims);
        assert!(result.is_ok());

        let strides = result.expect("compute_strides should succeed");
        assert_eq!(strides.len(), dims.len());

        // Verify strides are computed correctly
        let mut expected_stride = 1;
        for i in (0..dims.len()).rev() {
            assert_eq!(strides[i], expected_stride);
            expected_stride *= dims[i];
        }
    }

    #[test]
    #[cfg(feature = "std")]
    fn test_accelerator_large_batch_validation() {
        let config = AcceleratorConfig::new().with_batch_validation_threshold(10);
        let accelerator =
            GpuShapeAccelerator::new(config).expect("accelerator creation should succeed");

        // Create a batch of 50 shapes (exceeds threshold of 10)
        let shapes: Vec<Vec<usize>> = (0..50)
            .map(|i| {
                if i % 10 == 0 {
                    vec![] // Some invalid shapes
                } else {
                    vec![10, 20, 30]
                }
            })
            .collect();

        let result = accelerator.batch_validate(&shapes);
        assert!(result.is_ok());

        let validations = result.expect("batch_validate should succeed");
        assert_eq!(validations.len(), 50);

        // Check that invalid shapes (every 10th) are marked as invalid
        for i in 0..50 {
            if i % 10 == 0 {
                assert!(!validations[i]);
            } else {
                assert!(validations[i]);
            }
        }
    }
}