amari-gpu 0.24.1

GPU acceleration for mathematical computations
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
//! Unified GPU acceleration infrastructure for all mathematical domains
//!
//! This module provides a common interface and infrastructure for GPU acceleration
//! across tropical algebra, automatic differentiation, fusion systems, and other
//! mathematical domains in the Amari library.

use crate::{
    multi_gpu::{
        DeviceId, GpuDevice, IntelligentLoadBalancer, LoadBalancingStrategy, Workload,
        WorkloadCoordinator,
    },
    GpuError,
};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Instant;
use thiserror::Error;
use tokio::sync::RwLock;
use wgpu::util::DeviceExt;

#[derive(Error, Debug)]
pub enum UnifiedGpuError {
    #[error("GPU error: {0}")]
    Gpu(#[from] GpuError),

    #[error("Shader compilation failed: {0}")]
    ShaderCompilation(String),

    #[error("Buffer size mismatch: expected {expected}, got {actual}")]
    BufferSizeMismatch { expected: usize, actual: usize },

    #[error("Invalid operation: {0}")]
    InvalidOperation(String),

    #[error("Memory allocation failed: {0}")]
    MemoryAllocation(String),
}

pub type UnifiedGpuResult<T> = Result<T, UnifiedGpuError>;

/// Universal trait for GPU-accelerated mathematical operations
pub trait GpuAccelerated<T> {
    /// Convert data to GPU buffer format
    fn to_gpu_buffer(&self, context: &GpuContext) -> UnifiedGpuResult<wgpu::Buffer>;

    /// Reconstruct data from GPU buffer
    fn from_gpu_buffer(buffer: &wgpu::Buffer, context: &GpuContext) -> UnifiedGpuResult<T>;

    /// Execute GPU operation
    fn gpu_operation(
        &self,
        operation: &str,
        context: &GpuContext,
        params: &GpuOperationParams,
    ) -> UnifiedGpuResult<T>;
}

/// GPU operation parameters for flexible operation dispatch
#[derive(Debug, Clone)]
pub struct GpuOperationParams {
    /// Operation-specific parameters
    pub params: HashMap<String, GpuParam>,
    /// Batch size for operations
    pub batch_size: usize,
    /// Workgroup size for compute shaders
    pub workgroup_size: (u32, u32, u32),
}

/// Parameter types for GPU operations
#[derive(Debug, Clone)]
pub enum GpuParam {
    Float(f32),
    Double(f64),
    Integer(i32),
    UnsignedInteger(u32),
    Buffer(String), // Buffer identifier
    Array(Vec<f32>),
}

impl Default for GpuOperationParams {
    fn default() -> Self {
        Self {
            params: HashMap::new(),
            batch_size: 1,
            workgroup_size: (1, 1, 1),
        }
    }
}

/// Unified GPU context managing device, queue, and shader cache
pub struct GpuContext {
    pub device: wgpu::Device,
    pub queue: wgpu::Queue,
    shader_cache: HashMap<String, wgpu::ComputePipeline>,
    #[allow(dead_code)]
    buffer_pool: GpuBufferPool,
}

impl GpuContext {
    /// Initialize GPU context with WebGPU
    pub async fn new() -> UnifiedGpuResult<Self> {
        let instance = wgpu::Instance::default();

        let adapter = instance
            .request_adapter(&wgpu::RequestAdapterOptions {
                power_preference: wgpu::PowerPreference::HighPerformance,
                compatible_surface: None,
                force_fallback_adapter: false,
            })
            .await
            .ok_or_else(|| {
                UnifiedGpuError::Gpu(GpuError::InitializationError(
                    "No GPU adapter found".to_string(),
                ))
            })?;

        let (device, queue) = adapter
            .request_device(
                &wgpu::DeviceDescriptor {
                    label: Some("Amari Unified GPU Device"),
                    required_features: wgpu::Features::empty(),
                    required_limits: wgpu::Limits::default(),
                },
                None,
            )
            .await
            .map_err(|e| UnifiedGpuError::Gpu(GpuError::InitializationError(e.to_string())))?;

        Ok(Self {
            device,
            queue,
            shader_cache: HashMap::new(),
            buffer_pool: GpuBufferPool::new(),
        })
    }

