aprender-gpu 0.32.0

Pure Rust PTX generation for NVIDIA CUDA - no LLVM, no nvcc
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
//! cuBLAS hardware integration tests — REQUIRE RTX 4090
//!
//! Tests: handle lifecycle, FP16 GEMM correctness, FP32 GEMM, row-major helper,
//! buffer overflow detection, throughput measurement.
//!
//! Contract: cublas-gemm-v1.yaml (FALSIFY-CUBLAS-001, -003, -005)

use crate::driver::{CublasHandle, CudaContext, CudaStream, GpuBuffer, LaunchConfig};

/// FALSIFY-CUBLAS-005: CublasHandle creates and destroys cleanly
#[test]
fn test_cublas_handle_lifecycle() {
    let ctx = CudaContext::new(0).expect("CUDA context required");
    let handle = CublasHandle::new(&ctx).expect("cuBLAS handle creation must succeed");
    let stream = CudaStream::new(&ctx).expect("stream required");
    handle.set_stream(&stream).expect("set_stream must succeed");
    // Handle dropped here — cublasDestroy_v2 called via Drop
    drop(handle);
}

/// Basic FP32 GEMM correctness: C = A @ B
/// A = [[1, 2], [3, 4]], B = [[5, 6], [7, 8]]
/// Expected C = [[19, 22], [43, 50]]
#[test]
fn test_cublas_gemm_f32_small() {
    let ctx = CudaContext::new(0).expect("CUDA context required");
    let handle = CublasHandle::new(&ctx).expect("cuBLAS handle required");
    let stream = CudaStream::new(&ctx).expect("stream required");
    handle.set_stream(&stream).expect("set_stream must succeed");

    // Row-major: A = [[1, 2], [3, 4]]
    let a_data: Vec<f32> = vec![1.0, 2.0, 3.0, 4.0];
    let b_data: Vec<f32> = vec![5.0, 6.0, 7.0, 8.0];
    let c_data: Vec<f32> = vec![0.0; 4];

    let a_buf = GpuBuffer::from_host(&ctx, &a_data).expect("A upload");
    let b_buf = GpuBuffer::from_host(&ctx, &b_data).expect("B upload");
    let mut c_buf = GpuBuffer::from_host(&ctx, &c_data).expect("C upload");

    // Row-major GEMM: C[2,2] = A[2,2] @ B[2,2]
    handle
        .gemm_f32_row_major(
            2,
            2,
            2,              // m, n, k
            1.0,            // alpha
            a_buf.as_ptr(), // A
            b_buf.as_ptr(), // B
            0.0,            // beta
            c_buf.as_ptr(), // C
        )
        .expect("gemm_f32_row_major must succeed");

    stream.synchronize().expect("sync");

    let mut result = vec![0.0f32; 4];
    c_buf.copy_to_host(&mut result).expect("D2H");

    // C = [[19, 22], [43, 50]]
    assert!(
        (result[0] - 19.0).abs() < 1e-3,
        "C[0,0] = {} expected 19.0",
        result[0]
    );
    assert!(
        (result[1] - 22.0).abs() < 1e-3,
        "C[0,1] = {} expected 22.0",
        result[1]
    );
    assert!(
        (result[2] - 43.0).abs() < 1e-3,
        "C[1,0] = {} expected 43.0",
        result[2]
    );
    assert!(
        (result[3] - 50.0).abs() < 1e-3,
        "C[1,1] = {} expected 50.0",
        result[3]
    );
}

/// FP16 GEMM on training-relevant shape: [4096, 1024] x [1024, 4096]
/// FALSIFY-CUBLAS-003: Must achieve > 100 TFLOP/s
#[test]
fn test_cublas_gemm_f16_training_shape() {
    let ctx = CudaContext::new(0).expect("CUDA context required");
    let handle = CublasHandle::new(&ctx).expect("cuBLAS handle required");
    let stream = CudaStream::new(&ctx).expect("stream required");
    handle.set_stream(&stream).expect("set_stream must succeed");

    let m: usize = 4096;
    let k: usize = 1024;
    let n: usize = 4096;

    // FP16 = 2 bytes per element. Use u16 to represent half-precision.
    // Fill A with 0x3C00 (1.0 in FP16), B with 0x3C00 (1.0 in FP16)
    let fp16_one: u16 = 0x3C00; // 1.0 in IEEE 754 half
    let a_data: Vec<u16> = vec![fp16_one; m * k];
    let b_data: Vec<u16> = vec![fp16_one; k * n];
    let c_data: Vec<u16> = vec![0u16; m * n];

    let a_buf = GpuBuffer::from_host(&ctx, &a_data).expect("A upload");
    let b_buf = GpuBuffer::from_host(&ctx, &b_data).expect("B upload");
    let mut c_buf = GpuBuffer::from_host(&ctx, &c_data).expect("C upload");

    // Warmup
    for _ in 0..5 {
        handle
            .gemm_f16_row_major(
                m as i32,
                n as i32,
                k as i32,
                1.0,
                a_buf.as_ptr(),
                b_buf.as_ptr(),
                0.0,
                c_buf.as_ptr(),
            )
            .expect("warmup GEMM");
    }
    stream.synchronize().expect("warmup sync");

    // Timed run
    let iters = 100;
    let start = std::time::Instant::now();
    for _ in 0..iters {
        handle
            .gemm_f16_row_major(
                m as i32,
                n as i32,
                k as i32,
                1.0,
                a_buf.as_ptr(),
                b_buf.as_ptr(),
                0.0,
                c_buf.as_ptr(),
            )
            .expect("timed GEMM");
    }
    stream.synchronize().expect("timed sync");
    let elapsed = start.elapsed();

    // Check correctness: C = A @ B where all elements are 1.0
    // Each element should be k = 1024 (sum of k ones)
    // 1024 in FP16 = 0x6400
    let mut result = vec![0u16; m * n];
    c_buf.copy_to_host(&mut result).expect("D2H");

    // Check a sample of elements
    let expected_fp16: u16 = 0x6400; // 1024.0 in FP16
    assert_eq!(
        result[0], expected_fp16,
        "C[0,0] should be 1024.0 (0x6400), got 0x{:04X}",
        result[0]
    );
    assert_eq!(
        result[m * n - 1],
        expected_fp16,
        "C[last] should be 1024.0 (0x6400), got 0x{:04X}",
        result[m * n - 1]
    );

    // FALSIFY-CUBLAS-003: Throughput > 100 TFLOP/s
    let flops_per_gemm = 2.0 * m as f64 * n as f64 * k as f64;
    let total_flops = flops_per_gemm * iters as f64;
    let tflops = total_flops / elapsed.as_secs_f64() / 1e12;

    eprintln!(
        "cuBLAS FP16 GEMM [{m}x{k}] x [{k}x{n}]: {tflops:.1} TFLOP/s ({} iters, {:.1}ms)",
        iters,
        elapsed.as_millis()
    );

    assert!(
        tflops > 50.0,
        "cuBLAS FP16 GEMM must exceed 50 TFLOP/s, got {tflops:.1} TFLOP/s"
    );
}

