rustorch 0.6.29

Production-ready PyTorch-compatible deep learning library in Rust with special mathematical functions (gamma, Bessel, error functions), statistical distributions, Fourier transforms (FFT/RFFT), matrix decomposition (SVD/QR/LU/eigenvalue), automatic differentiation, neural networks, computer vision transforms, complete GPU acceleration (CUDA/Metal/OpenCL), SIMD optimizations, parallel processing, WebAssembly browser support, comprehensive distributed learning support, and performance validation
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
//! WebGPU backend for Chrome browser GPU acceleration
//! Chrome ブラウザGPU加速用WebGPUバックエンド

#[cfg(feature = "webgpu")]
use bytemuck;
#[cfg(feature = "webgpu")]
use js_sys;
#[cfg(feature = "webgpu")]
use std::borrow;
#[cfg(feature = "webgpu")]
use std::collections::HashMap;
#[cfg(feature = "webgpu")]
use wasm_bindgen::prelude::*;
#[cfg(feature = "webgpu")]
use wgpu::util::{BufferInitDescriptor, DeviceExt};
#[cfg(feature = "webgpu")]
use wgpu::*;

#[cfg(feature = "webgpu")]
#[wasm_bindgen]
extern "C" {
    #[wasm_bindgen(js_namespace = console)]
    fn log(s: &str);
}

#[cfg(feature = "webgpu")]
macro_rules! console_log {
    ($($t:tt)*) => (log(&format_args!($($t)*).to_string()))
}

#[cfg(feature = "webgpu")]
pub struct WebGPUContext {
    device: Device,
    queue: Queue,
    adapter_info: AdapterInfo,
    buffer_cache: HashMap<String, Buffer>,
    compute_pipeline_cache: HashMap<String, ComputePipeline>,
}

#[cfg(feature = "webgpu")]
impl WebGPUContext {
    pub async fn new() -> Result<WebGPUContext, JsValue> {
        console_error_panic_hook::set_once();

        // Request WebGPU adapter with Chrome optimization
        let instance = Instance::new(InstanceDescriptor {
            backends: Backends::BROWSER_WEBGPU,
            ..Default::default()
        });

        let adapter = instance
            .request_adapter(&RequestAdapterOptions {
                power_preference: PowerPreference::HighPerformance,
                force_fallback_adapter: false,
                compatible_surface: None,
            })
            .await
            .ok_or_else(|| JsValue::from_str("Failed to find WebGPU adapter"))?;

        let adapter_info = adapter.get_info();
        console_log!(
            "WebGPU Adapter: {} ({:?})",
            adapter_info.name,
            adapter_info.backend
        );

        // Request device with compute shader support
        let (device, queue) = adapter
            .request_device(
                &DeviceDescriptor {
                    label: Some("RusTorch WebGPU Device"),
                    required_features: Features::empty(),
                    required_limits: Limits::downlevel_webgl2_defaults(),
                    memory_hints: MemoryHints::Performance,
                },
                None,
            )
            .await
            .map_err(|e| JsValue::from_str(&format!("Failed to request device: {:?}", e)))?;

        console_log!("WebGPU device initialized successfully");

        Ok(WebGPUContext {
            device,
            queue,
            adapter_info,
            buffer_cache: HashMap::new(),
            compute_pipeline_cache: HashMap::new(),
        })
    }

    pub fn get_adapter_name(&self) -> String {
        self.adapter_info.name.clone()
    }

    pub fn get_backend_type(&self) -> String {
        format!("{:?}", self.adapter_info.backend)
    }

    pub fn create_buffer(&mut self, label: &str, size: u64, usage: u32) -> bool {
        let buffer = self.device.create_buffer(&BufferDescriptor {
            label: Some(label),
            size,
            usage: BufferUsages::from_bits_truncate(usage),
            mapped_at_creation: false,
        });

        self.buffer_cache.insert(label.to_string(), buffer);
        true
    }

    pub fn write_buffer_data(&mut self, buffer_label: &str, data: &[f32]) -> bool {
        if let Some(buffer) = self.buffer_cache.get(buffer_label) {
            let data_bytes = bytemuck::cast_slice(data);
            self.queue.write_buffer(buffer, 0, data_bytes);
            true
        } else {
            false
        }
    }