    /// Get or compile compute shader
    pub fn get_compute_pipeline(
        &mut self,
        shader_key: &str,
        shader_source: &str,
        bind_group_layout: &wgpu::BindGroupLayout,
    ) -> UnifiedGpuResult<&wgpu::ComputePipeline> {
        if !self.shader_cache.contains_key(shader_key) {
            let shader_module = self
                .device
                .create_shader_module(wgpu::ShaderModuleDescriptor {
                    label: Some(&format!("{} Shader", shader_key)),
                    source: wgpu::ShaderSource::Wgsl(shader_source.into()),
                });

            let pipeline_layout =
                self.device
                    .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                        label: Some(&format!("{} Pipeline Layout", shader_key)),
                        bind_group_layouts: &[bind_group_layout],
                        push_constant_ranges: &[],
                    });

            let compute_pipeline =
                self.device
                    .create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
                        label: Some(&format!("{} Pipeline", shader_key)),
                        layout: Some(&pipeline_layout),
                        module: &shader_module,
                        entry_point: "main",
                    });

            self.shader_cache
                .insert(shader_key.to_string(), compute_pipeline);
        }

        Ok(self
            .shader_cache
            .get(shader_key)
            .expect("Pipeline should exist"))
    }

    /// Create buffer with data
    pub fn create_buffer_with_data<T: bytemuck::Pod>(
        &self,
        label: &str,
        data: &[T],
        usage: wgpu::BufferUsages,
    ) -> wgpu::Buffer {
        self.device
            .create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some(label),
                contents: bytemuck::cast_slice(data),
                usage,
            })
    }

    /// Create empty buffer
    pub fn create_buffer(&self, label: &str, size: u64, usage: wgpu::BufferUsages) -> wgpu::Buffer {
        self.device.create_buffer(&wgpu::BufferDescriptor {
            label: Some(label),
            size,
            usage,
            mapped_at_creation: false,
        })
    }

    /// Execute compute shader
    pub fn execute_compute(
        &self,
        pipeline: &wgpu::ComputePipeline,
        bind_group: &wgpu::BindGroup,
        workgroup_count: (u32, u32, u32),
    ) {
        let mut encoder = self
            .device
            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("Compute Encoder"),
            });

        {
            let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                label: Some("Compute Pass"),
                timestamp_writes: None,
            });
            compute_pass.set_pipeline(pipeline);
            compute_pass.set_bind_group(0, bind_group, &[]);
            compute_pass.dispatch_workgroups(
                workgroup_count.0,
                workgroup_count.1,
                workgroup_count.2,
            );
        }

        self.queue.submit([encoder.finish()]);
    }

    /// Read buffer data back to CPU
    pub async fn read_buffer<T: bytemuck::Pod + Clone>(
        &self,
        buffer: &wgpu::Buffer,
        size: u64,
    ) -> UnifiedGpuResult<Vec<T>> {
        let staging_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("Staging Buffer"),
            size,
            usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
            mapped_at_creation: false,
        });

        let mut encoder = self
            .device
            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("Copy Encoder"),
            });

        encoder.copy_buffer_to_buffer(buffer, 0, &staging_buffer, 0, size);
        self.queue.submit([encoder.finish()]);

        let buffer_slice = staging_buffer.slice(..);
        let (tx, rx) = futures::channel::oneshot::channel();
        buffer_slice.map_async(wgpu::MapMode::Read, move |result| {
            tx.send(result).ok();
        });

        self.device.poll(wgpu::Maintain::Wait);

        rx.await
            .map_err(|_| UnifiedGpuError::InvalidOperation("Buffer read timeout".to_string()))?
            .map_err(|e| UnifiedGpuError::InvalidOperation(format!("Buffer map failed: {}", e)))?;

        let data = buffer_slice.get_mapped_range();
        let result: Vec<T> = bytemuck::cast_slice(&data).to_vec();
        drop(data);
        staging_buffer.unmap();

        Ok(result)
    }
}

/// GPU buffer pool for efficient memory management
pub struct GpuBufferPool {
    _pools: HashMap<String, Vec<wgpu::Buffer>>, // Future: implement buffer pooling
}

impl GpuBufferPool {
    pub fn new() -> Self {
        Self {
            _pools: HashMap::new(),
        }
    }

    // Future: Add buffer pooling methods
    // pub fn get_buffer(&mut self, size: u64, usage: wgpu::BufferUsages) -> wgpu::Buffer
    // pub fn return_buffer(&mut self, buffer: wgpu::Buffer)
}

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

