2019-01-28 11:13:34 -08:00
|
|
|
# Copyright 2018 Google LLC
|
|
|
|
#
|
|
|
|
# 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.
|
|
|
|
|
|
|
|
|
2019-02-23 20:34:14 -08:00
|
|
|
from functools import partial
|
2019-12-17 14:44:03 -08:00
|
|
|
import os
|
2019-12-17 16:22:55 -08:00
|
|
|
from random import shuffle
|
2019-03-19 16:54:55 -07:00
|
|
|
from unittest import SkipTest
|
2019-02-23 20:34:14 -08:00
|
|
|
|
2019-01-28 11:13:34 -08:00
|
|
|
import numpy as onp
|
|
|
|
from absl.testing import absltest
|
|
|
|
from absl.testing import parameterized
|
|
|
|
|
2019-11-06 08:36:53 -08:00
|
|
|
import jax
|
2019-01-28 11:13:34 -08:00
|
|
|
import jax.numpy as np
|
|
|
|
from jax import test_util as jtu
|
2020-01-29 03:04:59 +00:00
|
|
|
from jax import tree_util
|
2019-05-02 22:13:49 -07:00
|
|
|
from jax import core
|
2019-02-23 20:34:14 -08:00
|
|
|
from jax import lax
|
2019-09-11 06:01:32 -07:00
|
|
|
from jax import random
|
2020-04-15 12:43:55 -07:00
|
|
|
from jax.abstract_arrays import ShapedArray
|
2019-06-23 16:41:59 -07:00
|
|
|
from jax.api import (pmap, soft_pmap, jit, vmap, jvp, grad, make_jaxpr,
|
|
|
|
linearize, device_put)
|
2019-02-23 20:34:14 -08:00
|
|
|
from jax.lib import xla_bridge
|
2019-03-19 16:54:55 -07:00
|
|
|
from jax.util import prod
|
|
|
|
from jax.interpreters import pxla
|
2019-07-06 10:00:08 -07:00
|
|
|
from jax.interpreters import xla
|
2019-01-28 11:13:34 -08:00
|
|
|
|
|
|
|
from jax.config import config
|
|
|
|
config.parse_flags_with_absl()
|
|
|
|
|
2019-12-17 14:44:03 -08:00
|
|
|
prev_xla_flags = None
|
|
|
|
|
|
|
|
# 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()
|
2019-01-28 11:13:34 -08:00
|
|
|
|
2020-04-12 15:35:35 -04:00
|
|
|
ignore_soft_pmap_warning = partial(
|
|
|
|
jtu.ignore_warning, message="soft_pmap is an experimental.*")
|
|
|
|
|
2019-02-23 20:34:14 -08:00
|
|
|
|
2019-12-17 14:44:03 -08:00
|
|
|
class PmapTest(jtu.JaxTestCase):
|
2019-03-21 07:37:43 -07:00
|
|
|
def _getMeshShape(self, device_mesh_shape):
|
|
|
|
device_count = xla_bridge.device_count()
|
|
|
|
if any(size == -1 for size in device_mesh_shape):
|
|
|
|
try:
|
|
|
|
return onp.arange(device_count).reshape(device_mesh_shape).shape
|
2020-03-09 22:06:12 +02:00
|
|
|
except ValueError as err:
|
2019-03-21 07:37:43 -07:00
|
|
|
msg = "device mesh shape {} not compatible with device count {}"
|
2020-03-09 22:06:12 +02:00
|
|
|
raise SkipTest(msg.format(device_mesh_shape, device_count)) from err
|
2019-03-21 07:37:43 -07:00
|
|
|
else:
|
|
|
|
if device_count % prod(device_mesh_shape):
|
|
|
|
msg = "device mesh size {} does not divide available device count {}"
|
|
|
|
raise SkipTest(msg.format(prod(device_mesh_shape), device_count))
|
|
|
|
else:
|
|
|
|
return device_mesh_shape
|
|
|
|
|
2019-03-19 16:54:55 -07:00
|
|
|
def testBasic(self):
|
2019-04-12 16:28:40 -07:00
|
|
|
f = pmap(lambda x: x - lax.psum(x, 'i'), axis_name='i')
|
2019-03-19 16:54:55 -07:00
|
|
|
|
|
|
|
shape = (xla_bridge.device_count(), 4)
|
|
|
|
x = onp.arange(prod(shape), dtype=onp.float32).reshape(shape)
|
|
|
|
expected = x - onp.sum(x, 0)
|
|
|
|
|
|
|
|
ans = f(x)
|
|
|
|
self.assertAllClose(ans, expected, check_dtypes=False)
|
|
|
|
|
2020-01-29 18:10:48 +00:00
|
|
|
def testMean(self):
|
|
|
|
f = pmap(lambda x: x - lax.pmean(x, 'i'), axis_name='i')
|
|
|
|
|
|
|
|
shape = (xla_bridge.device_count(), 4)
|
|
|
|
x = onp.arange(prod(shape), dtype=onp.float32).reshape(shape)
|
|
|
|
expected = x - onp.broadcast_to(onp.mean(x, 0), x.shape)
|
|
|
|
|
|
|
|
ans = f(x)
|
|
|
|
self.assertAllClose(ans, expected, check_dtypes=False)
|
|
|
|
|
2020-03-19 15:35:00 +00:00
|
|
|
def testGather(self):
|
|
|
|
f = pmap(lambda x: lax.all_gather(x, 'i'), axis_name='i')
|
|
|
|
|
|
|
|
shape = (xla_bridge.device_count(), 4)
|
|
|
|
x = onp.arange(prod(shape), dtype=onp.float32).reshape(shape)
|
|
|
|
expected = onp.array([x] * xla_bridge.device_count())
|
|
|
|
ans = f(x)
|
|
|
|
self.assertAllClose(ans, expected, check_dtypes=False)
|
|
|
|
|
2020-01-29 03:04:59 +00:00
|
|
|
def testTrees(self):
|
|
|
|
ptranspose = lambda x, axis_name: lax.all_to_all(x, axis_name, 0, 0)
|
|
|
|
def protate(x, axis_name):
|
|
|
|
n = lax.psum(1, axis_name)
|
|
|
|
return lax.ppermute(x, axis_name, [(i, (i + 1) % n) for i in range(n)])
|
|
|
|
|
|
|
|
tree_f = lambda f: partial(tree_util.tree_map, f)
|
|
|
|
jax_f = lambda p: pmap(lambda x: p(x, 'i'), 'i')
|
|
|
|
onp_f = lambda p: tree_f(lambda x: onp.broadcast_to(p(x, 0), x.shape))
|
|
|
|
onp_transpose = tree_f(onp.transpose)
|
|
|
|
onp_rotate = tree_f(lambda x: onp.concatenate([x[-1:], x[:-1]]))
|
|
|
|
|
|
|
|
n = xla_bridge.device_count()
|
|
|
|
x = {'a': onp.arange(1 * n * n, 2 * n * n).reshape([n, n]),
|
|
|
|
'b': onp.arange(2 * n * n, 3 * n * n).reshape([n, n]),
|
|
|
|
'c': onp.arange(4 * n * n, 5 * n * n).reshape([n, n])}
|
|
|
|
|
|
|
|
assert_allclose = partial(tree_util.tree_multimap,
|
|
|
|
partial(self.assertAllClose, check_dtypes=False))
|
|
|
|
assert_allclose(jax_f(lax.pmax)(x), onp_f(onp.max)(x))
|
|
|
|
assert_allclose(jax_f(lax.pmin)(x), onp_f(onp.min)(x))
|
|
|
|
assert_allclose(jax_f(lax.psum)(x), onp_f(onp.sum)(x))
|
2020-01-29 18:10:48 +00:00
|
|
|
assert_allclose(jax_f(lax.pmean)(x), onp_f(onp.mean)(x))
|
2020-01-29 03:04:59 +00:00
|
|
|
if jtu.device_under_test() not in ("cpu", "gpu"):
|
|
|
|
# NOTE: all-to-all and ppermute only supported on TPU.
|
|
|
|
assert_allclose(jax_f(ptranspose)(x), onp_transpose(x))
|
|
|
|
assert_allclose(jax_f(protate)(x), onp_rotate(x))
|
|
|
|
|
2020-03-04 11:35:52 -05:00
|
|
|
def testCollectivesWithTreesOfDifferentDtypes(self):
|
|
|
|
n = len(jax.devices())
|
|
|
|
x = {'a': onp.arange(1 * n * n, 2 * n * n, dtype=onp.float32).reshape([n, n]),
|
|
|
|
'b': onp.arange(2 * n * n, 3 * n * n, dtype=onp.int32).reshape([n, n]),
|
|
|
|
'c': onp.arange(4 * n * n, 5 * n * n, dtype=onp.float32).reshape([n, n]),
|
|
|
|
'd': onp.arange(6 * n * n, 7 * n * n, dtype=onp.int32).reshape([n, n])}
|
|
|
|
tree_f = lambda f: partial(tree_util.tree_map, f)
|
|
|
|
jax_f = lambda p: pmap(lambda x: p(x, 'i'), 'i')
|
|
|
|
onp_f = lambda p: tree_f(lambda x: onp.broadcast_to(p(x, 0), x.shape))
|
|
|
|
assert_allclose = partial(tree_util.tree_multimap,
|
|
|
|
partial(self.assertAllClose, check_dtypes=False))
|
|
|
|
assert_allclose(jax_f(lax.pmax)(x), onp_f(onp.max)(x))
|
|
|
|
assert_allclose(jax_f(lax.pmin)(x), onp_f(onp.min)(x))
|
|
|
|
assert_allclose(jax_f(lax.psum)(x), onp_f(onp.sum)(x))
|
|
|
|
assert_allclose(jax_f(lax.pmean)(x), onp_f(onp.mean)(x))
|
|
|
|
|
2019-10-15 22:55:35 +00:00
|
|
|
def testComplexPsum(self):
|
|
|
|
f = pmap(lambda x: x - lax.psum(x, 'i'), axis_name='i')
|
|
|
|
|
|
|
|
shape = (xla_bridge.device_count(), 4 * 2)
|
|
|
|
x = onp.arange(prod(shape), dtype=onp.float32).reshape(shape).view(onp.complex64)
|
|
|
|
expected = x - onp.sum(x, 0)
|
|
|
|
|
|
|
|
ans = f(x)
|
|
|
|
self.assertAllClose(ans, expected, check_dtypes=False)
|
|
|
|
|
|
|
|
|
2019-03-19 16:54:55 -07:00
|
|
|
def testNestedBasic(self):
|
2019-04-12 16:28:40 -07:00
|
|
|
f = lambda x: lax.psum(lax.psum(x, 'i'), 'j')
|
2019-03-19 16:54:55 -07:00
|
|
|
f = pmap(pmap(f, 'i'), 'j')
|
|
|
|
|
2019-03-20 17:46:16 -07:00
|
|
|
def sum_and_broadcast(x, axis):
|
|
|
|
return onp.repeat(onp.sum(x, axis, keepdims=True), x.shape[axis], axis)
|
|
|
|
|
2019-03-19 16:54:55 -07:00
|
|
|
shape = (xla_bridge.device_count(), 1, 4)
|
|
|
|
x = onp.arange(prod(shape), dtype=onp.float32).reshape(shape)
|
|
|
|
|
|
|
|
ans = f(x)
|
2019-03-20 17:46:16 -07:00
|
|
|
expected = sum_and_broadcast(sum_and_broadcast(x, 0), 1)
|
2019-03-19 16:54:55 -07:00
|
|
|
self.assertAllClose(ans, expected, check_dtypes=False)
|
|
|
|
|
2019-10-10 13:13:21 -04:00
|
|
|
def testMismatchedAxisSizes(self):
|
|
|
|
n = xla_bridge.device_count()
|
|
|
|
f = pmap(lambda x, y: x + y)
|
2019-11-28 08:48:10 +01:00
|
|
|
self.assertRaisesRegex(
|
2019-11-14 16:00:55 -05:00
|
|
|
ValueError,
|
|
|
|
"Axis size .* does not match leading dimension of shape .*",
|
|
|
|
lambda: f(onp.random.randn(n), onp.random.randn(n - 1)))
|
2019-10-10 13:13:21 -04:00
|
|
|
|
2019-03-19 16:54:55 -07:00
|
|
|
@parameterized.named_parameters(
|
2020-04-15 12:43:55 -07:00
|
|
|
{"testcase_name": "_mesh={}".format(device_mesh_shape).replace(" ", ""),
|
2019-03-19 16:54:55 -07:00
|
|
|
"device_mesh_shape": device_mesh_shape}
|
|
|
|
for device_mesh_shape in [(1, 1), (2, -1), (-1, 2)])
|
|
|
|
def testNestedShardingAndStacking(self, device_mesh_shape):
|
2019-03-21 07:37:43 -07:00
|
|
|
mesh_shape = self._getMeshShape(device_mesh_shape)
|
2019-03-19 16:54:55 -07:00
|
|
|
|
|
|
|
f = lambda x: x
|
|
|
|
f = pmap(pmap(f, 'i'), 'j')
|
|
|
|
|
|
|
|
shape = mesh_shape + (4,)
|
|
|
|
x = onp.arange(prod(shape), dtype=onp.float32).reshape(shape)
|
2019-03-20 17:46:16 -07:00
|
|
|
|
2019-03-19 16:54:55 -07:00
|
|
|
ans = f(x)
|
2019-03-20 17:46:16 -07:00
|
|
|
expected = x
|
2019-03-19 16:54:55 -07:00
|
|
|
self.assertEqual(ans.shape, expected.shape)
|
|
|
|
self.assertAllClose(ans, expected, check_dtypes=False)
|
|
|
|
|
|
|
|
def testJvpAndPartialEval(self):
|
|
|
|
@partial(pmap, axis_name='i')
|
|
|
|
def f(x):
|
|
|
|
return np.sin(x)
|
|
|
|
|
|
|
|
def splitjvp(x):
|
|
|
|
_, jvp = linearize(f, x)
|
|
|
|
return jvp(np.ones_like(x))
|
|
|
|
|
|
|
|
shape = (xla_bridge.device_count(), 4)
|
|
|
|
x = onp.arange(prod(shape), dtype=onp.float32).reshape(shape)
|
|
|
|
expected = onp.cos(x)
|
|
|
|
|
|
|
|
ans = splitjvp(x)
|
|
|
|
self.assertAllClose(ans, expected, check_dtypes=False)
|
|
|
|
|
|
|
|
make_jaxpr(splitjvp)(x) # doesn't crash
|
|
|
|
|
|
|
|
def testGradBasic(self):
|
|
|
|
@partial(pmap, axis_name='i')
|
|
|
|
def f(x):
|
|
|
|
return np.sin(x)
|
|
|
|
|
|
|
|
shape = (xla_bridge.device_count(), 4)
|
|
|
|
x = onp.arange(prod(shape), dtype=onp.float32).reshape(shape)
|
|
|
|
|
|
|
|
ans = grad(lambda x: np.sum(np.sin(x)))(x)
|
|
|
|
expected = grad(lambda x: np.sum(f(x)))(x)
|
|
|
|
self.assertAllClose(ans, expected, check_dtypes=False)
|
|
|
|
|
2019-11-06 08:36:53 -08:00
|
|
|
def testGradOfPsum(self):
|
|
|
|
@partial(pmap, axis_name='i')
|
|
|
|
def f(x):
|
|
|
|
return lax.psum(x, axis_name='i')
|
|
|
|
|
|
|
|
shape = (jax.device_count(), 4)
|
|
|
|
x = onp.arange(prod(shape), dtype=onp.float32).reshape(shape)
|
|
|
|
jtu.check_grads(f, (x,), 2, ["fwd", "rev"], 1e-2, 1e-2, eps=1.)
|
|
|
|
|
2019-03-19 16:54:55 -07:00
|
|
|
def testGradOfJvp(self):
|
|
|
|
@partial(pmap, axis_name='i')
|
|
|
|
def f(x):
|
|
|
|
return np.sin(x)
|
|
|
|
|
|
|
|
def splitjvp(x):
|
|
|
|
_, jvp = linearize(f, x)
|
|
|
|
return jvp(np.ones_like(x))
|
|
|
|
|
|
|
|
fun = lambda x: np.sum(jvp(np.sin, (x,), (np.ones_like(x),))[1])
|
|
|
|
|
|
|
|
shape = (xla_bridge.device_count(), 4)
|
|
|
|
x = onp.arange(prod(shape), dtype=onp.float32).reshape(shape)
|
|
|
|
|
|
|
|
ans = grad(lambda x: np.sum(splitjvp(x)))(x)
|
|
|
|
expected = grad(fun)(x)
|
|
|
|
self.assertAllClose(ans, expected, check_dtypes=True)
|
|
|
|
|
|
|
|
def testTwoArgsGrad(self):
|
|
|
|
def f(x, y):
|
2019-04-12 16:28:40 -07:00
|
|
|
return lax.psum(5. * np.cos(x) * np.sin(y), 'i')
|
2019-03-19 16:54:55 -07:00
|
|
|
f = pmap(f, 'i')
|
|
|
|
|
|
|
|
def g(x, y):
|
|
|
|
tot = np.sum(5. * np.cos(x) * np.sin(y))
|
|
|
|
return tot * np.ones_like(x) # broadcast to map like pjit does
|
|
|
|
|
|
|
|
shape = (xla_bridge.device_count(), 4)
|
|
|
|
x = onp.arange(prod(shape), dtype=onp.float32).reshape(shape)
|
|
|
|
y = 4 + x
|
|
|
|
ans = grad(lambda x, y: np.sum(g(x, y)))(x, y)
|
|
|
|
expected = grad(lambda x, y: np.sum(g(x, y)))(x, y)
|
|
|
|
self.assertAllClose(ans, expected, check_dtypes=False)
|
|
|
|
|
|
|
|
@parameterized.named_parameters(
|
2020-04-15 12:43:55 -07:00
|
|
|
{"testcase_name": "_mesh={}".format(device_mesh_shape).replace(" ", ""),
|
2019-03-19 16:54:55 -07:00
|
|
|
"device_mesh_shape": device_mesh_shape}
|
|
|
|
for device_mesh_shape in [(1, 1), (2, -1), (-1, 2)])
|
|
|
|
def testNestedWithClosure(self, device_mesh_shape):
|
2019-03-21 07:37:43 -07:00
|
|
|
mesh_shape = self._getMeshShape(device_mesh_shape)
|
2019-02-23 20:34:14 -08:00
|
|
|
|
2019-03-06 14:36:47 -08:00
|
|
|
@partial(pmap, axis_name='i')
|
2019-02-23 20:34:14 -08:00
|
|
|
def test_fun(x):
|
|
|
|
y = np.sum(np.sin(x))
|
|
|
|
|
2019-03-06 14:36:47 -08:00
|
|
|
@partial(pmap, axis_name='j')
|
2019-02-23 20:34:14 -08:00
|
|
|
def g(z):
|
|
|
|
return 3. * np.exp(np.sin(x).sum() * np.cos(y) * np.tan(z))
|
|
|
|
|
|
|
|
return grad(lambda w: np.sum(g(w)))(x)
|
|
|
|
|
|
|
|
@vmap
|
|
|
|
def baseline_fun(x):
|
|
|
|
y = np.sum(np.sin(x))
|
|
|
|
|
|
|
|
@vmap
|
|
|
|
def g(z):
|
|
|
|
return 3. * np.exp(np.sin(x).sum() * np.cos(y) * np.tan(z))
|
|
|
|
|
|
|
|
return grad(lambda w: np.sum(g(w)))(x)
|
|
|
|
|
2019-03-19 16:54:55 -07:00
|
|
|
shape = mesh_shape + (4,)
|
|
|
|
x = onp.arange(prod(shape), dtype=onp.float32).reshape(shape)
|
|
|
|
|
2019-02-23 20:34:14 -08:00
|
|
|
ans = grad(lambda x: np.sum(test_fun(x)))(x)
|
|
|
|
expected = grad(lambda x: np.sum(baseline_fun(x)))(x)
|
2019-12-17 14:44:03 -08:00
|
|
|
self.assertAllClose(ans, expected, check_dtypes=True, atol=1e-3)
|
2019-02-01 16:59:28 -08:00
|
|
|
|
2019-05-02 22:13:49 -07:00
|
|
|
def testShardedDeviceArrays(self):
|
2019-03-19 16:54:55 -07:00
|
|
|
f = lambda x: 2 * x
|
|
|
|
f = pmap(f, axis_name='i')
|
|
|
|
|
|
|
|
shape = (xla_bridge.device_count(), 4)
|
|
|
|
x = onp.arange(prod(shape), dtype=onp.float32).reshape(shape)
|
|
|
|
|
|
|
|
# test that we can pass in and out ShardedDeviceArrays
|
|
|
|
y = f(x)
|
2019-05-02 22:13:49 -07:00
|
|
|
self.assertIsInstance(y, np.ndarray)
|
|
|
|
self.assertIsInstance(y, pxla.ShardedDeviceArray)
|
2019-03-19 16:54:55 -07:00
|
|
|
self.assertAllClose(y, 2 * x, check_dtypes=False)
|
|
|
|
z = f(y)
|
2019-05-02 22:13:49 -07:00
|
|
|
self.assertIsInstance(z, pxla.ShardedDeviceArray)
|
2019-03-19 16:54:55 -07:00
|
|
|
self.assertAllClose(z, 2 * 2 * x, check_dtypes=False)
|
|
|
|
|
|
|
|
# test that we can pass in a regular DeviceArray
|
|
|
|
y = f(device_put(x))
|
2019-05-02 22:13:49 -07:00
|
|
|
self.assertIsInstance(y, pxla.ShardedDeviceArray)
|
2019-03-19 16:54:55 -07:00
|
|
|
self.assertAllClose(y, 2 * x, check_dtypes=False)
|
|
|
|
|
|
|
|
# test that we can pass a ShardedDeviceArray to a regular jit computation
|
|
|
|
z = y + y
|
|
|
|
self.assertAllClose(z, 2 * 2 * x, check_dtypes=False)
|
|
|
|
|
|
|
|
# test that we can handle device movement on dispatch
|
|
|
|
y.device_buffers = y.device_buffers[::-1]
|
|
|
|
z = f(y)
|
|
|
|
self.assertAllClose(z, 2 * 2 * x[::-1], check_dtypes=False)
|
|
|
|
|
2019-05-02 22:13:49 -07:00
|
|
|
# test that the repr doesn't crash
|
|
|
|
repr(z)
|
|
|
|
|
2020-04-15 18:43:46 -07:00
|
|
|
# Tests edge cases in lax._reshape_sharded_device_array
|
|
|
|
@parameterized.named_parameters(
|
|
|
|
{"testcase_name": "_in={}_out={}".format(in_shape, out_shape)
|
|
|
|
.replace(" ", ""),
|
|
|
|
"in_shape": in_shape, "out_shape": out_shape}
|
|
|
|
for in_shape, out_shape in [
|
|
|
|
[(1,1), (1,)], [(1,), (1,1)], [(1,), ()], [(4,7), (2,2,7)]
|
|
|
|
])
|
|
|
|
def testShardedDeviceArrayReshape(self, in_shape, out_shape):
|
|
|
|
if xla_bridge.device_count() < max(in_shape[:1] + out_shape[:1]):
|
|
|
|
raise SkipTest("not enough devices")
|
|
|
|
|
|
|
|
x = onp.arange(prod(in_shape)).reshape(in_shape)
|
|
|
|
sharded_x = pmap(lambda x: x)(x)
|
|
|
|
self.assertAllClose(sharded_x.reshape(out_shape), x.reshape(out_shape),
|
|
|
|
check_dtypes=False)
|
|
|
|
|
2019-04-01 17:56:23 -07:00
|
|
|
def testPsumMultiple(self):
|
2019-04-12 16:28:40 -07:00
|
|
|
f = lambda x: lax.psum(x, ('i', 'j'))
|
2019-04-01 17:56:23 -07:00
|
|
|
f = pmap(pmap(f, 'i'), 'j')
|
|
|
|
|
|
|
|
def sum_and_broadcast(x, axis):
|
|
|
|
return onp.repeat(onp.sum(x, axis, keepdims=True), x.shape[axis], axis)
|
|
|
|
|
|
|
|
device_count = xla_bridge.device_count()
|
|
|
|
num_pairs, ragged = divmod(device_count, 2)
|
|
|
|
if num_pairs > 1 and not ragged:
|
|
|
|
shape = (num_pairs, 2, 4)
|
|
|
|
else:
|
|
|
|
shape = (device_count, 1, 4)
|
|
|
|
x = onp.arange(prod(shape), dtype=onp.float32).reshape(shape)
|
|
|
|
|
|
|
|
ans = f(x)
|
|
|
|
expected = sum_and_broadcast(sum_and_broadcast(x, 0), 1)
|
|
|
|
self.assertAllClose(ans, expected, check_dtypes=False)
|
|
|
|
|
2019-11-13 21:10:16 -08:00
|
|
|
def testAxisGroups(self):
|
2020-02-06 17:19:54 -08:00
|
|
|
axis_env = xla.AxisEnv(8, ('i', 'j'), (4, 2))
|
2019-11-13 21:10:16 -08:00
|
|
|
groups = xla.axis_groups(axis_env, 'i')
|
2019-04-01 17:56:23 -07:00
|
|
|
self.assertEqual(groups, ((0, 2, 4, 6), (1, 3, 5, 7)))
|
|
|
|
|
2019-11-13 21:10:16 -08:00
|
|
|
groups = xla.axis_groups(axis_env, 'j')
|
2019-04-01 17:56:23 -07:00
|
|
|
self.assertEqual(groups, ((0, 1), (2, 3), (4, 5), (6, 7)))
|
|
|
|
|
2019-11-13 21:10:16 -08:00
|
|
|
groups = xla.axis_groups(axis_env, ('i', 'j'))
|
2019-04-01 17:56:23 -07:00
|
|
|
self.assertEqual(groups, ((0, 1, 2, 3, 4, 5, 6, 7,),))
|
|
|
|
|
2019-11-13 21:10:16 -08:00
|
|
|
groups = xla.axis_groups(axis_env, ('j', 'i'))
|
2019-04-01 17:56:23 -07:00
|
|
|
self.assertEqual(len(groups), 1)
|
|
|
|
self.assertEqual((tuple(sorted(groups[0])),),
|
|
|
|
((0, 1, 2, 3, 4, 5, 6, 7,),)) # order doesn't matter
|
|
|
|
|
2019-05-09 15:46:34 -07:00
|
|
|
@jtu.skip_on_devices("cpu", "gpu")
|
|
|
|
def testCollectivePermute(self):
|
|
|
|
device_count = xla_bridge.device_count()
|
2019-05-10 14:24:15 -07:00
|
|
|
rotation = [(i, (i + 1) % device_count) for i in range(device_count)]
|
2019-05-10 12:27:14 -07:00
|
|
|
f = lambda x: lax.ppermute(x, perm=rotation, axis_name='i')
|
2019-05-09 15:46:34 -07:00
|
|
|
f = pmap(f, 'i')
|
|
|
|
|
|
|
|
x = np.arange(4 * device_count).reshape((device_count, 4))
|
|
|
|
ans = f(x)
|
2019-05-10 12:27:14 -07:00
|
|
|
expected = onp.roll(x, shift=1, axis=0)
|
2019-05-09 15:46:34 -07:00
|
|
|
self.assertAllClose(ans, expected, check_dtypes=False)
|
|
|
|
|
2019-05-31 14:04:04 -07:00
|
|
|
@jtu.skip_on_devices("cpu", "gpu")
|
|
|
|
def testCollectivePermuteGrad(self):
|
|
|
|
device_count = xla_bridge.device_count()
|
|
|
|
shift_right = [(i, (i + 1)) for i in range(device_count - 1)]
|
|
|
|
f = lambda x: lax.ppermute(x, perm=shift_right, axis_name='i')
|
|
|
|
y = onp.pi + onp.arange(device_count, dtype=onp.float32)
|
|
|
|
g = lambda x: np.sum(y * pmap(f, 'i')(x))
|
|
|
|
|
|
|
|
x = onp.arange(device_count, dtype=onp.float32)
|
|
|
|
ans = grad(g)(x)
|
|
|
|
expected = onp.concatenate([onp.pi + onp.arange(1, device_count), [0]])
|
2019-05-31 14:11:38 -07:00
|
|
|
self.assertAllClose(ans, expected, check_dtypes=False)
|
|
|
|
|
|
|
|
@jtu.skip_on_devices("cpu", "gpu")
|
|
|
|
def testCollectivePermuteCyclicGrad(self):
|
|
|
|
device_count = xla_bridge.device_count()
|
|
|
|
shift_right = [(i, (i + 1) % device_count) for i in range(device_count)]
|
|
|
|
f = lambda x: lax.ppermute(x, perm=shift_right, axis_name='i')
|
|
|
|
y = onp.pi + onp.arange(device_count, dtype=onp.float32)
|
|
|
|
g = lambda x: np.sum(y * pmap(f, 'i')(x))
|
|
|
|
|
|
|
|
x = onp.arange(device_count, dtype=onp.float32)
|
|
|
|
ans = grad(g)(x)
|
|
|
|
expected = onp.roll(onp.pi + onp.arange(device_count), 1)
|
2019-05-31 14:04:04 -07:00
|
|
|
self.assertAllClose(ans, expected, check_dtypes=False)
|
|
|
|
|
2020-01-10 16:49:08 -08:00
|
|
|
@jtu.skip_on_devices("cpu")
|
|
|
|
def testCollectivePermuteCyclicWithPShuffle(self):
|
|
|
|
device_count = xla_bridge.device_count()
|
|
|
|
values = onp.arange(device_count)
|
|
|
|
shift_right = [(i - 1) % device_count for i in range(device_count)]
|
|
|
|
f = lambda x: lax.pshuffle(x, perm=shift_right, axis_name='i')
|
2020-01-13 14:55:29 -08:00
|
|
|
expected = onp.roll(values, -1)
|
2020-01-10 16:49:08 -08:00
|
|
|
ans = onp.asarray(pmap(f, "i")(values))
|
|
|
|
self.assertAllClose(ans, expected, check_dtypes=False)
|
|
|
|
|
|
|
|
@jtu.skip_on_devices("cpu")
|
|
|
|
def testPShuffleWithBadPerm(self):
|
|
|
|
device_count = xla_bridge.device_count()
|
|
|
|
bad_perm = list(range(device_count))
|
|
|
|
bad_perm[0] = 1
|
|
|
|
f = lambda x: lax.pshuffle(x, perm=bad_perm, axis_name='i')
|
|
|
|
g = lambda: pmap(f, "i")(onp.arange(device_count))
|
|
|
|
self.assertRaisesRegex(
|
2020-01-13 14:12:37 -08:00
|
|
|
AssertionError,
|
2020-04-12 15:35:35 -04:00
|
|
|
"Given `perm` does not represent a real permutation: \\[1.*\\]", g)
|
2020-01-10 16:49:08 -08:00
|
|
|
|
2019-11-15 14:33:39 -08:00
|
|
|
@jtu.skip_on_devices("cpu", "gpu")
|
2019-11-16 14:40:25 -08:00
|
|
|
def testPpermuteWithZipObject(self):
|
|
|
|
# https://github.com/google/jax/issues/1703
|
2019-11-15 14:33:39 -08:00
|
|
|
num_devices = xla_bridge.device_count()
|
|
|
|
perm = [num_devices - 1] + list(range(num_devices - 1))
|
|
|
|
f = pmap(
|
|
|
|
lambda x: lax.ppermute(x, "i", zip(range(num_devices), perm)), "i")
|
2019-11-15 14:35:12 -08:00
|
|
|
result = f(np.arange(num_devices, dtype=np.float32))
|
2019-11-15 14:33:39 -08:00
|
|
|
expected = np.asarray(perm, dtype=np.float32)
|
Change scalar promotion rules to prefer array types over scalar types. (#1709)
* Change scalar promotion rules to prefer array types over scalar types.
Currently JAX does not treat Python scalars specially during type promotion. This means that, for example:
`1. + np.array([...], np.float32)`
ends up as an array of type np.float64. The `1.` is promoted to a default type (here np.float64), and the type promotion of a np.float64 and an np.float32 is an np.float64. This is unlike classic NumPy, which treats scalars specially during type promotion, in particular, preferring the type of an array over the type of a scalar.
This change adds a notion of weak_type to JAX avals. During type promotion, we prefer non-weak types, i.e., the type of the array in the example above, ignoring the type of the scalar.
In contexts where a Python scalar is to be promoted to a NumPy value, a default type is used (e.g., `np.float_`). This change also makes it possible to use 32-bit default types that differ from NumPy's default types. The JAX test suite passes with 32-bit default types. However, we do not yet enable this change or expose it in the API.
2019-11-18 14:51:10 -05:00
|
|
|
self.assertAllClose(result, expected, check_dtypes=True)
|
2019-11-15 14:33:39 -08:00
|
|
|
|
2019-05-09 15:46:34 -07:00
|
|
|
@jtu.skip_on_devices("cpu", "gpu")
|
|
|
|
def testRule30(self):
|
2019-05-10 12:27:14 -07:00
|
|
|
# This is a test of collective_permute implementing a simple halo exchange
|
|
|
|
# to run a rule 30 simulation: https://en.wikipedia.org/wiki/Rule_30
|
|
|
|
# Halo exchange should be useful in spatially-sharded convolutions and in
|
|
|
|
# other simulations.
|
2019-05-09 15:46:34 -07:00
|
|
|
device_count = xla_bridge.device_count()
|
2019-05-10 12:27:14 -07:00
|
|
|
|
|
|
|
def send_right(x, axis_name):
|
|
|
|
left_perm = [(i, (i + 1) % device_count) for i in range(device_count)]
|
|
|
|
return lax.ppermute(x, perm=left_perm, axis_name=axis_name)
|
|
|
|
|
|
|
|
def send_left(x, axis_name):
|
|
|
|
left_perm = [((i + 1) % device_count, i) for i in range(device_count)]
|
|
|
|
return lax.ppermute(x, perm=left_perm, axis_name=axis_name)
|
2019-05-09 15:46:34 -07:00
|
|
|
|
|
|
|
def update_board(board):
|
|
|
|
left = board[:-2]
|
|
|
|
right = board[2:]
|
|
|
|
center = board[1:-1]
|
|
|
|
return lax.bitwise_xor(left, lax.bitwise_or(center, right))
|
|
|
|
|
|
|
|
@partial(pmap, axis_name='i')
|
|
|
|
def step(board_slice):
|
|
|
|
left, right = board_slice[:1], board_slice[-1:]
|
2019-05-10 12:27:14 -07:00
|
|
|
right, left = send_left(left, 'i'), send_right(right, 'i')
|
2019-05-09 15:46:34 -07:00
|
|
|
enlarged_board_slice = np.concatenate([left, board_slice, right])
|
|
|
|
return update_board(enlarged_board_slice)
|
|
|
|
|
|
|
|
board = onp.zeros(40, dtype=bool)
|
|
|
|
board[board.shape[0] // 2] = True
|
|
|
|
reshaped_board = board.reshape((device_count, -1))
|
|
|
|
|
|
|
|
boards = []
|
|
|
|
def print_board(board):
|
|
|
|
boards.append(''.join('*' if x else ' ' for x in board.ravel()))
|
|
|
|
|
|
|
|
print_board(reshaped_board)
|
|
|
|
for _ in range(20):
|
|
|
|
reshaped_board = step(reshaped_board)
|
|
|
|
print_board(reshaped_board)
|
|
|
|
|
|
|
|
ans = '\n'.join(boards)
|
|
|
|
expected = '\n'.join((
|
|
|
|
' * ',
|
|
|
|
' *** ',
|
|
|
|
' ** * ',
|
|
|
|
' ** **** ',
|
|
|
|
' ** * * ',
|
|
|
|
' ** **** *** ',
|
|
|
|
' ** * * * ',
|
|
|
|
' ** **** ****** ',
|
|
|
|
' ** * *** * ',
|
|
|
|
' ** **** ** * *** ',
|
|
|
|
' ** * * **** ** * ',
|
|
|
|
' ** **** ** * * **** ',
|
|
|
|
' ** * *** ** ** * * ',
|
|
|
|
' ** **** ** *** *** ** *** ',
|
|
|
|
' ** * * *** * *** * * ',
|
|
|
|
' ** **** ** * * ***** ******* ',
|
|
|
|
' ** * *** **** * *** * ',
|
|
|
|
' ** **** ** *** ** ** * *** ',
|
|
|
|
' ** * * *** * ** *** **** ** * ',
|
|
|
|
' ** **** ** * ****** * * *** ****',
|
|
|
|
' * * *** **** **** *** ** * ',
|
|
|
|
))
|
|
|
|
|
|
|
|
print(ans)
|
|
|
|
self.assertEqual(ans, expected)
|
|
|
|
|
|
|
|
@jtu.skip_on_devices("cpu", "gpu")
|
|
|
|
def testReduceMax(self):
|
|
|
|
f = pmap(lambda x: x - lax.pmax(x, 'i'), axis_name='i')
|
|
|
|
|
|
|
|
shape = (xla_bridge.device_count(), 4)
|
|
|
|
x = onp.arange(prod(shape), dtype=onp.float32).reshape(shape)
|
|
|
|
expected = x - onp.max(x, 0)
|
|
|
|
|
|
|
|
ans = f(x)
|
|
|
|
self.assertAllClose(ans, expected, check_dtypes=False)
|
|
|
|
|
|
|
|
@jtu.skip_on_devices("cpu", "gpu")
|
|
|
|
def testReduceMin(self):
|
|
|
|
f = pmap(lambda x: x - lax.pmin(x, 'i'), axis_name='i')
|
|
|
|
|
|
|
|
shape = (xla_bridge.device_count(), 4)
|
|
|
|
x = onp.arange(prod(shape), dtype=onp.float32).reshape(shape)
|
|
|
|
expected = x - onp.min(x, 0)
|
|
|
|
|
|
|
|
ans = f(x)
|
|
|
|
self.assertAllClose(ans, expected, check_dtypes=False)
|
|
|
|
|
2019-05-17 09:08:08 -07:00
|
|
|
def testDeviceCountError(self):
|
|
|
|
device_count = xla_bridge.device_count()
|
|
|
|
|
|
|
|
f = pmap(lambda x: x)
|
|
|
|
x = np.arange(device_count + 1)
|
2019-11-11 07:02:36 -08:00
|
|
|
self.assertRaisesRegex(ValueError, ".*requires.*replicas", lambda: f(x))
|
2019-05-17 09:08:08 -07:00
|
|
|
|
|
|
|
f = pmap(lambda x: x)
|
|
|
|
x = onp.ones((device_count + 1, 10))
|
2019-11-11 07:02:36 -08:00
|
|
|
self.assertRaisesRegex(ValueError, ".*requires.*replicas", lambda: f(x))
|
2019-05-17 09:08:08 -07:00
|
|
|
|
|
|
|
f = pmap(lambda x: pmap(lambda x: x)(x))
|
|
|
|
x = onp.ones((device_count, 2, 10))
|
2019-11-11 07:02:36 -08:00
|
|
|
self.assertRaisesRegex(ValueError, ".*requires.*replicas", lambda: f(x))
|
2019-05-17 09:08:08 -07:00
|
|
|
|
2019-05-29 10:39:51 -07:00
|
|
|
def testPmapConstant(self):
|
|
|
|
device_count = xla_bridge.device_count()
|
|
|
|
f = pmap(lambda x: 3)
|
|
|
|
x = np.arange(device_count)
|
2019-12-19 11:19:58 -08:00
|
|
|
with jtu.count_jit_and_pmap_compiles() as count:
|
|
|
|
ans = f(x)
|
|
|
|
self.assertEqual(count[0], 0)
|
2019-05-29 10:39:51 -07:00
|
|
|
expected = onp.repeat(3, device_count)
|
|
|
|
self.assertAllClose(ans, expected, check_dtypes=False)
|
|
|
|
|
2019-12-17 16:22:55 -08:00
|
|
|
f = pmap(lambda x: (x, 3))
|
implement lazy sublanguage
Before this commit, this computation would avoid materializing the iota
array at trace time:
@jit
def f(x):
m, n = x.shape
return x + np.arange(n)
But this one would materialize the iota array at trace time and stage it
into the computation as a potentially large array constant:
@jit
def f(x):
m, n = x.shape
return x + np.arange(m)[:, None]
The difference is that previously operations like broadcasts,
transposes, and reshapes that add singleton dimensions (as above) would
force otherwise lazy values to be materialized, while after this commit
broadcasts, transposes, and reshapes are all lazy operations that only
update metadata on their input rather than compiling and executing XLA
computations and producing new buffers.
Also, np.eye and np.tri become lazy (in addition to np.zeros, np.ones, np.full).
This commit replaces the ad-hoc "lazy device constant" system, which was
used to get the simpler behavior in the first example above.
Incidentally fixes #1431
See https://github.com/google/jax/pull/1668 for more.
2020-01-03 15:46:19 -08:00
|
|
|
x = onp.arange(device_count)
|
2019-12-19 11:19:58 -08:00
|
|
|
with jtu.count_jit_and_pmap_compiles() as count:
|
|
|
|
_, ans = f(x)
|
|
|
|
self.assertEqual(count[0], 1)
|
2019-12-17 16:22:55 -08:00
|
|
|
self.assertAllClose(ans, expected, check_dtypes=False)
|
|
|
|
|
|
|
|
def testPmapConstantDevices(self):
|
|
|
|
if xla_bridge.device_count() == 1:
|
|
|
|
raise SkipTest("this test requires multiple devices")
|
|
|
|
|
|
|
|
devices = xla_bridge.devices()[:-1]
|
|
|
|
shuffle(devices)
|
|
|
|
f = pmap(lambda x: 3, devices=devices)
|
|
|
|
x = np.arange(len(devices))
|
2019-12-19 11:19:58 -08:00
|
|
|
with jtu.count_jit_and_pmap_compiles() as count:
|
|
|
|
ans = f(x)
|
|
|
|
self.assertEqual(count[0], 0)
|
2019-12-17 16:22:55 -08:00
|
|
|
expected = onp.repeat(3, len(devices))
|
|
|
|
self.assertAllClose(ans, expected, check_dtypes=False)
|
|
|
|
|
|
|
|
# Test that 'ans' was properly replicated across devices.
|
|
|
|
self.assertEqual([b.device() for b in ans.device_buffers], devices)
|
|
|
|
|
|
|
|
def testPmapConstantError(self):
|
|
|
|
device_count = xla_bridge.device_count()
|
|
|
|
f = pmap(lambda x: 3)
|
|
|
|
x = np.arange(device_count + 1)
|
|
|
|
self.assertRaisesRegex(
|
|
|
|
ValueError, r"Cannot replicate across \d+ replicas because only \d+ "
|
|
|
|
r"local devices are available.", lambda: f(x))
|
|
|
|
|
|
|
|
f = pmap(lambda x: 3, devices=[xla_bridge.devices()[0]])
|
|
|
|
x = np.arange(2)
|
|
|
|
self.assertRaisesRegex(
|
|
|
|
ValueError, "Cannot replicate across 2 replicas because only 1 "
|
|
|
|
"local devices are available.", lambda: f(x))
|
|
|
|
|
|
|
|
def testNestedPmapConstant(self):
|
|
|
|
if xla_bridge.device_count() == 1:
|
|
|
|
raise SkipTest("this test requires multiple devices")
|
|
|
|
|
|
|
|
f = pmap(pmap(lambda x: 3))
|
|
|
|
shape = (2, xla_bridge.device_count() // 2, 3)
|
|
|
|
x = np.arange(prod(shape)).reshape(shape)
|
2019-12-19 11:19:58 -08:00
|
|
|
with jtu.count_jit_and_pmap_compiles() as count:
|
|
|
|
ans = f(x)
|
|
|
|
self.assertEqual(count[0], 0)
|
2019-12-17 16:22:55 -08:00
|
|
|
expected = 3 * onp.ones(shape[:2])
|
|
|
|
self.assertAllClose(ans, expected, check_dtypes=False)
|
|
|
|
|
|
|
|
# Test that 'ans' was properly replicated across devices.
|
|
|
|
expected_sharded = pmap(pmap(lambda x: x))(expected)
|
|
|
|
self.assertEqual([b.device() for b in ans.device_buffers],
|
|
|
|
[b.device() for b in expected_sharded.device_buffers])
|
|
|
|
|
|
|
|
f = pmap(pmap(lambda x: (x, 3)))
|
|
|
|
x_sharded, ans = f(x)
|
|
|
|
self.assertAllClose(ans, expected, check_dtypes=False)
|
|
|
|
self.assertEqual([b.device() for b in ans.device_buffers],
|
|
|
|
[b.device() for b in x_sharded.device_buffers])
|
|
|
|
|
|
|
|
|
|
|
|
def testNestedPmapConstantDevices(self):
|
|
|
|
raise SkipTest("Nested pmaps with devices not yet implemented")
|
|
|
|
|
|
|
|
if xla_bridge.device_count() < 6:
|
|
|
|
raise SkipTest("this test requires >= 6 devices")
|
|
|
|
|
|
|
|
devices = xla_bridge.devices()[:-2]
|
|
|
|
shuffle(devices)
|
|
|
|
f = pmap(pmap(lambda x: 3), devices=devices)
|
|
|
|
shape = (2, len(devices) // 2, 3)
|
|
|
|
x = np.arange(prod(shape)).reshape(shape)
|
2019-12-19 11:19:58 -08:00
|
|
|
with jtu.count_jit_and_pmap_compiles() as count:
|
|
|
|
ans = f(x)
|
|
|
|
self.assertEqual(count[0], 0)
|
2019-12-17 16:22:55 -08:00
|
|
|
expected = 3 * onp.ones(shape[:2])
|
|
|
|
self.assertAllClose(ans, expected, check_dtypes=False)
|
|
|
|
|
|
|
|
# Test that 'ans' was properly replicated across devices.
|
|
|
|
expected_sharded = pmap(pmap(lambda x: x), devices=devices)(expected)
|
|
|
|
self.assertEqual([b.device() for b in ans.device_buffers],
|
|
|
|
[b.device() for b in expected_sharded.device_buffers])
|
|
|
|
|
|
|
|
def testNestedPmapConstantError(self):
|
|
|
|
f = pmap(pmap(lambda x: 3))
|
|
|
|
shape = (2, xla_bridge.device_count() // 2 + 1, 3)
|
|
|
|
x = np.arange(prod(shape)).reshape(shape)
|
|
|
|
self.assertRaisesRegex(
|
|
|
|
ValueError, r"Cannot replicate across \d+ replicas because only \d+ "
|
|
|
|
r"local devices are available.", lambda: f(x))
|
|
|
|
|
|
|
|
if xla_bridge.device_count() > 1:
|
|
|
|
f = pmap(pmap(lambda x: 3), devices=xla_bridge.devices()[:-1])
|
|
|
|
shape = (2, xla_bridge.device_count() // 2, 3)
|
|
|
|
x = np.arange(prod(shape)).reshape(shape)
|
|
|
|
self.assertRaisesRegex(
|
|
|
|
ValueError, r"Cannot replicate across \d+ replicas because only \d+ "
|
|
|
|
r"local devices are available.", lambda: f(x))
|
|
|
|
|
2019-05-29 10:39:51 -07:00
|
|
|
def testCollectiveConstant(self):
|
|
|
|
device_count = xla_bridge.device_count()
|
|
|
|
f = pmap(lambda x: lax.psum(1, 'i'), 'i')
|
|
|
|
x = np.arange(device_count)
|
|
|
|
ans = f(x)
|
|
|
|
expected = onp.repeat(device_count, device_count)
|
|
|
|
self.assertAllClose(ans, expected, check_dtypes=False)
|
|
|
|
|
|
|
|
def testCollectiveConstantNested(self):
|
|
|
|
device_count = xla_bridge.device_count()
|
|
|
|
|
|
|
|
@partial(pmap, axis_name='i')
|
|
|
|
def f(x):
|
|
|
|
@partial(pmap, axis_name='j')
|
|
|
|
def g(y):
|
|
|
|
a = lax.psum(1, 'i')
|
|
|
|
b = lax.psum(1, 'j')
|
|
|
|
c = lax.psum(1, ('i', 'j'))
|
|
|
|
return a, b, c
|
|
|
|
return g(x)
|
|
|
|
|
|
|
|
shape = (device_count, 1, 4)
|
|
|
|
x = np.arange(prod(shape)).reshape(shape)
|
|
|
|
a, b, c = f(x)
|
|
|
|
|
|
|
|
self.assertEqual(a.shape, shape[:-1])
|
|
|
|
self.assertEqual(b.shape, shape[:-1])
|
|
|
|
self.assertEqual(c.shape, shape[:-1])
|
|
|
|
|
|
|
|
self.assertEqual(a.ravel()[0], device_count)
|
|
|
|
self.assertEqual(b.ravel()[0], 1)
|
|
|
|
self.assertEqual(c.ravel()[0], device_count * 1)
|
|
|
|
|
|
|
|
def testAxisIndex(self):
|
|
|
|
device_count = xla_bridge.device_count()
|
|
|
|
f = pmap(lambda x: x + pxla.axis_index('i'), 'i')
|
|
|
|
x = np.ones(device_count)
|
|
|
|
ans = f(x)
|
|
|
|
expected = 1 + onp.arange(device_count)
|
|
|
|
self.assertAllClose(ans, expected, check_dtypes=False)
|
|
|
|
|
2019-06-04 18:33:52 -07:00
|
|
|
def testVmapOfPmap(self):
|
|
|
|
device_count = xla_bridge.device_count()
|
|
|
|
f0 = lambda x: x
|
|
|
|
f1 = pmap(f0, axis_name='i')
|
|
|
|
ax = onp.random.randn(2, device_count, 50, 60)
|
|
|
|
bx = vmap(f1)(ax)
|
|
|
|
self.assertAllClose(ax, bx, check_dtypes=False)
|
|
|
|
|
2019-09-11 06:01:32 -07:00
|
|
|
def testVmapOfPmap2(self):
|
|
|
|
N_DEVICES = xla_bridge.device_count()
|
|
|
|
keys = random.split(random.PRNGKey(1), 13) # [13, 2]
|
|
|
|
|
|
|
|
@pmap
|
|
|
|
def g(key):
|
|
|
|
params = random.normal(key, ())
|
|
|
|
return 0.
|
|
|
|
|
|
|
|
@vmap
|
|
|
|
def s(keys):
|
|
|
|
keys = np.broadcast_to(keys, (N_DEVICES,) + keys.shape)
|
|
|
|
return g(keys)
|
|
|
|
|
2019-09-11 06:22:25 -07:00
|
|
|
ans = s(keys) # doesn't crash
|
|
|
|
self.assertEqual(ans.shape, (13, N_DEVICES))
|
2019-09-11 06:01:32 -07:00
|
|
|
|
2019-06-04 18:33:52 -07:00
|
|
|
def testVmapOfPmapNonLeadingAxis(self):
|
|
|
|
device_count = xla_bridge.device_count()
|
|
|
|
f0 = lambda x: x
|
|
|
|
f1 = pmap(f0, axis_name='i')
|
|
|
|
ax = onp.random.randn(device_count, 2, 50, 60)
|
|
|
|
bx = vmap(f1, in_axes=2, out_axes=2)(ax)
|
|
|
|
self.assertAllClose(ax, bx, check_dtypes=False)
|
|
|
|
|
|
|
|
def testVmapOfPmapTuple(self):
|
|
|
|
device_count = xla_bridge.device_count()
|
|
|
|
f0 = lambda *x: x
|
|
|
|
f1 = pmap(f0, axis_name='i')
|
|
|
|
|
|
|
|
ax = onp.random.randn(device_count, 2, 50, 60)
|
|
|
|
ay = onp.random.randn(device_count, 30, 2)
|
|
|
|
az1 = onp.random.randn(device_count, 20)
|
|
|
|
az2 = onp.random.randn(2, device_count, 20)
|
|
|
|
|
|
|
|
bx, by, bz = vmap(f1, in_axes=(1, 2, (None, 0)), out_axes=(1, 2, 0))(ax, ay, (az1, az2))
|
|
|
|
|
|
|
|
self.assertAllClose(ax, bx, check_dtypes=False)
|
|
|
|
self.assertAllClose(ay, by, check_dtypes=False)
|
|
|
|
|
|
|
|
bz1, bz2 = bz
|
|
|
|
expected_bz1 = onp.broadcast_to(az1, (2,) + az1.shape)
|
|
|
|
self.assertAllClose(expected_bz1, bz1, check_dtypes=False)
|
|
|
|
self.assertAllClose(bz2, bz2, check_dtypes=False)
|
|
|
|
|
2019-06-23 16:41:59 -07:00
|
|
|
@jtu.skip_on_devices("gpu")
|
2019-06-08 08:57:34 -07:00
|
|
|
def testPswapaxes(self):
|
|
|
|
device_count = xla_bridge.device_count()
|
2019-12-17 14:44:03 -08:00
|
|
|
# TODO: AllToAll not yet implemented on XLA:CPU
|
|
|
|
if jtu.device_under_test() == "cpu":
|
|
|
|
device_count = 1
|
2019-06-08 08:57:34 -07:00
|
|
|
shape = (device_count, 3, device_count, 5)
|
|
|
|
x = onp.arange(prod(shape)).reshape(shape)
|
|
|
|
|
|
|
|
ans = pmap(lambda x: lax.pswapaxes(x, 'i', 1), axis_name='i')(x)
|
|
|
|
expected = onp.swapaxes(x, 0, 2)
|
|
|
|
self.assertAllClose(ans, expected, check_dtypes=False)
|
|
|
|
|
2020-04-15 12:43:55 -07:00
|
|
|
def testReshardInput(self):
|
|
|
|
if xla_bridge.device_count() < 6:
|
|
|
|
raise SkipTest("testReshardInput requires 6 devices")
|
|
|
|
# Manually construct a ShardedDeviceArray with the wrong sharding for the
|
|
|
|
# subsequent pmap
|
|
|
|
shard_shape = (3,2)
|
|
|
|
shard = np.arange(np.prod(shard_shape)).reshape(shard_shape)
|
|
|
|
bufs = [xla.device_put(shard, d) for d in xla_bridge.devices()[:4]]
|
|
|
|
aval = ShapedArray((6,4), shard.dtype)
|
|
|
|
sharding_spec = pxla.ShardingSpec(
|
|
|
|
shards_per_axis=(2, 2),
|
|
|
|
is_axis_materialized=(True, True),
|
|
|
|
replication_factor=2)
|
|
|
|
arr = pxla.ShardedDeviceArray(aval, sharding_spec, bufs)
|
|
|
|
|
|
|
|
r = pmap(lambda x: x + 1)(arr)
|
|
|
|
self.assertAllClose(r, arr + 1, check_dtypes=True)
|
|
|
|
self.assertEqual(len(r.device_buffers), 6)
|
|
|
|
|
2020-04-12 15:35:35 -04:00
|
|
|
@ignore_soft_pmap_warning()
|
2019-06-23 16:41:59 -07:00
|
|
|
def testSoftPmapPsum(self):
|
|
|
|
n = 4 * xla_bridge.device_count()
|
|
|
|
def f(x):
|
|
|
|
return x / lax.psum(x, 'i')
|
|
|
|
ans = soft_pmap(f, 'i')(np.ones(n))
|
|
|
|
expected = onp.ones(n) / n
|
|
|
|
self.assertAllClose(ans, expected, check_dtypes=False)
|
|
|
|
|
2020-04-12 15:35:35 -04:00
|
|
|
@ignore_soft_pmap_warning()
|
2019-06-23 16:41:59 -07:00
|
|
|
def testSoftPmapAxisIndex(self):
|
|
|
|
n = 4 * xla_bridge.device_count()
|
|
|
|
def f(x):
|
|
|
|
return x * lax.axis_index('i')
|
|
|
|
ans = soft_pmap(f, 'i')(2 * np.ones(n))
|
|
|
|
expected = 2 * onp.arange(n)
|
|
|
|
self.assertAllClose(ans, expected, check_dtypes=False)
|
|
|
|
|
2020-04-12 15:35:35 -04:00
|
|
|
@ignore_soft_pmap_warning()
|
2019-06-23 16:41:59 -07:00
|
|
|
def testSoftPmapOfJit(self):
|
|
|
|
n = 4 * xla_bridge.device_count()
|
|
|
|
def f(x):
|
|
|
|
return 3 * x
|
|
|
|
ans = soft_pmap(jit(f), 'i')(onp.arange(n))
|
|
|
|
expected = 3 * onp.arange(n)
|
|
|
|
self.assertAllClose(ans, expected, check_dtypes=False)
|
|
|
|
|
2020-04-12 15:35:35 -04:00
|
|
|
@ignore_soft_pmap_warning()
|
2019-06-23 16:41:59 -07:00
|
|
|
def testSoftPmapNested(self):
|
|
|
|
n = 4 * xla_bridge.device_count()
|
|
|
|
|
|
|
|
@partial(soft_pmap, axis_name='i')
|
|
|
|
@partial(soft_pmap, axis_name='j')
|
|
|
|
def f(x):
|
|
|
|
i_size = lax.psum(1, 'i')
|
|
|
|
return x + lax.axis_index('i') + i_size * lax.axis_index('j')
|
|
|
|
|
|
|
|
ans = f(np.zeros((n, n)))
|
|
|
|
expected = onp.arange(n ** 2).reshape(n, n).T
|
|
|
|
self.assertAllClose(ans, expected, check_dtypes=False)
|
|
|
|
|
2020-04-12 15:35:35 -04:00
|
|
|
@ignore_soft_pmap_warning()
|
2019-06-23 16:41:59 -07:00
|
|
|
def testGradOfSoftPmap(self):
|
|
|
|
n = 4 * xla_bridge.device_count()
|
|
|
|
|
|
|
|
@partial(soft_pmap, axis_name='i')
|
|
|
|
def f(x):
|
|
|
|
return x * lax.axis_index('i')
|
|
|
|
|
|
|
|
ans = grad(lambda x: np.sum(f(x)))(np.zeros((n, n)))
|
|
|
|
expected = onp.repeat(onp.arange(n)[:, None], n, axis=1)
|
|
|
|
self.assertAllClose(ans, expected, check_dtypes=False)
|
|
|
|
|
2020-04-12 15:35:35 -04:00
|
|
|
@ignore_soft_pmap_warning()
|
2019-07-06 10:00:08 -07:00
|
|
|
def testSoftPmapDevicePersistence(self):
|
|
|
|
device_count = xla_bridge.device_count()
|
|
|
|
shape = (2 * 2 * device_count, 2, 3)
|
|
|
|
|
|
|
|
# check that we can maintain device persistence across calls
|
|
|
|
x = onp.arange(prod(shape)).reshape(shape)
|
|
|
|
x = soft_pmap(lambda x: x)(x)
|
2020-04-15 12:43:55 -07:00
|
|
|
self.assertIsInstance(x, pxla.ShardedDeviceArray)
|
2019-07-06 10:00:08 -07:00
|
|
|
x._npy_value = onp.float32(onp.nan) # can't be coerced to ndarray for xfer
|
|
|
|
x = soft_pmap(lambda x: x)(x) # doesn't crash
|
2020-04-15 12:43:55 -07:00
|
|
|
self.assertIsInstance(x, pxla.ShardedDeviceArray)
|
2019-07-06 10:00:08 -07:00
|
|
|
|
|
|
|
# check that we don't crash when we can't maintain device persistence
|
|
|
|
x = onp.arange(prod(shape)).reshape(shape)
|
|
|
|
x = soft_pmap(lambda x: x)(x)
|
2020-04-15 12:43:55 -07:00
|
|
|
self.assertIsInstance(x, pxla.ShardedDeviceArray)
|
2019-07-06 10:00:08 -07:00
|
|
|
y = x.reshape(device_count, -1)
|
|
|
|
self.assertIsInstance(y, xla.DeviceArray) # should have forced collection
|
|
|
|
soft_pmap(lambda x: x)(y) # doesn't crash
|
|
|
|
z = x + 2
|
|
|
|
self.assertIsInstance(z, xla.DeviceArray) # should have forced collection
|
|
|
|
x._npy_value = onp.float32(onp.nan) # can't be coerced to ndarray for xfer
|
2019-11-11 07:02:36 -08:00
|
|
|
self.assertRaisesRegex(
|
2019-07-06 10:00:08 -07:00
|
|
|
RuntimeError,
|
|
|
|
'.*does not match host shape or layout of computation parameter 0.*',
|
|
|
|
lambda: x + 2)
|
|
|
|
|
|
|
|
# check that different axis merges aren't a problem
|
|
|
|
x = onp.arange(prod(shape)).reshape(shape)
|
|
|
|
x = soft_pmap(lambda x: x)(x)
|
2020-04-15 12:43:55 -07:00
|
|
|
self.assertIsInstance(x, pxla.ShardedDeviceArray)
|
2019-07-06 10:00:08 -07:00
|
|
|
x = x.reshape(2 * device_count, 2, 2, 3) # axis merge of the wrong size
|
|
|
|
self.assertIsInstance(x, xla.DeviceArray) # should have forced collection
|
|
|
|
|
2019-06-23 16:41:59 -07:00
|
|
|
@jtu.skip_on_devices("gpu")
|
2019-06-27 22:09:57 -04:00
|
|
|
def DISABLED_testSoftPmapAllToAll(self):
|
2019-06-23 16:41:59 -07:00
|
|
|
n = 4 * xla_bridge.device_count()
|
|
|
|
def f(x):
|
|
|
|
return lax.all_to_all(x, 'i', 0, 0)
|
|
|
|
ans = soft_pmap(f, 'i')(np.arange(n ** 2).reshape(n, n))
|
|
|
|
expected = onp.arange(n ** 2).reshape(n, n).T
|
|
|
|
self.assertAllClose(ans, expected, check_dtypes=False)
|
|
|
|
|
2019-07-03 21:15:52 -07:00
|
|
|
def testShardedDeviceArrayBlockUntilReady(self):
|
|
|
|
x = onp.arange(xla_bridge.device_count())
|
|
|
|
x = pmap(lambda x: x)(x)
|
2019-07-08 16:45:01 -07:00
|
|
|
x.block_until_ready() # doesn't crash
|
2019-07-03 21:15:52 -07:00
|
|
|
|
enable jit+pmap by merging pxla.py and xla.py
This change is essentially de-duplicating the XLA lowering logic between
xla.py and pxla.py. Only the latter was capable of handling collectives
(aka pmap primitives), which meant that these didn't work:
1. some compositions of jit and pmap, like jit-of-pmap
2. collectives inside initial-style control flow like scan
3. jax.xla_computation on a function involving collectives
By merging the logic into xla.py, now all the lowering machinery works
with everything. Woo!
The pxla.py file still exists and contains mostly dynamic/runtime
components for pmap and functions used only by pmap and collectives
translations. In particular, pxla.py has
* the pmap impl, particularly the dispatching logic for top-level pmaps,
including argument sharding and lazy sharded result persistence
* the ShardedDeviceArray / ShardedDeviceTuple classes
* the dynamic (trace-time) axis environment data structures and logic
and the special axis_index primitive
* the split-axis transformation for soft_pmap
* the PmapPrimitive (just a tagged version of Primitive)
* the static sharding/unsharding logic for pmap-inside-jit/pmap
These things moved over to xla.py
* the logic for lowering pmap primitives, especially the static axis
environment used during xla lowering
This change refactors the translation rule tables a bit. Instead of just
having one table, there are now four, and they contain rules with
slightly different type signatures:
* the `translations` table has rules with the same signatures as always,
i.e. `CompBuilder -> [XlaOperands] -> ParamsDict -> XlaOperandOut`
* the `backend_specific_translations` table is keyed by platform name
strings and has dict values that each have the same type as `translations`
* the `parallel_translations` table is used for primitives modeling
parallel collectives, and so it has rules with signature
`CompBuilder -> [XlaOperands] -> ReplicaGroups -> ParamsDict -> XlaOpOut`
* the `initial_style_translations` table is for the initial-style
control flow primitives (like `scan`), for which the translation rules
themselves lower jaxprs to XLA computations and thus require the static axis
env to be passed in; the rules there have signature
`CompBuilder -> AxisEnv -> [XlaOperands] -> ParamsDict -> XlaOpOut`
* the `call_translations` table is sued for `xla_call` and `xla_pmap`,
i.e. the primitives underlying `jit` and `pmap` respectively, and has
rules with signature
`CompBuilder -> Jaxpr -> AxisEnv -> [XlaOp] -> [XlaOp] -> ParamsDict -> XlaOp`
Having these as separate tables is an uninteresting implementation
detail. The lowering function `_jaxpr_computation` just does a case analysis
on whether the primitive being translated has an entry in any table
(where the `backend_specific_translations` table must be checked before
the `translations` table, since some primitives may be entered in both).
This change fixes #804 also addresses #852, in that the lax control flow
impls for those primitives are now based on Python-level jaxpr
interpreters rather than XLA compilation, but we should probably wait to
close the latter issue until we benchmark and improve things more. This
change at least seems not to be a performance regression: on my machine
the lax control flow tests go from running in ~20s to running in ~14s.
This change also adds a docstring for `jax.xla_computation` and some
basic tests.
2019-07-02 13:17:31 -07:00
|
|
|
def testJitPmapComposition(self):
|
|
|
|
f = lambda x: x - lax.psum(x, 'i')
|
|
|
|
|
|
|
|
shape = (xla_bridge.device_count(), 4)
|
|
|
|
x = onp.arange(prod(shape), dtype=onp.float32).reshape(shape)
|
|
|
|
expected = x - onp.sum(x, 0)
|
|
|
|
|
|
|
|
ans = jit(pmap(f, 'i'))(x)
|
|
|
|
self.assertAllClose(ans, expected, check_dtypes=False)
|
|
|
|
|
|
|
|
ans = pmap(jit(f), 'i')(x)
|
|
|
|
self.assertAllClose(ans, expected, check_dtypes=False)
|
|
|
|
|
2019-07-08 16:45:01 -07:00
|
|
|
def testMakeJaxprOfOpenSpmd(self):
|
|
|
|
f = lambda x: x - lax.psum(x, 'i')
|
|
|
|
shape = (xla_bridge.device_count(), 4)
|
|
|
|
x = onp.arange(prod(shape), dtype=onp.float32).reshape(shape)
|
|
|
|
make_jaxpr(f)(x) # doesn't crash
|
|
|
|
|
2019-07-08 18:21:43 -07:00
|
|
|
def testCompositionWithJitTwice(self):
|
|
|
|
@jit
|
|
|
|
def f(x):
|
|
|
|
y = 2 * x
|
2019-07-09 15:12:02 -07:00
|
|
|
|
2019-07-08 18:21:43 -07:00
|
|
|
@jit
|
|
|
|
def g(z):
|
|
|
|
return pmap(lambda x: x * y)(z)
|
2019-07-09 15:12:02 -07:00
|
|
|
|
2019-07-08 18:21:43 -07:00
|
|
|
return g(x)
|
|
|
|
|
2019-07-09 15:12:02 -07:00
|
|
|
f(onp.arange(1.).reshape((1, 1))) # doesn't crash
|
2019-07-08 18:21:43 -07:00
|
|
|
|
2019-07-25 18:11:44 -07:00
|
|
|
def testIssue1065(self):
|
|
|
|
# from https://github.com/google/jax/issues/1065
|
|
|
|
device_count = xla_bridge.device_count()
|
|
|
|
|
|
|
|
def multi_step_pmap(state, count):
|
|
|
|
@partial(pmap, axis_name='x')
|
|
|
|
@jit
|
|
|
|
def exchange_and_multi_step(state):
|
|
|
|
return state
|
|
|
|
|
|
|
|
@jit
|
|
|
|
def time_evolution(state):
|
|
|
|
return lax.fori_loop(0, count, lambda i, s: exchange_and_multi_step(s), state)
|
|
|
|
|
|
|
|
return time_evolution(state)
|
|
|
|
|
|
|
|
multi_step_pmap(np.zeros((device_count,)), count=1)
|
|
|
|
|
2019-08-21 16:39:59 -07:00
|
|
|
def testShardedDeviceArrayGetItem(self):
|
|
|
|
f = lambda x: 2 * x
|
|
|
|
f = pmap(f, axis_name='i')
|
|
|
|
|
|
|
|
shape = (xla_bridge.device_count(), 4)
|
|
|
|
x = onp.arange(prod(shape), dtype=onp.float32).reshape(shape)
|
|
|
|
|
|
|
|
y = f(x)
|
|
|
|
self.assertIsInstance(y, np.ndarray)
|
|
|
|
self.assertIsInstance(y, pxla.ShardedDeviceArray)
|
|
|
|
|
|
|
|
z = y[0] # doesn't crash
|
2019-08-21 20:36:47 -07:00
|
|
|
self.assertAllClose(z, 2 * x[0], check_dtypes=False)
|
2019-08-21 16:39:59 -07:00
|
|
|
|
2019-09-20 07:01:01 -07:00
|
|
|
def testPostProcessMap(self):
|
2019-09-20 20:45:01 -07:00
|
|
|
# TODO(mattjj): this fails with multiple devices (unless we add a jit)
|
|
|
|
# because we assume eager ops (like scan here) can't require more than 1
|
|
|
|
# replica.
|
|
|
|
raise SkipTest("need eager multi-replica support")
|
2019-09-20 07:01:01 -07:00
|
|
|
# test came from https://github.com/google/jax/issues/1369
|
|
|
|
nrep = xla_bridge.device_count()
|
|
|
|
|
|
|
|
def pmvm(a, b):
|
|
|
|
a = a.reshape((nrep, -1, a.shape[1]))
|
|
|
|
func = pmap(lambda z: np.dot(z, b))
|
|
|
|
return func(a).reshape(b.shape)
|
|
|
|
|
2019-09-20 20:45:01 -07:00
|
|
|
n = nrep * 2
|
2019-09-20 07:01:01 -07:00
|
|
|
rng = onp.random.RandomState(0)
|
2019-09-20 20:45:01 -07:00
|
|
|
a = rng.randn(n, n)
|
|
|
|
b = rng.randn(n)
|
2019-09-20 07:01:01 -07:00
|
|
|
|
|
|
|
iters = np.arange(5)
|
|
|
|
def body(carry, i):
|
|
|
|
return pmvm(a, carry), i
|
|
|
|
ans, _ = lax.scan(body, b, iters)
|
|
|
|
|
|
|
|
expected = onp.linalg.matrix_power(a, 5).dot(b)
|
|
|
|
self.assertAllClose(ans, expected, check_dtypes=False)
|
|
|
|
|
2019-09-18 17:21:57 -07:00
|
|
|
def testManyArgs(self):
|
|
|
|
@pmap
|
|
|
|
def f(args_list):
|
|
|
|
return sum(args_list)
|
|
|
|
|
|
|
|
vals = list(range(500))
|
|
|
|
ndevices = xla_bridge.device_count()
|
|
|
|
self.assertAllClose(f(np.array([vals] * ndevices)),
|
|
|
|
np.array([sum(vals)] * ndevices),
|
|
|
|
check_dtypes=True)
|
|
|
|
|
2020-04-21 18:12:02 -07:00
|
|
|
def testPostProcessMap(self):
|
|
|
|
# code from https://github.com/google/jax/issues/2787
|
|
|
|
def vv(x, y):
|
|
|
|
"""Vector-vector multiply"""
|
|
|
|
return np.dot(x, y)
|
|
|
|
|
|
|
|
def distributed_matrix_vector(x, y):
|
|
|
|
"""Matrix vector multiply. First batch it and then row by row"""
|
|
|
|
fv = lambda z: lax.map(lambda j: vv(j, y), z)
|
|
|
|
res = pmap(fv)(x.reshape((jax.device_count(), -1) + tuple(x.shape[1:])))
|
|
|
|
res = res.reshape(res.shape[0] * res.shape[1], *res.shape[2:])
|
|
|
|
return res
|
|
|
|
|
|
|
|
key = random.PRNGKey(1)
|
2020-04-21 18:27:53 -07:00
|
|
|
x = random.normal(key, (80, 50))
|
2020-04-21 18:12:02 -07:00
|
|
|
batched_mvm = vmap(lambda b: distributed_matrix_vector(x, b), in_axes=0)
|
|
|
|
y = random.normal(key, (10, 50, 1))
|
|
|
|
result = batched_mvm(y)
|
|
|
|
expected = np.einsum('ij,njk->nik', x, y)
|
2020-04-21 18:27:53 -07:00
|
|
|
tol = 1e-1 if jtu.device_under_test() == "tpu" else 1e-3
|
|
|
|
self.assertAllClose(result, expected, check_dtypes=False, atol=tol, rtol=tol)
|
2020-04-21 18:12:02 -07:00
|
|
|
|
2019-01-28 11:13:34 -08:00
|
|
|
|
2019-08-26 11:22:58 -07:00
|
|
|
class PmapWithDevicesTest(jtu.JaxTestCase):
|
|
|
|
|
|
|
|
def testAllDevices(self):
|
|
|
|
f = pmap(lambda x: x - lax.psum(x, 'i'), axis_name='i',
|
|
|
|
devices=xla_bridge.devices())
|
|
|
|
shape = (xla_bridge.device_count(), 4)
|
|
|
|
x = onp.arange(prod(shape), dtype=onp.float32).reshape(shape)
|
|
|
|
expected = x - onp.sum(x, 0)
|
|
|
|
ans = f(x)
|
|
|
|
self.assertAllClose(ans, expected, check_dtypes=True)
|
|
|
|
|
|
|
|
def testOneDevice(self):
|
|
|
|
if xla_bridge.device_count() == 1:
|
|
|
|
raise SkipTest("this test requires multiple devices")
|
|
|
|
|
|
|
|
d0 = xla_bridge.devices()[0]
|
|
|
|
d1 = xla_bridge.devices()[1]
|
|
|
|
f = lambda x: np.dot(x, x.T)
|
|
|
|
f0 = pmap(f, devices=[d0])
|
|
|
|
f1 = pmap(f, devices=[d1])
|
|
|
|
x = onp.random.rand(1, 1000, 1000)
|
|
|
|
r0 = f0(x)
|
|
|
|
r1 = f1(x)
|
|
|
|
expected = onp.expand_dims(onp.dot(x.squeeze(), x.squeeze().T), 0)
|
2019-12-17 21:22:32 -05:00
|
|
|
self.assertAllClose(r0, expected, check_dtypes=True, atol=1e-6, rtol=1e-3)
|
|
|
|
self.assertAllClose(r1, expected, check_dtypes=True, atol=1e-6, rtol=1e-3)
|
2019-08-26 11:22:58 -07:00
|
|
|
|
|
|
|
def testNoDevicesError(self):
|
|
|
|
f = pmap(lambda x: x - lax.psum(x, 'i'), axis_name='i', devices=[])
|
|
|
|
shape = (xla_bridge.device_count(), 4)
|
|
|
|
x = onp.arange(prod(shape), dtype=onp.float32).reshape(shape)
|
|
|
|
with self.assertRaisesRegex(
|
|
|
|
ValueError, "'devices' argument to pmap must be non-empty, or None."):
|
|
|
|
f(x)
|
|
|
|
|
|
|
|
def testBadAxisSizeError(self):
|
|
|
|
if xla_bridge.device_count() == 1:
|
|
|
|
raise SkipTest("this test requires multiple devices")
|
|
|
|
|
|
|
|
f = pmap(lambda x: lax.psum(x, 'i'), axis_name='i',
|
|
|
|
devices=xla_bridge.devices())
|
|
|
|
with self.assertRaisesRegex(
|
2019-09-27 11:50:21 -07:00
|
|
|
ValueError, r"Leading axis size of input to pmapped function must "
|
|
|
|
r"equal the number of local devices passed to pmap. Got axis_size=1, "
|
|
|
|
r"num_local_devices=\d."):
|
2019-08-26 11:22:58 -07:00
|
|
|
f(np.ones(1))
|
|
|
|
|
|
|
|
with self.assertRaisesRegex(
|
2019-09-27 11:50:21 -07:00
|
|
|
ValueError, r"Leading axis size of input to pmapped function must "
|
|
|
|
r"equal the number of local devices passed to pmap. Got axis_size=\d, "
|
|
|
|
r"num_local_devices=\d."):
|
2019-08-26 11:22:58 -07:00
|
|
|
f(np.ones(xla_bridge.device_count() + 1))
|
|
|
|
|
|
|
|
def testNestedPmapsError(self):
|
|
|
|
# Devices specified in outer pmap
|
|
|
|
@partial(pmap, axis_name='i', devices=xla_bridge.devices())
|
|
|
|
def foo(x):
|
|
|
|
@partial(pmap, axis_name='j')
|
|
|
|
def bar(y):
|
|
|
|
return lax.psum(y, 'j')
|
|
|
|
return bar(x)
|
|
|
|
|
|
|
|
with self.assertRaisesRegex(
|
2019-08-29 20:25:02 -07:00
|
|
|
ValueError,
|
|
|
|
"Nested pmaps with explicit devices argument."):
|
2019-08-26 11:22:58 -07:00
|
|
|
foo(np.ones((xla_bridge.device_count(), 1)))
|
|
|
|
|
|
|
|
# Devices specified in inner pmap
|
|
|
|
@partial(pmap, axis_name='i')
|
|
|
|
def foo(x):
|
|
|
|
@partial(pmap, axis_name='j', devices=xla_bridge.devices())
|
|
|
|
def bar(y):
|
|
|
|
return lax.psum(y, 'j')
|
|
|
|
return bar(x)
|
|
|
|
|
|
|
|
with self.assertRaisesRegex(
|
2019-08-29 20:25:02 -07:00
|
|
|
ValueError,
|
|
|
|
"Nested pmaps with explicit devices argument."):
|
2019-08-26 11:22:58 -07:00
|
|
|
foo(np.ones((xla_bridge.device_count(), 1)))
|
|
|
|
|
|
|
|
def testJitInPmap(self):
|
|
|
|
@partial(pmap, axis_name='i', devices=xla_bridge.devices())
|
|
|
|
def foo(x):
|
|
|
|
@jit
|
|
|
|
def bar(y):
|
|
|
|
return y + 1
|
|
|
|
return lax.psum(bar(x), 'i')
|
|
|
|
|
|
|
|
ndevices = xla_bridge.device_count()
|
|
|
|
ans = foo(np.ones((ndevices, 1)))
|
Change scalar promotion rules to prefer array types over scalar types. (#1709)
* Change scalar promotion rules to prefer array types over scalar types.
Currently JAX does not treat Python scalars specially during type promotion. This means that, for example:
`1. + np.array([...], np.float32)`
ends up as an array of type np.float64. The `1.` is promoted to a default type (here np.float64), and the type promotion of a np.float64 and an np.float32 is an np.float64. This is unlike classic NumPy, which treats scalars specially during type promotion, in particular, preferring the type of an array over the type of a scalar.
This change adds a notion of weak_type to JAX avals. During type promotion, we prefer non-weak types, i.e., the type of the array in the example above, ignoring the type of the scalar.
In contexts where a Python scalar is to be promoted to a NumPy value, a default type is used (e.g., `np.float_`). This change also makes it possible to use 32-bit default types that differ from NumPy's default types. The JAX test suite passes with 32-bit default types. However, we do not yet enable this change or expose it in the API.
2019-11-18 14:51:10 -05:00
|
|
|
expected = onp.ones((ndevices, 1), dtype=np.float_) * ndevices * 2
|
2019-08-26 11:22:58 -07:00
|
|
|
self.assertAllClose(ans, expected, check_dtypes=True)
|
|
|
|
|
|
|
|
def testPmapInJit(self):
|
|
|
|
@jit
|
|
|
|
def foo(x):
|
|
|
|
@partial(pmap, axis_name='i', devices=xla_bridge.devices())
|
|
|
|
def bar(y):
|
|
|
|
return lax.psum(y, 'i')
|
|
|
|
return bar(x)
|
|
|
|
|
|
|
|
ndevices = xla_bridge.device_count()
|
|
|
|
ans = foo(np.ones((ndevices, 1)))
|
Change scalar promotion rules to prefer array types over scalar types. (#1709)
* Change scalar promotion rules to prefer array types over scalar types.
Currently JAX does not treat Python scalars specially during type promotion. This means that, for example:
`1. + np.array([...], np.float32)`
ends up as an array of type np.float64. The `1.` is promoted to a default type (here np.float64), and the type promotion of a np.float64 and an np.float32 is an np.float64. This is unlike classic NumPy, which treats scalars specially during type promotion, in particular, preferring the type of an array over the type of a scalar.
This change adds a notion of weak_type to JAX avals. During type promotion, we prefer non-weak types, i.e., the type of the array in the example above, ignoring the type of the scalar.
In contexts where a Python scalar is to be promoted to a NumPy value, a default type is used (e.g., `np.float_`). This change also makes it possible to use 32-bit default types that differ from NumPy's default types. The JAX test suite passes with 32-bit default types. However, we do not yet enable this change or expose it in the API.
2019-11-18 14:51:10 -05:00
|
|
|
expected = onp.ones((ndevices, 1), dtype=np.float_) * ndevices
|
2019-08-26 11:22:58 -07:00
|
|
|
self.assertAllClose(ans, expected, check_dtypes=True)
|
|
|
|
|
|
|
|
def testGradBasic(self):
|
|
|
|
@partial(pmap, axis_name='i', devices=xla_bridge.devices())
|
|
|
|
def f(x):
|
|
|
|
return np.sin(x)
|
|
|
|
|
|
|
|
shape = (xla_bridge.device_count(), 4)
|
|
|
|
x = onp.arange(prod(shape), dtype=onp.float32).reshape(shape)
|
|
|
|
|
|
|
|
ans = grad(lambda x: np.sum(np.sin(x)))(x)
|
|
|
|
expected = grad(lambda x: np.sum(f(x)))(x)
|
|
|
|
self.assertAllClose(ans, expected, check_dtypes=False)
|
|
|
|
|
2020-02-14 15:45:26 +00:00
|
|
|
def testPmapStaticArgnums(self):
|
|
|
|
@partial(pmap, axis_name='i', static_broadcasted_argnums=1)
|
|
|
|
def f(x, y):
|
|
|
|
return np.sin(x + y)
|
|
|
|
shape = (xla_bridge.device_count(), 4)
|
|
|
|
x = onp.arange(prod(shape), dtype=onp.float32).reshape(shape)
|
|
|
|
y = onp.arange(4, dtype=onp.float32)
|
|
|
|
|
|
|
|
ans = f(x, y)
|
|
|
|
expected = onp.sin(x + y[None])
|
|
|
|
self.assertAllClose(ans, expected, check_dtypes=False)
|
|
|
|
|
2019-08-26 11:22:58 -07:00
|
|
|
|
2020-04-15 12:43:55 -07:00
|
|
|
class SpecToIndicesTest(jtu.JaxTestCase):
|
|
|
|
|
|
|
|
def testShardsPerAxis(self):
|
|
|
|
shape = (4, 8)
|
|
|
|
spec = pxla.ShardingSpec(shards_per_axis=(2, 2),
|
|
|
|
is_axis_materialized=(True, True),
|
|
|
|
replication_factor=1)
|
|
|
|
self.assertEqual(pxla.spec_to_indices(shape, spec),
|
|
|
|
((slice(0,2), slice(0,4)),
|
|
|
|
(slice(0,2), slice(4,8)),
|
|
|
|
(slice(2,4), slice(0,4)),
|
|
|
|
(slice(2,4), slice(4,8))))
|
|
|
|
|
|
|
|
def testUnshardedAxis(self):
|
|
|
|
shape = (4, 8)
|
|
|
|
spec = pxla.ShardingSpec(shards_per_axis=(2, 1),
|
|
|
|
is_axis_materialized=(True, True),
|
|
|
|
replication_factor=1)
|
|
|
|
self.assertEqual(pxla.spec_to_indices(shape, spec),
|
|
|
|
(slice(0,2), (slice(2,4))))
|
|
|
|
|
|
|
|
def testNoSharding(self):
|
|
|
|
shape = (4,8)
|
|
|
|
spec = pxla.ShardingSpec(shards_per_axis=(1, 1),
|
|
|
|
is_axis_materialized=(True, True),
|
|
|
|
replication_factor=1)
|
|
|
|
self.assertEqual(pxla.spec_to_indices(shape, spec),
|
|
|
|
(slice(None),))
|
|
|
|
|
|
|
|
def testUnmaterializedAxis(self):
|
|
|
|
shape = (4, 8)
|
|
|
|
spec = pxla.ShardingSpec(shards_per_axis=(4, 1),
|
|
|
|
is_axis_materialized=(False, True),
|
|
|
|
replication_factor=1)
|
|
|
|
self.assertEqual(pxla.spec_to_indices(shape, spec),
|
|
|
|
(0, 1, 2, 3))
|
|
|
|
|
|
|
|
shape = (2, 2)
|
|
|
|
spec = pxla.ShardingSpec(shards_per_axis=(1, 2),
|
|
|
|
is_axis_materialized=(True, False),
|
|
|
|
replication_factor=1)
|
|
|
|
self.assertEqual(pxla.spec_to_indices(shape, spec),
|
|
|
|
((slice(None), 0),
|
|
|
|
(slice(None), 1)))
|
|
|
|
|
|
|
|
def testReplication(self):
|
|
|
|
shape = (2, 8)
|
|
|
|
spec = pxla.ShardingSpec(shards_per_axis=(2, 1),
|
|
|
|
is_axis_materialized=(False, True),
|
|
|
|
replication_factor=3)
|
|
|
|
self.assertEqual(pxla.spec_to_indices(shape, spec),
|
|
|
|
(0, 0, 0, 1, 1, 1))
|
|
|
|
|
|
|
|
|
2019-01-28 11:13:34 -08:00
|
|
|
if __name__ == '__main__':
|
|
|
|
absltest.main()
|