numrs2 0.3.3

A Rust implementation inspired by NumPy for numerical computing (NumRS2)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
//! GPU Array Operations
//!
//! This module provides GPU-accelerated operations for NumRS2 arrays.
//! These operations leverage the GPU for significant performance improvements
//! on large data sets.

use crate::error::{NumRs2Error, Result};
use crate::gpu::array::GpuArray;
use wgpu::util::DeviceExt;

// Constants for compute shader configuration
const WORKGROUP_SIZE: u32 = 256;

/// Enumerates the types of element-wise operations
enum ElementWiseOp {
    Add = 0,
    Subtract = 1,
    Multiply = 2,
    Divide = 3,
    Exp = 4,
    Log = 5,
    Sin = 6,
    Cos = 7,
    Tan = 8,
    Sqrt = 9,
    Abs = 10,
    Neg = 11,
    Pow = 12,
}

/// Adds two GPU arrays element-wise
pub fn add<T: bytemuck::Pod + bytemuck::Zeroable>(
    a: &GpuArray<T>,
    b: &GpuArray<T>,
) -> Result<GpuArray<T>> {
    element_wise_op(a, b, ElementWiseOp::Add)
}

/// Subtracts two GPU arrays element-wise
pub fn subtract<T: bytemuck::Pod + bytemuck::Zeroable>(
    a: &GpuArray<T>,
    b: &GpuArray<T>,
) -> Result<GpuArray<T>> {
    element_wise_op(a, b, ElementWiseOp::Subtract)
}

/// Multiplies two GPU arrays element-wise
pub fn multiply<T: bytemuck::Pod + bytemuck::Zeroable>(
    a: &GpuArray<T>,
    b: &GpuArray<T>,
) -> Result<GpuArray<T>> {
    element_wise_op(a, b, ElementWiseOp::Multiply)
}

/// Divides two GPU arrays element-wise
pub fn divide<T: bytemuck::Pod + bytemuck::Zeroable>(
    a: &GpuArray<T>,
    b: &GpuArray<T>,
) -> Result<GpuArray<T>> {
    element_wise_op(a, b, ElementWiseOp::Divide)
}

/// Performs element-wise exponentiation (e^x)
pub fn exp<T: bytemuck::Pod + bytemuck::Zeroable>(a: &GpuArray<T>) -> Result<GpuArray<T>> {
    unary_element_wise_op(a, ElementWiseOp::Exp)
}

/// Performs element-wise natural logarithm (ln)
pub fn log<T: bytemuck::Pod + bytemuck::Zeroable>(a: &GpuArray<T>) -> Result<GpuArray<T>> {
    unary_element_wise_op(a, ElementWiseOp::Log)
}

/// Performs element-wise sine
pub fn sin<T: bytemuck::Pod + bytemuck::Zeroable>(a: &GpuArray<T>) -> Result<GpuArray<T>> {
    unary_element_wise_op(a, ElementWiseOp::Sin)
}

/// Performs element-wise cosine
pub fn cos<T: bytemuck::Pod + bytemuck::Zeroable>(a: &GpuArray<T>) -> Result<GpuArray<T>> {
    unary_element_wise_op(a, ElementWiseOp::Cos)
}

/// Performs element-wise tangent
pub fn tan<T: bytemuck::Pod + bytemuck::Zeroable>(a: &GpuArray<T>) -> Result<GpuArray<T>> {
    unary_element_wise_op(a, ElementWiseOp::Tan)
}

/// Performs element-wise square root
pub fn sqrt<T: bytemuck::Pod + bytemuck::Zeroable>(a: &GpuArray<T>) -> Result<GpuArray<T>> {
    unary_element_wise_op(a, ElementWiseOp::Sqrt)
}

/// Performs element-wise absolute value
pub fn abs<T: bytemuck::Pod + bytemuck::Zeroable>(a: &GpuArray<T>) -> Result<GpuArray<T>> {
    unary_element_wise_op(a, ElementWiseOp::Abs)
}

/// Performs element-wise negation
pub fn neg<T: bytemuck::Pod + bytemuck::Zeroable>(a: &GpuArray<T>) -> Result<GpuArray<T>> {
    unary_element_wise_op(a, ElementWiseOp::Neg)
}