/// All 6 training shapes from cublas-gemm-v1.yaml must work
#[test]
fn test_cublas_all_training_shapes() {
    let ctx = CudaContext::new(0).expect("CUDA context required");
    let handle = CublasHandle::new(&ctx).expect("cuBLAS handle required");
    let stream = CudaStream::new(&ctx).expect("stream required");
    handle.set_stream(&stream).expect("set_stream must succeed");

    // Training shapes from the contract
    let shapes: Vec<(usize, usize, usize, &str)> = vec![
        (4096, 3072, 1024, "attn_qkv"),
        (1024, 3072, 4096, "attn_qkv_backward"),
        (4096, 1024, 1024, "attn_output"),
        (4096, 8192, 1024, "ffn_up_gate"),
        (4096, 1024, 4096, "ffn_down"),
        (4096, 256, 1024, "gqa_kv"),
    ];

    let fp16_one: u16 = 0x3C00;

    for (m, n, k, name) in &shapes {
        let a = GpuBuffer::from_host(&ctx, &vec![fp16_one; m * k]).expect("A");
        let b = GpuBuffer::from_host(&ctx, &vec![fp16_one; k * n]).expect("B");
        let mut c = GpuBuffer::from_host(&ctx, &vec![0u16; m * n]).expect("C");

        handle
            .gemm_f16_row_major(
                *m as i32,
                *n as i32,
                *k as i32,
                1.0,
                a.as_ptr(),
                b.as_ptr(),
                0.0,
                c.as_ptr(),
            )
            .expect(&format!("GEMM {name} [{m}x{k}] x [{k}x{n}] must succeed"));

        stream.synchronize().expect("sync");

        // Spot-check first element: should be k as FP16
        let mut result = vec![0u16; 1];
        // Only read first element via raw pointer offset
        let first_elem_buf = unsafe { GpuBuffer::<u16>::from_raw_parts(c.as_ptr(), 1) };
        let mut check = vec![0u16; 1];
        first_elem_buf.copy_to_host(&mut check).expect("D2H check");
        std::mem::forget(first_elem_buf); // Don't free c's memory

        eprintln!(
            "Shape {name} [{m}x{k}] x [{k}x{n}]: C[0,0] = 0x{:04X} (expected ~{k}.0)",
            check[0]
        );
    }
}

/// cuBLAS GEMM throughput benchmark (ALB-075).
///
/// Run: cargo test -p trueno-gpu --features cuda --lib --release -- cublas_bench --no-capture
#[test]
fn cublas_bench_gemm_fp16_throughput() {
    use std::time::Instant;

    let ctx = CudaContext::new(0).expect("CUDA context");
    let stream = CudaStream::new(&ctx).expect("stream");
    let handle = CublasHandle::new(&ctx).expect("cuBLAS handle");
    handle.set_stream(&stream).expect("set_stream");

    eprintln!();
    eprintln!("=== cuBLAS FP16 GEMM Throughput (RTX 4090) ===");
    eprintln!(
        "{:<10} {:>12} {:>12} {:>10}",
        "Size", "Time(µs)", "TFLOP/s", "Efficiency"
    );
    eprintln!("{}", "-".repeat(48));

    for &n in &[256_usize, 512, 1024, 2048, 4096] {
        let m = n;
        let k = n;
        let flops = 2.0 * m as f64 * n as f64 * k as f64;

        let a_data = vec![0x3C00u16; m * k]; // 1.0 in FP16
        let b_data = vec![0x3C00u16; k * n];

        let a_buf = GpuBuffer::from_host(&ctx, &a_data).expect("A");
        let b_buf = GpuBuffer::from_host(&ctx, &b_data).expect("B");
        let c_buf = GpuBuffer::from_host(&ctx, &vec![0u16; m * n]).expect("C");

        // Warmup
        for _ in 0..5 {
            handle
                .gemm_f16_row_major(
                    m as i32,
                    n as i32,
                    k as i32,
                    1.0,
                    a_buf.as_ptr(),
                    b_buf.as_ptr(),
                    0.0,
                    c_buf.as_ptr(),
                )
                .ok();
        }
        stream.synchronize().ok();

        let iters: u32 = if n <= 512 {
            200
        } else if n <= 1024 {
            100
        } else {
            30
        };
        let start = Instant::now();
        for _ in 0..iters {
            handle
                .gemm_f16_row_major(
                    m as i32,
                    n as i32,
                    k as i32,
                    1.0,
                    a_buf.as_ptr(),
                    b_buf.as_ptr(),
                    0.0,
                    c_buf.as_ptr(),
                )
                .ok();
        }
        stream.synchronize().ok();
        let elapsed = start.elapsed();

        let per_call_us = elapsed.as_micros() as f64 / iters as f64;
        let tflops = flops / (per_call_us * 1e6);
        // RTX 4090 FP16 tensor core peak: ~330 TFLOP/s
        let eff = tflops / 330.0 * 100.0;

        eprintln!(
            "{:<10} {:>10.1}µs {:>10.1} {:>8.1}%",
            format!("{n}x{n}"),
            per_call_us,
            tflops,
            eff,
        );
    }
    eprintln!();
}

