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
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
//! Device enumeration and selection algorithms
//!
//! This module provides intelligent device discovery, enumeration, and selection
//! algorithms that can choose optimal devices based on workload characteristics
//! and system constraints.

use crate::device::implementations::DeviceFactory;
use crate::device::{Device, DeviceCapabilities, DeviceType};
use crate::error::Result;
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, RwLock};

/// Device discovery engine for intelligent device selection
///
/// Provides advanced device discovery capabilities with smart selection algorithms
/// that consider workload characteristics, device capabilities, and system constraints.
///
/// # Examples
///
/// ```ignore
/// use torsh_core::device::{DeviceDiscovery, WorkloadProfile};
///
/// let discovery = DeviceDiscovery::new();
/// discovery.scan_devices()?;
///
/// // Select device for specific workload
/// let workload = WorkloadProfile::training_large();
/// let device = discovery.select_optimal_device(&workload)?;
/// ```
#[derive(Debug)]
pub struct DeviceDiscovery {
    discovered_devices: RwLock<Vec<DiscoveredDevice>>,
    device_cache: RwLock<HashMap<DeviceType, Arc<dyn Device>>>,
    selection_history: RwLock<Vec<SelectionRecord>>,
    config: DiscoveryConfig,
}

impl DeviceDiscovery {
    /// Create a new device discovery engine
    pub fn new() -> Self {
        Self {
            discovered_devices: RwLock::new(Vec::new()),
            device_cache: RwLock::new(HashMap::new()),
            selection_history: RwLock::new(Vec::new()),
            config: DiscoveryConfig::default(),
        }
    }

    /// Create discovery engine with custom configuration
    pub fn with_config(config: DiscoveryConfig) -> Self {
        Self {
            discovered_devices: RwLock::new(Vec::new()),
            device_cache: RwLock::new(HashMap::new()),
            selection_history: RwLock::new(Vec::new()),
            config,
        }
    }

    /// Scan for available devices
    pub fn scan_devices(&self) -> Result<usize> {
        let mut discovered = Vec::new();

        // Scan each device type
        if self.config.scan_cpu {
            discovered.extend(self.scan_cpu_devices()?);
        }

        if self.config.scan_cuda {
            discovered.extend(self.scan_cuda_devices()?);
        }

        if self.config.scan_metal {
            discovered.extend(self.scan_metal_devices()?);
        }

        if self.config.scan_wgpu {
            discovered.extend(self.scan_wgpu_devices()?);
        }

        let count = discovered.len();

        // Update discovered devices
        {
            let mut devices = self
                .discovered_devices
                .write()
                .expect("lock should not be poisoned");
            *devices = discovered;
        }

        // Populate device cache
        self.populate_device_cache()?;

        Ok(count)
    }

    /// Get all discovered devices
    pub fn get_discovered_devices(&self) -> Vec<DiscoveredDevice> {
        let devices = self
            .discovered_devices
            .read()
            .expect("lock should not be poisoned");
        devices.clone()
    }

    /// Select optimal device for a specific workload
    pub fn select_optimal_device(
        &self,
        workload: &WorkloadProfile,
    ) -> Result<Option<Arc<dyn Device>>> {
        let devices = self
            .discovered_devices
            .read()
            .expect("lock should not be poisoned");
        let cache = self
            .device_cache
            .read()
            .expect("lock should not be poisoned");

        if devices.is_empty() {
            return Ok(None);
        }

        let mut best_device = None;
        let mut best_score = 0.0;

        for discovered in devices.iter() {
            if !discovered.is_available {
                continue;
            }

            // Check workload compatibility
            if !self.is_workload_compatible(discovered, workload)? {
                continue;
            }

            // Calculate fitness score
            let score = self.calculate_fitness_score(discovered, workload)?;

            if score > best_score {
                best_score = score;
                best_device = cache.get(&discovered.device_type).cloned();
            }
        }

        // Record selection
        if let Some(ref device) = best_device {
            self.record_selection(device.device_type(), workload.clone(), best_score);
        }

        Ok(best_device)
    }