/// Shared GPU context for efficient resource management across all crates
/// Now supports both single-GPU (legacy) and multi-GPU operations
#[derive(Clone)]
pub struct SharedGpuContext {
    // Legacy single-GPU support (primary device)
    device: Arc<wgpu::Device>,
    queue: Arc<wgpu::Queue>,
    adapter_info: wgpu::AdapterInfo,
    buffer_pool: Arc<std::sync::Mutex<EnhancedGpuBufferPool>>,
    shader_cache: Arc<std::sync::Mutex<HashMap<String, Arc<wgpu::ComputePipeline>>>>,
    creation_time: Instant,

    // Multi-GPU support (v0.9.6+)
    multi_gpu_enabled: bool,
    gpu_devices: Arc<RwLock<HashMap<DeviceId, Arc<GpuDevice>>>>,
    load_balancer: Arc<IntelligentLoadBalancer>,
    workload_coordinator: Arc<WorkloadCoordinator>,
    primary_device_id: DeviceId,
}

impl SharedGpuContext {
    /// Get the global shared GPU context (singleton pattern)
    /// Note: This creates a new context each time for now. In production,
    /// this would be a proper singleton with atomic initialization.
    pub async fn global() -> UnifiedGpuResult<&'static Self> {
        let context = Self::new().await?;
        // Leak the context to make it 'static - in production, this would be managed properly
        Ok(Box::leak(Box::new(context)))
    }

    /// Create a new shared GPU context (single GPU mode for backward compatibility)
    async fn new() -> UnifiedGpuResult<Self> {
        let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
            backends: wgpu::Backends::all(),
            flags: wgpu::InstanceFlags::default(),
            dx12_shader_compiler: wgpu::Dx12Compiler::default(),
            gles_minor_version: wgpu::Gles3MinorVersion::Automatic,
        });

        let adapter = instance
            .request_adapter(&wgpu::RequestAdapterOptions {
                power_preference: wgpu::PowerPreference::HighPerformance,
                compatible_surface: None,
                force_fallback_adapter: false,
            })
            .await
            .ok_or_else(|| {
                UnifiedGpuError::InvalidOperation("No suitable GPU adapter found".into())
            })?;

        let adapter_info = adapter.get_info();

        let (device, queue) = adapter
            .request_device(
                &wgpu::DeviceDescriptor {
                    label: Some("Shared Amari GPU Device"),
                    required_features: wgpu::Features::TIMESTAMP_QUERY,
                    required_limits: wgpu::Limits::default(),
                },
                None,
            )
            .await
            .map_err(|e| {
                UnifiedGpuError::InvalidOperation(format!("Device request failed: {:?}", e))
            })?;

        let primary_device_id = DeviceId(0);

        // Create single-GPU device for multi-GPU compatibility
        let gpu_device = Arc::new(
            GpuDevice::new(primary_device_id, &adapter, device, queue)
                .await
                .map_err(|_| {
                    UnifiedGpuError::InvalidOperation("Failed to create GPU device".into())
                })?,
        );

        let device_arc = Arc::clone(&gpu_device.device);
        let queue_arc = Arc::clone(&gpu_device.queue);

        let mut gpu_devices = HashMap::new();
        gpu_devices.insert(primary_device_id, gpu_device);

        Ok(Self {
            device: device_arc,
            queue: queue_arc,
            adapter_info,
            buffer_pool: Arc::new(std::sync::Mutex::new(EnhancedGpuBufferPool::new())),
            shader_cache: Arc::new(std::sync::Mutex::new(HashMap::new())),
            creation_time: Instant::now(),

            // Multi-GPU fields (initially single-GPU mode)
            multi_gpu_enabled: false,
            gpu_devices: Arc::new(RwLock::new(gpu_devices)),
            load_balancer: Arc::new(IntelligentLoadBalancer::new(
                LoadBalancingStrategy::Balanced,
            )),
            workload_coordinator: Arc::new(WorkloadCoordinator::new()),
            primary_device_id,
        })
    }

    /// Create a new shared GPU context with multi-GPU support
    pub async fn with_multi_gpu() -> UnifiedGpuResult<Self> {
        let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
            backends: wgpu::Backends::all(),
            flags: wgpu::InstanceFlags::default(),
            dx12_shader_compiler: wgpu::Dx12Compiler::default(),
            gles_minor_version: wgpu::Gles3MinorVersion::Automatic,
        });

        // Enumerate all available adapters
        let adapters: Vec<_> = instance.enumerate_adapters(wgpu::Backends::all());

        if adapters.is_empty() {
            return Err(UnifiedGpuError::InvalidOperation(
                "No GPU adapters found".into(),
            ));
        }

        // Initialize devices from adapters
        let mut gpu_devices = HashMap::new();
        let mut primary_device = None;
        let mut primary_queue = None;
        let mut primary_adapter_info = None;

        for (i, adapter) in adapters.iter().enumerate() {
            let device_id = DeviceId(i);

            // Try to create device
            if let Ok((device, queue)) = adapter
                .request_device(
                    &wgpu::DeviceDescriptor {
                        label: Some(&format!("Amari Multi-GPU Device {}", i)),
                        required_features: wgpu::Features::TIMESTAMP_QUERY,
                        required_limits: wgpu::Limits::default(),
                    },
                    None,
                )
                .await
            {
                // Create GPU device wrapper
                if let Ok(gpu_device) = GpuDevice::new(device_id, adapter, device, queue).await {
                    // Set primary device (first successful device)
                    if primary_device.is_none() {
                        primary_device = Some(Arc::clone(&gpu_device.device));
                        primary_queue = Some(Arc::clone(&gpu_device.queue));
                        primary_adapter_info = Some(adapter.get_info());
                    }

                    gpu_devices.insert(device_id, Arc::new(gpu_device));
                }
            }
        }

        if gpu_devices.is_empty() {
            return Err(UnifiedGpuError::InvalidOperation(
                "No usable GPU devices found".into(),
            ));
        }

        let primary_device_id = DeviceId(0);
        let load_balancer = Arc::new(IntelligentLoadBalancer::new(
            LoadBalancingStrategy::CapabilityAware,
        ));

        // Add all devices to load balancer
        for device in gpu_devices.values() {
            load_balancer.add_device(Arc::clone(device)).await;
        }

        Ok(Self {
            device: primary_device.unwrap(),
            queue: primary_queue.unwrap(),
            adapter_info: primary_adapter_info.unwrap(),
            buffer_pool: Arc::new(std::sync::Mutex::new(EnhancedGpuBufferPool::new())),
            shader_cache: Arc::new(std::sync::Mutex::new(HashMap::new())),
            creation_time: Instant::now(),

            // Multi-GPU configuration
            multi_gpu_enabled: true,
            gpu_devices: Arc::new(RwLock::new(gpu_devices)),
            load_balancer,
            workload_coordinator: Arc::new(WorkloadCoordinator::new()),
            primary_device_id,
        })
    }

    /// Get the device
    pub fn device(&self) -> &wgpu::Device {
        &self.device
    }

    /// Get the queue
    pub fn queue(&self) -> &wgpu::Queue {
        &self.queue
    }

    /// Get adapter info
    pub fn adapter_info(&self) -> &wgpu::AdapterInfo {
        &self.adapter_info
    }

    /// Get or create a buffer from the pool
    pub fn get_buffer(
        &self,
        size: u64,
        usage: wgpu::BufferUsages,
        label: Option<&str>,
    ) -> wgpu::Buffer {
        if let Ok(mut pool) = self.buffer_pool.lock() {
            pool.get_or_create(&self.device, size, usage, label)
        } else {
            // Fallback if mutex is poisoned
            self.device.create_buffer(&wgpu::BufferDescriptor {
                label,
                size,
                usage,
                mapped_at_creation: false,
            })
        }
    }

    /// Return a buffer to the pool for reuse
    pub fn return_buffer(&self, buffer: wgpu::Buffer, size: u64, usage: wgpu::BufferUsages) {
        if let Ok(mut pool) = self.buffer_pool.lock() {
            pool.return_buffer(buffer, size, usage);
        }
        // If mutex is poisoned, just drop the buffer
    }

    /// Get or create a compute pipeline from cache
    pub fn get_compute_pipeline(
        &self,
        shader_key: &str,
        shader_source: &str,
        entry_point: &str,
    ) -> UnifiedGpuResult<Arc<wgpu::ComputePipeline>> {
        let cache_key = format!("{}:{}", shader_key, entry_point);

        if let Ok(mut cache) = self.shader_cache.lock() {
            if let Some(pipeline) = cache.get(&cache_key) {
                return Ok(Arc::clone(pipeline));
            }

            // Create new pipeline
            let shader_module = self
                .device
                .create_shader_module(wgpu::ShaderModuleDescriptor {
                    label: Some(&format!("{} Shader", shader_key)),
                    source: wgpu::ShaderSource::Wgsl(shader_source.into()),
                });

            let bind_group_layout =
                self.device
                    .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                        label: Some(&format!("{} Bind Group Layout", shader_key)),
                        entries: &[
                            wgpu::BindGroupLayoutEntry {
                                binding: 0,
                                visibility: wgpu::ShaderStages::COMPUTE,
                                ty: wgpu::BindingType::Buffer {
                                    ty: wgpu::BufferBindingType::Storage { read_only: true },
                                    has_dynamic_offset: false,
                                    min_binding_size: None,
                                },
                                count: None,
                            },
                            wgpu::BindGroupLayoutEntry {
                                binding: 1,
                                visibility: wgpu::ShaderStages::COMPUTE,
                                ty: wgpu::BindingType::Buffer {
                                    ty: wgpu::BufferBindingType::Storage { read_only: false },
                                    has_dynamic_offset: false,
                                    min_binding_size: None,
                                },
                                count: None,
                            },
                        ],
                    });

            let pipeline_layout =
                self.device
                    .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                        label: Some(&format!("{} Pipeline Layout", shader_key)),
                        bind_group_layouts: &[&bind_group_layout],
                        push_constant_ranges: &[],
                    });

            let pipeline = self
                .device
                .create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
                    label: Some(&format!("{} Pipeline", shader_key)),
                    layout: Some(&pipeline_layout),
                    module: &shader_module,
                    entry_point,
                });

            let pipeline_arc = Arc::new(pipeline);
            cache.insert(cache_key, Arc::clone(&pipeline_arc));
            Ok(pipeline_arc)
        } else {
            Err(UnifiedGpuError::InvalidOperation(
                "Failed to access shader cache".into(),
            ))
        }
    }

    /// Get buffer pool statistics
    pub fn buffer_pool_stats(&self) -> BufferPoolStats {
        if let Ok(pool) = self.buffer_pool.lock() {
            pool.get_stats()
        } else {
            BufferPoolStats::default()
        }
    }

    /// Get uptime of this context
    pub fn uptime(&self) -> std::time::Duration {
        self.creation_time.elapsed()
    }

    /// Get optimal workgroup configuration for given operation type and data size
    pub fn get_optimal_workgroup(&self, operation: &str, data_size: usize) -> (u32, u32, u32) {
        match operation {
            "matrix_multiply" | "matrix_operation" => {
                // 2D workgroups optimized for matrix operations
                // Use larger workgroups for better occupancy
                (16, 16, 1)
            }
            "vector_operation" | "reduce" | "scan" => {
                // 1D operations - prefer large workgroups for coalesced memory access
                let workgroup_size = if data_size > 10000 {
                    256 // Large batches benefit from maximum occupancy
                } else if data_size > 1000 {
                    128 // Medium batches
                } else {
                    64 // Small batches
                };
                (workgroup_size, 1, 1)
            }
            "geometric_algebra" | "clifford_algebra" => {
                // GA operations with moderate computational complexity
                (128, 1, 1)
            }
            "cellular_automata" | "ca_evolution" => {
                // 2D grid operations, optimized for spatial locality
                (16, 16, 1)
            }
            "neural_network" | "batch_processing" => {
                // Large 1D workgroups for high-throughput batch processing
                (256, 1, 1)
            }
            "information_geometry" | "fisher_information" | "bregman_divergence" => {
                // Statistical manifold computations - large workgroups
                (256, 1, 1)
            }
            "tropical_algebra" | "tropical_matrix" => {
                // Tropical operations, moderate workgroup size
                (128, 1, 1)
            }
            "dual_number" | "automatic_differentiation" => {
                // AD operations, balanced workgroup size
                (128, 1, 1)
            }
            "fusion_system" | "llm_evaluation" => {
                // Complex fusion operations, large workgroups
                (256, 1, 1)
            }
            "enumerative_geometry" | "intersection_theory" => {
                // Geometric computations, moderate workgroups
                (64, 1, 1)
            }
            _ => (64, 1, 1), // Conservative default for unknown operations
        }
    }

    /// Generate optimized WGSL workgroup declaration for operation
    pub fn get_workgroup_declaration(&self, operation: &str, data_size: usize) -> String {
        let (x, y, z) = self.get_optimal_workgroup(operation, data_size);

        if y == 1 && z == 1 {
            format!("@compute @workgroup_size({})", x)
        } else if z == 1 {
            format!("@compute @workgroup_size({}, {})", x, y)
        } else {
            format!("@compute @workgroup_size({}, {}, {})", x, y, z)
        }
    }

    // === Multi-GPU Methods (v0.9.6+) ===

    /// Check if multi-GPU mode is enabled
    pub fn is_multi_gpu_enabled(&self) -> bool {
        self.multi_gpu_enabled
    }

    /// Get the number of available GPU devices
    pub async fn device_count(&self) -> usize {
        self.gpu_devices.read().await.len()
    }

    /// Get information about all GPU devices
    pub async fn get_device_info(&self) -> Vec<(DeviceId, String, String)> {
        let devices = self.gpu_devices.read().await;
        devices
            .iter()
            .map(|(id, device)| {
                (
                    *id,
                    device.adapter_info.name.clone(),
                    format!("{:?}", device.capabilities.architecture),
                )
            })
            .collect()
    }

    /// Get a specific GPU device by ID
    pub async fn get_device(&self, device_id: DeviceId) -> Option<Arc<GpuDevice>> {
        let devices = self.gpu_devices.read().await;
        devices.get(&device_id).cloned()
    }

    /// Get the optimal device for a specific operation
    pub async fn optimal_device_for_operation(
        &self,
        operation: &str,
        _data_size: usize,
    ) -> DeviceId {
        if !self.multi_gpu_enabled {
            return self.primary_device_id;
        }

        let devices = self.gpu_devices.read().await;
        let available_devices: Vec<_> = devices
            .values()
            .filter(|device| device.is_available())
            .collect();

        if available_devices.is_empty() {
            return self.primary_device_id;
        }

        // Find device with best performance score for this operation
        available_devices
            .iter()
            .max_by(|a, b| {
                a.performance_score(operation)
                    .partial_cmp(&b.performance_score(operation))
                    .unwrap_or(std::cmp::Ordering::Equal)
            })
            .map(|device| device.id)
            .unwrap_or(self.primary_device_id)
    }

    /// Distribute a workload across multiple GPUs
    pub async fn distribute_workload(
        &self,
        workload: Workload,
    ) -> UnifiedGpuResult<Vec<crate::multi_gpu::DeviceWorkload>> {
        if !self.multi_gpu_enabled {
            // Single GPU fallback
            return Ok(vec![crate::multi_gpu::DeviceWorkload {
                device_id: self.primary_device_id,
                workload_fraction: 1.0,
                data_range: (0, workload.data_size),
                estimated_completion_ms: 100.0,
                memory_requirement_mb: workload.memory_requirement_mb,
            }]);
        }

        self.load_balancer
            .distribute_workload(&workload)
            .await
            .map_err(|e| {
                UnifiedGpuError::InvalidOperation(format!("Workload distribution failed: {:?}", e))
            })
    }

    /// Execute a workload on multiple GPUs and aggregate results
    pub async fn execute_multi_gpu_workload(
        &self,
        workload_id: String,
        workload: Workload,
    ) -> UnifiedGpuResult<Vec<Vec<u8>>> {
        if !self.multi_gpu_enabled {
            return Err(UnifiedGpuError::InvalidOperation(
                "Multi-GPU mode not enabled".into(),
            ));
        }

        // Distribute workload
        let assignments = self.distribute_workload(workload).await?;

        // Submit to coordinator
        self.workload_coordinator
            .submit_workload(workload_id.clone(), assignments)
            .await
            .map_err(|e| {
                UnifiedGpuError::InvalidOperation(format!("Workload submission failed: {:?}", e))
            })?;

        // Wait for completion (with timeout)
        let timeout = std::time::Duration::from_secs(30);
        self.workload_coordinator
            .wait_for_completion(&workload_id, timeout)
            .await
            .map_err(|e| {
                UnifiedGpuError::InvalidOperation(format!("Workload execution failed: {:?}", e))
            })
    }

    /// Get real-time GPU utilization across all devices
    pub async fn get_gpu_utilization(&self) -> HashMap<DeviceId, f32> {
        let devices: tokio::sync::RwLockReadGuard<HashMap<DeviceId, Arc<GpuDevice>>> =
            self.gpu_devices.read().await;
        devices
            .iter()
            .map(|(id, device): (&DeviceId, &Arc<GpuDevice>)| (*id, device.current_load()))
            .collect()
    }

    /// Get performance statistics for multi-GPU operations
    pub async fn get_multi_gpu_stats(&self) -> MultiGpuStats {
        let devices: tokio::sync::RwLockReadGuard<HashMap<DeviceId, Arc<GpuDevice>>> =
            self.gpu_devices.read().await;
        let device_count = devices.len();

        let total_operations: usize = devices
            .values()
            .map(|device| {
                device
                    .total_operations
                    .load(std::sync::atomic::Ordering::Relaxed)
            })
            .sum();

        let total_errors: usize = devices
            .values()
            .map(|device| {
                device
                    .error_count
                    .load(std::sync::atomic::Ordering::Relaxed)
            })
            .sum();

        let avg_utilization = if !devices.is_empty() {
            devices
                .values()
                .map(|device: &Arc<GpuDevice>| device.current_load())
                .sum::<f32>()
                / devices.len() as f32
        } else {
            0.0
        };

        MultiGpuStats {
            device_count,
            total_operations,
            total_errors,
            avg_utilization_percent: avg_utilization,
            uptime: self.creation_time.elapsed(),
        }
    }

    /// Set load balancing strategy for multi-GPU operations
    pub async fn set_load_balancing_strategy(
        &self,
        _strategy: LoadBalancingStrategy,
    ) -> UnifiedGpuResult<()> {
        if !self.multi_gpu_enabled {
            return Err(UnifiedGpuError::InvalidOperation(
                "Multi-GPU mode not enabled".into(),
            ));
        }

        // Note: In a full implementation, this would update the load balancer's strategy
        // For now, this is a placeholder that could be extended
        Ok(())
    }

    /// Add a new GPU device to the multi-GPU context (hot-plugging support)
    pub async fn add_gpu_device(&self, device: Arc<GpuDevice>) -> UnifiedGpuResult<()> {
        if !self.multi_gpu_enabled {
            return Err(UnifiedGpuError::InvalidOperation(
                "Multi-GPU mode not enabled".into(),
            ));
        }

        let mut devices: tokio::sync::RwLockWriteGuard<HashMap<DeviceId, Arc<GpuDevice>>> =
            self.gpu_devices.write().await;
        devices.insert(device.id, Arc::clone(&device));

        // Add to load balancer
        self.load_balancer.add_device(device).await;

        Ok(())
    }

    /// Remove a GPU device from the multi-GPU context
    pub async fn remove_gpu_device(&self, device_id: DeviceId) -> UnifiedGpuResult<()> {
        if !self.multi_gpu_enabled {
            return Err(UnifiedGpuError::InvalidOperation(
                "Multi-GPU mode not enabled".into(),
            ));
        }

        let mut devices: tokio::sync::RwLockWriteGuard<HashMap<DeviceId, Arc<GpuDevice>>> =
            self.gpu_devices.write().await;
        devices.remove(&device_id);

        // Remove from load balancer
        self.load_balancer.remove_device(device_id).await;

        Ok(())
    }
}

