scirs2-core 0.4.2

Core utilities and common functionality for SciRS2 (scirs2-core)
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
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
//! Cross-device memory management for efficient data transfer between CPU and GPU
//!
//! This module provides utilities for managing memory across different devices
//! (CPU, GPU, TPU) with efficient data transfer and synchronization. It includes:
//!
//! - Cross-device memory transfer with automatic format conversion
//! - Memory pools for efficient allocation
//! - Smart caching for frequently accessed data
//! - Efficient pinned memory for faster CPU-GPU transfers
//! - Asynchronous data transfer with event-based synchronization

use crate::error::{CoreError, CoreResult, ErrorContext, ErrorLocation};
#[cfg(feature = "gpu")]
use crate::gpu::{GpuBackend, GpuBuffer, GpuContext, GpuDataType};
use ::ndarray::{Array, ArrayBase, Dimension, IxDyn, RawData};
use std::any::TypeId;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;
use std::sync::{Arc, Mutex};

/// Device types supported by the cross-device memory management
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DeviceType {
    /// CPU (host) memory
    Cpu,
    /// Discrete GPU memory
    Gpu(GpuBackend),
    /// TPU (Tensor Processing Unit) memory
    Tpu,
}

impl DeviceType {
    /// Check if the device is available on the current system
    pub fn is_available(&self) -> bool {
        match self {
            DeviceType::Cpu => true,
            DeviceType::Gpu(backend) => backend.is_available(),
            DeviceType::Tpu => false, // TPU support not yet implemented
        }
    }

    /// Get the name of the device
    pub fn name(&self) -> String {
        match self {
            DeviceType::Cpu => "CPU".to_string(),
            DeviceType::Gpu(backend) => format!("GPU ({backend})"),
            DeviceType::Tpu => "TPU".to_string(),
        }
    }
}

impl std::fmt::Display for DeviceType {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            DeviceType::Cpu => write!(f, "CPU"),
            DeviceType::Gpu(backend) => write!(f, "GPU ({backend})"),
            DeviceType::Tpu => write!(f, "TPU"),
        }
    }
}

/// Memory transfer direction between devices
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TransferDirection {
    /// Host to device transfer (e.g., CPU to GPU)
    HostToDevice,
    /// Device to host transfer (e.g., GPU to CPU)
    DeviceToHost,
    /// Device to device transfer (e.g., GPU to TPU)
    DeviceToDevice,
}

/// Transfer mode for cross-device operations
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TransferMode {
    /// Synchronous transfer (blocks until complete)
    Synchronous,
    /// Asynchronous transfer (returns immediately, track with events)
    Asynchronous,
}

/// Memory layout for device buffers
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MemoryLayout {
    /// Row-major layout (C-style)
    RowMajor,
    /// Column-major layout (Fortran-style)
    ColumnMajor,
    /// Strided layout (custom strides)
    Strided,
}

/// Options for cross-device memory transfers
#[derive(Debug, Clone)]
pub struct TransferOptions {
    /// Transfer mode (synchronous or asynchronous)
    pub mode: TransferMode,
    /// Memory layout for the transfer
    pub layout: MemoryLayout,
    /// Whether to use pinned memory for the transfer
    pub use_pinned_memory: bool,
    /// Whether to enable streaming transfers for large buffers
    pub enable_streaming: bool,
    /// Stream ID for asynchronous transfers
    pub stream_id: Option<usize>,
}

impl Default for TransferOptions {
    fn default() -> Self {
        Self {
            mode: TransferMode::Synchronous,
            layout: MemoryLayout::RowMajor,
            use_pinned_memory: true,
            enable_streaming: true,
            stream_id: None,
        }
    }
}

/// Builder for transfer options
#[derive(Debug, Clone)]
pub struct TransferOptionsBuilder {
    options: TransferOptions,
}

impl TransferOptionsBuilder {
    /// Create a new transfer options builder with default values
    pub fn new() -> Self {
        Self {
            options: TransferOptions::default(),
        }
    }

    /// Set the transfer mode
    pub const fn mode(mut self, mode: TransferMode) -> Self {
        self.options.mode = mode;
        self
    }

    /// Set the memory layout
    pub const fn layout(mut self, layout: MemoryLayout) -> Self {
        self.options.layout = layout;
        self
    }

    /// Set whether to use pinned memory
    pub const fn memory(mut self, use_pinnedmemory: bool) -> Self {
        self.options.use_pinned_memory = use_pinnedmemory;
        self
    }

    /// Set whether to enable streaming transfers
    pub const fn streaming(mut self, enablestreaming: bool) -> Self {
        self.options.enable_streaming = enablestreaming;
        self
    }

    /// Set the stream ID for asynchronous transfers
    pub const fn with_stream_id(mut self, streamid: Option<usize>) -> Self {
        self.options.stream_id = streamid;
        self
    }

    /// Build the transfer options
    pub fn build(self) -> TransferOptions {
        self.options
    }
}

impl Default for TransferOptionsBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// Cache key for the device memory cache
#[derive(Debug, Clone, PartialEq, Eq)]
struct CacheKey {
    /// Data identifier (usually the memory address of the host array)
    data_id: usize,
    /// Device type
    device: DeviceType,
    /// Element type ID
    type_id: TypeId,
    /// Size in elements
    size: usize,
}