/// Performs element-wise power (a^b)
pub fn pow<T: bytemuck::Pod + bytemuck::Zeroable>(
    a: &GpuArray<T>,
    b: &GpuArray<T>,
) -> Result<GpuArray<T>> {
    element_wise_op(a, b, ElementWiseOp::Pow)
}

/// Performs matrix multiplication of two GPU arrays
pub fn matmul<T: bytemuck::Pod + bytemuck::Zeroable>(
    a: &GpuArray<T>,
    b: &GpuArray<T>,
) -> Result<GpuArray<T>> {
    // Validate shapes for matrix multiplication
    if a.shape().len() != 2 || b.shape().len() != 2 {
        return Err(NumRs2Error::ShapeMismatch {
            expected: vec![2],
            actual: vec![a.shape().len(), b.shape().len()],
        });
    }

    let a_shape = a.shape();
    let b_shape = b.shape();

    if a_shape[1] != b_shape[0] {
        return Err(NumRs2Error::DimensionMismatch(format!(
            "Cannot multiply matrices with shapes {:?} and {:?}",
            a_shape, b_shape
        )));
    }

    // Output shape is [a_rows, b_cols]
    let out_shape = vec![a_shape[0], b_shape[1]];
    let context = a.context().clone();

    // Create output array
    let result = GpuArray::<T>::new_with_shape(&out_shape, context.clone())?;

    // Create bind group layout and pipeline
    let bind_group_layout =
        context
            .device()
            .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                label: Some("NumRS2 MatMul Bind Group Layout"),
                entries: &[
                    // Input matrix A
                    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,
                    },
                    // Input matrix B
                    wgpu::BindGroupLayoutEntry {
                        binding: 1,
                        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,
                    },
                    // Output matrix C
                    wgpu::BindGroupLayoutEntry {
                        binding: 2,
                        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,
                    },
                    // Dimensions
                    wgpu::BindGroupLayoutEntry {
                        binding: 3,
                        visibility: wgpu::ShaderStages::COMPUTE,
                        ty: wgpu::BindingType::Buffer {
                            ty: wgpu::BufferBindingType::Uniform,
                            has_dynamic_offset: false,
                            min_binding_size: None,
                        },
                        count: None,
                    },
                ],
            });

    // Select the appropriate shader based on the type
    let shader = if std::mem::size_of::<T>() == 4 {
        context.matmul_f32_shader()
    } else {
        context.matmul_f64_shader()
    };

    let pipeline_layout =
        context
            .device()
            .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                label: Some("NumRS2 MatMul Pipeline Layout"),
                bind_group_layouts: &[Some(&bind_group_layout)],
                immediate_size: 0,
            });

    let pipeline = context
        .device()
        .create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
            label: Some("NumRS2 MatMul Pipeline"),
            layout: Some(&pipeline_layout),
            module: shader,
            entry_point: Some("main"),
            cache: None,
            compilation_options: Default::default(),
        });

    // Create dimensions buffer
    let dims = [
        a_shape[0] as u32, // a_rows
        a_shape[1] as u32, // a_cols (same as b_rows)
        b_shape[1] as u32, // b_cols
        0,                 // padding
    ];

    let dimensions_buffer =
        context
            .device()
            .create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some("MatMul Dimensions"),
                contents: bytemuck::cast_slice(&dims),
                usage: wgpu::BufferUsages::UNIFORM,
            });

    // Create bind group
    let bind_group = context
        .device()
        .create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("NumRS2 MatMul Bind Group"),
            layout: &bind_group_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: a.buffer().as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: b.buffer().as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: result.buffer().as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 3,
                    resource: dimensions_buffer.as_entire_binding(),
                },
            ],
        });

    // Calculate workgroup dimensions (one workgroup per output element with tiling)
    let workgroup_count_x = (out_shape[1] as f32 / 16.0).ceil() as u32;
    let workgroup_count_y = (out_shape[0] as f32 / 16.0).ceil() as u32;

    // Run the compute pass
    context.run_compute(
        &pipeline,
        &[&bind_group],
        (workgroup_count_x, workgroup_count_y, 1),
    );

    Ok(result)
}