/// Enhanced buffer pool with statistics and eviction policies
pub struct EnhancedGpuBufferPool {
    pools: HashMap<(u64, wgpu::BufferUsages), Vec<wgpu::Buffer>>,
    stats: HashMap<(u64, wgpu::BufferUsages), PoolEntryStats>,
    total_created: u64,
    total_reused: u64,
    last_cleanup: Instant,
}

#[derive(Debug, Clone, Default)]
pub struct PoolEntryStats {
    pub created_count: u64,
    pub reused_count: u64,
    pub last_used: Option<Instant>,
    pub total_size_bytes: u64,
}

#[derive(Debug, Clone, Default)]
pub struct BufferPoolStats {
    pub total_buffers_created: u64,
    pub total_buffers_reused: u64,
    pub current_pooled_count: usize,
    pub total_pooled_memory_mb: f32,
    pub hit_rate_percent: f32,
}

impl EnhancedGpuBufferPool {
    pub fn new() -> Self {
        Self {
            pools: HashMap::new(),
            stats: HashMap::new(),
            total_created: 0,
            total_reused: 0,
            last_cleanup: Instant::now(),
        }
    }
}

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

impl EnhancedGpuBufferPool {
    pub fn get_or_create(
        &mut self,
        device: &wgpu::Device,
        size: u64,
        usage: wgpu::BufferUsages,
        label: Option<&str>,
    ) -> wgpu::Buffer {
        let key = (size, usage);

        // Try to reuse from pool
        if let Some(buffers) = self.pools.get_mut(&key) {
            if let Some(buffer) = buffers.pop() {
                self.total_reused += 1;
                self.stats.entry(key).or_default().reused_count += 1;
                self.stats.get_mut(&key).unwrap().last_used = Some(Instant::now());
                return buffer;
            }
        }

        // Create new buffer
        let buffer = device.create_buffer(&wgpu::BufferDescriptor {
            label,
            size,
            usage,
            mapped_at_creation: false,
        });

        self.total_created += 1;
        let stats = self.stats.entry(key).or_default();
        stats.created_count += 1;
        stats.total_size_bytes += size;
        stats.last_used = Some(Instant::now());

        // Periodic cleanup
        if self.last_cleanup.elapsed().as_secs() > 30 {
            self.cleanup_old_buffers();
        }

        buffer
    }