impl Hash for CacheKey {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.data_id.hash(state);
        self.device.hash(state);
        std::any::TypeId::of::<i32>().hash(state);
        self.size.hash(state);
    }
}

/// Event for tracking asynchronous operations
#[derive(Debug)]
pub struct TransferEvent {
    /// Device associated with the event
    #[allow(dead_code)]
    device: DeviceType,
    /// Internal event handle (implementation-specific)
    #[allow(dead_code)]
    handle: Arc<Mutex<Box<dyn std::any::Any + Send + Sync>>>,
    /// Whether the event has been completed
    completed: Arc<std::sync::atomic::AtomicBool>,
}

impl TransferEvent {
    /// Create a new transfer event
    #[allow(dead_code)]
    fn device(devicetype: DeviceType, handle: Box<dyn std::any::Any + Send + Sync>) -> Self {
        Self {
            device: devicetype,
            handle: Arc::new(Mutex::new(handle)),
            completed: Arc::new(std::sync::atomic::AtomicBool::new(false)),
        }
    }

    /// Wait for the event to complete
    pub fn wait(&self) {
        // In a real implementation, this would block until the event is complete
        // For now, just set the completed flag for demonstration
        self.completed
            .store(true, std::sync::atomic::Ordering::SeqCst);
    }

    /// Check if the event has completed
    pub fn is_complete(&self) -> bool {
        self.completed.load(std::sync::atomic::Ordering::SeqCst)
    }
}

/// Cache entry for the device memory cache
struct CacheEntry<T: GpuDataType> {
    /// Buffer on the device
    buffer: DeviceBuffer<T>,
    /// Size in elements
    size: usize,
    /// Last access time
    last_access: std::time::Instant,
    /// Whether the buffer is dirty (modified on device)
    #[allow(dead_code)]
    dirty: bool,
}

/// Device memory manager for cross-device operations
pub struct DeviceMemoryManager {
    /// GPU context for accessing GPU functionality
    gpu_context: Option<GpuContext>,
    /// Cache of device buffers
    cache: Mutex<HashMap<CacheKey, Box<dyn std::any::Any + Send + Sync>>>,
    /// Maximum cache size in bytes
    max_cache_size: usize,
    /// Current cache size in bytes
    current_cache_size: std::sync::atomic::AtomicUsize,
    /// Whether the caching is enabled
    enable_caching: bool,
}

impl std::fmt::Debug for DeviceMemoryManager {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DeviceMemoryManager")
            .field("gpu_context", &"<gpu_context>")
            .field("cache", &"<cache>")
            .field("max_cache_size", &self.max_cache_size)
            .field(
                "current_cache_size",
                &self
                    .current_cache_size
                    .load(std::sync::atomic::Ordering::Relaxed),
            )
            .field("enable_caching", &self.enable_caching)
            .finish()
    }
}

impl DeviceMemoryManager {
    /// Create a new device memory manager
    pub fn new(max_cachesize: usize) -> Result<Self, CoreError> {
        // Try to create a GPU context if a GPU is available
        let gpu_context = match GpuBackend::preferred() {
            backend if backend.is_available() => GpuContext::new(backend).ok(),
            _ => None,
        };

        Ok(Self {
            gpu_context,
            cache: Mutex::new(HashMap::new()),
            max_cache_size: max_cachesize,
            current_cache_size: std::sync::atomic::AtomicUsize::new(0),
            enable_caching: true,
        })
    }

    /// Check if a device type is available
    pub fn is_device_available(&self, device: DeviceType) -> bool {
        match device {
            DeviceType::Cpu => true,
            DeviceType::Gpu(_) => self.gpu_context.is_some(),
            DeviceType::Tpu => false, // TPU not yet supported
        }
    }

    /// Get a list of available devices
    pub fn available_devices(&self) -> Vec<DeviceType> {
        let mut devices = vec![DeviceType::Cpu];

        if let Some(ref context) = self.gpu_context {
            devices.push(DeviceType::Gpu(context.backend()));
        }

        devices
    }

