forked from jax-ml/jax
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxmap_test.py
2129 lines (1838 loc) · 84.7 KB
/
xmap_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 2020 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 as it
import os
import re
from itertools import product, permutations
from typing import (Tuple, List, Dict, Generator, Iterator, Union, Optional)
from unittest import SkipTest
import numpy as np
from absl.testing import absltest
from absl.testing import parameterized
from functools import partial
import jax
import jax.numpy as jnp
import jax.scipy as jscipy
from jax._src import test_util as jtu
from jax import vmap
from jax import lax
from jax._src import core
from jax._src.core import NamedShape
from jax.experimental import maps
from jax.experimental import global_device_array
from jax._src import array
from jax._src.sharding import NamedSharding
from jax.experimental.pjit import pjit, with_sharding_constraint
from jax.sharding import PartitionSpec as P
from jax.experimental.maps import xmap, serial_loop, SerialLoop
from jax.errors import JAXTypeError
from jax._src import config as jax_config
from jax._src.nn import initializers as nn_initializers
from jax._src.lib import xla_bridge
from jax._src.lib import xla_client
from jax._src.util import unzip2, prod, safe_zip
from jax._src.lax import parallel as lax_parallel
from jax._src.lax.parallel import pgather
from jax.interpreters import batching, pxla
from jax.ad_checkpoint import checkpoint
from jax.config import config
config.parse_flags_with_absl()
# TODO(mattjj): de-duplicate setUpModule and tearDownModule with pmap_test.py
# Run all tests with 8 CPU devices.
def setUpModule():
global prev_xla_flags
prev_xla_flags = os.getenv("XLA_FLAGS")
flags_str = prev_xla_flags or ""
# Don't override user-specified device count, or other XLA flags.
if "xla_force_host_platform_device_count" not in flags_str:
os.environ["XLA_FLAGS"] = (flags_str +
" --xla_force_host_platform_device_count=8")
# Clear any cached backends so new CPU backend will pick up the env var.
xla_bridge.get_backend.cache_clear()
# Reset to previous configuration in case other test modules will be run.
def tearDownModule():
if prev_xla_flags is None:
del os.environ["XLA_FLAGS"]
else:
os.environ["XLA_FLAGS"] = prev_xla_flags
xla_bridge.get_backend.cache_clear()
def create_array(global_shape, global_mesh, mesh_axes, global_data=None):
if global_data is None:
global_data = np.arange(
prod(global_shape), dtype=np.float32).reshape(global_shape)
sharding = NamedSharding(global_mesh, mesh_axes)
return array.make_array_from_callback(
global_shape, sharding, lambda idx: global_data[idx]), global_data
# -------------------- Itertools helpers --------------------
def partitions(s, k):
for indices in product(range(k), repeat=len(s)):
outs = [[] for _ in range(k)]
for i, elt in zip(indices, s):
outs[i].append(elt)
yield outs
def powerset(s):
s = list(s)
return it.chain.from_iterable(it.combinations(s, r) for r in range(len(s)+1))
# -------------------- vmap test helpers --------------------
ensure_bdim_p = core.Primitive('ensure_bdim')
ensure_bdim_p.def_abstract_eval(lambda x, **kwargs: core.raise_to_shaped(x))
def _ensure_bdim_batcher(axis_size, frame_name, main_type, vals_in, dims_in, axis_name, bdim):
v, = vals_in
d, = dims_in
assert d is not batching.not_mapped
return jnp.moveaxis(v, d, bdim), bdim
batching.axis_primitive_batchers[ensure_bdim_p] = _ensure_bdim_batcher
batching.primitive_batchers[ensure_bdim_p] = lambda v, d: (v[0], d[0])
core.axis_substitution_rules[ensure_bdim_p] = partial(
lax_parallel._subst_all_names_in_param, 'axis_name')
def ensure_bdim(x, axis_name, bdim):
return ensure_bdim_p.bind(x, axis_name=(axis_name,), bdim=bdim)
# When we use the SPMD lowering, we vmap the xmap body to make all named
# axes positional again. This lowering can introduce constants, which we
# have to handle properly in the lowering rule.
constant_introducing_p = core.Primitive('introduce_constant')
constant_introducing_p.def_abstract_eval(lambda x, **_: core.raise_to_shaped(x))
def _constant_introducing_batcher(_1, _2, _3, xs, ds, axis_name):
(x,), (d,) = xs, ds
# Introduce a constant
return (x + np.arange(x.size, dtype=x.dtype).reshape(x.shape)), d
batching.axis_primitive_batchers[constant_introducing_p] = _constant_introducing_batcher
core.axis_substitution_rules[constant_introducing_p] = partial(
lax_parallel._subst_all_names_in_param, 'axis_name')
# -------------------- Axis resources generation --------------------
AxisResources = Dict[str, Union[str, Tuple[str, ...]]]
def schedules(sizes: Dict[str, int]
) -> Generator[Tuple[AxisResources, jtu.MeshSpec], None, None]:
"""Test utility generating xmap parallel schedules from logical names & sizes.
Args:
sizes: dict mapping logical axis name to its corresponding size.
Returns:
A generator producing finitely many values, where each value is a pair in
which the first element is a value suitable for xmap's axis_resources
argument and the second element is a list of pairs with the first element
representing a generated physical mesh axis name and the second element
representing a corresponding generated mesh axis size. The generated mesh
names/sizes can be used to define a physical mesh in tests.
This function doesn't generate schedules which map distinct logical axis names
to the same parallel resource name. It only generates parallel resources; the
rest are implicitly left for vectorization. Parallel resource names are
generated by prepending an 'r', 'r1', or 'r2' to the corresponding logical
name.
Examples:
>>> for sched in schedules({'i': 2, 'j': 4}):
... print(sched)
({}, [])
({'i': 'ri'}, [('ri', 1)])
({'i': 'ri'}, [('ri', 2)])
({'i': ('r1i', 'r2i')}, [('r1i', 1), ('r2i', 1)])
({'i': ('r1i', 'r2i')}, [('r1i', 1), ('r2i', 2)])
({'i': ('r1i', 'r2i')}, [('r1i', 2), ('r2i', 1)])
({'j': 'rj'}, [('rj', 1)])
({'j': 'rj'}, [('rj', 2)])
({'j': 'rj'}, [('rj', 4)])
({'j': ('r1j', 'r2j')}, [('r1j', 1), ('r2j', 1)])
({'j': ('r1j', 'r2j')}, [('r1j', 1), ('r2j', 2)])
({'j': ('r1j', 'r2j')}, [('r1j', 1), ('r2j', 4)])
({'j': ('r1j', 'r2j')}, [('r1j', 2), ('r2j', 1)])
({'j': ('r1j', 'r2j')}, [('r1j', 2), ('r2j', 2)])
({'j': ('r1j', 'r2j')}, [('r1j', 4), ('r2j', 1)])
({'i': 'ri', 'j': 'rj'}, [('ri', 1), ('rj', 1)])
({'i': 'ri', 'j': 'rj'}, [('ri', 1), ('rj', 2)])
({'i': 'ri', 'j': 'rj'}, [('ri', 1), ('rj', 4)])
({'i': 'ri', 'j': 'rj'}, [('ri', 2), ('rj', 1)])
({'i': 'ri', 'j': 'rj'}, [('ri', 2), ('rj', 2)])
({'i': 'ri', 'j': 'rj'}, [('ri', 2), ('rj', 4)])
({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 1), ('r1j', 1), ('r2j', 1)])
({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 1), ('r1j', 1), ('r2j', 2)])
({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 1), ('r1j', 1), ('r2j', 4)])
({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 1), ('r1j', 2), ('r2j', 1)])
({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 1), ('r1j', 2), ('r2j', 2)])
({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 1), ('r1j', 4), ('r2j', 1)])
({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 2), ('r1j', 1), ('r2j', 1)])
({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 2), ('r1j', 1), ('r2j', 2)])
({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 2), ('r1j', 1), ('r2j', 4)])
({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 2), ('r1j', 2), ('r2j', 1)])
({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 2), ('r1j', 2), ('r2j', 2)])
({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 2), ('r1j', 4), ('r2j', 1)])
({'j': 'rj', 'i': ('r1i', 'r2i')}, [('rj', 1), ('r1i', 1), ('r2i', 1)])
({'j': 'rj', 'i': ('r1i', 'r2i')}, [('rj', 1), ('r1i', 1), ('r2i', 2)])
({'j': 'rj', 'i': ('r1i', 'r2i')}, [('rj', 1), ('r1i', 2), ('r2i', 1)])
({'j': 'rj', 'i': ('r1i', 'r2i')}, [('rj', 2), ('r1i', 1), ('r2i', 1)])
({'j': 'rj', 'i': ('r1i', 'r2i')}, [('rj', 2), ('r1i', 1), ('r2i', 2)])
({'j': 'rj', 'i': ('r1i', 'r2i')}, [('rj', 2), ('r1i', 2), ('r2i', 1)])
({'j': 'rj', 'i': ('r1i', 'r2i')}, [('rj', 4), ('r1i', 1), ('r2i', 1)])
({'j': 'rj', 'i': ('r1i', 'r2i')}, [('rj', 4), ('r1i', 1), ('r2i', 2)])
({'j': 'rj', 'i': ('r1i', 'r2i')}, [('rj', 4), ('r1i', 2), ('r2i', 1)])
"""
def divisors(n: int) -> List[int]:
return [m for m in range(1, n + 1) if not n % m]
def divisors2(n: int) -> Iterator[Tuple[int, int]]:
for k1 in divisors(n):
for k2 in divisors(n // k1):
yield (k1, k2)
# choose a subset of logical axis names to map to parallel resources
for names in powerset(sizes):
# partition that set of logical axis names into two subsets: one subset to
# map to one parallel resource axis and a second subset to map to two
# parallel resource axes.
for names1, names2 in partitions(names, 2):
# to avoid generating too many complex cases, we skip generating cases
# where more than one logical axis name is to be mapped to two parallel
# resource axes. comment out this line to generate more complex tests.
if len(names2) > 1: continue
# make up parallel resource axis names for each logical axis
axis_resources1 = ((name, 'r' + name) for name in names1)
axis_resources2 = ((name, ('r1' + name, 'r2' + name)) for name in names2)
axis_resources = dict(it.chain(axis_resources1, axis_resources2))
# make up sizes for each resource axis, where the size must divide the
# corresponding logical axis
for mesh_sizes1 in product(*(divisors(sizes[n]) for n in names1)):
for mesh_sizes2 in product(*(divisors2(sizes[n]) for n in names2)):
mesh_data1 = (('r' + name, size) for name, size in zip(names1, mesh_sizes1))
mesh_data2 = (pair for name, (size1, size2) in zip(names2, mesh_sizes2)
for pair in [('r1' + name, size1), ('r2' + name, size2)])
mesh_data = list(it.chain(mesh_data1, mesh_data2))
yield axis_resources, mesh_data
@jtu.pytest_mark_if_available('multiaccelerator')
class XMapTestCase(jtu.BufferDonationTestCase):
pass
# A mixin that enables SPMD lowering tests
class SPMDTestMixin:
def setUp(self):
super().setUp()
jtu.set_spmd_lowering_flag(True)
def tearDown(self):
jtu.restore_spmd_lowering_flag()
class ManualSPMDTestMixin:
def setUp(self):
if not hasattr(xla_client.OpSharding.Type, "MANUAL"):
raise SkipTest
super().setUp()
jtu.set_spmd_lowering_flag(True)
jtu.set_spmd_manual_lowering_flag(True)
def tearDown(self):
jtu.restore_spmd_manual_lowering_flag()
jtu.restore_spmd_lowering_flag()
@jtu.pytest_mark_if_available('multiaccelerator')
class XMapTest(XMapTestCase):
def testBasic(self):
local_devices = list(jax.local_devices())
if len(local_devices) < 4:
raise SkipTest("Test requires at least 4 local devices")
def f(a, b):
return a * 2, b * 4
devices = np.array(local_devices[:4]).reshape((2, 2))
with jax.sharding.Mesh(devices, ('x', 'y')):
fm = xmap(f,
in_axes=({0: 'a', 1: 'b'}, ['c', ...]),
out_axes=({0: 'a', 1: 'b'}, ['c', ...]),
axis_resources={'a': 'x', 'b': 'y', 'c': 'x'})
ashape = (16, 8, 5)
a = jnp.arange(np.prod(ashape)).reshape(ashape)
bshape = (2, 7)
b = jnp.arange(np.prod(bshape)).reshape(bshape)
c, d = fm(a, b)
self.assertAllClose(c, a * 2)
self.assertAllClose(d, b * 4)
@jtu.with_mesh([('x', 2), ('y', 2)])
def testCollectiveReduce(self):
fm = xmap(lambda a, b: (lax.psum(a * 2, 'a'), b * 4),
in_axes=(['a', 'b', ...], {0: 'c'}),
out_axes=(['b', ...], {0: 'c'}),
axis_resources={'a': 'x', 'b': 'y', 'c': 'x'})
ashape = (16, 8, 5)
a = jnp.arange(np.prod(ashape)).reshape(ashape)
bshape = (2, 7)
b = jnp.arange(np.prod(bshape)).reshape(bshape)
c, d = fm(a, b)
self.assertAllClose(c, (a * 2).sum(0))
self.assertAllClose(d, b * 4)
@jtu.with_mesh([('x', 2), ('y', 2)])
def testCollectivePermute2D(self):
perm = np.array([3, 1, 2, 0])
x = jnp.arange(4).reshape((2, 2))
result = xmap(lambda x: lax.pshuffle(x, ('i', 'j'), perm),
in_axes=['i', 'j', ...],
out_axes=['i', 'j', ...],
axis_resources={'i': 'x', 'j': 'y'})(x).reshape((-1,))
self.assertAllClose(result, perm, check_dtypes=False)
def testCollectivePermute1D(self):
perm = np.array([3, 1, 2, 0])
x = jnp.arange(4)
result = xmap(lambda x: lax.pshuffle(x, 'i', perm),
in_axes=['i', ...],
out_axes=['i', ...])(x)
self.assertAllClose(result, perm, check_dtypes=False)
def testCollectiveAllGather(self):
x = jnp.arange(4, dtype='int32')
result = xmap(lambda x: lax.all_gather(x, 'i') + lax.axis_index('i'),
in_axes=['i', ...], out_axes=['i', ...])(x)
self.assertAllClose(result, x[jnp.newaxis] + x[jnp.newaxis].T)
@jtu.with_mesh([('x', 2), ('y', 2)])
def testOneLogicalTwoMeshAxesBasic(self):
def f(v):
return lax.psum(v * 2, 'a'), v * 4
fm = xmap(f, in_axes=['a', ...], out_axes=({}, {1: 'a'}),
axis_resources={'a': ('x', 'y')})
vshape = (4, 5)
v = jnp.arange(np.prod(vshape)).reshape(vshape)
ans, ans2 = fm(v)
self.assertAllClose(ans, (v * 2).sum(0))
self.assertAllClose(ans2, v.T * 4)
@jtu.with_mesh([('x', 2), ('y', 2)])
def testOneLogicalTwoMeshAxesSharding(self):
def f(v):
return v * 4
fxy = xmap(f, in_axes=['a', ...], out_axes={1: 'a'},
axis_resources={'a': ('x', 'y')})
fyx = xmap(f, in_axes=['a', ...], out_axes={1: 'a'},
axis_resources={'a': ('y', 'x')})
vshape = (4, 5)
v = jnp.arange(np.prod(vshape)).reshape(vshape)
zxy = fxy(v)
if config.jax_array:
zxy_sharding_spec = global_device_array._get_sharding_spec(
zxy.shape, zxy.sharding.mesh, zxy.sharding.spec)
else:
zxy_sharding_spec = zxy.sharding_spec
self.assertEqual(
zxy_sharding_spec,
pxla.ShardingSpec((pxla.NoSharding(), pxla.Chunked((2, 2))),
(pxla.ShardedAxis(0), pxla.ShardedAxis(1))))
zyx = fyx(v)
if config.jax_array:
zyx_sharding_spec = global_device_array._get_sharding_spec(
zyx.shape, zyx.sharding.mesh, zyx.sharding.spec)
else:
zyx_sharding_spec = zyx.sharding_spec
self.assertEqual(
zyx_sharding_spec,
pxla.ShardingSpec((pxla.NoSharding(), pxla.Chunked((2, 2))),
(pxla.ShardedAxis(1), pxla.ShardedAxis(0))))
@jtu.with_mesh([('x', 2), ('y', 2)])
def testSkipFirstMeshDim(self):
def run(axis_resources):
return xmap(lambda x: x * 2, in_axes=['i', ...], out_axes=['i', ...],
axis_resources=axis_resources)(jnp.ones((4,)))
self.assertAllClose(run({'i': 'x'}), run({'i': 'y'}))
def testCaching(self):
def f(x):
assert python_should_be_executing
return x * 2
devices = np.array(jax.local_devices()[:2])
if devices.size < 2:
raise SkipTest("Test requires 2 devices")
x = np.arange(8).reshape((2, 2, 2))
with jax.sharding.Mesh(devices, ('x',)):
python_should_be_executing = True
xmap(f, in_axes=['a', ...], out_axes=['a', ...],
axis_resources={'a': 'x'})(x)
python_should_be_executing = False
xmap(f, in_axes=['a', ...], out_axes=['a', ...],
axis_resources={'a': 'x'})(x)
with jax.sharding.Mesh(devices, ('x',)):
python_should_be_executing = False
xmap(f, in_axes=['a', ...], out_axes=['a', ...],
axis_resources={'a': 'x'})(x)
def testNoTracerLeak(self):
if config.jax_array:
self.skipTest('Does not work with Array because of ShardingContext '
'being used in xmap because of jit. Removing that '
'restriction makes the test pass but that should be done '
'in a separate CL.')
@jax.jit
def xmap_linearize(xs):
eye = jnp.eye(xs.shape[0], dtype=jnp.float32)
primal, grad_f = jax.linearize(jnp.sin, xs)
return maps.xmap(
grad_f,
in_axes=['i', ...],
out_axes=['i', ...],
axis_resources={'i': maps.SerialLoop(1)})(eye)
xs = jnp.arange(1, 4, step=1).astype(jnp.float32)
xmap_linearize(xs) # Doesn't raise a tracer leak error
@parameterized.named_parameters(
{"testcase_name": name, "mesh": mesh, "axis_resources": axis_resources}
for name, mesh, axis_resources in (
('OneToOne', (('x', 2), ('y', 2)), (('a', 'y'), ('b', 'x'))),
('Multiple', (('x', 2), ('y', 2), ('z', 2)), (('a', 'y'), ('b', ('x', 'z')))),
))
@jtu.with_mesh_from_kwargs
@jax.numpy_dtype_promotion('standard')
def testNestedMesh(self, mesh, axis_resources):
@partial(xmap, in_axes={1: 'a'}, out_axes=({0: 'a'}, {}),
axis_resources=dict([axis_resources[0]]))
def f(x):
y = x * 2
@partial(xmap, in_axes={0: 'b'}, out_axes=({1: 'b'}, {}),
axis_resources=dict([axis_resources[1]]))
def h(y):
# Multiply by a constant array to better exercise the partial_eval rule
return jnp.sin(y) * np.arange(y.size, dtype=float), lax.psum(y, ('a', 'b'))
return h(y)
xshape = (4, 2, 5)
x = jnp.arange(np.prod(xshape), dtype=float).reshape(xshape)
y = f(x)
self.assertAllClose(
y, ((jnp.sin(x * 2) *
np.arange(xshape[-1], dtype=float)[None, None]).transpose(
(1, 2, 0)), (x * 2).sum((0, 1))))
if config.jax_array:
sharding_spec = global_device_array._get_sharding_spec(
y[0].shape, y[0].sharding.mesh, y[0].sharding.spec)
else:
sharding_spec = y[0].sharding_spec
self.assertEqual(sharding_spec.sharding,
(pxla.Chunked([2]), pxla.NoSharding(), pxla.NoSharding()))
self.assertEqual(sharding_spec.mesh_mapping,
(pxla.Replicated(2), pxla.ShardedAxis(0)) +
(pxla.Replicated(2),) * (len(mesh) - 2))
if config.experimental_xmap_spmd_lowering:
hlo = f.lower(x).compiler_ir(dialect="hlo").as_hlo_text()
# Make sure that there are non-partial sharding specs in the HLO
self.assertRegex(hlo, r"sharding={devices=\[[0-9,]+\][0-9,]+}")
@jtu.with_and_without_mesh
def testMultipleCalls(self, mesh, axis_resources):
def f(x, y):
assert x.shape == y.shape == (3, 5)
return jnp.tensordot(x, y, axes=([1], [1]))
f_mapped = xmap(f,
in_axes=(['i', ...], ['j', ...]),
out_axes=['i', 'j', ...],
axis_resources=dict(axis_resources))
x = jnp.arange(30).reshape(2, 3, 5)
expected = jnp.einsum('imk,jnk->ijmn', x, x)
for i in range(10):
self.assertAllClose(f_mapped(x, x), expected)
@jtu.with_and_without_mesh
@jtu.skip_on_devices("cpu") # In/out aliasing not supported on CPU.
def testBufferDonation(self, mesh, axis_resources):
shard = lambda x: x
if axis_resources:
shard = xmap(lambda x: x, in_axes=['i', ...], out_axes=['i', ...],
axis_resources=dict(axis_resources))
f = xmap(lambda x, y: x + y * 4,
in_axes=['i', ...], out_axes=['i', ...],
axis_resources=dict(axis_resources),
donate_argnums=0)
# The multiplications below disable some optimizations that prevent reuse
x = shard(jnp.zeros((2, 5)) * 4)
y = shard(jnp.ones((2, 5)) * 2)
f(x, y)
self.assertNotDeleted(y)
self.assertDeleted(x)
@jtu.skip_on_devices("cpu") # In/out aliasing not supported on CPU.
@jtu.with_mesh([('x', 2)])
@jtu.ignore_warning(category=UserWarning, # SPMD test generates warning.
message="Some donated buffers were not usable*")
def testBufferDonationNamedShape(self):
axis_resources = {'i': 'x'}
# named in_aval, unnamed out_aval
f = xmap(lambda _: jnp.ones((2, 5)),
in_axes=['i', ...], out_axes=[...],
axis_resources=axis_resources,
donate_argnums=0)
shard = xmap(lambda x: x, in_axes=['i', ...], out_axes=['i', ...],
axis_resources=dict(axis_resources))
x = shard(jnp.zeros((4, 5)))
f(x)
self.assertDeleted(x)
@jtu.with_mesh([('x', 2), ('y', 2)])
def testConstantsInLowering(self):
h = xmap(partial(constant_introducing_p.bind, axis_name='i'),
in_axes=['i'], out_axes=['i'], axis_resources={'i': 'x'})
f = xmap(h, in_axes=['j', ...], out_axes=['j', ...], axis_resources={'j': 'y'})
yp = 1 + jnp.arange(10, dtype=np.float32)
self.assertAllClose(
f(jnp.ones((2, 20), dtype=np.float32)),
jnp.broadcast_to(jnp.concatenate([yp, yp]), (2, 20)))
def testControlFlow(self):
x = jnp.arange(5)
xmap(lambda x: lax.fori_loop(0, 10, lambda _, x: lax.psum(x, 'i'), x),
in_axes=['i', ...], out_axes=['i', ...])(x)
@jtu.with_and_without_mesh
def testAxisSizes(self, mesh, axis_resources):
result = xmap(lambda: lax.axis_index('i'),
in_axes=(), out_axes=['i', ...],
axis_sizes={'i': 6},
axis_resources=dict(axis_resources))()
self.assertAllClose(result, jnp.arange(6, dtype=result.dtype))
def testCollectiveOverNoName(self):
result = xmap(lambda: lax.psum(jnp.array(2) ** 2, 'i'),
in_axes={}, out_axes={}, axis_sizes={'i': 4})()
self.assertEqual(result, 16)
def VmapOfXmapCases(s):
xmap_in_axes = ([{}] +
[{i: 'x'} for i in range(3)] +
[{i: 'x', j: 'y'} for i in range(4) for j in range(4) if i != j])
for xmap_dim_x, xmap_dim_y in s(product(xmap_in_axes, repeat=2)):
xmap_axes = sorted(set(xmap_dim_x.values()) | set(xmap_dim_y.values()))
num_axes = len(xmap_axes)
if xmap_axes is None:
continue
xmap_out_axes = [dict(zip(dims, xmap_axes))
for dims in permutations(range(2 + num_axes), num_axes)]
for xmap_dim_z in s(xmap_out_axes):
for vmap_dim_x in s([*range(2 + len(xmap_dim_x)), None]):
for vmap_dim_y in s([*range(2 + len(xmap_dim_y)), None]):
if vmap_dim_x is None and vmap_dim_y is None:
continue
for vmap_dim_result in s(range(3)):
for vmap_dim_z in s(range(2 + len(xmap_axes))):
for vmap_as_xmap in s([False, True]):
yield {"testcase_name":
f"_xin={(sorted(xmap_dim_x.items()), sorted(xmap_dim_y.items()))}_"
f"xout={sorted(xmap_dim_z.items())}_vin={(vmap_dim_x, vmap_dim_y)}_"
f"vout={vmap_dim_z}_vresult={vmap_dim_result}_{vmap_as_xmap=}",
"xmap_in_axes": (xmap_dim_x, xmap_dim_y),
"xmap_out_axes": xmap_dim_z,
"vmap_in_axes": (vmap_dim_x, vmap_dim_y),
"vmap_out_axes": vmap_dim_z,
"vmap_result_axis": vmap_dim_result,
"vmap_as_xmap": vmap_as_xmap}
@parameterized.named_parameters(jtu.named_cases_from_sampler(VmapOfXmapCases))
def testNestedMap(self,
xmap_in_axes, xmap_out_axes,
vmap_in_axes, vmap_out_axes, vmap_result_axis,
vmap_as_xmap):
"""Test various vmap(xmap) and xmap(xmap) combinations.
The outer map always introduces a single dimension, the inner map introduces one or two.
"""
(xin_x, xin_y) = xmap_in_axes
(vin_x, vin_y) = vmap_in_axes
vmap_size = 7
xmap_sizes = {'x': 11, 'y': 13}
xshape = [2, 3]
yshape = [3, 5]
zshape = [2, 5]
xind = ['n', 'k']
yind = ['k', 'm']
zind = ['n', 'm']
f = lambda x, y: ensure_bdim(jnp.einsum('nk,km->nm', x, y), 'v', vmap_result_axis)
for pos, name in sorted(xin_x.items()):
xshape.insert(pos, xmap_sizes[name])
xind.insert(pos, name)
for pos, name in sorted(xin_y.items()):
yshape.insert(pos, xmap_sizes[name])
yind.insert(pos, name)
for pos, name in sorted(xmap_out_axes.items()):
zshape.insert(pos, xmap_sizes[name])
zind.insert(pos, name)
if vin_x is not None:
xshape.insert(vin_x, vmap_size)
xind.insert(vin_x, 'v')
if vin_y is not None:
yshape.insert(vin_y, vmap_size)
yind.insert(vin_y, 'v')
zshape.insert(vmap_out_axes, vmap_size)
zind.insert(vmap_out_axes, 'v')
if vmap_as_xmap:
do_vmap = partial(xmap,
in_axes=({vin_x: 'v'} if vin_x is not None else {},
{vin_y: 'v'} if vin_y is not None else {}),
out_axes={vmap_out_axes: 'v'})
else:
do_vmap = partial(vmap, in_axes=vmap_in_axes, out_axes=vmap_out_axes, axis_name='v')
fm = do_vmap(xmap(f, in_axes=xmap_in_axes, out_axes=xmap_out_axes))
fref = partial(jnp.einsum, f"{''.join(xind)},{''.join(yind)}->{''.join(zind)}")
rng = self.rng()
x = rng.randn(*xshape)
y = rng.randn(*yshape)
self.assertAllClose(fm(x, y), fref(x, y), atol={np.float64: 1e-14})
def testBatchingPostProcess(self):
x = jnp.arange(10).reshape(5, 2)
f = jax.vmap(lambda y: xmap(lambda x: x + y, in_axes=['i', ...], out_axes=['i', ...])(x))
ref = jax.vmap(lambda y: jax.vmap(lambda x: x + y)(x))
self.assertAllClose(f(x * 2), ref(x * 2))
def testAutodiffBroadcast(self):
f = xmap(lambda x, y: jnp.cos(lax.dot(x, jnp.sin(y),
precision=lax.Precision.HIGHEST)),
in_axes=(['i', ...], {}), out_axes=['i', ...])
x = jnp.arange(12, dtype=jnp.float32).reshape((3, 4)) / 100
y = jnp.arange(20, dtype=jnp.float32).reshape((4, 5)) / 100
jtu.check_grads(f, (x, y), order=2, modes=['fwd'])
jtu.check_grads(f, (x, y), order=1, modes=['rev'])
with self.assertRaises(AssertionError):
# Second order reverse-mode differentiations seems to be broken,
# likely due to the transpose of psum being defined incorrectly.
jtu.check_grads(f, (x, y), order=2, modes=['rev'])
def testAutodiffNoBroadcast(self):
f = xmap(lambda x, y: jnp.cos(lax.dot(x, jnp.sin(y),
precision=lax.Precision.HIGHEST)),
in_axes=(['i', ...], [None, 'i']), out_axes=['i'])
x = jnp.arange(12, dtype=jnp.float32).reshape((3, 4)) / 100
y = jnp.arange(12, dtype=jnp.float32).reshape((4, 3)) / 100
jtu.check_grads(f, (x, y), order=2)
@jtu.with_and_without_mesh
def testNamedShape(self, mesh, axis_resources):
x = np.arange(4,)
y = 2
f = xmap(lambda x, y: (x + y, y * lax.axis_index('i')),
in_axes=(['i', ...], {}),
out_axes=(['i', ...], ['i', ...]),
axis_resources=dict(axis_resources))
z, w = f(x, y)
self.assertEqual(z.aval.named_shape, {})
self.assertEqual(w.aval.named_shape, {})
@jtu.with_and_without_mesh
def testBroadcast(self, mesh, axis_resources):
x = jnp.asarray(2.0)
f = xmap(lambda x: x, in_axes={}, out_axes=['i'],
axis_sizes={'i': 4}, axis_resources=dict(axis_resources))
self.assertAllClose(f(x), jnp.asarray([2.0, 2.0, 2.0, 2.0]))
def testNestedBroadcast(self):
x = jnp.asarray(2.0)
f = xmap(lambda x: x, in_axes={}, out_axes=['i'], axis_sizes={'i': 4})
g = xmap(f, in_axes={}, out_axes=['j', ...], axis_sizes={'j': 7})
self.assertAllClose(g(x), jnp.tile(x.reshape((1, 1)), (7, 4)))
@serial_loop('l', 4)
def testLoopBasic(self):
x = jnp.arange(16)
y = xmap(lambda x: x + 4, in_axes=['i'], out_axes=['i'],
axis_resources={'i': 'l'})(x)
self.assertAllClose(y, x + 4)
@jtu.with_mesh([('x', 2)])
@serial_loop('l', 4)
def testLoopWithMesh(self):
x = jnp.arange(16)
y = xmap(lambda x: x + 4, in_axes=['i'], out_axes=['i'],
axis_resources={'i': ('x', 'l')})(x)
self.assertAllClose(y, x + 4)
def testLoopAnonBasic(self):
x = jnp.arange(16)
y = xmap(lambda x: x + 4, in_axes=['i'], out_axes=['i'],
axis_resources={'i': SerialLoop(4)})(x)
self.assertAllClose(y, x + 4)
@jtu.with_mesh([('x', 2)])
def testLoopAnonWithMesh(self):
x = jnp.arange(16)
y = xmap(lambda x: x + 4, in_axes=['i'], out_axes=['i'],
axis_resources={'i': ('x', SerialLoop(4))})(x)
self.assertAllClose(y, x + 4)
def testLowerWithAbstractArgs(self):
x = jax.ShapeDtypeStruct((2, 2), jnp.float32)
# Make sure this doesn't crash
xmap(lambda x: x + 4, in_axes=['i', ...], out_axes=['i', ...]).lower(x)
def testLowerCompile(self):
f = xmap(lambda x: x + 4, in_axes=['i', ...], out_axes=['i', ...])
x = jnp.arange(4, dtype=jnp.float32).reshape((2, 2))
f_exe = f.lower(x).compile()
self.assertAllClose(f_exe(x), f(x))
def testLowerCompileInTreeMismatch(self):
f = xmap(lambda x: x + 4, in_axes=['i', ...], out_axes=['i', ...])
x = jnp.arange(4, dtype=jnp.float32).reshape((2, 2))
f_exe = f.lower(x).compile()
self.assertRaisesRegex(
TypeError, "function compiled for .*, called with .*",
lambda: f_exe([x]))
def testLowerCompileArgTypeMismatch(self):
f = xmap(lambda x: x + 4, in_axes=['i', ...], out_axes=['i', ...])
x = jnp.arange(4, dtype=jnp.float32).reshape((2, 2))
x_f32 = x.astype(jnp.float32)
x_i32 = x.astype(jnp.int32)
f_exe = f.lower(x_f32).compile()
self.assertRaisesRegex(
TypeError,
"Computation was compiled for different input types and called with "
"different types. One of the mismatches is:\n"
"Compiled with:\n.*float32.*\n"
"called with:\n.*int32.*",
lambda: f_exe(x_i32))
def testLowerAsText(self):
f = xmap(lambda x: x + 4, in_axes=['i', ...], out_axes=['i', ...])
x = jnp.arange(4, dtype=jnp.float32).reshape((2, 2))
f = f.lower(x)
self.assertIsInstance(f.as_text(), str)
self.assertIsInstance(f.as_text(dialect='hlo'), str)
self.assertIsInstance(f.as_text(dialect='mhlo'), str)
self.assertIsInstance(f.as_text(dialect='stablehlo'), str)
def testLowerCompilerIR(self):
f = xmap(lambda x: x + 4, in_axes=['i', ...], out_axes=['i', ...])
x = jnp.arange(4, dtype=jnp.float32).reshape((2, 2))
f = f.lower(x)
self.assertIsNotNone(f.compiler_ir())
self.assertIsNotNone(f.compiler_ir(dialect='hlo'))
self.assertIsNotNone(f.compiler_ir(dialect='mhlo'))
self.assertIsNotNone(f.compiler_ir(dialect='stablehlo'))
@jtu.ignore_warning(category=DeprecationWarning)
def testLowerCompileCompilerIR(self):
# TODO(frostig): remove (deprecated)
f = xmap(lambda x: x + 4, in_axes=['i', ...], out_axes=['i', ...])
x = jnp.arange(4, dtype=jnp.float32).reshape((2, 2))
f = f.lower(x).compile()
self.assertIsNotNone(f.compiler_ir())
def testLowerCompileAsText(self):
f = xmap(lambda x: x + 4, in_axes=['i', ...], out_axes=['i', ...])
x = jnp.arange(4, dtype=jnp.float32).reshape((2, 2))
f = f.lower(x).compile()
self.assertIsInstance(f.as_text(), (str, type(None)))
@jtu.skip_on_xla_cpu_mlir
def testLowerCostAnalysis(self):
# TODO(b/261771737): add support for uncompiled cost analysis in C API.
if "PJRT C API" in xla_bridge.get_backend().platform_version:
raise SkipTest("C API does not support uncompiled cost analysis")
f = xmap(lambda x: x + 4, in_axes=['i', ...], out_axes=['i', ...])
x = jnp.arange(4, dtype=jnp.float32).reshape((2, 2))
f = f.lower(x)
f.cost_analysis() # doesn't raise
@jtu.skip_on_xla_cpu_mlir
def testLowerCompileCostAnalysis(self):
f = xmap(lambda x: x + 4, in_axes=['i', ...], out_axes=['i', ...])
x = jnp.arange(4, dtype=jnp.float32).reshape((2, 2))
f = f.lower(x).compile()
f.cost_analysis() # doesn't raise
@jtu.skip_on_xla_cpu_mlir
def testLowerCompileMemoryAnalysis(self):
f = xmap(lambda x: x + 4, in_axes=['i', ...], out_axes=['i', ...])
x = jnp.arange(4, dtype=jnp.float32).reshape((2, 2))
f = f.lower(x).compile()
f.memory_analysis() # doesn't raise
def testLowerCompileExecutable(self):
f = xmap(lambda x: x + 4, in_axes=['i', ...], out_axes=['i', ...])
x = jnp.arange(4, dtype=jnp.float32).reshape((2, 2))
f = f.lower(x).compile()
self.assertIsNotNone(f.runtime_executable())
def testNewCheckpoint(self):
f = checkpoint(xmap(lambda x: x, in_axes=['i', ...], out_axes=['i', ...]))
self.assertAllClose(jax.grad(lambda x: f(x).sum())(jnp.arange(3.)), jnp.ones(3))
def testNewCheckpointNonlinearWithPolicy(self):
raise SkipTest("fails!") # TODO(mattjj,apaszke): residual outvars problem
f = checkpoint(xmap(lambda x: jnp.sin(jnp.sin(x)), in_axes=['i', ...],
out_axes=['i', ...]),
policy=lambda prim, *_, **__: str(prim) == 'sin')
jax.grad(lambda x: f(x).sum())(jnp.arange(3.)) # TODO crashes!
@jtu.pytest_mark_if_available('multiaccelerator')
class XMapTestSPMD(SPMDTestMixin, XMapTest):
"""Re-executes all basic tests with the SPMD partitioner enabled"""
skipped_tests = {
"CollectivePermute2D" # vmap of multidimensional permute not implemented yet
}
def setUp(self):
for skipped_name in self.skipped_tests:
if skipped_name in self._testMethodName:
raise SkipTest
super().setUp()
@jtu.with_mesh([('x', 2), ('y', 2), ('z', 2)])
@jax.numpy_dtype_promotion('standard')
def testNestedMeshSPMD(self):
h = xmap(lambda y: (jnp.sin(y) * np.arange(y.size, dtype=float),
lax.psum(y, ('a', 'b', 'c'))),
in_axes={0: 'c'}, out_axes=({1: 'c'}, {}),
axis_resources={'c': 'z'})
f = xmap(lambda x: h(x * 2),
in_axes=[None, 'a', 'b', ...], out_axes=(['a', 'b', ...], {}),
axis_resources={'a': 'x', 'b': 'y'})
xshape = (8, 2, 4, 5)
x = jnp.arange(np.prod(xshape), dtype=float).reshape(xshape)
hlo = f.lower(x).compiler_ir(dialect="hlo").as_hlo_text()
match = re.search(r"sharding={devices=\[([0-9,]+)\][0-9,]+}", hlo)
self.assertIsNot(match, None)
tile_factors = [int(s) for s in match.group(1).split(',')]
self.assertEqual(set(tile_factors), {1, 2})
@jtu.with_mesh([('x', 2)])
def testFixedSharding(self):
# TODO(apaszke): Add support for extracting XLA computations generated by
# xmap and make this less of a smoke test.
try:
config.update("experimental_xmap_ensure_fixed_sharding", True)
f = xmap(lambda x: jnp.sin(2 * jnp.sum(jnp.cos(x) + 4, 'i')),
in_axes=['i'], out_axes={}, axis_resources={'i': 'x'})
x = jnp.arange(20, dtype=jnp.float32)
f(x)
finally:
config.update("experimental_xmap_ensure_fixed_sharding", False)
@jtu.with_mesh([('x', 2)])
def testConstantsInLowering(self):
h = xmap(partial(constant_introducing_p.bind, axis_name='i'),
in_axes=['i'], out_axes=['i'], axis_resources={'i': 'x'})
f = pjit(h, in_shardings=None, out_shardings=None)
yp = 1 + jnp.arange(10, dtype=np.float32)
self.assertAllClose(
f(jnp.ones(20, dtype=np.float32)),
jnp.concatenate([yp, yp]))
@jtu.pytest_mark_if_available('multiaccelerator')
class XMapTestManualSPMD(ManualSPMDTestMixin, XMapTestCase):
@jtu.with_mesh([('x', 2)])
def testBasic(self):
f = lambda x: jnp.sin(jnp.cos(x) + x) * x
fx = xmap(f, in_axes=['i'], out_axes=['i'], axis_resources={'i': 'x'})
x = jnp.arange(20, dtype=jnp.float32)
self.assertAllClose(fx(x), f(x))
@jtu.with_mesh([('x', 2)])
def testReplicated(self):
# TODO(apaszke): This seems to be failing if I try to have a replicated and a mapped argument?
f = lambda x: jnp.sin(jnp.cos(x) + x) * x
fx = xmap(f, in_axes=[...], out_axes=[...], axis_sizes={'i': 4}, axis_resources={'i': 'x'})
x = jnp.arange(20, dtype=jnp.float32)
self.assertAllClose(fx(x), f(x))
@jtu.with_mesh([('x', 2), ('y', 1)])
def testInPJit(self):
f = xmap(lambda x: jnp.sin(x) + x, in_axes=['i'], out_axes=['i'], axis_resources={'i': 'x'})
h = pjit(lambda x: f(x * x) + x, in_shardings=P('y'), out_shardings=None)
x = jnp.arange(20, dtype=jnp.float32)
self.assertAllClose(h(x), jnp.sin(x * x) + x * x + x)
@jtu.with_mesh([('x', 2), ('y', 1)])
def testInPJitReplicated(self):
f = xmap(lambda x: jnp.sin(x) + x, in_axes={}, out_axes={}, axis_sizes={'i': 4}, axis_resources={'i': 'x'})
h = pjit(lambda x: f(x * x) + x, in_shardings=P('y'), out_shardings=None)
x = jnp.arange(20, dtype=jnp.float32)
self.assertAllClose(h(x), jnp.sin(x * x) + x * x + x)
@jtu.with_mesh([('x', 2), ('y', 1)])
def testNestedConstraint(self):
# TODO(b/219691408): Using P('y') instead of P() causes an XLA crash!
fimpl = lambda x: with_sharding_constraint(jnp.sin(x), P()) + x
f = xmap(fimpl, in_axes=['i', ...], out_axes=['i', ...], axis_resources={'i': 'x'})
h = pjit(lambda x: f(x * x) + x, in_shardings=P('y'), out_shardings=None)
x = jnp.arange(20, dtype=jnp.float32).reshape(4, 5)
self.assertAllClose(h(x), jnp.sin(x * x) + x * x + x)
@parameterized.named_parameters(
{'testcase_name': name, 'mesh': mesh}
for name, mesh in (
('1d', (('x', 2),)),
('2d', (('x', 2), ('y', 2))),
))
@jtu.with_mesh_from_kwargs
def testCollective(self, mesh):
all_axes = tuple(axis[0] for axis in mesh)
f = xmap(lambda x: lax.psum(x, 'i'), in_axes=['i', 'j'], out_axes=['j'],
axis_resources=dict(zip('ij', all_axes)))
h = pjit(lambda x: f(x * x), in_shardings=P(*all_axes), out_shardings=None)
x = jnp.arange(16, dtype=jnp.float32).reshape(4, 4)
self.assertAllClose(h(x), (x * x).sum(0))
@parameterized.named_parameters(
{'testcase_name': name, 'mesh': mesh}
for name, mesh in (
('1d', (('x', 2),)),
))
@jtu.with_mesh_from_kwargs
def testAllGather(self, mesh):
# try hard_xmap variant, mapping across leading axes
x = jnp.arange(8).reshape(2, 4)
if not config.jax_array:
self.skipTest('Do not test on the cpu+no array test')
f = xmap(lambda x: lax.all_gather(x, 'i', axis=0, tiled=True),
in_axes=['i', None], out_axes=[None],
axis_resources={'i': 'x'})
h = pjit(f, in_shardings=P('x', None), out_shardings=P(None))(x)
assert (h.device_buffers[0] == x.reshape(8)).all()
@parameterized.named_parameters(
{'testcase_name': name, 'mesh': mesh}
for name, mesh in (
('1d', (('x', 2),)),
))
@jtu.with_mesh_from_kwargs
def testReduceScatter(self, mesh):
# try hard_xmap variant, mapping across leading axes
x = jnp.arange(8).reshape(2, 4)
if not config.jax_array:
self.skipTest('Do not test on the cpu+no array test')
f = xmap(lambda x: lax.psum_scatter(x, 'i', scatter_dimension=0, tiled=True),
in_axes=[None, None], out_axes=['i', None, None], axis_sizes={'i': 2},
axis_resources={'i': 'x'})
h = pjit(
lambda x: f(x).reshape((2, 4)),
in_shardings=P(None, None),
out_shardings=P('x', None),
)(x)
assert (h.device_buffers[0].reshape(4) == x[0, :]*2).all()
@jtu.with_mesh([('x', 2)])
def testBareXmapCollective(self):
x = jnp.arange(20, dtype=jnp.float32).reshape(4, 5)
y = xmap(lambda x: lax.psum(x, 'i'),
in_axes=['i', ...], out_axes=[...], axis_resources={'i': 'x'})(x)
self.assertAllClose(x.sum(0), y)
@jtu.with_mesh([('x', 2)])
def testPPermute(self):
n = 2
x = jnp.arange(n * 5, dtype=jnp.float32).reshape(n, 5)
f = xmap(lambda x: lax.ppermute(x, 'i', perm=[(j, (j + 1) % n) for j in range(n)]),
in_axes=['i', ...], out_axes=['i', ...], axis_resources={'i': 'x'})
g = pjit(f, in_shardings=P('x'), out_shardings=P('x'))
self.assertAllClose(g(x), x[::-1])
@jtu.with_mesh([('x', 2)])
def testConstantsInLowering(self):
h = xmap(partial(constant_introducing_p.bind, axis_name='i'),
in_axes=['i'], out_axes=['i'], axis_resources={'i': 'x'})
f = pjit(h, in_shardings=None, out_shardings=None)
yp = 1 + jnp.arange(10, dtype=np.float32)
self.assertAllClose(
f(jnp.ones(20, dtype=np.float32)),
jnp.concatenate([yp, yp]))
@jtu.pytest_mark_if_available('multiaccelerator')
class NamedNumPyTest(XMapTestCase):
@jtu.sample_product(
reduction=(jnp.sum, jnp.max, jnp.min, jnp.mean, jnp.var, jnp.std,
jscipy.special.logsumexp),
axes=(0, 'i', (1,), ('i',), (0, 1), (0, 'i'), ('i', 0)),
mapped_axis=range(3),
)
def testReductions(self, reduction, axes, mapped_axis):
axes_t = axes if isinstance(axes, tuple) else (axes,)