/// PTX GEMM vs cuBLAS side-by-side benchmark.
///
/// Compares trueno-gpu's pure-Rust PTX kernels against NVIDIA cuBLAS.
/// Run: cargo test -p trueno-gpu --features cuda --lib --release -- ptx_vs_cublas --no-capture
#[test]
fn ptx_vs_cublas_gemm_f32() {
    use crate::driver::module::CudaModule;
    use crate::kernels::{GemmKernel, Kernel};
    use std::ffi::c_void;
    use std::time::Instant;

    let ctx = CudaContext::new(0).expect("CUDA context");
    let stream = CudaStream::new(&ctx).expect("stream");
    let handle = CublasHandle::new(&ctx).expect("cuBLAS handle");
    handle.set_stream(&stream).expect("set_stream");

    eprintln!();
    eprintln!("=== PTX GEMM (pure Rust) vs cuBLAS (NVIDIA) — FP32 ===");
    eprintln!(
        "{:<10} {:>12} {:>12} {:>10}",
        "Size", "PTX(µs)", "cuBLAS(µs)", "Ratio"
    );
    eprintln!("{}", "-".repeat(48));

    // FP32 tiled GEMM — test small sizes where PTX launch overhead matters
    for &n in &[32_usize, 64, 128, 256] {
        let m = n;
        let k = n;

        let a_data = vec![1.0f32; m * k];
        let b_data = vec![1.0f32; k * n];
        let c_data = vec![0.0f32; m * n];

        let a_buf = GpuBuffer::from_host(&ctx, &a_data).expect("A");
        let b_buf = GpuBuffer::from_host(&ctx, &b_data).expect("B");
        let c_buf = GpuBuffer::from_host(&ctx, &c_data).expect("C");

        // --- PTX GEMM ---
        let tile_size = 32.min(n);
        let kernel = GemmKernel::tiled(m as u32, n as u32, k as u32, tile_size as u32);
        let ptx = kernel.emit_ptx();
        let mut module = match CudaModule::from_ptx(&ctx, &ptx) {
            Ok(m) => m,
            Err(e) => {
                eprintln!("{:<10} PTX compile failed: {e}", format!("{n}x{n}"));
                continue;
            }
        };

        let grid_x = ((n + tile_size - 1) / tile_size) as u32;
        let grid_y = ((m + tile_size - 1) / tile_size) as u32;
        let config = LaunchConfig {
            grid: (grid_x, grid_y, 1),
            block: (tile_size as u32, tile_size as u32, 1),
            shared_mem: 0,
        };

        let mut a_ptr = a_buf.as_ptr();
        let mut b_ptr = b_buf.as_ptr();
        let mut c_ptr = c_buf.as_ptr();
        let mut m_val = m as u32;
        let mut n_val = n as u32;
        let mut k_val = k as u32;

        let mut args: Vec<*mut c_void> = vec![
            &mut a_ptr as *mut _ as *mut c_void,
            &mut b_ptr as *mut _ as *mut c_void,
            &mut c_ptr as *mut _ as *mut c_void,
            &mut m_val as *mut _ as *mut c_void,
            &mut n_val as *mut _ as *mut c_void,
            &mut k_val as *mut _ as *mut c_void,
        ];

        // Warmup PTX
        for _ in 0..3 {
            unsafe {
                stream
                    .launch_kernel(&mut module, kernel.name(), &config, &mut args)
                    .ok();
            }
        }
        stream.synchronize().ok();

        // Benchmark PTX
        let iters = 50;
        let start = Instant::now();
        for _ in 0..iters {
            unsafe {
                stream
                    .launch_kernel(&mut module, kernel.name(), &config, &mut args)
                    .ok();
            }
        }
        stream.synchronize().ok();
        let ptx_us = start.elapsed().as_micros() as f64 / iters as f64;

        // --- cuBLAS FP32 ---
        // cuBLAS uses column-major, so we transpose: C^T = B^T @ A^T
        use crate::driver::GemmOp;
        // Warmup
        for _ in 0..3 {
            handle
                .gemm_f32(
                    GemmOp::NoTrans,
                    GemmOp::NoTrans,
                    n as i32,
                    m as i32,
                    k as i32,
                    1.0,
                    b_buf.as_ptr(),
                    n as i32,
                    a_buf.as_ptr(),
                    k as i32,
                    0.0,
                    c_buf.as_ptr(),
                    n as i32,
                )
                .ok();
        }
        stream.synchronize().ok();

        let start = Instant::now();
        for _ in 0..iters {
            handle
                .gemm_f32(
                    GemmOp::NoTrans,
                    GemmOp::NoTrans,
                    n as i32,
                    m as i32,
                    k as i32,
                    1.0,
                    b_buf.as_ptr(),
                    n as i32,
                    a_buf.as_ptr(),
                    k as i32,
                    0.0,
                    c_buf.as_ptr(),
                    n as i32,
                )
                .ok();
        }
        stream.synchronize().ok();
        let cublas_us = start.elapsed().as_micros() as f64 / iters as f64;

        let ratio = if cublas_us > 0.0 {
            ptx_us / cublas_us
        } else {
            0.0
        };
        let status = if ratio < 2.0 {
            "competitive"
        } else if ratio < 5.0 {
            "gap"
        } else {
            "needs work"
        };

        eprintln!(
            "{:<10} {:>10.1}µs {:>10.1}µs {:>8.1}x  {status}",
            format!("{n}x{n}"),
            ptx_us,
            cublas_us,
            ratio,
        );
    }
    eprintln!();
    eprintln!("Note: PTX kernels are pure Rust (no nvcc). cuBLAS is NVIDIA vendor-optimized.");
    eprintln!("PTX/cuBLAS ratio <2x = competitive, <5x = gap, >5x = needs work.");
}

/// WMMA Tensor Core FP16 PTX vs cuBLAS FP16 benchmark.
///
/// Tests trueno-gpu's pure-Rust WMMA 16×16×16 FP16 kernels against cuBLAS
/// with tensor core FP16 accumulation. Both use hardware tensor cores.
///
/// Run: cargo test -p trueno-gpu --features cuda --lib --release -- wmma_vs_cublas --no-capture
#[test]
fn wmma_vs_cublas_fp16() {
    use crate::driver::module::CudaModule;
    use crate::driver::GemmOp;
    use crate::kernels::{GemmKernel, Kernel};
    use std::ffi::c_void;
    use std::time::Instant;

    let ctx = CudaContext::new(0).expect("CUDA context");
    let stream = CudaStream::new(&ctx).expect("stream");
    let handle = CublasHandle::new(&ctx).expect("cuBLAS handle");
    handle.set_stream(&stream).expect("set_stream");

    eprintln!();
    eprintln!("=== WMMA Tensor Core (pure Rust PTX) vs cuBLAS — FP16 ===");
    eprintln!(
        "{:<10} {:>12} {:>12} {:>12} {:>10}",
        "Size", "WMMA(µs)", "cuBLAS(µs)", "WMMA TFLOP/s", "Ratio"
    );
    eprintln!("{}", "-".repeat(60));

    for &n in &[128_usize, 256, 512, 1024] {
        let m = n;
        let k = n;
        let flops = 2.0 * m as f64 * n as f64 * k as f64;

        // FP32 input (WMMA kernel converts to FP16 internally)
        let a_data = vec![1.0f32; m * k];
        let b_data = vec![1.0f32; k * n];
        let c_data = vec![0.0f32; m * n];

        let a_buf = GpuBuffer::from_host(&ctx, &a_data).expect("A");
        let b_buf = GpuBuffer::from_host(&ctx, &b_data).expect("B");
        let c_buf = GpuBuffer::from_host(&ctx, &c_data).expect("C");

        // --- WMMA PTX kernel ---
        let kernel = GemmKernel::tensor_core(m as u32, n as u32, k as u32);
        let ptx = kernel.emit_ptx();
        let mut module = match CudaModule::from_ptx(&ctx, &ptx) {
            Ok(m) => m,
            Err(e) => {
                eprintln!("{:<10} WMMA PTX compile failed: {e}", format!("{n}x{n}"));
                continue;
            }
        };

        let grid_x = ((n + 15) / 16) as u32;
        let grid_y = ((m + 15) / 16) as u32;
        let config = LaunchConfig {
            grid: (grid_x, grid_y, 1),
            block: (32, 1, 1), // 1 warp per 16x16 tile
            shared_mem: 0,
        };

        let mut a_ptr = a_buf.as_ptr();
        let mut b_ptr = b_buf.as_ptr();
        let mut c_ptr = c_buf.as_ptr();
        let mut m_val = m as u32;
        let mut n_val = n as u32;
        let mut k_val = k as u32;

        let mut args: Vec<*mut c_void> = vec![
            &mut a_ptr as *mut _ as *mut c_void,
            &mut b_ptr as *mut _ as *mut c_void,
            &mut c_ptr as *mut _ as *mut c_void,
            &mut m_val as *mut _ as *mut c_void,
            &mut n_val as *mut _ as *mut c_void,
            &mut k_val as *mut _ as *mut c_void,
        ];

        // Warmup WMMA
        for _ in 0..5 {
            unsafe {
                stream
                    .launch_kernel(&mut module, kernel.name(), &config, &mut args)
                    .ok();
            }
        }
        stream.synchronize().ok();

        let iters = if n <= 256 { 100 } else { 50 };
        let start = Instant::now();
        for _ in 0..iters {
            unsafe {
                stream
                    .launch_kernel(&mut module, kernel.name(), &config, &mut args)
                    .ok();
            }
        }
        stream.synchronize().ok();
        let wmma_us = start.elapsed().as_micros() as f64 / iters as f64;
        let wmma_tflops = flops / (wmma_us * 1e6);

        // --- cuBLAS FP16 ---
        let a16 = vec![0x3C00u16; m * k]; // 1.0 in FP16
        let b16 = vec![0x3C00u16; k * n];
        let c16 = vec![0u16; m * n];
        let a16_buf = GpuBuffer::from_host(&ctx, &a16).expect("A16");
        let b16_buf = GpuBuffer::from_host(&ctx, &b16).expect("B16");
        let c16_buf = GpuBuffer::from_host(&ctx, &c16).expect("C16");

        for _ in 0..5 {
            handle
                .gemm_f16_row_major(
                    m as i32,
                    n as i32,
                    k as i32,
                    1.0,
                    a16_buf.as_ptr(),
                    b16_buf.as_ptr(),
                    0.0,
                    c16_buf.as_ptr(),
                )
                .ok();
        }
        stream.synchronize().ok();

        let start = Instant::now();
        for _ in 0..iters {
            handle
                .gemm_f16_row_major(
                    m as i32,
                    n as i32,
                    k as i32,
                    1.0,
                    a16_buf.as_ptr(),
                    b16_buf.as_ptr(),
                    0.0,
                    c16_buf.as_ptr(),
                )
                .ok();
        }
        stream.synchronize().ok();
        let cublas_us = start.elapsed().as_micros() as f64 / iters as f64;

        let ratio = if cublas_us > 0.0 {
            wmma_us / cublas_us
        } else {
            0.0
        };

        eprintln!(
            "{:<10} {:>10.1}µs {:>10.1}µs {:>10.1} {:>8.1}x",
            format!("{n}x{n}"),
            wmma_us,
            cublas_us,
            wmma_tflops,
            ratio,
        );
    }
    eprintln!();
}