    /// Transfer data from host to device
    pub fn transfer_to_device<T, S, D>(
        &self,
        array: &ArrayBase<S, D>,
        device: DeviceType,
        options: Option<TransferOptions>,
    ) -> CoreResult<DeviceArray<T, D>>
    where
        T: GpuDataType,
        S: RawData<Elem = T> + crate::ndarray::Data,
        D: Dimension,
    {
        let options = options.unwrap_or_default();

        // Check if the device is available
        if !self.is_device_available(device) {
            return Err(CoreError::DeviceError(
                ErrorContext::new(format!("Device {device} is not available"))
                    .with_location(ErrorLocation::new(file!(), line!())),
            ));
        }

        // For CPU, just create a view of the array
        if device == DeviceType::Cpu {
            return Ok(DeviceArray::new_cpu(array.to_owned()));
        }

        // For GPU, create a GPU buffer
        if let DeviceType::Gpu(backend) = device {
            if let Some(ref context) = self.gpu_context {
                if context.backend() != backend {
                    return Err(CoreError::DeviceError(
                        ErrorContext::new(format!(
                            "GPU backend mismatch: requested {}, available {}",
                            backend,
                            context.backend()
                        ))
                        .with_location(ErrorLocation::new(file!(), line!())),
                    ));
                }

                // Create a flat view of the array data
                let flat_data = array.as_slice().ok_or_else(|| {
                    CoreError::DeviceError(
                        ErrorContext::new("Array is not contiguous".to_string())
                            .with_location(ErrorLocation::new(file!(), line!())),
                    )
                })?;

                // Check if we have a cached buffer for this array
                let data_id = flat_data.as_ptr() as usize;
                let key = CacheKey {
                    data_id,
                    device,
                    type_id: TypeId::of::<T>(),
                    size: flat_data.len(),
                };

                let buffer = if self.enable_caching {
                    let mut cache = self.cache.lock().expect("Operation failed");
                    if let Some(entry) = cache.get_mut(&key) {
                        // We found a cached entry, cast it to the correct type
                        if let Some(entry) = entry.downcast_mut::<CacheEntry<T>>() {
                            // Update the last access time
                            entry.last_access = std::time::Instant::now();
                            entry.buffer.clone()
                        } else {
                            // This should never happen if our caching logic is correct
                            return Err(CoreError::DeviceError(
                                ErrorContext::new("Cache entry type mismatch".to_string())
                                    .with_location(ErrorLocation::new(file!(), line!())),
                            ));
                        }
                    } else {
                        // No cached entry, create a new buffer
                        let gpubuffer = context.create_buffer_from_slice(flat_data);
                        let buffer = DeviceBuffer::new_gpu(gpubuffer);

                        // Add to cache
                        let entry = CacheEntry {
                            buffer: buffer.clone(),
                            size: flat_data.len(),
                            last_access: std::time::Instant::now(),
                            dirty: false,
                        };

                        let buffersize = std::mem::size_of_val(flat_data);
                        self.current_cache_size
                            .fetch_add(buffersize, std::sync::atomic::Ordering::SeqCst);

                        // If we're over the cache size limit, evict old entries
                        self.evict_cache_entries_if_needed();

                        cache.insert(key, Box::new(entry));
                        buffer
                    }
                } else {
                    // Caching is disabled, just create a new buffer
                    let gpubuffer = context.create_buffer_from_slice(flat_data);
                    DeviceBuffer::new_gpu(gpubuffer)
                };

                return Ok(DeviceArray {
                    buffer,
                    shape: array.raw_dim(),
                    device: DeviceType::Gpu(crate::gpu::GpuBackend::preferred()),
                    phantom: PhantomData,
                });
            }
        }

        Err(CoreError::DeviceError(
            ErrorContext::new(format!("{device}"))
                .with_location(ErrorLocation::new(file!(), line!())),
        ))
    }

    /// Transfer data from device to host
    pub fn transfer_to_host<T, D>(
        &self,
        devicearray: &DeviceArray<T, D>,
        options: Option<TransferOptions>,
    ) -> CoreResult<Array<T, D>>
    where
        T: GpuDataType,
        D: Dimension,
    {
        let options = options.unwrap_or_default();

        // For CPU arrays, just clone the data
        if devicearray.device == DeviceType::Cpu {
            if let Some(cpuarray) = devicearray.buffer.get_cpuarray() {
                let reshaped = cpuarray
                    .clone()
                    .to_shape(devicearray.shape.clone())
                    .map_err(|e| CoreError::ShapeError(ErrorContext::new(e.to_string())))?
                    .to_owned();
                return Ok(reshaped);
            }
        }

        // For GPU arrays, copy the data back to the host
        if let DeviceType::Gpu(_) = devicearray.device {
            if let Some(gpubuffer) = devicearray.buffer.get_gpubuffer() {
                let size = devicearray.size();
                let mut data = vec![unsafe { std::mem::zeroed() }; size];

                // Copy data from GPU to host
                let _ = gpubuffer.copy_to_host(&mut data);

                // Reshape the data to match the original array shape
                return Array::from_shape_vec(devicearray.shape.clone(), data).map_err(|e| {
                    CoreError::DeviceError(
                        ErrorContext::new(format!("{e}"))
                            .with_location(ErrorLocation::new(file!(), line!())),
                    )
                });
            }
        }

        Err(CoreError::DeviceError(
            ErrorContext::new(format!(
                "Unsupported device type for transfer to host: {}",
                devicearray.device
            ))
            .with_location(ErrorLocation::new(file!(), line!())),
        ))
    }

    /// Transfer data between devices
    pub fn transfer_between_devices<T, D>(
        &self,
        devicearray: &DeviceArray<T, D>,
        target_device: DeviceType,
        options: Option<TransferOptions>,
    ) -> CoreResult<DeviceArray<T, D>>
    where
        T: GpuDataType,
        D: Dimension,
    {
        let options = options.unwrap_or_default();

        // If the source and target devices are the same, just clone the array
        if devicearray.device == target_device {
            return Ok(devicearray.clone());
        }

        // For transfers to CPU, use transfer_to_host
        if target_device == DeviceType::Cpu {
            let hostarray = self.transfer_to_host(devicearray, Some(options))?;
            return Ok(DeviceArray::new_cpu(hostarray));
        }

        // For transfers from CPU to another device, use transfer_to_device
        if devicearray.device == DeviceType::Cpu {
            if let Some(cpuarray) = devicearray.buffer.get_cpuarray() {
                // Reshape the CPU array to match the expected dimension type
                let cpu_clone = cpuarray.clone();
                let reshaped = cpu_clone
                    .to_shape(devicearray.shape.clone())
                    .map_err(|e| CoreError::ShapeError(ErrorContext::new(e.to_string())))?;
                return self.transfer_to_device(&reshaped.to_owned(), target_device, Some(options));
            }
        }

        // For transfers between GPUs (or future TPU support)
        // In a real implementation, we would use peer-to-peer transfers if available,
        // or copy through host memory if not

        // For now, we'll transfer through host memory
        let hostarray = self.transfer_to_host(devicearray, Some(options.clone()))?;
        self.transfer_to_device(&hostarray, target_device, Some(options))
    }

