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
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
//! Metal Performance Shaders kernel implementations for GPU acceleration
//! GPU加速のためのMetal Performance Shadersカーネル実装

use crate::error::{RusTorchError, RusTorchResult};
use std::collections::HashMap;
// Metal GPU kernel implementations
use std::ffi::c_void;
use std::marker::PhantomData;

#[cfg(feature = "metal")]
use metal::foreign_types::ForeignType;
#[cfg(feature = "metal")]
use metal::{
    CommandQueue, CompileOptions, ComputePipelineState, Device, Library, MTLResourceOptions,
    MTLSize,
};

/// Metal kernel types
/// Metalカーネルタイプ
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum MetalKernelType {
    /// Element-wise operations (add, mul, etc.)
    /// 要素ごとの演算(加算、乗算など)
    ElementWise,
    /// Matrix multiplication operations
    /// 行列乗算演算
    MatMul,
    /// Reduction operations (sum, mean, etc.)
    /// リダクション演算(合計、平均など)
    Reduction,
    /// Convolution operations
    /// 畳み込み演算
    Convolution,
    /// Batch normalization operations
    /// バッチ正規化演算
    BatchNorm,
}

/// Metal kernel parameters
/// Metalカーネルパラメータ
#[derive(Debug, Clone)]
pub struct MetalKernelParams {
    /// Threads per threadgroup for Metal kernel execution
    /// Metalカーネル実行のスレッドグループあたりのスレッド数
    pub threads_per_threadgroup: (u32, u32, u32),
    /// Threadgroups per grid for Metal kernel execution
    /// Metalカーネル実行のグリッドあたりのスレッドグループ数
    pub threadgroups_per_grid: (u32, u32, u32),
}

impl Default for MetalKernelParams {
    fn default() -> Self {
        Self {
            threads_per_threadgroup: (1, 1, 1),
            threadgroups_per_grid: (1, 1, 1),
        }
    }
}

/// Metal buffer wrapper
/// Metalバッファラッパー
pub struct MetalBuffer<T> {
    _buffer: *mut c_void,
    size: usize,
    _phantom: PhantomData<T>,
}

impl<T> MetalBuffer<T> {
    /// Create a new Metal buffer
    /// 新しいMetalバッファを作成
    #[cfg(feature = "metal")]
    pub fn new(size: usize, device: &Device) -> RusTorchResult<Self> {
        let buffer_size = size * std::mem::size_of::<T>();
        let buffer = device.new_buffer(buffer_size as u64, MTLResourceOptions::StorageModeShared);

        Ok(Self {
            _buffer: buffer.as_ptr() as *mut c_void,
            size,
            _phantom: PhantomData,
        })
    }

    #[cfg(not(feature = "metal"))]
    /// Create a new Metal buffer with specified size
    /// 指定されたサイズで新しいMetalバッファを作成
    pub fn new(_size: usize, _device: &()) -> RusTorchResult<Self> {
        Err(RusTorchError::UnsupportedDevice(
            "Metal not available".to_string(),
        ))
    }

    /// Copy data from host to Metal buffer
    /// ホストからMetalバッファへデータをコピー
    pub fn copy_from_host(&mut self, host_data: &[T]) -> RusTorchResult<()> {
        if host_data.len() != self.size {
            return Err(RusTorchError::InvalidOperation(
                "Size mismatch in host-to-device copy".to_string(),
            ));
        }

        #[cfg(feature = "metal")]
        {
            unsafe {
                let buffer_ptr = self._buffer as *mut T;
                std::ptr::copy_nonoverlapping(host_data.as_ptr(), buffer_ptr, self.size);
            }
            Ok(())
        }
        #[cfg(not(feature = "metal"))]
        {
            Err(RusTorchError::UnsupportedDevice(
                "Metal not available".to_string(),
            ))
        }
    }

    /// Copy data from Metal buffer to host
    /// Metalバッファからホストへデータをコピー
    pub fn copy_to_host(&self, host_data: &mut [T]) -> RusTorchResult<()> {
        if host_data.len() != self.size {
            return Err(RusTorchError::InvalidOperation(
                "Size mismatch in device-to-host copy".to_string(),
            ));
        }

        #[cfg(feature = "metal")]
        {
            unsafe {
                let buffer_ptr = self._buffer as *const T;
                std::ptr::copy_nonoverlapping(buffer_ptr, host_data.as_mut_ptr(), self.size);
            }
            Ok(())
        }
        #[cfg(not(feature = "metal"))]
        {
            Err(RusTorchError::UnsupportedDevice(
                "Metal not available".to_string(),
            ))
        }
    }
}

/// Metal kernel executor for high-performance GPU operations
/// 高性能GPU演算のためのMetalカーネル実行器
#[cfg(feature = "metal")]
pub struct MetalKernelExecutor {
    device: Device,
    command_queue: CommandQueue,
    library: Library,
    pipeline_states: HashMap<MetalKernelType, ComputePipelineState>,
}