    pub async fn read_buffer_data(&self, buffer_label: &str) -> Result<Vec<f32>, JsValue> {
        let buffer = self
            .buffer_cache
            .get(buffer_label)
            .ok_or_else(|| JsValue::from_str("Buffer not found"))?;

        let buffer_slice = buffer.slice(..);
        buffer_slice.map_async(MapMode::Read, |_| {});

        // Wait for the mapping to complete
        self.device.poll(Maintain::Wait);

        let data = buffer_slice.get_mapped_range();
        let result: Vec<f32> = bytemuck::cast_slice(&data).to_vec();

        drop(data);
        buffer.unmap();

        Ok(result)
    }

    pub fn create_compute_pipeline(&mut self, label: &str, shader_source: &str) -> bool {
        let shader_module = self.device.create_shader_module(ShaderModuleDescriptor {
            label: Some(&format!("{}_shader", label)),
            source: ShaderSource::Wgsl(shader_source.into()),
        });

        let compute_pipeline = self
            .device
            .create_compute_pipeline(&ComputePipelineDescriptor {
                label: Some(label),
                layout: None,
                module: &shader_module,
                entry_point: Some("main"),
                compilation_options: Default::default(),
                cache: None,
            });

        self.compute_pipeline_cache
            .insert(label.to_string(), compute_pipeline);
        true
    }

    pub fn dispatch_compute(
        &self,
        pipeline_label: &str,
        workgroup_x: u32,
        workgroup_y: u32,
        workgroup_z: u32,
    ) -> bool {
        if let Some(pipeline) = self.compute_pipeline_cache.get(pipeline_label) {
            let mut encoder = self
                .device
                .create_command_encoder(&CommandEncoderDescriptor {
                    label: Some("Compute Encoder"),
                });

            {
                let mut compute_pass = encoder.begin_compute_pass(&ComputePassDescriptor {
                    label: Some("Compute Pass"),
                    timestamp_writes: None,
                });
                compute_pass.set_pipeline(pipeline);
                compute_pass.dispatch_workgroups(workgroup_x, workgroup_y, workgroup_z);
            }

            self.queue.submit([encoder.finish()]);
            true
        } else {
            false
        }
    }

    pub fn get_buffer_count(&self) -> u32 {
        self.buffer_cache.len() as u32
    }

    pub fn get_pipeline_count(&self) -> u32 {
        self.compute_pipeline_cache.len() as u32
    }

    pub fn clear_cache(&mut self) {
        self.buffer_cache.clear();
        self.compute_pipeline_cache.clear();
    }

    // Tensor operation execution functions with binding groups
    pub async fn tensor_add(
        &mut self,
        a_label: &str,
        b_label: &str,
        output_label: &str,
    ) -> Result<bool, JsValue> {
        self.execute_binary_operation("tensor_add", a_label, b_label, output_label)
            .await
    }

    pub async fn tensor_mul(
        &mut self,
        a_label: &str,
        b_label: &str,
        output_label: &str,
    ) -> Result<bool, JsValue> {
        self.execute_binary_operation("tensor_mul", a_label, b_label, output_label)
            .await
    }

    pub async fn tensor_relu(
        &mut self,
        input_label: &str,
        output_label: &str,
    ) -> Result<bool, JsValue> {
        self.execute_unary_operation("tensor_relu", input_label, output_label)
            .await
    }

    pub async fn tensor_sigmoid(
        &mut self,
        input_label: &str,
        output_label: &str,
    ) -> Result<bool, JsValue> {
        self.execute_unary_operation("tensor_sigmoid", input_label, output_label)
            .await
    }