    /// Evict cache entries if the total size exceeds the limit
    fn evict_cache_entries_if_needed(&self) {
        let current_size = self
            .current_cache_size
            .load(std::sync::atomic::Ordering::SeqCst);
        if current_size <= self.max_cache_size {
            return;
        }

        let mut cache = self.cache.lock().expect("Operation failed");

        // Collect keys with their access times to avoid borrow conflicts
        let mut key_times: Vec<_> = cache
            .iter()
            .map(|(key, value)| {
                let access_time = match value.downcast_ref::<CacheEntry<f32>>() {
                    Some(entry) => entry.last_access,
                    None => match value.downcast_ref::<CacheEntry<f64>>() {
                        Some(entry) => entry.last_access,
                        None => match value.downcast_ref::<CacheEntry<i32>>() {
                            Some(entry) => entry.last_access,
                            None => match value.downcast_ref::<CacheEntry<u32>>() {
                                Some(entry) => entry.last_access,
                                None => std::time::Instant::now(), // Fallback, shouldn't happen
                            },
                        },
                    },
                };
                (key.clone(), access_time)
            })
            .collect();

        // Sort by access time (oldest first)
        key_times.sort_by_key(|a| a.1);

        // Remove entries until we're under the limit
        let mut removed_size = 0;
        let target_size = current_size - self.max_cache_size / 2; // Remove enough to get below half the limit

        for key_ in key_times {
            let entry = cache.remove(&key_.0).expect("Operation failed");

            // Calculate the size of the entry based on its type
            let entry_size = match entry.downcast_ref::<CacheEntry<f32>>() {
                Some(entry) => entry.size * std::mem::size_of::<f32>(),
                None => match entry.downcast_ref::<CacheEntry<f64>>() {
                    Some(entry) => entry.size * std::mem::size_of::<f64>(),
                    None => match entry.downcast_ref::<CacheEntry<i32>>() {
                        Some(entry) => entry.size * std::mem::size_of::<i32>(),
                        None => match entry.downcast_ref::<CacheEntry<u32>>() {
                            Some(entry) => entry.size * std::mem::size_of::<u32>(),
                            None => 0, // Fallback, shouldn't happen
                        },
                    },
                },
            };

            removed_size += entry_size;

            if removed_size >= target_size {
                break;
            }
        }

        // Update the current cache size
        self.current_cache_size
            .fetch_sub(removed_size, std::sync::atomic::Ordering::SeqCst);
    }

    /// Clear the cache
    pub fn clear_cache(&self) {
        let mut cache = self.cache.lock().expect("Operation failed");
        cache.clear();
        self.current_cache_size
            .store(0, std::sync::atomic::Ordering::SeqCst);
    }

    /// Execute a kernel on a device array
    pub fn execute_kernel<T, D>(
        &self,
        devicearray: &DeviceArray<T, D>,
        kernel_name: &str,
        params: HashMap<String, KernelParam>,
    ) -> CoreResult<()>
    where
        T: GpuDataType,
        D: Dimension,
    {
        // Only GPU devices support kernel execution
        if let DeviceType::Gpu(_) = devicearray.device {
            if let Some(ref context) = self.gpu_context {
                // Get the kernel
                let kernel = context
                    .get_kernel(kernel_name)
                    .map_err(|e| CoreError::ComputationError(ErrorContext::new(e.to_string())))?;

                // Set the input buffer parameter
                if let Some(gpubuffer) = devicearray.buffer.get_gpubuffer() {
                    kernel.set_buffer("input", gpubuffer);
                }

                // Set other parameters
                for (name, param) in params {
                    match param {
                        KernelParam::Buffer(buffer) => {
                            if let Some(gpubuffer) = buffer.get_gpubuffer() {
                                kernel.set_buffer(&name, gpubuffer);
                            }
                        }
                        KernelParam::U32(value) => kernel.set_u32(&name, value),
                        KernelParam::I32(value) => kernel.set_i32(&name, value),
                        KernelParam::F32(value) => kernel.set_f32(&name, value),
                        KernelParam::F64(value) => kernel.set_f64(&name, value),
                    }
                }

                // Compute dispatch dimensions
                let total_elements = devicearray.size();
                let work_group_size = 256; // A common CUDA/OpenCL work group size
                let num_groups = total_elements.div_ceil(work_group_size);

                // Dispatch the kernel
                kernel.dispatch([num_groups as u32, 1, 1]);

                return Ok(());
            }
        }

        Err(CoreError::DeviceError(
            ErrorContext::new(format!(
                "Unsupported device type for kernel execution: {}",
                devicearray.device
            ))
            .with_location(ErrorLocation::new(file!(), line!())),
        ))
    }
}

/// Kernel parameter for GPU execution
#[derive(Debug, Clone)]
pub enum KernelParam {
    /// Buffer parameter
    Buffer(DeviceBuffer<f32>), // Note: In a real implementation, this would be generic
    /// U32 parameter
    U32(u32),
    /// I32 parameter
    I32(i32),
    /// F32 parameter
    F32(f32),
    /// F64 parameter
    F64(f64),
}

