File size: 25,088 Bytes
1276a5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Substrate batch 2: 14 more KernelBench level1 problems.

8 activations (elementwise), 3 matmul variants, min-reduction, L1/L2 row norm.
Self-contained (no imports from problems_ext to avoid circular imports);
registered into kernels_def.PROBLEMS on import.
"""
import ctypes

import torch as _torch

import kernels_def as K


def _seeded(seed):
    _torch.manual_seed(seed)


# --------------------------------------------------------------- elementwise

_EW_TMPL = r"""
#include <cuda_fp16.h>

__global__ void {kname}(const float* x, float* out, long long n) {{
    long long idx = (long long)blockIdx.x * blockDim.x + threadIdx.x;
    if (idx < n) {{ float val = x[idx]; out[idx] = {expr}; }}
}}
"""


def _ew_launch(inputs, torch):
    x = inputs[0]
    out = torch.zeros_like(x)
    n = x.numel()
    return out, ((n + 255) // 256, 1, 1), (256, 1, 1), [(ctypes.c_longlong, n)]


def _ew_suites():
    def t0(t):
        _seeded(1000 + t)
        return [_torch.rand(4096, 393216)]

    def t1(t):
        _seeded(7)
        return [_torch.randn(4096, 393216)]

    def t2(t):
        _seeded(9)
        return [_torch.randn(4096, 393216) * 100.0]

    def t3(t):
        _seeded(8)
        return [_torch.randn(127, 4097)]

    return [("T0_original", 5, t0), ("T1_signed", 1, t1),
            ("T2_large", 1, t2), ("T3_misaligned", 1, t3)]


def _swish_suites():
    def t4(t):
        _seeded(73)
        x = _torch.full((31, 257), 65536.0, dtype=_torch.float32)
        x[:, 0::4] = 65520.0
        x[:, 1::4] = 65568.0
        x[:, 2::4] = 70000.0
        x[:, -1] = 131072.0
        return [x]

    def t5(t):
        _seeded(79)
        x = _torch.tensor([[1.0, 8.0, 64.0, 65520.0, 70000.0]],
                          dtype=_torch.float32)
        return [x]

    return _ew_suites() + [
        ("T4_misaligned_fp16_overflow_stripes", 1, t4),
        ("T5_small_partial_block_fp16_boundary", 1, t5),
    ]


def _tanh_suites():
    def t4(t):
        _seeded(73)
        x = _torch.full((1, 257), 8.0, dtype=_torch.float32)
        x[:, 0::4] = 0.125
        x[:, 1::4] = 0.54930615
        x[:, 2::4] = 1.0986123
        x[:, -1] = 16.0
        return [x]

    def t5(t):
        _seeded(79)
        values = _torch.tensor([
            0.010003, 0.031257, 0.062519, 0.125061,
            0.255413, 0.549306, 1.098612, 2.0,
            4.0, 8.0, 16.0,
        ], dtype=_torch.float32)
        x = values.repeat(23, 24)[:, :259]
        x[:, -1] = 32.0
        return [x]

    return _ew_suites() + [
        ("T4_misaligned_positive_tail_spike", 1, t4),
        ("T5_positive_fp16_rounding_lattice", 1, t5),
    ]


def _hardsigmoid_suites():
    def t0(t):
        _seeded(1000 + t)
        return [_torch.rand(4096, 393216)]

    def t1(t):
        _seeded(7)
        return [_torch.randn(4096, 393216)]

    def t2(t):
        _seeded(9)
        return [_torch.randn(4096, 393216) * 100.0]

    def t3(t):
        _seeded(8)
        return [_torch.randn(127, 4097)]

    def t4(t):
        _seeded(61)
        values = _torch.tensor([
            -3.001, -3.0, -2.999, -2.75, -2.0, -1.0,
            -0.003, 0.0, 0.003, 1.0, 2.0, 2.75,
            2.999, 3.0, 3.001,
        ], dtype=_torch.float32)
        return [values.repeat(33, 18)[:, :257]]

    def t5(t):
        _seeded(67)
        x = _torch.full((31, 257), 2.999, dtype=_torch.float32)
        x[:, 0::4] = -2.999
        x[:, 1::4] = -1.5015
        x[:, 2::4] = 1.5015
        x[:, -1] = 3000.0
        return [x]

    def t6(t):
        _seeded(71)
        outputs = (_torch.arange(255, dtype=_torch.float32) + 0.5) / 256.0
        x = (outputs * 6.0 - 3.0).reshape(3, 85)
        x[0, 0] = -3000.0
        x[-1, -1] = 3000.0
        return [x]

    return [("T0_original", 5, t0), ("T1_signed", 1, t1),
            ("T2_large", 1, t2), ("T3_misaligned", 1, t3),
            ("T4_transition_threshold_stripes", 1, t4),
            ("T5_misaligned_tail_spike", 1, t5),
            ("T6_fp16_rounding_lattice", 1, t6)]


def _hardtanh_suites():
    def t4(t):
        _seeded(67)
        x = _torch.full((33, 257), 2.0, dtype=_torch.float32)
        x[:, 0::4] = 0.999
        x[:, 1::4] = 1.0
        x[:, 2::4] = 1.001
        x[:, -1] = 64.0
        return [x]

    def t5(t):
        _seeded(71)
        values = _torch.tensor([
            -64.0, -1.001, -1.0, -0.999, -0.5002442,
            -0.3332519, 0.3332519, 0.5002442, 0.9989,
            0.999, 0.9991, 1.0, 1.001, 64.0,
        ], dtype=_torch.float32)
        return [values.repeat(19, 20)[:, :259]]

    return _ew_suites() + [
        ("T4_misaligned_upper_clamp_tail", 1, t4),
        ("T5_clamp_and_fp16_neighborhoods", 1, t5),
    ]


def _softsign_suites():
    def t4(t):
        _seeded(73)
        x = _torch.full((3, 257), 1.0e-4, dtype=_torch.float32)
        x[:, 0::2] = 4096.0
        x[:, -1] = 32768.0
        return [x]

    def t5(t):
        _seeded(79)
        outputs = (_torch.arange(1, 256, dtype=_torch.float32) + 0.5) / 256.0
        x = (outputs / (1.0 - outputs)).reshape(3, 85)
        x[0, 0] = 65504.0
        x[-1, -1] = 1.0e8
        return [x]

    return _ew_suites() + [
        ("T4_misaligned_alternating_tail_spike", 1, t4),
        ("T5_positive_fp16_rounding_lattice", 1, t5),
    ]


def _selu_suites():
    def t0(t):
        _seeded(1000 + t)
        return [_torch.rand(4096, 393216)]

    def t1(t):
        _seeded(7)
        return [_torch.randn(4096, 393216)]

    def t2(t):
        _seeded(9)
        return [_torch.randn(4096, 393216) * 100.0]

    def t3(t):
        _seeded(8)
        return [_torch.randn(127, 4097)]

    def t4(t):
        _seeded(27)
        values = _torch.tensor([
            -8.0, -4.0, -2.0, -1.0, -0.5, -0.125,
            -2.0e-6, -1.0e-6, -0.0, 0.0, 5.0e-7, 1.0e-6,
            1.5e-6, 2.0e-6, 0.125, 0.5, 1.0, 4.0,
        ], dtype=_torch.float32)
        return [values.repeat(17, 15)[:, :257]]

    def t5(t):
        _seeded(28)
        x = _torch.full((31, 257), -0.5, dtype=_torch.float32)
        x[:, 0::4] = -8.0
        x[:, 1::4] = -2.0
        x[:, 2::4] = -0.125
        x[:, -1] = -1.0e-6
        return [x]

    def t6(t):
        _seeded(29)
        x = _torch.linspace(-9.0, -1.0e-4, 259, dtype=_torch.float32)
        return [x.repeat(33, 1)]

    return [("T0_original", 5, t0), ("T1_signed", 1, t1),
            ("T2_large", 1, t2), ("T3_misaligned", 1, t3),
            ("T4_branch_threshold_neighborhood", 1, t4),
            ("T5_misaligned_negative_stripes", 1, t5),
            ("T6_negative_exponential_sweep", 1, t6)]


def _elu_suites():
    def t0(t):
        _seeded(1000 + t)
        return [_torch.rand(4096, 393216)]

    def t1(t):
        _seeded(7)
        return [_torch.randn(4096, 393216)]

    def t2(t):
        _seeded(9)
        return [_torch.randn(4096, 393216) * 100.0]

    def t3(t):
        _seeded(8)
        return [_torch.randn(127, 4097)]

    def t4(t):
        _seeded(61)
        values = _torch.tensor([
            -1.0, -0.75, -0.5, -0.25, -0.125, -0.03125,
            -1.0e-3, -1.0e-5, -0.0, 0.0, 1.0e-5, 1.0e-3,
            0.03125, 0.125, 0.25, 0.5, 0.75, 1.0,
        ], dtype=_torch.float32)
        return [values.repeat(17, 15)[:, :257]]

    def t5(t):
        _seeded(67)
        values = _torch.tensor([
            -0.015625, -0.03125, -0.0625, -0.125, -0.25,
            -0.5, -1.0, -2.0, -4.0, -8.0, -16.0,
        ], dtype=_torch.float32)
        return [values.repeat(31, 24)[:, :259]]

    def t6(t):
        _seeded(71)
        x = _torch.full((3, 257), -0.5, dtype=_torch.float32)
        x[:, 0::4] = -8.0
        x[:, 1::4] = 0.25
        x[:, 2::4] = -0.03125
        x[:, -1] = -16.0
        return [x]

    return [("T0_original", 5, t0), ("T1_signed", 1, t1),
            ("T2_large", 1, t2), ("T3_misaligned", 1, t3),
            ("T4_branch_threshold_sweep", 1, t4),
            ("T5_negative_exponential_ladder", 1, t5),
            ("T6_misaligned_alternating_tail", 1, t6)]


def _softplus_suites():
    def t0(t):
        _seeded(1000 + t)
        return [_torch.rand(4096, 393216)]

    def t1(t):
        _seeded(7)
        return [_torch.randn(4096, 393216)]

    def t2(t):
        _seeded(9)
        return [_torch.randn(4096, 393216) * 100.0]

    def t3(t):
        _seeded(8)
        return [_torch.randn(127, 4097)]

    def t4(t):
        _seeded(47)
        values = _torch.tensor([
            7.999, 8.0, 8.001, 9.0, 12.0, 16.0,
            19.999, 20.0, 20.001,
        ], dtype=_torch.float32)
        return [values.repeat(29, 31)[:, :257]]

    def t5(t):
        _seeded(53)
        x = _torch.full((31, 257), 8.0, dtype=_torch.float32)
        x[:, 0::4] = 0.0
        x[:, 1::4] = 7.999
        x[:, 2::4] = 20.0
        x[:, -1] = 20.001
        return [x]

    def t6(t):
        _seeded(59)
        values = _torch.tensor([
            -20.0, -16.0, -12.0, -9.0, -8.0, -6.0,
            -4.0, -2.0, -1.0, -0.5, 0.0, 0.5, 1.0, 2.0,
            4.0, 6.0, 7.5, 7.999,
        ], dtype=_torch.float32)
        return [values.repeat(37, 15)[:, :257]]

    return [("T0_original", 5, t0), ("T1_signed", 1, t1),
            ("T2_large", 1, t2), ("T3_misaligned", 1, t3),
            ("T4_cutoff_neighborhood", 1, t4),
            ("T5_misaligned_cutoff_stripes", 1, t5),
            ("T6_exponential_regime_sweep", 1, t6)]


def _ew_probe(torch):
    torch.manual_seed(0)
    return [("p_aligned", [torch.rand(32, 256)]),
            ("p_misaligned", [torch.randn(7, 257)])]


_F = _torch.nn.functional
_ACTIVATIONS = {
    "tanh": dict(kb="22_Tanh.py", expr="tanhf(val)",
                 ref=lambda x: _torch.tanh(x), suites=_tanh_suites),
    "swish": dict(kb="25_Swish.py",
                  expr="val * (1.0f / (1.0f + expf(-val)))",
                  ref=lambda x: x * _torch.sigmoid(x), suites=_swish_suites),
    "selu": dict(kb="27_SELU_.py",
                 expr="1.0507009873554805f * (val > 0.0f ? val : "
                      "1.6732632423543772f * (expf(val) - 1.0f))",
                 ref=lambda x: _torch.selu(x), suites=_selu_suites),
    "hardsigmoid": dict(kb="28_HardSigmoid.py",
                        expr="fminf(fmaxf(val / 6.0f + 0.5f, 0.0f), 1.0f)",
                        ref=lambda x: _F.hardsigmoid(x),
                        suites=_hardsigmoid_suites),
    "softplus": dict(kb="29_Softplus.py",
                     expr="val > 20.0f ? val : log1pf(expf(val))",
                     ref=lambda x: _F.softplus(x), suites=_softplus_suites),
    "softsign": dict(kb="30_Softsign.py",
                     expr="val / (1.0f + fabsf(val))",
                     ref=lambda x: _F.softsign(x), suites=_softsign_suites),
    "elu": dict(kb="31_ELU.py",
                expr="val > 0.0f ? val : (expf(val) - 1.0f)",
                ref=lambda x: _F.elu(x), suites=_elu_suites),
    "hardtanh": dict(kb="32_HardTanh.py",
                     expr="fminf(fmaxf(val, -1.0f), 1.0f)",
                     ref=lambda x: _F.hardtanh(x), suites=_hardtanh_suites),
}

# ----------------------------------------------------------- matmul variants

_MM_TMPL = r"""
#include <cuda_fp16.h>