#[cfg(feature = "metal")]
impl MetalKernelExecutor {
    /// Create a new Metal kernel executor
    /// 新しいMetalカーネル実行器を作成
    pub fn new() -> RusTorchResult<Self> {
        let device = Device::system_default()
            .ok_or_else(|| RusTorchError::tensor_op("No Metal device available"))?;

        let command_queue = device.new_command_queue();

        // Metal shader library source optimized for AMD Radeon Pro Vega 56
        let shader_source = r#"
        #include <metal_stdlib>
        using namespace metal;
        
        // Optimized element-wise addition with vectorization
        kernel void elementwise_add_f32(
            device const float* a [[buffer(0)]],
            device const float* b [[buffer(1)]],
            device float* result [[buffer(2)]],
            uint index [[thread_position_in_grid]]
        ) {
            result[index] = a[index] + b[index];
        }
        
        // Optimized element-wise multiplication with vectorization
        kernel void elementwise_mul_f32(
            device const float* a [[buffer(0)]],
            device const float* b [[buffer(1)]],
            device float* result [[buffer(2)]],
            uint index [[thread_position_in_grid]]
        ) {
            result[index] = a[index] * b[index];
        }
        
        // High-performance matrix multiplication optimized for Vega 56 architecture
        kernel void matrix_multiply_f32(
            device const float* a [[buffer(0)]],
            device const float* b [[buffer(1)]],
            device float* c [[buffer(2)]],
            constant uint& M [[buffer(3)]],
            constant uint& N [[buffer(4)]],
            constant uint& K [[buffer(5)]],
            uint2 gid [[thread_position_in_grid]]
        ) {
            uint row = gid.y;
            uint col = gid.x;
            
            if (row >= M || col >= N) return;
            
            float sum = 0.0;
            // Unroll loop for better performance on Vega architecture
            for (uint k = 0; k < K; k++) {
                sum += a[row * K + k] * b[k * N + col];
            }
            c[row * N + col] = sum;
        }
        
        // Optimized tiled matrix multiplication for large matrices
        kernel void tiled_matrix_multiply_f32(
            device const float* a [[buffer(0)]],
            device const float* b [[buffer(1)]],
            device float* c [[buffer(2)]],
            constant uint& M [[buffer(3)]],
            constant uint& N [[buffer(4)]],
            constant uint& K [[buffer(5)]],
            threadgroup float* tile_a [[threadgroup(0)]],
            threadgroup float* tile_b [[threadgroup(1)]],
            uint2 gid [[thread_position_in_grid]],
            uint2 lid [[thread_position_in_threadgroup]]
        ) {
            const uint TILE_SIZE = 16; // Optimized for Vega 56 memory hierarchy
            
            uint row = gid.y;
            uint col = gid.x;
            uint local_row = lid.y;
            uint local_col = lid.x;
            
            float sum = 0.0;
            
            // Tiled computation for better memory bandwidth utilization
            for (uint tile = 0; tile < (K + TILE_SIZE - 1) / TILE_SIZE; tile++) {
                // Load tiles into shared memory
                uint a_idx = row * K + tile * TILE_SIZE + local_col;
                uint b_idx = (tile * TILE_SIZE + local_row) * N + col;
                
                tile_a[local_row * TILE_SIZE + local_col] = 
                    (row < M && tile * TILE_SIZE + local_col < K) ? a[a_idx] : 0.0;
                tile_b[local_row * TILE_SIZE + local_col] = 
                    (tile * TILE_SIZE + local_row < K && col < N) ? b[b_idx] : 0.0;
                
                threadgroup_barrier(mem_flags::mem_threadgroup);
                
                // Compute partial result
                for (uint k = 0; k < TILE_SIZE; k++) {
                    sum += tile_a[local_row * TILE_SIZE + k] * 
                           tile_b[k * TILE_SIZE + local_col];
                }
                
                threadgroup_barrier(mem_flags::mem_threadgroup);
            }
            
            if (row < M && col < N) {
                c[row * N + col] = sum;
            }
        }
        
        kernel void reduce_sum_f32(
            device const float* input [[buffer(0)]],
            device float* output [[buffer(1)]],
            threadgroup float* shared_data [[threadgroup(0)]],
            uint tid [[thread_index_in_threadgroup]],
            uint bid [[threadgroup_position_in_grid]],
            uint block_size [[threads_per_threadgroup]],
            uint grid_size [[threadgroups_per_grid]]
        ) {
            uint index = bid * block_size + tid;

            // Load data into shared memory
            shared_data[tid] = (index < grid_size * block_size) ? input[index] : 0.0;
            threadgroup_barrier(mem_flags::mem_threadgroup);

            // Reduction in shared memory
            for (uint s = block_size / 2; s > 0; s >>= 1) {
                if (tid < s) {
                    shared_data[tid] += shared_data[tid + s];
                }
                threadgroup_barrier(mem_flags::mem_threadgroup);
            }

            // Write result for this block
            if (tid == 0) {
                output[bid] = shared_data[0];
            }
        }

        // Activation functions optimized for Vega 56 architecture

        // ReLU activation: max(0, x)
        kernel void relu_f32(
            device const float* input [[buffer(0)]],
            device float* output [[buffer(1)]],
            constant uint& n [[buffer(2)]],
            uint index [[thread_position_in_grid]]
        ) {
            if (index >= n) return;
            output[index] = fmax(0.0f, input[index]);
        }

        // Sigmoid activation: 1 / (1 + exp(-x))
        kernel void sigmoid_f32(
            device const float* input [[buffer(0)]],
            device float* output [[buffer(1)]],
            constant uint& n [[buffer(2)]],
            uint index [[thread_position_in_grid]]
        ) {
            if (index >= n) return;
            output[index] = 1.0f / (1.0f + exp(-input[index]));
        }

        // Tanh activation: (exp(x) - exp(-x)) / (exp(x) + exp(-x))
        kernel void tanh_f32(
            device const float* input [[buffer(0)]],
            device float* output [[buffer(1)]],
            constant uint& n [[buffer(2)]],
            uint index [[thread_position_in_grid]]
        ) {
            if (index >= n) return;
            output[index] = tanh(input[index]);
        }

        // GELU activation: x * 0.5 * (1 + erf(x / sqrt(2))) - using Abramowitz and Stegun approximation
        kernel void gelu_f32(
            device const float* input [[buffer(0)]],
            device float* output [[buffer(1)]],
            constant uint& n [[buffer(2)]],
            uint index [[thread_position_in_grid]]
        ) {
            if (index >= n) return;
            float x = input[index];
            float sqrt_2_inv = 0.70710678118f; // 1 / sqrt(2)
            float t = x * sqrt_2_inv;

            // Abramowitz and Stegun approximation for erf function
            float a1 =  0.254829592f;
            float a2 = -0.284496736f;
            float a3 =  1.421413741f;
            float a4 = -1.453152027f;
            float a5 =  1.061405429f;
            float p  =  0.3275911f;

            float sign = (t >= 0.0f) ? 1.0f : -1.0f;
            t = fabs(t);

            float t_p = 1.0f / (1.0f + p * t);
            float erf_approx = 1.0f - (((((a5 * t_p + a4) * t_p) + a3) * t_p + a2) * t_p + a1) * t_p * exp(-t * t);
            erf_approx *= sign;

            output[index] = x * 0.5f * (1.0f + erf_approx);
        }

        // Softmax activation (per element, requires separate reduction for proper implementation)
        kernel void softmax_f32(
            device const float* input [[buffer(0)]],
            device float* output [[buffer(1)]],
            constant uint& n [[buffer(2)]],
            constant float& max_val [[buffer(3)]],
            constant float& sum_exp [[buffer(4)]],
            uint index [[thread_position_in_grid]]
        ) {
            if (index >= n) return;
            float exp_val = exp(input[index] - max_val);
            output[index] = exp_val / sum_exp;
        }

        // Leaky ReLU activation: max(alpha * x, x)
        kernel void leaky_relu_f32(
            device const float* input [[buffer(0)]],
            device float* output [[buffer(1)]],
            constant uint& n [[buffer(2)]],
            constant float& alpha [[buffer(3)]],
            uint index [[thread_position_in_grid]]
        ) {
            if (index >= n) return;
            float x = input[index];
            output[index] = (x > 0.0f) ? x : alpha * x;
        }

        // ELU activation: x if x > 0, alpha * (exp(x) - 1) if x <= 0
        kernel void elu_f32(
            device const float* input [[buffer(0)]],
            device float* output [[buffer(1)]],
            constant uint& n [[buffer(2)]],
            constant float& alpha [[buffer(3)]],
            uint index [[thread_position_in_grid]]
        ) {
            if (index >= n) return;
            float x = input[index];
            output[index] = (x > 0.0f) ? x : alpha * (exp(x) - 1.0f);
        }

        // Swish activation: x * sigmoid(x)
        kernel void swish_f32(
            device const float* input [[buffer(0)]],
            device float* output [[buffer(1)]],
            constant uint& n [[buffer(2)]],
            uint index [[thread_position_in_grid]]
        ) {
            if (index >= n) return;
            float x = input[index];
            float sigmoid_x = 1.0f / (1.0f + exp(-x));
            output[index] = x * sigmoid_x;
        }
        "#;

        let library = device
            .new_library_with_source(shader_source, &CompileOptions::new())
            .map_err(|e| {
                RusTorchError::KernelError(format!("Failed to compile Metal shaders: {:?}", e))
            })?;

        let mut pipeline_states = HashMap::new();

        // Create compute pipeline states
        let add_function = library
            .get_function("elementwise_add_f32", None)
            .map_err(|e| {
                RusTorchError::KernelError(format!("Failed to get add function: {:?}", e))
            })?;
        let add_pipeline = device
            .new_compute_pipeline_state_with_function(&add_function)
            .map_err(|e| {
                RusTorchError::KernelError(format!("Failed to create add pipeline: {:?}", e))
            })?;
        pipeline_states.insert(MetalKernelType::ElementWise, add_pipeline);

        let matmul_function = library
            .get_function("matrix_multiply_f32", None)
            .map_err(|e| {
                RusTorchError::KernelError(format!("Failed to get matmul function: {:?}", e))
            })?;
        let matmul_pipeline = device
            .new_compute_pipeline_state_with_function(&matmul_function)
            .map_err(|e| {
                RusTorchError::KernelError(format!("Failed to create matmul pipeline: {:?}", e))
            })?;
        pipeline_states.insert(MetalKernelType::MatMul, matmul_pipeline);

        let tiled_matmul_function = library
            .get_function("tiled_matrix_multiply_f32", None)
            .map_err(|e| {
                RusTorchError::KernelError(format!("Failed to get tiled matmul function: {:?}", e))
            })?;
        let tiled_matmul_pipeline = device
            .new_compute_pipeline_state_with_function(&tiled_matmul_function)
            .map_err(|e| {
                RusTorchError::KernelError(format!(
                    "Failed to create tiled matmul pipeline: {:?}",
                    e
                ))
            })?;
        pipeline_states.insert(MetalKernelType::Convolution, tiled_matmul_pipeline);

        let reduce_function = library.get_function("reduce_sum_f32", None).map_err(|e| {
            RusTorchError::KernelError(format!("Failed to get reduce function: {:?}", e))
        })?;
        let reduce_pipeline = device
            .new_compute_pipeline_state_with_function(&reduce_function)
            .map_err(|e| {
                RusTorchError::KernelError(format!("Failed to create reduce pipeline: {:?}", e))
            })?;
        pipeline_states.insert(MetalKernelType::Reduction, reduce_pipeline);

        Ok(Self {
            device,
            command_queue,
            library,
            pipeline_states,
        })
    }