/// Buffer location (CPU or GPU)
#[derive(Clone)]
enum BufferLocation<T: GpuDataType> {
    /// CPU buffer
    Cpu(Arc<Array<T, IxDyn>>),
    /// GPU buffer
    Gpu(Arc<GpuBuffer<T>>),
}

impl<T> std::fmt::Debug for BufferLocation<T>
where
    T: GpuDataType + std::fmt::Debug,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            BufferLocation::Cpu(_) => write!(f, "Cpu(Array)"),
            BufferLocation::Gpu(_) => write!(f, "Gpu(GpuBuffer)"),
        }
    }
}

/// Buffer for cross-device operations
#[derive(Debug, Clone)]
pub struct DeviceBuffer<T: GpuDataType> {
    /// Buffer data (CPU or GPU)
    location: BufferLocation<T>,
}

impl<T: GpuDataType> DeviceBuffer<T> {
    /// Create a new CPU buffer
    fn new_cpu<D: Dimension>(array: Array<T, D>) -> Self {
        Self {
            location: BufferLocation::Cpu(Arc::new(array.into_dyn())),
        }
    }

    /// Create a new GPU buffer
    fn new_gpu(buffer: GpuBuffer<T>) -> Self {
        Self {
            location: BufferLocation::Gpu(Arc::new(buffer)),
        }
    }

    /// Get the CPU array if available
    fn get_cpuarray(&self) -> Option<&Array<T, IxDyn>> {
        match self.location {
            BufferLocation::Cpu(ref array) => Some(array),
            _ => None,
        }
    }

    /// Get the GPU buffer if available
    fn get_gpubuffer(&self) -> Option<&GpuBuffer<T>> {
        match self.location {
            BufferLocation::Gpu(ref buffer) => Some(buffer),
            _ => None,
        }
    }

    /// Get the size of the buffer in elements
    fn size(&self) -> usize {
        match self.location {
            BufferLocation::Cpu(ref array) => array.len(),
            BufferLocation::Gpu(ref buffer) => buffer.len(),
        }
    }
}

/// Array residing on a specific device (CPU, GPU, TPU)
#[derive(Debug, Clone)]
pub struct DeviceArray<T: GpuDataType, D: Dimension> {
    /// Buffer containing the array data
    buffer: DeviceBuffer<T>,
    /// Shape of the array
    shape: D,
    /// Device where the array resides
    device: DeviceType,
    /// Phantom data for the element type
    phantom: PhantomData<T>,
}

impl<T: GpuDataType, D: Dimension> DeviceArray<T, D> {
    /// Create a new CPU array
    fn new_cpu<S: RawData<Elem = T> + crate::ndarray::Data>(array: ArrayBase<S, D>) -> Self {
        Self {
            buffer: DeviceBuffer::new_cpu(array.to_owned()),
            shape: array.raw_dim(),
            device: DeviceType::Cpu,
            phantom: PhantomData,
        }
    }

    /// Get the device where the array resides
    pub fn device(&self) -> DeviceType {
        self.device
    }

    /// Get the shape of the array
    pub const fn shape(&self) -> &D {
        &self.shape
    }

    /// Get the size of the array in elements
    pub fn size(&self) -> usize {
        self.buffer.size()
    }

    /// Get the number of dimensions
    pub fn ndim(&self) -> usize {
        self.shape.ndim()
    }

    /// Check if the array is on the CPU
    pub fn is_on_cpu(&self) -> bool {
        self.device == DeviceType::Cpu
    }

    /// Check if the array is on a GPU
    pub fn is_on_gpu(&self) -> bool {
        matches!(self.device, DeviceType::Gpu(_))
    }

    /// Get a reference to the underlying CPU array if available
    pub fn as_cpuarray(&self) -> Option<&Array<T, IxDyn>> {
        self.buffer.get_cpuarray()
    }

    /// Get a reference to the underlying GPU buffer if available
    pub fn as_gpubuffer(&self) -> Option<&GpuBuffer<T>> {
        self.buffer.get_gpubuffer()
    }
}

/// Stream for asynchronous operations
pub struct DeviceStream {
    /// Device associated with the stream
    #[allow(dead_code)]
    device: DeviceType,
    /// Internal stream handle (implementation-specific)
    #[allow(dead_code)]
    handle: Arc<Mutex<Box<dyn std::any::Any + Send + Sync>>>,
}

impl DeviceStream {
    /// Create a new device stream
    pub fn new(device: DeviceType) -> CoreResult<Self> {
        // In a real implementation, we would create a stream for the _device
        // For now, just create a dummy stream
        Ok(Self {
            device,
            handle: Arc::new(Mutex::new(Box::new(()))),
        })
    }

    /// Synchronize the stream
    pub fn synchronize(&self) {
        // In a real implementation, this would wait for all operations to complete
    }
}

/// Memory pool for efficient allocation on a device
pub struct DeviceMemoryPool {
    /// Device associated with the pool
    device: DeviceType,
    /// List of free buffers by size
    freebuffers: Mutex<HashMap<usize, Vec<Box<dyn std::any::Any + Send + Sync>>>>,
    /// Maximum pool size in bytes
    max_poolsize: usize,
    /// Current pool size in bytes
    current_poolsize: std::sync::atomic::AtomicUsize,
}