/// Transposes a GPU array
pub fn transpose<T: bytemuck::Pod + bytemuck::Zeroable>(a: &GpuArray<T>) -> Result<GpuArray<T>> {
    // Validate that the array has at least 2 dimensions
    if a.shape().len() < 2 {
        return Err(NumRs2Error::InvalidOperation(format!(
            "Cannot transpose array with less than 2 dimensions, got shape {:?}",
            a.shape()
        )));
    }

    // For 2D arrays, simply swap the dimensions
    if a.shape().len() == 2 {
        let mut out_shape = a.shape().to_vec();
        out_shape.swap(0, 1);

        let context = a.context().clone();
        let result = GpuArray::<T>::new_with_shape(&out_shape, context.clone())?;

        // Create bind group layout and pipeline
        let bind_group_layout =
            context
                .device()
                .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                    label: Some("NumRS2 Transpose Bind Group Layout"),
                    entries: &[
                        // Input array
                        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,
                        },
                        // Output array
                        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,
                        },
                        // Dimensions
                        wgpu::BindGroupLayoutEntry {
                            binding: 2,
                            visibility: wgpu::ShaderStages::COMPUTE,
                            ty: wgpu::BindingType::Buffer {
                                ty: wgpu::BufferBindingType::Uniform,
                                has_dynamic_offset: false,
                                min_binding_size: None,
                            },
                            count: None,
                        },
                    ],
                });

        // Select the appropriate shader based on the type
        let shader = if std::mem::size_of::<T>() == 4 {
            context.element_wise_f32_shader()
        } else {
            context.element_wise_f64_shader()
        };

        let pipeline_layout =
            context
                .device()
                .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                    label: Some("NumRS2 Transpose Pipeline Layout"),
                    bind_group_layouts: &[Some(&bind_group_layout)],
                    immediate_size: 0,
                });

        let pipeline = context
            .device()
            .create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
                label: Some("NumRS2 Transpose Pipeline"),
                layout: Some(&pipeline_layout),
                module: shader,
                entry_point: Some("transpose"),
                cache: None,
                compilation_options: Default::default(),
            });

        // Create dimensions buffer
        let dims = [a.shape()[0] as u32, a.shape()[1] as u32, 0, 0];

        let dimensions_buffer =
            context
                .device()
                .create_buffer_init(&wgpu::util::BufferInitDescriptor {
                    label: Some("Transpose Dimensions"),
                    contents: bytemuck::cast_slice(&dims),
                    usage: wgpu::BufferUsages::UNIFORM,
                });

        // Create bind group
        let bind_group = context
            .device()
            .create_bind_group(&wgpu::BindGroupDescriptor {
                label: Some("NumRS2 Transpose Bind Group"),
                layout: &bind_group_layout,
                entries: &[
                    wgpu::BindGroupEntry {
                        binding: 0,
                        resource: a.buffer().as_entire_binding(),
                    },
                    wgpu::BindGroupEntry {
                        binding: 1,
                        resource: result.buffer().as_entire_binding(),
                    },
                    wgpu::BindGroupEntry {
                        binding: 2,
                        resource: dimensions_buffer.as_entire_binding(),
                    },
                ],
            });

        // Calculate workgroup dimensions
        let workgroup_count_x = (out_shape[1] as f32 / 16.0).ceil() as u32;
        let workgroup_count_y = (out_shape[0] as f32 / 16.0).ceil() as u32;

        // Run the compute pass
        context.run_compute(
            &pipeline,
            &[&bind_group],
            (workgroup_count_x, workgroup_count_y, 1),
        );

        return Ok(result);
    }

    // For higher dimensions, we need a more complex implementation
    // (not covered in this initial version)
    Err(NumRs2Error::NotImplemented(
        "Transpose for arrays with more than 2 dimensions is not implemented yet".to_string(),
    ))
}