/// CTA-tiled WMMA (4 warps, 32×32 tiles) vs cuBLAS FP16.
///
/// Run: cargo test -p trueno-gpu --features cuda --lib --release -- cta_wmma_vs_cublas --no-capture
#[test]
fn cta_wmma_vs_cublas_fp16() {
    use crate::driver::module::CudaModule;
    use crate::kernels::gemm::basic::tensor_core::cta_wmma::build_cta_wmma_fp16;
    use crate::ptx::PtxModule;
    use std::ffi::c_void;
    use std::time::Instant;

    let ctx = CudaContext::new(0).expect("CUDA context");
    let stream = CudaStream::new(&ctx).expect("stream");
    let handle = CublasHandle::new(&ctx).expect("cuBLAS handle");
    handle.set_stream(&stream).expect("set_stream");

    eprintln!();
    eprintln!("=== CTA WMMA (4-warp, 32x32) vs cuBLAS — FP16 ===");
    eprintln!(
        "{:<10} {:>12} {:>12} {:>12} {:>10}",
        "Size", "CTA(us)", "cuBLAS(us)", "CTA TFLOP/s", "Ratio"
    );
    eprintln!("{}", "-".repeat(60));

    for &n in &[128_usize, 256, 512, 1024] {
        let m = n;
        let k = n;
        let flops = 2.0 * m as f64 * n as f64 * k as f64;

        let a16 = vec![0x3C00u16; m * k];
        let b16 = vec![0x3C00u16; k * n];
        let c32 = vec![0.0f32; m * n];

        let a_buf = GpuBuffer::from_host(&ctx, &a16).expect("A");
        let b_buf = GpuBuffer::from_host(&ctx, &b16).expect("B");
        let c_buf = GpuBuffer::from_host(&ctx, &c32).expect("C");

        let kernel = build_cta_wmma_fp16(m as u32, n as u32, k as u32);
        let ptx_str = PtxModule::new().add_kernel(kernel).emit();
        let mut module = match CudaModule::from_ptx(&ctx, &ptx_str) {
            Ok(m) => m,
            Err(e) => {
                eprintln!("{:<10} CTA compile failed: {e}", format!("{n}x{n}"));
                continue;
            }
        };

        let grid_x = ((n + 31) / 32) as u32;
        let grid_y = ((m + 31) / 32) as u32;
        let config = LaunchConfig {
            grid: (grid_x, grid_y, 1),
            block: (128, 1, 1),
            shared_mem: 2048,
        };

        let mut a_ptr = a_buf.as_ptr();
        let mut b_ptr = b_buf.as_ptr();
        let mut c_ptr = c_buf.as_ptr();
        let mut m_v = m as u32;
        let mut n_v = n as u32;
        let mut k_v = k as u32;
        let mut args: Vec<*mut c_void> = vec![
            &mut a_ptr as *mut _ as *mut c_void,
            &mut b_ptr as *mut _ as *mut c_void,
            &mut c_ptr as *mut _ as *mut c_void,
            &mut m_v as *mut _ as *mut c_void,
            &mut n_v as *mut _ as *mut c_void,
            &mut k_v as *mut _ as *mut c_void,
        ];

        for _ in 0..5 {
            unsafe {
                stream
                    .launch_kernel(&mut module, "gemm_cta_wmma_fp16", &config, &mut args)
                    .ok();
            }
        }
        stream.synchronize().ok();

        let iters = 50;
        let start = Instant::now();
        for _ in 0..iters {
            unsafe {
                stream
                    .launch_kernel(&mut module, "gemm_cta_wmma_fp16", &config, &mut args)
                    .ok();
            }
        }
        stream.synchronize().ok();
        let cta_us = start.elapsed().as_micros() as f64 / iters as f64;
        let cta_tflops = flops / (cta_us * 1e6);

        // cuBLAS
        let c16_buf = GpuBuffer::from_host(&ctx, &vec![0u16; m * n]).expect("C16");
        for _ in 0..5 {
            handle
                .gemm_f16_row_major(
                    m as i32,
                    n as i32,
                    k as i32,
                    1.0,
                    a_buf.as_ptr(),
                    b_buf.as_ptr(),
                    0.0,
                    c16_buf.as_ptr(),
                )
                .ok();
        }
        stream.synchronize().ok();
        let start = Instant::now();
        for _ in 0..iters {
            handle
                .gemm_f16_row_major(
                    m as i32,
                    n as i32,
                    k as i32,
                    1.0,
                    a_buf.as_ptr(),
                    b_buf.as_ptr(),
                    0.0,
                    c16_buf.as_ptr(),
                )
                .ok();
        }
        stream.synchronize().ok();
        let cublas_us = start.elapsed().as_micros() as f64 / iters as f64;
        let ratio = if cublas_us > 0.0 {
            cta_us / cublas_us
        } else {
            0.0
        };

        eprintln!(
            "{:<10} {:>10.1}us {:>10.1}us {:>10.1} {:>8.1}x",
            format!("{n}x{n}"),
            cta_us,
            cublas_us,
            cta_tflops,
            ratio,
        );
    }
    eprintln!();
}