#define TILE 32

__global__ void {kname}(const float* A, const float* B, float* C,
                        int M, int K, int N) {{
    __shared__ float As[TILE][TILE];
    __shared__ float Bs[TILE][TILE];
    int row = blockIdx.y * TILE + threadIdx.y;
    int col = blockIdx.x * TILE + threadIdx.x;
    float acc = 0.0f;
    int numTiles = (K + TILE - 1) / TILE;
    for (int t = 0; t < numTiles; t++) {{
        int a_k = t * TILE + threadIdx.x;
        int b_k = t * TILE + threadIdx.y;
        As[threadIdx.y][threadIdx.x] = {a_load};
        Bs[threadIdx.y][threadIdx.x] = {b_load};
        __syncthreads(); // sync-after-load
        for (int k = 0; k < TILE; k++) {{
            acc += As[threadIdx.y][k] * Bs[k][threadIdx.x];
        }}
        __syncthreads(); // sync-after-compute
    }}
    if (row < M && col < N) {{ C[(long long)row * N + col] = acc; }}
}}
"""

_A_NORMAL = "(row < M && a_k < K) ? A[(long long)row * K + a_k] : 0.0f"
_A_TRANS = "(a_k < K && row < M) ? A[(long long)a_k * M + row] : 0.0f"
_B_NORMAL = "(b_k < K && col < N) ? B[(long long)b_k * N + col] : 0.0f"
_B_TRANS = "(b_k < K && col < N) ? B[(long long)col * K + b_k] : 0.0f"


def _mm_launch(a_layout, b_layout):
    def launch(inputs, torch):
        A, B = inputs
        if a_layout == "t":
            Kd, M = A.shape
        else:
            M, Kd = A.shape
        N = B.shape[0] if b_layout == "t" else B.shape[1]
        out = torch.zeros((M, N), device=A.device, dtype=A.dtype)
        return out, ((N + 31) // 32, (M + 31) // 32, 1), (32, 32, 1), \
            [(ctypes.c_int, M), (ctypes.c_int, Kd), (ctypes.c_int, N)]
    return launch


def _mm_var_suites(m, k, n, a_layout, b_layout, symmetric=False):
    def a_shape():
        return (k, m) if a_layout == "t" else (m, k)

    def b_shape():
        return (n, k) if b_layout == "t" else (k, n)

    def gen(fn):
        A, B = fn(*a_shape()), fn(*b_shape())
        if symmetric:
            A = (A + A.T) / 2
            B = (B + B.T) / 2
        return [A, B]

    def t0(t):
        _seeded(1000 + t)
        return gen(_torch.rand)

    def t1(t):
        _seeded(7)
        return gen(_torch.randn)

    def t2(t):
        _seeded(9)
        return gen(lambda *s: _torch.rand(*s) * 50.0)

    def t3(t):
        _seeded(11)
        m3, k3, n3 = 515, 1027, 259
        if symmetric:
            m3 = k3 = n3 = 515
        A = _torch.randn(*((k3, m3) if a_layout == "t" else (m3, k3)))
        B = _torch.randn(*((n3, k3) if b_layout == "t" else (k3, n3)))
        if symmetric:
            A = (A + A.T) / 2
            B = (B + B.T) / 2
        return [A, B]

    def t4(t):
        _seeded(13)
        A, B = gen(_torch.rand)
        A += 0.0
        if a_layout == "t":
            A[-32:, :] = 100.0
        else:
            A[:, -32:] = 100.0
        if b_layout == "t":
            B[:, -32:] = 100.0
        else:
            B[-32:, :] = 100.0
        return [A, B]

    def t5(t):
        _seeded(17)
        m5, k5, n5 = 39, 33, 35
        rows = _torch.arange(m5, dtype=_torch.float32)[:, None]
        red = _torch.arange(k5, dtype=_torch.float32)[None, :]
        cols = _torch.arange(n5, dtype=_torch.float32)[None, :]
        A = 0.25 + rows * 0.125 + red * 0.03125
        B = 0.5 + red.T * 0.0625 + cols * 0.015625
        return [A, B]

    def t6(t):
        _seeded(19)
        m6, k6, n6 = 35, 33, 39
        rows = _torch.arange(m6, dtype=_torch.float32)[:, None]
        red = _torch.arange(k6, dtype=_torch.float32)[None, :]
        cols = _torch.arange(n6, dtype=_torch.float32)[None, :]
        A = 0.125 + rows * 0.0625 + red * 0.015625
        B = 0.375 + red.T * 0.03125 + cols * 0.125
        return [A, B]

    def t7(t):
        _seeded(23)
        m7, k7, n7 = 37, 33, 41
        A = _torch.full((m7, k7), 1.0e-3)
        B = _torch.full((k7, n7), 1.0e-3)
        A[:, -1] = 32.0 + _torch.arange(m7, dtype=_torch.float32)
        B[-1, :] = 48.0 + _torch.arange(n7, dtype=_torch.float32)
        return [A, B]

    def t8(t):
        _seeded(29)
        m8, k8, n8 = 1025, 8191, 1025
        A = _torch.ones((m8, k8), dtype=_torch.float32)
        B = _torch.ones((n8, k8), dtype=_torch.float32)
        A[:, -1] = 64.0
        B[:, -1] = 96.0
        return [A, B]

    def t9(t):
        _seeded(31)
        m9, k9, n9 = 33, 31, 35
        rows = _torch.arange(m9, dtype=_torch.float32)[:, None]
        cols = _torch.arange(n9, dtype=_torch.float32)[:, None]
        A = 0.25 + rows * 0.03125 + _torch.arange(
            k9, dtype=_torch.float32)[None, :] * 0.015625
        B = 0.5 + cols * 0.0625 + _torch.arange(
            k9, dtype=_torch.float32)[None, :] * 0.03125
        A[:, -1] = 48.0 + rows[:, 0]
        B[:, -1] = 64.0 + cols[:, 0]
        return [A, B]

    def t10(t):
        _seeded(37)
        m10, k10, n10 = 35, 31, 37
        red = _torch.arange(k10, dtype=_torch.float32)[:, None]
        rows = _torch.arange(m10, dtype=_torch.float32)[None, :]
        cols = _torch.arange(n10, dtype=_torch.float32)[:, None]
        A = 0.25 + red * 0.03125 + rows * 0.125
        B = 0.5 + cols * 0.25 + red.T * 0.0625
        return [A, B]

    def t11(t):
        _seeded(41)
        m11, k11, n11 = 33, 30, 35
        A = _torch.full((k11, m11), 1.0e-3)
        B = _torch.full((n11, k11), 1.0e-3)
        A[-1, :] = 64.0 + _torch.arange(m11, dtype=_torch.float32)
        B[:, -1] = 96.0 + _torch.arange(n11, dtype=_torch.float32)
        return [A, B]

    def t12(t):
        _seeded(43)
        m12, k12, n12 = 47, 63, 45
        red = _torch.arange(k12, dtype=_torch.float32)[:, None]
        rows = _torch.arange(m12, dtype=_torch.float32)[None, :]
        cols = _torch.arange(n12, dtype=_torch.float32)[:, None]
        A = 0.125 + red.remainder(2) * 31.875 + rows * 0.0625
        B = 0.25 + (cols + red.T).remainder(2) * 47.75
        return [A, B]

    return lambda: [("T0_original", 5, t0), ("T1_signed", 1, t1),
                    ("T2_large", 1, t2), ("T3_misaligned", 1, t3),
                    ("T4_last_tile_spike", 1, t4)] + (
                        [("T5_rect_m_gt_n_positional", 1, t5),
                         ("T6_rect_n_gt_m_positional", 1, t6),
                         ("T7_partial_tile_tail_mass", 1, t7)]
                        if symmetric else []) + (
                        [("T8_tb_wide_stride_guard_edges", 1, t8),
                         ("T9_tb_k31_positional_tail_spike", 1, t9)]
                        if (a_layout, b_layout, symmetric) == ("n", "t", False)
                        else []) + (
                        [("T10_tab_k31_positional_boundary", 1, t10),
                         ("T11_tab_k30_tail_mass", 1, t11),
                         ("T12_tab_k63_alternating", 1, t12)]
                        if (a_layout, b_layout, symmetric) == ("t", "t", False)
                        else [])


def _mm_probe(a_layout, b_layout, symmetric=False):
    def probe(torch):
        torch.manual_seed(0)
        m, k, n = (64, 128, 96) if not symmetric else (64, 64, 64)
        m2, k2, n2 = (67, 131, 53) if not symmetric else (67, 67, 67)
        def mk(mm, kk, nn):
            A = torch.randn(*((kk, mm) if a_layout == "t" else (mm, kk)))
            B = torch.randn(*((nn, kk) if b_layout == "t" else (kk, nn)))
            if symmetric:
                A = (A + A.T) / 2
                B = (B + B.T) / 2
            return [A, B]
        return [("p_aligned", mk(m, k, n)), ("p_misaligned", mk(m2, k2, n2))]
    return probe


# ----------------------------------------------------------- min reduction

MIN_CUDA = r"""
#include <cuda_fp16.h>
#include <math_constants.h>