    /// Select multiple devices for distributed workload
    pub fn select_devices_for_distributed_workload(
        &self,
        workload: &WorkloadProfile,
        target_count: usize,
    ) -> Result<Vec<Arc<dyn Device>>> {
        let devices = self
            .discovered_devices
            .read()
            .expect("lock should not be poisoned");
        let cache = self
            .device_cache
            .read()
            .expect("lock should not be poisoned");

        let mut candidates: Vec<_> = devices
            .iter()
            .filter(|d| d.is_available && self.is_workload_compatible(d, workload).unwrap_or(false))
            .collect();

        // Sort by fitness score
        candidates.sort_by(|a, b| {
            let score_a = self.calculate_fitness_score(a, workload).unwrap_or(0.0);
            let score_b = self.calculate_fitness_score(b, workload).unwrap_or(0.0);
            score_b
                .partial_cmp(&score_a)
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        let selected: Vec<_> = candidates
            .into_iter()
            .take(target_count)
            .filter_map(|d| cache.get(&d.device_type).cloned())
            .collect();

        Ok(selected)
    }

    /// Get devices by capability requirements
    pub fn get_devices_by_capabilities(
        &self,
        requirements: &CapabilityRequirements,
    ) -> Result<Vec<Arc<dyn Device>>> {
        let devices = self
            .discovered_devices
            .read()
            .expect("lock should not be poisoned");
        let cache = self
            .device_cache
            .read()
            .expect("lock should not be poisoned");

        let mut matching_devices = Vec::new();

        for discovered in devices.iter() {
            if !discovered.is_available {
                continue;
            }

            if self.meets_capability_requirements(discovered, requirements)? {
                if let Some(device) = cache.get(&discovered.device_type) {
                    matching_devices.push(device.clone());
                }
            }
        }

        Ok(matching_devices)
    }

    /// Recommend device for specific use case
    pub fn recommend_device(&self, use_case: UseCase) -> Result<DeviceRecommendation> {
        let workload = match use_case {
            UseCase::Training => WorkloadProfile::training_large(),
            UseCase::Inference => WorkloadProfile::inference(),
            UseCase::Development => WorkloadProfile::development(),
            UseCase::Benchmarking => WorkloadProfile::benchmarking(),
            UseCase::Research => WorkloadProfile::research(),
        };

        let devices = self
            .discovered_devices
            .read()
            .expect("lock should not be poisoned");
        let cache = self
            .device_cache
            .read()
            .expect("lock should not be poisoned");

        let mut recommendations = Vec::new();

        for discovered in devices.iter() {
            if !discovered.is_available {
                continue;
            }

            let score = self.calculate_fitness_score(discovered, &workload)?;
            let reasoning = self.generate_recommendation_reasoning(discovered, &workload, score);

            if let Some(device) = cache.get(&discovered.device_type) {
                recommendations.push(DeviceOption {
                    device: device.clone(),
                    score,
                    reasoning,
                    estimated_performance: self.estimate_performance(discovered, &workload)?,
                });
            }
        }

        // Sort by score
        recommendations.sort_by(|a, b| {
            b.score
                .partial_cmp(&a.score)
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        Ok(DeviceRecommendation {
            use_case,
            options: recommendations,
            workload_profile: workload,
        })
    }

    /// Get device discovery statistics
    pub fn get_statistics(&self) -> DiscoveryStatistics {
        let devices = self
            .discovered_devices
            .read()
            .expect("lock should not be poisoned");
        let history = self
            .selection_history
            .read()
            .expect("lock should not be poisoned");

        let total_devices = devices.len();
        let available_devices = devices.iter().filter(|d| d.is_available).count();

        let device_types: HashSet<_> = devices.iter().map(|d| d.device_type).collect();
        let unique_device_types = device_types.len();

        let total_memory: u64 = devices.iter().map(|d| d.capabilities.total_memory()).sum();

        DiscoveryStatistics {
            total_devices,
            available_devices,
            unique_device_types,
            total_memory_gb: total_memory / (1024 * 1024 * 1024),
            total_selections: history.len(),
        }
    }

    fn scan_cpu_devices(&self) -> Result<Vec<DiscoveredDevice>> {
        let mut devices = Vec::new();

        let device_type = DeviceType::Cpu;
        if DeviceFactory::is_device_type_available(device_type) {
            let capabilities = DeviceCapabilities::detect(device_type)?;
            let platform_info = self.detect_cpu_platform_info();

            devices.push(DiscoveredDevice {
                device_type,
                capabilities,
                is_available: true,
                platform_info,
                discovery_time: std::time::Instant::now(),
            });
        }

        Ok(devices)
    }

    fn scan_cuda_devices(&self) -> Result<Vec<DiscoveredDevice>> {
        #[allow(unused_mut)] // mut needed for conditional compilation features
        let mut devices = Vec::new();

        #[cfg(feature = "cuda")]
        {
            // In a real implementation, this would query CUDA runtime
            for index in 0..2 {
                let device_type = DeviceType::Cuda(index);
                if DeviceFactory::is_device_type_available(device_type) {
                    if let Ok(capabilities) = DeviceCapabilities::detect(device_type) {
                        let platform_info = self.detect_cuda_platform_info(index);

                        devices.push(DiscoveredDevice {
                            device_type,
                            capabilities,
                            is_available: true,
                            platform_info,
                            discovery_time: std::time::Instant::now(),
                        });
                    }
                }
            }
        }

        Ok(devices)
    }

    fn scan_metal_devices(&self) -> Result<Vec<DiscoveredDevice>> {
        #[allow(unused_mut)] // mut needed for conditional compilation features
        let mut devices = Vec::new();

        #[cfg(target_os = "macos")]
        {
            let device_type = DeviceType::Metal(0);
            if DeviceFactory::is_device_type_available(device_type) {
                if let Ok(capabilities) = DeviceCapabilities::detect(device_type) {
                    let platform_info = self.detect_metal_platform_info();

                    devices.push(DiscoveredDevice {
                        device_type,
                        capabilities,
                        is_available: true,
                        platform_info,
                        discovery_time: std::time::Instant::now(),
                    });
                }
            }
        }

        Ok(devices)
    }

    fn scan_wgpu_devices(&self) -> Result<Vec<DiscoveredDevice>> {
        #[allow(unused_mut)] // mut needed for conditional compilation features
        let mut devices = Vec::new();

        #[cfg(feature = "wgpu")]
        {
            let device_type = DeviceType::Wgpu(0);
            if DeviceFactory::is_device_type_available(device_type) {
                if let Ok(capabilities) = DeviceCapabilities::detect(device_type) {
                    let platform_info = self.detect_wgpu_platform_info();

                    devices.push(DiscoveredDevice {
                        device_type,
                        capabilities,
                        is_available: true,
                        platform_info,
                        discovery_time: std::time::Instant::now(),
                    });
                }
            }
        }

        Ok(devices)
    }

    fn populate_device_cache(&self) -> Result<()> {
        let devices = self
            .discovered_devices
            .read()
            .expect("lock should not be poisoned");
        let mut cache = self
            .device_cache
            .write()
            .expect("lock should not be poisoned");

        cache.clear();

        for discovered in devices.iter() {
            if discovered.is_available {
                if let Ok(device) = DeviceFactory::create_device(discovered.device_type) {
                    let arc_device: Arc<dyn Device> = device.into();
                    cache.insert(discovered.device_type, arc_device);
                }
            }
        }

        Ok(())
    }

    fn is_workload_compatible(
        &self,
        device: &DiscoveredDevice,
        workload: &WorkloadProfile,
    ) -> Result<bool> {
        // Check memory requirements
        if device.capabilities.available_memory() < workload.min_memory_bytes {
            return Ok(false);
        }

        // Check compute requirements
        if device.capabilities.compute_units() < workload.min_compute_units {
            return Ok(false);
        }

        // Check precision requirements
        if workload.requires_fp64 && !device.capabilities.supports_double_precision() {
            return Ok(false);
        }

        if workload.requires_fp16 && !device.capabilities.supports_half_precision() {
            return Ok(false);
        }

        // Check device type constraints
        match workload.device_preference {
            DevicePreference::GpuOnly => {
                if device.device_type.is_cpu() {
                    return Ok(false);
                }
            }
            DevicePreference::CpuOnly => {
                if !device.device_type.is_cpu() {
                    return Ok(false);
                }
            }
            DevicePreference::CudaOnly => {
                if !device.device_type.is_cuda() {
                    return Ok(false);
                }
            }
            DevicePreference::Any => {}
        }

        Ok(true)
    }

    fn calculate_fitness_score(
        &self,
        device: &DiscoveredDevice,
        workload: &WorkloadProfile,
    ) -> Result<f64> {
        let mut score = 0.0;

        // Base performance score
        let perf_score = device.capabilities.compute_score() as f64 / 1_000_000.0;
        score += perf_score * workload.performance_weight;

        // Memory score
        let memory_ratio =
            device.capabilities.available_memory() as f64 / workload.min_memory_bytes as f64;
        let memory_score = memory_ratio.min(2.0); // Cap at 2x requirement
        score += memory_score * workload.memory_weight;

        // Efficiency score (performance per watt, estimated)
        let efficiency_score = self.estimate_efficiency(device)?;
        score += efficiency_score * workload.efficiency_weight;

        // Compatibility bonus
        if device.device_type.is_gpu() && workload.prefers_gpu {
            score += 0.5;
        }

        if device.capabilities.supports_double_precision() && workload.requires_fp64 {
            score += 0.3;
        }

        if device.capabilities.supports_half_precision() && workload.requires_fp16 {
            score += 0.2;
        }

        // Selection history bonus (prefer previously successful devices)
        let history_bonus = self.get_history_bonus(device.device_type, workload);
        score += history_bonus;

        Ok(score)
    }

    fn meets_capability_requirements(
        &self,
        device: &DiscoveredDevice,
        requirements: &CapabilityRequirements,
    ) -> Result<bool> {
        if let Some(min_memory) = requirements.min_memory_gb {
            if device.capabilities.total_memory_mb() < min_memory * 1024 {
                return Ok(false);
            }
        }

        if let Some(min_cores) = requirements.min_compute_units {
            if device.capabilities.compute_units() < min_cores {
                return Ok(false);
            }
        }

        if requirements.requires_gpu && device.device_type.is_cpu() {
            return Ok(false);
        }

        if requirements.requires_fp64 && !device.capabilities.supports_double_precision() {
            return Ok(false);
        }

        if requirements.requires_fp16 && !device.capabilities.supports_half_precision() {
            return Ok(false);
        }

        for feature in &requirements.required_features {
            if !device.capabilities.supports_feature(feature) {
                return Ok(false);
            }
        }

        Ok(true)
    }

    fn estimate_efficiency(&self, device: &DiscoveredDevice) -> Result<f64> {
        // Estimate efficiency based on device type and capabilities
        match device.device_type {
            DeviceType::Cpu => Ok(0.5), // CPUs are generally less efficient for ML
            DeviceType::Cuda(_) => Ok(0.9), // CUDA GPUs are highly efficient
            DeviceType::Metal(_) => Ok(0.8), // Metal is efficient but slightly less than CUDA
            DeviceType::Wgpu(_) => Ok(0.6), // WebGPU has overhead
        }
    }

    fn estimate_performance(
        &self,
        device: &DiscoveredDevice,
        workload: &WorkloadProfile,
    ) -> Result<PerformanceEstimate> {
        let base_throughput = device.capabilities.compute_score() as f64;

        // Adjust for workload type
        let workload_multiplier = match workload.workload_type {
            WorkloadType::Training => 1.0,
            WorkloadType::Inference => 1.2, // Inference is typically faster
            WorkloadType::Validation => 1.1,
            WorkloadType::Benchmarking => 0.9, // Benchmarks might be more demanding
        };

        let estimated_throughput = base_throughput * workload_multiplier;

        // Estimate latency based on device type
        let estimated_latency_ms = match device.device_type {
            DeviceType::Cpu => 10.0,
            DeviceType::Cuda(_) => 2.0,
            DeviceType::Metal(_) => 3.0,
            DeviceType::Wgpu(_) => 5.0,
        };

        Ok(PerformanceEstimate {
            throughput: estimated_throughput,
            latency_ms: estimated_latency_ms,
            memory_bandwidth_gbps: device.capabilities.peak_bandwidth_gbps().unwrap_or(1.0),
        })
    }

    fn generate_recommendation_reasoning(
        &self,
        device: &DiscoveredDevice,
        workload: &WorkloadProfile,
        score: f64,
    ) -> String {
        let mut reasons = Vec::new();

        if device.device_type.is_gpu() && workload.prefers_gpu {
            reasons.push("GPU acceleration preferred for this workload".to_string());
        }

        if device.capabilities.total_memory_mb() > workload.min_memory_bytes / (1024 * 1024) {
            reasons.push(format!(
                "Sufficient memory ({:.1}GB available)",
                device.capabilities.total_memory_mb() as f64 / 1024.0
            ));
        }

        if device.capabilities.supports_half_precision() && workload.requires_fp16 {
            reasons.push("Supports required half-precision operations".to_string());
        }

        if score > 2.0 {
            reasons.push("High performance score for workload requirements".to_string());
        } else if score > 1.0 {
            reasons.push("Good performance score for workload requirements".to_string());
        }

        if reasons.is_empty() {
            "Meets basic requirements".to_string()
        } else {
            reasons.join("; ")
        }
    }

    fn get_history_bonus(&self, device_type: DeviceType, workload: &WorkloadProfile) -> f64 {
        let history = self
            .selection_history
            .read()
            .expect("lock should not be poisoned");

        let successful_selections = history
            .iter()
            .filter(|record| {
                record.device_type == device_type
                    && record.workload.workload_type == workload.workload_type
                    && record.success_score > 1.0
            })
            .count();

        // Small bonus for previously successful selections
        (successful_selections as f64) * 0.1
    }

    fn record_selection(&self, device_type: DeviceType, workload: WorkloadProfile, score: f64) {
        let mut history = self
            .selection_history
            .write()
            .expect("lock should not be poisoned");
        history.push(SelectionRecord {
            device_type,
            workload,
            success_score: score,
            timestamp: std::time::Instant::now(),
        });

        // Keep history bounded
        if history.len() > 1000 {
            history.remove(0);
        }
    }

    fn detect_cpu_platform_info(&self) -> PlatformInfo {
        PlatformInfo {
            vendor: "Unknown".to_string(),
            architecture: std::env::consts::ARCH.to_string(),
            features: vec!["sse2".to_string(), "avx".to_string()],
            driver_version: None,
        }
    }

    #[allow(dead_code)]
    fn detect_cuda_platform_info(&self, _index: usize) -> PlatformInfo {
        PlatformInfo {
            vendor: "NVIDIA".to_string(),
            architecture: "CUDA".to_string(),
            features: vec!["compute_capability_8_6".to_string()],
            driver_version: Some("12.0".to_string()),
        }
    }

    #[allow(dead_code)] // Metal platform info - only used on macOS
    fn detect_metal_platform_info(&self) -> PlatformInfo {
        PlatformInfo {
            vendor: "Apple".to_string(),
            architecture: "Apple Silicon".to_string(),
            features: vec!["unified_memory".to_string(), "tile_shaders".to_string()],
            driver_version: Some("Metal 3.0".to_string()),
        }
    }

    #[allow(dead_code)]
    fn detect_wgpu_platform_info(&self) -> PlatformInfo {
        PlatformInfo {
            vendor: "WebGPU".to_string(),
            architecture: "WebGPU".to_string(),
            features: vec!["compute_shaders".to_string()],
            driver_version: Some("1.0".to_string()),
        }
    }
}

/// Discovered device information
#[derive(Debug, Clone)]
pub struct DiscoveredDevice {
    /// Type of the discovered device
    pub device_type: DeviceType,
    /// Capabilities of the device
    pub capabilities: DeviceCapabilities,
    /// Whether the device is currently available
    pub is_available: bool,
    /// Platform-specific information
    pub platform_info: PlatformInfo,
    /// When this device was discovered
    pub discovery_time: std::time::Instant,
}

/// Platform-specific device information
#[derive(Debug, Clone)]
pub struct PlatformInfo {
    /// Device vendor name
    pub vendor: String,
    /// Device architecture description
    pub architecture: String,
    /// List of supported features
    pub features: Vec<String>,
    /// Driver version if available
    pub driver_version: Option<String>,
}

/// Workload profile for device selection
#[derive(Debug, Clone)]
pub struct WorkloadProfile {
    /// Type of workload (training, inference, etc.)
    pub workload_type: WorkloadType,
    /// Minimum required memory in bytes
    pub min_memory_bytes: u64,
    /// Minimum required compute units
    pub min_compute_units: u32,
    /// Whether 64-bit floating point is required
    pub requires_fp64: bool,
    /// Whether 16-bit floating point is required
    pub requires_fp16: bool,
    /// Whether GPU is preferred for this workload
    pub prefers_gpu: bool,
    /// Device preference policy
    pub device_preference: DevicePreference,
    /// Weight for performance in selection (0.0-1.0)
    pub performance_weight: f64,
    /// Weight for memory capacity in selection (0.0-1.0)
    pub memory_weight: f64,
    /// Weight for power efficiency in selection (0.0-1.0)
    pub efficiency_weight: f64,
}

impl WorkloadProfile {
    /// Profile for large model training
    pub fn training_large() -> Self {
        Self {
            workload_type: WorkloadType::Training,
            min_memory_bytes: 8 * 1024 * 1024 * 1024, // 8GB
            min_compute_units: 32,
            requires_fp64: false,
            requires_fp16: true,
            prefers_gpu: true,
            device_preference: DevicePreference::GpuOnly,
            performance_weight: 1.0,
            memory_weight: 0.8,
            efficiency_weight: 0.6,
        }
    }

    /// Profile for inference
    pub fn inference() -> Self {
        Self {
            workload_type: WorkloadType::Inference,
            min_memory_bytes: 2 * 1024 * 1024 * 1024, // 2GB
            min_compute_units: 8,
            requires_fp64: false,
            requires_fp16: true,
            prefers_gpu: true,
            device_preference: DevicePreference::Any,
            performance_weight: 0.8,
            memory_weight: 0.6,
            efficiency_weight: 1.0,
        }
    }

    /// Profile for development work
    pub fn development() -> Self {
        Self {
            workload_type: WorkloadType::Training,
            min_memory_bytes: 1024 * 1024 * 1024, // 1GB
            min_compute_units: 4,
            requires_fp64: false,
            requires_fp16: false,
            prefers_gpu: false,
            device_preference: DevicePreference::Any,
            performance_weight: 0.5,
            memory_weight: 0.7,
            efficiency_weight: 0.3,
        }
    }

    /// Profile for benchmarking
    pub fn benchmarking() -> Self {
        Self {
            workload_type: WorkloadType::Benchmarking,
            min_memory_bytes: 4 * 1024 * 1024 * 1024, // 4GB
            min_compute_units: 16,
            requires_fp64: true,
            requires_fp16: true,
            prefers_gpu: true,
            device_preference: DevicePreference::Any,
            performance_weight: 1.0,
            memory_weight: 0.5,
            efficiency_weight: 0.5,
        }
    }

    /// Profile for research work
    pub fn research() -> Self {
        Self {
            workload_type: WorkloadType::Training,
            min_memory_bytes: 16 * 1024 * 1024 * 1024, // 16GB
            min_compute_units: 64,
            requires_fp64: true,
            requires_fp16: true,
            prefers_gpu: true,
            device_preference: DevicePreference::Any,
            performance_weight: 1.0,
            memory_weight: 1.0,
            efficiency_weight: 0.4,
        }
    }
}

/// Workload type classification
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WorkloadType {
    /// Model training workload
    Training,
    /// Model inference workload
    Inference,
    /// Validation workload
    Validation,
    /// Benchmarking workload
    Benchmarking,
}

/// Device preference for workload
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DevicePreference {
    /// Any available device
    Any,
    /// GPU devices only
    GpuOnly,
    /// CPU devices only
    CpuOnly,
    /// CUDA devices only
    CudaOnly,
}

/// Use case for device recommendation
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UseCase {
    /// Model training use case
    Training,
    /// Model inference use case
    Inference,
    /// Development use case
    Development,
    /// Benchmarking use case
    Benchmarking,
    /// Research use case
    Research,
}

/// Capability requirements for device filtering
#[derive(Debug, Clone)]
pub struct CapabilityRequirements {
    /// Minimum memory in GB
    pub min_memory_gb: Option<u64>,
    /// Minimum compute units
    pub min_compute_units: Option<u32>,
    /// Whether GPU is required
    pub requires_gpu: bool,
    /// Whether 64-bit floating point is required
    pub requires_fp64: bool,
    /// Whether 16-bit floating point is required
    pub requires_fp16: bool,
    /// Required device features
    pub required_features: Vec<String>,
}

impl CapabilityRequirements {
    /// Create basic capability requirements with no restrictions
    pub fn basic() -> Self {
        Self {
            min_memory_gb: None,
            min_compute_units: None,
            requires_gpu: false,
            requires_fp64: false,
            requires_fp16: false,
            required_features: Vec::new(),
        }
    }

    /// Create capability requirements for GPU training
    pub fn gpu_training() -> Self {
        Self {
            min_memory_gb: Some(4),
            min_compute_units: Some(16),
            requires_gpu: true,
            requires_fp64: false,
            requires_fp16: true,
            required_features: vec!["tensor_cores".to_string()],
        }
    }
}

/// Device recommendation result
#[derive(Debug)]
pub struct DeviceRecommendation {
    /// Use case for this recommendation
    pub use_case: UseCase,
    /// List of recommended device options
    pub options: Vec<DeviceOption>,
    /// Workload profile used for recommendation
    pub workload_profile: WorkloadProfile,
}

/// Individual device option in recommendation
#[derive(Debug)]
pub struct DeviceOption {
    /// The recommended device
    pub device: Arc<dyn Device>,
    /// Fitness score for this device (0.0-1.0)
    pub score: f64,
    /// Human-readable reasoning for recommendation
    pub reasoning: String,
    /// Estimated performance characteristics
    pub estimated_performance: PerformanceEstimate,
}

/// Performance estimate for a device
#[derive(Debug, Clone)]
pub struct PerformanceEstimate {
    /// Estimated throughput (operations/second)
    pub throughput: f64,
    /// Estimated latency in milliseconds
    pub latency_ms: f64,
    /// Memory bandwidth in GB/s
    pub memory_bandwidth_gbps: f64,
}

/// Selection history record
#[derive(Debug, Clone)]
struct SelectionRecord {
    device_type: DeviceType,
    workload: WorkloadProfile,
    success_score: f64,
    #[allow(dead_code)] // Part of future device selection history tracking
    timestamp: std::time::Instant,
}

/// Discovery configuration
#[derive(Debug, Clone)]
pub struct DiscoveryConfig {
    /// Whether to scan for CPU devices
    pub scan_cpu: bool,
    /// Whether to scan for CUDA devices
    pub scan_cuda: bool,
    /// Whether to scan for Metal devices
    pub scan_metal: bool,
    /// Whether to scan for WebGPU devices
    pub scan_wgpu: bool,
    /// Whether to cache discovered devices
    pub cache_discoveries: bool,
    /// Whether to track device selection history
    pub track_selection_history: bool,
}

impl Default for DiscoveryConfig {
    fn default() -> Self {
        Self {
            scan_cpu: true,
            scan_cuda: cfg!(feature = "cuda"),
            scan_metal: cfg!(target_os = "macos"),
            scan_wgpu: cfg!(feature = "wgpu"),
            cache_discoveries: true,
            track_selection_history: true,
        }
    }
}

/// Discovery statistics
#[derive(Debug, Clone)]
pub struct DiscoveryStatistics {
    /// Total number of devices discovered
    pub total_devices: usize,
    /// Number of currently available devices
    pub available_devices: usize,
    /// Number of unique device types
    pub unique_device_types: usize,
    /// Total memory across all devices in GB
    pub total_memory_gb: u64,
    /// Total number of device selections made
    pub total_selections: usize,
}

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

/// Utility functions for device discovery
pub mod utils {
    use super::*;

    /// Create discovery engine and perform initial scan
    pub fn create_and_scan() -> Result<DeviceDiscovery> {
        let discovery = DeviceDiscovery::new();
        discovery.scan_devices()?;
        Ok(discovery)
    }

    /// Quick device selection for common use cases
    pub fn quick_select_for_training() -> Result<Option<Arc<dyn Device>>> {
        let discovery = create_and_scan()?;
        let workload = WorkloadProfile::training_large();
        discovery.select_optimal_device(&workload)
    }

    /// Quick device selection for inference
    pub fn quick_select_for_inference() -> Result<Option<Arc<dyn Device>>> {
        let discovery = create_and_scan()?;
        let workload = WorkloadProfile::inference();
        discovery.select_optimal_device(&workload)
    }

    /// Get best GPU device if available
    pub fn get_best_gpu() -> Result<Option<Arc<dyn Device>>> {
        let discovery = create_and_scan()?;
        let requirements = CapabilityRequirements {
            min_memory_gb: Some(1),
            min_compute_units: Some(8),
            requires_gpu: true,
            requires_fp64: false,
            requires_fp16: false,
            required_features: Vec::new(),
        };

        let devices = discovery.get_devices_by_capabilities(&requirements)?;
        Ok(devices.into_iter().next())
    }

    /// Create summary of all discovered devices
    pub fn create_device_summary() -> Result<Vec<String>> {
        let discovery = create_and_scan()?;
        let devices = discovery.get_discovered_devices();

        let summary = devices
            .iter()
            .map(|device| {
                format!(
                    "{:?} - {:.1}GB, {} cores, {}",
                    device.device_type,
                    device.capabilities.total_memory_mb() as f64 / 1024.0,
                    device.capabilities.compute_units(),
                    if device.is_available {
                        "Available"
                    } else {
                        "Unavailable"
                    }
                )
            })
            .collect();

        Ok(summary)
    }

    /// Check if any high-performance devices are available
    pub fn has_high_performance_devices() -> Result<bool> {
        let discovery = create_and_scan()?;
        let requirements = CapabilityRequirements {
            min_memory_gb: Some(8),
            min_compute_units: Some(32),
            requires_gpu: true,
            requires_fp64: false,
            requires_fp16: true,
            required_features: Vec::new(),
        };

        let devices = discovery.get_devices_by_capabilities(&requirements)?;
        Ok(!devices.is_empty())
    }
}

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

    #[test]
    fn test_device_discovery() {
        let discovery = DeviceDiscovery::new();
        let count = discovery
            .scan_devices()
            .expect("scan_devices should succeed");
        assert!(count > 0); // At least CPU should be discovered

        let devices = discovery.get_discovered_devices();
        assert!(!devices.is_empty());

        // CPU device should always be found
        assert!(devices.iter().any(|d| d.device_type == DeviceType::Cpu));
    }

    #[test]
    fn test_workload_profiles() {
        let training = WorkloadProfile::training_large();
        assert_eq!(training.workload_type, WorkloadType::Training);
        assert!(training.prefers_gpu);
        assert!(training.requires_fp16);

        let inference = WorkloadProfile::inference();
        assert_eq!(inference.workload_type, WorkloadType::Inference);
        assert!(inference.min_memory_bytes < training.min_memory_bytes);

        let development = WorkloadProfile::development();
        assert!(!development.prefers_gpu);
    }

    #[test]
    fn test_capability_requirements() {
        let basic = CapabilityRequirements::basic();
        assert!(!basic.requires_gpu);
        assert!(basic.required_features.is_empty());

        let gpu_training = CapabilityRequirements::gpu_training();
        assert!(gpu_training.requires_gpu);
        assert!(gpu_training.min_memory_gb.is_some());
        assert!(!gpu_training.required_features.is_empty());
    }

    #[test]
    fn test_device_selection() {
        let discovery = DeviceDiscovery::new();
        discovery
            .scan_devices()
            .expect("scan_devices should succeed");

        let workload = WorkloadProfile::development();
        let device = discovery
            .select_optimal_device(&workload)
            .expect("select_optimal_device should succeed");
        assert!(device.is_some()); // Should find at least CPU

        let distributed = discovery
            .select_devices_for_distributed_workload(&workload, 2)
            .expect("select_devices_for_distributed_workload should succeed");
        assert!(!distributed.is_empty());
    }

    #[test]
    fn test_device_recommendation() {
        let discovery = DeviceDiscovery::new();
        discovery
            .scan_devices()
            .expect("scan_devices should succeed");

        let recommendation = discovery
            .recommend_device(UseCase::Development)
            .expect("recommend_device should succeed");
        assert_eq!(recommendation.use_case, UseCase::Development);
        assert!(!recommendation.options.is_empty());

        for option in &recommendation.options {
            assert!(option.score >= 0.0);
            assert!(!option.reasoning.is_empty());
        }
    }

    #[test]
    fn test_discovery_statistics() {
        let discovery = DeviceDiscovery::new();
        discovery
            .scan_devices()
            .expect("scan_devices should succeed");

        let stats = discovery.get_statistics();
        assert!(stats.total_devices > 0);
        assert!(stats.available_devices > 0);
        assert!(stats.unique_device_types > 0);
    }

    #[test]
    fn test_utils_functions() {
        let discovery = utils::create_and_scan().expect("create_and_scan should succeed");
        assert!(!discovery.get_discovered_devices().is_empty());

        let _training_device =
            utils::quick_select_for_training().expect("quick_select_for_training should succeed");
        // May or may not find a suitable device depending on system

        let _inference_device =
            utils::quick_select_for_inference().expect("quick_select_for_inference should succeed");
        // Should at least find CPU for inference

        let summary = utils::create_device_summary().expect("create_device_summary should succeed");
        assert!(!summary.is_empty());

        let _has_hp = utils::has_high_performance_devices()
            .expect("has_high_performance_devices should succeed");
        // Result depends on available hardware
    }

    #[test]
    fn test_platform_info() {
        let discovery = DeviceDiscovery::new();
        let cpu_info = discovery.detect_cpu_platform_info();
        assert!(!cpu_info.vendor.is_empty());
        assert!(!cpu_info.architecture.is_empty());
    }

    #[test]
    fn test_performance_estimate() {
        let discovery = DeviceDiscovery::new();
        discovery
            .scan_devices()
            .expect("scan_devices should succeed");

        let devices = discovery.get_discovered_devices();
        if let Some(device) = devices.first() {
            let workload = WorkloadProfile::development();
            let estimate = discovery
                .estimate_performance(device, &workload)
                .expect("estimate_performance should succeed");
            assert!(estimate.throughput > 0.0);
            assert!(estimate.latency_ms > 0.0);
        }
    }
}