-
Notifications
You must be signed in to change notification settings - Fork 158
Expand file tree
/
Copy pathtest_pallas.py
More file actions
4594 lines (4038 loc) · 193 KB
/
Copy pathtest_pallas.py
File metadata and controls
4594 lines (4038 loc) · 193 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 ast
import math
import os
import re
from typing import TYPE_CHECKING
from typing import Any
from typing import Callable
import unittest
from examples.geglu import _geglu_pallas as _geglu_pallas_example
from examples.swiglu import _swiglu_fwd_pallas as _swiglu_fwd_pallas_example
import torch
from torch.testing._internal.common_utils import instantiate_parametrized_tests
from torch.testing._internal.common_utils import parametrize
import helion
from helion._testing import DEVICE
from helion._testing import TestCase
from helion._testing import code_and_output
from helion._testing import onlyBackends
from helion._testing import skipIfPallasInterpret
from helion._testing import skipUnlessPallas
from helion._testing import xfailIfPallas
from helion._testing import xfailIfPallasInterpret
from helion._testing import xfailIfPallasTpu
import helion.language as hl
if TYPE_CHECKING:
from helion.autotuner.base_search import PopulationBasedSearch
from helion.autotuner.base_search import PopulationMember
# N-D-tiled Pallas geglu/swiglu (#2725), re-wrapped on the pallas backend so the
# example kernels get real correctness coverage under pallas interpret / TPU CI.
_geglu_pallas = helion.kernel(
_geglu_pallas_example.fn, backend="pallas", static_shapes=True
)
_swiglu_fwd_pallas = helion.kernel(
_swiglu_fwd_pallas_example.fn, backend="pallas", static_shapes=True
)
@helion.kernel(backend="pallas", static_shapes=True)
def add_kernel(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
x, y = torch.broadcast_tensors(x, y)
out = torch.empty_like(x)
for tile in hl.tile(out.size()):
out[tile] = x[tile] + y[tile]
return out
@helion.kernel(backend="pallas", static_shapes=True)
def pallas_mul(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
out = torch.empty_like(x)
for tile in hl.tile(out.size()):
out[tile] = x[tile] * y[tile]
return out
@helion.kernel(backend="pallas", static_shapes=True)
def pallas_relu(x: torch.Tensor) -> torch.Tensor:
out = torch.empty_like(x)
for tile in hl.tile(out.size()):
out[tile] = torch.relu(x[tile])
return out
@helion.kernel(backend="pallas", static_shapes=True)
def pallas_sin(x: torch.Tensor) -> torch.Tensor:
out = torch.empty_like(x)
for tile in hl.tile(out.size()):
out[tile] = torch.sin(x[tile])
return out
@helion.kernel(backend="pallas", static_shapes=True)
def pallas_sigmoid(x: torch.Tensor) -> torch.Tensor:
out = torch.empty_like(x)
for tile in hl.tile(out.size()):
out[tile] = torch.sigmoid(x[tile])
return out
@helion.kernel(backend="pallas", static_shapes=True)
def pallas_pointwise_chain(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
out = torch.empty_like(x)
for tile in hl.tile(out.size()):
out[tile] = torch.sigmoid(torch.sin(torch.relu(x[tile] * y[tile])))
return out
@helion.kernel(backend="pallas", static_shapes=True)
def pallas_affine_scalar_args(
x: torch.Tensor,
scale: int,
bias: float,
) -> torch.Tensor:
out = torch.empty_like(x)
for tile in hl.tile(out.size()):
out[tile] = x[tile] * scale + bias
return out
@helion.kernel(backend="pallas", static_shapes=True)
def pallas_matmul_broadcast_bias(
x: torch.Tensor, y: torch.Tensor, bias: torch.Tensor
) -> torch.Tensor:
m, k = x.size()
_, n = y.size()
out = torch.empty(
[m, n], device=x.device, dtype=torch.promote_types(x.dtype, y.dtype)
)
for tile_m, tile_n in hl.tile([m, n]):
acc = hl.zeros([tile_m, tile_n], dtype=torch.float32)
for tile_k in hl.tile(k):
acc = torch.addmm(acc, x[tile_m, tile_k], y[tile_k, tile_n])
out[tile_m, tile_n] = acc + bias[tile_m, tile_n]
return out
@helion.kernel(backend="pallas", static_shapes=True)
def pallas_matmul_bf16(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
"""bf16 matmul kernel mirroring the perf harness's helion variant.
Used by ``test_pallas_matmul_bf16_no_tiling_seed_covers_large_cubes`` to
exercise the no-tiling ``lax.dot_general`` lowering on bf16 square matmuls.
"""
m, k = x.size()
_, n = y.size()
out = torch.empty(
[m, n], device=x.device, dtype=torch.promote_types(x.dtype, y.dtype)
)
for tile_m, tile_n in hl.tile([m, n]):
acc = hl.zeros([tile_m, tile_n], dtype=torch.float32)
for tile_k in hl.tile(k):
acc = torch.addmm(acc, x[tile_m, tile_k], y[tile_k, tile_n])
out[tile_m, tile_n] = acc
return out
@helion.kernel(backend="pallas", static_shapes=True)
def pallas_bmm(A: torch.Tensor, B: torch.Tensor) -> torch.Tensor:
b, m, k = A.size()
b, k, n = B.size()
out = torch.empty(
[b, m, n], device=A.device, dtype=torch.promote_types(A.dtype, B.dtype)
)
for tile_b, tile_m, tile_n in hl.tile([b, m, n]):
acc = hl.zeros([tile_b, tile_m, tile_n], dtype=torch.float32)
for tile_k in hl.tile(k):
acc = torch.baddbmm(
acc, A[tile_b, tile_m, tile_k], B[tile_b, tile_k, tile_n]
)
out[tile_b, tile_m, tile_n] = acc
return out
@helion.kernel(backend="pallas", static_shapes=True)
def pallas_bmm_subrange_k(
A: torch.Tensor, B: torch.Tensor, k_start: int, k_end: int
) -> torch.Tensor:
"""BMM where the K reduction only covers [k_start, k_end)."""
b, m, k = A.size()
b2, k2, n = B.size()
out = torch.zeros(
[b, m, n], device=A.device, dtype=torch.promote_types(A.dtype, B.dtype)
)
for tile_b, tile_m, tile_n in hl.tile([b, m, n]):
acc = hl.zeros([tile_b, tile_m, tile_n], dtype=torch.float32)
for tile_k in hl.tile(k_start, k_end):
acc = torch.baddbmm(
acc, A[tile_b, tile_m, tile_k], B[tile_b, tile_k, tile_n]
)
out[tile_b, tile_m, tile_n] = acc
return out
@helion.kernel(backend="pallas", static_shapes=True)
def pallas_sum_reduction(x: torch.Tensor) -> torch.Tensor:
n, _m = x.size()
out = torch.empty([n], dtype=x.dtype, device=x.device)
for tile_n in hl.tile(n):
out[tile_n] = x[tile_n, :].sum(-1)
return out
@helion.kernel(backend="pallas", static_shapes=True)
def pallas_sum_reduce_dim0(x: torch.Tensor) -> torch.Tensor:
_n, m = x.size()
out = torch.empty([m], dtype=x.dtype, device=x.device)
for tile_m in hl.tile(m):
out[tile_m] = x[:, tile_m].sum(0)
return out
@helion.kernel(backend="pallas", static_shapes=True)
def pallas_sum_reduce_middle(x: torch.Tensor) -> torch.Tensor:
b, _n, m = x.size()
out = torch.empty([b, m], dtype=x.dtype, device=x.device)
for tile_b, tile_m in hl.tile([b, m]):
out[tile_b, tile_m] = x[tile_b, :, tile_m].sum(1)
return out
@helion.kernel(backend="pallas", static_shapes=True)
def pallas_sum_reduce_multiple(x: torch.Tensor) -> torch.Tensor:
b, _n, _m = x.size()
out = torch.empty([b], dtype=x.dtype, device=x.device)
for tile_b in hl.tile(b):
out[tile_b] = x[tile_b, :, :].sum([0, 1])
return out
@helion.kernel(backend="pallas", static_shapes=True)
def pallas_max_reduction(x: torch.Tensor) -> torch.Tensor:
n, _m = x.size()
out = torch.empty([n], dtype=x.dtype, device=x.device)
for tile_n in hl.tile(n):
out[tile_n] = torch.amax(x[tile_n, :], dim=-1)
return out
@helion.kernel(backend="pallas", static_shapes=True)
def pallas_min_reduction(x: torch.Tensor) -> torch.Tensor:
n, _m = x.size()
out = torch.empty([n], dtype=x.dtype, device=x.device)
for tile_n in hl.tile(n):
out[tile_n] = torch.amin(x[tile_n, :], dim=-1)
return out
@helion.kernel(backend="pallas", static_shapes=True)
def pallas_argmin_reduction(x: torch.Tensor) -> torch.Tensor:
n, _m = x.size()
out = torch.empty([n], dtype=torch.int32, device=x.device)
for tile_n in hl.tile(n):
out[tile_n] = torch.argmin(x[tile_n, :], dim=-1).to(torch.int32)
return out
@helion.kernel(backend="pallas", static_shapes=True)
def pallas_tile_begin_end(x: torch.Tensor) -> torch.Tensor:
out = torch.empty_like(x)
for tile in hl.tile(x.size(0)):
out[tile] = x[tile] + tile.begin - tile.end
return out
@helion.kernel(backend="pallas", static_shapes=True)
def pallas_inplace_add(x: torch.Tensor, y: torch.Tensor) -> None:
for tile in hl.tile(x.size()):
x[tile] = x[tile] + y[tile]
@helion.kernel(backend="pallas", static_shapes=True)
def pallas_add_2d(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
out = torch.empty_like(x)
for tile_m, tile_n in hl.tile(out.size()):
out[tile_m, tile_n] = x[tile_m, tile_n] + y[tile_m, tile_n]
return out
@helion.kernel(backend="pallas", static_shapes=True)
def pallas_arange_add(x: torch.Tensor) -> torch.Tensor:
n, m = x.size()
out = torch.empty_like(x)
for tile_n in hl.tile(n):
offsets = hl.arange(m)
out[tile_n, :] = x[tile_n, :] + offsets[None, :]
return out
@helion.kernel(backend="pallas", static_shapes=True)
def pallas_scatter_store(values: torch.Tensor, indices: torch.Tensor) -> torch.Tensor:
out = torch.zeros_like(values)
for tile_m, tile_n in hl.tile(values.size()):
out[indices[tile_m], tile_n] = values[tile_m, tile_n]
return out
@helion.kernel(backend="pallas", static_shapes=True)
def pallas_inner_loop_add(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
"""Kernel with an outer grid loop and an inner device loop."""
m, n = x.size()
out = torch.empty_like(x)
for tile_m in hl.tile(m):
for tile_n in hl.tile(n):
out[tile_m, tile_n] = x[tile_m, tile_n] + y[tile_m, tile_n]
return out
@helion.kernel(backend="pallas", static_shapes=True)
def pallas_two_pass_reduction(x: torch.Tensor) -> torch.Tensor:
"""Two inner reduction loops over the same dim: reduce to a per-row mean,
then subtract it from each element.
"""
m, n = x.size()
out = torch.empty_like(x)
for tile_m in hl.tile(m):
acc = torch.zeros_like(x[tile_m, 0], dtype=torch.float32)
for tile_n in hl.tile(n):
acc = acc + torch.sum(x[tile_m, tile_n], dim=-1)
mean = (acc / n)[:, None]
for tile_n in hl.tile(n):
out[tile_m, tile_n] = x[tile_m, tile_n] - mean.to(x.dtype)
return out
@helion.kernel(backend="pallas", static_shapes=True)
def pallas_scalar_lookup_in_pipeline(
biases: torch.Tensor, x: torch.Tensor, out: torch.Tensor
) -> torch.Tensor:
"""Per-program scalar lookup from a small 1-D table combined with an
inner pipeline loop. Each of the ``G`` outer programs reads its own
``biases[g]`` and broadcasts it across the inner pipeline body."""
G = biases.size(0)
M = x.size(0)
for g in hl.grid(G):
b = biases[g]
for tile_m in hl.tile(M):
out[tile_m] = x[tile_m] + b
return out
@helion.kernel(backend="pallas", static_shapes=True)
def pallas_inner_loop_add_with_scalar_access(
x: torch.Tensor, y: torch.Tensor
) -> torch.Tensor:
"""Kernel that mixes pipeline-tiled and scalar reads of the same tensor."""
m, n = x.size()
out = torch.empty_like(x)
for tile_m in hl.tile(m):
for tile_n in hl.tile(n):
out[tile_m, tile_n] = x[tile_m, tile_n] + y[tile_m, tile_n] + x[0, 0]
return out
@helion.kernel(backend="pallas", static_shapes=True)
def pallas_jagged_segment_add(x: torch.Tensor, offsets: torch.Tensor) -> torch.Tensor:
"""Outer grid over jagged segments + an inner ``hl.tile(start, end)`` loop
whose begin (``offsets[g]``) is an arbitrary runtime offset. A
block-aligned BlockSpec index can only address starts that are multiples of
the block size, so the emit_pipeline path must slice the segment with a
dynamic ``pl.ds`` (``pl.BoundedSlice`` block)."""
out = torch.empty_like(x)
for g in hl.grid(offsets.size(0) - 1):
start = offsets[g]
end = offsets[g + 1]
for tile in hl.tile(start, end):
out[tile, :] = x[tile, :] + 1.0
return out
@helion.kernel(backend="pallas", static_shapes=True)
def pallas_add_3d(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
"""Kernel with an outer grid loop and a 2D inner device loop."""
b, m, n = x.size()
out = torch.empty_like(x)
for tile_b in hl.tile(b):
for tile_m, tile_n in hl.tile([m, n]):
out[tile_b, tile_m, tile_n] = (
x[tile_b, tile_m, tile_n] + y[tile_b, tile_m, tile_n]
)
return out
@helion.kernel(backend="pallas", static_shapes=True)
def pallas_attention(
q_in: torch.Tensor, k_in: torch.Tensor, v_in: torch.Tensor
) -> torch.Tensor:
m_dim = q_in.size(-2)
n_dim = k_in.size(-2)
assert n_dim == v_in.size(-2)
head_dim = hl.specialize(q_in.size(-1))
assert head_dim == k_in.size(-1) == v_in.size(-1)
q_view = q_in.reshape([-1, m_dim, head_dim])
k_view = k_in.reshape([-1, n_dim, head_dim])
v_view = v_in.reshape([-1, n_dim, head_dim])
out = torch.empty_like(q_view)
sm_scale = 1.0 / math.sqrt(head_dim)
qk_scale = sm_scale * 1.44269504
for tile_b, tile_m in hl.tile([q_view.size(0), m_dim]):
m_i = hl.full([tile_b, tile_m], float("-inf"), dtype=torch.float32)
l_i = torch.full_like(m_i, 1.0)
acc = hl.zeros([tile_b, tile_m, head_dim], dtype=torch.float32)
q = q_view[tile_b, tile_m, :]
for tile_n in hl.tile(v_view.size(1)):
# scaling Q in-loop on-demand reduces spillage, faster than keeping pre-scaled Q
q_scaled = q * qk_scale
k = k_view[tile_b, tile_n, :]
# Keep scores in fp32 to match SDPA tolerances on bf16/fp16 inputs.
# same as hl.dot(q, k, out_dtype=torch.float32)
qk = torch.bmm(q_scaled, k.transpose(1, 2), torch.float32)
m_ij = torch.maximum(m_i, torch.amax(qk, -1))
qk = qk - m_ij[:, :, None]
p = torch.exp2(qk)
l_ij = torch.sum(p, -1)
alpha = torch.exp2(m_i - m_ij)
l_i = l_i * alpha + l_ij
acc = acc * alpha[:, :, None]
v = v_view[tile_b, tile_n, :]
p = p.to(v.dtype)
acc = torch.baddbmm(acc, p, v)
m_i = m_ij
acc = acc / l_i[:, :, None]
out[tile_b, tile_m, :] = acc.to(out.dtype)
return out.view(q_in.size())
@helion.kernel(backend="pallas", static_shapes=True)
def pallas_row_scale_mul(x: torch.Tensor, r: torch.Tensor) -> torch.Tensor:
"""Elementwise multiply ``x [M, N]`` by per-row scale ``r [M, 1]``.
Iterates rows with a two-level tiling: an outer CTA tile and an inner
``hl.tile(begin, end)`` that becomes the per-Pallas-loop-type body.
"""
m, _ = x.shape
out = torch.empty_like(x)
for mb_cta in hl.tile(m, block_size=8):
for mb in hl.tile(mb_cta.begin, mb_cta.end):
out[mb, :] = x[mb, :] * r[mb, :]
return out
@helion.kernel(backend="pallas", static_shapes=True)
def pallas_reduce_non_pow2(x: torch.Tensor) -> torch.Tensor:
"""Softmax over a non-power-of-2 reduction dim.
Uses amax + exp + sum which forces explicit index/mask generation,
exercising the RDIM_SIZE code path.
"""
n, _m = x.size()
out = torch.empty_like(x)
for tile_n in hl.tile(n):
row = x[tile_n, :]
max_val = torch.amax(row, dim=-1, keepdim=True)
exp_val = torch.exp(row - max_val)
out[tile_n, :] = exp_val / torch.sum(exp_val, dim=-1, keepdim=True)
return out
def _cumsum_broadcast_ref(
a: torch.Tensor, b: torch.Tensor, block_k: int = 128
) -> torch.Tensor:
"""Eager reference for cumsum_broadcast kernels.
running[b,m] accumulates row sums; acc[b,m,d] += running[:,:,None].
"""
batch, m, k = a.shape
head_dim = b.shape[-1]
running = torch.zeros(batch, m, dtype=torch.float32, device=a.device)
acc = torch.zeros(batch, m, head_dim, dtype=torch.float32, device=a.device)
for kb in range(0, k, block_k):
chunk = a[:, :, kb : kb + block_k]
running = running + chunk.sum(-1).float()
acc = acc + running[:, :, None]
return acc.to(a.dtype)
def _scaled_bmm_ref(
a: torch.Tensor, b: torch.Tensor, block_k: int = 128
) -> torch.Tensor:
"""Eager reference for scaled_bmm kernels.
m_i[b,m] accumulates row sums; acc[b,m,d] += m_i[:,:,None].
"""
batch, m, k = a.shape
head_dim = b.shape[-1]
m_i = torch.zeros(batch, m, dtype=torch.float32, device=a.device)
acc = torch.zeros(batch, m, head_dim, dtype=torch.float32, device=a.device)
for kb in range(0, k, block_k):
chunk = a[:, :, kb : kb + block_k]
m_i = m_i + chunk.sum(-1).float()
acc = acc + m_i[:, :, None]
return acc.to(a.dtype)
def _running_max_broadcast_ref(
a: torch.Tensor, b: torch.Tensor, block_k: int = 128
) -> torch.Tensor:
"""Eager reference for running_max_broadcast kernel.
scale[b,m] = running max of chunk row maxes; acc[b,m,d] += scale[:,:,None].
"""
batch, m, k = a.shape
head_dim = b.shape[-1]
scale = torch.zeros(batch, m, dtype=torch.float32, device=a.device)
acc = torch.zeros(batch, m, head_dim, dtype=torch.float32, device=a.device)
for kb in range(0, k, block_k):
chunk = a[:, :, kb : kb + block_k]
scale = torch.maximum(scale, chunk.amax(-1).float())
acc = acc + scale[:, :, None]
return acc.to(a.dtype)
@helion.kernel(backend="pallas", static_shapes=True)
def pallas_chunked_add(x: torch.Tensor) -> torch.Tensor:
"""Iterates over chunks of rows; uses tile_k.index + tile_chunk.begin * chunk_size
to compute the global row index (TileIndexWithOffsetPattern)."""
nrows, ncols = x.shape
chunk_size = 64
nchunks = nrows // chunk_size
out = torch.empty_like(x)
for tile_col, tile_chunk in hl.tile([ncols, nchunks], block_size=[None, 1]):
for tile_k in hl.tile(chunk_size, block_size=64):
row = tile_k.index + tile_chunk.begin * chunk_size
out[row, tile_col] = x[row, tile_col] + 1.0
return out
@helion.kernel(backend="pallas", static_shapes=True)
def pallas_rand_add(x: torch.Tensor, seed: int) -> torch.Tensor:
"""Kernel that uses hl.rand to generate random values and add them to x."""
out = torch.empty_like(x)
(m,) = x.size()
for tile_m in hl.tile(m):
out[tile_m] = x[tile_m] + hl.rand([tile_m], seed=seed)
return out
@helion.kernel(backend="pallas", static_shapes=True)
def kernel_output_index_remapping(
x: torch.Tensor, # [batch*heads, seq_len, head_dim]
batch: int,
heads: int,
) -> torch.Tensor:
"""Reshapes a [batch*heads, seq_len, head_dim] tensor to [batch, heads, seq_len, head_dim].
Iterates over the combined batch*heads dimension and the seq_len dimension.
"""
batch_heads, seq_len, head_dim = x.size()
out = torch.empty([batch, heads, seq_len, head_dim], dtype=x.dtype, device=x.device)
for bh in hl.grid(batch_heads):
b = bh // heads
h = bh % heads
for tile_m in hl.tile(seq_len):
out[b, h, tile_m, :] = x[bh, tile_m, :]
return out
@helion.kernel(backend="pallas", static_shapes=True)
def kernel_tile_index_is_blockwise(
x: torch.Tensor,
) -> torch.Tensor:
seq_len = x.size(0)
out = torch.empty_like(x)
for tile_m in hl.tile(seq_len):
out[tile_m.index] = x[tile_m.index] + 1.0
return out
@helion.kernel(backend="pallas", static_shapes=True)
def kernel_tile_begin_plus_offset_is_elementwise(
x: torch.Tensor,
) -> torch.Tensor:
seq_len = x.size(0)
out = torch.zeros_like(x)
for tile_m in hl.tile(seq_len):
out[tile_m.begin + 5] = x[tile_m.begin + 5] + 1.0
return out
@onlyBackends(["triton", "pallas"])
@skipUnlessPallas("JAX/Pallas TPU not available")
class TestPallas(TestCase):
def test_estimate_pallas_vmem_bytes(self) -> None:
"""VMEM OOM: Tests that block sizes and dtypes (fp32, bf16) are correctly estimated."""
# Test 1: float32 (4 bytes per element)
# 3 tensors * 2048 * 4096 * 4 bytes * 2 (multiplier) = ~201.3MB (OOM)
args_f32 = (
torch.randn(2048, 4096, device=DEVICE, dtype=torch.float32),
torch.randn(2048, 4096, device=DEVICE, dtype=torch.float32),
)
with self.assertRaisesRegex(
RuntimeError,
r"Ran out of memory in memory space vmem.*Estimated [0-9.]+MB exceeds",
):
code_and_output(pallas_add_2d, args_f32, block_sizes=[2048, 4096])
# Test 2: bfloat16 (2 bytes per element)
# 3 tensors * 1024 * 4096 * 2 bytes * 2 (multiplier) = ~50.3MB (Passes safely under 64MB)
args_bf16 = (
torch.randn(1024, 4096, device=DEVICE, dtype=torch.bfloat16),
torch.randn(1024, 4096, device=DEVICE, dtype=torch.bfloat16),
)
try:
code_and_output(pallas_add_2d, args_bf16, block_sizes=[1024, 4096])
except Exception as e:
if "Ran out of memory in memory space vmem" in str(e):
self.fail(f"bfloat16 incorrectly threw VMEM OOM: {e}")
@xfailIfPallasInterpret(
"torch.float8_e4m3fn has no JAX dtype mapping in interpret mode; "
"conversion errors before the VMEM check fires"
)
def test_estimate_pallas_vmem_bytes_fp8(self) -> None:
"""VMEM OOM at fp8 (1 byte/element)."""
# 3 tensors * 4096 * 8192 * 1 byte * 2 (multiplier) = ~201.3MB (OOM)
args_fp8 = (
torch.randn(4096, 8192, device=DEVICE, dtype=torch.float32).to(
torch.float8_e4m3fn
),
torch.randn(4096, 8192, device=DEVICE, dtype=torch.float32).to(
torch.float8_e4m3fn
),
)
with self.assertRaisesRegex(
RuntimeError,
r"Ran out of memory in memory space vmem.*Estimated [0-9.]+MB exceeds",
):
code_and_output(pallas_add_2d, args_fp8, block_sizes=[4096, 8192])
def test_output_index_remapping_in_pipeline(self) -> None:
total_elements = 8 * 128 * 128
x = torch.arange(total_elements, device=DEVICE, dtype=torch.bfloat16).view(
8, 128, 128
)
batch = 2
heads = 4
code, result = code_and_output(
kernel_output_index_remapping,
(x, batch, heads),
block_sizes=[32],
pallas_loop_type="emit_pipeline",
)
expected = x.reshape(batch, heads, 128, 128)
with self.subTest(name="correctness"):
torch.testing.assert_close(result, expected)
with self.subTest(name="pipeline_emit"):
self.assertIn("pltpu.emit_pipeline", code)
with self.subTest(name="shrunken_blockspec"):
self.assertIn(
"pl.BlockSpec((1, 1, _BLOCK_SIZE_1, 128), "
"lambda _j: (offset_0 // heads, offset_0 % heads, _j, 0)",
code,
)
with self.subTest(name="body_vmem_indices"):
self.assertIn("out_vmem[0, 0, :, :]", code)
def test_output_index_remapping_in_fori_loop(self) -> None:
total_elements = 8 * 128 * 128
x = torch.arange(total_elements, device=DEVICE, dtype=torch.bfloat16).view(
8, 128, 128
)
batch = 2
heads = 4
code, result = code_and_output(
kernel_output_index_remapping,
(x, batch, heads),
block_sizes=[32],
pallas_loop_type="fori_loop",
)
with self.subTest(name="correctness"):
expected = x.reshape(batch, heads, 128, 128)
torch.testing.assert_close(result, expected)
with self.subTest(name="fori_loop_emit"):
self.assertIn("jax.lax.fori_loop", code)
with self.subTest(name="body_vmem_indices"):
self.assertIn("out_buf[0, 0, :, :]", code)
with self.subTest(name="vmem_shape_allocation"):
self.assertIn("((1, 1, 32, 128), 'jnp.bfloat16', 'vmem')", code)
with self.subTest(name="hbm_dma_slices"):
self.assertIn("pl.ds(symnode_0, 1), pl.ds(symnode_1, 1)", code)
def test_pipeline_kernel_tile_index_is_blockwise(self) -> None:
x = torch.arange(1024, device=DEVICE, dtype=torch.float32)
code, result = code_and_output(
kernel_tile_index_is_blockwise,
(x,),
block_sizes=[256],
pallas_loop_type="emit_pipeline",
)
torch.testing.assert_close(result, x + 1.0)
self.assertNotIn("pltpu.emit_pipeline", code)
self.assertIn("out[:]", code)
def test_pipeline_kernel_tile_begin_plus_offset_is_elementwise(self) -> None:
x = torch.arange(1024, device=DEVICE, dtype=torch.float32)
code, result = code_and_output(
kernel_tile_begin_plus_offset_is_elementwise,
(x,),
block_sizes=[256],
pallas_loop_type="emit_pipeline",
)
expected = torch.zeros_like(x)
expected[5::256] = x[5::256] + 1.0
torch.testing.assert_close(result, expected)
self.assertNotIn("pltpu.emit_pipeline", code)
self.assertIn("_smem_arg_indices", code)
self.assertIn("out[5]", code)
def test_add_1d(self) -> None:
args = (torch.randn(1024, device=DEVICE), torch.randn(1024, device=DEVICE))
code, result = code_and_output(add_kernel, args, block_size=256)
torch.testing.assert_close(result, args[0] + args[1])
def test_add_large(self) -> None:
args = (torch.randn(4096, device=DEVICE), torch.randn(4096, device=DEVICE))
code, result = code_and_output(add_kernel, args, block_size=512)
torch.testing.assert_close(result, args[0] + args[1])
def test_geglu_pallas_nd(self) -> None:
# N-D-tiled GEGLU (#2725): correctness on the pallas backend.
a = torch.randn(64, 128, device=DEVICE, dtype=torch.float32)
b = torch.randn(64, 128, device=DEVICE, dtype=torch.float32)
code, result = code_and_output(_geglu_pallas, (a, b), block_sizes=[16, 32])
expected = torch.nn.functional.gelu(a, approximate="tanh") * b
torch.testing.assert_close(result, expected, rtol=1e-3, atol=1e-3)
def test_swiglu_pallas_nd(self) -> None:
# N-D-tiled SwiGLU (#2725): correctness on the pallas backend.
a = torch.randn(64, 128, device=DEVICE, dtype=torch.float32)
b = torch.randn(64, 128, device=DEVICE, dtype=torch.float32)
code, result = code_and_output(_swiglu_fwd_pallas, (a, b), block_sizes=[16, 32])
expected = torch.nn.functional.silu(a) * b
torch.testing.assert_close(result, expected, rtol=1e-3, atol=1e-3)
def test_store_slice_1d(self) -> None:
"""Store value sliced when block_size > tensor dim (1D)."""
@helion.kernel(backend="pallas", static_shapes=True)
def fill_kernel(x: torch.Tensor) -> torch.Tensor:
out = torch.empty_like(x)
for tile in hl.tile(x.size(0)):
out[tile] = hl.full([tile], 1.0, dtype=x.dtype)
return out
x = torch.randn(1024, device=DEVICE, dtype=torch.float32)
code, result = code_and_output(fill_kernel, (x,), block_size=4096)
self.assertIn("[:1024]", code)
torch.testing.assert_close(result, torch.ones_like(x))
def test_store_slice_2d(self) -> None:
"""Store value sliced on the dim where block_size > tensor dim (2D)."""
@helion.kernel(backend="pallas", static_shapes=True)
def fill_2d(x: torch.Tensor) -> torch.Tensor:
m, n = x.size()
out = torch.empty_like(x)
for tile_m, tile_n in hl.tile([m, n]):
out[tile_m, tile_n] = hl.full([tile_m, tile_n], 1.0, dtype=x.dtype)
return out
# 100 < 128, 256 == 256 → only dim 0 needs slicing
x = torch.randn(100, 256, device=DEVICE, dtype=torch.float32)
code, result = code_and_output(fill_2d, (x,), block_size=[128, 256])
self.assertIn("[:100, :]", code)
torch.testing.assert_close(result, torch.ones_like(x))
# 100 < 128, 200 < 256 → both dims need slicing
x2 = torch.randn(100, 200, device=DEVICE, dtype=torch.float32)
code2, result2 = code_and_output(fill_2d, (x2,), block_size=[128, 256])
self.assertIn("[:100, :200]", code2)
torch.testing.assert_close(result2, torch.ones_like(x2))
def test_store_slice_skips_pl_ds_dim(self) -> None:
"""Store value is not sliced on dimensions indexed with pl.ds()."""
@helion.kernel(backend="pallas", static_shapes=True)
def fill_inner_loop(x: torch.Tensor) -> torch.Tensor:
m, n = x.size()
out = torch.empty_like(x)
for tile_m in hl.tile(m):
for tile_n in hl.tile(n):
out[tile_m, tile_n] = hl.full([tile_m, tile_n], 1.0, dtype=x.dtype)
return out
x = torch.randn(64, 32, device=DEVICE, dtype=torch.float32)
code, result = code_and_output(
fill_inner_loop,
(x,),
block_size=[128, 64],
pallas_loop_type="fori_loop",
)
self.assertIn("pl.ds(", code)
self.assertIn("[:64, :]", code)
self.assertNotIn("[:64, :32]", code)
torch.testing.assert_close(result, torch.ones_like(x))
def test_add_does_not_donate_inputs(self) -> None:
"""Verify that read-only inputs are not donated by the kernel.
Regression test: the codegen used to mark all tensor args as outputs
(including read-only inputs rebound by broadcast_tensors), causing JAX
to donate their buffers. Any external reference to the inputs would
then fail with "Buffer has been deleted or donated".
"""
x = torch.randn(1024, device=DEVICE, dtype=torch.float32)
y = torch.randn(1024, device=DEVICE, dtype=torch.float32)
# Save copies to compare against after the kernel call.
x_copy = x.clone()
y_copy = y.clone()
code, result = code_and_output(add_kernel, (x, y), block_size=256)
torch.testing.assert_close(result, x_copy + y_copy)
# Only the output (index 2) should be in _output_indices, not inputs.
self.assertIn("_output_indices=[2]", code)
# The original inputs must still be accessible (not donated).
torch.testing.assert_close(x, x_copy)
torch.testing.assert_close(y, y_copy)
def test_wrapper_gather_before_loop_is_read_only_input(self) -> None:
"""A tensor created by eager wrapper code and only read by Pallas is not output."""
@helion.kernel(backend="pallas", static_shapes=True)
def gather_then_tile(x: torch.Tensor, idx: torch.Tensor) -> torch.Tensor:
gathered = x[idx]
out = torch.empty_like(gathered)
for tile in hl.tile(out.size()):
out[tile] = gathered[tile] + 1.0
return out
x = torch.randn(128, device=DEVICE, dtype=torch.float32)
idx = torch.arange(127, -1, -1, device=DEVICE, dtype=torch.int32)
code, result = code_and_output(gather_then_tile, (x, idx), block_sizes=[128])
torch.testing.assert_close(result, x[idx] + 1.0)
self.assertIn("_output_indices=[1]", code)
self.assertIn("_inplace_indices=[]", code)
def test_wrapper_gather_and_scatter_around_loop(self) -> None:
"""Eager prologue gather and epilogue scatter compose around Pallas."""
@helion.kernel(
backend="pallas",
static_shapes=True,
ignore_warnings=[helion.exc.TensorOperationInWrapper],
)
def gather_tile_scatter(x: torch.Tensor, idx: torch.Tensor) -> torch.Tensor:
gathered = x[idx]
out = torch.empty_like(gathered)
for tile in hl.tile(out.size()):
out[tile] = gathered[tile] + 1.0
scattered = torch.empty_like(out)
scattered[idx] = out
return scattered
x = torch.randn(128, device=DEVICE, dtype=torch.float32)
idx = torch.arange(127, -1, -1, device=DEVICE, dtype=torch.int32)
code, result = code_and_output(gather_tile_scatter, (x, idx), block_sizes=[128])
expected = torch.empty_like(x)
expected[idx] = x[idx] + 1.0
torch.testing.assert_close(result, expected)
self.assertIn("_inplace_indices=[]", code)
def test_add_2d(self) -> None:
args = (
torch.randn(64, 512, device=DEVICE, dtype=torch.float32),
torch.randn(64, 512, device=DEVICE, dtype=torch.float32),
)
code, result = code_and_output(pallas_add_2d, args, block_sizes=[8, 512])
torch.testing.assert_close(result, args[0] + args[1])
def test_arange(self) -> None:
x = torch.randn(8, 64, device=DEVICE, dtype=torch.float32)
offsets = torch.arange(64, device=DEVICE, dtype=torch.int32).float()
code, result = code_and_output(pallas_arange_add, (x,), block_size=8)
torch.testing.assert_close(result, x + offsets[None, :])
self.assertIn("jnp.arange", code)
def test_bool_view_expand_where(self) -> None:
@helion.kernel(backend="pallas", static_shapes=True)
def pallas_bool_view_expand_where(x: torch.Tensor) -> torch.Tensor:
m, n = x.size()
out = torch.empty_like(x)
for tile_m, tile_n in hl.tile([m, n]):
mask = x[tile_m, 0] > 0
mask_2d = mask.view(tile_m.block_size, 1).expand(
tile_m.block_size, tile_n.block_size
)
out[tile_m, tile_n] = torch.where(mask_2d, x[tile_m, tile_n], 0.0)
return out
x = torch.randn(16, 128, device=DEVICE, dtype=torch.float32)
code, result = code_and_output(
pallas_bool_view_expand_where,
(x,),
block_sizes=[16, 128],
)
expected = torch.where(x[:, :1] > 0, x, torch.zeros_like(x))
torch.testing.assert_close(result, expected)
self.assertIn("astype(jnp.int32)", code)
def test_indirect_gather_with_tiled_dim(self) -> None:
@helion.kernel(backend="pallas", static_shapes=True)
def pallas_indirect_gather_with_tiled_dim(
values: torch.Tensor, indices: torch.Tensor
) -> torch.Tensor:
out = torch.empty([indices.size(0), values.size(1)], device=values.device)
for tile_m, tile_n in hl.tile(out.size()):
out[tile_m, tile_n] = values[indices[tile_m], tile_n]
return out
values = torch.randn(16, 8, device=DEVICE, dtype=torch.float32)
indices = torch.randperm(16, device=DEVICE).to(torch.int32)
code, result = code_and_output(
pallas_indirect_gather_with_tiled_dim,
(values, indices),
block_sizes=[4, 4],
)
torch.testing.assert_close(result, values[indices.to(torch.int64), :])
self.assertIn("values[:,", code)
def test_scatter_store(self) -> None:
for dtype in (torch.float32, torch.bfloat16):
with self.subTest(dtype=dtype):
values = torch.randn(16, 8, device=DEVICE, dtype=dtype)
indices = torch.randperm(16, device=DEVICE).to(torch.int32)
code, result = code_and_output(
pallas_scatter_store, (values, indices), block_sizes=[4, 4]
)
expected = torch.zeros_like(values)
expected[indices.to(torch.int64)] = values
torch.testing.assert_close(result, expected)
self.assertIn("one_hot", code)
self.assertIn("jnp.triu", code)
self.assertIn("jnp.eye", code)
self.assertIn("jnp.swapaxes", code)
self.assertIn("jnp.ones_like", code)
self.assertIn("jnp.where", code)
self.assertIn("dot_general", code)
def test_scatter_store_duplicate_indices(self) -> None:
values = torch.randn(16, 8, device=DEVICE, dtype=torch.float32)
indices = torch.tensor(
[0, 1, 1, 2, 4, 4, 4, 8, 8, 9, 10, 10, 12, 13, 14, 14],
device=DEVICE,
dtype=torch.int32,
)
code, result = code_and_output(
pallas_scatter_store, (values, indices), block_sizes=[16, 8]
)
expected = torch.zeros_like(values)
expected[indices.to(torch.int64)] = values
torch.testing.assert_close(result, expected)
def test_tensor_index_atomic_add_raises(self) -> None:
@helion.kernel(backend="pallas", static_shapes=True)
def atomic_add_tensor_index(
values: torch.Tensor, indices: torch.Tensor
) -> torch.Tensor:
out = torch.zeros_like(values)
for tile in hl.tile(values.size(0)):
hl.atomic_add(out, [indices[tile]], values[tile])
return out
values = torch.randn(16, device=DEVICE, dtype=torch.float32)
indices = torch.randperm(16, device=DEVICE).to(torch.int32)
with self.assertRaisesRegex(
NotImplementedError,
"tensor-indexed memory op is not supported for op=atomic_add",
):
code_and_output(
atomic_add_tensor_index,
(values, indices),
block_size=16,
)
def test_scatter_store_multiple_tensor_indices_raises(self) -> None:
@helion.kernel(backend="pallas", static_shapes=True)
def scatter_store_multiple_tensor_indices(
values: torch.Tensor, row_indices: torch.Tensor, col_indices: torch.Tensor
) -> torch.Tensor:
out = torch.zeros(
[values.size(0), values.size(0)],
dtype=values.dtype,
device=values.device,
)
for tile in hl.tile(values.size(0)):
out[row_indices[tile], col_indices[tile]] = values[tile, tile]
return out
values = torch.randn(16, 16, device=DEVICE, dtype=torch.float32)
row_indices = torch.randperm(16, device=DEVICE).to(torch.int32)
col_indices = torch.randperm(16, device=DEVICE).to(torch.int32)
with self.assertRaisesRegex(
NotImplementedError,
"multiple indirect dims are not supported",
):
code_and_output(
scatter_store_multiple_tensor_indices,
(values, row_indices, col_indices),
block_size=16,
)