/// Helper function for element-wise binary operations
fn element_wise_op<T: bytemuck::Pod + bytemuck::Zeroable>(
    a: &GpuArray<T>,
    b: &GpuArray<T>,
    op: ElementWiseOp,
) -> Result<GpuArray<T>> {
    // Validate shapes
    if a.shape() != b.shape() {
        return Err(NumRs2Error::ShapeMismatch {
            expected: a.shape().to_vec(),
            actual: b.shape().to_vec(),
        });
    }

    // Create output array with same shape
    let context = a.context().clone();
    let result = GpuArray::<T>::new_with_shape(a.shape(), context.clone())?;

    // Create bind group layout
    let bind_group_layout =
        context
            .device()
            .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                label: Some("NumRS2 Element-wise Bind Group Layout"),
                entries: &[
                    // Input array A
                    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,
                    },
                    // Input array B
                    wgpu::BindGroupLayoutEntry {
                        binding: 1,
                        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,
                    },
                    // Output array
                    wgpu::BindGroupLayoutEntry {
                        binding: 2,
                        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,
                    },
                    // Operation type and array size
                    wgpu::BindGroupLayoutEntry {
                        binding: 3,
                        visibility: wgpu::ShaderStages::COMPUTE,
                        ty: wgpu::BindingType::Buffer {
                            ty: wgpu::BufferBindingType::Uniform,
                            has_dynamic_offset: false,
                            min_binding_size: None,
                        },
                        count: None,
                    },
                ],
            });

    // Select the appropriate shader based on the type
    let shader = if std::mem::size_of::<T>() == 4 {
        context.element_wise_f32_shader()
    } else {
        context.element_wise_f64_shader()
    };

    // Create pipeline
    let pipeline_layout =
        context
            .device()
            .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                label: Some("NumRS2 Element-wise Pipeline Layout"),
                bind_group_layouts: &[Some(&bind_group_layout)],
                immediate_size: 0,
            });

    let pipeline = context
        .device()
        .create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
            label: Some("NumRS2 Element-wise Pipeline"),
            layout: Some(&pipeline_layout),
            module: shader,
            entry_point: Some("binary_op"),
            cache: None,
            compilation_options: Default::default(),
        });

    // Create uniform buffer with operation type and size
    let params = [op as u32, a.size() as u32, 0, 0];

    let params_buffer = context
        .device()
        .create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some("Element-wise Op Params"),
            contents: bytemuck::cast_slice(&params),
            usage: wgpu::BufferUsages::UNIFORM,
        });

    // Create bind group
    let bind_group = context
        .device()
        .create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("NumRS2 Element-wise Bind Group"),
            layout: &bind_group_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: a.buffer().as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: b.buffer().as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: result.buffer().as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 3,
                    resource: params_buffer.as_entire_binding(),
                },
            ],
        });

    // Calculate workgroup count
    let total_threads = a.size() as u32;
    let workgroup_count = total_threads.div_ceil(WORKGROUP_SIZE);

    // Run the compute pass
    context.run_compute(&pipeline, &[&bind_group], (workgroup_count, 1, 1));

    Ok(result)
}

/// Enumerates the types of reduction operations
#[derive(Clone, Copy)]
enum ReductionOp {
    Sum = 0,
    Mean = 1,
    Max = 2,
    Min = 3,
}

/// Computes the sum of all elements in a GPU array (f32 version)
pub fn sum_f32(a: &GpuArray<f32>) -> Result<f32> {
    reduction_op_f32(a, ReductionOp::Sum)
}

/// Computes the sum of all elements in a GPU array (f64 version)
pub fn sum_f64(a: &GpuArray<f64>) -> Result<f64> {
    reduction_op_f64(a, ReductionOp::Sum)
}

/// Computes the mean of all elements in a GPU array (f32 version)
pub fn mean_f32(a: &GpuArray<f32>) -> Result<f32> {
    reduction_op_f32(a, ReductionOp::Mean)
}

/// Computes the mean of all elements in a GPU array (f64 version)
pub fn mean_f64(a: &GpuArray<f64>) -> Result<f64> {
    reduction_op_f64(a, ReductionOp::Mean)
}

/// Computes the maximum value in a GPU array (f32 version)
pub fn max_f32(a: &GpuArray<f32>) -> Result<f32> {
    reduction_op_f32(a, ReductionOp::Max)
}

/// Computes the maximum value in a GPU array (f64 version)
pub fn max_f64(a: &GpuArray<f64>) -> Result<f64> {
    reduction_op_f64(a, ReductionOp::Max)
}

/// Computes the minimum value in a GPU array (f32 version)
pub fn min_f32(a: &GpuArray<f32>) -> Result<f32> {
    reduction_op_f32(a, ReductionOp::Min)
}

/// Computes the minimum value in a GPU array (f64 version)
pub fn min_f64(a: &GpuArray<f64>) -> Result<f64> {
    reduction_op_f64(a, ReductionOp::Min)
}

