-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
pallas_test.py
1756 lines (1557 loc) · 60.6 KB
/
pallas_test.py
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
# Copyright 2023 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import functools
import itertools
import os
import unittest
os.environ["XLA_PYTHON_CLIENT_MEM_FRACTION"] = "0.5"
from absl.testing import absltest
from absl.testing import parameterized
import jax
from jax import lax
from jax import random
from jax._src import config
from jax._src import linear_util as lu
from jax._src import test_util as jtu
from jax._src import state
from jax._src.lax.control_flow.for_loop import for_loop
from jax._src.pallas.pallas_call import _trace_to_jaxpr
from jax.interpreters import partial_eval as pe
import jax.numpy as jnp
from jax.experimental import pallas as pl
from jax.experimental.pallas.ops import attention
from jax.experimental.pallas.ops import layer_norm
from jax.experimental.pallas.ops import rms_norm
from jax.experimental.pallas.ops import softmax
try:
from jax._src.pallas.triton.lowering import compile_jaxpr
from jax.experimental.pallas import gpu as plgpu
except ModuleNotFoundError:
compile_jaxpr = None
import numpy as np
# TODO(sharadmv): Update signatures of pallas_call to correct inputs/outputs.
# pylint: disable=no-value-for-parameter
config.update("jax_traceback_filtering", "off")
config.parse_flags_with_absl()
@functools.partial(jax.jit, static_argnames=["bm", "bn", "gm", "bk",
"interpret", "debug"])
def matmul(x, y, *, bm, bn, gm, bk, interpret, debug=False):
m, n, k = x.shape[0], y.shape[1], x.shape[1]
@functools.partial(
pl.pallas_call, out_shape=jax.ShapeDtypeStruct((m, n), jnp.float32),
interpret=interpret,
debug=debug,
grid=pl.cdiv(m, bm) * pl.cdiv(n, bn))
def matmul_kernel(x_ref, y_ref, o_ref):
pid = pl.program_id(axis=0)
num_pid_m = m // bm
num_pid_n = n // bn
num_pid_in_group = gm * num_pid_n
group_id = lax.div(pid, num_pid_in_group)
first_pid_m = group_id * gm
group_size_m = jnp.minimum(num_pid_m - first_pid_m, gm)
pid_m = first_pid_m + lax.rem(pid, group_size_m)
pid_n = lax.div(lax.rem(pid, num_pid_in_group), group_size_m)
idx_m = pid_m * bm + jnp.arange(bm)
idx_n = pid_n * bn + jnp.arange(bn)
idx_m = pl.max_contiguous(pl.multiple_of(idx_m, bm), bm)
idx_n = pl.max_contiguous(pl.multiple_of(idx_n, bn), bn)
acc = jnp.zeros((bm, bn), dtype=jnp.float32)
def body(i, acc_ref):
idx_k = i * bk + jnp.arange(bk)
x_idx = (
jax.lax.broadcast_in_dim(idx_m, (bm, bk), (0,)),
jax.lax.broadcast_in_dim(idx_k, (bm, bk), (1,)))
y_idx = (
jax.lax.broadcast_in_dim(idx_k, (bk, bn), (0,)),
jax.lax.broadcast_in_dim(idx_n, (bk, bn), (1,)))
x_block, y_block = x_ref[x_idx], y_ref[y_idx]
out = pl.dot(x_block, y_block)
acc_ref[:, :] += out
acc = for_loop(k // bk, body, acc).astype(o_ref.dtype)
o_idx = (
jax.lax.broadcast_in_dim(idx_m, (bm, bn), (0,)),
jax.lax.broadcast_in_dim(idx_n, (bm, bn), (1,)),
)
o_ref[o_idx] = acc
return matmul_kernel(x, y)
@functools.partial(jax.jit, static_argnames=["bm", "bn", "bk",
"interpret", "debug"])
def matmul_block_spec(x, y, *, bm, bn, bk, interpret, debug=False):
m, n, k = x.shape[0], y.shape[1], x.shape[1]
@functools.partial(
pl.pallas_call, out_shape=jax.ShapeDtypeStruct((m, n), jnp.float32),
interpret=interpret,
debug=debug,
in_specs=[
pl.BlockSpec(lambda i, _: (i, 0), (bm, x.shape[1])),
pl.BlockSpec(lambda _, j: (0, j), (y.shape[0], bn))
],
out_specs=pl.BlockSpec(lambda i, j: (i, j), (bm, bn)),
grid=(pl.cdiv(m, bm), pl.cdiv(n, bn)))
def matmul_kernel(x_ref, y_ref, o_ref):
acc = jnp.zeros(o_ref.shape, dtype=jnp.float32)
def body(i, acc_ref):
x_block = pl.load(x_ref, (slice(None), pl.ds(i * bk, bk)))
y_block = pl.load(y_ref, (pl.ds(i * bk, bk), slice(None)))
acc_ref[:, :] += pl.dot(x_block, y_block)
acc = for_loop(k // bk, body, acc).astype(o_ref.dtype)
o_ref[:, :] = acc
return matmul_kernel(x, y)
class PallasTest(parameterized.TestCase):
INTERPRET = False
def setUp(self):
if not jtu.test_device_matches(["gpu"]):
self.skipTest("Only works on GPU")
try:
import triton # noqa: F401
except ImportError:
self.skipTest("Triton is not installed. Skipping PallasTest.")
super().setUp()
if compile_jaxpr:
compile_jaxpr.cache_clear()
_trace_to_jaxpr.cache_clear()
def pallas_call(self, *args, **kwargs):
return pl.pallas_call(*args, **kwargs, interpret=self.INTERPRET)
class PallasCallTest(PallasTest):
def test_add_one(self):
@functools.partial(
self.pallas_call, out_shape=jax.ShapeDtypeStruct((), jnp.float32))
def add_one(x_ref, o_ref):
o_ref[()] = x_ref[()] + 1.
x = 0.
self.assertEqual(add_one(x), 1.)
def test_add_singleton_vector(self):
@functools.partial(
self.pallas_call, out_shape=jax.ShapeDtypeStruct((1,), jnp.float32),
grid=1)
def add_one(x_ref, o_ref):
o_ref[0] = x_ref[0] + 1.
x = jnp.array([0.], jnp.float32)
np.testing.assert_allclose(add_one(x), jnp.array([1.], jnp.float32))
def test_add_vector_block_spec(self):
@functools.partial(
self.pallas_call, out_shape=jax.ShapeDtypeStruct((8,), jnp.int32),
in_specs=[pl.BlockSpec(lambda i: i, (1,))],
out_specs=pl.BlockSpec(lambda i: i, (1,)),
grid=8, debug=False)
def add_one(x_ref, o_ref):
o_ref[0] = x_ref[0] + 1
np.testing.assert_allclose(add_one(jnp.arange(8)), jnp.arange(8) + 1)
def test_add_matrix_block_spec(self):
@functools.partial(
self.pallas_call, out_shape=jax.ShapeDtypeStruct((8, 8), jnp.int32),
in_specs=[pl.BlockSpec(lambda i, j: (i, j), (2, 2))],
out_specs=pl.BlockSpec(lambda i, j: (i, j), (2, 2)),
grid=(4, 4))
def add_one(x_ref, o_ref):
o_ref[:, :] = x_ref[:, :] + 1
x = jnp.arange(64).reshape((8, 8))
np.testing.assert_allclose(add_one(x), x + 1)
def test_vector_indexing(self):
@functools.partial(
self.pallas_call, out_shape=jax.ShapeDtypeStruct((), jnp.float32),
grid=1)
def index(x_ref, i_ref, o_ref):
o_ref[()] = x_ref[i_ref[()]]
x = jnp.arange(5.)
for i in range(5):
np.testing.assert_allclose(index(x, i), x[i])
def test_vector_slicing(self):
@functools.partial(
self.pallas_call, out_shape=jax.ShapeDtypeStruct((2,), jnp.float32),
grid=1)
def index(x_ref, idx_ref, o_ref):
idx = idx_ref[()]
o_ref[:] = x_ref[idx]
x = jnp.arange(5.)
for i in range(4):
idx = jnp.arange(i, i + 2)
np.testing.assert_allclose(index(x, idx), x[idx])
def test_where_broadcasting(self):
@functools.partial(
self.pallas_call,
out_shape=jax.ShapeDtypeStruct((4, 2, 2), jnp.float32),
grid=1)
def copyitem(x_ref, in_idx_ref, out_idx_ref, o_ref):
mask = (jnp.arange(o_ref.shape[0]) == out_idx_ref[()])
o_ref[...] = jnp.where(jax.lax.broadcast_in_dim(mask, (4, 2, 2), (0,)),
x_ref[in_idx_ref[()]], 0)
x = jnp.arange(7 * 2 * 2.).reshape(7, 2, 2)
for ii in range(7):
for oi in range(4):
out = copyitem(x, ii, oi)
self.assertEqual((4, 2, 2), out.shape)
np.testing.assert_allclose(out[:oi], jnp.zeros_like(out[:oi]))
np.testing.assert_allclose(out[oi], x[ii])
np.testing.assert_allclose(out[oi + 1:], jnp.zeros_like(out[oi + 1:]))
@parameterized.parameters(*[
((), (2,), ()),
((1,), (2,), (0,)),
((1, 1), (2, 2), (0, 1)),
((), (2, 2), ()),
])
def test_broadcast_in_dim(self, in_shape, out_shape, dims):
@functools.partial(
self.pallas_call, out_shape=jax.ShapeDtypeStruct(out_shape, jnp.float32),
grid=1)
def f(x_ref, o_ref):
x = x_ref[...]
o_ref[...] = jax.lax.broadcast_in_dim(x, out_shape, dims)
x = jnp.arange(int(np.prod(in_shape)), dtype=jnp.float32).reshape(in_shape)
expected = jax.lax.broadcast_in_dim(x, out_shape, dims)
np.testing.assert_allclose(f(x), expected)
@parameterized.parameters(*[
((2, 4), (8,)),
((2, 4), (8, 1)),
((2, 4), (1, 8)),
((64,), (32, 2)),
])
def test_reshape(self, in_shape, out_shape):
# TODO(sharadmv): re-enable when `reshape` works again
self.skipTest("Reshape not yet supported in Triton-MLIR")
@functools.partial(
self.pallas_call, out_shape=jax.ShapeDtypeStruct(out_shape, jnp.float32),
grid=1)
def f(x_ref, o_ref):
o_ref[...] = x_ref[...].reshape(out_shape)
x = jnp.arange(int(np.prod(in_shape)), dtype=jnp.float32).reshape(in_shape)
expected = x.reshape(out_shape)
np.testing.assert_allclose(f(x), expected)
@parameterized.parameters(*[
((), (1,)),
((), (1, 1)),
((2, 4), (2, 4)),
((2, 4), (2, 4, 1)),
((2, 4, 1), (2, 4)),
((2, 4), (1, 2, 4)),
((1, 2, 4), (2, 4)),
((2, 4), (2, 1, 4)),
((1, 2, 1, 4, 1), (2, 4)),
((2, 4,), (1, 2, 1, 4)),
((2, 4,), (1, 2, 4, 1)),
((1, 2, 4, 1), (1, 2, 1, 4, 1)),
])
def test_reshape_noop_or_singleton_dims(self, in_shape, out_shape):
@functools.partial(
self.pallas_call, out_shape=jax.ShapeDtypeStruct(out_shape, jnp.float32),
grid=1)
def f(x_ref, o_ref):
o_ref[...] = x_ref[...].reshape(out_shape)
x = jnp.arange(int(np.prod(in_shape)), dtype=jnp.float32).reshape(in_shape)
expected = x.reshape(out_shape)
np.testing.assert_allclose(f(x), expected)
@parameterized.named_parameters(*[
(f"m_{m}_n_{n}_k_{k}_dtype_{dtype}_bm_{block_size_m}_"
f"bn_{block_size_n}_bk_{block_size_k}_gm_{group_size_m}", m, n, k, dtype,
block_size_m, block_size_n, block_size_k, group_size_m)
for m in [512, 1024]
for k in [512]
for n in [512, 1024]
for dtype in ["float32", "float16"]
for block_size_m in [64, 128]
for block_size_n in [128, 256]
for block_size_k in [32]
for group_size_m in [8]
if block_size_m <= m and block_size_n <= n and block_size_k <= k
])
def test_matmul(self, m, n, k, dtype, bm, bn, bk, gm):
if plgpu.get_compute_capability(0) < 70:
raise unittest.SkipTest(
"Matmul only works on GPUs with capability >= sm70")
if (plgpu.get_compute_capability(0) <= 75
and (bm > 128 or bn > 128 or bk > 32)):
raise unittest.SkipTest("Block sizes too big for sm70.")
k1, k2 = random.split(random.PRNGKey(0))
x = random.normal(k1, (m, k), dtype=dtype)
y = random.normal(k2, (k, n), dtype=dtype)
out, expected = matmul(x, y, bm=bm, bn=bn, bk=bk, gm=gm,
interpret=self.INTERPRET), jnp.matmul(x, y)
np.testing.assert_allclose(out, expected, atol=0.05, rtol=0.05)
@parameterized.named_parameters(*[
(f"m_{m}_n_{n}_k_{k}_dtype_{dtype}_bm_{block_size_m}_"
f"bn_{block_size_n}_bk_{block_size_k}", m, n, k, dtype,
block_size_m, block_size_n, block_size_k)
for m in [512, 1024]
for k in [512]
for n in [512, 1024]
for dtype in ["float32", "float16"]
for block_size_m in [64, 128]
for block_size_n in [128, 256]
for block_size_k in [32]
if block_size_m <= m and block_size_n <= n and block_size_k <= k
])
def test_matmul_block_spec(self, m, n, k, dtype, bm, bn, bk):
if plgpu.get_compute_capability(0) < 70:
raise unittest.SkipTest(
"Matmul only works on GPUs with capability >= sm70")
if (plgpu.get_compute_capability(0) <= 75
and (bm > 128 or bn > 128 or bk > 32)):
raise unittest.SkipTest("Block sizes too big for sm70.")
k1, k2 = random.split(random.PRNGKey(0))
x = random.normal(k1, (m, k), dtype=dtype)
y = random.normal(k2, (k, n), dtype=dtype)
out, expected = matmul_block_spec(x, y, bm=bm, bn=bn, bk=bk,
interpret=self.INTERPRET), jnp.matmul(x, y)
np.testing.assert_allclose(out, expected, atol=0.05, rtol=0.05)
@parameterized.named_parameters(*(
dict(testcase_name=f"{size}_{dtype}", size=size, dtype=dtype)
for size in [16, 32, 64]
for dtype in ["float32", "float16"]
))
def test_dot(self, size, dtype):
if plgpu.get_compute_capability(0) < 70:
raise unittest.SkipTest(
"Matmul only works on GPUs with capability >= sm70")
@functools.partial(
self.pallas_call,
out_shape=jax.ShapeDtypeStruct((size, size), dtype),
grid=1)
def dot(x_ref, y_ref, o_ref):
x = x_ref[:, :]
y = y_ref[:, :]
o_ref[:, :] = pl.dot(x, y).astype(o_ref.dtype)
k1, k2 = random.split(random.PRNGKey(0))
x = random.normal(k1, (size, size), dtype=dtype)
y = random.normal(k2, (size, size), dtype=dtype)
out, expected = dot(x, y), jnp.dot(x, y)
np.testing.assert_allclose(out, expected, atol=0.05, rtol=0.05)
@parameterized.named_parameters(*(
dict(testcase_name=f"{batch_size}_{size}_{block_size}_{dtype}",
batch_size=batch_size, size=size, block_size=block_size, dtype=dtype)
for batch_size in [1, 2, 4, 23]
for size in [1, 2, 129, 255, 256]
for block_size in [1, 2, 32, 64, 128, 256]
for dtype in ["float32"]
if size < block_size
))
def test_softmax(self, batch_size, size, block_size, dtype):
@functools.partial(self.pallas_call,
out_shape=jax.ShapeDtypeStruct((batch_size, size), dtype),
grid=batch_size)
def softmax(x_ref, o_ref):
row_idx = pl.program_id(0)
x_idx = jnp.arange(block_size)
row_idxs = (row_idx, x_idx)
mask = x_idx < x_ref.shape[1]
row = pl.load(x_ref, row_idxs, mask=mask, other=-float("inf"))
row_minus_max = row - jnp.max(row, axis=0)
numerator = jnp.exp(row_minus_max)
denominator = jnp.sum(numerator, axis=0)
softmax_output = numerator / denominator
pl.store(o_ref, row_idxs, softmax_output, mask=mask)
key = random.PRNGKey(0)
x = random.normal(key, [batch_size, size], dtype=dtype)
np.testing.assert_allclose(softmax(x), jax.nn.softmax(x, axis=-1),
atol=1e-5, rtol=1e-5)
@parameterized.parameters(*(
(size, block_size)
for size in [1, 2, 64, 129, 1021]
for block_size in [1, 2, 32, 64, 128]
))
def test_masked_load_store(self, size, block_size):
@functools.partial(self.pallas_call,
out_shape=(
jax.ShapeDtypeStruct((size,), jnp.float32)
),
grid=pl.cdiv(size, block_size))
def add_one(x_ref, o_ref):
idx = pl.program_id(0) * block_size + jnp.arange(block_size)
mask = idx < x_ref.shape[0]
x = pl.load(x_ref, (idx,), mask=mask)
pl.store(o_ref, (idx,), x + 1., mask=mask)
key = random.PRNGKey(0)
x = random.normal(key, (size,))
np.testing.assert_allclose(add_one(x), x + 1., atol=1e-5, rtol=1e-5)
def test_broadcasted_load_store(self):
m, n = 16, 32
@functools.partial(
self.pallas_call,
out_shape=(
jax.ShapeDtypeStruct((m, n), jnp.float32)
), grid=1)
def load(x_ref, o_ref):
x = pl.load(x_ref, (jnp.arange(m)[:, None], jnp.arange(n)[None, :]))
pl.store(o_ref, (jnp.arange(m)[:, None], jnp.arange(n)[None, :]), x + 1.)
key = random.PRNGKey(0)
x = random.normal(key, (m, n))
np.testing.assert_allclose(load(x), x + 1., atol=1e-5, rtol=1e-5)
def test_swap(self):
m, n = 16, 32
@functools.partial(
self.pallas_call,
out_shape=(jax.ShapeDtypeStruct((m, n), jnp.float32),) * 2,
grid=1,
input_output_aliases={0: 0, 1: 1},
)
def swap(_, _2, x_ref, y_ref):
x = x_ref[:]
y = pl.swap(y_ref, (slice(None),), x)
x_ref[:] = y
x = random.normal(random.PRNGKey(0), (m, n))
y = random.normal(random.PRNGKey(1), (m, n))
out = swap(x, y)
np.testing.assert_array_equal(out[0], y)
np.testing.assert_array_equal(out[1], x)
def test_masked_swap(self):
m, n = 16, 32
@functools.partial(
self.pallas_call,
out_shape=(jax.ShapeDtypeStruct((m, n), jnp.float32),) * 2,
grid=1,
input_output_aliases={0: 0, 1: 1},
)
def masked_swap(_, _2, mask_ref, x_ref, y_ref):
x = x_ref[:]
y = pl.swap(y_ref, (slice(None),), x, mask=mask_ref[:])
x_ref[:] = y
x = random.normal(random.PRNGKey(0), (m, n))
y = random.normal(random.PRNGKey(1), (m, n))
mask = random.bernoulli(random.PRNGKey(2), shape=(m, n))
out = masked_swap(x, y, mask)
np.testing.assert_array_equal(out[0], jnp.where(mask, y, x))
np.testing.assert_array_equal(out[1], jnp.where(mask, x, y))
def test_unused_ref(self):
m, n = 16, 32
@functools.partial(
self.pallas_call,
out_shape=(
jax.ShapeDtypeStruct((m, n), jnp.float32)
), grid=1)
def dummy(_, o_ref):
pl.store(o_ref, (jnp.arange(m)[:, None], jnp.arange(n)[None, :]),
jnp.ones_like(o_ref))
key = random.PRNGKey(0)
x = random.normal(key, (m, n))
np.testing.assert_allclose(dummy(x), jnp.ones_like(x), atol=1e-5, rtol=1e-5)
def test_pallas_call_with_input_output_aliasing(self):
def add_inplace_kernel(_, o_ref, *, block_size):
pid = pl.program_id(axis=0) # we use a 1d launch grid so axis is 0
block_start = pid * block_size
offsets = block_start + jnp.arange(block_size)
mask = offsets < o_ref.shape[0]
x = pl.load(o_ref, (offsets,), mask=mask)
output = x + 1
pl.store(o_ref, (offsets,), output, mask=mask)
grid = (8,)
size = 8
dtype = "float32"
k1 = random.PRNGKey(0)
block_size = 1
x = random.normal(k1, [size], dtype=dtype)
kernel = functools.partial(add_inplace_kernel, block_size=block_size)
out = self.pallas_call(
kernel,
out_shape=jax.ShapeDtypeStruct(x.shape, x.dtype),
grid=grid, input_output_aliases={0: 0})(x)
expected = x + 1
np.testing.assert_allclose(out, expected)
@parameterized.named_parameters(*[
("add_i32", pl.atomic_add, np.array([1, 2, 3, 4], np.int32), np.sum),
("max_i", pl.atomic_max, np.array([1, 2, 3, 4], np.int32), np.max),
("min_i32", pl.atomic_min, np.array([1, 2, 3, 4], np.int32), np.min),
("add_f16", pl.atomic_add, np.array([1, 2, 3, 4], np.float16), np.sum),
("add_f32", pl.atomic_add, np.array([1, 2, 3, 4], np.float32), np.sum),
("max_f32", pl.atomic_max, np.array([1, 2, 3, 4], np.float32), np.max),
("min_f32", pl.atomic_min, np.array([1, 2, 3, 4], np.float32), np.min),
])
def test_scalar_atomic(self, op, value, numpy_op):
if plgpu.get_compute_capability(0) < 70:
raise unittest.SkipTest(
"Atomic ops onl works on GPUs with capability >= sm70")
@functools.partial(
self.pallas_call,
out_shape=jax.ShapeDtypeStruct((), value.dtype),
grid=value.shape[0],
input_output_aliases={1: 0})
def atomic_kernel(x_ref, _, o_ref):
pid = pl.program_id(axis=0)
op(o_ref, (), x_ref[pid])
if op == pl.atomic_add:
neutral = np.array(0, dtype=value.dtype)
elif op == pl.atomic_max:
if np.issubdtype(value.dtype, np.integer):
neutral = np.array(np.iinfo(value.dtype).min, value.dtype)
else:
neutral = np.array(-float('inf'), value.dtype)
elif op == pl.atomic_min:
if np.issubdtype(value.dtype, np.integer):
neutral = np.array(np.iinfo(value.dtype).max, value.dtype)
else:
neutral = np.array(float('inf'), value.dtype)
elif op == pl.atomic_or:
neutral = np.array(False, value.dtype)
else:
raise NotImplementedError()
out = atomic_kernel(value, neutral)
np.testing.assert_allclose(out, numpy_op(value))
@parameterized.parameters(*[(0,), (1,)])
def test_array_atomic_add(self, axis):
if plgpu.get_compute_capability(0) < 70:
raise unittest.SkipTest(
"Atomic ops onl works on GPUs with capability >= sm70")
m, n = 32, 8
if axis == 0:
grid = m
else:
grid = n
out_shape = jax.ShapeDtypeStruct((n if axis == 0 else m,), jnp.float32)
@functools.partial(
self.pallas_call,
out_shape=out_shape,
grid=grid,
input_output_aliases={1: 0})
def reduce(x_ref, _, y_ref):
i = pl.program_id(axis=0)
if axis == 0:
idx = (i, jnp.arange(n))
else:
idx = (jnp.arange(m), i)
x = pl.load(x_ref, idx)
pl.atomic_add(y_ref, (jnp.arange(y.shape[0]),), x)
x = random.normal(random.PRNGKey(0), (m, n))
y = jnp.zeros(out_shape.shape, out_shape.dtype)
y = reduce(x, y)
y_ref = np.sum(x, axis=axis)
np.testing.assert_allclose(y, y_ref, atol=1e-2, rtol=1e-2)
@parameterized.parameters(False, True)
def test_reduce_only_dim(self, use_store):
m = 32
x = random.normal(random.PRNGKey(0), (m,), dtype=jnp.float32)
out_shape = jax.ShapeDtypeStruct((), x.dtype)
@functools.partial(
self.pallas_call,
out_shape=out_shape,
grid=1, debug=False)
def reduce(x_ref, y_ref):
x = pl.load(x_ref, (jnp.arange(m),))
y = jnp.sum(x, axis=-1)
if use_store:
pl.store(y_ref, (), y)
else:
y_ref[...] = y
y = reduce(x)
y_ref = jnp.sum(x, axis=-1)
np.testing.assert_allclose(y, y_ref, atol=1e-2, rtol=1e-2)
@parameterized.named_parameters(*[
(f"{op_name}_{dtype}_{axis}", op, dtype, axis)
for op_name, op in [
("add", jnp.sum),
("max", jnp.max),
("min", jnp.min),
("argmax", jnp.argmax),
("argmin", jnp.argmin),
]
for axis in [0, 1, (1,), (0, 1)]
for dtype in ["float16", "float32", "int32", "uint32"]
if isinstance(axis, int) or "arg" not in op_name
])
def test_array_reduce(self, op, dtype, axis):
m, n = 32, 8
out_dtype = dtype
if op in {jnp.argmin, jnp.argmax}:
out_dtype = jnp.int32
def make_x(key):
if jnp.issubdtype(dtype, jnp.integer):
return random.permutation(
key, jnp.arange(m * n, dtype=dtype), independent=True
).reshape(m, n)
else:
return random.normal(key, (m, n), dtype=dtype)
out_shape = jax.ShapeDtypeStruct(
op(make_x(random.PRNGKey(0)), axis=axis).shape, out_dtype)
if isinstance(axis, int):
grid = tuple(a for i, a in enumerate((m, n)) if i != axis)
else:
grid = tuple(a for i, a in enumerate((m, n)) if i not in axis)
@functools.partial(
self.pallas_call,
out_shape=out_shape,
grid=grid)
def reduce(x_ref, y_ref):
x = pl.load(x_ref, (jnp.arange(m)[:, None], jnp.arange(n)[None]))
y = op(x, axis=axis)
pl.store(y_ref, tuple(jnp.arange(d) for d in y.shape), y)
for i, key in enumerate(random.split(random.PRNGKey(0), 20)):
x = make_x(key)
y = reduce(x)
y_ref = op(x, axis=axis)
np.testing.assert_allclose(y, y_ref, atol=1e-2, rtol=1e-2, err_msg=i)
def test_using_pallas_slice(self):
m, n = 32, 4
out_shape = jax.ShapeDtypeStruct((4, n), jnp.float32)
@functools.partial(
self.pallas_call,
out_shape=out_shape,
grid=1)
def slice_kernel(x_ref, y_ref):
x = pl.load(x_ref, (pl.dslice(0, 4), pl.dslice(0, 4)))
pl.store(y_ref, (pl.dslice(4), pl.dslice(4)), x)
x = random.normal(random.PRNGKey(0), (m, n))
y = slice_kernel(x)
y_ref = x[:4]
np.testing.assert_allclose(y, y_ref, atol=1e-2, rtol=1e-2)
def test_pallas_trace_cache(self):
trace_count = 0
@functools.partial(
self.pallas_call, out_shape=jax.ShapeDtypeStruct((), jnp.float32),
grid=1)
def add_one(x_ref, o_ref):
nonlocal trace_count
o_ref[()] = x_ref[()] + 1.
trace_count += 1
@jax.jit
def f(x):
return add_one(add_one(x))
x = jnp.array(0., dtype=jnp.float32)
self.assertEqual(f(x), 2.)
self.assertEqual(trace_count, 1)
def test_pallas_compilation_cache(self):
if not compile_jaxpr:
self.skipTest("No Triton GPU.")
if self.INTERPRET:
raise unittest.SkipTest("No Triton compilation in interpreter mode.")
@functools.partial(
self.pallas_call, out_shape=jax.ShapeDtypeStruct((), jnp.float32),
grid=1)
def add_one(x_ref, o_ref):
o_ref[()] = x_ref[()] + 1.
@jax.jit
def f(x):
return add_one(add_one(x))
x = jnp.array(0., dtype=jnp.float32)
self.assertEqual(f(x), 2.)
num_misses = compile_jaxpr.cache_info().misses
self.assertEqual(num_misses, 1)
@parameterized.parameters(*[
(0, 0, 1),
(0, 1, 1),
(1, 0, 1),
(1, 1, 1),
(2, 1, 1),
(2, 1, 1),
])
def test_atomic_cas(self, init_value, cmp, new_value):
@functools.partial(
self.pallas_call, out_shape=(
jax.ShapeDtypeStruct((), jnp.int32),
jax.ShapeDtypeStruct((), jnp.int32)),
input_output_aliases={0: 0})
def swap(_, lock_ref, out_ref):
out_ref[()] = pl.atomic_cas(lock_ref, cmp, new_value)
lock, out = swap(init_value)
np.testing.assert_allclose(lock, new_value if cmp == init_value else
init_value)
np.testing.assert_allclose(out, init_value)
@parameterized.parameters(*[
1, 2, 3, 4, 8
])
def test_atomic_counter(self, num_threads):
if self.INTERPRET:
self.skipTest("While loop not supported in interpret mode yet.")
@functools.partial(
self.pallas_call, out_shape=(
jax.ShapeDtypeStruct((), jnp.int32),
jax.ShapeDtypeStruct((), jnp.int32)),
input_output_aliases={0: 0, 1: 1},
grid=(num_threads,))
def increment(_, __, lock_ref, counter_ref):
def _cond(_):
return pl.atomic_cas(lock_ref, 0, 1) == 1
lax.while_loop(_cond, lambda a: a, 0)
counter_ref[...] += 1
pl.atomic_xchg(lock_ref, (), 0)
lock, count = increment(0, 0)
np.testing.assert_allclose(lock, 0)
np.testing.assert_allclose(count, num_threads)
def test_custom_jvp_call(self):
@functools.partial(jax.custom_jvp, nondiff_argnums=(1,))
def softmax(x, axis=-1):
unnormalized = jnp.exp(x - jnp.max(x, axis, keepdims=True))
return unnormalized / jnp.sum(unnormalized, axis, keepdims=True)
@softmax.defjvp
def softmax_jvp(axis, primals, tangents):
(x,), (x_dot,) = primals, tangents
y = softmax(x, axis)
return y, y * (x_dot - (y * x_dot).sum(axis, keepdims=True))
m, n = 16, 32
x = random.normal(random.PRNGKey(0), (m, n))
@functools.partial(self.pallas_call, out_shape=x, grid=1)
def softmax_kernel(x_ref, y_ref):
y_ref[:] = softmax(x_ref[:])
np.testing.assert_allclose(softmax_kernel(x), jax.nn.softmax(x), atol=1e-7)
class PallasCallInterpreterTest(PallasCallTest):
INTERPRET = True
class PallasControlFlowTest(PallasTest):
def setUp(self):
super().setUp()
if self.INTERPRET:
self.skipTest("Control flow not supported in interpreter mode yet.")
def test_loop_with_float64_carry(self):
# Test that the jnp.zeros(f64) loop init_val is actually f64, and that
# fori_loop handles i64 index variables, i.e. error: 'scf.for' op along
# control flow edge from Region #0 to Region #0: source type #0
# 'tensor<4xf64>' should match input type #0 'tensor<4xf32>'
with config.enable_x64(True):
@functools.partial(self.pallas_call,
out_shape=jax.ShapeDtypeStruct((4,), jnp.float64),
grid=1,
debug=False)
def f(x_ref, y_ref):
def body(i, acc):
# TODO(sharadmv): DCE loop index but retain carry breaks scan pattern.
# return acc + x_ref[...]
return acc + x_ref[...] + i * 0
y_ref[...] = lax.fori_loop(
0, 3, body, jnp.zeros((4,), jnp.float64))
np.testing.assert_allclose(np.arange(1, 5.) * 3,
f(jnp.arange(1, 5., dtype=jnp.float64)))
def test_cond_simple(self):
arg = jnp.float32(0.)
@functools.partial(self.pallas_call,
out_shape=jax.ShapeDtypeStruct(arg.shape, jnp.float32),
debug=False)
def f(branch_ref, x_ref, y_ref):
y_ref[...] = lax.switch(
branch_ref[...],
(lambda x: x**2, lambda x: -x),
x_ref[...])
y = f(jnp.int32(0), arg + 3.)
self.assertEqual(y, 9.)
y = f(jnp.int32(1), arg + 2.)
self.assertEqual(y, -2.)
def test_cond_threebranch(self):
arg = jnp.float32(0.)
@functools.partial(self.pallas_call,
out_shape=jax.ShapeDtypeStruct(arg.shape, jnp.float32),
grid=1,
debug=False)
def f(branch_ref, x_ref, y_ref):
y_ref[...] = lax.switch(
branch_ref[...],
(lambda x: x**2, lambda x: -x, lambda x: -x**2),
x_ref[...])
y = f(jnp.int32(0), arg + 3.)
self.assertEqual(y, 9.)
y = f(jnp.int32(1), arg + 2.)
self.assertEqual(y, -2.)
y = f(jnp.int32(2), arg + 4.)
self.assertEqual(y, -16.)
@parameterized.parameters(1, 2, 4, 8)
def test_cond_vectors(self, block_size):
arg = jnp.float32([0.] * 8)
@functools.partial(self.pallas_call,
out_shape=jax.ShapeDtypeStruct(arg.shape, jnp.float32),
in_specs=[pl.BlockSpec(lambda _: (), ()),
pl.BlockSpec(lambda i: i, (block_size,))],
out_specs=pl.BlockSpec(lambda i: i, (block_size,)),
grid=pl.cdiv(arg.shape[0], block_size),
debug=False)
def f(branch_ref, x_ref, y_ref):
y_ref[...] = lax.switch(
branch_ref[...],
(lambda x: x**2, lambda x: -x),
x_ref[...])
y = f(jnp.int32(0), arg + 3.)
np.testing.assert_allclose(y, arg + 9.)
y = f(jnp.int32(1), arg + 2.)
np.testing.assert_allclose(y, arg - 2.)
@parameterized.parameters(1, 2, 4, 8)
def test_cond_threebranch_vectors(self, block_size):
arg = jnp.float32([0.] * 8)
@functools.partial(self.pallas_call,
out_shape=jax.ShapeDtypeStruct(arg.shape, jnp.float32),
in_specs=[pl.BlockSpec(lambda _: (), ()),
pl.BlockSpec(lambda i: i, (block_size,))],
out_specs=pl.BlockSpec(lambda i: i, (block_size,)),
grid=pl.cdiv(arg.shape[0], block_size),
debug=False)
def f(branch_ref, x_ref, y_ref):
y_ref[...] = lax.switch(
branch_ref[...],
(lambda x: x**2, lambda x: -x, lambda x: -x**2),
x_ref[...])
y = f(jnp.int32(0), arg + 3.)
np.testing.assert_allclose(y, arg + 9.)
y = f(jnp.int32(1), arg + 2.)
np.testing.assert_allclose(y, arg - 2.)
y = f(jnp.int32(2), arg + 4.)
np.testing.assert_allclose(y, arg - 16.)
@parameterized.parameters(*itertools.product([1, 8], [1, 2, 4]))
def test_cond_threebranch_matrix_out(self, bx, by):
x = jnp.arange(64.)[:, None]
y = jnp.arange(128.)[None, :]
# TODO(sharadmv): Renaming in_specs->in_spec silently breaks.
@functools.partial(
self.pallas_call,
out_shape=jax.ShapeDtypeStruct((x.shape[0], y.shape[1]), jnp.float32),
in_specs=[
pl.BlockSpec(lambda _, __: (), ()),
pl.BlockSpec(lambda i, _: (i, 0), (bx, 1)),
pl.BlockSpec(lambda _, j: (0, j), (1, by))],
out_specs=pl.BlockSpec(lambda i, j: (i, j), (bx, by)),
grid=(pl.cdiv(x.shape[0], bx), pl.cdiv(y.shape[1], by)),
debug=False)
def f(branch_ref, x_ref, y_ref, o_ref):
o_ref[...] = lax.switch(
branch_ref[...],
(lambda x, y: (x - y)**2,
lambda x, y: -jnp.abs(x - y),
lambda x, y: jnp.sqrt(jnp.abs(x - y))),
x_ref[...],
y_ref[...])
np.testing.assert_allclose(f(jnp.int32(0), x, y), (x - y)**2)
np.testing.assert_allclose(f(jnp.int32(1), x, y), -jnp.abs(x - y))
np.testing.assert_allclose(f(jnp.int32(2), x, y), jnp.sqrt(jnp.abs(x - y)))
def test_conditional_write(self):
arg = jnp.arange(8, dtype=jnp.float32)
@functools.partial(self.pallas_call,
out_shape=jax.ShapeDtypeStruct(arg.shape, jnp.float32),
debug=False)
def f(branch_ref, x_ref, out_ref):
out_ref[...] = -x_ref[...]
def if_true(z):
out_ref[4] = z
return ()
jax.lax.cond(branch_ref[...], if_true, lambda z: (), x_ref[6])
np.testing.assert_allclose(f(jnp.bool_(True), arg),
jnp.float32([0., -1, -2, -3, 6, -5, -6, -7]))
np.testing.assert_allclose(f(jnp.bool_(False), arg),
-arg)
# We actually expect the assertion failure in linearize, but this also
# covers another case where an effect was causing an earlier assertion
# failure.
with self.assertRaises(AssertionError):
# Notably, we should not have a ValueError for mismatched Read<N> effect.
_ = jax.grad(lambda x: jnp.sum(f(jnp.bool_(True), x)**2))(arg)
# np.testing.assert_allclose(
# dx, jnp.float32([0., 2, 4, 6, 0, 10, 12 + 12, 14]))
def test_scan_cond_vm_explicit_ref_arg(self):
program = jnp.int32([0, 1, 2, 3, 2])
params = jnp.arange(len(program) * 3.).reshape(len(program), 3)
x = jnp.arange(7.)
bx = 4
@jax.jit
@functools.partial(
self.pallas_call,
out_shape=jax.ShapeDtypeStruct((x.shape[0],), jnp.float32),
in_specs=[
pl.BlockSpec(lambda _: (0,), program.shape), # program
pl.BlockSpec(lambda _: (0, 0), params.shape), # params
pl.BlockSpec(lambda i: (i,), (bx,))], # x
out_specs=pl.BlockSpec(lambda i: (i,), (bx,)),
grid=pl.cdiv(x.shape[0], bx),
debug=False)
def f(program_ref, params_ref, x_ref, out_ref):
x = x_ref[...]
def body_fn(i, args):
state, program_ref, params_ref = args
opcode = program_ref[i]
state = jax.lax.switch(
opcode,
(lambda state, params, i: state + params[i, 0] * 2.**i * x,
lambda state, params, i: state + params[i, 1] * 2.**i * x,
lambda state, params, i: state + params[i, 2] * 2.**i * x,
lambda state, params, i: state + params[i, 1] * 2.**i * x,
),
state, params_ref, i)
return state, program_ref, params_ref
out_ref[...] = jax.lax.fori_loop(
0, len(program), body_fn,
(jnp.zeros(x.shape), program_ref, params_ref))[0]
expected = (x * params[0, 0] +
2 * x * params[1, 1] +
4 * x * params[2, 2] +
8 * x * params[3, 1] +
16 * x * params[4, 2])
np.testing.assert_allclose(f(program, params, x), expected)
with self.assertRaises(AssertionError):
jax.value_and_grad(lambda params, x: f(program, params, x).sum())(
params, x)
def test_scan_cond_vm_closing_over_ref(self):
# ** Difference is the closure over params_ref in the switch branches. **
program = jnp.int32([0, 1, 2, 3, 2, -1])
params = jnp.arange(len(program) * 3.).reshape(len(program), 3)
x = jnp.arange(7.)
bx = 4
@jax.jit
@functools.partial(
self.pallas_call,
out_shape=jax.ShapeDtypeStruct((x.shape[0],), jnp.float32),
in_specs=[
pl.BlockSpec(lambda _: (0,), program.shape), # program
pl.BlockSpec(lambda _: (0, 0), params.shape), # params
pl.BlockSpec(lambda i: (i,), (bx,))], # x
out_specs=pl.BlockSpec(lambda i: (i,), (bx,)),