-
Notifications
You must be signed in to change notification settings - Fork 158
Expand file tree
/
Copy pathtest_examples.py
More file actions
2729 lines (2410 loc) · 93 KB
/
Copy pathtest_examples.py
File metadata and controls
2729 lines (2410 loc) · 93 KB
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
from __future__ import annotations
import math
import unittest
from unittest.mock import patch
from packaging import version
import torch
import torch.nn.functional as F
from torch.testing._internal.common_utils import instantiate_parametrized_tests
from torch.testing._internal.common_utils import parametrize
import helion
from helion import _compat
from helion._testing import DEVICE
from helion._testing import EXAMPLES_DIR
from helion._testing import HALF_DTYPE
from helion._testing import LONG_INT_TYPE
from helion._testing import CosSimilarity
from helion._testing import RefEagerTestBase
from helion._testing import TestCase
from helion._testing import _get_backend
from helion._testing import check_example
from helion._testing import float32_matmul_precision
from helion._testing import import_path
from helion._testing import onlyBackends
from helion._testing import skipIfA10G
from helion._testing import skipIfCudaCapabilityLessThan
from helion._testing import skipIfCudaSharedMemoryLessThan
from helion._testing import skipIfFn
from helion._testing import skipIfNotCUDA
from helion._testing import skipIfPallas
from helion._testing import skipIfPallasInterpret
from helion._testing import skipIfRefEager
from helion._testing import skipIfRocm
from helion._testing import skipIfTileIR
from helion._testing import skipIfXPU
from helion._testing import xfailIfPallas
from helion._testing import xfailIfPallasInterpret
from helion._testing import xfailIfPallasTpu
from helion.runtime.config import Config
from helion.runtime.ref_mode import is_ref_mode_enabled
_orig_matmul_fp32_precision: str = "none"
_orig_cudnn_fp32_precision: str = "none"
def _compile_only(
fn: helion.Kernel,
args: tuple[object, ...],
**kwargs: object,
) -> object:
bound = fn.bind(args)
if kwargs:
config = Config(
# pyrefly: ignore [bad-argument-type]
**kwargs
)
elif fn.configs:
(config,) = fn.configs
else:
config = bound.config_spec.default_config()
for key in bound.config_spec.unsupported_config_keys(config.config):
config.config.pop(key, None)
if is_ref_mode_enabled(bound.kernel.settings):
bound._config = config
return bound
return bound.compile_config(config)
def setUpModule() -> None:
global _orig_matmul_fp32_precision, _orig_cudnn_fp32_precision
_orig_matmul_fp32_precision = torch.backends.cuda.matmul.fp32_precision
_orig_cudnn_fp32_precision = torch.backends.cudnn.conv.fp32_precision
torch.backends.cuda.matmul.fp32_precision = "tf32"
torch.backends.cudnn.conv.fp32_precision = "tf32"
def tearDownModule() -> None:
torch.backends.cuda.matmul.fp32_precision = _orig_matmul_fp32_precision
torch.backends.cudnn.conv.fp32_precision = _orig_cudnn_fp32_precision
@onlyBackends(["triton", "cute", "pallas"])
class TestExamples(RefEagerTestBase, TestCase):
def test_add(self):
args = (
torch.randn([512, 512], device=DEVICE, dtype=torch.float32),
torch.randn([512], device=DEVICE, dtype=HALF_DTYPE),
)
check_example("add", args, sum(args), block_sizes=[128, 1], flatten_loop=True)
def test_add_loop_order(self):
args = (
torch.randn([512, 512], device=DEVICE, dtype=torch.float32),
torch.randn([512, 512], device=DEVICE, dtype=HALF_DTYPE),
)
check_example(
"add", args, sum(args), block_sizes=[256, 128], loop_orders=[[1, 0]]
)
@skipIfCudaSharedMemoryLessThan(
131072, reason="block sizes exceed device shared memory limit"
)
def test_matmul(self):
args = (
torch.randn([1024, 256], device=DEVICE, dtype=torch.float32),
torch.randn([256, 512], device=DEVICE, dtype=torch.float32),
)
check_example(
"matmul",
args,
args[0] @ args[1],
block_sizes=[128, 128, 128],
)
def test_matmul_default(self):
"""Matmul without explicit block_sizes to exercise autotuner defaults."""
args = (
torch.randn([1024, 1024], device=DEVICE, dtype=torch.float32),
torch.randn([1024, 1024], device=DEVICE, dtype=torch.float32),
)
check_example(
"matmul",
args,
args[0] @ args[1],
)
@xfailIfPallas(
"Pallas TPU clamps the N block to the lane width (128) which does"
" not match the test's N=96 bias dimension"
)
def test_matmul_bias_epilogue_wrapper(self):
from typing import Any
from typing import Callable
from typing import NamedTuple
class BiasEpilogue(NamedTuple):
bias: torch.Tensor
@property
def fn(
self,
) -> Callable[[torch.Tensor, tuple[torch.Tensor, ...]], torch.Tensor]:
bias = self.bias
def epilogue(
acc: torch.Tensor, tile: tuple[torch.Tensor, ...]
) -> torch.Tensor:
return acc + bias[tile[1]]
return epilogue
def __call__(
self, acc: torch.Tensor, tile: tuple[torch.Tensor, ...]
) -> torch.Tensor:
return self.fn(acc, tile)
@property
def __closure__(self) -> tuple[Any, ...] | None:
return self.fn.__closure__
a = torch.randn([128, 64], device=DEVICE, dtype=torch.float32)
b = torch.randn([64, 96], device=DEVICE, dtype=torch.float32)
bias = torch.randn([96], device=DEVICE, dtype=torch.float32)
check_example(
"matmul",
(a, b, BiasEpilogue(bias)),
a @ b + bias,
block_sizes=[32, 32, 32],
)
def test_matmul_bf16_tcgen05(self):
"""Matmul at 256^3 bf16 — fixture sized just above the cute
tcgen05 admission floor (M >= 64 divisible by 64) so the cute
autotune sub-sweep fires the ``uses_tcgen05`` codegen marker.
"""
args = (
torch.randn([256, 256], device=DEVICE, dtype=torch.bfloat16),
torch.randn([256, 256], device=DEVICE, dtype=torch.bfloat16),
)
check_example(
"matmul",
args,
args[0] @ args[1],
block_sizes=[64, 64, 32],
)
@xfailIfPallas("missing barrier implementation")
@skipIfTileIR("PassManager::run failed")
@skipIfXPU("Split-K barrier not supported on XPU backend")
def test_split_k_barrier(self):
m, k, n = 64, 512, 64
a = torch.randn([m, k], device=DEVICE, dtype=torch.float32)
b = torch.randn([k, n], device=DEVICE, dtype=torch.float32)
expected = a @ b
check_example(
"split_k_barrier",
(a, b),
expected,
fn_name="split_k_matmul",
block_sizes=[16, 8, 16, 16, 16],
pid_type="persistent_blocked",
split_k=64,
)
@xfailIfPallas("missing barrier implementation")
@skipIfTileIR("PassManager::run failed")
@skipIfRefEager("Test requires compiled kernel with specific config")
def test_split_k_barrier_accuracy(self):
"""Test split_k_barrier with a shape that exposes accuracy issues.
This test uses shape (64, 33, 64) where K is not divisible by split_k.
The bug manifests after multiple kernel executions - errors accumulate
due to improper handling of the tmp tensor across invocations.
"""
from examples.split_k_barrier import split_k_matmul
m, k, n = 64, 33, 64
config = helion.Config(
block_sizes=[16, 8, 16, 16, 16],
pid_type="persistent_blocked",
split_k=32,
)
# Compile once and reuse - this triggers the accumulating error bug
torch.manual_seed(0)
a0 = torch.randn([m, k], device=DEVICE, dtype=torch.float32)
b0 = torch.randn([k, n], device=DEVICE, dtype=torch.float32)
bound = split_k_matmul.bind((a0, b0))
compiled = bound.compile_config(config)
# Run multiple iterations - errors accumulate starting around iteration 2-3
for seed in range(5):
torch.manual_seed(seed)
a = torch.randn([m, k], device=DEVICE, dtype=torch.float32)
b = torch.randn([k, n], device=DEVICE, dtype=torch.float32)
expected = a @ b
result = compiled(a, b)
torch.testing.assert_close(
result,
expected,
atol=1e-1,
rtol=1e-2,
msg=f"Accuracy failure at iteration {seed}",
)
def test_matmul_bwd(self):
"""Test backward pass for matmul via matmul_autograd."""
mod = import_path(EXAMPLES_DIR / "matmul.py")
# Set a fixed config to avoid autotuning in CI
config = helion.Config(block_sizes=[16, 16, 16])
mod.matmul.configs = [config]
mat1 = torch.randn(
[128, 128], device=DEVICE, dtype=torch.float32, requires_grad=True
)
mat2 = torch.randn(
[128, 128], device=DEVICE, dtype=torch.float32, requires_grad=True
)
mat1_ref = mat1.detach().clone().requires_grad_(True)
mat2_ref = mat2.detach().clone().requires_grad_(True)
ref_out = torch.matmul(mat1_ref, mat2_ref)
grad_out = torch.randn_like(ref_out)
ref_out.backward(grad_out)
result = mod.matmul_autograd(mat1, mat2)
result.backward(grad_out)
torch.testing.assert_close(result, ref_out, atol=1e-1, rtol=1e-2)
torch.testing.assert_close(mat1.grad, mat1_ref.grad, atol=1e-1, rtol=1e-2)
torch.testing.assert_close(mat2.grad, mat2_ref.grad, atol=1e-1, rtol=1e-2)
def test_addmm_bwd(self):
"""Test backward pass for addmm via addmm_autograd."""
mod = import_path(EXAMPLES_DIR / "matmul.py")
# Set a fixed config to avoid autotuning in CI
config = helion.Config(block_sizes=[16, 16, 16])
mod.matmul.configs = [config]
bias = torch.randn(
[128, 128], device=DEVICE, dtype=torch.float32, requires_grad=True
)
mat1 = torch.randn(
[128, 128], device=DEVICE, dtype=torch.float32, requires_grad=True
)
mat2 = torch.randn(
[128, 128], device=DEVICE, dtype=torch.float32, requires_grad=True
)
alpha, beta = 2.0, 0.5
bias_ref = bias.detach().clone().requires_grad_(True)
mat1_ref = mat1.detach().clone().requires_grad_(True)
mat2_ref = mat2.detach().clone().requires_grad_(True)
ref_out = torch.addmm(bias_ref, mat1_ref, mat2_ref, alpha=alpha, beta=beta)
grad_out = torch.randn_like(ref_out)
ref_out.backward(grad_out)
result = mod.addmm_autograd(bias, mat1, mat2, alpha, beta)
result.backward(grad_out)
torch.testing.assert_close(result, ref_out, atol=1e-1, rtol=1e-2)
torch.testing.assert_close(bias.grad, bias_ref.grad, atol=1e-1, rtol=1e-2)
torch.testing.assert_close(mat1.grad, mat1_ref.grad, atol=1e-1, rtol=1e-2)
torch.testing.assert_close(mat2.grad, mat2_ref.grad, atol=1e-1, rtol=1e-2)
def test_matmul_layernorm_static_shapes(self):
args = (
torch.randn([1024, 256], device=DEVICE, dtype=torch.float32),
torch.randn([256, 512], device=DEVICE, dtype=torch.float32),
torch.randn([512], device=DEVICE, dtype=torch.float32),
torch.randn([512], device=DEVICE, dtype=torch.float32),
)
check_example(
"matmul_layernorm",
args,
torch.nn.functional.layer_norm(
(args[0] @ args[1]),
normalized_shape=(512,),
weight=args[2],
bias=args[3],
),
block_sizes=[16, 16],
static_shapes=True,
)
@onlyBackends(["pallas"])
def test_matmul_layernorm_half_dtype_multi_k_tile(self):
"""Guards K-loop accumulator precision when inputs are half-precision.
Across multiple K-tile iterations the partial-sum accumulator must
stay in fp32 to keep the layernorm output within tight tolerance;
regressions here surface as out-of-tolerance results on bf16/fp16.
"""
m, k, n = 1024, 1024, 1024
args = (
torch.randn([m, k], device=DEVICE, dtype=HALF_DTYPE),
torch.randn([k, n], device=DEVICE, dtype=HALF_DTYPE),
torch.randn([n], device=DEVICE, dtype=HALF_DTYPE),
torch.randn([n], device=DEVICE, dtype=HALF_DTYPE),
)
expected = torch.nn.functional.layer_norm(
(args[0] @ args[1]).to(torch.float32),
normalized_shape=(n,),
weight=args[2].to(torch.float32),
bias=args[3].to(torch.float32),
).to(HALF_DTYPE)
check_example(
"matmul_layernorm",
args,
expected,
block_sizes=[32, 256],
static_shapes=True,
atol=1e-2,
rtol=1e-2,
)
def test_matmul_layernorm_small_shapes_compile_on_cute(self):
if _get_backend() != "cute":
self.skipTest("CuTe-specific compile coverage")
mod = import_path(EXAMPLES_DIR / "matmul_layernorm.py")
args = (
torch.randn([32, 64], device=DEVICE, dtype=torch.float32),
torch.randn([64, 128], device=DEVICE, dtype=torch.float32),
torch.randn([128], device=DEVICE, dtype=torch.float32),
torch.randn([128], device=DEVICE, dtype=torch.float32),
)
_compile_only(mod.matmul_layernorm, args, block_sizes=[16, 16])
@skipIfFn(
lambda: _get_backend() == "cute",
"CuTe matmul+layernorm example is unsupported and too expensive in-process",
)
@xfailIfPallas("JAX tracer error with dynamic shapes")
def test_matmul_layernorm_dynamic_shapes(self):
args = (
torch.randn([128, 256], device=DEVICE, dtype=torch.float32),
torch.randn([256, 400], device=DEVICE, dtype=torch.float32),
torch.randn([400], device=DEVICE, dtype=torch.float32),
torch.randn([400], device=DEVICE, dtype=torch.float32),
)
check_example(
"matmul_layernorm",
args,
torch.nn.functional.layer_norm(
(args[0] @ args[1]),
normalized_shape=(400,),
weight=args[2],
bias=args[3],
),
block_sizes=[16, 16],
static_shapes=False,
)
@unittest.skipIf(
version.parse(torch.__version__.split("+")[0]) < version.parse("2.8"),
"Requires torch 2.8+",
)
def test_bmm(self):
args = (
torch.randn([16, 512, 768], device=DEVICE, dtype=HALF_DTYPE),
torch.randn([16, 768, 1024], device=DEVICE, dtype=HALF_DTYPE),
)
check_example(
"bmm",
args,
torch.bmm(args[0], args[1]),
block_sizes=[16, 16, 16, 16],
)
def test_bmm_non_divisible_k(self):
args = (
torch.randn([4, 128, 384], device=DEVICE, dtype=HALF_DTYPE),
torch.randn([4, 384, 128], device=DEVICE, dtype=HALF_DTYPE),
)
check_example(
"bmm",
args,
torch.bmm(args[0], args[1]),
block_sizes=[1, 128, 128, 256],
)
@skipIfNotCUDA()
@skipIfCudaCapabilityLessThan((9, 0), reason="FP8 requires CUDA capability >= 9.0")
def test_fp8_gemm(self):
# Create FP32 tensors and convert to FP8
x = torch.randn([256, 256], device=DEVICE, dtype=torch.float32)
y = torch.randn([256, 256], device=DEVICE, dtype=torch.float32)
# Convert to FP8 format
x_fp8 = x.to(torch.float8_e4m3fn)
y_fp8 = y.to(torch.float8_e4m3fn).T.contiguous().T
args = (x_fp8, y_fp8)
# Import the reference implementation
mod = import_path(EXAMPLES_DIR / "fp8_gemm.py")
scale_a = torch.tensor(1.0, device=DEVICE)
scale_b = torch.tensor(1.0, device=DEVICE)
expected = mod.reference_fp8_gemm_pytorch(x_fp8, y_fp8, scale_a, scale_b)
check_example(
"fp8_gemm",
args,
expected,
block_sizes=[16, 16, 32],
num_warps=4,
num_stages=3,
)
def test_template_via_closure0(self):
bias = torch.randn([1, 512], device=DEVICE, dtype=HALF_DTYPE)
args = (
torch.randn([512, 512], device=DEVICE, dtype=HALF_DTYPE),
torch.randn([512, 512], device=DEVICE, dtype=HALF_DTYPE),
lambda acc, tile: torch.relu(acc + bias[tile]),
)
check_example(
"matmul",
args,
torch.relu(args[0] @ args[1] + bias),
fn_name="matmul",
emit_code=False,
block_sizes=[64, 64, 16],
loop_orders=[[0, 1]],
num_warps=2,
num_stages=4,
indexing="pointer",
l2_grouping=64,
)
@patch.object(_compat, "_supports_tensor_descriptor", lambda: False)
@skipIfXPU("Failed on XPU - https://github.com/pytorch/helion/issues/795")
@skipIfTileIR("TileIR does not support block_ptr indexing")
def test_template_via_closure1(self):
bias = torch.randn([1, 512], device=DEVICE, dtype=HALF_DTYPE)
args = (
torch.randn([512, 512], device=DEVICE, dtype=HALF_DTYPE),
torch.randn([512, 512], device=DEVICE, dtype=HALF_DTYPE),
lambda acc, tile: torch.relu(acc + bias[tile]),
)
check_example(
"matmul",
args,
torch.relu(args[0] @ args[1] + bias),
fn_name="matmul",
emit_code=False,
block_sizes=[64, 64, 16],
loop_orders=[[0, 1]],
num_warps=2,
num_stages=4,
indexing="block_ptr",
l2_grouping=64,
)
@patch.object(_compat, "_supports_tensor_descriptor", lambda: False)
@skipIfTileIR("TileIR does not support block_ptr indexing")
def test_template_via_closure2(self):
args = (
torch.randn([512, 512], device=DEVICE, dtype=HALF_DTYPE),
torch.randn([512, 512], device=DEVICE, dtype=HALF_DTYPE),
lambda x, _: torch.nn.functional.relu(x),
)
check_example(
"matmul",
args,
torch.relu(args[0] @ args[1]),
fn_name="matmul",
emit_code=False,
block_sizes=[64, 64, 16],
loop_orders=[[0, 1]],
num_warps=2,
num_stages=4,
indexing="block_ptr",
l2_grouping=64,
)
@patch.object(_compat, "_supports_tensor_descriptor", lambda: False)
@skipIfTileIR("TileIR does not support block_ptr indexing")
def test_softmax(self):
args = (torch.randn([512, 512], device=DEVICE, dtype=torch.float32),)
check_example(
"softmax",
args,
torch.nn.functional.softmax(*args, dim=1),
emit_code=False,
block_size=1,
num_warps=4,
num_stages=1,
indexing="block_ptr",
)
@patch.object(_compat, "_supports_tensor_descriptor", lambda: False)
@skipIfTileIR("TileIR does not support block_ptr indexing")
def test_softmax_looped(self):
args = (torch.randn([512, 512], device=DEVICE, dtype=torch.float32),)
check_example(
"softmax",
args,
torch.nn.functional.softmax(*args, dim=1),
emit_code=False,
block_size=1,
num_warps=4,
num_stages=1,
indexing="block_ptr",
reduction_loop=32,
)
@patch.object(_compat, "_supports_tensor_descriptor", lambda: False)
@skipIfTileIR("TileIR does not support block_ptr indexing")
def test_softmax_decomposed(self):
args = (torch.randn([512, 512], device=DEVICE, dtype=torch.float32),)
check_example(
"softmax",
args,
torch.nn.functional.softmax(*args, dim=1),
fn_name="softmax_decomposed",
emit_code=False,
block_size=1,
num_warps=4,
num_stages=1,
indexing="block_ptr",
)
def test_softmax_two_pass(self):
args = (torch.randn([512, 512], device=DEVICE, dtype=torch.float32),)
check_example(
"softmax",
args,
torch.nn.functional.softmax(*args, dim=1),
fn_name="softmax_two_pass",
emit_code=False,
)
@patch.object(_compat, "_supports_tensor_descriptor", lambda: False)
@skipIfTileIR("TileIR does not support block_ptr indexing")
def test_softmax_two_pass_block_ptr(self):
args = (torch.randn([512, 512], device=DEVICE, dtype=torch.float32),)
check_example(
"softmax",
args,
torch.nn.functional.softmax(*args, dim=1),
fn_name="softmax_two_pass",
emit_code=False,
block_sizes=[8, 64],
indexing="block_ptr",
)
def test_cross_entropy(self):
n, v = 128, 1000
logits = torch.randn(n, v, device=DEVICE, dtype=torch.float32)
labels = torch.randint(0, v, (n,), device=DEVICE, dtype=LONG_INT_TYPE)
# PyTorch cross_entropy requires Long labels for the reference
expected = torch.nn.functional.cross_entropy(logits, labels.long())
check_example(
"cross_entropy",
(logits, labels),
expected,
)
def test_welford(self):
s, d = 128, 1024
weight = torch.rand((d,), device=DEVICE, dtype=torch.float32)
bias = torch.rand((d,), device=DEVICE, dtype=torch.float32)
x = torch.rand((s, d), device=DEVICE, dtype=torch.float32)
check_example(
"welford",
(weight, bias, x),
torch.nn.functional.layer_norm(
x,
normalized_shape=(x.shape[-1],),
weight=weight,
bias=bias,
eps=1e-05,
),
)
def test_low_mem_dropout(self):
from examples.low_mem_dropout import low_mem_dropout
from examples.low_mem_dropout import low_mem_dropout_bwd
p = 0.25
size = 1024
block_size = 512
seed = 123
seed2 = 456
x = torch.randn(size=(size,)).to(device=DEVICE)
out_fwd = _compile_only(
low_mem_dropout, (p, x, seed), block_sizes=[block_size]
)(p, x, seed)
grad_y = torch.ones_like(x)
bwd = _compile_only(
low_mem_dropout_bwd,
(p, grad_y, seed),
block_sizes=[block_size],
)
grad_x = bwd(p, grad_y, seed)
grad_x2 = bwd(p, grad_y, seed2)
mask_fwd = out_fwd != 0
mask_bwd = grad_x != 0
self.assertTrue(
torch.equal(mask_fwd, mask_bwd),
"Same elements should be dropped in fwd and bwd with the same seed",
)
mask_bwd2 = grad_x2 != 0
self.assertFalse(
torch.equal(mask_bwd, mask_bwd2),
"Different elements should be dropped when using a different seed",
)
check_example(
"low_mem_dropout",
(p, grad_y, seed),
grad_x,
block_sizes=[block_size],
)
@skipIfPallasInterpret(
"65536x1024x1280 GEMM is too slow under CPU interpret -- it exceeds the "
"300s per-test timeout and (thread timeout method) kills the whole job"
)
@xfailIfPallasTpu("precision differences with bf16xint16 operations on pallas")
@skipIfTileIR("precision differences with bf16xint16 operations on tileir")
@skipIfRocm("precision differences with bf16xint16 operations on rocm")
@skipIfXPU("precision differences with bf16xint16 operations on xpu")
def test_bf16xint16(self):
from examples.bf16xint16_gemm import reference_bf16xint16_pytorch
m, k, n = 65536, 1024, 1280
# The CuTe scalar matmul fallback accumulates each bf16xbf16 product in
# full fp32 (it never rounds the per-element products back to bf16), so
# it is *more* accurate than torch's bf16 tensor-core reference. The cute
# output bit-matches a full-precision (IEEE fp32) products matmul cast to
# bf16, so use that as the reference. ``setUpModule`` flips the default
# matmul fp32 precision to TF32, which would make ``torch.matmul`` itself
# lossy, so force IEEE fp32 for the reference computation.
is_cute = _get_backend() == "cute"
def expected(
xt: torch.Tensor, wt: torch.Tensor, transpose: bool
) -> torch.Tensor:
if not is_cute:
return reference_bf16xint16_pytorch(xt, wt, transpose)
if transpose:
x_f32 = xt.to(torch.bfloat16).float()
w_f32 = wt.float()
else:
x_f32 = xt.float()
w_f32 = wt.to(torch.bfloat16).float()
prev = torch.backends.cuda.matmul.fp32_precision
torch.backends.cuda.matmul.fp32_precision = "ieee"
try:
out = torch.matmul(x_f32, w_f32)
finally:
torch.backends.cuda.matmul.fp32_precision = prev
return out.to(torch.bfloat16)
x = torch.randn([m, k], device=DEVICE, dtype=torch.bfloat16)
w = torch.randint(-(2**15), 2**15 - 1, (k, n), device=DEVICE, dtype=torch.int16)
check_example(
"bf16xint16_gemm",
(x, w),
expected(x, w, False),
fn_name="_bf16xint16_gemm",
)
x_int16 = torch.randint(
-(2**15), 2**15 - 1, (m, k), device=DEVICE, dtype=torch.int16
)
w_bf16 = torch.randn([k, n], device=DEVICE, dtype=torch.bfloat16)
check_example(
"bf16xint16_gemm",
(x_int16, w_bf16),
expected(x_int16, w_bf16, True),
fn_name="_int16xbf16_gemm",
)
def test_rms_norm_fwd(self):
args = (
torch.randn([128, 256], device=DEVICE, dtype=HALF_DTYPE),
torch.randn([256], device=DEVICE, dtype=HALF_DTYPE),
1e-5,
)
# Import and use the reference implementation from rms_norm.py
mod = import_path(EXAMPLES_DIR / "rms_norm.py")
expected = mod.rms_norm_pytorch(*args)
check_example(
"rms_norm",
args,
(expected, None), # Expected: (output, 1/rms)
fn_name="rms_norm_fwd",
block_sizes=[16],
indexing="pointer",
)
def test_swiglu_bwd(self):
"""Test backward pass for swiglu."""
x1, x2 = [
torch.randn(1024, device=DEVICE, dtype=torch.bfloat16, requires_grad=True)
for _ in range(2)
]
out = F.silu(x1) * x2
grad_out = torch.randn_like(out)
out.backward(grad_out)
args = (
grad_out,
x1,
x2,
)
check_example(
"swiglu",
args,
(x1.grad, x2.grad),
fn_name="swiglu_bwd",
)
@parametrize("dtype", (torch.float32, HALF_DTYPE))
def test_rms_norm_bwd(self, dtype):
"""Test backward pass for rms norm weight gradient."""
batch_size, dim = 2048, 2048
x = torch.randn([batch_size, dim], device=DEVICE, dtype=dtype)
weight = torch.randn([dim], device=DEVICE, dtype=dtype, requires_grad=True)
grad_out = torch.randn([batch_size, dim], device=DEVICE, dtype=dtype)
eps = 1e-5
# Compute forward pass to get rms
from examples.rms_norm import rms_norm_fwd
# Create configured kernel with explicit config
config = helion.Config(block_size=32, num_warps=4, num_stages=3)
configured_kernel = helion.kernel(rms_norm_fwd.fn, config=config)
y, rms = configured_kernel(x, weight, eps)
# Compute expected gradients with PyTorch
x_torch = x.detach().clone().requires_grad_(True)
weight_torch = weight.detach().clone().requires_grad_(True)
y_torch = torch.nn.functional.rms_norm(x_torch, [dim], weight_torch, eps)
y_torch.backward(grad_out)
# Test the kernel using check_example
args = (
grad_out,
x,
weight,
rms,
)
# rms_norm_bwd_dw returns grad_weight
check_example(
"rms_norm",
args,
(x_torch.grad, weight_torch.grad), # Expected: grad_weight
fn_name="rms_norm_bwd",
block_size=[32, 1],
num_warps=4,
num_stages=3,
rtol=1e-2,
atol=1e-2,
)
def test_embedding_pointers(self):
args = (
torch.randint(0, 1024, [8, 128], device=DEVICE, dtype=torch.int32),
torch.randn([1024, 256], device=DEVICE, dtype=HALF_DTYPE),
)
check_example(
"embedding",
args,
torch.nn.functional.embedding(*args),
block_sizes=[1, 256],
indexing="pointer",
)
@patch.object(_compat, "_supports_tensor_descriptor", lambda: False)
@skipIfTileIR("TileIR does not support block_ptr indexing")
def test_embedding_block_ptr(self):
args = (
torch.randint(0, 1024, [8, 128], device=DEVICE, dtype=torch.int32),
torch.randn([1024, 256], device=DEVICE, dtype=HALF_DTYPE),
)
check_example(
"embedding",
args,
torch.nn.functional.embedding(*args),
block_sizes=[8, 64],
indexing="block_ptr",
pid_type="xyz",
)
@skipIfTileIR("PassManager::run failed")
def test_epilogue_subtiling_residual_gelu(self):
m, k, n = 8192, 8192, 8192
x = torch.randn([m, k], device=DEVICE, dtype=HALF_DTYPE)
w = torch.randn([k, n], device=DEVICE, dtype=HALF_DTYPE)
bias = torch.randn([n], device=DEVICE, dtype=HALF_DTYPE)
residual = torch.randn([m, n], device=DEVICE, dtype=HALF_DTYPE)
acc = x.float() @ w.float()
expected = torch.nn.functional.gelu(
acc * 1.25 + residual.float() * 0.5 + bias.float()
).half()
block_sizes = [16, 16, 16] if _get_backend() == "cute" else [64, 64, 64]
check_example(
"epilogue_subtiling",
(x, w, bias, residual),
expected,
fn_name="matmul_bias_residual_gelu_cast",
block_sizes=block_sizes,
)
@skipIfTileIR("PassManager::run failed")
def test_epilogue_subtiling_gelu_aux(self):
m, k, n = 8192, 8192, 8192
x = torch.randn([m, k], device=DEVICE, dtype=HALF_DTYPE)
w = torch.randn([k, n], device=DEVICE, dtype=HALF_DTYPE)
bias = torch.randn([n], device=DEVICE, dtype=HALF_DTYPE)
acc = x.float() @ w.float()
pre = acc * 1.25 + bias.float()
expected = (
torch.nn.functional.gelu(pre).half(),
pre.half(),
)
block_sizes = [16, 16, 16] if _get_backend() == "cute" else [64, 64, 64]
check_example(
"epilogue_subtiling",
(x, w, bias),
expected,
fn_name="matmul_bias_gelu_aux",
block_sizes=block_sizes,
)
def test_attention_pointer(self):
args = (
torch.randn(1, 32, 512, 64, dtype=torch.float32, device=DEVICE),
torch.randn(1, 32, 512, 64, dtype=torch.float32, device=DEVICE),
torch.randn(1, 32, 512, 64, dtype=torch.float32, device=DEVICE),
)
check_example(
"attention",
args,
(torch.nn.functional.scaled_dot_product_attention(*args), None),
block_sizes=[1, 64, 32],
indexing="pointer",
)
@patch.object(_compat, "_supports_tensor_descriptor", lambda: False)
@skipIfXPU("failure on XPU")
@skipIfTileIR("TileIR does not support block_ptr indexing")
def test_attention_block_pointer(self):
args = (
torch.randn(2, 32, 1024, 64, dtype=HALF_DTYPE, device=DEVICE),
torch.randn(2, 32, 512, 64, dtype=HALF_DTYPE, device=DEVICE),
torch.randn(2, 32, 512, 64, dtype=HALF_DTYPE, device=DEVICE),
)
check_example(
"attention",
args,
(torch.nn.functional.scaled_dot_product_attention(*args), None),
block_sizes=[16, 32, 16],
num_stages=1,
indexing="block_ptr",
)
def test_attention_dynamic(self):
args = (
torch.randn(1, 32, 512, 64, dtype=torch.float32, device=DEVICE),
torch.randn(1, 32, 512, 64, dtype=torch.float32, device=DEVICE),
torch.randn(1, 32, 512, 64, dtype=torch.float32, device=DEVICE),
)
check_example(
"attention",
args,
(torch.nn.functional.scaled_dot_product_attention(*args), None),
fn_name="attention_dynamic",
block_sizes=[1, 64, 32],
)
def test_xsa(self):
args = (
torch.randn(2, 32, 1024, 64, dtype=HALF_DTYPE, device=DEVICE),
torch.randn(2, 32, 1024, 64, dtype=HALF_DTYPE, device=DEVICE),
torch.randn(2, 32, 1024, 64, dtype=HALF_DTYPE, device=DEVICE),
)
mod = import_path(EXAMPLES_DIR / "xsa.py")
check_example(
"xsa",
args,
mod.ref_xsa(*args),
fn_name="xsa_kernel",
block_sizes=[1, 64, 32],
)
def test_xsa_near_zero_v(self):
q = torch.randn(2, 4, 128, 64, dtype=HALF_DTYPE, device=DEVICE)
k = torch.randn_like(q)
v = torch.randn_like(q)
# Force ||V_i|| = 0 < eps so F.normalize's eps-clamp matters.
v[..., 0, :] = 0.0
args = (q, k, v)
mod = import_path(EXAMPLES_DIR / "xsa.py")
check_example(
"xsa",
args,
mod.ref_xsa(*args),
fn_name="xsa_kernel",
block_sizes=[1, 64, 32],
)
def test_concat(self):
args = (
torch.randn(512, 500, device=DEVICE),
torch.randn(512, 512, device=DEVICE),
)
check_example(
"concatenate",
args,
torch.cat(args, dim=1),
fn_name="concat2d_dim1",
)
@xfailIfPallas("BlockSpec tiling failure")
@patch.object(_compat, "_supports_tensor_descriptor", lambda: False)
@skipIfTileIR("TileIR does not support block_ptr indexing")
def test_concat_block_ptr(self):
args = (
torch.randn(222, 100, device=DEVICE),
torch.randn(222, 151, device=DEVICE),
)
check_example(
"concatenate",
args,
torch.cat(args, dim=1),
fn_name="concat2d_dim1",
indexing="block_ptr",
block_sizes=[128, 64],
)
@skipIfPallas("TODO: follow up on timeout due to google-pytorch/torch_tpu@42d10ff")
@xfailIfPallas("BlockSpec tiling failure")
def test_jagged_dense_add(self):
mod = import_path(EXAMPLES_DIR / "jagged_dense_add.py")
args = (
*mod.random_jagged_2d(500, 5000, device=DEVICE),