/// Helper function for f32 reduction operations
fn reduction_op_f32(a: &GpuArray<f32>, op: ReductionOp) -> Result<f32> {
    let context = a.context().clone();
    let total_elements = a.size() as u32;

    // Calculate number of workgroups needed
    let workgroup_count = total_elements.div_ceil(WORKGROUP_SIZE);

    // Create output buffer for partial results (one per workgroup)
    let partial_results_size = workgroup_count as usize * std::mem::size_of::<f32>();
    let partial_results_buffer = context.device().create_buffer(&wgpu::BufferDescriptor {
        label: Some("Reduction Partial Results"),
        size: partial_results_size as u64,
        usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
        mapped_at_creation: false,
    });

    // Create bind group layout
    let bind_group_layout =
        context
            .device()
            .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                label: Some("NumRS2 Reduction Bind Group Layout"),
                entries: &[
                    // Input array
                    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,
                    },
                    // Output partial results
                    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,
                    },
                    // Parameters (operation type, array size)
                    wgpu::BindGroupLayoutEntry {
                        binding: 2,
                        visibility: wgpu::ShaderStages::COMPUTE,
                        ty: wgpu::BindingType::Buffer {
                            ty: wgpu::BufferBindingType::Uniform,
                            has_dynamic_offset: false,
                            min_binding_size: None,
                        },
                        count: None,
                    },
                ],
            });

    let shader = context.reduction_f32_shader();

    // Create pipeline
    let pipeline_layout =
        context
            .device()
            .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                label: Some("NumRS2 Reduction Pipeline Layout"),
                bind_group_layouts: &[Some(&bind_group_layout)],
                immediate_size: 0,
            });

    let pipeline = context
        .device()
        .create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
            label: Some("NumRS2 Reduction Pipeline"),
            layout: Some(&pipeline_layout),
            module: shader,
            entry_point: Some("reduction"),
            cache: None,
            compilation_options: Default::default(),
        });

    // Create uniform buffer with operation type and size
    let params = [op as u32, total_elements, 0, 0];

    let params_buffer = context
        .device()
        .create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some("Reduction Op Params"),
            contents: bytemuck::cast_slice(&params),
            usage: wgpu::BufferUsages::UNIFORM,
        });

    // Create bind group
    let bind_group = context
        .device()
        .create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("NumRS2 Reduction Bind Group"),
            layout: &bind_group_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: a.buffer().as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: partial_results_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: params_buffer.as_entire_binding(),
                },
            ],
        });

    // Run the compute pass
    context.run_compute(&pipeline, &[&bind_group], (workgroup_count, 1, 1));

    // Read back partial results
    let staging_buffer = context.device().create_buffer(&wgpu::BufferDescriptor {
        label: Some("Reduction Staging Buffer"),
        size: partial_results_size as u64,
        usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
        mapped_at_creation: false,
    });

    // Copy from GPU to staging buffer
    let mut encoder = context
        .device()
        .create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("Reduction Copy Encoder"),
        });

    encoder.copy_buffer_to_buffer(
        &partial_results_buffer,
        0,
        &staging_buffer,
        0,
        partial_results_size as u64,
    );

    context.queue().submit(Some(encoder.finish()));

    // Map the staging buffer and read results
    let buffer_slice = staging_buffer.slice(..);
    let (tx, rx) = std::sync::mpsc::channel();
    buffer_slice.map_async(wgpu::MapMode::Read, move |result| {
        tx.send(result)
            .expect("Failed to send f32 reduction buffer mapping result - receiver dropped");
    });

    context
        .device()
        .poll(wgpu::PollType::wait_indefinitely())
        .expect("GPU device poll failed during f32 reduction buffer mapping");
    rx.recv()
        .map_err(|e| {
            NumRs2Error::RuntimeError(format!(
                "Failed to receive f32 reduction buffer mapping result: {:?}",
                e
            ))
        })?
        .map_err(|e| NumRs2Error::RuntimeError(format!("Failed to map buffer: {:?}", e)))?;

    let data = buffer_slice.get_mapped_range();
    let partial_results: &[f32] = bytemuck::cast_slice(&data);

    // Perform final reduction on CPU
    let final_result = match op {
        ReductionOp::Sum => partial_results.iter().sum(),
        ReductionOp::Mean => partial_results.iter().sum::<f32>() / total_elements as f32,
        ReductionOp::Max => partial_results
            .iter()
            .cloned()
            .fold(f32::NEG_INFINITY, f32::max),
        ReductionOp::Min => partial_results
            .iter()
            .cloned()
            .fold(f32::INFINITY, f32::min),
    };

    drop(data);
    staging_buffer.unmap();

    Ok(final_result)
}