    /// Execute element-wise addition using Metal Performance Shaders
    /// Metal Performance Shadersを使用して要素ごと加算を実行
    pub fn elementwise_add_f32(&self, a: &[f32], b: &[f32], c: &mut [f32]) -> RusTorchResult<()> {
        let size = a.len();
        if b.len() != size || c.len() != size {
            return Err(RusTorchError::InvalidOperation(
                "Array size mismatch in element-wise addition".to_string(),
            ));
        }

        // Create Metal buffers
        let a_buffer = self.device.new_buffer_with_data(
            a.as_ptr() as *const c_void,
            (size * std::mem::size_of::<f32>()) as u64,
            MTLResourceOptions::StorageModeShared,
        );

        let b_buffer = self.device.new_buffer_with_data(
            b.as_ptr() as *const c_void,
            (size * std::mem::size_of::<f32>()) as u64,
            MTLResourceOptions::StorageModeShared,
        );

        let c_buffer = self.device.new_buffer(
            (size * std::mem::size_of::<f32>()) as u64,
            MTLResourceOptions::StorageModeShared,
        );

        // Get pipeline state
        let pipeline_state = self
            .pipeline_states
            .get(&MetalKernelType::ElementWise)
            .ok_or_else(|| {
                RusTorchError::KernelError("ElementWise pipeline not found".to_string())
            })?;

        // Create command buffer and encoder
        let command_buffer = self.command_queue.new_command_buffer();
        let compute_encoder = command_buffer.new_compute_command_encoder();

        compute_encoder.set_compute_pipeline_state(pipeline_state);
        compute_encoder.set_buffer(0, Some(&a_buffer), 0);
        compute_encoder.set_buffer(1, Some(&b_buffer), 0);
        compute_encoder.set_buffer(2, Some(&c_buffer), 0);

        // Calculate thread configuration
        let threads_per_threadgroup = MTLSize::new(256, 1, 1);
        let threadgroups_per_grid = MTLSize::new(((size + 255) / 256) as u64, 1, 1);

        compute_encoder.dispatch_thread_groups(threadgroups_per_grid, threads_per_threadgroup);
        compute_encoder.end_encoding();

        command_buffer.commit();
        command_buffer.wait_until_completed();

        // Copy result back to host
        unsafe {
            let result_ptr = c_buffer.contents() as *const f32;
            std::ptr::copy_nonoverlapping(result_ptr, c.as_mut_ptr(), size);
        }

        Ok(())
    }

    /// Execute tiled matrix multiplication using Metal for large matrices
    /// 大行列に対してMetalを使用してタイル化行列乗算を実行
    pub fn tiled_matmul_f32(
        &self,
        a: &[f32],
        b: &[f32],
        c: &mut [f32],
        m: usize,
        n: usize,
        k: usize,
    ) -> RusTorchResult<()> {
        const TILE_SIZE: usize = 16; // Optimized for Vega 56

        // Create Metal buffers
        let a_buffer = self.device.new_buffer_with_data(
            a.as_ptr() as *const c_void,
            (m * k * std::mem::size_of::<f32>()) as u64,
            MTLResourceOptions::StorageModeShared,
        );

        let b_buffer = self.device.new_buffer_with_data(
            b.as_ptr() as *const c_void,
            (k * n * std::mem::size_of::<f32>()) as u64,
            MTLResourceOptions::StorageModeShared,
        );

        let c_buffer = self.device.new_buffer(
            (m * n * std::mem::size_of::<f32>()) as u64,
            MTLResourceOptions::StorageModeShared,
        );

        // Create parameter buffers
        let m_u32 = m as u32;
        let n_u32 = n as u32;
        let k_u32 = k as u32;
        let m_buffer = self.device.new_buffer_with_data(
            &m_u32 as *const u32 as *const c_void,
            std::mem::size_of::<u32>() as u64,
            MTLResourceOptions::StorageModeShared,
        );
        let n_buffer = self.device.new_buffer_with_data(
            &n_u32 as *const u32 as *const c_void,
            std::mem::size_of::<u32>() as u64,
            MTLResourceOptions::StorageModeShared,
        );
        let k_buffer = self.device.new_buffer_with_data(
            &k_u32 as *const u32 as *const c_void,
            std::mem::size_of::<u32>() as u64,
            MTLResourceOptions::StorageModeShared,
        );

        // Get tiled pipeline state
        let pipeline_state = self
            .pipeline_states
            .get(&MetalKernelType::Convolution)
            .ok_or_else(|| {
                RusTorchError::KernelError("Tiled MatMul pipeline not found".to_string())
            })?;

        // Create command buffer and encoder
        let command_buffer = self.command_queue.new_command_buffer();
        let compute_encoder = command_buffer.new_compute_command_encoder();

        compute_encoder.set_compute_pipeline_state(pipeline_state);
        compute_encoder.set_buffer(0, Some(&a_buffer), 0);
        compute_encoder.set_buffer(1, Some(&b_buffer), 0);
        compute_encoder.set_buffer(2, Some(&c_buffer), 0);
        compute_encoder.set_buffer(3, Some(&m_buffer), 0);
        compute_encoder.set_buffer(4, Some(&n_buffer), 0);
        compute_encoder.set_buffer(5, Some(&k_buffer), 0);

        // Set threadgroup memory for tiles (2 tiles * TILE_SIZE * TILE_SIZE * sizeof(f32))
        let threadgroup_memory_size = 2 * TILE_SIZE * TILE_SIZE * std::mem::size_of::<f32>();
        compute_encoder.set_threadgroup_memory_length(0, threadgroup_memory_size as u64);
        compute_encoder.set_threadgroup_memory_length(1, threadgroup_memory_size as u64);

        // Calculate thread configuration for tiled execution
        let threads_per_threadgroup = MTLSize::new(TILE_SIZE as u64, TILE_SIZE as u64, 1);
        let threadgroups_per_grid = MTLSize::new(
            n.div_ceil(TILE_SIZE) as u64,
            m.div_ceil(TILE_SIZE) as u64,
            1,
        );

        compute_encoder.dispatch_thread_groups(threadgroups_per_grid, threads_per_threadgroup);
        compute_encoder.end_encoding();

        command_buffer.commit();
        command_buffer.wait_until_completed();

        // Copy result back to host
        unsafe {
            let result_ptr = c_buffer.contents() as *const f32;
            std::ptr::copy_nonoverlapping(result_ptr, c.as_mut_ptr(), m * n);
        }

        Ok(())
    }