    pub fn return_buffer(&mut self, buffer: wgpu::Buffer, size: u64, usage: wgpu::BufferUsages) {
        let key = (size, usage);
        self.pools.entry(key).or_default().push(buffer);
    }

    pub fn get_stats(&self) -> BufferPoolStats {
        let total_ops = self.total_created + self.total_reused;
        let hit_rate = if total_ops > 0 {
            (self.total_reused as f32 / total_ops as f32) * 100.0
        } else {
            0.0
        };

        let current_pooled_count = self.pools.values().map(|v| v.len()).sum();
        let total_pooled_memory_mb: f32 = self
            .pools
            .iter()
            .map(|((size, _usage), buffers)| {
                (*size as f32 * buffers.len() as f32) / 1024.0 / 1024.0
            })
            .sum();

        BufferPoolStats {
            total_buffers_created: self.total_created,
            total_buffers_reused: self.total_reused,
            current_pooled_count,
            total_pooled_memory_mb,
            hit_rate_percent: hit_rate,
        }
    }

    fn cleanup_old_buffers(&mut self) {
        let now = Instant::now();
        let cleanup_threshold = std::time::Duration::from_secs(300); // 5 minutes

        self.pools.retain(|&key, buffers| {
            if let Some(stats) = self.stats.get(&key) {
                if let Some(last_used) = stats.last_used {
                    if now.duration_since(last_used) > cleanup_threshold {
                        // Remove old unused buffers
                        buffers.clear();
                        return false;
                    }
                }
            }
            true
        });

        self.last_cleanup = now;
    }
}