    pub async fn tensor_matmul(
        &mut self,
        a_label: &str,
        b_label: &str,
        output_label: &str,
        m: u32,
        n: u32,
        k: u32,
    ) -> Result<bool, JsValue> {
        let pipeline = self
            .compute_pipeline_cache
            .get("tensor_matmul")
            .ok_or_else(|| JsValue::from_str("Matrix multiplication pipeline not found"))?;

        let a_buffer = self
            .buffer_cache
            .get(a_label)
            .ok_or_else(|| JsValue::from_str("Buffer A not found"))?;
        let b_buffer = self
            .buffer_cache
            .get(b_label)
            .ok_or_else(|| JsValue::from_str("Buffer B not found"))?;
        let output_buffer = self
            .buffer_cache
            .get(output_label)
            .ok_or_else(|| JsValue::from_str("Output buffer not found"))?;

        // Create dimensions buffer
        let dims_data = [m, n, k];
        let dims_buffer = self.device.create_buffer_init(&BufferInitDescriptor {
            label: Some("Matrix Dimensions"),
            contents: bytemuck::cast_slice(&dims_data),
            usage: BufferUsages::STORAGE,
        });

        let bind_group = self.device.create_bind_group(&BindGroupDescriptor {
            label: Some("MatMul Bind Group"),
            layout: &pipeline.get_bind_group_layout(0),
            entries: &[
                BindGroupEntry {
                    binding: 0,
                    resource: a_buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 1,
                    resource: b_buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 2,
                    resource: output_buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 3,
                    resource: dims_buffer.as_entire_binding(),
                },
            ],
        });

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

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

            let workgroup_x = (n + 7) / 8;
            let workgroup_y = (m + 7) / 8;
            compute_pass.dispatch_workgroups(workgroup_x, workgroup_y, 1);
        }

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