    /// Execute standard matrix multiplication using Metal
    /// Metalを使用して標準行列乗算を実行
    pub fn matmul_f32(
        &self,
        a: &[f32],
        b: &[f32],
        c: &mut [f32],
        m: usize,
        n: usize,
        k: usize,
    ) -> RusTorchResult<()> {
        // Use tiled version for large matrices for better performance
        if m >= 256 || n >= 256 || k >= 256 {
            return self.tiled_matmul_f32(a, b, c, m, n, k);
        }
        // Create Metal buffers
        let a_buffer = self.device.new_buffer_with_data(
            a.as_ptr() as *const c_void,
            (m * k * std::mem::size_of::<f32>()) as u64,
            MTLResourceOptions::StorageModeShared,
        );

        let b_buffer = self.device.new_buffer_with_data(
            b.as_ptr() as *const c_void,
            (k * n * std::mem::size_of::<f32>()) as u64,
            MTLResourceOptions::StorageModeShared,
        );

        let c_buffer = self.device.new_buffer(
            (m * n * std::mem::size_of::<f32>()) as u64,
            MTLResourceOptions::StorageModeShared,
        );

        // Create parameter buffers
        let m_u32 = m as u32;
        let n_u32 = n as u32;
        let k_u32 = k as u32;
        let m_buffer = self.device.new_buffer_with_data(
            &m_u32 as *const u32 as *const c_void,
            std::mem::size_of::<u32>() as u64,
            MTLResourceOptions::StorageModeShared,
        );
        let n_buffer = self.device.new_buffer_with_data(
            &n_u32 as *const u32 as *const c_void,
            std::mem::size_of::<u32>() as u64,
            MTLResourceOptions::StorageModeShared,
        );
        let k_buffer = self.device.new_buffer_with_data(
            &k_u32 as *const u32 as *const c_void,
            std::mem::size_of::<u32>() as u64,
            MTLResourceOptions::StorageModeShared,
        );

        // Get pipeline state
        let pipeline_state = self
            .pipeline_states
            .get(&MetalKernelType::MatMul)
            .ok_or_else(|| RusTorchError::KernelError("MatMul pipeline not found".to_string()))?;

        // Create command buffer and encoder
        let command_buffer = self.command_queue.new_command_buffer();
        let compute_encoder = command_buffer.new_compute_command_encoder();

        compute_encoder.set_compute_pipeline_state(pipeline_state);
        compute_encoder.set_buffer(0, Some(&a_buffer), 0);
        compute_encoder.set_buffer(1, Some(&b_buffer), 0);
        compute_encoder.set_buffer(2, Some(&c_buffer), 0);
        compute_encoder.set_buffer(3, Some(&m_buffer), 0);
        compute_encoder.set_buffer(4, Some(&n_buffer), 0);
        compute_encoder.set_buffer(5, Some(&k_buffer), 0);

        // Calculate thread configuration
        let threads_per_threadgroup = MTLSize::new(16, 16, 1);
        let threadgroups_per_grid = MTLSize::new(((n + 15) / 16) as u64, ((m + 15) / 16) as u64, 1);

        compute_encoder.dispatch_thread_groups(threadgroups_per_grid, threads_per_threadgroup);
        compute_encoder.end_encoding();

        command_buffer.commit();
        command_buffer.wait_until_completed();

        // Copy result back to host
        unsafe {
            let result_ptr = c_buffer.contents() as *const f32;
            std::ptr::copy_nonoverlapping(result_ptr, c.as_mut_ptr(), m * n);
        }

        Ok(())
    }

    /// Perform matrix multiplication using Metal with result return
    /// Metalを使用して行列乗算を実行し結果を返す  
    pub fn matrix_multiply_f32(
        &self,
        a: &[f32],
        b: &[f32],
        m: usize,
        n: usize,
        k: usize,
    ) -> RusTorchResult<Vec<f32>> {
        if a.len() != m * k || b.len() != k * n {
            return Err(RusTorchError::InvalidOperation(
                "Matrix dimension mismatch".to_string(),
            ));
        }

        let mut result = vec![0.0f32; m * n];
        self.matmul_f32(a, b, &mut result, m, n, k)?;
        Ok(result)
    }

    /// Execute 2D convolution using Metal GPU
    /// Metal GPUを使用して2D畳み込みを実行
    pub fn conv2d_f32(
        &self,
        input: &[f32],
        kernel: &[f32],
        output: &mut [f32],
        input_height: usize,
        input_width: usize,
        input_channels: usize,
        output_channels: usize,
        kernel_height: usize,
        kernel_width: usize,
        stride_h: usize,
        stride_w: usize,
        pad_h: usize,
        pad_w: usize,
    ) -> RusTorchResult<()> {
        // Calculate output dimensions
        let output_height = (input_height + 2 * pad_h - kernel_height) / stride_h + 1;
        let output_width = (input_width + 2 * pad_w - kernel_width) / stride_w + 1;

        // For now, implement as optimized matrix multiplication (im2col + GEMM approach)
        // This is a common approach in high-performance convolution implementations

        // Convert convolution to matrix multiplication using im2col
        let patch_size = kernel_height * kernel_width * input_channels;
        let num_patches = output_height * output_width;

        // Create im2col matrix: [patch_size, num_patches]
        let mut im2col_matrix = vec![0.0f32; patch_size * num_patches];

        // Extract patches (im2col operation)
        for out_h in 0..output_height {
            for out_w in 0..output_width {
                let patch_idx = out_h * output_width + out_w;
                let start_h = out_h * stride_h;
                let start_w = out_w * stride_w;

                for kh in 0..kernel_height {
                    for kw in 0..kernel_width {
                        for ch in 0..input_channels {
                            let in_h = start_h + kh;
                            let in_w = start_w + kw;

                            let im2col_row =
                                ch * kernel_height * kernel_width + kh * kernel_width + kw;
                            let im2col_idx = im2col_row * num_patches + patch_idx;

                            if in_h >= pad_h
                                && in_h < input_height + pad_h
                                && in_w >= pad_w
                                && in_w < input_width + pad_w
                            {
                                let actual_in_h = in_h - pad_h;
                                let actual_in_w = in_w - pad_w;
                                let input_idx = ch * input_height * input_width
                                    + actual_in_h * input_width
                                    + actual_in_w;
                                im2col_matrix[im2col_idx] = input[input_idx];
                            } else {
                                im2col_matrix[im2col_idx] = 0.0; // Padding
                            }
                        }
                    }
                }
            }
        }

        // Use Metal matrix multiplication: kernel [output_channels, patch_size] * im2col [patch_size, num_patches]
        let mut result_matrix = vec![0.0f32; output_channels * num_patches];
        self.matmul_f32(
            kernel,
            &im2col_matrix,
            &mut result_matrix,
            output_channels,
            num_patches,
            patch_size,
        )?;

        // Copy result to output with proper layout
        for out_ch in 0..output_channels {
            for out_h in 0..output_height {
                for out_w in 0..output_width {
                    let result_idx = out_ch * num_patches + out_h * output_width + out_w;
                    let output_idx =
                        out_ch * output_height * output_width + out_h * output_width + out_w;
                    output[output_idx] = result_matrix[result_idx];
                }
            }
        }

        Ok(())
    }