/// Helper function for f64 reduction operations
fn reduction_op_f64(a: &GpuArray<f64>, op: ReductionOp) -> Result<f64> {
    let context = a.context().clone();
    let total_elements = a.size() as u32;

    // Calculate number of workgroups needed
    let workgroup_count = total_elements.div_ceil(WORKGROUP_SIZE);

    // Create output buffer for partial results (one per workgroup)
    let partial_results_size = workgroup_count as usize * std::mem::size_of::<f64>();
    let partial_results_buffer = context.device().create_buffer(&wgpu::BufferDescriptor {
        label: Some("Reduction Partial Results"),
        size: partial_results_size as u64,
        usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
        mapped_at_creation: false,
    });

    // Create bind group layout
    let bind_group_layout =
        context
            .device()
            .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                label: Some("NumRS2 Reduction Bind Group Layout"),
                entries: &[
                    // Input array
                    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,
                    },
                    // Output partial results
                    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,
                    },
                    // Parameters (operation type, array size)
                    wgpu::BindGroupLayoutEntry {
                        binding: 2,
                        visibility: wgpu::ShaderStages::COMPUTE,
                        ty: wgpu::BindingType::Buffer {
                            ty: wgpu::BufferBindingType::Uniform,
                            has_dynamic_offset: false,
                            min_binding_size: None,
                        },
                        count: None,
                    },
                ],
            });

    let shader = context.reduction_f64_shader();

    // Create pipeline
    let pipeline_layout =
        context
            .device()
            .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                label: Some("NumRS2 Reduction Pipeline Layout"),
                bind_group_layouts: &[Some(&bind_group_layout)],
                immediate_size: 0,
            });

    let pipeline = context
        .device()
        .create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
            label: Some("NumRS2 Reduction Pipeline"),
            layout: Some(&pipeline_layout),
            module: shader,
            entry_point: Some("reduction"),
            cache: None,
            compilation_options: Default::default(),
        });

    // Create uniform buffer with operation type and size
    let params = [op as u32, total_elements, 0, 0];

    let params_buffer = context
        .device()
        .create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some("Reduction Op Params"),
            contents: bytemuck::cast_slice(&params),
            usage: wgpu::BufferUsages::UNIFORM,
        });

    // Create bind group
    let bind_group = context
        .device()
        .create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("NumRS2 Reduction Bind Group"),
            layout: &bind_group_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: a.buffer().as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: partial_results_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: params_buffer.as_entire_binding(),
                },
            ],
        });

    // Run the compute pass
    context.run_compute(&pipeline, &[&bind_group], (workgroup_count, 1, 1));

    // Read back partial results
    let staging_buffer = context.device().create_buffer(&wgpu::BufferDescriptor {
        label: Some("Reduction Staging Buffer"),
        size: partial_results_size as u64,
        usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
        mapped_at_creation: false,
    });

    // Copy from GPU to staging buffer
    let mut encoder = context
        .device()
        .create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("Reduction Copy Encoder"),
        });

    encoder.copy_buffer_to_buffer(
        &partial_results_buffer,
        0,
        &staging_buffer,
        0,
        partial_results_size as u64,
    );

    context.queue().submit(Some(encoder.finish()));

    // Map the staging buffer and read results
    let buffer_slice = staging_buffer.slice(..);
    let (tx, rx) = std::sync::mpsc::channel();
    buffer_slice.map_async(wgpu::MapMode::Read, move |result| {
        tx.send(result)
            .expect("Failed to send f64 reduction buffer mapping result - receiver dropped");
    });

    context
        .device()
        .poll(wgpu::PollType::wait_indefinitely())
        .expect("GPU device poll failed during f64 reduction buffer mapping");
    rx.recv()
        .map_err(|e| {
            NumRs2Error::RuntimeError(format!(
                "Failed to receive f64 reduction buffer mapping result: {:?}",
                e
            ))
        })?
        .map_err(|e| NumRs2Error::RuntimeError(format!("Failed to map buffer: {:?}", e)))?;

    let data = buffer_slice.get_mapped_range();
    let partial_results: &[f64] = bytemuck::cast_slice(&data);

    // Perform final reduction on CPU
    let final_result = match op {
        ReductionOp::Sum => partial_results.iter().sum(),
        ReductionOp::Mean => partial_results.iter().sum::<f64>() / total_elements as f64,
        ReductionOp::Max => partial_results
            .iter()
            .cloned()
            .fold(f64::NEG_INFINITY, f64::max),
        ReductionOp::Min => partial_results
            .iter()
            .cloned()
            .fold(f64::INFINITY, f64::min),
    };

    drop(data);
    staging_buffer.unmap();

    Ok(final_result)
}