    // Helper function for binary operations (add, mul)
    async fn execute_binary_operation(
        &mut self,
        operation: &str,
        a_label: &str,
        b_label: &str,
        output_label: &str,
    ) -> Result<bool, JsValue> {
        let pipeline = self
            .compute_pipeline_cache
            .get(operation)
            .ok_or_else(|| JsValue::from_str(&format!("Pipeline {} not found", operation)))?;

        let a_buffer = self
            .buffer_cache
            .get(a_label)
            .ok_or_else(|| JsValue::from_str("Buffer A not found"))?;
        let b_buffer = self
            .buffer_cache
            .get(b_label)
            .ok_or_else(|| JsValue::from_str("Buffer B not found"))?;
        let output_buffer = self
            .buffer_cache
            .get(output_label)
            .ok_or_else(|| JsValue::from_str("Output buffer not found"))?;

        let bind_group = self.device.create_bind_group(&BindGroupDescriptor {
            label: Some(&format!("{} Bind Group", operation)),
            layout: &pipeline.get_bind_group_layout(0),
            entries: &[
                BindGroupEntry {
                    binding: 0,
                    resource: a_buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 1,
                    resource: b_buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 2,
                    resource: output_buffer.as_entire_binding(),
                },
            ],
        });

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

        {
            let mut compute_pass = encoder.begin_compute_pass(&ComputePassDescriptor {
                label: Some(&format!("{} Pass", operation)),
                timestamp_writes: None,
            });
            compute_pass.set_pipeline(pipeline);
            compute_pass.set_bind_group(0, &bind_group, &[]);

            // Calculate workgroups based on buffer size
            let workgroup_count = (output_buffer.size() as u32 / 4 + 63) / 64; // f32 = 4 bytes, workgroup_size = 64
            compute_pass.dispatch_workgroups(workgroup_count, 1, 1);
        }

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

    // Helper function for unary operations (relu, sigmoid)
    async fn execute_unary_operation(
        &mut self,
        operation: &str,
        input_label: &str,
        output_label: &str,
    ) -> Result<bool, JsValue> {
        let pipeline = self
            .compute_pipeline_cache
            .get(operation)
            .ok_or_else(|| JsValue::from_str(&format!("Pipeline {} not found", operation)))?;

        let input_buffer = self
            .buffer_cache
            .get(input_label)
            .ok_or_else(|| JsValue::from_str("Input buffer not found"))?;
        let output_buffer = self
            .buffer_cache
            .get(output_label)
            .ok_or_else(|| JsValue::from_str("Output buffer not found"))?;

        let bind_group = self.device.create_bind_group(&BindGroupDescriptor {
            label: Some(&format!("{} Bind Group", operation)),
            layout: &pipeline.get_bind_group_layout(0),
            entries: &[
                BindGroupEntry {
                    binding: 0,
                    resource: input_buffer.as_entire_binding(),
                },
                BindGroupEntry {
                    binding: 1,
                    resource: output_buffer.as_entire_binding(),
                },
            ],
        });

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

        {
            let mut compute_pass = encoder.begin_compute_pass(&ComputePassDescriptor {
                label: Some(&format!("{} Pass", operation)),
                timestamp_writes: None,
            });
            compute_pass.set_pipeline(pipeline);
            compute_pass.set_bind_group(0, &bind_group, &[]);

            // Calculate workgroups based on buffer size
            let workgroup_count = (output_buffer.size() as u32 / 4 + 63) / 64; // f32 = 4 bytes, workgroup_size = 64
            compute_pass.dispatch_workgroups(workgroup_count, 1, 1);
        }

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

// WebGPU Tensor for Chrome GPU-accelerated operations
#[cfg(feature = "webgpu")]
#[wasm_bindgen]
pub struct WebGPUTensor {
    data: Vec<f32>,
    shape: Vec<u32>,
    buffer_label: String,
    device_id: String,
}

#[cfg(feature = "webgpu")]
#[wasm_bindgen]
impl WebGPUTensor {
    #[wasm_bindgen(constructor)]
    pub fn new(data: Vec<f32>, shape: Vec<u32>, buffer_label: String) -> WebGPUTensor {
        WebGPUTensor {
            data,
            shape,
            buffer_label,
            device_id: "default".to_string(),
        }
    }

    pub fn data(&self) -> Vec<f32> {
        self.data.clone()
    }

    pub fn shape(&self) -> Vec<u32> {
        self.shape.clone()
    }

    pub fn buffer_label(&self) -> String {
        self.buffer_label.clone()
    }

    pub fn numel(&self) -> u32 {
        self.shape.iter().product()
    }

    pub fn byte_size(&self) -> u32 {
        self.numel() * 4 // f32 = 4 bytes
    }
}

// WebGPU compute shader templates for tensor operations
#[cfg(feature = "webgpu")]
pub const TENSOR_ADD_SHADER: &str = r#"
@group(0) @binding(0) var<storage, read> input_a: array<f32>;
@group(0) @binding(1) var<storage, read> input_b: array<f32>;
@group(0) @binding(2) var<storage, read_write> output: array<f32>;

@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
    let index = global_id.x;
    if (index >= arrayLength(&output)) {
        return;
    }
    output[index] = input_a[index] + input_b[index];
}
"#;

#[cfg(feature = "webgpu")]
pub const TENSOR_MUL_SHADER: &str = r#"
@group(0) @binding(0) var<storage, read> input_a: array<f32>;
@group(0) @binding(1) var<storage, read> input_b: array<f32>;
@group(0) @binding(2) var<storage, read_write> output: array<f32>;

@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
    let index = global_id.x;
    if (index >= arrayLength(&output)) {
        return;
    }
    output[index] = input_a[index] * input_b[index];
}
"#;

#[cfg(feature = "webgpu")]
pub const TENSOR_MATMUL_SHADER: &str = r#"
@group(0) @binding(0) var<storage, read> input_a: array<f32>;
@group(0) @binding(1) var<storage, read> input_b: array<f32>;
@group(0) @binding(2) var<storage, read_write> output: array<f32>;
@group(0) @binding(3) var<storage, read> dimensions: array<u32>; // [M, N, K]

@compute @workgroup_size(8, 8)
fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
    let M = dimensions[0];
    let N = dimensions[1];
    let K = dimensions[2];
    
    let row = global_id.y;
    let col = global_id.x;
    
    if (row >= M || col >= N) {
        return;
    }
    
    var sum: f32 = 0.0;
    for (var k: u32 = 0u; k < K; k++) {
        let a_index = row * K + k;
        let b_index = k * N + col;
        sum += input_a[a_index] * input_b[b_index];
    }
    
    let output_index = row * N + col;
    output[output_index] = sum;
}
"#;

#[cfg(feature = "webgpu")]
pub const TENSOR_RELU_SHADER: &str = r#"
@group(0) @binding(0) var<storage, read> input: array<f32>;
@group(0) @binding(1) var<storage, read_write> output: array<f32>;

@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
    let index = global_id.x;
    if (index >= arrayLength(&output)) {
        return;
    }
    output[index] = max(input[index], 0.0);
}
"#;

#[cfg(feature = "webgpu")]
pub const TENSOR_SIGMOID_SHADER: &str = r#"
@group(0) @binding(0) var<storage, read> input: array<f32>;
@group(0) @binding(1) var<storage, read_write> output: array<f32>;