    /// Execute reduction operation (sum) using Metal
    /// Metalを使用してリダクション演算(合計)を実行
    pub fn reduce_sum_f32(&self, input: &[f32]) -> RusTorchResult<f32> {
        let size = input.len();
        let block_size = 256;
        let grid_size = size.div_ceil(block_size);

        // Create Metal buffers
        let input_buffer = self.device.new_buffer_with_data(
            input.as_ptr() as *const c_void,
            (size * std::mem::size_of::<f32>()) as u64,
            MTLResourceOptions::StorageModeShared,
        );

        let output_buffer = self.device.new_buffer(
            (grid_size * std::mem::size_of::<f32>()) as u64,
            MTLResourceOptions::StorageModeShared,
        );

        // Get pipeline state
        let pipeline_state = self
            .pipeline_states
            .get(&MetalKernelType::Reduction)
            .ok_or_else(|| {
                RusTorchError::KernelError("Reduction pipeline not found".to_string())
            })?;

        // Create command buffer and encoder
        let command_buffer = self.command_queue.new_command_buffer();
        let compute_encoder = command_buffer.new_compute_command_encoder();

        compute_encoder.set_compute_pipeline_state(pipeline_state);
        compute_encoder.set_buffer(0, Some(&input_buffer), 0);
        compute_encoder.set_buffer(1, Some(&output_buffer), 0);

        // Set threadgroup memory
        compute_encoder
            .set_threadgroup_memory_length(0, (block_size * std::mem::size_of::<f32>()) as u64);

        // Calculate thread configuration
        let threads_per_threadgroup = MTLSize::new(block_size as u64, 1, 1);
        let threadgroups_per_grid = MTLSize::new(grid_size as u64, 1, 1);

        compute_encoder.dispatch_thread_groups(threadgroups_per_grid, threads_per_threadgroup);
        compute_encoder.end_encoding();

        command_buffer.commit();
        command_buffer.wait_until_completed();

        // Copy partial results back and sum on CPU
        let mut partial_results = vec![0.0f32; grid_size];
        unsafe {
            let result_ptr = output_buffer.contents() as *const f32;
            std::ptr::copy_nonoverlapping(result_ptr, partial_results.as_mut_ptr(), grid_size);
        }

        Ok(partial_results.iter().sum())
    }

    /// Execute ReLU activation using Metal GPU
    /// Metal GPUを使用してReLU活性化を実行
    pub fn relu_f32(&self, input: &[f32], output: &mut [f32]) -> RusTorchResult<()> {
        if input.len() != output.len() {
            return Err(RusTorchError::InvalidOperation(
                "Input and output lengths must match".to_string(),
            ));
        }

        let n = input.len();

        // Create buffers
        let input_buffer = self.device.new_buffer_with_data(
            input.as_ptr() as *const c_void,
            (n * std::mem::size_of::<f32>()) as u64,
            metal::MTLResourceOptions::StorageModeShared,
        );

        let output_buffer = self.device.new_buffer(
            (n * std::mem::size_of::<f32>()) as u64,
            metal::MTLResourceOptions::StorageModeShared,
        );

        // Get or create pipeline state for ReLU
        let function = self
            .library
            .get_function("relu_f32", None)
            .map_err(|e| RusTorchError::gpu(&format!("Failed to get ReLU function: {}", e)))?;

        let pipeline_state = self
            .device
            .new_compute_pipeline_state_with_function(&function)
            .map_err(|e| RusTorchError::gpu(&format!("Failed to create ReLU pipeline: {}", e)))?;

        // Create command buffer and encoder
        let command_buffer = self.command_queue.new_command_buffer();
        let encoder = command_buffer.new_compute_command_encoder();

        encoder.set_compute_pipeline_state(&pipeline_state);
        encoder.set_buffer(0, Some(&input_buffer), 0);
        encoder.set_buffer(1, Some(&output_buffer), 0);
        encoder.set_bytes(
            2,
            std::mem::size_of::<u32>() as u64,
            &(n as u32) as *const u32 as *const c_void,
        );

        // Dispatch threads
        let threads_per_threadgroup = metal::MTLSize::new(256, 1, 1);
        let threadgroups = metal::MTLSize::new(((n + 255) / 256).try_into().unwrap(), 1, 1);

        encoder.dispatch_thread_groups(threadgroups, threads_per_threadgroup);
        encoder.end_encoding();

        command_buffer.commit();
        command_buffer.wait_until_completed();

        // Copy result back to host
        unsafe {
            let result_ptr = output_buffer.contents() as *const f32;
            std::ptr::copy_nonoverlapping(result_ptr, output.as_mut_ptr(), n);
        }

        Ok(())
    }

    /// Execute Sigmoid activation using Metal GPU
    /// Metal GPUを使用してSigmoid活性化を実行
    pub fn sigmoid_f32(&self, input: &[f32], output: &mut [f32]) -> RusTorchResult<()> {
        if input.len() != output.len() {
            return Err(RusTorchError::InvalidOperation(
                "Input and output lengths must match".to_string(),
            ));
        }

        let n = input.len();

        // Create buffers
        let input_buffer = self.device.new_buffer_with_data(
            input.as_ptr() as *const c_void,
            (n * std::mem::size_of::<f32>()) as u64,
            metal::MTLResourceOptions::StorageModeShared,
        );

        let output_buffer = self.device.new_buffer(
            (n * std::mem::size_of::<f32>()) as u64,
            metal::MTLResourceOptions::StorageModeShared,
        );

        // Get or create pipeline state for Sigmoid
        let function = self
            .library
            .get_function("sigmoid_f32", None)
            .map_err(|e| RusTorchError::gpu(&format!("Failed to get Sigmoid function: {}", e)))?;

        let pipeline_state = self
            .device
            .new_compute_pipeline_state_with_function(&function)
            .map_err(|e| {
                RusTorchError::gpu(&format!("Failed to create Sigmoid pipeline: {}", e))
            })?;

        // Create command buffer and encoder
        let command_buffer = self.command_queue.new_command_buffer();
        let encoder = command_buffer.new_compute_command_encoder();

        encoder.set_compute_pipeline_state(&pipeline_state);
        encoder.set_buffer(0, Some(&input_buffer), 0);
        encoder.set_buffer(1, Some(&output_buffer), 0);
        encoder.set_bytes(
            2,
            std::mem::size_of::<u32>() as u64,
            &(n as u32) as *const u32 as *const c_void,
        );

        // Dispatch threads
        let threads_per_threadgroup = metal::MTLSize::new(256, 1, 1);
        let threadgroups = metal::MTLSize::new(((n + 255) / 256).try_into().unwrap(), 1, 1);

        encoder.dispatch_thread_groups(threadgroups, threads_per_threadgroup);
        encoder.end_encoding();

        command_buffer.commit();
        command_buffer.wait_until_completed();

        // Copy result back to host
        unsafe {
            let result_ptr = output_buffer.contents() as *const f32;
            std::ptr::copy_nonoverlapping(result_ptr, output.as_mut_ptr(), n);
        }

        Ok(())
    }

