-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
pjit_test.py
5316 lines (4385 loc) · 183 KB
/
pjit_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 2021 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.
from collections import OrderedDict, namedtuple
import contextlib
import re
from functools import partial
import logging
import math
import textwrap
import threading
import unittest
from absl.testing import absltest
from absl.testing import parameterized
import numpy as np
import concurrent.futures
import jax
import jax.numpy as jnp
from jax._src import core
from jax._src import config
from jax._src import test_util as jtu
from jax import dtypes
from jax import stages
from jax import lax
from jax._src.lax import lax as lax_internal
from jax.lax import with_sharding_constraint
from jax._src import prng
from jax.sharding import PartitionSpec as P, Mesh
from jax.experimental import multihost_utils
from jax.experimental.custom_partitioning import custom_partitioning
from jax._src import array
from jax._src.sharding import Sharding, common_devices_indices_map
from jax._src import op_shardings
from jax._src import sharding_impls
from jax._src.sharding_impls import (
AUTO, UNSPECIFIED, NamedSharding, GSPMDSharding, PositionalSharding,
SingleDeviceSharding, parse_flatten_op_sharding)
import jax._src.pjit as pjit_lib
from jax._src.pjit import pjit
from jax._src import mesh as mesh_lib
from jax._src.interpreters import pxla
from jax._src.lib.mlir import dialects
from jax._src import xla_bridge
from jax._src.lib import xla_client as xc
from jax._src.lib import xla_extension_version
from jax._src.lib import xla_extension
from jax._src.util import curry, unzip2
config.parse_flags_with_absl()
# Run all tests with 8 CPU devices.
_exit_stack = contextlib.ExitStack()
def setUpModule():
_exit_stack.enter_context(jtu.set_host_platform_device_count(8))
def tearDownModule():
_exit_stack.close()
def create_array(global_shape, global_mesh, mesh_axes, global_data=None,
dtype=np.float32):
if global_data is None:
global_data = np.arange(
math.prod(global_shape), dtype=dtype).reshape(global_shape)
if isinstance(mesh_axes, Sharding):
sharding = mesh_axes
else:
sharding = NamedSharding(global_mesh, mesh_axes)
return array.make_array_from_callback(
global_shape, sharding, lambda idx: global_data[idx]), global_data
def _check_instance(self, x):
self.assertIsInstance(x, array.ArrayImpl)
@curry
def check_1d_2d_mesh(f, set_mesh):
return parameterized.named_parameters(
{"testcase_name": "_" + name, "mesh": mesh, "resources": resources}
for name, mesh, resources in (
("2", (("x", 2),), "x"),
("2x1", (("x", 2), ("y", 1)), ("x", "y")),
("2x2", (("x", 2), ("y", 2)), ("x", "y")),
))(jtu.with_mesh_from_kwargs(f) if set_mesh else f)
# TODO(skye): make the buffer donation utils part of JaxTestCase
@jtu.pytest_mark_if_available('multiaccelerator')
class PJitTest(jtu.BufferDonationTestCase):
@jtu.with_mesh([('x', 1)])
def testDeviceBufferAval(self):
@partial(pjit, in_shardings=None, out_shardings=P('x'))
def f(x):
return x
shape = (2, 2)
x = np.arange(math.prod(shape), dtype=np.float32).reshape(shape)
actual = f(x)
expected = x
self.assertAllClose(actual, expected, check_dtypes=False)
_check_instance(self, actual)
self.assertLen(actual.addressable_shards, 1)
self.assertAllClose(
np.asarray(actual.addressable_shards[0].data), expected, check_dtypes=False)
# Repro for a bug on addressable_shards aval
_ = repr(actual.addressable_shards)
@jtu.with_mesh([('x', 2)])
def testBasic1D(self):
@partial(pjit,
in_shardings=(P('x'), P('x')),
out_shardings=None)
def f(x, y):
return x + y
shape = (8, 8)
x = np.arange(math.prod(shape), dtype=np.float32).reshape(shape)
actual = f(x, x + 1)
expected = x + (x + 1)
self.assertAllClose(actual, expected, check_dtypes=False)
_check_instance(self, actual)
self.assertLen(actual.addressable_shards, 2)
self.assertAllClose(np.asarray(actual.addressable_shards[0].data), expected,
check_dtypes=False)
@jtu.with_mesh([('x', 2)])
def testJitOfPjitDisallowed(self):
@partial(pjit,
in_shardings=(P('x'), P('x')),
out_shardings=None)
def f(x, y):
return x + y
shape = (8, 8)
x = np.arange(math.prod(shape), dtype=np.float32).reshape(shape)
out = jax.jit(f)(x, x + 1)
self.assertArraysEqual(out, x + x + 1)
@jtu.with_mesh([('x', 2)])
def testUnevenShardingConstraint(self):
@partial(pjit,
in_shardings=(P('x'), P('x')),
out_shardings=None)
def f(x, y):
x = x[:3]
y = y[:3]
x = with_sharding_constraint(x, P('x'))
y = with_sharding_constraint(y, P('x'))
out = x + y
return jnp.pad(out, [[0, 1]])
shape = (4,)
x = np.arange(math.prod(shape), dtype=np.float32).reshape(shape)
actual = f(x, x + 1)
expected = x + (x + 1)
self.assertAllClose(actual[:3], expected[:3], check_dtypes=False)
_check_instance(self, actual)
self.assertLen(actual.addressable_shards, 2)
self.assertAllClose(np.asarray(actual.addressable_shards[0].data)[:3],
expected[:3], check_dtypes=False)
def testBasic1DWithMeshContextManager(self):
@partial(pjit,
in_shardings=(P('x'), P('x')),
out_shardings=None)
def f(x, y):
return x + y
shape = (8, 8)
x = np.arange(math.prod(shape), dtype=np.float32).reshape(shape)
with jtu.create_mesh((2,), ('x')) as mesh:
actual = f(x, x + 1)
expected = x + (x + 1)
self.assertEqual(mesh, jtu.create_mesh((2,), ('x')))
self.assertAllClose(actual, expected, check_dtypes=False)
_check_instance(self, actual)
self.assertLen(actual.addressable_shards, 2)
self.assertAllClose(np.asarray(actual.addressable_shards[0].data), expected,
check_dtypes=False)
@jtu.with_mesh([('x', 2), ('y', 2)])
def testBasic2D(self):
@partial(pjit,
in_shardings=(P(None, 'x', 'y'), P('y')),
out_shardings=P('x'))
def f(x, y):
return x @ y
x_shape = (8, 6, 4)
y_shape = (4, 2)
x = jnp.arange(math.prod(x_shape)).reshape(x_shape)
y = jnp.arange(math.prod(y_shape)).reshape(y_shape)
actual = f(x, y)
expected = x @ y
self.assertAllClose(actual, expected, check_dtypes=False)
_check_instance(self, actual)
self.assertLen(actual.addressable_shards, 4)
split0, split1 = np.split(expected, 2)
self.assertAllClose(np.asarray(actual.addressable_shards[0].data), split0,
check_dtypes=False)
self.assertAllClose(np.asarray(actual.addressable_shards[1].data), split0,
check_dtypes=False)
self.assertAllClose(np.asarray(actual.addressable_shards[2].data), split1,
check_dtypes=False)
self.assertAllClose(np.asarray(actual.addressable_shards[3].data), split1,
check_dtypes=False)
def testDifferentNestedMesh(self):
with jtu.create_mesh((2, 1), ("x", "y")) as m1:
with jtu.create_mesh((2, 2), ("a", "b")) as m2:
self.assertEqual(mesh_lib.thread_resources.env.physical_mesh, m2)
self.assertEqual(mesh_lib.thread_resources.env.physical_mesh, m1)
self.assertEqual(mesh_lib.thread_resources.env.physical_mesh,
mesh_lib.EMPTY_ENV.physical_mesh)
def testSameNestedMesh(self):
mesh = jtu.create_mesh((2, 1), ("a", "b"))
thread_resources = mesh_lib.thread_resources
with mesh as m1:
with mesh as m2:
self.assertEqual(thread_resources.env.physical_mesh, m2)
self.assertEqual(thread_resources.env.physical_mesh, m1)
self.assertEqual(thread_resources.env.physical_mesh,
mesh_lib.EMPTY_ENV.physical_mesh)
def testMeshDecorator(self):
x = jnp.arange(8)
mesh_shape = (2, 2)
size = math.prod(mesh_shape)
if len(jax.devices()) < size:
raise unittest.SkipTest(f"Test requires {size} global devices.")
mesh_devices = np.array(jax.devices()[:size]).reshape(mesh_shape)
@jax.sharding.Mesh(mesh_devices, ('x', 'y'))
def dec():
return pjit(lambda x: x, in_shardings=P('x'), out_shardings=None)(x)
out = dec()
self.assertArraysEqual(out, x)
def testMeshHashRace(self):
mesh = jtu.create_mesh((2, 1), ('a', 'testMeshHashRace'))
self.assertFalse(hasattr(mesh, '_hash'))
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as pool:
fs = []
for _ in range(5):
fs.append(pool.submit(lambda: hash(mesh)))
for f in concurrent.futures.as_completed(fs):
f.result()
self.assertTrue(hasattr(mesh, '_hash'))
@jtu.with_mesh([('x', 2), ('y', 2)])
def testTwoMeshAxisSharding(self):
@partial(pjit,
in_shardings=P(('x', 'y'),),
out_shardings=jax.sharding.PartitionSpec(('x', 'y'),))
def f(x, y):
return x @ y
shape = (8, 8)
x = jnp.arange(math.prod(shape)).reshape(shape)
actual = f(x, x + 1)
expected = x @ (x + 1)
self.assertAllClose(actual, expected, check_dtypes=False)
_check_instance(self, actual)
self.assertLen(actual.addressable_shards, 4)
splits = np.split(expected, 4)
self.assertAllClose(np.asarray(actual.addressable_shards[0].data), splits[0],
check_dtypes=False)
self.assertAllClose(np.asarray(actual.addressable_shards[1].data), splits[1],
check_dtypes=False)
self.assertAllClose(np.asarray(actual.addressable_shards[2].data), splits[2],
check_dtypes=False)
self.assertAllClose(np.asarray(actual.addressable_shards[3].data), splits[3],
check_dtypes=False)
@jtu.with_mesh([('x', 2)])
@jtu.run_on_devices('cpu', 'gpu', 'tpu')
def testBufferDonation(self):
@partial(pjit, in_shardings=P('x'), out_shardings=P('x'), donate_argnums=0)
def f(x, y):
return x + y
shard = pjit(lambda x: x, in_shardings=P('x'), out_shardings=P('x'))
x = shard(jnp.ones((2, 5)) * 4)
y = shard(jnp.ones((2, 5)) * 2)
expected = x + y
self.assertAllClose(f(x, y), expected)
self.assertNotDeleted(y)
self.assertDeleted(x)
@jtu.run_on_devices('cpu', 'gpu', 'tpu')
def testBufferDonationWithNames(self):
mesh = jtu.create_mesh((2,), ('x'))
s = NamedSharding(mesh, P('x'))
@partial(pjit, out_shardings=s, donate_argnames='inp2')
def f(inp1, inp2):
return inp1 + inp2
x = jax.device_put(np.ones((2, 5)) * 4, s)
y = jax.device_put(np.ones((2, 5)) * 2, s)
expected = x + y
self.assertAllClose(f(x, y), expected)
self.assertNotDeleted(x)
self.assertDeleted(y)
@jtu.run_on_devices('cpu', 'gpu', 'tpu')
def testBufferDonationWithKwargs(self):
mesh = jtu.create_mesh((2,), ('x'))
s = NamedSharding(mesh, P('x'))
@partial(pjit, out_shardings=s, donate_argnames=('inp2', 'inp3'))
def f(inp1, inp2, inp3):
return inp1 + inp2 + inp3, inp3
x = jax.device_put(np.ones((2, 5)) * 4, s)
y = jax.device_put(np.ones((2, 5)) * 2, s)
z = jax.device_put(np.ones((2, 5)), s)
expected = x + y + z
self.assertAllClose(f(x, inp2=y, inp3=z)[0], expected)
self.assertNotDeleted(x)
self.assertDeleted(y)
self.assertDeleted(z)
@jtu.run_on_devices('cpu', 'gpu', 'tpu')
def testBufferDonationWithPyTreeKwargs(self):
mesh = jtu.create_mesh((2,), ('x'))
s = NamedSharding(mesh, P('x'))
@partial(pjit, out_shardings=s, donate_argnames='inp2')
def f(inp1, inp2, inp3):
return jax.tree.map(lambda x, y, z: x + y + z, inp1, inp2, inp3)
x = np.ones((2, 5)) * 4
x_tree = jax.device_put({"a": {"b": x}, "c": x}, s)
y = np.ones((2, 5)) * 2
y_tree = jax.device_put({"a": {"b": y}, "c": y}, s)
z = np.ones((2, 5))
z_tree = jax.device_put({"a": {"b": z}, "c": z}, s)
expected = x + y + z
out = f(x_tree, inp2=y_tree, inp3=z_tree)
jax.tree.map(lambda o: self.assertAllClose(o, expected), out)
jax.tree.map(self.assertNotDeleted, x_tree)
jax.tree.map(self.assertDeleted, y_tree)
jax.tree.map(self.assertNotDeleted, z_tree)
@jtu.run_on_devices('tpu', 'cpu', 'gpu')
def testBufferDonationWithOutputShardingInference(self):
mesh = jtu.create_mesh((2,), 'x')
s = NamedSharding(mesh, P('x'))
rs = NamedSharding(mesh, P())
@partial(pjit, donate_argnames=('inp2', 'inp3'))
def f(inp1, inp2, inp3):
return (
jax.lax.with_sharding_constraint(inp1, rs),
inp1,
jax.lax.with_sharding_constraint(inp2, rs),
inp2,
jax.lax.with_sharding_constraint(inp3, rs),
inp3,
)
x = np.ones((2, 5)) * 4
x_tree = jax.device_put({'a': {'b': x}, 'c': x}, s)
y = np.ones((2, 7)) * 2
y_tree = jax.device_put({'a': {'b': y}, 'c': y}, s)
z = np.ones((2, 11))
z_tree = jax.device_put({'a': {'b': z}, 'c': z}, s)
out = f(x_tree, y_tree, z_tree)
jax.tree.map(self.assertNotDeleted, x_tree)
jax.tree.map(self.assertDeleted, y_tree)
jax.tree.map(self.assertDeleted, z_tree)
@jtu.run_on_devices('tpu')
def testBufferDonationWithOutputShardingInferenceAndTokens(self):
if config.use_shardy_partitioner.value:
self.skipTest('b/355263220: Shardy does not support callbacks yet.')
mesh = jtu.create_mesh((2,), 'x')
s = NamedSharding(mesh, P('x'))
def _callback(x):
self.assertIsInstance(x, jax.Array)
@partial(pjit, donate_argnames=('x'))
def f(x):
# Just to get tokens.
jax.experimental.io_callback(_callback, None, x, ordered=True)
jax.experimental.io_callback(_callback, None, x, ordered=True)
return x * x
x = np.ones((2, 5)) * 4
x = jax.device_put(x, s)
f(x)
jax.effects_barrier()
self.assertDeleted(x)
@jtu.run_on_devices('tpu', 'cpu', 'gpu')
def testBufferDonationNotDonated(self):
mesh = jtu.create_mesh((2,), 'x')
s = NamedSharding(mesh, P('x'))
@partial(pjit, donate_argnames=('x'))
def f(x):
return x @ x.T
x = jax.device_put(np.arange(16).reshape(8, 2), s)
f(x)
self.assertNotDeleted(x)
@jtu.with_mesh([('x', 2), ('y', 1)])
def testShardingConstraintStablehlo(self):
@partial(pjit, in_shardings=None, out_shardings=None)
def f(x):
y = x + 1
y = with_sharding_constraint(y, P('x', 'y'))
return y * 2
shape = (8, 8)
x = np.arange(math.prod(shape)).reshape(shape)
expected = (x + 1) * 2
actual = f(x)
self.assertAllClose(actual, expected, check_dtypes=False)
_check_instance(self, actual)
self.assertLen(actual.addressable_shards, 2)
self.assertAllClose(np.asarray(actual.addressable_shards[0].data), expected,
check_dtypes=False)
hlo = f.lower(np.ones(shape)).compiler_ir()
if config.use_shardy_partitioner.value:
# Annotation from with_sharding_constraint
self.assertIn('<@mesh, [{"x"}, {"y"}]>', str(hlo))
# Annotation from pjit
self.assertIn('sharding = #sdy.sharding<@mesh, [{}, {}]>}', str(hlo))
else:
# Annotation from with_sharding_constraint
self.assertIn('sharding = "{devices=[2,1]<=[2]}"', str(hlo))
# Annotation from pjit
self.assertIn('sharding = "{replicated}"', str(hlo))
def testShardingConstraintWithArray(self):
mesh = jtu.create_mesh((2, 1), ('x', 'y'))
s = NamedSharding(mesh, P(None))
@partial(pjit, in_shardings=s, out_shardings=s)
def f(x):
y = x + 1
y = with_sharding_constraint(y, NamedSharding(mesh, P('x', 'y')))
return y * 2
shape = (8, 8)
x = np.arange(math.prod(shape)).reshape(shape)
expected = (x + 1) * 2
actual = f(x)
self.assertAllClose(actual, expected, check_dtypes=False)
self.assertIsInstance(actual, array.ArrayImpl)
self.assertLen(actual.addressable_shards, 2)
self.assertAllClose(actual, expected, check_dtypes=False)
hlo = f.lower(np.ones(shape)).compiler_ir(dialect="hlo")
# Annotation from with_sharding_constraint
self.assertIn('sharding={devices=[2,1]<=[2]}', hlo.as_hlo_text())
# Annotation from pjit
self.assertIn("sharding={replicated}", hlo.as_hlo_text())
def testShardingConstraintWithArrayOpSharding(self):
if config.use_shardy_partitioner.value:
self.skipTest("Shardy doesn't support PositionalSharding")
shape = (8, 8)
mesh = jtu.create_mesh((2, 1), ('x', 'y'))
s = NamedSharding(mesh, P(None))
ops = pxla.to_gspmd_sharding(
NamedSharding(mesh, P('x', 'y')), len(shape))
@partial(pjit, in_shardings=s, out_shardings=s)
def f(x):
y = x + 1
y = with_sharding_constraint(y, ops)
return y * 2
x = np.arange(math.prod(shape)).reshape(shape)
expected = (x + 1) * 2
actual = f(x)
self.assertAllClose(actual, expected, check_dtypes=False)
self.assertIsInstance(actual, array.ArrayImpl)
self.assertLen(actual.addressable_shards, 2)
self.assertAllClose(actual, expected, check_dtypes=False)
hlo = f.lower(np.ones(shape)).compiler_ir(dialect="hlo")
# Annotation from with_sharding_constraint
self.assertIn('sharding={devices=[2,1]<=[2]}', hlo.as_hlo_text())
# Annotation from pjit
self.assertIn("sharding={replicated}", hlo.as_hlo_text())
def testShardingConstraintPyTreeWithArray(self):
mesh = jtu.create_mesh((2, 1), ('x', 'y'))
@jax.jit
def f(x):
return with_sharding_constraint(x, NamedSharding(mesh, P('x', 'y')))
shape = (8, 8)
v = np.arange(math.prod(shape)).reshape(shape)
x = [v, v * 2]
out = f(x)
self.assertArraysEqual(out[0], v)
self.assertArraysEqual(out[1], v * 2)
self.assertLen(out[0].addressable_shards, 2)
self.assertLen(out[1].addressable_shards, 2)
hlo = f.lower(x).compiler_ir(dialect="hlo")
# Annotations from with_sharding_constraint
self.assertIn('sharding={devices=[2,1]<=[2]}', hlo.as_hlo_text())
self.assertIn('sharding={devices=[2,1]<=[2]}', hlo.as_hlo_text())
def testShardingConstraintPyTreeWithUnconstrainedDimsWithJit(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
@jax.jit
def f(x):
x = with_sharding_constraint(
x, [NamedSharding(mesh, P(P.UNCONSTRAINED, 'y', None)),
NamedSharding(mesh, P('x', P.UNCONSTRAINED, None))])
x = x.copy()
x[0]['a'] *= 2
return x
shape = (2, 8, 8)
v = np.arange(math.prod(shape)).reshape(shape)
x = [{'a': v, 'b': v * 2}, v * 3]
actual = f(x)
expected = x.copy()
expected[0]['a'] *= 2
self.assertAllClose(actual, expected, check_dtypes=False)
self.assertLen(actual[0]['a'].addressable_shards, 4)
mlir_str = str(f.lower(x).compiler_ir())
if config.use_shardy_partitioner.value:
self.assertIn('<@mesh, [{?}, {"y"}, {}]>', mlir_str)
self.assertIn('<@mesh, [{"x"}, {?}, {}]>', mlir_str)
else:
self.assertIn("unspecified_dims=[0]", mlir_str)
self.assertIn("unspecified_dims=[1]", mlir_str)
@jtu.with_mesh([('x', 2), ('y', 2)])
def testShardingConstraintPyTreeVmapWithUnconstrainedDims(self):
@partial(pjit, in_shardings=None, out_shardings=None)
def f(x):
x = jax.vmap(lambda x: with_sharding_constraint(
x, [P(P.UNCONSTRAINED, 'y'),
P('x', P.UNCONSTRAINED)]))(x)
x = x.copy()
x[0]['a'] *= 2
return x
shape = (2, 8, 8)
v = np.arange(math.prod(shape)).reshape(shape)
x = [{'a': v, 'b': v * 2}, v * 3]
mlir_str = str(f.lower(x).compiler_ir())
if config.use_shardy_partitioner.value:
self.assertIn('<@mesh, [{?}, {?}, {"y"}]>', mlir_str)
self.assertIn('<@mesh, [{?}, {"x"}, {?}]>', mlir_str)
else:
self.assertIn("unspecified_dims=[0,1]", mlir_str)
self.assertIn("unspecified_dims=[0,2]", mlir_str)
def testCaching(self):
def f(x):
assert should_be_tracing
return jnp.sin(x) * 2
x = np.arange(16).reshape(4, 4)
devices = np.array(list(jax.local_devices())[:4])
if devices.size < 4:
raise unittest.SkipTest("Test requires 4 devices")
devices = devices.reshape((2, 2))
with jax.sharding.Mesh(devices, ('x', 'y')):
should_be_tracing = True
pjit(f, in_shardings=P(('x', 'y')), out_shardings=None)(x)
should_be_tracing = False
pjit(f, in_shardings=P(('x', 'y')), out_shardings=None)(x)
# Re-create the mesh to make sure that has no influence on caching
with jax.sharding.Mesh(devices, ('x', 'y')):
should_be_tracing = False
pjit(f, in_shardings=P(('x', 'y')), out_shardings=None)(x)
@jtu.with_mesh([('x', 2), ('y', 1)])
def testNested(self):
# Add a constant captured by the nested pjit to make things more complicated
h = jnp.arange(4.)
f = pjit(
lambda x: x.sum() + h.sum(),
in_shardings=P('x', 'y'),
out_shardings=None,
)
g = pjit(
lambda x: f(jnp.sin(x)), in_shardings=P('x', None), out_shardings=None
)
x = jnp.arange(16.).reshape((4, 4))
y = g(x)
self.assertAllClose(y, jnp.sin(x).sum() + h.sum())
_check_instance(self, y)
@check_1d_2d_mesh(set_mesh=True)
def testAutodiff(self, mesh, resources):
if len(mesh) != 2: return
assert resources == ('x', 'y')
# Add a constant captured by the nested pjit to make things more complicated
h = jnp.arange(4.)
f = pjit(
lambda x: x.sum(1) * h.sum(),
in_shardings=P('x', 'y'),
out_shardings=P(('x', 'y')),
)
g = pjit(
lambda x: f(jnp.sin(x * 4 + 2)),
in_shardings=P('x', None),
out_shardings=P(('x', 'y')),
)
jtu.check_grads(g, (jnp.arange(16.).reshape((4, 4)) / 100,), order=2)
@jtu.with_mesh([('x', 2), ('y', 1)])
def testAutodiffCache(self):
f = pjit(
lambda x: jnp.sin(x).sum(), in_shardings=P('x'), out_shardings=None
)
x = jnp.arange(16, dtype=jnp.float32)
jax.grad(f)(x) # Warm up the cache.
before = pjit_lib._pjit_lower_cached.cache_info()
jax.grad(f)(x)
after = pjit_lib._pjit_lower_cached.cache_info()
# One hit for the forward pass, one hit for backward.
self.assertEqual(after.hits, before.hits + 2)
self.assertEqual(after.misses, before.misses)
@jtu.with_mesh([('x', 2), ('y', 1)])
def testEvalJaxpr(self):
x, y = jnp.arange(4.), jnp.arange(5.)
f = pjit(
lambda x, y: x.sum() + jnp.sin(y),
in_shardings=(P('x'), P('y')),
out_shardings=P('y'),
)
f_jaxpr = jax.make_jaxpr(f)(x, y)
f_eval = core.jaxpr_as_fun(f_jaxpr)
r, = f_eval(x, y)
self.assertAllClose(r, x.sum() + jnp.sin(y))
@jtu.with_mesh([('x', 2)])
def testNonArrayArg(self):
self.assertEqual(
pjit(lambda x: x + 2, in_shardings=None, out_shardings=None)(1), 3
)
@jtu.with_mesh([('x', 2)])
def testNonHashableAxisResources(self):
x = jnp.arange(4)
y = pjit(
lambda x: {'b': x['a'] + 2},
in_shardings=({'a': P('x')},),
out_shardings={'b': P('x')},
)({'a': x})
self.assertAllClose(y, {'b': x + 2})
@jtu.with_mesh([('x', 2)])
def testGradOfConstraint(self):
# Make sure that we can compute grads through sharding constraints
h = lambda x: jnp.sin(with_sharding_constraint(x, P('x'))).sum()
f = pjit(lambda x: jax.grad(h)(x), in_shardings=None, out_shardings=None)
x = jnp.arange(8, dtype=jnp.float32)
out = f(x)
self.assertAllClose(out, jnp.cos(x))
self.assertLen(out.devices(), 2)
@jtu.with_mesh([('x', 2)])
def testNoopPartitionSpecs(self):
noops = [P(), P(None), P(()), P((), None), P(None, None, ())]
x = jnp.arange(8).reshape((2, 2, 2))
for spec in noops:
y = pjit(lambda x: x * 2, in_shardings=spec, out_shardings=spec)(x)
self.assertAllClose(y, x * 2)
@jtu.with_mesh([('x', 2)])
def testVMap(self):
f = pjit(lambda x, y: (x + y, x), in_shardings=P('x'), out_shardings=P('x'))
x = jnp.arange(4)
y = jnp.arange(5*4).reshape((5, 4))
z, w = jax.vmap(f, in_axes=(None, 0), out_axes=(0, None))(x, y)
self.assertAllClose(z, x[jnp.newaxis] + y)
self.assertAllClose(w, x)
self.assertEqual(
z.sharding._to_xla_hlo_sharding(z.ndim).tile_assignment_dimensions(),
[1, 2])
self.assertEqual(
w.sharding._to_xla_hlo_sharding(w.ndim).tile_assignment_dimensions(), [2])
@jtu.with_mesh([('x', 2)])
def testVMapShardingConstraint(self):
f = pjit(
lambda x: with_sharding_constraint(x, P('x')),
in_shardings=P(),
out_shardings=P('x'),
)
x = jnp.arange(5*4).reshape((5, 4))
jaxpr = jax.make_jaxpr(jax.vmap(f))(x)
pjit_eqn, = jaxpr.eqns
constraint_eqn, = pjit_eqn.params['jaxpr'].eqns
op = constraint_eqn.params['sharding']._to_xla_hlo_sharding(x.ndim)
self.assertTrue(op.is_tiled())
self.assertListEqual(op.tile_assignment_dimensions(), [1, 2])
self.assertListEqual(op.tile_assignment_devices(), [0, 1])
self.assertFalse(op_shardings.is_op_sharding_replicated(op))
@jtu.with_mesh([('x', 2)])
def testVMapShardingConstraintWithSpmdAxis(self):
f = pjit(
jax.vmap(
lambda x: with_sharding_constraint(x, P(None)),
spmd_axis_name='x',
),
in_shardings=P('x'),
out_shardings=P('x'),
)
x = jnp.arange(16 * 4).reshape((16, 4))
jaxpr = jax.make_jaxpr(f)(x)
pjit_eqn, = jaxpr.eqns
constraint_eqn, = pjit_eqn.params['jaxpr'].eqns
op = constraint_eqn.params['sharding']._to_xla_hlo_sharding(x.ndim)
self.assertTrue(op.is_tiled())
self.assertListEqual(op.tile_assignment_dimensions(), [2, 1])
self.assertListEqual(op.tile_assignment_devices(), [0, 1])
self.assertFalse(op_shardings.is_op_sharding_replicated(op))
@jtu.with_mesh([('x', 2)])
def testLowerWithDuckTyping(self):
x = jax.ShapeDtypeStruct((2, 2), jnp.float32)
# Make sure this doesn't crash
pjit(lambda x: x + 4, in_shardings=P('x'), out_shardings=P('x')).lower(x)
@jtu.with_mesh([('x', 2)])
def testLowerDonateArgnumsAvailable(self):
x = jax.ShapeDtypeStruct((2, 2), jnp.float32)
def f(*args):
x, *_ = args
return x
f_low = pjit(f, donate_argnums=(0,),
in_shardings=P('x'), out_shardings=P('x')).lower(x)
f_com = f_low.compile()
f_low.donate_argnums == f_com.donate_argnums == (0,)
@jtu.with_mesh([('x', 2)])
def testLowerDonateArgnumsAvailableWithNames(self):
x = jax.ShapeDtypeStruct((2, 2), jnp.float32)
def f(inp1):
return inp1
f_low = pjit(f, in_shardings=P('x'), out_shardings=P('x'),
donate_argnames=('inp1',)).lower(x)
f_com = f_low.compile()
f_low.donate_argnums == f_com.donate_argnums == (0,)
@unittest.skip('Fails in OSS builds on GPU with jax at HEAD and latest '
'jaxlib on pypi.')
def testInfeed(self):
devices = np.array(jax.local_devices())
nr_devices = len(devices)
shape = (nr_devices * 3, nr_devices * 5)
def f_for_jit(x):
token = lax.create_token(x)
(y,), token = lax.infeed(
token, shape=(core.ShapedArray(x.shape, np.float32),))
(z,), token = lax.infeed(
token, shape=(core.ShapedArray(x.shape, np.float32),))
(w,), token = lax.infeed(
token, shape=(core.ShapedArray(x.shape, np.float32),))
return x + y + z + w
x = np.arange(math.prod(shape), dtype=np.float32).reshape(shape)
y = x * 2.
z = x * 3.
w = x * 4.
# Transfer data to infeed before executing the function. For GPUs, the
# execution of the compiled function is blocking, so transferring data
# to infeed before executing ensures that the execution does not deadlock
# waiting for the infeed data.
logging.info('Transferring to infeed for the jit call')
d = devices[0]
d.transfer_to_infeed((y,))
d.transfer_to_infeed((z,))
d.transfer_to_infeed((w,))
# JIT
logging.info('Making jit call')
res0 = jax.jit(f_for_jit)(x)
self.assertAllClose(res0, x + y + z + w, check_dtypes=True)
# PJIT
def f_for_pjit(x):
token = lax.create_token(x)
# A replicated infeed
(y,), token = lax.infeed(
token,
shape=(core.ShapedArray(x.shape, np.float32),),
partitions=(None,))
# An infeed sharded on first axis
(z,), token = lax.infeed(
token,
shape=(core.ShapedArray(x.shape, np.float32),),
partitions=(P(nr_devices, 1),))
# An infeed sharded on second axis
(w,), token = lax.infeed(
token,
shape=(core.ShapedArray(x.shape, np.float32),),
partitions=(P(1, nr_devices),))
return x + y + z + w
logging.info('Transferring to infeed for the pjit call')
for didx, d in enumerate(devices):
# Transfer the whole array to all devices for replicated.
d.transfer_to_infeed((y,))
# For sharded infeed, transfer only the needed slices to each device.
d.transfer_to_infeed(z[3 * didx:3 * didx + 3, :])
d.transfer_to_infeed((w[:, 5 * didx:5 * didx + 5],))
with jax.sharding.Mesh(devices, ['d']):
logging.info('Making pjit call')
res = pjit(f_for_pjit, in_shardings=(P('d'),), out_shardings=P('d'))(x)
self.assertAllClose(res0, res, check_dtypes=True)
def testOutfeed(self):
if xla_bridge.using_pjrt_c_api():
raise unittest.SkipTest('outfeed not implemented in PJRT C API')
if config.use_shardy_partitioner.value:
self.skipTest(
'b/355263220: outfeed lowering not supported by Shardy')
devices = np.array(jax.local_devices())
nr_devices = len(devices)
shape = (nr_devices * 3, nr_devices * 5)
def f(x):
token = lax.create_token(x)
token = lax.outfeed(token, x, partitions=(None,))
token = lax.outfeed(token, x, partitions=(P(nr_devices, 1),))
token = lax.outfeed(token, x, partitions=(P(1, nr_devices),))
return x
x = np.arange(math.prod(shape), dtype=np.float32).reshape(shape)
def _dispatch():
with jax.sharding.Mesh(devices, ['d']):
logging.info('Making pjit call')
pjit(f, in_shardings=(P('d'),), out_shardings=P('d'))(x)
execution = threading.Thread(target=_dispatch)
execution.start()
# Check the expected outfeed for all devices.
def check_outfeed(x_fn):
for didx, d in enumerate(devices):
x = x_fn(didx)
y, = d.transfer_from_outfeed(
xc.shape_from_pyval((x,)).with_major_to_minor_layout_if_absent())
self.assertAllClose(x, y, check_dtypes=True)
logging.info('Transferring from outfeed for the pjit call')
# Note, when checking results of multiple outfeeds, the loop structure
# should be such that we check a given outfeed for all devices before
# moving on to the next outfeed. If there are any collectives generated
# by pjit, a loop structutre like:
# for each device:
# check outfeed#0;
# check outfeed#1;
#
# Could cause a deadlock if there is a collective scheduled between the
# 2 outfeeds, as device #0, after processing outfeed#0 will execute the
# collective, waiting for other devices to join, but other devices won't
# execute their collective until their outfeed#0 is executed. This is
# because, for GPU for example, execution of an outfeed on GPU is blocked
# till the corresponding `transfer_from_outfeed` is executed on the host.
# Transfer the whole array from all devices for replicated.
check_outfeed(lambda didx: x)
# For sharded outfeed, the results are sliced.
check_outfeed(lambda didx: x[3 * didx:3 * didx + 3, :])
check_outfeed(lambda didx: x[:, 5 * didx:5 * didx + 5])
execution.join()
@jtu.with_mesh([('x', 2)])
def testWithCustomPRNGKey(self):
if not config.enable_custom_prng.value:
raise unittest.SkipTest("test requires jax_enable_custom_prng")
key = prng.random_seed(87, impl=prng.rbg_prng_impl)
# Make sure this doesn't crash
pjit(lambda x: x, in_shardings=None, out_shardings=None)(key)
@jtu.with_mesh([('x', 2), ('y', 2)])
def testLowerCompile(self):
@partial(pjit,
in_shardings=P(('x', 'y'),),
out_shardings=P(('x', 'y'),))
def f(x, y):
return x @ y
shape = (8, 8)
x = jnp.arange(math.prod(shape)).reshape(shape)
expected = x @ (x + 1)
lowered = f.lower(x, x + 1)
compiled = lowered.compile()
actual = compiled(x, x + 1)
self.assertEqual(lowered.in_avals, compiled.in_avals)
self.assertEqual(
lowered.in_avals,
((core.ShapedArray(x.shape, x.dtype, weak_type=False),) * 2, {}))
splits = np.split(expected, 4)
self.assertAllClose(np.asarray(actual.addressable_shards[0].data), splits[0],
check_dtypes=False)
self.assertAllClose(np.asarray(actual.addressable_shards[1].data), splits[1],
check_dtypes=False)
self.assertAllClose(np.asarray(actual.addressable_shards[2].data), splits[2],
check_dtypes=False)
self.assertAllClose(np.asarray(actual.addressable_shards[3].data), splits[3],
check_dtypes=False)
for obj in [lowered, compiled]:
self.assertFalse(obj._no_kwargs)
self.assertEqual(obj.in_tree, jax.tree.flatten(((0, 0), {}))[1])
@jtu.with_mesh([('x', 2), ('y', 2)])
def testLowerCompileWithKwargs(self):
@pjit
def f(x, y, **kwargs):
return x @ y
shape = (8, 8)
x = jnp.arange(math.prod(shape)).reshape(shape)
exe = f.lower(x, x + 1, a=1, b=2).compile()
out = exe(x, x + 1, a=1, b=2)
self.assertArraysEqual(out, x @ (x + 1))
@jtu.with_mesh([('x', 2), ('y', 2)])
def testLowerCompileInTreeMismatch(self):
@partial(pjit,
in_shardings=P(('x', 'y'),),
out_shardings=P(('x', 'y'),))
def f(x, y):
return x @ y
shape = (8, 8)
x = jnp.arange(math.prod(shape)).reshape(shape)
exe = f.lower(x, x + 1).compile()
self.assertRaisesRegex(
TypeError,
'Function compiled with input pytree does not match the input pytree it'
' was called with',
lambda: exe([x], [x + 1]),
)