impl std::fmt::Debug for DeviceMemoryPool {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DeviceMemoryPool")
            .field("device", &self.device)
            .field("freebuffers", &"<freebuffers>")
            .field("max_poolsize", &self.max_poolsize)
            .field(
                "current_poolsize",
                &self
                    .current_poolsize
                    .load(std::sync::atomic::Ordering::Relaxed),
            )
            .finish()
    }
}

impl DeviceMemoryPool {
    /// Create a new device memory pool
    pub fn new(device: DeviceType, max_poolsize: usize) -> Self {
        Self {
            device,
            freebuffers: Mutex::new(HashMap::new()),
            max_poolsize,
            current_poolsize: std::sync::atomic::AtomicUsize::new(0),
        }
    }

    /// Allocate a buffer of the given size
    pub fn allocate<T: GpuDataType + num_traits::Zero>(
        &self,
        size: usize,
    ) -> CoreResult<DeviceBuffer<T>> {
        // Check if we have a free buffer of the right size
        let mut freebuffers = self.freebuffers.lock().expect("Operation failed");
        if let Some(buffers) = freebuffers.get_mut(&size) {
            if let Some(buffer) = buffers.pop() {
                // We found a free buffer, cast it to the correct type
                if let Ok(buffer) = buffer.downcast::<DeviceBuffer<T>>() {
                    return Ok(*buffer);
                }
            }
        }

        // No free buffer, allocate a new one
        match self.device {
            DeviceType::Cpu => {
                // Allocate CPU memory
                let array = Array::<T, crate::ndarray::IxDyn>::zeros(IxDyn(&[size]));
                Ok(DeviceBuffer::new_cpu(array))
            }
            DeviceType::Gpu(_) => {
                // Allocate GPU memory
                Err(CoreError::ImplementationError(
                    ErrorContext::new("GPU memory allocation not implemented".to_string())
                        .with_location(ErrorLocation::new(file!(), line!())),
                ))
            }
            DeviceType::Tpu => {
                // TPU not yet supported
                Err(CoreError::DeviceError(
                    ErrorContext::new("TPU not supported".to_string())
                        .with_location(ErrorLocation::new(file!(), line!())),
                ))
            }
        }
    }

    /// Free a buffer (return it to the pool)
    pub fn free<T: GpuDataType>(&self, buffer: DeviceBuffer<T>) {
        let size = buffer.size();
        let buffersize = size * std::mem::size_of::<T>();

        // Check if adding this buffer would exceed the pool size
        let current_size = self
            .current_poolsize
            .load(std::sync::atomic::Ordering::SeqCst);
        if current_size + buffersize > self.max_poolsize {
            // Pool is full, just let the buffer be dropped
            return;
        }

        // Add the buffer to the pool
        let mut freebuffers = self.freebuffers.lock().expect("Operation failed");
        freebuffers.entry(size).or_default().push(Box::new(buffer));

        // Update the pool size
        self.current_poolsize
            .fetch_add(buffersize, std::sync::atomic::Ordering::SeqCst);
    }

    /// Clear the pool
    pub fn clear(&self) {
        let mut freebuffers = self.freebuffers.lock().expect("Operation failed");
        freebuffers.clear();
        self.current_poolsize
            .store(0, std::sync::atomic::Ordering::SeqCst);
    }
}

/// Cross-device array operations
impl<T: GpuDataType, D: Dimension> DeviceArray<T, D> {
    /// Map the array elements using a function
    pub fn map<F>(&self, f: F, manager: &DeviceMemoryManager) -> CoreResult<DeviceArray<T, D>>
    where
        F: Fn(T) -> T + Send + Sync,
        D: Clone,
    {
        // For CPU arrays, use ndarray's map function
        if self.is_on_cpu() {
            if let Some(cpuarray) = self.as_cpuarray() {
                let mapped = cpuarray.map(|&x| f(x));
                return Ok(DeviceArray {
                    buffer: DeviceBuffer::new_cpu(mapped),
                    shape: self.shape.clone(),
                    device: DeviceType::Cpu,
                    phantom: PhantomData,
                });
            }
        }

        // For GPU arrays, transfer to host, map, and transfer back
        // In a real implementation, we would use a GPU kernel
        let hostarray = manager.transfer_to_host(self, None)?;
        let mapped = hostarray.map(|&x| f(x));
        manager.transfer_to_device(&mapped, self.device, None)
    }

    /// Reduce the array using a binary operation
    pub fn reduce<F>(&self, f: F, manager: &DeviceMemoryManager) -> CoreResult<T>
    where
        F: Fn(T, T) -> T + Send + Sync,
        T: Copy,
    {
        // For CPU arrays, use ndarray's fold function
        if self.is_on_cpu() {
            if let Some(cpuarray) = self.as_cpuarray() {
                if cpuarray.is_empty() {
                    return Err(CoreError::ValueError(
                        ErrorContext::new("Cannot reduce empty array".to_string())
                            .with_location(ErrorLocation::new(file!(), line!())),
                    ));
                }

                let first = cpuarray[0];
                let result = cpuarray.iter().skip(1).fold(first, |acc, &x| f(acc, x));
                return Ok(result);
            }
        }

        // For GPU arrays, transfer to host and reduce
        // In a real implementation, we would use a GPU reduction kernel
        let hostarray = manager.transfer_to_host(self, None)?;
        if hostarray.is_empty() {
            return Err(CoreError::ValueError(
                ErrorContext::new("Cannot reduce empty array".to_string())
                    .with_location(ErrorLocation::new(file!(), line!())),
            ));
        }

        let first = *hostarray.iter().next().expect("Operation failed");
        let result = hostarray.iter().skip(1).fold(first, |acc, &x| f(acc, x));
        Ok(result)
    }
}