@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
    let index = global_id.x;
    if (index >= arrayLength(&output)) {
        return;
    }
    output[index] = 1.0 / (1.0 + exp(-input[index]));
}
"#;

#[cfg(feature = "webgpu")]
pub const TENSOR_SOFTMAX_SHADER: &str = r#"
@group(0) @binding(0) var<storage, read> input: array<f32>;
@group(0) @binding(1) var<storage, read_write> output: array<f32>;
@group(0) @binding(2) var<storage, read> params: array<u32>; // [batch_size, features]

// Two-pass softmax: first pass finds max, second pass computes softmax
@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
    let batch_size = params[0];
    let features = params[1];
    let batch_idx = global_id.x;
    
    if (batch_idx >= batch_size) {
        return;
    }
    
    let start_idx = batch_idx * features;
    
    // Find max value in this batch
    var max_val: f32 = input[start_idx];
    for (var i: u32 = 1u; i < features; i++) {
        max_val = max(max_val, input[start_idx + i]);
    }
    
    // Compute sum of exponentials
    var sum_exp: f32 = 0.0;
    for (var i: u32 = 0u; i < features; i++) {
        sum_exp += exp(input[start_idx + i] - max_val);
    }
    
    // Compute softmax
    for (var i: u32 = 0u; i < features; i++) {
        let idx = start_idx + i;
        output[idx] = exp(input[idx] - max_val) / sum_exp;
    }
}
"#;

// Chrome WebGPU Performance Optimizer
#[cfg(feature = "webgpu")]
#[wasm_bindgen]
pub struct ChromeWebGPUOptimizer {
    context: WebGPUContext,
    workgroup_sizes: HashMap<String, (u32, u32, u32)>,
    optimal_buffer_sizes: HashMap<String, u64>,
}

#[cfg(feature = "webgpu")]
#[wasm_bindgen]
impl ChromeWebGPUOptimizer {
    #[wasm_bindgen]
    pub async fn create() -> Result<ChromeWebGPUOptimizer, JsValue> {
        let context = WebGPUContext::new().await?;

        let mut workgroup_sizes = HashMap::new();
        workgroup_sizes.insert("tensor_add".to_string(), (64, 1, 1));
        workgroup_sizes.insert("tensor_mul".to_string(), (64, 1, 1));
        workgroup_sizes.insert("tensor_matmul".to_string(), (8, 8, 1));
        workgroup_sizes.insert("tensor_relu".to_string(), (64, 1, 1));
        workgroup_sizes.insert("tensor_sigmoid".to_string(), (64, 1, 1));
        workgroup_sizes.insert("tensor_softmax".to_string(), (64, 1, 1));

        let mut optimal_buffer_sizes = HashMap::new();
        optimal_buffer_sizes.insert("small".to_string(), 1024 * 1024); // 1MB
        optimal_buffer_sizes.insert("medium".to_string(), 16 * 1024 * 1024); // 16MB
        optimal_buffer_sizes.insert("large".to_string(), 64 * 1024 * 1024); // 64MB

        Ok(ChromeWebGPUOptimizer {
            context,
            workgroup_sizes,
            optimal_buffer_sizes,
        })
    }

    pub fn initialize_shaders(&mut self) -> bool {
        let shaders = [
            ("tensor_add", TENSOR_ADD_SHADER),
            ("tensor_mul", TENSOR_MUL_SHADER),
            ("tensor_matmul", TENSOR_MATMUL_SHADER),
            ("tensor_relu", TENSOR_RELU_SHADER),
            ("tensor_sigmoid", TENSOR_SIGMOID_SHADER),
            ("tensor_softmax", TENSOR_SOFTMAX_SHADER),
        ];

        for (name, source) in &shaders {
            if !self.context.create_compute_pipeline(name, source) {
                console_log!("Failed to create shader: {}", name);
                return false;
            }
        }

        console_log!("All compute shaders initialized successfully");
        true
    }