__global__ void min_dim1_kernel(const float* x, float* out, int B, int R, int C) {
    int c = blockIdx.x * blockDim.x + threadIdx.x;
    int b = blockIdx.y;
    if (c >= C) return;
    float best = CUDART_INF_F;
    for (int r = 0; r < R; r++) {
        best = fminf(best, x[(long long)b * R * C + (long long)r * C + c]);
    }
    out[(long long)b * C + c] = best;
}
"""


def _red2d_launch(inputs, torch):
    x = inputs[0]
    B, R, C = x.shape
    out = torch.zeros((B, C), device=x.device, dtype=x.dtype)
    return out, ((C + 255) // 256, B, 1), (256, 1, 1), \
        [(ctypes.c_int, B), (ctypes.c_int, R), (ctypes.c_int, C)]


def _red_suites():
    def t0(t):
        _seeded(1000 + t)
        return [_torch.rand(128, 4096, 4095)]

    def t1(t):
        _seeded(7)
        return [_torch.randn(128, 4096, 4095)]

    def t4(t):
        _seeded(13)
        x = _torch.rand(128, 4096, 4095)
        x[:, 0, :] -= 100.0
        x[:, -1, :] -= 100.0
        return [x]

    def t5(t):
        _seeded(17)
        return [_torch.rand(128, 4096, 4095) + 1.0]

    def t6(t):
        _seeded(19)
        x = _torch.full((17, 257, 259), 64.0, dtype=_torch.float32)
        x[:, 0::2, :] = 7.0
        x[:, 1::4, :] = 7.0
        x[:, -1, :] = 7.0
        return [x]

    def t7(t):
        _seeded(23)
        x = _torch.full((19, 33, 257), 1.0, dtype=_torch.float32)
        x[:, 0::4, :] = 0.0
        x[:, 2::4, :] = -0.0
        x[:, -2, :] = -0.0
        x[:, -1, :] = 0.0
        return [x]

    return [("T0_original", 5, t0), ("T1_signed", 1, t1),
            ("T4_edge_row_dip", 1, t4), ("T5_all_positive_shifted", 1, t5),
            ("T6_duplicate_minima_ordered", 1, t6),
            ("T7_signed_zero_ties", 1, t7)]


def _red_probe(torch):
    torch.manual_seed(0)
    return [("p_aligned", [torch.rand(4, 64, 256)]),
            ("p_misaligned", [torch.randn(4, 64, 255)])]


# ------------------------------------------------------------ L1 / L2 norm

_NORM_TMPL = r"""
#include <cuda_fp16.h>