    /// Execute Tanh activation using Metal GPU
    /// Metal GPUを使用してTanh活性化を実行
    pub fn tanh_f32(&self, input: &[f32], output: &mut [f32]) -> RusTorchResult<()> {
        if input.len() != output.len() {
            return Err(RusTorchError::InvalidOperation(
                "Input and output lengths must match".to_string(),
            ));
        }

        let n = input.len();

        // Create buffers
        let input_buffer = self.device.new_buffer_with_data(
            input.as_ptr() as *const c_void,
            (n * std::mem::size_of::<f32>()) as u64,
            metal::MTLResourceOptions::StorageModeShared,
        );

        let output_buffer = self.device.new_buffer(
            (n * std::mem::size_of::<f32>()) as u64,
            metal::MTLResourceOptions::StorageModeShared,
        );

        // Get or create pipeline state for Tanh
        let function = self
            .library
            .get_function("tanh_f32", None)
            .map_err(|e| RusTorchError::gpu(&format!("Failed to get Tanh function: {}", e)))?;

        let pipeline_state = self
            .device
            .new_compute_pipeline_state_with_function(&function)
            .map_err(|e| RusTorchError::gpu(&format!("Failed to create Tanh pipeline: {}", e)))?;

        // Create command buffer and encoder
        let command_buffer = self.command_queue.new_command_buffer();
        let encoder = command_buffer.new_compute_command_encoder();

        encoder.set_compute_pipeline_state(&pipeline_state);
        encoder.set_buffer(0, Some(&input_buffer), 0);
        encoder.set_buffer(1, Some(&output_buffer), 0);
        encoder.set_bytes(
            2,
            std::mem::size_of::<u32>() as u64,
            &(n as u32) as *const u32 as *const c_void,
        );

        // Dispatch threads
        let threads_per_threadgroup = metal::MTLSize::new(256, 1, 1);
        let threadgroups = metal::MTLSize::new(((n + 255) / 256).try_into().unwrap(), 1, 1);

        encoder.dispatch_thread_groups(threadgroups, threads_per_threadgroup);
        encoder.end_encoding();

        command_buffer.commit();
        command_buffer.wait_until_completed();

        // Copy result back to host
        unsafe {
            let result_ptr = output_buffer.contents() as *const f32;
            std::ptr::copy_nonoverlapping(result_ptr, output.as_mut_ptr(), n);
        }

        Ok(())
    }

    /// Execute GELU activation using Metal GPU
    /// Metal GPUを使用してGELU活性化を実行
    pub fn gelu_f32(&self, input: &[f32], output: &mut [f32]) -> RusTorchResult<()> {
        if input.len() != output.len() {
            return Err(RusTorchError::InvalidOperation(
                "Input and output lengths must match".to_string(),
            ));
        }

        let n = input.len();

        // Create buffers
        let input_buffer = self.device.new_buffer_with_data(
            input.as_ptr() as *const c_void,
            (n * std::mem::size_of::<f32>()) as u64,
            metal::MTLResourceOptions::StorageModeShared,
        );

        let output_buffer = self.device.new_buffer(
            (n * std::mem::size_of::<f32>()) as u64,
            metal::MTLResourceOptions::StorageModeShared,
        );

        // Get or create pipeline state for GELU
        let function = self
            .library
            .get_function("gelu_f32", None)
            .map_err(|e| RusTorchError::gpu(&format!("Failed to get GELU function: {}", e)))?;

        let pipeline_state = self
            .device
            .new_compute_pipeline_state_with_function(&function)
            .map_err(|e| RusTorchError::gpu(&format!("Failed to create GELU pipeline: {}", e)))?;

        // Create command buffer and encoder
        let command_buffer = self.command_queue.new_command_buffer();
        let encoder = command_buffer.new_compute_command_encoder();

        encoder.set_compute_pipeline_state(&pipeline_state);
        encoder.set_buffer(0, Some(&input_buffer), 0);
        encoder.set_buffer(1, Some(&output_buffer), 0);
        encoder.set_bytes(
            2,
            std::mem::size_of::<u32>() as u64,
            &(n as u32) as *const u32 as *const c_void,
        );

        // Dispatch threads
        let threads_per_threadgroup = metal::MTLSize::new(256, 1, 1);
        let threadgroups = metal::MTLSize::new(((n + 255) / 256).try_into().unwrap(), 1, 1);

        encoder.dispatch_thread_groups(threadgroups, threads_per_threadgroup);
        encoder.end_encoding();

        command_buffer.commit();
        command_buffer.wait_until_completed();

        // Copy result back to host
        unsafe {
            let result_ptr = output_buffer.contents() as *const f32;
            std::ptr::copy_nonoverlapping(result_ptr, output.as_mut_ptr(), n);
        }

        Ok(())
    }

    /// Execute Leaky ReLU activation using Metal GPU
    /// Metal GPUを使用してLeaky ReLU活性化を実行
    pub fn leaky_relu_f32(
        &self,
        input: &[f32],
        output: &mut [f32],
        alpha: f32,
    ) -> RusTorchResult<()> {
        if input.len() != output.len() {
            return Err(RusTorchError::InvalidOperation(
                "Input and output lengths must match".to_string(),
            ));
        }

        let n = input.len();

        // Create buffers
        let input_buffer = self.device.new_buffer_with_data(
            input.as_ptr() as *const c_void,
            (n * std::mem::size_of::<f32>()) as u64,
            metal::MTLResourceOptions::StorageModeShared,
        );

        let output_buffer = self.device.new_buffer(
            (n * std::mem::size_of::<f32>()) as u64,
            metal::MTLResourceOptions::StorageModeShared,
        );

        // Get or create pipeline state for Leaky ReLU
        let function = self
            .library
            .get_function("leaky_relu_f32", None)
            .map_err(|e| {
                RusTorchError::gpu(&format!("Failed to get Leaky ReLU function: {}", e))
            })?;

        let pipeline_state = self
            .device
            .new_compute_pipeline_state_with_function(&function)
            .map_err(|e| {
                RusTorchError::gpu(&format!("Failed to create Leaky ReLU pipeline: {}", e))
            })?;

        // Create command buffer and encoder
        let command_buffer = self.command_queue.new_command_buffer();
        let encoder = command_buffer.new_compute_command_encoder();

        encoder.set_compute_pipeline_state(&pipeline_state);
        encoder.set_buffer(0, Some(&input_buffer), 0);
        encoder.set_buffer(1, Some(&output_buffer), 0);
        encoder.set_bytes(
            2,
            std::mem::size_of::<u32>() as u64,
            &(n as u32) as *const u32 as *const c_void,
        );
        encoder.set_bytes(
            3,
            std::mem::size_of::<f32>() as u64,
            &alpha as *const f32 as *const c_void,
        );

        // Dispatch threads
        let threads_per_threadgroup = metal::MTLSize::new(256, 1, 1);
        let threadgroups = metal::MTLSize::new(((n + 255) / 256).try_into().unwrap(), 1, 1);

        encoder.dispatch_thread_groups(threadgroups, threads_per_threadgroup);
        encoder.end_encoding();

        command_buffer.commit();
        command_buffer.wait_until_completed();

        // Copy result back to host
        unsafe {
            let result_ptr = output_buffer.contents() as *const f32;
            std::ptr::copy_nonoverlapping(result_ptr, output.as_mut_ptr(), n);
        }

        Ok(())
    }