    pub fn get_recommended_workgroup_size(&self, operation: &str, data_size: u32) -> Vec<u32> {
        if let Some(&(x, y, z)) = self.workgroup_sizes.get(operation) {
            // Adjust workgroup size based on data size for optimal performance
            match operation {
                "tensor_matmul" => {
                    let optimal_x = (data_size as f32).sqrt().ceil() as u32;
                    let optimal_y = optimal_x;
                    vec![optimal_x.min(16), optimal_y.min(16), z]
                }
                _ => {
                    let optimal_x = (data_size / 64).max(1).min(256);
                    vec![optimal_x, y, z]
                }
            }
        } else {
            vec![64, 1, 1] // Default workgroup size
        }
    }

    pub fn get_optimal_buffer_size(&self, data_size_bytes: u64) -> u64 {
        if data_size_bytes <= self.optimal_buffer_sizes["small"] {
            self.optimal_buffer_sizes["small"]
        } else if data_size_bytes <= self.optimal_buffer_sizes["medium"] {
            self.optimal_buffer_sizes["medium"]
        } else {
            self.optimal_buffer_sizes["large"]
        }
    }

    pub fn estimate_performance_gain(&self, operation: &str, data_size: u32) -> f32 {
        // Conservative performance estimates for Chrome WebGPU vs CPU
        match operation {
            "tensor_add" | "tensor_mul" => {
                if data_size > 1000 {
                    2.0
                } else {
                    1.2
                }
            }
            "tensor_matmul" => {
                if data_size > 256 {
                    10.0
                } else if data_size > 64 {
                    4.0
                } else {
                    1.5
                }
            }
            "tensor_relu" | "tensor_sigmoid" => {
                if data_size > 500 {
                    3.0
                } else {
                    1.5
                }
            }
            "tensor_softmax" => {
                if data_size > 1000 {
                    5.0
                } else {
                    2.0
                }
            }
            _ => 1.0,
        }
    }
}

// Error handling for WebGPU operations
#[cfg(feature = "webgpu")]
#[wasm_bindgen]
pub struct WebGPUError {
    message: String,
    error_type: String,
}

#[cfg(feature = "webgpu")]
#[wasm_bindgen]
impl WebGPUError {
    #[wasm_bindgen(constructor)]
    pub fn new(message: String, error_type: String) -> WebGPUError {
        WebGPUError {
            message,
            error_type,
        }
    }

    pub fn message(&self) -> String {
        self.message.clone()
    }

    pub fn error_type(&self) -> String {
        self.error_type.clone()
    }
}

// WebGPU feature detection and compatibility
#[cfg(feature = "webgpu")]
#[wasm_bindgen]
pub async fn check_webgpu_support() -> bool {
    if let Some(window) = web_sys::window() {
        let navigator = window.navigator();
        // Use js_sys to access gpu property that might not be in web-sys yet
        let gpu_val = js_sys::Reflect::get(&navigator, &wasm_bindgen::JsValue::from_str("gpu"));
        if let Ok(gpu) = gpu_val {
            if !gpu.is_undefined() && !gpu.is_null() {
                console_log!("WebGPU API found in navigator");
                return true;
            }
        }
    }
    console_log!("WebGPU not supported in this browser");
    false
}

#[cfg(feature = "webgpu")]
#[wasm_bindgen]
pub fn get_chrome_webgpu_info() -> String {
    let webgpu_available = if let Some(window) = web_sys::window() {
        let navigator = window.navigator();
        let gpu_val = js_sys::Reflect::get(&navigator, &wasm_bindgen::JsValue::from_str("gpu"));
        gpu_val.is_ok() && !gpu_val.unwrap().is_undefined()
    } else {
        false
    };

    format!(
        "Chrome WebGPU Support: {}\nRecommended for: Chrome 113+, Edge 113+\nOptimal performance: Chrome with hardware acceleration enabled",
        if webgpu_available { "Available" } else { "Not Available" }
    )
}

// Utility functions for Chrome WebGPU optimization
#[cfg(feature = "webgpu")]
#[wasm_bindgen]
pub fn calculate_optimal_workgroups(total_elements: u32, workgroup_size: u32) -> u32 {
    (total_elements + workgroup_size - 1) / workgroup_size
}

#[cfg(feature = "webgpu")]
#[wasm_bindgen]
pub fn estimate_gpu_memory_usage(tensor_count: u32, average_size_mb: f32) -> f32 {
    // Conservative estimate including buffer overhead
    tensor_count as f32 * average_size_mb * 1.5
}