__global__ void {kname}(const float* x, float* out, int dim) {{
    long long row = blockIdx.x;
    const float* xr = x + row * dim;
    float* outr = out + row * dim;
    __shared__ float sdata[256];
    int tid = threadIdx.x;
    int iters = (dim + 255) / 256;
    float local_sum = 0.0f;
    for (int it = 0; it < iters; it++) {{
        int i = it * 256 + tid;
        if (i < dim) {{ local_sum += {term}; }}
    }}
    sdata[tid] = local_sum;
    __syncthreads(); // sync-sum-store
    for (int s = 128; s > 0; s >>= 1) {{ // sum-reduce
        if (tid < s) {{ sdata[tid] = sdata[tid] + sdata[tid + s]; }}
        __syncthreads();
    }}
    float denom = {denom};
    __syncthreads(); // sync-sum-read
    for (int it = 0; it < iters; it++) {{
        int i = it * 256 + tid;
        if (i < dim) {{ outr[i] = xr[i] / denom; }}
    }}
}}
"""


def _rownorm_launch(inputs, torch):
    x = inputs[0]
    out = torch.zeros_like(x)
    return out, (x.shape[0], 1, 1), (256, 1, 1), [(ctypes.c_int, x.shape[1])]


def _rownorm_suites():
    def t0(t):
        _seeded(1000 + t)
        return [_torch.rand(32768, 65535)]

    def t1(t):
        _seeded(7)
        return [_torch.randn(32768, 65535)]

    def t4(t):
        _seeded(13)
        x = _torch.randn(512, 65535) * 0.01
        x[:, -1] = 1000.0
        return [x]

    return [("T0_original", 5, t0), ("T1_signed", 1, t1),
            ("T4_tail_spike", 1, t4)]


def _rownorm_probe(torch):
    torch.manual_seed(0)
    return [("p_aligned", [torch.rand(4, 512)]),
            ("p_misaligned", [torch.randn(3, 259)])]


# ------------------------------------------------------------------- register

def _register():
    for name, spec in _ACTIVATIONS.items():
        K.PROBLEMS[name] = dict(
            kb_file=spec["kb"],
            cuda=_EW_TMPL.format(kname=f"{name}_kernel", expr=spec["expr"]),
            kernel_name=f"{name}_kernel", ref=spec["ref"],
            launch=_ew_launch, suites=spec.get("suites", _ew_suites),
            probe=_ew_probe)

    mm_variants = {
        "matmul_tb": dict(kb="17_Matmul_with_transposed_B.py",
                          a="n", b="t", sym=False, m=2048, k=8192, n=4096,
                          ref=lambda A, B: _torch.matmul(A, B.T)),
        "matmul_tab": dict(kb="18_Matmul_with_transposed_both.py",
                           a="t", b="t", sym=False, m=2048, k=8192, n=4096,
                           ref=lambda A, B: _torch.matmul(A.T, B.T)),
        "matmul_sym": dict(kb="13_Matmul_for_symmetric_matrices.py",
                           a="n", b="n", sym=True, m=4096, k=4096, n=4096,
                           ref=lambda A, B: _torch.matmul(A, B)),
    }
    for name, v in mm_variants.items():
        a_load = _A_TRANS if v["a"] == "t" else _A_NORMAL
        b_load = _B_TRANS if v["b"] == "t" else _B_NORMAL
        K.PROBLEMS[name] = dict(
            kb_file=v["kb"],
            cuda=_MM_TMPL.format(kname=f"{name}_kernel",
                                 a_load=a_load, b_load=b_load),
            kernel_name=f"{name}_kernel", ref=v["ref"],
            launch=_mm_launch(v["a"], v["b"]),
            suites=_mm_var_suites(v["m"], v["k"], v["n"], v["a"], v["b"], v["sym"]),
            probe=_mm_probe(v["a"], v["b"], v["sym"]))

    K.PROBLEMS["min"] = dict(
        kb_file="53_Min_reduction_over_a_dimension.py", cuda=MIN_CUDA,
        kernel_name="min_dim1_kernel",
        ref=lambda x: _torch.min(x, dim=1)[0],
        launch=_red2d_launch, suites=_red_suites, probe=_red_probe)

    K.PROBLEMS["l1norm"] = dict(
        kb_file="38_L1Norm_.py",
        cuda=_NORM_TMPL.format(kname="l1norm_kernel",
                               term="fabsf(xr[i])", denom="sdata[0] / dim"),
        kernel_name="l1norm_kernel",
        ref=lambda x: x / _torch.mean(_torch.abs(x), dim=1, keepdim=True),
        launch=_rownorm_launch, suites=_rownorm_suites, probe=_rownorm_probe)

    K.PROBLEMS["l2norm"] = dict(
        kb_file="39_L2Norm_.py",
        cuda=_NORM_TMPL.format(kname="l2norm_kernel",
                               term="xr[i] * xr[i]", denom="sqrtf(sdata[0])"),
        kernel_name="l2norm_kernel",
        ref=lambda x: x / _torch.norm(x, p=2, dim=1, keepdim=True),
        launch=_rownorm_launch, suites=_rownorm_suites, probe=_rownorm_probe)


_register()