    /// Execute ELU activation using Metal GPU
    /// Metal GPUを使用してELU活性化を実行
    pub fn elu_f32(&self, input: &[f32], output: &mut [f32], alpha: f32) -> RusTorchResult<()> {
        if input.len() != output.len() {
            return Err(RusTorchError::InvalidOperation(
                "Input and output lengths must match".to_string(),
            ));
        }

        let n = input.len();

        // Create buffers
        let input_buffer = self.device.new_buffer_with_data(
            input.as_ptr() as *const c_void,
            (n * std::mem::size_of::<f32>()) as u64,
            metal::MTLResourceOptions::StorageModeShared,
        );

        let output_buffer = self.device.new_buffer(
            (n * std::mem::size_of::<f32>()) as u64,
            metal::MTLResourceOptions::StorageModeShared,
        );

        // Get or create pipeline state for ELU
        let function = self
            .library
            .get_function("elu_f32", None)
            .map_err(|e| RusTorchError::gpu(&format!("Failed to get ELU function: {}", e)))?;

        let pipeline_state = self
            .device
            .new_compute_pipeline_state_with_function(&function)
            .map_err(|e| RusTorchError::gpu(&format!("Failed to create ELU pipeline: {}", e)))?;

        // Create command buffer and encoder
        let command_buffer = self.command_queue.new_command_buffer();
        let encoder = command_buffer.new_compute_command_encoder();

        encoder.set_compute_pipeline_state(&pipeline_state);
        encoder.set_buffer(0, Some(&input_buffer), 0);
        encoder.set_buffer(1, Some(&output_buffer), 0);
        encoder.set_bytes(
            2,
            std::mem::size_of::<u32>() as u64,
            &(n as u32) as *const u32 as *const c_void,
        );
        encoder.set_bytes(
            3,
            std::mem::size_of::<f32>() as u64,
            &alpha as *const f32 as *const c_void,
        );

        // Dispatch threads
        let threads_per_threadgroup = metal::MTLSize::new(256, 1, 1);
        let threadgroups = metal::MTLSize::new(((n + 255) / 256).try_into().unwrap(), 1, 1);

        encoder.dispatch_thread_groups(threadgroups, threads_per_threadgroup);
        encoder.end_encoding();

        command_buffer.commit();
        command_buffer.wait_until_completed();

        // Copy result back to host
        unsafe {
            let result_ptr = output_buffer.contents() as *const f32;
            std::ptr::copy_nonoverlapping(result_ptr, output.as_mut_ptr(), n);
        }

        Ok(())
    }

    /// Execute Swish activation using Metal GPU
    /// Metal GPUを使用してSwish活性化を実行
    pub fn swish_f32(&self, input: &[f32], output: &mut [f32]) -> RusTorchResult<()> {
        if input.len() != output.len() {
            return Err(RusTorchError::InvalidOperation(
                "Input and output lengths must match".to_string(),
            ));
        }

        let n = input.len();

        // Create buffers
        let input_buffer = self.device.new_buffer_with_data(
            input.as_ptr() as *const c_void,
            (n * std::mem::size_of::<f32>()) as u64,
            metal::MTLResourceOptions::StorageModeShared,
        );

        let output_buffer = self.device.new_buffer(
            (n * std::mem::size_of::<f32>()) as u64,
            metal::MTLResourceOptions::StorageModeShared,
        );

        // Get or create pipeline state for Swish
        let function = self
            .library
            .get_function("swish_f32", None)
            .map_err(|e| RusTorchError::gpu(&format!("Failed to get Swish function: {}", e)))?;

        let pipeline_state = self
            .device
            .new_compute_pipeline_state_with_function(&function)
            .map_err(|e| RusTorchError::gpu(&format!("Failed to create Swish pipeline: {}", e)))?;

        // Create command buffer and encoder
        let command_buffer = self.command_queue.new_command_buffer();
        let encoder = command_buffer.new_compute_command_encoder();

        encoder.set_compute_pipeline_state(&pipeline_state);
        encoder.set_buffer(0, Some(&input_buffer), 0);
        encoder.set_buffer(1, Some(&output_buffer), 0);
        encoder.set_bytes(
            2,
            std::mem::size_of::<u32>() as u64,
            &(n as u32) as *const u32 as *const c_void,
        );

        // Dispatch threads
        let threads_per_threadgroup = metal::MTLSize::new(256, 1, 1);
        let threadgroups = metal::MTLSize::new(((n + 255) / 256).try_into().unwrap(), 1, 1);

        encoder.dispatch_thread_groups(threadgroups, threads_per_threadgroup);
        encoder.end_encoding();

        command_buffer.commit();
        command_buffer.wait_until_completed();

        // Copy result back to host
        unsafe {
            let result_ptr = output_buffer.contents() as *const f32;
            std::ptr::copy_nonoverlapping(result_ptr, output.as_mut_ptr(), n);
        }

        Ok(())
    }
}

/// Non-Metal fallback executor for compatibility
/// 互換性のための非Metalフォールバック実行器
#[cfg(not(feature = "metal"))]
pub struct MetalKernelExecutor;

#[cfg(not(feature = "metal"))]
impl MetalKernelExecutor {
    /// Create a new Metal kernel executor (fallback implementation)
    /// 新しいMetalカーネル実行器を作成(フォールバック実装)
    pub fn new() -> RusTorchResult<Self> {
        Err(RusTorchError::UnsupportedDevice(
            "Metal not available".to_string(),
        ))
    }

    /// Perform element-wise addition using Metal
    /// Metalを使用して要素ごとの加算を実行
    pub fn elementwise_add_f32(
        &self,
        _a: &[f32],
        _b: &[f32],
        _c: &mut [f32],
    ) -> RusTorchResult<()> {
        Err(RusTorchError::UnsupportedDevice(
            "Metal not available".to_string(),
        ))
    }

    /// Perform matrix multiplication using Metal
    /// Metalを使用して行列乗算を実行
    pub fn matmul_f32(
        &self,
        _a: &[f32],
        _b: &[f32],
        _c: &mut [f32],
        _m: usize,
        _n: usize,
        _k: usize,
    ) -> RusTorchResult<()> {
        Err(RusTorchError::UnsupportedDevice(
            "Metal not available".to_string(),
        ))
    }

    /// Perform reduction sum using Metal
    /// Metalを使用してリダクション合計を実行
    pub fn reduce_sum_f32(&self, _input: &[f32]) -> RusTorchResult<f32> {
        Err(RusTorchError::UnsupportedDevice(
            "Metal not available".to_string(),
        ))
    }
}

/// Public interface functions for Metal operations
/// Metal演算のためのパブリックインターフェース関数
///
/// Execute Metal matrix multiplication
/// Metal行列乗算を実行
pub fn metal_matmul_f32(
    _a: &[f32],
    _b: &[f32],
    _c: &mut [f32],
    _m: usize,
    _n: usize,
    _k: usize,
) -> RusTorchResult<()> {
    #[cfg(feature = "metal")]
    {
        let executor = MetalKernelExecutor::new()?;
        executor.matmul_f32(_a, _b, _c, _m, _n, _k)
    }
    #[cfg(not(feature = "metal"))]
    {
        Err(RusTorchError::UnsupportedDevice(
            "Metal not available".to_string(),
        ))
    }
}