/// CTA WMMA double-buffered vs single-buffered vs cuBLAS FP16.
///
/// PERF-CTA-007: Measures the speedup from double-buffered shared memory
/// which overlaps global load of next K-tile with WMMA compute of current tile.
///
/// Run: cargo test -p trueno-gpu --features cuda --lib --release -- cta_wmma_dbuf_bench --no-capture
#[test]
fn cta_wmma_dbuf_bench_fp16() {
    use crate::driver::module::CudaModule;
    use crate::kernels::gemm::basic::tensor_core::cta_wmma::{
        build_cta_wmma_fp16, build_cta_wmma_fp16_dbuf,
    };
    use crate::ptx::PtxModule;
    use std::ffi::c_void;
    use std::time::Instant;

    let ctx = CudaContext::new(0).expect("CUDA context");
    let stream = CudaStream::new(&ctx).expect("stream");
    let handle = CublasHandle::new(&ctx).expect("cuBLAS handle");
    handle.set_stream(&stream).expect("set_stream");

    eprintln!();
    eprintln!("=== CTA WMMA: Single-buf vs Double-buf vs cuBLAS — FP16 ===");
    eprintln!(
        "{:<8} {:>10} {:>10} {:>10} {:>8} {:>8} {:>10}",
        "Size", "Single(us)", "Dbuf(us)", "cuBLAS(us)", "Speedup", "vs cuBL", "Dbuf TFLOP/s"
    );
    eprintln!("{}", "-".repeat(78));

    for &n in &[128_usize, 256, 512, 1024] {
        let m = n;
        let k = n;
        let flops = 2.0 * m as f64 * n as f64 * k as f64;

        let a16 = vec![0x3C00u16; m * k];
        let b16 = vec![0x3C00u16; k * n];
        let c32 = vec![0.0f32; m * n];

        let a_buf = GpuBuffer::from_host(&ctx, &a16).expect("A");
        let b_buf = GpuBuffer::from_host(&ctx, &b16).expect("B");
        let c_buf = GpuBuffer::from_host(&ctx, &c32).expect("C");

        let grid_x = ((n + 31) / 32) as u32;
        let grid_y = ((m + 31) / 32) as u32;

        // ─── Single-buffer ───
        let kernel_s = build_cta_wmma_fp16(m as u32, n as u32, k as u32);
        let ptx_s = PtxModule::new().add_kernel(kernel_s).emit();
        let mut mod_s = match CudaModule::from_ptx(&ctx, &ptx_s) {
            Ok(m) => m,
            Err(e) => {
                eprintln!("{:<8} Single compile failed: {e}", format!("{n}"));
                continue;
            }
        };
        let cfg_s = LaunchConfig {
            grid: (grid_x, grid_y, 1),
            block: (128, 1, 1),
            shared_mem: 2048,
        };

        let mut a_ptr = a_buf.as_ptr();
        let mut b_ptr = b_buf.as_ptr();
        let mut c_ptr = c_buf.as_ptr();
        let mut m_v = m as u32;
        let mut n_v = n as u32;
        let mut k_v = k as u32;
        let mut args: Vec<*mut c_void> = vec![
            &mut a_ptr as *mut _ as *mut c_void,
            &mut b_ptr as *mut _ as *mut c_void,
            &mut c_ptr as *mut _ as *mut c_void,
            &mut m_v as *mut _ as *mut c_void,
            &mut n_v as *mut _ as *mut c_void,
            &mut k_v as *mut _ as *mut c_void,
        ];

        for _ in 0..5 {
            unsafe {
                stream
                    .launch_kernel(&mut mod_s, "gemm_cta_wmma_fp16", &cfg_s, &mut args)
                    .ok();
            }
        }
        stream.synchronize().ok();
        let iters = 50;
        let start = Instant::now();
        for _ in 0..iters {
            unsafe {
                stream
                    .launch_kernel(&mut mod_s, "gemm_cta_wmma_fp16", &cfg_s, &mut args)
                    .ok();
            }
        }
        stream.synchronize().ok();
        let single_us = start.elapsed().as_micros() as f64 / iters as f64;

        // ─── Double-buffer ───
        let kernel_d = build_cta_wmma_fp16_dbuf(m as u32, n as u32, k as u32);
        let ptx_d = PtxModule::new().add_kernel(kernel_d).emit();
        let mut mod_d = match CudaModule::from_ptx(&ctx, &ptx_d) {
            Ok(m) => m,
            Err(e) => {
                eprintln!("{:<8} Double-buf compile failed: {e}", format!("{n}"));
                continue;
            }
        };
        let cfg_d = LaunchConfig {
            grid: (grid_x, grid_y, 1),
            block: (128, 1, 1),
            shared_mem: 4096,
        };

        // Reset args
        a_ptr = a_buf.as_ptr();
        b_ptr = b_buf.as_ptr();
        c_ptr = c_buf.as_ptr();
        m_v = m as u32;
        n_v = n as u32;
        k_v = k as u32;

        for _ in 0..5 {
            unsafe {
                stream
                    .launch_kernel(&mut mod_d, "gemm_cta_wmma_fp16", &cfg_d, &mut args)
                    .ok();
            }
        }
        stream.synchronize().ok();
        let start = Instant::now();
        for _ in 0..iters {
            unsafe {
                stream
                    .launch_kernel(&mut mod_d, "gemm_cta_wmma_fp16", &cfg_d, &mut args)
                    .ok();
            }
        }
        stream.synchronize().ok();
        let dbuf_us = start.elapsed().as_micros() as f64 / iters as f64;
        let dbuf_tflops = flops / (dbuf_us * 1e6);

        // ─── cuBLAS reference ───
        let c16_buf = GpuBuffer::from_host(&ctx, &vec![0u16; m * n]).expect("C16");
        for _ in 0..5 {
            handle
                .gemm_f16_row_major(
                    m as i32,
                    n as i32,
                    k as i32,
                    1.0,
                    a_buf.as_ptr(),
                    b_buf.as_ptr(),
                    0.0,
                    c16_buf.as_ptr(),
                )
                .ok();
        }
        stream.synchronize().ok();
        let start = Instant::now();
        for _ in 0..iters {
            handle
                .gemm_f16_row_major(
                    m as i32,
                    n as i32,
                    k as i32,
                    1.0,
                    a_buf.as_ptr(),
                    b_buf.as_ptr(),
                    0.0,
                    c16_buf.as_ptr(),
                )
                .ok();
        }
        stream.synchronize().ok();
        let cublas_us = start.elapsed().as_micros() as f64 / iters as f64;

        let speedup = single_us / dbuf_us;
        let vs_cublas = cublas_us / dbuf_us;

        eprintln!(
            "{:<8} {:>10.1} {:>10.1} {:>10.1} {:>7.2}x {:>7.2}x {:>10.1}",
            format!("{n}"),
            single_us,
            dbuf_us,
            cublas_us,
            speedup,
            vs_cublas,
            dbuf_tflops,
        );
    }
    eprintln!();
}