/// Smart GPU/CPU dispatch based on workload characteristics
pub struct GpuDispatcher {
    gpu_context: Option<GpuContext>,
    cpu_threshold: usize,
    gpu_threshold: usize,
}

impl GpuDispatcher {
    /// Create new dispatcher with GPU context
    pub async fn new() -> UnifiedGpuResult<Self> {
        let gpu_context = (GpuContext::new().await).ok(); // Graceful fallback to CPU-only

        Ok(Self {
            gpu_context,
            cpu_threshold: 100,  // Use CPU for small workloads
            gpu_threshold: 1000, // Use GPU for large workloads
        })
    }

    /// Determine optimal compute strategy
    pub fn should_use_gpu(&self, workload_size: usize) -> bool {
        self.gpu_context.is_some()
            && workload_size >= self.cpu_threshold
            && workload_size >= self.gpu_threshold
    }

    /// Execute operation with optimal strategy
    pub async fn execute<T, F, G>(&mut self, workload_size: usize, gpu_op: G, cpu_op: F) -> T
    where
        F: FnOnce() -> T,
        G: FnOnce(&mut GpuContext) -> UnifiedGpuResult<T>,
    {
        if self.should_use_gpu(workload_size) {
            if let Some(ref mut ctx) = self.gpu_context {
                if let Ok(result) = gpu_op(ctx) {
                    return result;
                }
            }
        }

        // Fallback to CPU
        cpu_op()
    }
}