/// Cross-device manager for handling data transfers and operations
#[derive(Debug)]
pub struct CrossDeviceManager {
    /// Memory managers for each device
    memory_managers: HashMap<DeviceType, DeviceMemoryManager>,
    /// Memory pools for each device
    memory_pools: HashMap<DeviceType, DeviceMemoryPool>,
    /// Active data transfers
    active_transfers: Mutex<Vec<TransferEvent>>,
    /// Enable caching
    #[allow(dead_code)]
    enable_caching: bool,
    /// Maximum cache size in bytes
    #[allow(dead_code)]
    max_cache_size: usize,
}

impl CrossDeviceManager {
    /// Create a new cross-device manager
    pub fn new(max_cachesize: usize) -> CoreResult<Self> {
        let mut memory_managers = HashMap::new();
        let mut memory_pools = HashMap::new();

        // Create CPU memory manager and pool
        let cpu_manager = DeviceMemoryManager::new(max_cachesize)?;
        memory_managers.insert(DeviceType::Cpu, cpu_manager);
        memory_pools.insert(
            DeviceType::Cpu,
            DeviceMemoryPool::new(DeviceType::Cpu, max_cachesize),
        );

        // Try to create GPU memory manager and pool
        let gpu_backend = GpuBackend::preferred();
        if gpu_backend.is_available() {
            let gpu_device = DeviceType::Gpu(gpu_backend);
            let gpu_manager = DeviceMemoryManager::new(max_cachesize)?;
            memory_managers.insert(gpu_device, gpu_manager);
            memory_pools.insert(gpu_device, DeviceMemoryPool::new(gpu_device, max_cachesize));
        }

        Ok(Self {
            memory_managers,
            memory_pools,
            active_transfers: Mutex::new(Vec::new()),
            enable_caching: true,
            max_cache_size: max_cachesize,
        })
    }

    /// Get a list of available devices
    pub fn available_devices(&self) -> Vec<DeviceType> {
        self.memory_managers.keys().cloned().collect()
    }

    /// Check if a device is available
    pub fn is_device_available(&self, device: DeviceType) -> bool {
        self.memory_managers.contains_key(&device)
    }

    /// Transfer data to a device
    pub fn to_device<T, S, D>(
        &self,
        array: &ArrayBase<S, D>,
        device: DeviceType,
        options: Option<TransferOptions>,
    ) -> CoreResult<DeviceArray<T, D>>
    where
        T: GpuDataType,
        S: RawData<Elem = T> + crate::ndarray::Data,
        D: Dimension,
    {
        // Check if the device is available
        if !self.is_device_available(device) {
            return Err(CoreError::DeviceError(
                ErrorContext::new(format!("Device {device} is not available"))
                    .with_location(ErrorLocation::new(file!(), line!())),
            ));
        }

        // Get the memory manager for the device
        let manager = self.memory_managers.get(&device).expect("Operation failed");
        manager.transfer_to_device(array, device, options)
    }

    /// Transfer data from a device to the host
    pub fn to_host<T, D>(
        &self,
        devicearray: &DeviceArray<T, D>,
        options: Option<TransferOptions>,
    ) -> CoreResult<Array<T, D>>
    where
        T: GpuDataType,
        D: Dimension,
    {
        // Get the memory manager for the device
        let manager = self
            .memory_managers
            .get(&devicearray.device)
            .ok_or_else(|| {
                CoreError::DeviceError(
                    ErrorContext::new(format!("Device {} is not available", devicearray.device))
                        .with_location(ErrorLocation::new(file!(), line!())),
                )
            })?;

        manager.transfer_to_host(devicearray, options)
    }

    /// Transfer data between devices
    pub fn transfer<T, D>(
        &self,
        devicearray: &DeviceArray<T, D>,
        target_device: DeviceType,
        options: Option<TransferOptions>,
    ) -> CoreResult<DeviceArray<T, D>>
    where
        T: GpuDataType,
        D: Dimension,
    {
        // Check if the target _device is available
        if !self.is_device_available(target_device) {
            return Err(CoreError::DeviceError(
                ErrorContext::new(format!("Device {target_device} is not available"))
                    .with_location(ErrorLocation::new(file!(), line!())),
            ));
        }

        // Get the memory manager for the source _device
        let manager = self
            .memory_managers
            .get(&devicearray.device)
            .ok_or_else(|| {
                CoreError::DeviceError(
                    ErrorContext::new(format!("Device {} is not available", devicearray.device))
                        .with_location(ErrorLocation::new(file!(), line!())),
                )
            })?;

        manager.transfer_between_devices(devicearray, target_device, options)
    }