/// 64×64 CTA WMMA: single-buf vs double-buf vs 32×32 vs cuBLAS FP16.
///
/// PERF-CTA64-001: 2× compute-to-load ratio (32 FLOP/byte).
/// Double-buffer retried with 16 WMMAs/K-tile amortization (was 4 in 32×32).
///
/// Run: cargo test -p trueno-gpu --features cuda --lib --release -- cta64_vs_cta32 --no-capture
#[test]
fn cta64_vs_cta32_vs_cublas_fp16() {
    use crate::driver::module::CudaModule;
    use crate::kernels::gemm::basic::tensor_core::cta64_wmma::{
        build_cta64_mma_fp16_cpasync, build_cta64_wmma_fp16, build_cta64_wmma_fp16_cpasync,
        build_cta64_wmma_fp16_dbuf, build_cta64x128_mma_fp16_cpasync,
        build_cta64x128_mma_pipeline_fp16,
    };
    use crate::kernels::gemm::basic::tensor_core::cta_wmma::build_cta_wmma_fp16;
    use crate::ptx::PtxModule;
    use std::ffi::c_void;
    use std::time::Instant;

    let ctx = CudaContext::new(0).expect("CUDA context");
    let stream = CudaStream::new(&ctx).expect("stream");
    let handle = CublasHandle::new(&ctx).expect("cuBLAS handle");
    handle.set_stream(&stream).expect("set_stream");

    eprintln!();
    eprintln!("=== CTA64: single vs dbuf vs cp.async vs CTA32 vs cuBLAS — FP16 ===");
    eprintln!(
        "{:<6} {:>8} {:>8} {:>8} {:>8} {:>8} {:>8} {:>6}",
        "Size", "CTA32", "CTA64", "Dbuf64", "CpAsync", "cuBLAS", "CpA TF/s", "cpVsCu"
    );
    eprintln!("{}", "-".repeat(80));

    for &n in &[128_usize, 256, 512, 1024, 2048, 4096] {
        let m = n;
        let k = n;
        let flops = 2.0 * m as f64 * n as f64 * k as f64;

        let a16 = vec![0x3C00u16; m * k];
        let b16 = vec![0x3C00u16; k * n];
        let c32 = vec![0.0f32; m * n];

        let a_buf = GpuBuffer::from_host(&ctx, &a16).expect("A");
        let b_buf = GpuBuffer::from_host(&ctx, &b16).expect("B");
        let c_buf = GpuBuffer::from_host(&ctx, &c32).expect("C");

        // Scale iterations for larger sizes
        let iters = if n <= 1024 {
            50
        } else if n <= 2048 {
            20
        } else {
            10
        };

        // ─── 32×32 CTA (baseline) ───
        let kernel_32 = build_cta_wmma_fp16(m as u32, n as u32, k as u32);
        let ptx_32 = PtxModule::new().add_kernel(kernel_32).emit();
        let mut mod_32 = match CudaModule::from_ptx(&ctx, &ptx_32) {
            Ok(m) => m,
            Err(e) => {
                eprintln!("{:<8} CTA32 compile failed: {e}", n);
                continue;
            }
        };
        let cfg_32 = LaunchConfig {
            grid: (((n + 31) / 32) as u32, ((m + 31) / 32) as u32, 1),
            block: (128, 1, 1),
            shared_mem: 2048,
        };

        let mut a_ptr = a_buf.as_ptr();
        let mut b_ptr = b_buf.as_ptr();
        let mut c_ptr = c_buf.as_ptr();
        let mut m_v = m as u32;
        let mut n_v = n as u32;
        let mut k_v = k as u32;
        let mut args: Vec<*mut c_void> = vec![
            &mut a_ptr as *mut _ as *mut c_void,
            &mut b_ptr as *mut _ as *mut c_void,
            &mut c_ptr as *mut _ as *mut c_void,
            &mut m_v as *mut _ as *mut c_void,
            &mut n_v as *mut _ as *mut c_void,
            &mut k_v as *mut _ as *mut c_void,
        ];

        for _ in 0..5 {
            unsafe {
                stream
                    .launch_kernel(&mut mod_32, "gemm_cta_wmma_fp16", &cfg_32, &mut args)
                    .ok();
            }
        }
        stream.synchronize().ok();
        let start = Instant::now();
        for _ in 0..iters {
            unsafe {
                stream
                    .launch_kernel(&mut mod_32, "gemm_cta_wmma_fp16", &cfg_32, &mut args)
                    .ok();
            }
        }
        stream.synchronize().ok();
        let cta32_us = start.elapsed().as_micros() as f64 / iters as f64;

        // ─── 64×64 CTA ───
        let kernel_64 = build_cta64_wmma_fp16(m as u32, n as u32, k as u32);
        let ptx_64 = PtxModule::new().add_kernel(kernel_64).emit();
        let mut mod_64 = match CudaModule::from_ptx(&ctx, &ptx_64) {
            Ok(m) => m,
            Err(e) => {
                eprintln!("{:<8} CTA64 compile failed: {e}", n);
                continue;
            }
        };
        let cfg_64 = LaunchConfig {
            grid: (((n + 63) / 64) as u32, ((m + 63) / 64) as u32, 1),
            block: (512, 1, 1),
            shared_mem: 4096,
        };

        a_ptr = a_buf.as_ptr();
        b_ptr = b_buf.as_ptr();
        c_ptr = c_buf.as_ptr();
        m_v = m as u32;
        n_v = n as u32;
        k_v = k as u32;

        for _ in 0..5 {
            unsafe {
                stream
                    .launch_kernel(&mut mod_64, "gemm_cta64_wmma_fp16", &cfg_64, &mut args)
                    .ok();
            }
        }
        stream.synchronize().ok();
        let start = Instant::now();
        for _ in 0..iters {
            unsafe {
                stream
                    .launch_kernel(&mut mod_64, "gemm_cta64_wmma_fp16", &cfg_64, &mut args)
                    .ok();
            }
        }
        stream.synchronize().ok();
        let cta64_us = start.elapsed().as_micros() as f64 / iters as f64;

        // ─── 64×64 CTA double-buffer ───
        let kernel_db = build_cta64_wmma_fp16_dbuf(m as u32, n as u32, k as u32);
        let ptx_db = PtxModule::new().add_kernel(kernel_db).emit();
        let mut mod_db = match CudaModule::from_ptx(&ctx, &ptx_db) {
            Ok(m) => m,
            Err(e) => {
                eprintln!("{:<6} CTA64-dbuf compile failed: {e}", n);
                continue;
            }
        };
        let cfg_db = LaunchConfig {
            grid: (((n + 63) / 64) as u32, ((m + 63) / 64) as u32, 1),
            block: (512, 1, 1),
            shared_mem: 8192, // 2×4096
        };

        a_ptr = a_buf.as_ptr();
        b_ptr = b_buf.as_ptr();
        c_ptr = c_buf.as_ptr();
        m_v = m as u32;
        n_v = n as u32;
        k_v = k as u32;

        for _ in 0..5 {
            unsafe {
                stream
                    .launch_kernel(&mut mod_db, "gemm_cta64_wmma_fp16", &cfg_db, &mut args)
                    .ok();
            }
        }
        stream.synchronize().ok();
        let start = Instant::now();
        for _ in 0..iters {
            unsafe {
                stream
                    .launch_kernel(&mut mod_db, "gemm_cta64_wmma_fp16", &cfg_db, &mut args)
                    .ok();
            }
        }
        stream.synchronize().ok();
        let dbuf64_us = start.elapsed().as_micros() as f64 / iters as f64;
        let _dbuf64_tflops = flops / (dbuf64_us * 1e6);

        // ─── 64×64 cp.async (SM 8.0+) ───
        let kernel_cp = build_cta64_wmma_fp16_cpasync(m as u32, n as u32, k as u32);
        // cp.async requires sm_80+ target
        let ptx_cp = PtxModule::new()
            .target("sm_80")
            .add_kernel(kernel_cp)
            .emit();
        let cpasync_us = match CudaModule::from_ptx(&ctx, &ptx_cp) {
            Ok(mut mod_cp) => {
                let cfg_cp = LaunchConfig {
                    grid: (((n + 63) / 64) as u32, ((m + 63) / 64) as u32, 1),
                    block: (512, 1, 1),
                    shared_mem: 8192,
                };
                a_ptr = a_buf.as_ptr();
                b_ptr = b_buf.as_ptr();
                c_ptr = c_buf.as_ptr();
                m_v = m as u32;
                n_v = n as u32;
                k_v = k as u32;
                for _ in 0..5 {
                    unsafe {
                        stream
                            .launch_kernel(
                                &mut mod_cp,
                                "gemm_cta64_cpasync_fp16",
                                &cfg_cp,
                                &mut args,
                            )
                            .ok();
                    }
                }
                stream.synchronize().ok();
                let start = Instant::now();
                for _ in 0..iters {
                    unsafe {
                        stream
                            .launch_kernel(
                                &mut mod_cp,
                                "gemm_cta64_cpasync_fp16",
                                &cfg_cp,
                                &mut args,
                            )
                            .ok();
                    }
                }
                stream.synchronize().ok();
                start.elapsed().as_micros() as f64 / iters as f64
            }
            Err(e) => {
                eprintln!("{:<6} cp.async compile failed: {e}", n);
                f64::INFINITY
            }
        };
        let cpasync_tflops = flops / (cpasync_us * 1e6);

        // ─── cuBLAS reference ───
        let c16_buf = GpuBuffer::from_host(&ctx, &vec![0u16; m * n]).expect("C16");
        for _ in 0..5 {
            handle
                .gemm_f16_row_major(
                    m as i32,
                    n as i32,
                    k as i32,
                    1.0,
                    a_buf.as_ptr(),
                    b_buf.as_ptr(),
                    0.0,
                    c16_buf.as_ptr(),
                )
                .ok();
        }
        stream.synchronize().ok();
        let start = Instant::now();
        for _ in 0..iters {
            handle
                .gemm_f16_row_major(
                    m as i32,
                    n as i32,
                    k as i32,
                    1.0,
                    a_buf.as_ptr(),
                    b_buf.as_ptr(),
                    0.0,
                    c16_buf.as_ptr(),
                )
                .ok();
        }
        stream.synchronize().ok();
        let cublas_us = start.elapsed().as_micros() as f64 / iters as f64;

        let cp_vs_cublas = cublas_us / cpasync_us;

        // ─── 128×128 cp.async (Phase 2 bridge plan) ───
        let kernel_128 =
            crate::kernels::gemm::basic::tensor_core::cta128_wmma::build_cta128_wmma_fp16_cpasync(
                m as u32, n as u32, k as u32,
            );
        let ptx_128 = PtxModule::new()
            .target("sm_80")
            .add_kernel(kernel_128)
            .emit();
        let cta128_us = match CudaModule::from_ptx(&ctx, &ptx_128) {
            Ok(mut mod_128) => {
                let cfg_128 = LaunchConfig {
                    grid: (((n + 127) / 128) as u32, ((m + 127) / 128) as u32, 1),
                    block: (512, 1, 1),
                    shared_mem: 16384, // 2 stages × 8KB
                };
                a_ptr = a_buf.as_ptr();
                b_ptr = b_buf.as_ptr();
                c_ptr = c_buf.as_ptr();
                m_v = m as u32;
                n_v = n as u32;
                k_v = k as u32;
                for _ in 0..5 {
                    unsafe {
                        stream
                            .launch_kernel(
                                &mut mod_128,
                                "gemm_cta128_cpasync_fp16",
                                &cfg_128,
                                &mut args,
                            )
                            .ok();
                    }
                }
                stream.synchronize().ok();
                let start = Instant::now();
                for _ in 0..iters {
                    unsafe {
                        stream
                            .launch_kernel(
                                &mut mod_128,
                                "gemm_cta128_cpasync_fp16",
                                &cfg_128,
                                &mut args,
                            )
                            .ok();
                    }
                }
                stream.synchronize().ok();
                start.elapsed().as_micros() as f64 / iters as f64
            }
            Err(e) => {
                eprintln!("{:<6} cta128 compile failed: {e}", n);
                f64::INFINITY
            }
        };
        let cta128_tflops = flops / (cta128_us * 1e6);
        let cta128_vs_cublas = cublas_us / cta128_us;

        // ─── 64×64 mma.sync (Phase 1 bridge plan) ───
        let kernel_mma = build_cta64_mma_fp16_cpasync(m as u32, n as u32, k as u32);
        let ptx_mma = PtxModule::new()
            .target("sm_80")
            .add_kernel(kernel_mma)
            .emit();
        let mma_us = match CudaModule::from_ptx(&ctx, &ptx_mma) {
            Ok(mut mod_mma) => {
                let cfg_mma = LaunchConfig {
                    grid: (((n + 63) / 64) as u32, ((m + 63) / 64) as u32, 1),
                    block: (512, 1, 1),
                    shared_mem: 8192,
                };
                a_ptr = a_buf.as_ptr();
                b_ptr = b_buf.as_ptr();
                c_ptr = c_buf.as_ptr();
                m_v = m as u32;
                n_v = n as u32;
                k_v = k as u32;
                for _ in 0..5 {
                    unsafe {
                        stream
                            .launch_kernel(&mut mod_mma, "gemm_cta64_mma_fp16", &cfg_mma, &mut args)
                            .ok();
                    }
                }
                stream.synchronize().ok();
                let start = Instant::now();
                for _ in 0..iters {
                    unsafe {
                        stream
                            .launch_kernel(&mut mod_mma, "gemm_cta64_mma_fp16", &cfg_mma, &mut args)
                            .ok();
                    }
                }
                stream.synchronize().ok();
                start.elapsed().as_micros() as f64 / iters as f64
            }
            Err(e) => {
                eprintln!("{:<6} mma.sync compile failed: {e}", n);
                f64::INFINITY
            }
        };
        let mma_tflops = flops / (mma_us * 1e6);

        // ─── 64×128 mma.sync (wider tile, +33% AI) ───
        let mma128_us = if n >= 256 {
            let kernel_128 = build_cta64x128_mma_fp16_cpasync(m as u32, n as u32, k as u32);
            let ptx_128 = PtxModule::new()
                .target("sm_80")
                .add_kernel(kernel_128)
                .emit();
            match CudaModule::from_ptx(&ctx, &ptx_128) {
                Ok(mut mod_128) => {
                    let cfg_128 = LaunchConfig {
                        grid: (((n + 127) / 128) as u32, ((m + 63) / 64) as u32, 1),
                        block: (512, 1, 1),
                        shared_mem: 12288,
                    };
                    a_ptr = a_buf.as_ptr();
                    b_ptr = b_buf.as_ptr();
                    c_ptr = c_buf.as_ptr();
                    m_v = m as u32;
                    n_v = n as u32;
                    k_v = k as u32;
                    for _ in 0..5 {
                        unsafe {
                            stream
                                .launch_kernel(
                                    &mut mod_128,
                                    "gemm_cta64x128_mma_fp16",
                                    &cfg_128,
                                    &mut args,
                                )
                                .ok();
                        }
                    }
                    stream.synchronize().ok();
                    let start = Instant::now();
                    for _ in 0..iters {
                        unsafe {
                            stream
                                .launch_kernel(
                                    &mut mod_128,
                                    "gemm_cta64x128_mma_fp16",
                                    &cfg_128,
                                    &mut args,
                                )
                                .ok();
                        }
                    }
                    stream.synchronize().ok();

                    // Correctness spot-check: all-ones inputs → C[i] should be K
                    if n == 256 {
                        let mut result = vec![0.0f32; m * n];
                        c_buf.copy_to_host(&mut result).expect("D2H");
                        let expected = k as f32;
                        let max_err = result
                            .iter()
                            .map(|&v| (v - expected).abs())
                            .fold(0.0f32, f32::max);
                        assert!(
                            max_err < 1.0,
                            "64x128 correctness FAILED at {n}: max_err={max_err}, expected={expected}"
                        );
                        eprintln!("  64x128 correctness OK at {n}: max_err={max_err:.4}");
                        // Reset C buffer for timing
                        let c32 = vec![0.0f32; m * n];
                        let c_buf_fresh = GpuBuffer::from_host(&ctx, &c32).expect("C reset");
                        c_ptr = c_buf_fresh.as_ptr();
                    }

                    start.elapsed().as_micros() as f64 / iters as f64
                }
                Err(e) => {
                    eprintln!("  64x128 compile failed: {e}");
                    f64::INFINITY
                }
            }
        } else {
            f64::INFINITY
        };
        let mma128_tflops = flops / (mma128_us * 1e6);

        // ─── 64×128 pipelined mma.sync (3-stage sw pipeline) ───
        let pipe_us = if n >= 256 {
            let kernel_pipe = build_cta64x128_mma_pipeline_fp16(m as u32, n as u32, k as u32);
            let ptx_pipe = PtxModule::new()
                .target("sm_80")
                .add_kernel(kernel_pipe)
                .emit();
            match CudaModule::from_ptx(&ctx, &ptx_pipe) {
                Ok(mut mod_pipe) => {
                    let cfg_pipe = LaunchConfig {
                        grid: (((n + 127) / 128) as u32, ((m + 63) / 64) as u32, 1),
                        block: (512, 1, 1),
                        shared_mem: 18432,
                    };
                    // Reset C
                    let c32 = vec![0.0f32; m * n];
                    let c_buf_p = GpuBuffer::from_host(&ctx, &c32).expect("C pipe");
                    let mut c_ptr_p = c_buf_p.as_ptr();
                    let mut args_pipe: Vec<*mut c_void> = vec![
                        &mut a_ptr as *mut _ as *mut c_void,
                        &mut b_ptr as *mut _ as *mut c_void,
                        &mut c_ptr_p as *mut _ as *mut c_void,
                        &mut m_v as *mut _ as *mut c_void,
                        &mut n_v as *mut _ as *mut c_void,
                        &mut k_v as *mut _ as *mut c_void,
                    ];
                    // Warmup
                    for _ in 0..5 {
                        unsafe {
                            stream
                                .launch_kernel(
                                    &mut mod_pipe,
                                    "gemm_cta64x128_mma_pipeline_fp16",
                                    &cfg_pipe,
                                    &mut args_pipe,
                                )
                                .ok();
                        }
                    }
                    stream.synchronize().ok();
                    let start = Instant::now();
                    for _ in 0..iters {
                        unsafe {
                            stream
                                .launch_kernel(
                                    &mut mod_pipe,
                                    "gemm_cta64x128_mma_pipeline_fp16",
                                    &cfg_pipe,
                                    &mut args_pipe,
                                )
                                .ok();
                        }
                    }
                    stream.synchronize().ok();
                    start.elapsed().as_micros() as f64 / iters as f64
                }
                Err(e) => {
                    eprintln!("  pipeline compile failed: {e}");
                    f64::INFINITY
                }
            }
        } else {
            f64::INFINITY
        };
        let pipe_tflops = flops / (pipe_us * 1e6);

        eprintln!(
            "{:<6} {:>8.1} {:>8.1} {:>8.1} {:>8.1} {:>8.1} {:>8.1} {:>5.2}x | mma: {:>8.1} {:>8.1} | 128: {:>8.1} {:>8.1} | pipe: {:>8.1} {:>8.1}",
            n,
            cta32_us,
            cta64_us,
            dbuf64_us,
            cpasync_us,
            cublas_us,
            cpasync_tflops,
            cp_vs_cublas,
            mma_us,
            mma_tflops,
            mma128_us,
            mma128_tflops,
            pipe_us,
            pipe_tflops,
        );
    }
    eprintln!();
}