/// Multi-GPU statistics for monitoring and optimization
#[derive(Debug, Clone)]
pub struct MultiGpuStats {
    pub device_count: usize,
    pub total_operations: usize,
    pub total_errors: usize,
    pub avg_utilization_percent: f32,
    pub uptime: std::time::Duration,
}

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

    #[tokio::test]
    #[ignore = "GPU hardware required, may fail in CI/CD environments"]
    async fn test_gpu_context_creation() {
        // Test should pass even without GPU (graceful fallback)
        let _result = GpuContext::new().await;
        // Don't assert success since GPU might not be available in CI
    }

    #[tokio::test]
    #[ignore = "GPU hardware required, may fail in CI/CD environments"]
    async fn test_gpu_dispatcher() {
        let dispatcher = GpuDispatcher::new().await;
        assert!(dispatcher.is_ok());
    }

    #[test]
    fn test_gpu_operation_params() {
        let mut params = GpuOperationParams::default();
        params
            .params
            .insert("scale".to_string(), GpuParam::Float(2.0));
        params.batch_size = 100;

        assert_eq!(params.batch_size, 100);
        match params.params.get("scale") {
            Some(GpuParam::Float(val)) => assert_eq!(*val, 2.0),
            _ => panic!("Expected float parameter"),
        }
    }
}