    /// Execute a kernel on a device array
    pub fn execute_kernel<T, D>(
        &self,
        devicearray: &DeviceArray<T, D>,
        kernel_name: &str,
        params: HashMap<String, KernelParam>,
    ) -> CoreResult<()>
    where
        T: GpuDataType,
        D: Dimension,
    {
        // Get the memory manager for the device
        let manager = self
            .memory_managers
            .get(&devicearray.device)
            .ok_or_else(|| {
                CoreError::DeviceError(
                    ErrorContext::new(format!("Device {} is not available", devicearray.device))
                        .with_location(ErrorLocation::new(file!(), line!())),
                )
            })?;

        manager.execute_kernel(devicearray, kernel_name, params)
    }

    /// Allocate memory on a device
    pub fn allocate<T: GpuDataType + num_traits::Zero>(
        &self,
        size: usize,
        device: DeviceType,
    ) -> CoreResult<DeviceBuffer<T>> {
        // Check if the device is available
        if !self.is_device_available(device) {
            return Err(CoreError::DeviceError(
                ErrorContext::new(format!("Device {device} is not available"))
                    .with_location(ErrorLocation::new(file!(), line!())),
            ));
        }

        // Get the memory pool for the device
        let pool = self.memory_pools.get(&device).expect("Operation failed");
        pool.allocate(size)
    }

    /// Free memory on a device
    pub fn free<T: GpuDataType>(&self, buffer: DeviceBuffer<T>, device: DeviceType) {
        // Check if the device is available
        if !self.is_device_available(device) {
            return;
        }

        // Get the memory pool for the device
        let pool = self.memory_pools.get(&device).expect("Operation failed");
        pool.free(buffer);
    }

    /// Clear all caches and pools
    pub fn clear(&self) {
        // Clear all memory managers
        for manager in self.memory_managers.values() {
            manager.clear_cache();
        }

        // Clear all memory pools
        for pool in self.memory_pools.values() {
            pool.clear();
        }

        // Clear active transfers
        let mut active_transfers = self.active_transfers.lock().expect("Operation failed");
        active_transfers.clear();
    }

    /// Wait for all active transfers to complete
    pub fn synchronize(&self) {
        let mut active_transfers = self.active_transfers.lock().expect("Operation failed");
        for event in active_transfers.drain(..) {
            event.wait();
        }
    }
}

/// Create a cross-device manager with default settings
#[allow(dead_code)]
pub fn create_cross_device_manager() -> CoreResult<CrossDeviceManager> {
    CrossDeviceManager::new(1024 * 1024 * 1024) // 1 GB cache by default
}

/// Extension trait for arrays to simplify device transfers
pub trait ToDevice<T, D>
where
    T: GpuDataType,
    D: Dimension,
{
    /// Transfer the array to a device
    fn to_device(
        &self,
        device: DeviceType,
        manager: &CrossDeviceManager,
    ) -> CoreResult<DeviceArray<T, D>>;
}

impl<T, S, D> ToDevice<T, D> for ArrayBase<S, D>
where
    T: GpuDataType,
    S: RawData<Elem = T> + crate::ndarray::Data,
    D: Dimension,
{
    fn to_device(
        &self,
        device: DeviceType,
        manager: &CrossDeviceManager,
    ) -> CoreResult<DeviceArray<T, D>> {
        manager.to_device(self, device, None)
    }
}

/// Extension trait for device arrays to simplify host transfers
pub trait ToHost<T, D>
where
    T: GpuDataType,
    D: Dimension,
{
    /// Transfer the device array to the host
    fn to_host(&self, manager: &CrossDeviceManager) -> CoreResult<Array<T, D>>;
}

impl<T, D> ToHost<T, D> for DeviceArray<T, D>
where
    T: GpuDataType,
    D: Dimension,
{
    fn to_host(&self, manager: &CrossDeviceManager) -> CoreResult<Array<T, D>> {
        manager.to_host(self, None)
    }
}

// Convenience functions

/// Create a device array on the CPU
#[allow(dead_code)]
pub fn create_cpuarray<T, S, D>(array: &ArrayBase<S, D>) -> DeviceArray<T, D>
where
    T: GpuDataType,
    S: RawData<Elem = T> + crate::ndarray::Data,
    D: Dimension,
{
    DeviceArray::new_cpu(array.to_owned())
}

/// Create a device array on the GPU
#[allow(dead_code)]
pub fn create_gpuarray<T, S, D>(
    array: &ArrayBase<S, D>,
    manager: &CrossDeviceManager,
) -> CoreResult<DeviceArray<T, D>>
where
    T: GpuDataType,
    S: RawData<Elem = T> + crate::ndarray::Data,
    D: Dimension,
{
    // Find the first available GPU
    for device in manager.available_devices() {
        if let DeviceType::Gpu(_) = device {
            return manager.to_device(array, device, None);
        }
    }

    Err(CoreError::DeviceError(
        ErrorContext::new("No GPU device available".to_string())
            .with_location(ErrorLocation::new(file!(), line!())),
    ))
}

/// Transfer an array to the best available device
#[allow(dead_code)]
pub fn to_best_device<T, S, D>(
    array: &ArrayBase<S, D>,
    manager: &CrossDeviceManager,
) -> CoreResult<DeviceArray<T, D>>
where
    T: GpuDataType,
    S: RawData<Elem = T> + crate::ndarray::Data,
    D: Dimension,
{
    // Try to find a GPU first
    for device in manager.available_devices() {
        if let DeviceType::Gpu(_) = device {
            return manager.to_device(array, device, None);
        }
    }

    // Fall back to CPU
    Ok(create_cpuarray(array))
}