-
Notifications
You must be signed in to change notification settings - Fork 3.8k
Expand file tree
/
Copy pathlayout_test.py
More file actions
860 lines (688 loc) · 29.5 KB
/
Copy pathlayout_test.py
File metadata and controls
860 lines (688 loc) · 29.5 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
# 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 math
import re
from absl.testing import absltest
from absl.testing import parameterized
import numpy as np
import jax
import jax.numpy as jnp
from jax.sharding import NamedSharding, PartitionSpec as P
from jax._src.sharding_impls import make_single_device_sharding
from jax._src import config
from jax._src import test_util as jtu
from jax._src.util import safe_zip
from jax.experimental.layout import with_layout_constraint, Format, Layout
config.parse_flags_with_absl()
jtu.request_cpu_devices(8)
class LayoutTest(jtu.JaxTestCase):
def test_auto_layout(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
shape1 = (128, 128)
shape2 = (128, 128)
s1 = NamedSharding(mesh, P('x', 'y'))
s2 = NamedSharding(mesh, P('x'))
def apply(x, y):
return x.T, y.T
def init(x, y):
return x * 2, y * 2
np_inp1 = np.arange(math.prod(shape1), dtype=np.int32).reshape(shape1)
np_inp2 = np.arange(math.prod(shape2), dtype=np.int32).reshape(shape2)
sds1 = jax.ShapeDtypeStruct(np_inp1.shape, np_inp1.dtype, sharding=s1)
sds2 = jax.ShapeDtypeStruct(np_inp2.shape, np_inp2.dtype, sharding=s2)
lowered_apply = jax.jit(apply, in_shardings=Format(Layout.AUTO),
out_shardings=Format(Layout.AUTO)).lower(sds1, sds2)
compiled_apply = lowered_apply.compile()
arg_formats, kw_layouts = compiled_apply.input_formats
self.assertEmpty(kw_layouts)
for i, o in zip(arg_formats, compiled_apply.output_formats):
self.assertEqual(i.layout.major_to_minor,
o.layout.major_to_minor[::-1])
init_compiled = jax.jit(
init, out_shardings=arg_formats).lower(sds1, sds2).compile()
for i, o in zip(init_compiled.input_formats[0],
init_compiled.output_formats):
self.assertEqual(i, o)
arr1 = jax.device_put(np_inp1, s1)
arr2 = jax.device_put(np_inp2, s2)
with jtu.count_aot_jit_cpp_cache_miss() as init_count:
init_out = init_compiled(arr1, arr2)
init_compiled(arr1, arr2)
self.assertEqual(init_count(), 1)
self.assertEqual(init_out[0].format, init_compiled.output_formats[0])
self.assertEqual(init_out[1].format, init_compiled.output_formats[1])
with jtu.count_aot_jit_cpp_cache_miss() as apply_count:
apply_out = compiled_apply(*init_out)
compiled_apply(*init_out)
self.assertEqual(apply_count(), 1)
self.assertEqual(apply_out[0].format, compiled_apply.output_formats[0])
self.assertEqual(apply_out[1].format, compiled_apply.output_formats[1])
self.assertTupleEqual(apply_out[0].format.layout.major_to_minor,
init_out[0].format.layout.major_to_minor[::-1])
self.assertTupleEqual(apply_out[1].format.layout.major_to_minor,
init_out[1].format.layout.major_to_minor[::-1])
self.assertArraysEqual(init_out[0], np_inp1 * 2)
self.assertArraysEqual(init_out[1], np_inp2 * 2)
self.assertArraysEqual(apply_out[0], (np_inp1 * 2).T)
self.assertArraysEqual(apply_out[1], (np_inp2 * 2).T)
def test_default_layout(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
shape = (4, 4, 2)
np_inp = np.arange(math.prod(shape), dtype=np.int32).reshape(shape)
s = NamedSharding(mesh, P('x', 'y'))
sds = jax.ShapeDtypeStruct(np_inp.shape, np_inp.dtype, sharding=s)
arr = jax.device_put(np_inp, s)
def f(x):
return x.T
lowered = jax.jit(f, in_shardings=None, out_shardings=None).lower(sds)
compiled = lowered.compile()
out = compiled(arr)
self.assertTupleEqual(
compiled.input_formats[0][0].layout.major_to_minor[::-1],
(2, 1, 0))
self.assertTupleEqual(
compiled.output_formats.layout.major_to_minor[::-1],
(2, 1, 0))
self.assertArraysEqual(out, np_inp.T)
self.assertEqual(out.sharding, NamedSharding(mesh, P(None, 'y', 'x')))
compiled_auto = jax.jit(f, in_shardings=Format(Layout.AUTO),
out_shardings=Format(Layout.AUTO)).lower(sds).compile()
self.assertTupleEqual(
compiled_auto.input_formats[0][0].layout.major_to_minor[::-1],
(2, 1, 0))
self.assertTupleEqual(
compiled_auto.output_formats.layout.major_to_minor[::-1],
(0, 1, 2))
with self.assertRaisesRegex(
ValueError, "jax.jit` does not accept device-local layouts directly"):
jax.jit(f, in_shardings=Layout.AUTO,
out_shardings=Layout.AUTO).lower(sds).compile()
def test_in_layouts_out_layouts(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
shape = (8, 8)
np_inp = np.arange(math.prod(shape)).reshape(shape)
s = NamedSharding(mesh, P('x', 'y'))
arr = jax.device_put(np_inp, s)
def f(x):
return x.T
compiled = jax.jit(f, in_shardings=Format(),
out_shardings=Format(Layout.AUTO)).lower(arr).compile()
self.assertTupleEqual(
compiled.input_formats[0][0].layout.major_to_minor[::-1],
(1, 0))
self.assertTupleEqual(
compiled.output_formats.layout.major_to_minor[::-1],
(0, 1))
out = compiled(arr)
self.assertArraysEqual(out, np_inp.T)
self.assertEqual(out.format, compiled.output_formats)
self.assertEqual(out.sharding, NamedSharding(mesh, P('y', 'x')))
def test_sharding_and_layouts(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
shape = (4, 8)
np_inp = np.arange(math.prod(shape)).reshape(shape)
s = NamedSharding(mesh, P('x', 'y'))
compiled = jax.jit(lambda x: x.T, in_shardings=Format(Layout.AUTO, s),
out_shardings=Format(Layout.AUTO, s)).lower(np_inp).compile()
out = compiled(np_inp)
self.assertTupleEqual(
compiled.input_formats[0][0].layout.major_to_minor[::-1],
(1, 0))
if not jtu.test_device_matches(['cpu']):
self.assertTupleEqual(
compiled.output_formats.layout.major_to_minor[::-1],
(0, 1))
self.assertArraysEqual(out, np_inp.T)
self.assertEqual(out.sharding, s)
def test_dce_in_layouts(self):
def f(x, y, z, a, b, c):
return z * 2, b.T
shape = (8, 2)
inps = [np.arange(math.prod(shape)).reshape(shape)] * 6
compiled = jax.jit(f, in_shardings=Format(Layout.AUTO),
out_shardings=Format(Layout.AUTO)).lower(*inps).compile()
arg_formats, _ = compiled.input_formats
out1, out2 = compiled(*inps)
compiled2 = jax.jit(f, in_shardings=arg_formats).lower(*inps).compile()
out3, out4 = compiled2(*inps)
for l1, l2 in safe_zip(arg_formats, compiled2.input_formats[0]):
self.assertEqual(l1, l2)
self.assertArraysEqual(out1, out3)
self.assertArraysEqual(out2, out4)
arrs = [jax.device_put(i, l) for i, l in zip(inps, arg_formats)]
out5, out6 = jax.jit(f)(*arrs)
self.assertArraysEqual(out1, out5)
self.assertArraysEqual(out2, out6)
def test_no_error_dced_args(self):
mesh = jtu.create_mesh((2, 1), ('x', 'y'))
shape = (8, 2)
s = NamedSharding(mesh, P('x', 'y'))
np_inp = np.arange(math.prod(shape)).reshape(shape)
arr1 = jax.device_put(np_inp, s)
arr2 = jax.device_put(np_inp, s)
arrs = [arr1, arr2]
def f(x, y):
return x * 2
jf = jax.jit(f, in_shardings=Format(Layout.AUTO, s),
out_shardings=Format(Layout.AUTO, s))
compiled = jf.lower(np_inp, np_inp).compile()
arg_formats, _ = compiled.input_formats
arrs = [jax.device_put(i, l) for i, l in zip(arrs, arg_formats)]
compiled(*arrs)
def test_aot_layout_mismatch(self):
if jtu.test_device_matches(['cpu', 'gpu']):
# The test fails on GPU because the compilation with both input and
# output set to auto layout is underspecified. The GPU compiler chooses
# the default layout as the input layout and that choice does not
# raise an exception.
self.skipTest('This test does not work on CPU or GPU backends.')
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
shape = (256, 4, 2)
np_inp = np.arange(math.prod(shape), dtype=np.int32).reshape(shape)
s = NamedSharding(mesh, P('x'))
sds = jax.ShapeDtypeStruct(np_inp.shape, np_inp.dtype, sharding=s)
arr = jax.device_put(np_inp, s)
def f(x):
return (x * 2).T
with self.assertRaisesRegex(
ValueError,
'Layout passed to jit does not match the layout on the respective arg'):
jax.jit(f, in_shardings=Format(Layout.AUTO)).lower(arr)
compiled = jax.jit(f, in_shardings=Format(Layout.AUTO),
out_shardings=Format(Layout.AUTO)).lower(sds).compile()
with self.assertRaisesRegex(
ValueError,
r'Computation was compiled for input layouts that disagree with the '
r'layouts of arguments passed to it.'):
compiled(arr)
@jtu.ignore_warning(category=DeprecationWarning,
message="backend and device argument")
def test_cpu_default_backend_layout(self):
inp = jax.device_put(np.ones((8, 8)), device=jax.devices('cpu')[0])
out_cpu = jax.jit(jnp.dot)(inp, inp)
jax.jit(jnp.dot, backend=jax.default_backend()).lower(
out_cpu, out_cpu).compile() # doesn't crash
def test_device_put_concrete_layout(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
shape = (8, 128)
np_inp = np.arange(math.prod(shape)).reshape(shape)
s = NamedSharding(mesh, P('x', 'y'))
arr = jax.device_put(np_inp, s)
compiled = jax.jit(
lambda x: x * 2, out_shardings=Format(Layout.AUTO)).lower(arr).compile()
col = compiled.output_formats
out = jax.device_put(np_inp, col)
self.assertEqual(out.format, col)
self.assertArraysEqual(out, np_inp)
for s in out.addressable_shards:
self.assertEqual(out.format.layout,
s.data.format.layout)
def test_device_put_non_concrete_layout_error(self):
np_inp = np.arange(16).reshape(8, 2)
l1 = Format(Layout.AUTO, make_single_device_sharding(jax.devices()[0]))
with self.assertRaisesRegex(
ValueError, 'sharding and layout.*should be concrete'):
jax.device_put(np_inp, l1)
l2 = Format(Layout.AUTO)
with self.assertRaisesRegex(
ValueError, 'sharding and layout.*should be concrete'):
jax.device_put(np_inp, l2)
l3 = Format(None, make_single_device_sharding(jax.devices()[0]))
out = jax.device_put(np_inp, l3)
self.assertArraysEqual(out, np_inp)
self.assertTrue(out._committed)
def invalid_layout_spec(self):
x = np.arange(8)
compiled = jax.jit(lambda x: x).lower(x).compile()
with self.assertRaisesRegex(
ValueError, 'Sharding has to be concrete when layout.*'):
Format(compiled.output_formats[0], None)
def test_layout_on_sds(self):
mesh = jtu.create_mesh((2, 1), ('x', 'y'))
s = NamedSharding(mesh, P('x', 'y'))
np_inp = np.arange(16).reshape(8, 2)
arr = jax.device_put(np_inp, s)
out_format = jax.jit(jnp.sin, out_shardings=Format(Layout.AUTO)).lower(
arr).compile().output_formats
sds = jax.ShapeDtypeStruct(arr.shape, arr.dtype, sharding=out_format)
arg_format, _ = jax.jit(lambda x: x * 2).lower(sds).compile().input_formats
self.assertEqual(arg_format[0], out_format)
with self.assertRaisesRegex(
TypeError,
'Layout.AUTO` cannot be used in place of a device-local'
' layout in a `ShapeDtypeStruct`'):
jax.ShapeDtypeStruct(arr.shape, arr.dtype, sharding=Format(Layout.AUTO))
def test_make_array_from_callback(self):
mesh = jtu.create_mesh((2, 1), ('x', 'y'))
s = NamedSharding(mesh, P('x', 'y'))
np_inp = np.arange(16, dtype=np.int32).reshape(8, 2)
sds = jax.ShapeDtypeStruct(np_inp.shape, np_inp.dtype, sharding=s)
format = jax.jit(lambda x: x * 2).lower(sds).compile().output_formats
out = jax.make_array_from_callback(np_inp.shape, format,
lambda idx: np_inp[idx])
self.assertArraysEqual(out, np_inp)
self.assertEqual(out.format, format)
with self.assertRaisesRegex(
TypeError,
'`Layout.AUTO` cannot be used in place of a device-local'
' layout'):
jax.make_array_from_callback(np_inp.shape, Format(Layout.AUTO, s),
lambda idx: np_inp[idx])
with self.assertRaisesRegex(
TypeError, 'sharding should be an instance of `jax.sharding`'):
jax.make_array_from_callback(
np_inp.shape, Format(None, None), lambda idx: np_inp[idx])
def test_wsc_concrete_layout(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
shape = (16, 128)
s = NamedSharding(mesh, P('x'))
np_inp = np.arange(math.prod(shape)).reshape(shape)
arr = jax.device_put(np_inp, s)
# Create a custom layout instead of using `arr.layout` to test the API.
custom_dll = Layout(major_to_minor=(0, 1))
@jax.jit
def f(x):
y = x.T
# Constrain `y` to the original layout of `arr` because without it,
# the layout of `y` would be the transpose of `arr`.
return jax.lax.with_sharding_constraint(y, Format(custom_dll, s))
out = f(arr)
self.assertEqual(out.format.layout.major_to_minor,
custom_dll.major_to_minor)
self.assertEqual(out.format, arr.format)
self.assertArraysEqual(out, np_inp.T)
def test_wsc_bfloat16_concrete_layout(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
shape = (64, 128)
s = NamedSharding(mesh, P('x'))
inp = jnp.arange(math.prod(shape), dtype=jnp.bfloat16).reshape(shape)
arr = jax.device_put(inp, s)
# Create a custom layout instead of using `arr.layout` to test the API.
custom_dll = Layout(major_to_minor=(0, 1))
@jax.jit
def f(x):
y = x.T
# Constrain `y` to the original layout of `arr` because without it,
# the layout of `y` would be the transpose of `arr`.
return jax.lax.with_sharding_constraint(y, Format(custom_dll, s))
out = f(arr)
self.assertEqual(out.format.layout.major_to_minor,
custom_dll.major_to_minor)
self.assertEqual(out.format, arr.format)
self.assertArraysEqual(out, inp.T)
def test_device_put_user_concrete_layout(self):
shape = (8, 128)
np_inp = np.arange(math.prod(shape)).reshape(shape)
dll = Layout(major_to_minor=(1, 0))
s = make_single_device_sharding(jax.devices()[0])
out = jax.device_put(np_inp, Format(dll, s))
self.assertEqual(out.format.layout.major_to_minor,
dll.major_to_minor)
self.assertArraysEqual(out, np_inp)
def test_device_put_user_concrete_layout_multi_device(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
shape = (16, 128)
s = NamedSharding(mesh, P('x'))
np_inp = np.arange(math.prod(shape)).reshape(shape)
jnp_inp = jnp.arange(math.prod(shape)).reshape(shape)
arr = jax.device_put(np_inp, s)
custom_format = Format(Layout(major_to_minor=(0, 1)), s)
out1 = jax.device_put(arr, custom_format)
with jax.set_mesh(mesh):
out2 = jax.device_put(arr, custom_format)
out3 = jax.device_put(jnp_inp, custom_format)
out4 = jax.device_put(np_inp, custom_format)
for o in [out1, out2, out3, out4]:
self.assertArraysEqual(o, np_inp)
self.assertEqual(o.format.layout.major_to_minor,
custom_format.layout.major_to_minor)
def test_concrete_layout_jit(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
shape = (16, 128)
s = NamedSharding(mesh, P('x'))
np_inp = np.arange(math.prod(shape)).reshape(shape)
arr = jax.device_put(np_inp, s)
def f(x):
return x.T
custom_dll = Layout(major_to_minor=(0, 1))
f = jax.jit(f, out_shardings=Format(custom_dll, s))
out = f(arr)
self.assertArraysEqual(out, np_inp.T)
self.assertEqual(out.format.layout.major_to_minor,
custom_dll.major_to_minor)
def test_compatible_aval_error(self):
custom_dll = Layout(major_to_minor=(0, 1, 2))
l = Format(custom_dll, make_single_device_sharding(jax.devices()[0]))
inp = np.arange(8)
@jax.jit(in_shardings=l)
def f(x):
return x * 2
with self.assertRaisesRegex(
ValueError,
'.*Length of major_to_minor and the rank of the value should match.*'):
f(inp)
def test_incompatible_aval_error_device_put(self):
custom_dll = Layout(major_to_minor=(0, 1, 2))
l = Format(custom_dll, make_single_device_sharding(jax.devices()[0]))
inp = np.arange(8)
with self.assertRaisesRegex(
ValueError,
'.*Length of major_to_minor and the rank of the value should match.*'):
jax.device_put(inp, l)
def test_concrete_layout_in_shardings(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
s = NamedSharding(mesh, P('x', 'y'))
shape = (16, 128)
np_inp = np.arange(math.prod(shape)).reshape(shape)
arr = jax.device_put(np_inp, s)
custom_dll = Layout(major_to_minor=(0, 1))
@jax.jit(
in_shardings=Format(custom_dll, s),
out_shardings=Format(Layout.AUTO))
def f(x):
return x.T
out = f(arr)
self.assertArraysEqual(out, np_inp.T)
self.assertEqual(out.format.layout.major_to_minor,
custom_dll.major_to_minor[::-1])
custom_dll2 = Layout(major_to_minor=(1, 0))
@jax.jit(in_shardings=Format(custom_dll2, s))
def g(x):
return x.T
with self.assertRaisesRegex(
ValueError,
'Layout passed to jit does not match the layout on the respective arg'):
g(arr)
def test_in_layouts_jit_jnp_input(self):
major_last_layout = Layout(major_to_minor=(1, 0))
sharding = make_single_device_sharding(jax.devices()[0])
f = jax.jit(lambda x: x + 1,
in_shardings=Format(major_last_layout, sharding))
arr = jnp.arange(8 * 128).reshape(8, 128)
out = f(arr)
self.assertArraysEqual(out, arr + 1)
# cpp dispatch should call into shard_args from cpp.
out2 = f(arr)
self.assertArraysEqual(out2, arr + 1)
np_inp = np.arange(8 * 128).reshape(8, 128)
out3 = f(np_inp)
self.assertArraysEqual(out3, np_inp + 1)
# cpp dispatch should call into shard_args from cpp.
out4 = f(np_inp)
self.assertArraysEqual(out4, np_inp + 1)
def test_layout_donation(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
s = NamedSharding(mesh, P('x', 'y'))
shape = (16, 128)
np_inp = np.arange(math.prod(shape)).reshape(shape)
custom_dll = Layout(major_to_minor=(0, 1))
arr = jax.device_put(np_inp, Format(custom_dll, s))
@jax.jit(in_shardings=Format(custom_dll, s), donate_argnums=0)
def f(x):
return x
f(arr)
self.assertTrue(arr.is_deleted())
def test_layout_donation_auto(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
s = NamedSharding(mesh, P('x', 'y'))
shape = (128, 16)
np_inp = np.arange(math.prod(shape)).reshape(shape)
arr = jax.device_put(np_inp, s)
@jax.jit(out_shardings=Format(Layout.AUTO), donate_argnums=0)
def f(x):
return x * x
f(arr)
self.assertTrue(arr.is_deleted())
def test_layout_donation_matching_in_and_out(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
s = NamedSharding(mesh, P('x', 'y'))
shape = (128, 16)
np_inp = np.arange(math.prod(shape)).reshape(shape)
custom_dll = Layout(major_to_minor=(0, 1))
l = Format(custom_dll, s)
arr = jax.device_put(np_inp, l)
@jax.jit(in_shardings=l, out_shardings=l, donate_argnums=0)
def f(x):
return x * x
f(arr)
self.assertTrue(arr.is_deleted())
@jtu.skip_on_devices('cpu', 'gpu')
def test_layout_donation_mismatching_in_and_out_fails(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
s = NamedSharding(mesh, P('x', 'y'))
shape = (16*2, 32016*2)
np_inp = np.arange(math.prod(shape), dtype=jnp.bfloat16).reshape(shape)
tiling = ((8, 128), (2, 1))
custom_dll1 = Layout(major_to_minor=(1, 0), tiling=tiling)
l1 = Format(custom_dll1, s)
arr = jax.device_put(np_inp, s)
@jax.jit(out_shardings=l1, donate_argnums=0)
def f(x):
return x * x
sds = jax.ShapeDtypeStruct(np_inp.shape, np_inp.dtype, sharding=s)
f.lower(sds).compile()(arr)
self.assertFalse(arr.is_deleted())
def test_donation_error_on_auto(self):
@jax.jit(donate_argnums=0, in_shardings=Format(Layout.AUTO))
def f(x):
return x * 2
with self.assertRaisesRegex(
ValueError, ".*Did you mean to set the.*output layout.*AUTO.*"):
f(jnp.arange(8))
@jax.jit(donate_argnums=0, out_shardings=Format(Layout.AUTO))
def g(x):
return x * 2
with self.assertRaisesRegex(
ValueError, ".*Did you mean to set the.*input layout.*AUTO.*"):
g(jnp.arange(8))
def test_cpp_layout_cache_miss(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
s = NamedSharding(mesh, P('x', 'y'))
shape = (16, 16)
np_inp = np.arange(math.prod(shape)).reshape(shape)
arr = jax.device_put(np_inp, s)
arr_m2m = arr.format.layout.major_to_minor
custom_format = Format(Layout(major_to_minor=arr_m2m[::-1]), s)
arr2 = jax.device_put(np_inp, custom_format)
@jax.jit
def f(x):
return x @ x.T
with jtu.count_pjit_cpp_cache_miss() as count:
out = f(arr)
out2 = f(arr2)
self.assertEqual(count(), 2)
self.assertArraysEqual(out, np_inp @ np_inp.T)
self.assertArraysEqual(out2, np_inp @ np_inp.T)
def test_layout_donation_with_default_layout(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
s = NamedSharding(mesh, P('x', 'y'))
shape = (16, 16)
np_inp = np.arange(math.prod(shape)).reshape(shape)
arr = jax.device_put(np_inp, s)
out_format = Format(arr.format.layout, s)
@jax.jit(out_shardings=out_format, donate_argnums=0)
def f(x):
return x * 2
lowered_text = f.lower(arr).as_text()
self.assertIn('tf.aliasing_output = 0', lowered_text)
self.assertNotIn('jax.buffer_donor', lowered_text)
out = f(arr)
self.assertArraysEqual(out, np_inp * 2)
self.assertEqual(out.format, out_format)
def test_with_layout_constraint(self):
if not jtu.test_device_matches(['tpu']):
self.skipTest('Only works for TPU')
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
shape = (16, 128)
s = NamedSharding(mesh, P('x'))
np_inp = np.arange(math.prod(shape)).reshape(shape)
arr = jax.device_put(np_inp, s)
# Create a custom layout instead of using `arr.layout` to test the API.
custom_dll = Layout(major_to_minor=arr.format.layout.major_to_minor[::-1])
def f(x):
y = x.T
# Constrain `y` to the original layout of `arr` because without it,
# the layout of `y` would be the transpose of `arr`.
y = with_layout_constraint(y, custom_dll)
return y * 2
f(arr) # doesn't crash
f = jax.jit(f)
out = f(arr)
self.assertEqual(out.format.layout.major_to_minor,
custom_dll.major_to_minor)
self.assertArraysEqual(out, np_inp.T * 2)
lowered_text = f.lower(arr).as_text()
self.assertIn('LayoutConstraint', lowered_text)
def test_with_layout_constraint_with_tiling(self):
if not jtu.test_device_matches(['tpu']):
self.skipTest('Only works for TPU')
if not jtu.stablehlo_version_at_least('1.18.0'):
self.skipTest('Requires stablehlo 1.18.0 or higher')
shape = (64, 256)
np_inp = np.arange(math.prod(shape), dtype=jnp.bfloat16).reshape(shape)
arr = jax.device_put(np_inp)
# Create a custom layout instead of using `arr.layout` to test the API.
custom_dll = Layout(
major_to_minor=arr.format.layout.major_to_minor[::-1],
tiling=((16, 128), (2, 1)),
)
@jax.jit
def f(x):
y = x.T
# Constrain `y` to the original layout of `arr` because without it,
# the layout of `y` would be the transpose of `arr`.
return with_layout_constraint(y, custom_dll) * 2
out = f(arr)
self.assertEqual(
out.format.layout.major_to_minor, custom_dll.major_to_minor
)
self.assertArraysEqual(out, np_inp.T * 2)
lowered_text = f.lower(arr).as_text()
self.assertIn('LayoutConstraint', lowered_text)
self.assertIn(
'result_tilings = [[dense<[16, 128]> : tensor<2xindex>, dense<[2, 1]> :'
' tensor<2xindex>]]',
lowered_text,
)
def test_with_layout_constraint_vmap(self):
if not jtu.test_device_matches(['tpu']):
self.skipTest('Only works for TPU')
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
shape = (16, 128)
s = NamedSharding(mesh, P('x'))
np_inp = np.arange(math.prod(shape)).reshape(shape)
arr = jax.device_put(np_inp, s)
def f(x):
y = x.T
# Constrain `y` to the original layout of `arr` because without it,
# the layout of `y` would be the transpose of `arr`.
y = with_layout_constraint(y, Layout(major_to_minor=(0,)))
return y * 2
out = jax.jit(jax.vmap(f))(arr)
self.assertEqual(out.format.layout.major_to_minor, (0, 1))
def test_eval_shape_format(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
s = NamedSharding(mesh, P('x', 'y'))
shape = (128, 16)
np_inp = np.arange(math.prod(shape)).reshape(shape)
custom_dll = Layout(major_to_minor=(0, 1))
l = Format(custom_dll, s)
arr = jax.device_put(np_inp, l)
@jax.jit(in_shardings=l, out_shardings=l)
def f(x):
return x * x
out = jax.eval_shape(f, arr)
self.assertEqual(out.format, l)
self.assertEqual(out.sharding, s)
def test_valid_custom_layout_after_copy_across_clients(self):
if not jtu.test_device_matches(['tpu']):
self.skipTest('Only works for TPU')
custom_dll = Layout(major_to_minor=(1, 0))
cpu_sharding = make_single_device_sharding(
jax.local_devices(backend='cpu')[0])
cpu_format = Format(custom_dll, cpu_sharding)
cpu_array = jax.device_put(np.ones((128, 8)), cpu_format)
mesh = jtu.create_mesh((1, 1), ('x', 'y'))
tpu_sharding = jax.sharding.NamedSharding(mesh, P())
tpu_format = Format(custom_dll, tpu_sharding)
copied_tpu_array = jax.device_put(cpu_array, tpu_format.sharding)
canonical_tpu_array = jax.device_put(np.ones((128, 8)), tpu_format)
self.assertEqual(
copied_tpu_array.format.layout, canonical_tpu_array.format.layout)
@parameterized.named_parameters(
('device_to_pinned_host', 'device', 'pinned_host'),
('pinned_host_to_device', 'pinned_host', 'device'),
('device_to_unpinned_host', 'device', 'unpinned_host'),
('unpinned_host_to_device', 'unpinned_host', 'device'),
('pinned_host_to_unpinned_host', 'pinned_host', 'unpinned_host'),
('unpinned_host_to_pinned_host', 'unpinned_host', 'pinned_host'),
)
def test_valid_layout_after_copy_across_memories(
self, src_memory_kind, dst_memory_kind):
if not jtu.test_device_matches(['tpu']):
self.skipTest('Only works for TPU')
custom_dll = Layout(major_to_minor=(1, 0))
mesh = jtu.create_mesh((1, 1), ('x', 'y'))
src_tpu_sharding = jax.sharding.NamedSharding(
mesh, P(), memory_kind=src_memory_kind)
dst_tpu_sharding = jax.sharding.NamedSharding(
mesh, P(), memory_kind=dst_memory_kind)
# TPU unpinned_host memories do not support custom layouts.
if src_memory_kind == 'unpinned_host':
src_tpu_format = src_tpu_sharding
else:
src_tpu_format = Format(custom_dll, src_tpu_sharding)
if dst_memory_kind == 'unpinned_host':
dst_tpu_format = dst_tpu_sharding
else:
dst_tpu_format = Format(custom_dll, dst_tpu_sharding)
tpu_array = jax.device_put(np.ones((128, 8)), src_tpu_format)
copied_tpu_array = jax.device_put(tpu_array, dst_tpu_sharding)
canonical_tpu_array = jax.device_put(np.ones((128, 8)), dst_tpu_format)
self.assertEqual(
copied_tpu_array.format.layout, canonical_tpu_array.format.layout)
@jtu.run_on_devices('tpu')
@jtu.with_explicit_mesh((2,), 'x')
def test_reshard_layout_constraint(self, mesh):
arr1 = jax.device_put(np.arange(128 * 256).reshape(128, 256), P(None, 'x'))
arr2 = jax.device_put(np.arange(128 * 256).reshape(256, 128), P('x', None))
@jax.jit
def f(x, y):
z = jnp.dot(x, y, out_sharding=P(unreduced={'x'}))
z = with_layout_constraint(z, Layout(major_to_minor=(1, 0)))
z = z + z
return with_layout_constraint(z, Layout(major_to_minor=(1, 0)))
out = f(arr1, arr2)
self.assertArraysEqual(jax.reshard(out, P()),
jnp.dot(arr1, arr2, out_sharding=P()) * 2)
self.assertEqual(out.sharding,
NamedSharding(mesh, P(None, None, unreduced={'x'})))
self.assertEqual(out.format.layout.major_to_minor, (1, 0))
self.assertNotIn('all-reduce(', f.lower(arr1, arr2).compile().as_text())
def test_layout_propagation_host(self):
mesh = jtu.create_mesh((2,), 'x')
arr = jnp.ones((5, 2, 1004, 512, 36), dtype=jnp.float32)
host_sharding = jax.NamedSharding(mesh, jax.P(), memory_kind='pinned_host')
host_format = Format(layout=Layout((0, 1, 4, 2, 3)),
sharding=host_sharding)
@jax.jit(out_shardings=host_format)
def test_fun(x):
return with_layout_constraint(x * 2, host_format.layout)
compiled_text = test_fun.lower(arr).compile().as_text()
match = re.search(r'->\s*f32\[5,2,1004,512,36\]\{([^}]+)\}', compiled_text)
layout_str = match.group(1)
self.assertIn('3,2,4,1,0', layout_str)
self.assertIn('S(5)', layout_str)
if __name__ == '__main__':
absltest.main(testLoader=jtu.JaxTestLoader())