/// Helper function for element-wise unary operations
fn unary_element_wise_op<T: bytemuck::Pod + bytemuck::Zeroable>(
    a: &GpuArray<T>,
    op: ElementWiseOp,
) -> Result<GpuArray<T>> {
    // Create output array with same shape
    let context = a.context().clone();
    let result = GpuArray::<T>::new_with_shape(a.shape(), context.clone())?;

    // Create bind group layout
    let bind_group_layout =
        context
            .device()
            .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                label: Some("NumRS2 Unary Element-wise Bind Group Layout"),
                entries: &[
                    // Input array
                    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,
                    },
                    // Output array
                    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,
                    },
                    // Operation type and array size
                    wgpu::BindGroupLayoutEntry {
                        binding: 2,
                        visibility: wgpu::ShaderStages::COMPUTE,
                        ty: wgpu::BindingType::Buffer {
                            ty: wgpu::BufferBindingType::Uniform,
                            has_dynamic_offset: false,
                            min_binding_size: None,
                        },
                        count: None,
                    },
                ],
            });

    // Select the appropriate shader based on the type
    let shader = if std::mem::size_of::<T>() == 4 {
        context.element_wise_f32_shader()
    } else {
        context.element_wise_f64_shader()
    };

    // Create pipeline
    let pipeline_layout =
        context
            .device()
            .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                label: Some("NumRS2 Unary Element-wise Pipeline Layout"),
                bind_group_layouts: &[Some(&bind_group_layout)],
                immediate_size: 0,
            });

    let pipeline = context
        .device()
        .create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
            label: Some("NumRS2 Unary Element-wise Pipeline"),
            layout: Some(&pipeline_layout),
            module: shader,
            entry_point: Some("unary_op"),
            cache: None,
            compilation_options: Default::default(),
        });

    // Create uniform buffer with operation type and size
    let params = [op as u32, a.size() as u32, 0, 0];

    let params_buffer = context
        .device()
        .create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some("Unary Element-wise Op Params"),
            contents: bytemuck::cast_slice(&params),
            usage: wgpu::BufferUsages::UNIFORM,
        });

    // Create bind group
    let bind_group = context
        .device()
        .create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("NumRS2 Unary Element-wise Bind Group"),
            layout: &bind_group_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: a.buffer().as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: result.buffer().as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: params_buffer.as_entire_binding(),
                },
            ],
        });

    // Calculate workgroup count
    let total_threads = a.size() as u32;
    let workgroup_count = total_threads.div_ceil(WORKGROUP_SIZE);

    // Run the compute pass
    context.run_compute(&pipeline, &[&bind_group], (workgroup_count, 1, 1));

    Ok(result)
}

/// Performs broadcasting-aware element-wise addition
///
/// Supports NumPy-style broadcasting where arrays with different shapes
/// can be combined if they are compatible.
pub fn broadcast_add<T: bytemuck::Pod + bytemuck::Zeroable>(
    a: &GpuArray<T>,
    b: &GpuArray<T>,
) -> Result<GpuArray<T>> {
    let output_shape = broadcast_shapes(a.shape(), b.shape())?;
    broadcast_binary_op(a, b, &output_shape, ElementWiseOp::Add)
}

/// Performs broadcasting-aware element-wise multiplication
pub fn broadcast_multiply<T: bytemuck::Pod + bytemuck::Zeroable>(
    a: &GpuArray<T>,
    b: &GpuArray<T>,
) -> Result<GpuArray<T>> {
    let output_shape = broadcast_shapes(a.shape(), b.shape())?;
    broadcast_binary_op(a, b, &output_shape, ElementWiseOp::Multiply)
}