/// Execute Metal element-wise addition
/// Metal要素ごと加算を実行
pub fn metal_elementwise_add_f32(_a: &[f32], _b: &[f32], _c: &mut [f32]) -> RusTorchResult<()> {
    #[cfg(feature = "metal")]
    {
        let executor = MetalKernelExecutor::new()?;
        executor.elementwise_add_f32(_a, _b, _c)
    }
    #[cfg(not(feature = "metal"))]
    {
        Err(RusTorchError::UnsupportedDevice(
            "Metal not available".to_string(),
        ))
    }
}

/// Execute Metal reduction sum
/// Metalリダクション合計を実行
pub fn metal_reduce_sum_f32(_input: &[f32]) -> RusTorchResult<f32> {
    #[cfg(feature = "metal")]
    {
        let executor = MetalKernelExecutor::new()?;
        executor.reduce_sum_f32(_input)
    }
    #[cfg(not(feature = "metal"))]
    {
        Err(RusTorchError::UnsupportedDevice(
            "Metal not available".to_string(),
        ))
    }
}

/// Execute Metal 2D convolution
/// Metal 2D畳み込みを実行
pub fn metal_conv2d_f32(
    input: &[f32],
    kernel: &[f32],
    output: &mut [f32],
    input_height: usize,
    input_width: usize,
    input_channels: usize,
    output_channels: usize,
    kernel_height: usize,
    kernel_width: usize,
    stride_h: usize,
    stride_w: usize,
    pad_h: usize,
    pad_w: usize,
) -> RusTorchResult<()> {
    #[cfg(feature = "metal")]
    {
        let executor = MetalKernelExecutor::new()?;
        executor.conv2d_f32(
            input,
            kernel,
            output,
            input_height,
            input_width,
            input_channels,
            output_channels,
            kernel_height,
            kernel_width,
            stride_h,
            stride_w,
            pad_h,
            pad_w,
        )
    }
    #[cfg(not(feature = "metal"))]
    {
        Err(RusTorchError::UnsupportedDevice(
            "Metal not available".to_string(),
        ))
    }
}

/// Execute ReLU activation using Metal GPU
/// Metal GPUを使用してReLU活性化を実行
#[cfg(feature = "metal")]
pub fn metal_relu_f32(input: &[f32], output: &mut [f32]) -> RusTorchResult<()> {
    let executor = MetalKernelExecutor::new()?;
    executor.relu_f32(input, output)
}

#[cfg(not(feature = "metal"))]
pub fn metal_relu_f32(_input: &[f32], _output: &mut [f32]) -> RusTorchResult<()> {
    Err(RusTorchError::UnsupportedDevice(
        "Metal not available".to_string(),
    ))
}

/// Execute Sigmoid activation using Metal GPU
/// Metal GPUを使用してSigmoid活性化を実行
#[cfg(feature = "metal")]
pub fn metal_sigmoid_f32(input: &[f32], output: &mut [f32]) -> RusTorchResult<()> {
    let executor = MetalKernelExecutor::new()?;
    executor.sigmoid_f32(input, output)
}

#[cfg(not(feature = "metal"))]
pub fn metal_sigmoid_f32(_input: &[f32], _output: &mut [f32]) -> RusTorchResult<()> {
    Err(RusTorchError::UnsupportedDevice(
        "Metal not available".to_string(),
    ))
}

/// Execute Tanh activation using Metal GPU
/// Metal GPUを使用してTanh活性化を実行
#[cfg(feature = "metal")]
pub fn metal_tanh_f32(input: &[f32], output: &mut [f32]) -> RusTorchResult<()> {
    let executor = MetalKernelExecutor::new()?;
    executor.tanh_f32(input, output)
}

#[cfg(not(feature = "metal"))]
pub fn metal_tanh_f32(_input: &[f32], _output: &mut [f32]) -> RusTorchResult<()> {
    Err(RusTorchError::UnsupportedDevice(
        "Metal not available".to_string(),
    ))
}

/// Execute GELU activation using Metal GPU
/// Metal GPUを使用してGELU活性化を実行
#[cfg(feature = "metal")]
pub fn metal_gelu_f32(input: &[f32], output: &mut [f32]) -> RusTorchResult<()> {
    let executor = MetalKernelExecutor::new()?;
    executor.gelu_f32(input, output)
}

#[cfg(not(feature = "metal"))]
pub fn metal_gelu_f32(_input: &[f32], _output: &mut [f32]) -> RusTorchResult<()> {
    Err(RusTorchError::UnsupportedDevice(
        "Metal not available".to_string(),
    ))
}

/// Execute Leaky ReLU activation using Metal GPU
/// Metal GPUを使用してLeaky ReLU活性化を実行
#[cfg(feature = "metal")]
pub fn metal_leaky_relu_f32(input: &[f32], output: &mut [f32], alpha: f32) -> RusTorchResult<()> {
    let executor = MetalKernelExecutor::new()?;
    executor.leaky_relu_f32(input, output, alpha)
}

#[cfg(not(feature = "metal"))]
pub fn metal_leaky_relu_f32(
    _input: &[f32],
    _output: &mut [f32],
    _alpha: f32,
) -> RusTorchResult<()> {
    Err(RusTorchError::UnsupportedDevice(
        "Metal not available".to_string(),
    ))
}

/// Execute ELU activation using Metal GPU
/// Metal GPUを使用してELU活性化を実行
#[cfg(feature = "metal")]
pub fn metal_elu_f32(input: &[f32], output: &mut [f32], alpha: f32) -> RusTorchResult<()> {
    let executor = MetalKernelExecutor::new()?;
    executor.elu_f32(input, output, alpha)
}

#[cfg(not(feature = "metal"))]
pub fn metal_elu_f32(_input: &[f32], _output: &mut [f32], _alpha: f32) -> RusTorchResult<()> {
    Err(RusTorchError::UnsupportedDevice(
        "Metal not available".to_string(),
    ))
}

/// Execute Swish activation using Metal GPU
/// Metal GPUを使用してSwish活性化を実行
#[cfg(feature = "metal")]
pub fn metal_swish_f32(input: &[f32], output: &mut [f32]) -> RusTorchResult<()> {
    let executor = MetalKernelExecutor::new()?;
    executor.swish_f32(input, output)
}

#[cfg(not(feature = "metal"))]
pub fn metal_swish_f32(_input: &[f32], _output: &mut [f32]) -> RusTorchResult<()> {
    Err(RusTorchError::UnsupportedDevice(
        "Metal not available".to_string(),
    ))
}

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

    #[test]
    fn test_metal_kernel_params() {
        let params = MetalKernelParams::default();
        assert_eq!(params.threads_per_threadgroup, (1, 1, 1));
        assert_eq!(params.threadgroups_per_grid, (1, 1, 1));
    }

    #[test]
    fn test_metal_executor_creation() {
        let result = MetalKernelExecutor::new();
        #[cfg(not(feature = "metal"))]
        assert!(result.is_err());
    }

    #[test]
    fn test_metal_kernel_types() {
        assert_eq!(MetalKernelType::ElementWise, MetalKernelType::ElementWise);
        assert_ne!(MetalKernelType::ElementWise, MetalKernelType::MatMul);
    }
}