/// Determines the output shape for broadcasting two arrays
fn broadcast_shapes(shape_a: &[usize], shape_b: &[usize]) -> Result<Vec<usize>> {
    let max_dims = shape_a.len().max(shape_b.len());
    let mut result = vec![1; max_dims];

    for i in 0..max_dims {
        let dim_a = if i < shape_a.len() {
            shape_a[shape_a.len() - 1 - i]
        } else {
            1
        };
        let dim_b = if i < shape_b.len() {
            shape_b[shape_b.len() - 1 - i]
        } else {
            1
        };

        if dim_a == dim_b {
            result[max_dims - 1 - i] = dim_a;
        } else if dim_a == 1 {
            result[max_dims - 1 - i] = dim_b;
        } else if dim_b == 1 {
            result[max_dims - 1 - i] = dim_a;
        } else {
            return Err(NumRs2Error::ShapeMismatch {
                expected: shape_a.to_vec(),
                actual: shape_b.to_vec(),
            });
        }
    }

    Ok(result)
}

/// Helper function for broadcasting binary operations
fn broadcast_binary_op<T: bytemuck::Pod + bytemuck::Zeroable>(
    a: &GpuArray<T>,
    b: &GpuArray<T>,
    output_shape: &[usize],
    op: ElementWiseOp,
) -> Result<GpuArray<T>> {
    // For now, if shapes match exactly, use regular operation
    if a.shape() == b.shape() {
        return element_wise_op(a, b, op);
    }

    // Otherwise, we need broadcasting support
    // This is a simplified implementation - full broadcasting requires more complex shader code
    Err(NumRs2Error::NotImplemented(
        "Full broadcasting support is not yet implemented for GPU arrays".to_string(),
    ))
}

/// Copies a GPU array with optional format conversion
pub fn copy_with_format<T: bytemuck::Pod + bytemuck::Zeroable>(
    src: &GpuArray<T>,
) -> Result<GpuArray<T>> {
    let context = src.context().clone();
    let result = GpuArray::<T>::new_with_shape(src.shape(), context.clone())?;

    // Create command encoder for the copy
    let mut encoder = context
        .device()
        .create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("NumRS2 Copy Encoder"),
        });

    encoder.copy_buffer_to_buffer(
        src.buffer(),
        0,
        result.buffer(),
        0,
        (src.size() * src.element_size()) as u64,
    );

    context.queue().submit(std::iter::once(encoder.finish()));

    Ok(result)
}

/// Fills a GPU array with a scalar value
pub fn fill<T: bytemuck::Pod + bytemuck::Zeroable + Clone>(
    array: &mut GpuArray<T>,
    value: T,
) -> Result<()> {
    let data = vec![value; array.size()];
    array
        .context()
        .queue()
        .write_buffer(array.buffer(), 0, bytemuck::cast_slice(&data));
    Ok(())
}

/// Creates a slice view of a GPU array
///
/// Note: This creates a new array with a copy of the sliced data
pub fn slice<T: bytemuck::Pod + bytemuck::Zeroable>(
    array: &GpuArray<T>,
    ranges: &[(usize, usize)],
) -> Result<GpuArray<T>> {
    if ranges.len() != array.shape().len() {
        return Err(NumRs2Error::DimensionMismatch(format!(
            "Number of slice ranges ({}) does not match array dimensions ({})",
            ranges.len(),
            array.shape().len()
        )));
    }

    // Validate ranges and calculate new shape
    let mut new_shape = Vec::with_capacity(ranges.len());
    for (i, (start, end)) in ranges.iter().enumerate() {
        if *start >= *end || *end > array.shape()[i] {
            return Err(NumRs2Error::IndexError(format!(
                "Invalid range [{}..{}] for dimension {} with size {}",
                start,
                end,
                i,
                array.shape()[i]
            )));
        }
        new_shape.push(*end - *start);
    }

    // For now, we need to transfer to CPU, slice, and transfer back
    // A more efficient implementation would use GPU compute shaders
    let cpu_array = array.to_array()?;

    // Build slice indices
    let mut slice_spec = String::new();
    for (i, (start, end)) in ranges.iter().enumerate() {
        if i > 0 {
            slice_spec.push_str(", ");
        }
        slice_spec.push_str(&format!("{}..{}", start, end));
    }

    // This is a simplified implementation - full slicing would require ndarray slice support
    Err(NumRs2Error::NotImplemented(
        "GPU array slicing is not yet fully implemented".to_string(),
    ))
}